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
378ce5945201e0ebb9362b06dfd28fafa161b914
C++
seanmoir/COSC342
/04/Shapes/Rectangle.cpp
UTF-8
978
3.359375
3
[]
no_license
#include "Rectangle.h" #include <algorithm> #include <iostream> Rectangle::Rectangle(int minX, int minY, int maxX, int maxY, const Pixel& colour) : Shape(colour), minX_(minX), minY_(minY), maxX_(maxX), maxY_(maxY) { } Rectangle::Rectangle(const Rectangle& rect) : Shape(rect), minX_(rect.minX_), maxX_(rect.maxX_), minY_(rect.minY_), maxY_(rect.maxY_) { } Rectangle::~Rectangle() { } Rectangle& Rectangle::operator=(const Rectangle& rect) { if (this != &rect) { Shape::operator=(rect); minX_ = rect.minX_; maxX_ = rect.maxX_; minY_ = rect.minY_; maxY_ = rect.maxY_; } return *this; } void Rectangle::draw(Image& image) const { // Make sure we're not drawing out of bounds int startX = std::max(0, minX_); int endX = std::min(maxX_ + 1, image.width()); int startY = std::max(0, minY_); int endY = std::min(maxY_ + 1, image.height()); for (int y = startY; y < endY; ++y) { for (int x = startX; x < endX; ++x) { image(x, y) = colour_; } } }
true
5e3018215a1f7c0b34a0cc09fe189074f3423c79
C++
ZeroBone/ZBoss
/src/components/container.cpp
UTF-8
3,749
2.6875
3
[ "MIT" ]
permissive
#include <zboss/components/container.hpp> #include <zboss/entity/entity.hpp> namespace zboss { using namespace std; Vector2D ContainerComponent::getPosition() const { return rawPosition; } void ContainerComponent::setPosition(const Vector2D& pos) { setPosition(pos.x, pos.y); } void ContainerComponent::setPosition(int x, int y) { rawPosition.x = x; rawPosition.y = y; translation = { {1., 0., (float)x}, {0., 1., (float)y}, {0., 0., 1.} }; localCachedTransform = translation * rotation; cachePosition(); } float ContainerComponent::getRotation() const { return rawAngle; } void ContainerComponent::setRotation(float angle) { rawAngle = angle; rotation = { {cos(angle), sin(angle), 0.0}, {-sin(angle), cos(angle), 0.0}, {0.0, 0.0, 1.0} }; localCachedTransform = translation * rotation; cachePosition(); } float ContainerComponent::getScale() const { return rawScale; } void ContainerComponent::setScale(float scale) { rawScale = scale; translation = translation * scale; localCachedTransform = translation * rotation; cachePosition(); } Matrix<3, 3> ContainerComponent::getCachedTransform() const { return localCachedTransform; } void ContainerComponent::cachePosition() { Matrix<3, 1> origin = { {0.0}, {0.0}, {1.0} }; Matrix<3, 1> transformed = parentCachedTransform * localCachedTransform * origin; cachedPosition = Vector2D(transformed(0, 0), transformed(1, 0)); } Vector2D ContainerComponent::getAbsolutePosition() { Matrix<3, 3> current_parent_pm_transform; auto parent = entity->find_first_ancestor_by_type<ContainerComponent>(); if (parent != nullptr) { /*auto pnode = static_pointer_cast<ContainerComponent>(parent); current_parent_pm_transform = pnode->get_pm_transform();*/ current_parent_pm_transform = parent->getComponent<ContainerComponent>().getCachedTransform(); } if (current_parent_pm_transform != parentCachedTransform) { parentCachedTransform = current_parent_pm_transform; cachePosition(); } return cachedPosition; } float ContainerComponent::getAbsoluteRotation() const { float abs_angle = 0; shared_ptr<const Entity> e = entity; // shared_ptr<const Entity> e2 = make_shared<Entity>(entity); // const Entity* e = entity; while (e != nullptr) { if (e->hasComponent<ContainerComponent>()) { abs_angle += e->getComponent<ContainerComponent>().getRotation(); /*auto pnode = static_pointer_cast<const PositionNode>(entity); abs_angle += pnode->get_rotation();*/ } e = e->get_parent(); } return abs_angle; } float ContainerComponent::getAbsoluteScale() const { float abs_zoom = 1; // shared_ptr<const Entity> node = make_shared<Entity>(entity); shared_ptr<const Entity> node = entity; while (node != nullptr) { if (node->hasComponent<ContainerComponent>()) { abs_zoom *= node->getComponent<ContainerComponent>().getScale(); /*auto pnode = static_pointer_cast<const PositionNode>(node); abs_zoom *= pnode->get_zoom();*/ } node = node->get_parent(); } return abs_zoom; } }
true
338fe6596dae7b5bc0bc27e7a29933178430b66e
C++
bayusamudra5502/PustakaCPP
/Pemrograman Kompetitif/beras2.cpp
UTF-8
1,077
2.875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; struct Beras{ double C1; int C; // Harga int W; // berat }; double f(int X, int N, vector<Beras> data){ if(X <= 0){ return 0; }else{ if(data.size() == 0){ return 0; }else{ double maxe = 0; for(unsigned int i = 0; i < data.size(); i++){ vector<Beras> cp(data); cp.at(i).W = cp.at(i).W - 1; if(cp.at(i).W == 0){ cp.erase(cp.begin() + i); } maxe = max(f(X-1, N, cp) + data.at(i).C1, maxe); } return maxe; } } } int main(){ int N, X; scanf("%d %d", &N, &X); vector<Beras> data(N); for(int i = 0; i < N; i++){ scanf("%d", &data.at(i).W); } for(int i = 0; i < N; i++){ scanf("%d", &data.at(i).C); data.at(i).C1 = (double) data.at(i).C / data.at(i).W; } printf("%.5lf\n", f(X,N,data)); }
true
dbcde73d4d0cb2ae2e60944a17c59e99a413f3a5
C++
Zuvo007/InternSearchWorkspace
/sourcecodes/9997.RecursionCodingBat/2.RevStringWord.cpp
UTF-8
1,306
3.5625
4
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; string GetReverse(string s,int start,int end) { //base case the function will continue //up to end=s.size()-1; //cout<<s; if(end==s.size()) { //this is for the last word of the string reverse(s.begin()+start,s.end()); //to reverse the entire string reverse(s.begin(),s.end()); return s; } //checking for a space //to separate each word in the string //when I am getting a space just reverse //all words before the space using two pointers //reversing all elements from start to end-1 //then set the start again to the end+1 th pos // make recursive call as follows if(s[end]==' ') { reverse(s.begin()+start,s.begin()+end); start=end+1; } //here I make recursive call //to traverse the string for further // when I didn't get any space return GetReverse(s,start,end+1); } int main() { string s,y; getline(cin,s); y=GetReverse(s,0,0); cout<<y; return 0; }
true
84db71696a32dd62a140c4b9fa1ed9b6ed571413
C++
HuNNTTeR/Programiranje-I
/Zadatak I/01.cpp
UTF-8
482
3.75
4
[]
no_license
#include<iostream> using namespace std; int isFact(int); int sum(int); int main() { int N; cout << "Unesi neki cijeli broj N" << endl; cin >> N; cout << "Suma faktorijela svih neparnih brojeva od 1 do " << N << " je " << sum(N); cin.get(); return 0; } int isFact(int x) { int f = 1; for (int i = 2; i <= x; i++) { f *= i; } return f; } int sum(int x) { int s = 0; for (int i = 1; i <= x; i++) { if (i % 2 != 0) { s += isFact(i); } } return s; }
true
ce4ca1c36a77c86c9d863848f9b8469c4c55124f
C++
IT6DevGroup/Epic-Defense
/Epic_defense/Epic_defense/log.cpp
UTF-8
1,864
3.015625
3
[]
no_license
#include "log.h" LOG &LOG::GetInstance () { static LOG theSingleInstance; return theSingleInstance; } LOG::LOG () { log_file = fopen ("error.log", "w"); } LOG::~LOG () { fclose(log_file); } void LOG::WriteStringToLog (char *fmt, ...) { va_list ap; char format[STRING_LENGTH]; int count = 0; int i, j; char c; double d; unsigned u; char *s; void *v; va_start(ap, fmt); while (*fmt) { for (j = 0; fmt[j] && fmt[j] != '%'; j++) format[j] = fmt[j]; if (j) { format[j] = '\0'; count += fprintf(log_file, format); fmt += j; } else { for (j = 0; !isalpha(fmt[j]); j++) { format[j] = fmt[j]; if (j && fmt[j] == '%') break; } format[j] = fmt[j]; format[j + 1] = '\0'; fmt += j + 1; switch (format[j]) { case 'd': case 'i': i = va_arg(ap, int); count += fprintf(log_file, format, i); break; case 'o': case 'x': case 'X': case 'u': u = va_arg(ap, unsigned); count += fprintf(log_file, format, u); break; case 'c': c = (char) va_arg(ap, int); count += fprintf(log_file, format, c); break; case 's': s = va_arg(ap, char *); count += fprintf(log_file, format, s); break; case 'f': case 'e': case 'E': case 'g': case 'G': d = va_arg(ap, double); count += fprintf(log_file, format, d); break; case 'p': v = va_arg(ap, void *); count += fprintf(log_file, format, v); break; case 'n': count += fprintf(log_file, "%d", count); break; case '%': count += fprintf(log_file, "%%"); break; default: fprintf (log_file, "Invalid format specifier in log().\n"); break; } } } va_end(ap); }
true
ec4cdfe375779610f49fb033bb1db921c42649ed
C++
juangil/programmingContests
/codeforces/codeforces320/B.cpp
UTF-8
1,426
2.765625
3
[]
no_license
# include <bits/stdc++.h> using namespace std; bool mycmp(pair< int, pair<int,int> > a, pair< int, pair<int,int> > b){ return a.first < b.first; } int main(){ int n; while(cin >> n){ vector< pair<int, pair<int,int> > > highest; for(int i = 2; i <= 2*n; ++i){ int m = i - 1; for(int j = 1; j <= m; ++j){ int tmp; cin >> tmp; pair< int,int > mpair = make_pair(i,j); pair< int, pair<int,int> > emp = make_pair(tmp, mpair); highest.push_back(emp); } //cout << "que paso" << endl; } sort(highest.begin(), highest.end(), mycmp); set< int > rep; vector< int > ans((2*n) + 1, 0); while(!highest.empty()){ pair< int, pair<int,int> > take = highest.back(); //cout << take.first << endl; highest.pop_back(); int a = take.second.first; int b = take.second.second; //cout << a << " " << b << endl; if(rep.count(a) == 0 && rep.count(b) == 0){ rep.insert(a); rep.insert(b); //cout << " meto: " << a << " " << b << " con: " << take.first << endl; ans[a] = b; ans[b] = a; } } for(int i = 1; i <= 2*n; ++i) cout << ans[i] << " "; } return 0; }
true
441a10280294dc28e59bbd6aebe5fa9ede3668b9
C++
Yairbib/Pipe-Puzzle-game
/src/Controller.cpp
UTF-8
3,493
2.671875
3
[]
no_license
#include "Controller.h" #include <SFML/Graphics.hpp> #include <fstream> void Controller::run() { Textures textures; std::ifstream file("Board.txt"); auto window = sf::RenderWindow(sf::VideoMode::getDesktopMode(), "The Pipe Puzzle Game", sf::Style::Default); setMenu(window, textures); for (float i = 0; i < 2; i++) m_stages.push_back(std::make_shared<Stage>(file, textures, i, window.getSize())); while (window.isOpen()) { displayStart(window); m_stages[static_cast<__int64>(m_stageNum) - 1]->mixBoard(); m_stages[static_cast<__int64>(m_stageNum) - 1]->run(window, m_menu.m_background); displayEndStage(window); } // window.create(sf::VideoMode::getDesktopMode(), "The Pipe Puzzle Game", sf::Style::Default); // } } void Controller::setMenu(sf::RenderWindow& window, const Textures &textures) { m_menu.m_background = sf::Sprite(textures.m_bg); m_menu.m_nextS= sf::Sprite(textures.m_nextS); m_menu.m_easy= sf::Sprite(textures.m_easy); m_menu.m_hard= sf::Sprite(textures.m_hard); m_menu.m_solved = sf::Sprite(textures.m_end); m_menu.m_easy.setPosition((window.getSize().x - m_menu.m_easy.getGlobalBounds().width) / 2, (window.getSize().y - m_menu.m_easy.getGlobalBounds().height) / 2 - 150); m_menu.m_hard.setPosition(m_menu.m_easy.getPosition().x,m_menu.m_easy.getPosition().y + 150); m_menu.m_solved.setPosition((window.getSize().x - m_menu.m_solved.getGlobalBounds().width) / 2, (window.getSize().y - m_menu.m_solved.getGlobalBounds().height) / 2 - 150); m_menu.m_nextS.setPosition(m_menu.m_solved.getPosition().x + 200, m_menu.m_solved.getPosition().y + 500); } void Controller::displayStart(sf::RenderWindow& window) { while (window.isOpen()) { sf::Event e; while (window.pollEvent(e)) { if (e.type == sf::Event::Closed) { window.close(); exit(0); } window.clear(); window.draw(m_menu.m_background); window.draw(m_menu.m_easy); window.draw(m_menu.m_hard); window.display(); if (e.type == sf::Event::MouseButtonPressed && e.key.code == sf::Mouse::Left) { auto tmp = sf::Mouse::getPosition(window); sf::Vector2f pos((float)tmp.x, (float)tmp.y); if (m_menu.m_easy.getGlobalBounds().contains(pos)) m_stageNum=1; else if(m_menu.m_hard.getGlobalBounds().contains(pos)) m_stageNum = 2; return; } } } } void Controller::displayEndStage(sf::RenderWindow& window) { while (window.isOpen()) { sf::Event e; while (window.pollEvent(e)) { if (e.type == sf::Event::Closed) { window.close(); exit(0); } window.clear(); window.draw(m_menu.m_background); window.draw(m_menu.m_solved); window.draw(m_menu.m_nextS); window.display(); if (e.type == sf::Event::MouseButtonPressed && e.key.code == sf::Mouse::Left) { auto tmp = sf::Mouse::getPosition(window); sf::Vector2f pos((float)tmp.x, (float)tmp.y); if (m_menu.m_nextS.getGlobalBounds().contains(pos)) return; } } } }
true
68247e36f1ce1e53afc0c7cb894b5abe8a11696f
C++
oulrich1/PastAssignments
/csci566-p4/include/geometry/geometry.h
UTF-8
3,768
2.734375
3
[]
no_license
/* Geometry.h * * Base class for geometric objects. */ #include "utils.h" using namespace std; typedef Angel::vec4 color4; typedef Angel::vec4 point4; #ifndef GEOMETRY_H #define GEOMETRY_H // this is the length of one symetric side of the unit cube.. // #define UNIT_CUBE_D 0.5 #define UNIT_CUBE_D 1.0 // this is half the length in usable coordinates when plotting cube points #define U_CUBE_C UNIT_CUBE_D/2 #define toRadians(degrees) (degrees * DegreesToRadians) class Geometry { public: Geometry(); Geometry(GLuint _program_id); void constrict_angles(); virtual ~Geometry(); /* generates triangles for gl.. from the verticies */ static vec4* glquad( vec4 *cur_vertices, int a, int b, int c, int d ); static vec4* glcube( vec4 *verts ); /* generates verticies.. */ static vec4* createUnitTriangle(); static vec4* createUnitPlane(); static vec4* createUnitCube(); static vec4* createUnitSphere(); static vec4* createUnitColors(); // 8 points colored in order.. /* Pure virtual function to display the Geometry. Classes inheriting from Geometry need to provide a definition for display(). */ virtual void init_data() = 0; // initializes this object's data virtual void init_gl() = 0; // initializes the GPU // with any data we care about sending over virtual void display() = 0; // switches to the object's vao/vbo and // invokes postRedisplay // rotates the entire body by radians // virtual void rotate(float rad) = 0; void rotate(vec4 ); // rotates... void translate(vec4 ); // translates // offset is vector, eye is point // not goign to make getters for these.. point4 eye; point4 at; vec4 up; vec4 getDirection(){return direction;} void setDirection(vec4 v){direction = v;} int getRoomIndex(); void setRoomIndex(int index); float radius; //TODO: // virtual void collides(Geometry *) = 0; protected: /* GL SPECIFIC ATTRIBUTES */ GLuint program_id, // shader program id vao, // vertex array object id vbo, // vertex buffer object id ibo, // index buffer object id texture_id; // model-view matrix uniform shader variable location GLuint model_view; GLuint texture_pos; char * texture_image; //TODO: /* colro uniform variable location */ GLuint new_color; GLuint normalMatrixLoc, lightLoc, addAmbientLoc, addDiffuseLoc, addSpecularLoc; GLintptr TOTAL_BUFFER_OFFSET; GLintptr VERTEX_BUFFER_OFFSET; GLintptr COLOR_BUFFER_OFFSET; GLintptr TEXTURE_BUFFER_OFFSET; /* END GL SPECIFIC STUFF */ int room_index; // BEGIN GEOMETRY LOGIC STUFF int NUM_COMPONENTS; // number of components that need a matrix mat4* model_view_matricies; mat4* models; mat4* views; vec4 offset; // offsets this instance in 3d space /* ---------------- */ mat4 I; vec4 thetas; vec4 direction; /* orientation properties */ float theta_x; /// using these and NOT yaw ptich roll... float theta_z; float theta_y; // default movement rate: float dx = 0.01, dy = 0.01, dz = 0.01; // default rotate rate: float dTheta = 4.5, dPhi = 0.5; // dmovement of geometry through the medium float drag_factor; private: // common state variables }; #endif
true
63055577980d6cbed6fcedd3eeeee8b0de725228
C++
PabloBlanco10/Algoritmos-EDA
/Algoritmos/Iterativos/circo.cpp
UTF-8
955
2.953125
3
[]
no_license
// // circo.cpp // // // Created by Pablo Blanco Peris on 31/1/17. // // #include <stdio.h> #include <iostream> using namespace std; int circo(int v[], int n){ int childs = 1; int max = v[0]; bool encontrado = true; for(int i = 1; i < n; i++){ if(encontrado){ if(v[i] <= max){ childs++; } else if(i < n - 1){ if(v[i+1] <= v[i]){ childs++; max = v[i]; } else encontrado = false; } } } return childs; } bool resuelve(){ int n; cin >> n; int v[500000]; while(n >0){ for(int i = 0; i < n; i++){ int a; cin >> a; v[i] = a; } cout << circo(v, n) << endl; cin >> n; } return false; } int main(){ while(resuelve()); return 0; }
true
0ea9b6484711f1bfa7413206ec581d3aa659daca
C++
manjaripokala/ParallelAlgorithms_Su20
/TermProject/generateGraph.cpp
UTF-8
4,357
3.03125
3
[ "MIT" ]
permissive
// // Created by Pedzinski, Dale on 8/9/20. // #include "jsmn.h" #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h> #include <limits.h> //For PATH_MAX //// Structure to represent a vertex and its distance //struct distNode { // int64_t node; // int64_t dist; // // bool operator<(const distNode &rhs) const { // return dist > rhs.dist || (dist == rhs.dist && node > rhs.node);; // } //}; // //// Structure to represent an edge //struct edge { // int64_t from; // int64_t to; // int64_t weight; // // bool operator<(const edge &rhs) const { // return weight > rhs.weight || (weight == rhs.weight && to > rhs.to); // } //}; // //// Structure to represent a edge source & destination //struct fromTo { // int64_t from; // int64_t to; // // bool operator<(const fromTo &rhs) const { // return to < rhs.to || (to == rhs.to && from < rhs.from); // } //}; const char *get_filename_ext(const char *filename) { const char *dot = strrchr(filename, '.'); if (!dot || dot == filename) return ""; return dot + 1; } int main() { struct dirent *de; // Pointer for directory entry // opendir() returns a pointer of DIR type. DIR *dr = opendir("."); if (dr == NULL) // opendir returns NULL if couldn't open directory { printf("Could not open current directory\n"); return 0; } // Refer http://pubs.opengroup.org/onlinepubs/7990989775/xsh/readdir.html // for readdir() while ((de = readdir(dr)) != NULL) { char filePath[PATH_MAX + 1]; if (strncmp(get_filename_ext(de->d_name), "csv", 2) == 0) { realpath(de->d_name, filePath); printf("%s\n", filePath); char const *const fileName = filePath; FILE *file = fopen(fileName, "r"); /* should check the result */ printf("%s\n", "file opened"); char line[4000]; int state = 0; int subState = 0; while (fgets(line, sizeof(line), file)) { char *token; char *rest = line; int *source; int *target; int *value; // printf("%s\n", "Next line:::"); while ((token = strtok_r(rest, "|\n", &rest))) { // printf("%s\n", token); if (strncmp(token, "Nodes", 2) == 0) { printf("Section is %s\n", token); state = 1; subState=0; break; } if (strncmp(token, "Edges", 2) == 0) { printf("Section is %s\n", token); state = 2; subState=0; break; } if (strncmp(token, "Operator", 2) == 0) { printf("Section is %s\n", token); state = 3; subState=0; break; } if (state == 1 && subState==0 ) { printf("Node is %s\n", token); break; } if (state == 2 && subState == 0) { // Source printf("Source is %s\n", token); source=(int *)token; subState = 1; }else if (state == 2 && subState == 1) { // Target printf("Target is %s\n", token); target =(int *)token; subState = 2; }else if (state == 2 && subState == 2) { // Value printf("Value is %s\n", token); value=(int *)token; subState = 0; break; } if (state == 3 && subState == 0) { printf("Airline is %s\n", token); break; } } } fclose(file); } } closedir(dr); }
true
f833842dc0044796000b1638d56b2e67a1ea6fc4
C++
Exxxasens/Programming
/Practice/09/C++/Project/Project.cpp
UTF-8
630
2.78125
3
[]
no_license
#include <iostream> #include <cmath> using namespace std; int main() { setlocale(LC_ALL, "Russian"); char a; int h1, h2, m1, m2; cin >> h1 >> a >> m1; cin >> h2 >> a >> m2; if ((h1 == 0 && h2 == 23 && m2 - 45 + m1 <= 15) || (h1 == 23 && h2 == 0 && m1 - 45 + m2 <= 15)) { cout << "Встреча состоится" << endl; return 0; } h1 = h1 * 60 + m1; h2 = h2 * 60 + m2; if (abs(h1 - h2) > 15) { cout << "Встреча не состоится" << endl; } else { cout << "Встреча состоится" << endl; } return 0; }
true
0a3ac567337cd5cd194b25efa20a8eb715971804
C++
deardeng/learning
/vstest/C++/51cpp/51cpp/04.cpp
UTF-8
1,597
3.53125
4
[]
no_license
#include <iostream> using namespace std; #include <string> class MyException{ public: MyException(const char* message) :message_(message){ cout << "MyException..." << endl; } MyException(const MyException& other):message_(other.message_){ cout << "Copy MyException..." << endl; } ~MyException(){ cout << "~MyException" << endl; } const char* what() const{ return message_.c_str(); } private: string message_; }; class Test{ public: Test(){ cout << "Test..." << endl; } Test(const Test& other){ cout << "Copy Test..." << endl; } ~Test(){ cout << "~Test..." << endl; } }; class Obj{ public: Obj(){ cout << "Obj..." << endl; } Obj(const Obj& other){ cout << "Copy Obj..." << endl; } ~Obj(){ cout << "~Obj..." << endl; } }; class Test3{ public: Test3(){ cout << "Test3..." << endl; } Test3(const Test3& other){ cout << "Copy Test3..." << endl; } ~Test3(){ cout << "~Test3..." << endl; throw 4; } }; class Test2{ public: Test2(){ obj_ = new Obj; cout << "Test2..." << endl; throw MyException("test exception2"); } Test2(const Test2& other){ cout << "Copy Test2..." << endl; } ~Test2(){ delete obj_; cout << "~Test2..." << endl; } private: Obj* obj_; }; int main(void){ try{ /*Test t; throw MyException("test exception");*/ /*Test2 t2;*/ Test3 t3; throw MyException("Test exception3"); } catch(MyException& e){ cout << e.what() << endl; } catch(int){ cout << "catch a int exception" << endl; } }
true
fe5eba8c79b7fc237fd2285b3bbc73040f9ad1b8
C++
ivilab/kjb
/lib/semantics/Token_map.cpp
UTF-8
1,263
2.90625
3
[]
no_license
/*! * @file Token_map.cpp * * @author Colin Dawson * $Id: Token_map.cpp 16870 2014-05-22 19:34:15Z cdawson $ */ #include "semantics/Token_map.h" #include <map> namespace semantics { Token_map::Val_type Token_map::get_code(const Token_map::Key_type& key) { Map::left_iterator it = map_.left.find(key); if(it == map_.left.end()) return UNKNOWN_TOKEN_VAL; else return it -> second; } Token_map::Val_type Token_map::encode( const Token_map::Key_type& key, bool learn) { Val_type code = get_code(key); if(learn && code == UNKNOWN_TOKEN_VAL) { code = next_val_; map_.insert(Key_val_pair(key, next_val_++)); } return code; } const Token_map::Key_type& Token_map::decode(const Token_map::Val_type& val) { Map::right_iterator it = map_.right.find(val); if(it == map_.right.end()) return unknown_key(); else return map_.right.at(val); } std::ostream& operator<<(std::ostream& os, Token_map& map) { os << "Keys:\tValues:" << std::endl; for(Token_map::Map::iterator it = map.map_.begin(); it != map.map_.end(); it++) { os << it->left << "\t" << it->right << std::endl; } return os; } const Token_map::Val_type Token_map::UNKNOWN_TOKEN_VAL = 1; };
true
002bf69404dcb2ccd56f2fcafb4b763d2194b8e8
C++
lineCode/FTXUI
/src/ftxui/dom/color.cpp
UTF-8
1,597
2.5625
3
[ "MIT" ]
permissive
// Copyright 2020 Arthur Sonzogni. All rights reserved. // Use of this source code is governed by the MIT license that can be found in // the LICENSE file. #include "ftxui/dom/elements.hpp" #include "ftxui/dom/node_decorator.hpp" namespace ftxui { class BgColor : public NodeDecorator { public: BgColor(Elements children, Color color) : NodeDecorator(std::move(children)), color_(color) {} void Render(Screen& screen) override { for (int y = box_.y_min; y <= box_.y_max; ++y) { for (int x = box_.x_min; x <= box_.x_max; ++x) { screen.PixelAt(x, y).background_color = color_; } } NodeDecorator::Render(screen); } Color color_; }; class FgColor : public NodeDecorator { public: FgColor(Elements children, Color color) : NodeDecorator(std::move(children)), color_(color) {} ~FgColor() override {} void Render(Screen& screen) override { for (int y = box_.y_min; y <= box_.y_max; ++y) { for (int x = box_.x_min; x <= box_.x_max; ++x) { screen.PixelAt(x, y).foreground_color = color_; } } NodeDecorator::Render(screen); } Color color_; }; std::unique_ptr<Node> color(Color c, Element child) { return std::make_unique<FgColor>(unpack(std::move(child)), c); } std::unique_ptr<Node> bgcolor(Color c, Element child) { return std::make_unique<BgColor>(unpack(std::move(child)), c); } Decorator color(Color c) { return [c](Element child) { return color(c, std::move(child)); }; } Decorator bgcolor(Color c) { return [c](Element child) { return bgcolor(c, std::move(child)); }; } } // namespace ftxui
true
06a47b81c4328e013c7158f6058d638e97db30ae
C++
Musthofa-017/tugas-besar-alpro
/Tugas Besar/main.h
UTF-8
4,193
3.03125
3
[]
no_license
#ifndef MAIN_INCLUDE #define MAIN_INCLUDE #include <iostream> #include <fstream> #include <sstream> using namespace std; class Bos { private: string username = "", password = ""; public: Bos(){ } bool login(string user, string pass){ ifstream file("data.dt"); while (!file.eof()){ file >> username; file >> password; if (username == user && password == pass){ file.close(); return true; } } file.close(); return false; } void inputKaryawan(){ string nama, nik; char c; cout << "Masukkan nama karyawan: "; cin >> nama; cout << "Masukkan nik karyawan: "; cin >> nik; cout << "Yakin? "; cin >> c; if (c == 'y' || c == 'Y'){ fstream file("karyawan.dt"); file.seekp(0, ios::end); file << "\n" << nama << ":" << nik; file.close(); } return; } void cetakKaryawan(){ system("cls"); string line, nama, nik; cout << "Daftar Karyawan:" << endl; fstream file("karyawan.dt"); while (getline(file, line)){ stringstream iss(line); getline(iss, nama, ':'); getline(iss, nik, '\n'); cout << nama << " " << nik << endl; } file.close(); } void hasilKerja(){ // Kode Pegawai - Nama - Tugas - Kode Ruang - Deadline cout << "1. Urut Berdasarkan Kode Pegawai \n"; cout << "2. Urut Berdasarkan Nama \n"; cout << "3. Urut Berdasarkan Tugas \n"; cout << "4. Urut Berdasarkan Kode Ruang \n"; cout << "5. Urut Berdasarkan Deadline \n"; cout << "0. Kembali \n"; } void tambahTugas(){ cout << "Masukkan Tugas : "; cin >> tugas; cout << "Masukkan Deadline : "; cin >> dl; cout << "Masukkan Target : "; cin >> kodeP; } void kesimpulanKerja(){ } }; class Init { private: int i; char c; string usr, pass; bool is_bos; Bos bos; public: Init(){ } void awal(){ system("cls"); cout << "====== SOFTWARE PERUSAHAAN PT TUNGGAL IKA ======" << endl; cout << "1. Login sebagai karyawan" << endl; cout << "2. Login sebagai atasan" << endl; cout << "0. Keluar" << endl; cout << "Pilih menu: "; cin >> i; switch(i){ case 0: return; break; case 1: is_bos = false; break; case 2: login(); break; } } void login(){ system("cls"); cout << "====== LOGIN SESSION ======" << endl; cout << "Masukkan username: "; cin >> usr; cout << "Masukkan password: "; cin >> pass; if (bos.login(usr, pass)){ is_bos = true; } else { cout << "Username/ password salah" << endl; cout << "Coba lagi? "; cin >> c; if (c == 'y' || c == 'Y') login(); else { cout << "Kembali ke menu utama? "; cin >> c; if (c == 'y' || c == 'Y') awal(); } } } bool isBos(){ return is_bos; } }; class Menu { private: Bos atasan; int i; public: Menu() {} void bos() { system("cls"); cout << "====== MENU ATASAN ======" << endl; cout << "1. Tambah Karyawan \n"; cout << "2. Tampilkan Karyawan \n"; cout << "3. Hasil Kerja Karyawan \n"; cout << "4. Tambah Tugas Karyawan \n"; cout << "5. Laporan Akhir Hasil Kerja \n"; cout << "0. Keluar \n"; cout << "Pilih menu: "; cin >> i; switch(i){ case 0: return; break; case 1: atasan.inputKaryawan(); bos(); break; case 2: atasan.cetakKaryawan(); break; case 3: atasan.hasilKerja(); break; case 4: atasan.tambahTugas(); break; case 5: atasan.kesimpulanKerja(); break; } } void karyawan() { system("cls"); cout << "====== MENU KARYAWAN ======" << endl; } }; #endif
true
b7493a6af0299b003611e9f9f95449c1467cf96e
C++
Oipo/Machine
/other/Machine-kitchen-old/src/menustate.cpp
UTF-8
1,911
3.03125
3
[]
no_license
#include "menustate.hpp" #include "menuentry.hpp" #include "gamestate.hpp" MenuState::MenuState(Game *game) : State(game), selection_(0) { AddEntry(MenuEntryID::Play, "Play"); AddEntry(MenuEntryID::Settings, "Settings"); AddEntry(MenuEntryID::About, "About"); AddEntry(MenuEntryID::Quit, "Quit"); entries_[0].set_selected(true); } void MenuState::Render() { sf::RenderWindow *rw = game_->get_window(); int width = 200; int height = 50; int padding = 20; int center_x = rw->GetWidth() / 2; int center_y = rw->GetHeight() / 2; int x = center_x - (width / 2); int y = center_y - (((entries_.size() * (height + padding)) - padding) / 2); for (int i = 0; i < entries_.size(); ++i, y += (height + padding)) { entries_[i].Draw(rw, x, y, width, height); } } void MenuState::OnEnter() { } void MenuState::OnExit() { } void MenuState::OnKeyPressed(sf::Key::Code key, bool alt, bool ctrl, bool shift) { if (key == sf::Key::Up) { MoveSelection(Direction::Up); } else if (key == sf::Key::Down) { MoveSelection(Direction::Down); } else if (key == sf::Key::Return) { Select(entries_[selection_].get_id()); } } void MenuState::MoveSelection(Direction::Enum direction) { entries_[selection_].set_selected(false); if (direction == Direction::Up) { --selection_; if (selection_ == -1) { selection_ = entries_.size() - 1; } } else if (direction == Direction::Down) { ++selection_; if (selection_ == entries_.size()) { selection_ = 0; } } entries_[selection_].set_selected(true); } void MenuState::Select(int id) { switch (id) { case MenuEntryID::Play: game_->set_active_state(new GameState(game_)); break; case MenuEntryID::Settings: break; case MenuEntryID::About: break; case MenuEntryID::Quit: game_->Quit(); break; } } void MenuState::AddEntry(int id, std::string text) { entries_.push_back(MenuEntry(id, text)); }
true
202c7feebb29ab7c9f0b67dc52a160bbfe05158e
C++
SharpNip/3DShip
/3DShip/3DShip/BoxCollider.cpp
UTF-8
2,788
3.171875
3
[]
no_license
#include "BoxCollider.h" //Default Constructor, everything's set to zero. BoxCollider::BoxCollider() :Collider3D(nullptr, Type::BOX, 0, 0, 0) , mWidth(0) , mHeight(0) , mDepth(0) { } //Default deconstructor BoxCollider::~BoxCollider() { } // Basically copied from Pier-Luc's 2D colliders, and simply adding in a 3rd dimension -> depth. // This is probably not the most "optimal" way for doing it as it's going to check all of the colliders in the scene instead of checking all of // the ones that are within a certain raycast length. BoxCollider::BoxCollider(Component* caller, float x, float y, float z, float width, float height, float depth) : Collider3D(caller, Type::BOX, x, y, z) , mWidth(abs(width)) , mHeight(abs(height)) , mDepth(abs(depth)) { } //BoxCollider::BoxCollider(Component* caller, D3DXVECTOR3 position, D3DXVECTOR3 dimensions) // : Collider3D(caller, Type::BOX, position.x, position.y, position.z) // , width(abs(dimensions.x)) // , height(abs(dimensions.y)) // , depth(abs(dimensions.z)) //{ // //} // Simple check to determine if a point is within coords // Basically the same as in rectangle, it will check if the xyz coords are touching. bool BoxCollider::Contains(const float x, const float y, const float z) { return (x >= this->GetPosition().x && x <= (this->GetPosition().x + this->GetWidth()) && y >= this->GetPosition().y && y <= (this->GetPosition().y + this->GetHeight()) && z >= this->GetPosition().z && z <= (this->GetPosition().z + this->GetDepth())); } // Modifies the height, width and depth of the colliders void BoxCollider::SetSize(float w, float h, float d) { this->mWidth = w; this->mHeight = h; this->mDepth = d; } void BoxCollider::SetSize(D3DXVECTOR3 v) { this->mWidth = v.x; this->mHeight = v.y; this->mDepth = v.z; } // Copied from Pierluc's Rectangle algorithm. // // But changed it for a 3 dimensional shape instead. bool BoxCollider::CollidesWith(BoxCollider* const box) { bool areColliding = false; if (this->GetPosition().x < (box->GetPosition().x + box->GetWidth()) && (this->GetPosition().x + this->GetWidth()) > box->GetPosition().x && this->GetPosition().y < (box->GetPosition().y + box->GetHeight()) && (this->GetPosition().y + this->GetHeight())> box->GetPosition().y && this->GetPosition().z < (box->GetPosition().z + box->GetDepth()) && (this->GetPosition().z + this->GetDepth())> box->GetPosition().z) { areColliding = true; } return areColliding; } // Based on the tested collider, we'll look for a rectangle-circle collision or a rectangle-rectangle collision. bool BoxCollider::CheckCollision(Collider3D* collider) { bool isColliding = false; if (collider->GetType() == Type::BOX) { isColliding = CollidesWith(static_cast<BoxCollider*>(collider)); } return isColliding; }
true
1c5e3624ad9037ce4c18f8e9a6eb5baff40defd6
C++
blockspacer/swordbow-magic
/include/clientrunningstate.hpp
UTF-8
1,617
2.578125
3
[ "MIT" ]
permissive
#ifndef CLIENTRUNNINGSTATE_HPP #define CLIENTRUNNINGSTATE_HPP #include "iclientstate.hpp" #include "messagetypes.hpp" #include "ipaddress.hpp" class Client; class ClientRunningState : public IClientState { private: Client* client; std::vector<int> presses; //contains what keystrokes have been made (cleared on every gameloop) std::vector<int> releases; //contains what keyreleases have been made (cleared on every gameloop) glm::vec2 mousePos; bool mouseIsMoving = false; //A InputData packet will be sent if this is true public: ClientRunningState(Client* client); void step(); void changeState(IClientState* state); void onChange(ClientDisconnectedState* state); void onChange(ClientReceiveInitialState* state); void onChange(ClientRunningState* state); /** Methods handling various packets**/ std::string name() const override; void greet(IPacket* packet) override; void handle(const OutdatedData* data) override; void handle(const ServerReplyToConnectData* data) override; void handle(const MoveComponentsDiffData* data) override; void handle(const RenderComponentsDiffData* data) override; void handle(const PlaySoundData* data) override; void handle(const RegisterIdToSystemData* data) override; void handle(const RemoveIdData* data) override; void handle(const RemoveIdFromSystemData* data) override; void handle(const RemoveIdFromSystemsData* data) override; void handle(const ActivateIdData* data) override; void handle(const KeepAliveData* data) override; void onEvent(const KeyEvent& evt); void onEvent(const MouseEvent& evt); }; #endif //CLIENTRUNNINGSTATE_HPP
true
1d79926f4bb8a4c9334b8d47ee11fef9452b2b9a
C++
Pstalwalkar7/GFG
/Graph/12.cpp
UTF-8
1,635
2.6875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; class Solution { public: //Function to return the minimum cost to react at bottom //right cell from top left cell. int minimumCostPath(vector<vector<int>>& grid) { int n = grid.size(); int m = grid[0].size(); vector<pair<int,int>> neigh = {{-1,0}, {0,-1}, {0,1}, {1,0}}; vector<vector<int>> dist(n, vector<int>(m, INT_MAX)); priority_queue<vector<int>> Q; // set<vector<int>> S; dist[0][0] = grid[0][0]; Q.push({-grid[0][0], 0, 0}); // S.insert({grid[0][0], 0, 0}); int wt, x, y, nx, ny; while(!Q.empty()){ auto A = Q.top(); Q.pop(); // auto A = *S.begin(); // S.erase(S.begin()); // wt = A[0]; wt = -A[0]; x = A[1]; y = A[2]; for(auto i : neigh){ nx = x + i.first; ny = y + i.second; if (nx < 0 or nx >= n or ny < 0 or ny >= m) continue; if (dist[nx][ny] > dist[x][y] + grid[nx][ny]){ dist[nx][ny] = dist[x][y] + grid[nx][ny]; Q.push({-grid[nx][ny], nx, ny}); // S.insert({grid[nx][ny], nx, ny}); } } } // for(int i = 0; i<n;i++){ // for(int j = 0; j<m;j++){ // cout<<dist[i][j]<<" "; // } // cout<<"\n"; // } return dist[n-1][m-1]; } };
true
6ace8673ac5508aa8b25944faf07b1be03e011cd
C++
lukewegryn/MIPS_Assembler
/main.cpp
UTF-8
4,966
3.015625
3
[]
no_license
/* Luke Wegryn * Project1 * CompOrg 2500 * 2/17/2015 */ #include <fstream> #include <iostream> #include <iomanip> #include <memory> #include <stdexcept> #include <string> #include <sstream> #include <vector> #include <QStringList> #include <QString> #include <QFile> #include <QTextStream> #include <QByteArray> #include "exceptions.h" #include "lexer.h" #include "util.h" #include "helper.cpp" std::string read_file(const std::string& name) { std::ifstream file(name); if (!file.is_open()) { std::string error = "Could not open file: "; error += name; throw std::runtime_error(error); } std::stringstream stream; stream << file.rdbuf(); return std::move(stream.str()); } /* The parseInstruction takes in the current instruction that the program is assembling and the file to output the assembly to. It assembles the current instruction and outputs the value to the file. */ QByteArray parseInstruction(currentInstruction curr, QString outFile){ uint assembled = decodeInstruction(curr); //function in helper.cpp QFile file(outFile); //file to write the assembled data to if (!file.open(QIODevice::Append | QIODevice::Text)) //append data to the file return 0; QTextStream out(&file); uint currMask = 0xf0000000; //this adds zeros to the front to make it appear as 8 characters in the file while(!(assembled & currMask)){ //while we still haven't gotten to the first non zero value in the assembled hex out << 0; //output a 0 to the text file currMask = currMask >> 4; //shift to mask the next hex character } out << hex << assembled << "\n"; //output the assembled instruction return 0; } int main(int argc, char** argv) { // Adjusting -- argv[0] is always filename. --argc; ++argv; if (argc == 0) { std::cerr << "Need a file" << std::endl; return 1; } for (int i = 0; i < argc; ++i) { std::string asmName(argv[i]); asmName += ".asm"; if (!util::ends_with_subseq(asmName, std::string(".asm"))) { std::cerr << "Need a valid file name (that ends in .asm)" << std::endl; std::cerr << "(Bad name: " << asmName << ")" << std::endl; return 1; } // 4 is len(".asm") auto length = asmName.size() - string_length(".asm"); std::string baseName(asmName.begin(), asmName.begin() + length); QString outFileName; outFileName = QString::fromStdString(baseName); //file to write to outFileName += ".txt"; QFile file(outFileName); if(file.exists()){ file.remove(); } std::cout << std::endl; try { auto text = read_file(asmName); try { auto lexed = lexer::analyze(text); // Parses the entire file and returns a vector of instructions for (int i =0; i < (int)lexed.size(); i++){ //look through the file and find where all the labels are currInstruction.token.clear(); //clear any lingering tokens from my structure if(lexed[i].labels.size() > 0){ // Checking if there is a label in the current instruction currInstruction.label = QString::fromStdString(lexed[i].labels[0]); //get the current label currLabel.first = currInstruction.label; //adding label to symbol table currLabel.second = i; //adding location of label to symbol table symbolList.append(currLabel); //add the label to the symbol list } } for (int i =0; i < (int)lexed.size(); i++){ //now actually do the assembling currInstruction.token.clear(); //clear any lingering tokens currInstruction.label.clear(); //clear any lingering labels currInstruction.name = QString::fromStdString(lexed[i].name); //get the current instruction name std::vector<lexer::token> tokens = lexed[i].args; for(int j=0; j < (int)tokens.size(); j++){ // adds all tokens to the dataStructure this instruction like $t1, $t2, $t3 if (tokens[j].type == lexer::token::Integer){ int currInt = tokens[j].integer(); currInstruction.token.append(QString::number(currInt)); //add tokens to current instruction if int } else currInstruction.token.append(QString::fromStdString(tokens[j].string())); //same if string } currInstruction.position = i; //put the current position in the structure currentLineNumber = i+1; //this is for the error messages parseInstruction(currInstruction, outFileName); //parse the current instruction and write to file } } catch(const bad_asm& e) { std::stringstream error; error << "Cannot assemble the assembly code at line " << e.line; throw std::runtime_error(error.str()); } catch(const bad_label& e) { std::stringstream error; error << "Undefined label " << e.what() << " at line " << e.line; throw std::runtime_error(error.str()); } } catch (const std::runtime_error& err) { std::cout << err.what() << endl; //return 1; //return 0; } } return 0; }
true
c807a7d96d33fe9d665d7714837e9b7eef0512e0
C++
newton449/virtual-server
/VirtualServerWindows/MainProgram/HttpServletsImpl.cpp
UTF-8
6,932
2.84375
3
[]
no_license
#include <fstream> #include "HttpServletsImpl.h" #include "FileSystem.h" #include "Logger.h" #include "StringUtils.h" //////////////////////////////////////////////////////////////////////// // Function implementations of DefaultHttpServlet // Do the HTTP method. void DefaultHttpServlet::doMethod(String methodName, IHttpServletRequest& request, IHttpServletResponse& response){ response.sendError(405); // 405 Method Not Allowed } //////////////////////////////////////////////////////////////////////// // Function implementations of StaticResourcesServlet StaticResourcesServlet::StaticResourcesServlet(string contextPath, string directoryPath) :contextPath(contextPath), directoryPath(directoryPath){ } void StaticResourcesServlet::doMethod(IHttpServletRequest& request, IHttpServletResponse& response){ // Only get method is allowed if (request.getMethod() != "GET"){ response.sendError(404); return; } // check context path string url = request.getRequestUrl(); if (!StringUtils::startWith(url, contextPath + "/")){ response.sendError(500); LOG(WARNING) << "The url \"" << url << "\" does not match the context path \"" << contextPath << "\"."; return; } // get short url (without first slash) url = url.substr(contextPath.length() + 1); if (url.empty()){ url = "index.html"; // default page } // build file path string filePath = StringUtils::fixFilePath(directoryPath + url); // check whether it exists if (!FileSystem::File::exists(filePath)){ LOG(DEBUG) << "Failed to find a file for \"" << url << "\" in directory \"" << directoryPath << "\""; response.sendError(404); return; } // get file size LOG(DEBUG) << "Sending file: " << filePath; FileSystem::FileInfo info(filePath); size_t fileSize = info.size(); response.setContentLength(fileSize); // TODO set content type according to mine-type if (StringUtils::hasEnding(filePath, ".html")){ response.setContentType("text/html"); } else if (StringUtils::hasEnding(filePath, ".zip")){ response.setContentType("application/x-compressed"); } else if (StringUtils::hasEnding(filePath, ".png")){ response.setContentType("image/png"); } else if (StringUtils::hasEnding(filePath, ".gif")){ response.setContentType("image/gif"); } else if (StringUtils::hasEnding(filePath, ".jpg")){ response.setContentType("image/jpg"); } else if (StringUtils::hasEnding(filePath, ".js")){ response.setContentType("text/javascript"); } else if (StringUtils::hasEnding(filePath, ".txt")){ response.setContentType("text/plain"); } else if (StringUtils::hasEnding(filePath, ".css")){ response.setContentType("text/css"); } else { LOG(WARNING) << "Unknown MIME type"; response.sendError(404); } response.flushBuffer(); // send the file to response ostream& out = response.getOutputStream(); ifstream fin(filePath, ifstream::in | ifstream::binary); int sentCount = 0; if (fin.good()){ char buf[1024]; while (true){ fin.read(buf, 1024); if (fin){ out.write(buf, fin.gcount()); } else{ out.write(buf, fin.gcount()); break; } } fin.close(); } else{ response.sendError(404); } //int c = fin.get(); //while (c != EOF){ // out.put(c); // c = fin.get(); //} //fin.close(); } //////////////////////////////////////////////////////////////////////// // Function implementations of UploadFileServlet // Constructor with the folder to save uploaded files. UploadFileServlet::UploadFileServlet(std::string folder){ if (folder.empty()){ this->folder = ".\\"; } else if (folder[folder.size() - 1] == '\\'){ this->folder = folder; } else{ this->folder = folder + "\\"; } } // Do HTTP method. void UploadFileServlet::doMethod(IHttpServletRequest& request, IHttpServletResponse& response){ if (!checkRequest(request, response)){ return; } // Create the file. The current file will be overrided. std::string name = request.getParameter("file_name"); createFolderForFile(folder + name); std::ofstream fout; fout.open(folder + name, std::ofstream::out | std::ofstream::binary); if (!fout){ response.sendErrorWithMessage(500, "Cannot open the file."); return; } // Read input bool error = true; std::istream& in = request.getInputStream(); std::string chunkSizeLine; std::string tmp; int chunkSize; std::getline(in, chunkSizeLine); char* buf = NULL; int bufSize = 0; while (in){ if (!readOneChunk(in, chunkSize, chunkSizeLine, error, buf, bufSize, fout, response)){ break; } // Read the next chunk std::getline(in, chunkSizeLine); } if (buf != NULL){ delete buf; } // close the file fout.close(); // Send error if occurred if (error){ if (!response.isCommitted()){ response.sendErrorWithMessage(400, "Wrong chunked format"); } // throw an exception to close connection throw std::logic_error("Wrong chunked format"); } else{ LOG(INFO) << "Saved the file \"" << folder << name << "\"."; } } void UploadFileServlet::createFolderForFile(std::string file){ size_t pos = file.find_last_of("\\"); if (pos != std::string::npos){ std::string dir = file.substr(0, pos); if (!FileSystem::Directory::exists(dir)){ FileSystem::Directory::create(dir); } } } // Checks the request. Returns false if error occurred. bool UploadFileServlet::checkRequest(IHttpServletRequest& request, IHttpServletResponse& response){ // Check whether it is chunck mode if (request.getHeader("Transfer-Encoding") != "chunked"){ response.sendErrorWithMessage(501, "Please use chunked mode"); return false; } std::string name = request.getParameter("file_name"); if (name.empty()){ // PENDING 404? response.sendErrorWithMessage(404, "Invalid file name"); return false; } return true; } // Reads one chunk in the input stream. Returns false to break the // loop. bool UploadFileServlet::readOneChunk(std::istream& in, int& chunkSize, std::string& chunkSizeLine, bool& error, char*& buf, int& bufSize, std::ofstream& fout, IHttpServletResponse& response){ std::string tmp; if (chunkSizeLine.empty() || chunkSizeLine[0]<48 || chunkSizeLine[0]>57){ // it is an invalid chuncked format return false; } chunkSize = std::atoi(chunkSizeLine.c_str()); // ignore optional alphabets. if (chunkSize == 0){ // read the empty line std::getline(in, tmp); error = false; // exit normally return false; } // check buf if (bufSize < chunkSize){ if (buf != NULL){ delete buf; } buf = new char[chunkSize]; bufSize = chunkSize; } // read chunk in.read(buf, chunkSize); if (!in){ return false; } // read the \r\n std::getline(in, tmp); if (tmp != "\r" && !tmp.empty()){ return false; } // Save to the file fout.write(buf, chunkSize); if (!fout){ response.sendErrorWithMessage(500, "Failed to save the file."); return false; } return true; }
true
6f637ee289791f67c3247f3bd9734be7d64fb7dc
C++
thdgmltjd123/Algorithm_04
/baekjoon/20200101/20200101/1427 소트인사이드.cpp
UHC
425
3.078125
3
[]
no_license
// 10989 ذߴ ̿Ͽ Ǯ! // ̹Ƿ count 迭 ! #include <iostream> #include <string> using namespace std; int main(void) { int count[10] = { 0, }; string s; cin >> s; for (int i = 0; i < s.length(); i++) { count[s[i] - '0']++; } for (int i = 9; i >= 0; i--) { for (int j = 0; j < count[i]; j++) { cout << i; } } return 0; }
true
f6d992b994ea8609e9b8a3f241ffb7c3e9787477
C++
claytonsuplinski/RacingGame
/RacingGame/alien.cpp
UTF-8
11,640
2.75
3
[]
no_license
/* Name: Clayton Suplinski ID: 906 580 2630 CS 559 Project 3 Creates an alien object out of cylinders, discs, and spheres. */ #include <iostream> #include "alien.h" using namespace std; using namespace glm; //Create a alien object Alien::Alien() : Object(){} Alien::~Alien(){ this->TakeDown(); } //Initialize the elements of the Alien object bool Alien::Initialize() { if (this->GLReturnedError("Alien::Initialize - on entry")) return false; if (!super::Initialize()) return false; this->arm = new Cylinder2();this->antenna = new Cylinder(); this->leg = new Cylinder2();this->body = new Cylinder2(); this->bodyBot = new Disc(); this->center = new Sphere();this->eye = new Sphere(); this->mouth = new Sphere(); this->head = new Sphere2(); this->hand = new Sphere2(); this->foot = new Sphere2(); this->center->lava = true; this->eyebrow = new Square(); this->arm->texID = 4; this->arm->Initialize(8,2.0f,0.15f,0.15f,"./textures/alienTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->body->texID = 10; this->body->Initialize(10,1.25f,1.25f,0.4f,"./textures/clothTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->antenna->color = vec3(0.0f, 0.0f, 0.0f); this->antenna->Initialize(2,2.5f,0.05f,0.05f, "phong.vert", "phong.frag"); this->leg->texID = 4; this->leg->Initialize(8,0.85f,0.2f,0.2f,"./textures/alienTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->bodyBot->color = vec3(0.35f, 0.3f, 0.25f); this->bodyBot->Initialize(10,1.25f, "phong.vert", "phong.frag"); this->center->color = vec3(1.0f, 0.15f, 0.05f); this->center->Initialize(8,0.35f, "phong.vert", "phong.frag"); this->foot->texID = 4; this->foot->Initialize(8,0.25f,"./textures/alienTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->eye->color = vec3(0.0f, 0.0f, 0.0f); this->eye->Initialize(8,0.75f, "phong.vert", "phong.frag"); this->head->texID = 4; this->head->Initialize(2,2.0f,"./textures/alienTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->hand->texID = 4; this->hand->Initialize(8,0.35f, "./textures/alienTexture.jpg", "basic_texture_shader.vert", "basic_texture_shader.frag"); this->mouth->color = vec3(0.0f, 0.0f, 0.0f);this->mouth->Initialize(8,0.15f, "phong.vert", "phong.frag"); this->eyebrow->color1 = vec3(0.0f, 0.0f, 0.0f);this->eyebrow->color2 = vec3(0.0f, 0.0f, 0.0f); this->eyebrow->Initialize(1,1.0f, "phong.vert", "phong.frag"); if (this->GLReturnedError("Tiger::Initialize - on exit")) return false; return true; } void Alien::StepShader(){ } //Delete the elements of the Alien void Alien::TakeDown(){ this->arm = NULL;this->antenna = NULL;this->leg = NULL; this->bodyBot = NULL;this->center = NULL;this->hand = NULL; this->body = NULL;this->eye = NULL;this->mouth = NULL; this->head = NULL;this->foot = NULL;this->eyebrow = NULL; this->vertices.clear(); this->shader.TakeDown(); this->solid_color.TakeDown(); super::TakeDown(); } //Draw a Alien object void Alien::Draw(const mat4 & projection, mat4 modelview, const ivec2 & size, const float rotY) { if (this->GLReturnedError("Alien::Draw - on entry")) return; glEnable(GL_DEPTH_TEST); float t = float(glutGet(GLUT_ELAPSED_TIME)) / 150.0f; mat4 another, scaler; //Make it run if(rotY == 0){ another = translate(modelview, vec3(0.35,0.0,0)); this->center->Draw(projection, another, size, rotY); another = translate(another, vec3(-0.35,0.0,0)); another = translate(another, vec3(0.85,0.95,0)); another = rotate(another, 90.0f, vec3(0,0,1)); this->body->Draw(projection, another, size, rotY); this->bodyBot->Draw(projection, another, size, rotY); //Arms another = translate(another, vec3(0.0,0.35,0.35)); another = rotate(another, 45.0f, vec3(1,0,0)); this->arm->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,1.75,0.0)); this->hand->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-1.75,0.0)); another = rotate(another, -45.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.35,-0.35)); another = translate(another, vec3(0.0,0.35,-0.35)); another = rotate(another, -45.0f, vec3(1,0,0)); this->arm->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,1.75,0.0)); this->hand->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-1.75,0.0)); another = rotate(another, 45.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.35,0.35)); //Legs another = translate(another, vec3(0.0,0.15,0.35)); another = rotate(another, 165.0f, vec3(1,0,0)); another = rotate(another, 55*sin(t), vec3(0,0,1)); this->leg->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,0.75,0.0)); this->foot->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-0.75,0.0)); another = rotate(another, -55*sin(t), vec3(0,0,1)); another = rotate(another, -165.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.15,-0.35)); another = translate(another, vec3(0.0,0.15,-0.35)); another = rotate(another, -165.0f, vec3(1,0,0)); another = rotate(another, -55*sin(t), vec3(0,0,1)); this->leg->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,0.75,0.0)); this->foot->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-0.75,0.0)); another = rotate(another, 55*sin(t), vec3(0,0,1)); another = rotate(another, 165.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.15,0.35)); another = rotate(another, -90.0f, vec3(0,0,1)); another = translate(another, vec3(-2.75,0.0,0)); scaler = scale(another, vec3(1.0, 0.5, 0.5)); this->head->Draw(projection, scaler, size, rotY); //Mouth another = translate(another, vec3(0.95,-0.85,0.0)); this->mouth->Draw(projection, another, size, rotY); another = translate(another, vec3(-0.95,0.85,0.0)); //Eye another = translate(another, vec3(-0.75,-0.85,0.5)); scaler = scale(another, vec3(1.0, 0.35, 0.35)); this->eye->Draw(projection, scaler, size, rotY); another = translate(another, vec3(-0.4,0.0,-0.3)); another = rotate(another, 135.0f, vec3(0,1,0)); scaler = scale(another, vec3(0.25, 0.25, 1.0)); this->eyebrow->Draw(projection, scaler, size, rotY); another = rotate(another, -135.0f, vec3(0,1,0)); another = translate(another, vec3(0.4,0.0,0.3)); //Antennas another = translate(another, vec3(-0.75, 0.85, 0.15)); another = rotate(another, 90.0f, vec3(1,0,0)); another = rotate(another, 65.0f, vec3(0,0,1)); this->antenna->Draw(projection, another, size, rotY); another = rotate(another, -65.0f, vec3(0,0,1)); another = rotate(another, -90.0f, vec3(1,0,0)); another = translate(another, vec3(0.0, 0.0, -1.3)); another = rotate(another, 90.0f, vec3(1,0,0)); another = rotate(another, 115.0f, vec3(0,0,1)); this->antenna->Draw(projection, another, size, rotY); another = rotate(another, -115.0f, vec3(0,0,1)); another = rotate(another, -90.0f, vec3(1,0,0)); another = translate(another, vec3(0.75, -0.85, 1.15)); //Eye another = translate(another, vec3(0.0,0.0,-1.0)); scaler = scale(another, vec3(1.0, 0.35, 0.35)); this->eye->Draw(projection, scaler, size, rotY); another = translate(another, vec3(-0.525,0.0,0.3)); another = rotate(another, 45.0f, vec3(0,1,0)); scaler = scale(another, vec3(0.25, 0.25, 1.0)); this->eyebrow->Draw(projection, scaler, size, rotY); another = rotate(another, -45.0f, vec3(0,1,0)); another = translate(another, vec3(0.525,0.0,-0.3)); another = translate(another, vec3(1.25,-0.75,0)); } //Make it dance else if(rotY == 1){ another = translate(modelview, vec3(0.35,0.0,0)); this->center->Draw(projection, another, size, rotY); another = translate(another, vec3(-0.35,0.0,0)); another = translate(another, vec3(0.85,0.95,0)); another = rotate(another, 90.0f, vec3(0,0,1)); this->body->Draw(projection, another, size, rotY); this->bodyBot->Draw(projection, another, size, 0); //Arms another = translate(another, vec3(0.0,0.35,0.35)); another = rotate(another, 45.0f, vec3(1,0,0)); another = rotate(another, -abs(15*sin(t)), vec3(1,0,0)); this->arm->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,1.75,0.0)); this->hand->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-1.75,0.0)); another = rotate(another, abs(15*sin(t)), vec3(1,0,0)); another = rotate(another, -45.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.35,-0.35)); another = translate(another, vec3(0.0,0.35,-0.35)); another = rotate(another, -45.0f, vec3(1,0,0)); another = rotate(another, -abs(15*sin(t)), vec3(1,0,0)); this->arm->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,1.75,0.0)); this->hand->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-1.75,0.0)); another = rotate(another, abs(15*sin(t)), vec3(1,0,0)); another = rotate(another, 45.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.35,0.35)); //Legs another = translate(another, vec3(0.0,0.15,0.35)); another = rotate(another, 165.0f, vec3(1,0,0)); another = rotate(another, abs(15*sin(t)), vec3(1,0,0)); this->leg->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,0.75,0.0)); this->foot->Draw(projection, another, size, rotY); another = rotate(another, -abs(15*sin(t)), vec3(1,0,0)); another = translate(another, vec3(0,-0.75,0.0)); another = rotate(another, -165.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.15,-0.35)); another = translate(another, vec3(0.0,0.15,-0.35)); another = rotate(another, -165.0f, vec3(1,0,0)); this->leg->Draw(projection, another, size, rotY); another = translate(another, vec3(0.0,0.75,0.0)); this->foot->Draw(projection, another, size, rotY); another = translate(another, vec3(0,-0.75,0.0)); another = rotate(another, 165.0f, vec3(1,0,0)); another = translate(another, vec3(0,-0.15,0.35)); another = rotate(another, -90.0f, vec3(0,0,1)); another = translate(another, vec3(-2.75,0.0,0)); scaler = scale(another, vec3(1.0, 0.5, 0.5)); this->head->Draw(projection, scaler, size, rotY); //Mouth another = translate(another, vec3(0.95,-0.85,0.0)); this->mouth->Draw(projection, another, size, rotY); another = translate(another, vec3(-0.95,0.85,0.0)); //Eye another = translate(another, vec3(-0.75,-0.85,0.5)); scaler = scale(another, vec3(1.0, 0.35, 0.35)); this->eye->Draw(projection, scaler, size, rotY); //Antennas another = translate(another, vec3(-0.75, 0.85, 0.15)); another = rotate(another, 90.0f, vec3(1,0,0)); another = rotate(another, 65.0f, vec3(0,0,1)); this->antenna->Draw(projection, another, size, rotY); another = rotate(another, -65.0f, vec3(0,0,1)); another = rotate(another, -90.0f, vec3(1,0,0)); another = translate(another, vec3(0.0, 0.0, -1.3)); another = rotate(another, 90.0f, vec3(1,0,0)); another = rotate(another, 115.0f, vec3(0,0,1)); this->antenna->Draw(projection, another, size, rotY); another = rotate(another, -115.0f, vec3(0,0,1)); another = rotate(another, -90.0f, vec3(1,0,0)); another = translate(another, vec3(0.75, -0.85, 1.15)); //Eye another = translate(another, vec3(0.0,0.0,-1.0)); scaler = scale(another, vec3(1.0, 0.35, 0.35)); this->eye->Draw(projection, scaler, size, rotY); another = translate(another, vec3(1.25,-0.75,0)); } if (this->GLReturnedError("Alien::Draw - on exit")) return; }
true
1dc1f10bb84a43db89c84198ddf34bd44b9a784d
C++
elwin0214/leetcode
/src/palindrome/ShortestPalindrome.cpp
UTF-8
632
2.96875
3
[]
no_license
/* https://leetcode.com/problems/shortest-palindrome/ Shortest Palindrome My Submissions Question Total Accepted: 11498 Total Submissions: 66112 Difficulty: Hard Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation. For example: Given "aacecaaa", return "aaacecaaa". Given "abcd", return "dcbabcd". Credits: Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases. Subscribe to see which companies asked this question */
true
8dc071380403497bf94ec676ee71f00efee3ff29
C++
tanvir14012/Sphere-Online-Judge-My_Solutions
/spoj ARITH2 try.cpp
UTF-8
1,806
3.046875
3
[]
no_license
#include <stdio.h> int main() { char operator; long long n, a, res; scanf( "%lld", &n ); while ( n-- ) { operator = 0; scanf( "%lld", &res ); while ( 1 ) { scanf( "%s", &operator ); if ( operator == '=' ) { break; } scanf( "%lld", &a ); switch ( operator ) { case '+': res += a; break; case '-': res -= a; break; case '*': res *= a; break; case '/': res /= a; break; } } printf( "%lld\n", res ); } return 0; } /* #include<iostream> #include<string> #include<stdio.h> using namespace std; int main() { int n; cin>>n; char ch; scanf("%*c",&ch); string str; while(n--) { getline(cin,str); char oper; int i=0; long long num=0,ans=0; for(;i<str.length()&&str.at(i)>='0'&&str.at(i)<='9';i++) { num*=10; num+=(str.at(i)-'0'); } ans=num; for(;i<str.length();) { num=0; i++; oper=str.at(i); if(oper=='=') break; i+=2; for(;str.at(i)>='0'&&str.at(i)<='9';i++) { num*=10; num+=(str.at(i)-'0'); } switch(oper) { case '+' : ans=ans+num; break; case '*': ans=ans*num; break; case '-': ans=ans-num; break; case '/' : ans=ans/num; break; } } cout<<ans<<endl; } } */
true
55b0e3f67edb83ed8961ea220c8c1dd2e33d9c5c
C++
Manash-git/C-Programming-Study
/str length manually.cpp
UTF-8
204
2.765625
3
[]
no_license
//#include<stdio.h> #include<bits/stdc++.h> int main(){ char s[100]; int i; printf("Enter a string:\t"); gets(s); for(i=0;s[i]!='\0';++i); printf("\n Length of the strings: %d",i); return 0; }
true
35acb6a81e9db7324fa47aa804ce0db7e5285fca
C++
IFortunater/LCRecord
/C++/70.cpp
UTF-8
1,260
3.65625
4
[]
no_license
#include<iostream> using namespace std; // 时间超限 不可取 // class Solution // { // private: // int count = 0; // public: // int climbStairs(int n) // { // calculate(n); // return count; // } // void calculate(int n){ // if (n == 0){ // count++; // return; // } // if (n < 0) // return; // calculate(n-1); // calculate(n-2); // } // }; // 仔细分析后得出:每一个数字n都是由前一个数字(n-1)+1和前两个数字(n-2)+2得来 // 所以到n的方案数等于到(n-1)的方案数+(n-2)的方案数 // 所以f(n) = f(n-1) + f(n-2) // 这是是不是就像是斐波那契呢 class Solution { private: int count = 0; public: int climbStairs(int n) { if (n == 0) return 0; if (n == 1) return 1; if (n == 2) return 2; int pre1 = 1, pre2 = 2; int res; for (int i = 3; i <= n; i++){ res = pre1 + pre2; pre1 = pre2; pre2 = res; } return res; } }; int main(int argc, char const *argv[]) { Solution s = Solution(); cout << s.climbStairs(4) << endl; return 0; }
true
63ad648d83d42e7e7acc5935cffd41aff47e29c7
C++
romaldowoho/UCSC-Cpp-class
/HW2 - basic/ninetynine/ninetynine.cpp
UTF-8
2,205
3.515625
4
[]
no_license
#include "ninetynine.h" #include "../util/util.h" void ninetynine::run() { string ones[] = {"nine", "eight", "seven", "six", "five", "four", "three", "two", "one", ""}; string zero[] = {"Nine", "Eight", "Seven", "Six", "Five", "Four", "Three", "Two", "One", "Zero"}; string tens[] = {"Ninety", "Eighty", "Seventy", "Sixty", "Fifty", "Forty", "Thirty", "Twenty"}; string teeens[] = {"Nineteen", "Eighteen", "Seventeen", "Sixteen", "Fifteen", "Fourteen", "Thirteen", "Twelve", "Eleven", "Ten"}; for(int i = 0; i < 8; i++) { for (int j = 0; j < 10; j++) { cout << tens[i] << " " << ones[j] << " bottles of beer on the wall," << endl; cout << tens[i] << " " << ones[j] << " bottles of beer," << endl; int k = j + 1; if(j == 9) continue; cout << "Take one down, pass it around," << endl; cout << tens[i] << " " << ones[k] << " bottles of beer on the wall," << endl; cout << endl; } } cout << "Take one down, pass it around," << endl; cout << "Nineteen bottles of beer on the wall," << endl; cout << endl; for(int i = 0; i < 10; i++) { cout << teeens[i] << " bottles of beer on the wall," << endl; cout << teeens[i] << " bottles of beer," << endl; int k = i + 1; if(i == 9) { cout << "Take one down, pass it around," << endl; cout << "Nine bottles of beer on the wall," << endl; cout << endl; } cout << "Take one down, pass it around," << endl; cout << teeens[k] << " bottles of beer on the wall," << endl; cout << endl; } for(int i = 0; i < 10; i++) { if (i == 8) { cout << zero[i] << " bottle of beer on the wall," << endl; cout << zero[i] << " bottle of beer," << endl; int k = i + 1; cout << "Take one down, pass it around," << endl; cout << zero[k] << " bottles of beer on the wall," << endl; cout << endl; break; } cout << zero[i] << " bottles of beer on the wall," << endl; cout << zero[i] << " bottles of beer," << endl; int k = i + 1; if(i == 9) continue; cout << "Take one down, pass it around," << endl; if (k==8) { cout << zero[k] << " bottle of beer on the wall," << endl; cout << endl; continue; } cout << zero[k] << " bottles of beer on the wall," << endl; cout << endl; } }
true
00b30b5369a458f19287bd1df9dcd67273756c3b
C++
LinkSon-PC/EDD_1S2020_PY1_201800634
/EDD_1S2020_201800634/EDD_1S2020_201800634/Matriz.h
UTF-8
5,201
2.5625
3
[]
no_license
#include <iostream> #include <string> #include <stdio.h> #include <conio.h> #include <stdlib.h> #include <fstream> #include "Ficha.h" using namespace std; class Matriz { int y; int x; Ficha* _Ficha; int _Punto; Matriz* _Arriba; Matriz* _Abajo; Matriz* _Izquierda; Matriz* _Dercha; public: static Matriz* _Tablero; static Matriz* _Aux; Matriz* _Inicio; ofstream RepTablero; int Dimension; inline int getY() { return this->y; }; inline void setY(int _y) { this->y = _y; }; inline int getX() { return this->x; }; inline void setX(int _x) { this->x = _x; }; inline int getPunto() { return this->_Punto; }; inline void setPunto(int Punto) { this->_Punto = Punto; }; inline Ficha* getFicha() { return this->_Ficha; }; inline void setFicha(Ficha* Ficha) { this->_Ficha = Ficha; }; Matriz(); Matriz(int _Dimension); Matriz(int _y, int _x, Ficha* Ficha); void GenerarMatriz(); Matriz* Celdas(Matriz* _Nodo); inline void ImprimirMatriz(); inline void Tablero(); //INSERTAR PUNTOS EN EL TABLERO void CeldaPuntos(int _x, int _y, Matriz* _Celda,int puntos); //INSERTAR FICHAS EN EL TABLREO void CeldasFichas(int _x, int _y, Matriz* _Celda, Ficha* Ficha); Matriz* InicioPalabra(int x, int y, Matriz* inicio); string ObtenerPalabra(int x, int y); int PuntosPalabra(int x, int y); void EliminarCelda(int x, int y, Matriz* inicio); //IMPIMIR FICHAS EN EL TABLERO /*void ImprimirTablero(); void ImprinirFichas(int _x, int _y, Matriz* _Celda, Ficha* Ficha); bool VerAbajo(Matriz* _Celda); bool VerDerecha(Matriz* _Celda);*/ }; void Matriz::ImprimirMatriz() { RepTablero.open("RepTablero.dot", ios::out); if (RepTablero.fail()) { cout << "ERROR ARCHIVO NO ENCONTRADO" << endl; } else { RepTablero << "digraph G { style = filled; bgcolor = white; color = lightgrey; node[shape=box, style = filled];" << endl; Tablero(); Matriz* _fila = this->_Inicio; for (int i = 0; i < this->Dimension; i++) { RepTablero << "{rank = same;"; Matriz* _columna = _fila; for (int i = 0; i < this->Dimension; i++) { RepTablero << to_string((int)&*_columna) << " "; _columna = _columna->_Dercha; } RepTablero << "};"; _fila = _fila->_Abajo; } RepTablero << "}"; RepTablero.close(); char dotT[] = "dot -Tjpg RepTablero.dot -o RepTablero.jpg"; system(dotT); char dotI[] = "RepTablero.jpg"; system(dotI); } } void Matriz::Tablero() { Matriz* _fila = this->_Inicio; for (int i = 0; i < this->Dimension; i++) { Matriz* _columna = _fila; for (int i = 0; i < this->Dimension; i++) { /*RepTablero << to_string((int)&*_columna) << "[label =\"" << "(" + to_string(_columna->getX()) + "," + to_string(_columna->getY()) + ")\"];";;*/ /*RepTablero << to_string((int)&*_columna) << "[label =\"" << _columna->getPunto() << "\"];";*/ RepTablero << to_string((int)&*_columna); if (_columna->getFicha() != NULL) { RepTablero << "[label =\"" << _columna->getFicha()->GetLetra() << "\"];"; } else { RepTablero << "[label =\" \"];"; } if (_columna->_Dercha!=NULL) { RepTablero << to_string((int)&*_columna) << "->" << to_string((int)&*_columna->_Dercha) << "[dir=both] ;" << endl; } _columna = _columna->_Dercha; } _fila = _fila->_Abajo; } Matriz* _columna = this->_Inicio; for (int i = 0; i < this->Dimension; i++) { _fila = _columna; for (int i = 0; i < this->Dimension; i++) { //RepTablero << to_string((int)&*_fila) << "[label =\"" << "(" + to_string(_fila->getX()) + "," + to_string(_fila->getY()) + ")\"];"; /*RepTablero << to_string((int)&*_fila) << "[label =\"" << _fila->getPunto() << "\"];";*/ RepTablero << to_string((int)&*_fila); if (_fila->getFicha() != NULL) { RepTablero << "[label =\"" << _fila->getFicha()->GetLetra() << "\"];"; } else { RepTablero << "[label =\" \"];"; } if (_fila->_Abajo != NULL) { RepTablero << to_string((int)&*_fila) << "->" << to_string((int)&*_fila->_Abajo) << "[dir=both] ;" << endl; } _fila = _fila->_Abajo; } _columna = _columna->_Dercha; } } /// ========================== PENDIENTE ============================== //void Matriz::ImprimirTablero() { // // Matriz* aux = this->_Inicio->_Abajo; // for (int i = 0; i < this->Dimension; i++) // { // string rank = "{rank = same;"; // if (VerDerecha(aux)) // { // // rank += "};"; // } // else // { // aux->_Aux->_Abajo; // i++; // } // // aux = aux->_Abajo; // } //} // //bool Matriz::VerDerecha(Matriz* _Celda) { // if (_Celda!=NULL) // { // if (_Celda->getFicha()!=NULL ) // { // return true; // } // else // { // return VerDerecha(_Celda->_Dercha); // } // } // return false; //} // //bool Matriz::VerAbajo(Matriz* _Celda) { // if (_Celda != NULL) // { // if (_Celda->getFicha() != NULL) // { // return true; // } // else // { // return VerAbajo(_Celda->_Abajo); // } // } // return false; //}
true
6fe0e1253d40b41e12f60bf03c1b03266a935f31
C++
hieu-ln/IT82-03
/CodeC3/LeQuocVin_C3_Bai1.cpp
UTF-8
7,157
2.859375
3
[]
no_license
//#include <iostream> //#include <iomanip> //#include <ctime> //#include <stdio.h> //using namespace std; //#define MAX 5000 //int a[MAX], n; //void output(int a[], int n) //{ // for (int i = 0; i < n; i++) // cout << setw(4) << a[i]; // cout << endl; //} //void input(int a[], int &n) //{ // for (int i = 0; i < n; i++) // a[i] = rand() % 100; // output(a, n); //} //void copy(int a[], int b[], int n) //{ // for (int i = 0; i < n; i++) // b[i] = a[i]; //} //void swap(int &a, int &b) //{ // int tamp = a; // a = b; // b = tamp; //} //void SelectionSort(int a[], int n) //{ // int min_pos; // for (int i = 0; i < n - 1; i++) // { // min_pos = i; // for (int j = i + 1; j < n; j++) // if (a[j] < a[min_pos]) // min_pos = j; // swap(a[min_pos], a[i]); // } //} //void InsertionSort(int a[], int n) //{ // int x, j; // for (int i = 1; i < n; i++) // { // x = a[i]; // j = i - 1; // while (0 <= j && x < a[i]) // { // a[j + 1] = a[j]; // j--; // } // a[j + 1] = x; // } //} ////void BubbleSort(int a[], int n) ////{ //// for (int i = 0; i < n - 1; i++) //// { //// for (int j = n - i - 1; j > i; j--) //// if (a[j - 1] > a[j]) //// swap(a[j], a[j - 1]); //// } ////} //void BubbleSort(int a[], int n) //{ // bool kq = false; // for (int i = 0; i < n - 1; i++) // { // kq = false; // for (int j = 0; j < n - 1; j++) // if (a[j - 1] > a[j]) { // kq = true; // swap(a[j], a[j + 1]); // } // if (kq == false) // break; // } //} //void InterchangeSort(int a[], int n) //{ // for (int i = 0; i < n - 1; i++) // for (int j = i + 1; j < n; j++) // if (a[i] > a[j]) // swap(a[i], a[j]); //} //int partition(int a[], int low, int high) //{ // int pivot = a[high]; // int left = low; // int right = high - 1; // while (true) { // while (left <= right && a[left] < pivot) // left++; // while (right >= left && a[right] > pivot) // right++; // if (left >= right) // break; // swap(a[left], a[right]); // left++; // right--; // } // swap(a[left], a[high]); // return left; //} //void QuickSort(int a[], int low, int high) //{ // if (low < high) // { // int pi = partition(a, low, high); // QuickSort(a, low, pi - 1); // QuickSort(a, pi + 1, high); // } //} //void heapify(int a[], int n, int i) //{ // int largest = i; // int l = 2 * i + 1; // int r = 2 * i + 2; // if (l < n && a[l] > a[largest]) // largest = l; // if (r < n && a[r] > a[largest]) // largest = r; // if (largest != i) // { // swap(a[i], a[largest]); // heapify(a, n, largest); // } //} //void HeapSort(int a[], int n) //{ // for (int i = n / 2 - 1; i >= 0; i--) // heapify(a, n, i); // for (int i = n - 1; i >= 0; i--) // { // swap(a[0], a[i]); // heapify(a, i, 0); // } //} //int search(int a[], int n, int x) //{ // int i = 0; // while (i < n && a[i] != x) // i++; // if (i < n) // return i; // return -1; //} //int BinarySearch(int a[], int n, int x) //{ // // int left = 0, right = n - 1, mid; // while (left <= right) // { // mid = right + (right - left) / 2; // if (a[mid] == x) // return mid; // if (x > a[mid]) // left = mid + 1; // else // right = mid - 1; // } // return -1; //} //int binary(int a[], int l, int r, int x) //{ // int mid; // if (r >= l) // mid = l + (r - l) / 2; // if (a[mid] == x) // return mid; // if (a[mid] > x) // return binary(a, l, mid - 1, x); // if (a[mid] < x) // return binary(a, mid + 1, r, x); // return -1; //} //int main() //{ // int n, choice, kq, b[MAX], x; // clock_t start; // double duration; // cout << "------- BAI TAP CHUONG 1, CHUONG 3, SAP XEP DANH SACH -------" << endl; // cout << "1.Khoi tao danh sach." << endl; // cout << "2.Xuat danh sach." << endl; // cout << "3.Danh sach tang theo InsertionSoft." << endl; // cout << "4.Danh sach tang theo SelectionSoft." << endl; // cout << "5.Danh sach tang theo InterchangSoft." << endl; // cout << "6.Danh sach tang theo BubbleSort." << endl; // cout << "7.Danh sach tang theo QuickSort." << endl; // cout << "8.Danh sach tang theo HeapSort." << endl; // cout << "9.Tim kiem phan tu theo tuan tu." << endl; // cout << "10.Tim kiem phan tu theo tim kiem nhi phan." << endl; // cout << "11.Danh sach tang theo QuickSort." << endl; // do { // cout << "Chon muc: "; // cin >> choice; // switch (choice) // { // case 1: // cout << "So phan tu trong danh sach: "; // cin >> n; // input(a, n); // break; // case 2: // cout << "Cac phan tu hien co trong danh sach:\n"; // output(a, n); // break; // case 3: // copy(a, b, n); // start = clock(); // InsertionSort(b, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian InsertionSort la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 4: // copy(a, b, n); // start = clock(); // SelectionSort(b, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian SelectionSort la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 5: // copy(a, b, n); // start = clock(); // InsertionSort(b, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian InsertionSort la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 6: // copy(a, b, n); // start = clock(); // BubbleSort(b, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 7: // copy(a, b, n); // start = clock(); // QuickSort(b, 0, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian QuickSort la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 8: // copy(a, b, n); // start = clock(); // HeapSort(b, n); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // cout << "Sau khi sap xep:\n"; // if (duration > 0) // cout << "Thoi gian HeapSort la: " << duration * 1000000 << " milisecond" << endl; // output(b, n); // break; // case 9: // cout << "Nhap so ban muon tim: "; // cin >> x; // start = clock(); // kq = search(a, n, x); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // if (kq == -1) // cout << "Khong tim thay!" << endl; // else // cout << "Tim thay tai vitri " << kq << endl; // break; // case 10: // cout << "Nhap so ban muon tim: "; // cin >> x; // start = clock(); // kq = search(a, n, x); // duration = (clock() - start) / (double)CLOCKS_PER_SEC; // if (kq == -1) // cout << "Khong tim thay!" << endl; // else // cout << "Tim thay tai vitri " << kq << endl; // break; // case 11: // cout << "Tam biet!" << endl; // break; // default: // cout << "Nhap sai, nhap lai!" << endl; // break; // } // } while (choice != 11); // system("pause"); // return 0; //}
true
6c6db65fd97da91be998be389c150752f9950039
C++
Fraszczak/_SpaceShooter
/Laser.cpp
UTF-8
281
2.53125
3
[]
no_license
#include "pch.h" #include "Laser.h" Laser::Laser(Animation &animation, float x, float y) : Entity::Entity(animation, x, y) { this->name = "Laser"; }; void Laser::update(sf::Time &t) { int laser_speed = 1; this->y -= laser_speed; if (this->y < 0) { this->life = false; } }
true
f3cefccd6f14a85e654120ad7d5b57e44963cd3a
C++
baoqingti/SmartPointer
/SmartPointer/main.cpp
GB18030
4,517
3.3125
3
[]
no_license
#include "SmartPointer_v1.h" #include "SmartPointer_v2.h" #include "SmartPointer_v3.h" #include "SmartPointer_v4.h" //Դ //v1,v2Ӧõ class SomeClass { public: SomeClass() {cout << "SomeClass default constructor" << endl;} ~SomeClass() {cout << "SomeClass destructor" << endl;} }; //v3Ӧõ class SomeClass3: public RefBase { public: SomeClass3() {cout << "SomeClass3 default constructor" << endl;} ~SomeClass3() {cout << "SomeClass3 destructor" << endl;} }; //v4Ӧõ class SomeClass4: public RefBase { public: SomeClass4() {cout << "SomeClass4 default constructor" << endl;} ~SomeClass4() {cout << "SomeClass4 destructor" << endl;} void func() {cout << "func() function" << endl;} }; class OtherClass4:public RefBase { public: OtherClass4() {cout << "OtherClass4 default constructor" << endl;} ~OtherClass4() {cout << "OtherClass4 destructor" << endl;} void foo() {cout << "foo() function" << endl;} }; void testcase1() { //һָָ֪룬ʹָĬϹ캯 SmartPointer_v1<char> spunknown; //һյָ SmartPointer_v1<char> spnull = nullptr; //һָָ SmartPointer_v1<SomeClass> spclass = new SomeClass; //ַָ SmartPointer_v1<const char> spstr = "Hello World"; } void testcase2() { // SmartPointer_v2<SomeClass> spclass1 = new SomeClass; cout << endl; spclass1 = spclass1; //Ըֵ cout << endl; // SmartPointer_v2<SomeClass> spclassother(spclass1); cout << endl; SmartPointer_v2<SomeClass> spclass2 = new SomeClass; cout << endl; cout << "ֵ" << endl; spclass2 = spclass1; //Կֵ cout << endl; } void testcase3() { cout << "۲testcase2ĽԱ,üʹpSomeClass3һΣ" << endl; SomeClass3 *pSomeClass3 = new SomeClass3(); cout << pSomeClass3->getRefCount() << endl; //ʱ0 SmartPointer_v3<SomeClass3> spOuter = pSomeClass3; cout << "SomeClass3 Ref Count (" << pSomeClass3->getRefCount() << ") outer 1" << endl; {//飬ΪһִеĶβΡ SmartPointer_v3<SomeClass3> spInner = spOuter; cout << "SomeClass Ref Count (" << pSomeClass3->getRefCount() << ") inner" << endl; } cout << "SomeClass Ref Count (" << pSomeClass3->getRefCount() << ") outer 2" << endl; cout << "new another SomeClass3 class for spOuter" << endl; SmartPointer_v3<SomeClass3> spOuter2 = new SomeClass3(); spOuter = spOuter2; //spOuterᱻͷ // } //Խ void testcase4_1() { SmartPointer_v4<SomeClass4> spcomeclass4 = new SomeClass4(); //Խ (*spcomeclass4).func(); spcomeclass4->func(); cout << endl; } //Чп void testcase4_2() { SomeClass4 *psomeclass4 = new SomeClass4(); SmartPointer_v4<SomeClass4> spsomeclass4 = psomeclass4; // SmartPointer_v4<OtherClass4> spotherclass4_1 = new OtherClass4(); SmartPointer_v4<OtherClass4> spotherclass4_2 = spotherclass4_1; if (spsomeclass4 == nullptr) cout << "spsomeclass4 is nullpter" << endl; if (spotherclass4_1 != nullptr) cout << "spotherclass4_1 is not nullptr" << endl; if (spsomeclass4 == psomeclass4) //ָָͨ cout << "spsomeclass4 and psomeclass4 are same pointer" << endl; if (spsomeclass4 != psomeclass4) cout << "spsomeclass4 and psomeclass are not same pointer" << endl; if (spotherclass4_1 == spotherclass4_2) //ָָ cout << "spotherclass4_1 and spotherclass4_2 are same pointer" << endl; if (spotherclass4_1 != spotherclass4_2) cout << "spotherclass4_1 and spotherclass4_2 are not same pointer" << endl; } int main() { cout << "***************testcase1*****************" << endl; testcase1(); cout << "***************testcase2:******************" << endl; testcase2(); cout << "***************testcase3:******************" << endl; testcase3(); cout << endl; cout << "***************testcase4_1:*****************" << endl; testcase4_1(); cout << "***************testcase4_2:******************" << endl; testcase4_2(); return 0; }
true
76a6c510e8e82ad175d7d322c497d577f33494b6
C++
VRavaglia/LingProg-2019-1-Trabalho
/Entidade.cpp
UTF-8
667
2.5625
3
[]
no_license
#include "Entidade.h" bool contemComponente(Componente componente, unsigned componentes){ if(componentes % componente == 0){ return true; } return false; } Entidade::Entidade(): velocidade (vec2<float>(0,0)){ } void Entidade::emForaDaTela() { } void Entidade::emColisao() { } void Entidade::addComponente(Componente componente) { componentes = componentes * componente; } void Entidade::removeComponente(Componente componente) { if (contemComponente(componente, componentes)){ componentes = componentes/componente; } } unsigned Entidade::getComponentes() { return componentes; } void Player::emColisao() { }
true
9b898f7890e3134ccd631d9b2e78fbff96397f43
C++
gerson1974/tripmaster
/screen.cpp
UTF-8
3,012
3.078125
3
[ "MIT" ]
permissive
#include "screen.h" Screen::Screen() : lcd(LiquidCrystal_I2C(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE)), printedTrip1Distance(0), printedTrip2Distance(0), printedTankDistance(0) { } void Screen::setupScreen() { lcd.begin(20, 4); lcd.setCursor(0,0); lcd.print("Crappy Tripmaster"); } void Screen::registerTripMaster(TripMaster* _tripMaster) { tripMaster = _tripMaster; } void Screen::updateScreenDirection() { bool up = false; bool down = false; if(tripMaster->currentDirection == forward) { up = true; } else if(tripMaster->currentDirection == backward) { down = true; } lcd.setCursor(0,0); up ? lcd.print("X") : lcd.print("."); lcd.setCursor(0,1); down ? lcd.print("X") : lcd.print("."); } void Screen::updateScreenTrips() { if(tripMaster->trip1->tripDistance - printedTrip1Distance > 0.1 || printedTrip1Distance - tripMaster->trip1->tripDistance > 0.1) { int printableTrip1_pre = (int) tripMaster->trip1->tripDistance; int printableTrip1_after = (int) ((tripMaster->trip1->tripDistance - printableTrip1_pre)*10); lcd.setCursor(0,2); lcd.print(printableTrip1_pre); lcd.setCursor(0,5); lcd.print("."); lcd.setCursor(0,6); lcd.print(printableTrip1_after); } if(tripMaster->trip2->tripDistance - printedTrip2Distance > 0.1 || printedTrip2Distance - tripMaster->trip2->tripDistance > 0.1) { int printableTrip2_pre = (int) tripMaster->trip2->tripDistance; int printableTrip2_after = (int) ((tripMaster->trip2->tripDistance - printableTrip2_pre)*10); lcd.setCursor(0,14); lcd.print(printableTrip2_pre); lcd.setCursor(0,17); lcd.print("."); lcd.setCursor(0,18); lcd.print(printableTrip2_after); } if(tripMaster->tank->tripDistance - printedTankDistance > 0.1 || printedTankDistance - tripMaster->tank->tripDistance > 0.1) { int printableTank_pre = (int) tripMaster->tank->tripDistance; int printableTank_after = (int) ((tripMaster->tank->tripDistance - printableTank_pre)*10); lcd.setCursor(3,8); lcd.print(printableTank_pre); lcd.setCursor(3,11); lcd.print("."); lcd.setCursor(3,12); lcd.print(printableTank_after); } } void Screen::updateTime() { //time_t t = now() //if(minute(t) == printedTime) //{ //} lcd.setCursor(3,14); lcd.print("HH"); lcd.setCursor(3,16); lcd.print(":"); lcd.setCursor(3,17); lcd.print("MM"); } void Screen::updateScreenShowTrip() { updateTime(); updateScreenTrips(); updateScreenDirection(); } void Screen::updateScreenShowMenu() { lcd.setCursor(0,0); lcd.print("THIS IS THE MENU"); lcd.setCursor(3,0); lcd.print("NOTHING MUCH BUT W/E") ; } void Screen::updateScreen(Event e) { switch(e) { case updatedirection: updateScreenDirection(); break; case updatetrip: updateScreenTrips(); break; case togglemenu: updateScreenShowMenu(); break; case initdone: //clearScreen(); updateScreenShowTrip(); break; default: ; } }
true
fc32b1ca2c884148270ecd558b50e75c99ad57a1
C++
HumMan/BaluScript
/Source/SemanticInterface/Internal/SStatements.cpp
UTF-8
5,109
2.609375
3
[]
no_license
#include "SStatements.h" #include "SLocalVar.h" #include "SMethod.h" #include "SExpression.h" #include "SBytecode.h" #include "SReturn.h" #include "SWhile.h" #include "SIf.h" #include "SFor.h" #include "SClass.h" class TSStatementBuilder :public SyntaxApi::IStatementVisitor { TSStatement* return_new_operation; TSClass* owner; TSMethod* method; TSStatements* parent; SemanticApi::TGlobalBuildContext build_context; public: TSStatement* GetResult() { return return_new_operation; } TSStatementBuilder(SemanticApi::TGlobalBuildContext build_context, TSClass* owner, TSMethod* method, TSStatements* parent) { this->owner = owner; this->method = method; this->parent = parent; this->build_context = build_context; } void Visit(SyntaxApi::IExpression* op) { TSExpression* new_node = new TSExpression(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::ILocalVar* op) { TSLocalVar* new_node = new TSLocalVar(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IReturn* op) { TSReturn* new_node = new TSReturn(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IStatements* op) { TSStatements* new_node = new TSStatements(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IBytecode* op) { TSBytecode* new_node = new TSBytecode(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IWhile* op) { TSWhile* new_node = new TSWhile(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IFor* op) { TSFor* new_node = new TSFor(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } void Visit(SyntaxApi::IIf* op) { TSIf* new_node = new TSIf(owner, method, parent, op); new_node->Build(build_context); return_new_operation = new_node; } }; TSStatements::TSStatements(TSClass* use_owner, TSMethod* use_method, TSStatements* use_parent, SyntaxApi::IStatements* use_syntax) :TSStatement(SyntaxApi::TStatementType::Statements, use_owner, use_method, use_parent, use_syntax) { } void TSStatements::AddVar(TSLocalVar* var, int stmt_id) { var_declarations.push_back(SemanticApi::TVarDecl(stmt_id, var)); //для статических локальных переменных смещение будет задано при инициализации всех статических переменных if (!var->IsStatic()) dynamic_cast<TSLocalVar*>(var_declarations.back().pointer)->SetOffset(GetLastVariableOffset());//на единицу не увеличиваем, т.к. переменная уже добавлена } int TSStatements::GetLastVariableOffset() { if (GetParentStatements() != nullptr) { return GetParentStatements()->GetLastVariableOffset() + var_declarations.size(); } else { return var_declarations.size() - 1; } } void TSStatements::Build(SemanticApi::TGlobalBuildContext build_context) { auto syntax = dynamic_cast<SyntaxApi::IStatements*>(GetSyntax()); for (size_t i = 0; i < syntax->GetStatementsCount(); i++) { SyntaxApi::IStatement* st = syntax->GetStatement(i); TSStatementBuilder b(build_context, GetOwner(), GetMethod(), this); st->Accept(&b); statements.push_back(std::unique_ptr<TSStatement>(b.GetResult())); } } std::vector<SemanticApi::ISStatement*> TSStatements::GetStatements() const { std::vector<SemanticApi::ISStatement*> result; result.reserve(statements.size()); for (auto& v : statements) result.push_back(v.get()); return result; } std::vector<SemanticApi::TVarDecl> TSStatements::GetVarDeclarations() const { return var_declarations; } void TSStatements::Accept(SemanticApi::ISStatementVisitor * visitor) { visitor->Visit(this); } SemanticApi::IVariable* TSStatements::GetVar(Lexer::TNameId name, int sender_id)const { for (size_t i = 0; i < var_declarations.size(); i++) { auto pointer = dynamic_cast<TSLocalVar*>(var_declarations[i].pointer); if (var_declarations[i].stmt_id <= sender_id &&pointer->GetName() == name) return pointer; } //for(int i=0;i<=statement.GetHigh();i++) // //TODO из-за этого перебора тормоза при большом количестве операторных скобок + невозможность искать локальную переменную за не линейную скорость //{ // if(except_this&&statement[i]==sender)break; // if(statement[i]->GetType()==TStatementType::VarDecl&&((TLocalVar*)(statement[i]))->GetName()==name) // return ((TLocalVar*)(statement[i])); // if(statement[i]==sender)break; //} if (GetParentStatements() != nullptr) return GetParentStatements()->GetVar(name, GetSyntax()->GetStmtId()); else if (GetMethod() != nullptr) return GetMethod()->GetVar(name); else return nullptr; }
true
540457daa6bf96d5b61f384e89ebc56cf94ac648
C++
PTMKUCCHi/GAME
/shooting/j1412口羽雅晴funnybullet.cpp
UTF-8
7,716
2.8125
3
[]
no_license
/*/////////////////////////////////////////////////////////// 今回は時間で制御して三つの弾幕の動きを作成した. 一つ目は,360度の方向に円形に一斉に発射する弾幕, 二つ目はソニックブームのように自機めがけて発射する弾幕 そして三つめが敵機から9方向に一直線上に連射される弾幕だ. 敵機の動きは円運動をさせたので,いろんなところから弾が飛びかっていて 実践的になったと感じた. 作ってみて実際のシューティングゲームのようにいろんな弾幕を作り出せたのでよかった. //////////////////////////////////////////////////////////*/ #include "DxLib.h" #define _USE_MATH_DEFINES #include <math.h> //ウィンドウサイズ #define MIN_X 0 #define MIN_Y 0 #define MAX_X 640 #define MAX_Y 480 //画面の中心座標 #define CENTER_X ((MIN_X + MAX_X)/2) #define CENTER_Y ((MIN_Y + MAX_Y)/2) //角度の計算(°→rad) #define OMEGA( t ) (t * M_PI / 180) //画面内に最大1000発の弾 #define MAX_BULLET 3000 //#define BLAST_FIG_NUM 16//爆発するアニメの画像数 //int BlastHandle[BLAST_FIG_NUM];//爆発画像ハンドル int t;//時間 int bullet_img;//弾の画像 //自機 struct Player { int x; int y; int img; double range;//当たり判定の半径 }; struct Player player; //敵 struct Enemy { int x;//座標 int y; int img;//画像 }; struct Enemy enemy; //個々の弾 struct Bullet { double x;//座標 double y; double speed; double angle; double range ;//当たり判定の半径 bool isExist;//存在したらtrue、いなかったらfalse int img;//画像 }; struct Bullet bullet[MAX_BULLET];//MAX_BULLET個のBullet //初期化 void Init() { int i; t=0;//時間初期化 //自機を適当な座標へ player.x = CENTER_X; player.y = CENTER_Y * 1.5 ; player.range = 5; //敵を適当な座標へ enemy.x=CENTER_X; enemy.y=CENTER_Y/2; //弾を全て初期化 for(i = 0; i < MAX_BULLET; i++) { bullet[i].isExist = false; bullet[i].x = 0; bullet[i].y = 0; bullet[i].speed = 0; bullet[i].angle = 0; bullet[i].range = 0; } } //画像・音ファイルを読み込む関数 void LoadData() { player.img = LoadGraph("player.png"); enemy.img = LoadGraph("enemy.png"); bullet_img = LoadGraph("bullet.png"); // LoadDivGraph( "bomb0.png", BLAST_FIG_NUM, 8, 2, 768/8, 192/2, BlastHandle );//爆発画像登録 640x480bomb0.png } //自機の移動 void MovePlayer() { const int speed = 4; if( CheckHitKey(KEY_INPUT_LEFT) ) player.x -= speed; if( CheckHitKey(KEY_INPUT_RIGHT) ) player.x += speed; if( CheckHitKey(KEY_INPUT_UP) ) player.y -= speed; if( CheckHitKey(KEY_INPUT_DOWN) ) player.y += speed; if( player.x < MIN_X ) player.x = MIN_X; else if( player.x > MAX_X ) player.x = MAX_X; if( player.y < MIN_Y ) player.y = MIN_Y; else if( player.y > MAX_Y) player.y = MAX_Y; } //自機の表示 void DrawPlayer() { DrawRotaGraphF( (float)player.x, (float)player.y, 1.0, 0, player.img, TRUE ) ; } //自機狙いの角度 double TargetAnglePlayer(double x, double y) { return atan2(player.y-y,player.x-x); } //弾幕の生成 //方向弾(x,y:発射地点, speed:速度, angle:角度) void MakeBullet(double x, double y, double speed, double angle, double range) { int i; for( i = 0; i < MAX_BULLET; i++) { //bullet[i]が使用されていなければパラメータ設定へ if( !bullet[i].isExist ) break; } if ( i == MAX_BULLET )//一つも空いてない return; bullet[i].isExist = true; //発射地点の座標 bullet[i].x = x; bullet[i].y = y; bullet[i].angle = angle;//発射角度 bullet[i].speed = speed;//速度 bullet[i].range = range; bullet[i].img = bullet_img;//画像の代入 } //弾の移動 void MoveBullet() { double x, y; double angle; int i; int r=100; //発射中の弾を全て調べる for(i = 0; i < MAX_BULLET; i++) { if( !bullet[i].isExist ) continue; x = bullet[i].x; y = bullet[i].y; angle = bullet[i].angle; //角度angle方向にspeed分進める x += bullet[i].speed * cos(angle); y += bullet[i].speed * sin(angle); //弾が画面外に出た場合、弾を消す if( x < MIN_X || x > MAX_X || y < MIN_Y || y > MAX_Y) bullet[i].isExist = false; bullet[i].x = x; bullet[i].y = y; } } void MakeWayBullet(double x, double y, double speed, int way, double wide_angle, double main_angle, double range) { int i; double w_angle; for( i = 0; i < way; i++) { w_angle = main_angle + i * wide_angle / ( way - 1 ) - wide_angle / 2; MakeBullet(x,y,speed,w_angle,range); } } //敵の行動 void ActionEnemy() { int direct=1; const int fire = 50; const double speed = 2.0; // const double wide_angle = OMEGA(360); const int way = 3; const double angle = OMEGA(90); const double angle2 = TargetAnglePlayer(enemy.x,enemy.y);//自機を追いかける const double range = 4; const int r=150; int i; //敵の動き /*enemy.x = player.x+r*cos(OMEGA(t)); enemy.y = player.y+r*sin(OMEGA(t));*/ enemy.x = CENTER_X+r*cos(OMEGA(t)); enemy.y = CENTER_Y+r*sin(OMEGA(t)); if(t<=1200){ //fire回のループごとに弾を発射 if( t % fire == 0 ){ for(i=0;i<360;i+=10){ MakeBullet(enemy.x, enemy.y, speed*1, OMEGA(i), range); } //MakeWayBullet(enemy.x, enemy.y, speed, way, OMEGA(90), angle, range); } } if(t>1200&&t<=2400){ if( t % fire == 0 ){ MakeWayBullet(enemy.x, enemy.y, speed*2, way*7, OMEGA(120), angle2, range); } } if(t>2400&&t<=3600){ if(t%(fire/5)==0){ //MakeBullet(enemy.x, enemy.y, speed*4, angle, range); MakeWayBullet(enemy.x, enemy.y, speed*2, way*3, OMEGA(360), angle, range); } } } //弾の表示 void DrawBullet() { double x,y,angle; int img; int i; //発射中の弾を全て調べる for(i = 0; i < MAX_BULLET; i++) { if( !bullet[i].isExist ) continue; x = bullet[i].x ; y = bullet[i].y ; angle = bullet[i].angle ; img = bullet[i].img ; //弾の表示 DrawRotaGraphF( (float)x, (float)y, 1.0, angle, img, TRUE ) ; } } //敵の表示 void DrawEnemy() { DrawRotaGraph( enemy.x, enemy.y, 1.0, 0.0, enemy.img, TRUE ) ; } int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { // タイトルを 変更 SetMainWindowText( "3種類の方向弾" ) ; // ウインドウモードに変更 ChangeWindowMode( TRUE ) ; // DXライブラリ初期化処理 if( DxLib_Init() == -1 ) // DXライブラリ初期化処理 return -1 ; // エラーが起きたら直ちに終了 // 描画先画面を裏にする SetDrawScreen(DX_SCREEN_BACK); LoadData(); Init(); //メインループ Escキーで終了 while(!ProcessMessage() && !CheckHitKey(KEY_INPUT_ESCAPE)) { ClearDrawScreen(); //自機の移動 MovePlayer(); //敵の行動 ActionEnemy(); //弾の移動 MoveBullet(); //敵の表示 DrawEnemy(); //自機の表示 DrawPlayer(); //弾の表示 DrawBullet(); t++;//時間を進める if(t>3600) t=0; // 裏画面の内容を表画面に反映 ScreenFlip(); } return 0; }
true
c4fa115f9e3cfcecf15ea58de6e5a7f9d67907ec
C++
at0x0ft/Lec.2018.ProgrammingC.CompetitiveProgrammingPart
/8/8.cpp
UTF-8
1,367
3.125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void cReadLn(int &n) { scanf("%d", &n); } void cReadLn(std::vector<int> &v) { int n = v.size(); for (int i = 0; i < n; i++) scanf("%d", &v[i]); } bool binSearch(const vector<int> &s, const int val) { int high = 0, low = s.size() - 1; if (low < 0) return false; while (low >= high) { int mid = (low + high) / 2; if (s[mid] == val) { return true; } else if (s[mid] < val) { low = mid - 1; } else { high = mid + 1; } } return false; } void refine(const vector<int> &s, vector<int> &t) { int slen = s.size(); for (int j = 0; j < t.size(); j++) { if (binSearch(s, t[j])) t.erase(t.begin() + j); } } void cPrintLn(const std::vector<int> &v, char delimiter = ' ') { int n = v.size(); for (int i = 0; i < n; i++) { std::cout << v[i]; if (i != n - 1) printf("%c", delimiter); } printf("\n"); } void cPrintLn(const int &a) { printf("%d\n", a); } int main() { int n; cReadLn(n); vector<int> s(n); cReadLn(s); int q; cReadLn(q); vector<int> t(q); cReadLn(t); refine(s, t); cPrintLn(t); cPrintLn(t.size()); return 0; }
true
080689f2b086a321ea053f5032d2780ab189f4e1
C++
SabaaKiwan/vaSheet03
/ActionRecognition/Utils.cc
UTF-8
1,370
2.859375
3
[]
no_license
/* * Utils.cpp * * Created on: May 10, 2017 * Author: ahsan */ #include "Utils.hh" void Utils::readVideo(const std::string& filename, std::vector<cv::Mat>& result) { // open video file cv::VideoCapture capture(filename); if(!capture.isOpened()) Core::Error::msg() << "Unable to open Video: " << filename << Core::Error::abort; cv::Mat frame, tmp; result.clear(); // read all frames u32 nFrames = capture.get(CV_CAP_PROP_FRAME_COUNT); while ((nFrames > 0) && (capture.read(frame))) { if (frame.channels() == 3) cv::cvtColor(frame, tmp, CV_BGR2GRAY); else tmp = frame; result.push_back(cv::Mat()); tmp.convertTo(result.back(), CV_32FC1); //result.push_back(tmp); nFrames--; } capture.release(); } void Utils::matrixToCVMat(const Math::Matrix<f32>& matrix, cv::Mat& cvMat, bool transpose) { u32 I = transpose ? matrix.nColumns() : matrix.nRows(); u32 J = transpose ? matrix.nRows() : matrix.nColumns(); for (u32 i=0; i<I; i++) { f32* row = cvMat.ptr<f32>(i); for (u32 j=0; j<J; j++) { if (transpose) row[j] = matrix.at(j, i); else row[j] = matrix.at(i, j); } } } void Utils::cvMatToMatrix(const cv::Mat& cvMat, Math::Matrix<f32>& matrix) { for (u32 i=0; i<(u32)cvMat.rows; i++) { const f32* row = cvMat.ptr<f32>(i); for (u32 j=0; j<(u32)cvMat.cols; j++) { matrix.at(i, j) = row[j]; } } }
true
07562707eec5265f8d53f1614718d094ba120754
C++
UzzielSW/Curso-de-Cplus
/Modulos de C++/Bloque 2.4 - Funciones/Ejercicio 3 - elevacion de un numero.cpp
UTF-8
759
3.75
4
[]
no_license
/*Ejercicio 3: Escriba una funci�n nombrada funpot() que eleve un n�mero entero que se le transmita a una potencia en n�mero entero positivo y despliegue el resultado. El n�mero entero positivo deber� ser el segundo valor transmitido a la funci�n.*/ #include<iostream> using namespace std; void pedirDatos(); void funpot(int x, int y); int numero, exponente; int main() { pedirDatos(); funpot(numero, exponente); getchar(); return 0; } void pedirDatos() { cout<<"Digite el numero a elevar: "; cin>>numero; cout<<"Digite el exponetente de elevacion: "; cin>>exponente; } void funpot(int x, int y) { long resultado = 1; for(int i=1; i <= y; i++) resultado *= x; cout<<"El resultado de la elevacion es: "<<resultado<<endl; }
true
2523b3529db774aef359fd7a22279bf57e745d68
C++
gkourtis/napl22
/naplCharTraits.cpp
UTF-8
1,781
2.984375
3
[]
no_license
class char_traits_Char : public std::char_traits<Char> { public: // typedef Char char_type; typedef uWord size_type; typedef int32_t int_type; typedef Char* pointer; typedef const Char* const_pointer; typedef Char& reference; typedef const Char& const_reference; //static size_type length(){return size();} //static int_type eof(){return int_type(-1);}; /* static constexpr char_type to_char_type (int_type a) noexcept { // The int is given by conversion routines that interpret the external codification of characters // e.g. it could be utf8 or iso8859-7 or any multibyte codification. // Being a int32_t covers al cases contemplated by unicod actually. // Depending on our internal type we may be able or not to express that character. // if the internal type is char8_t only 64 characters are possible. // if the internal type is char16_t then only 2^14 characters are possible. // if the internal type is char32_t then all characters are possible. // if the internal type is char64_t then all characters are possible. return a==0 ? 0 :(a!=(a&WordMask) ? Char(0x3F) : a )|CharMasked; } */ static void assign(char_type& r,const char_type& a){ r=a; } static void assign(char_type* p0,size_t n, char_type c){ for(char_type* p=p0;p<p0+n;p++) assign(*p++,c); } /* static char_type* copy(char_type* dest, const char_type* src, size_t n){ return (char_type*)memcpy(dest,src,sizeof(char_type[n])); } */ static constexpr int_type to_int_type(char_type c) noexcept { return c; //&WordMask; } }; typedef std::basic_string< Char,char_traits_Char,Allocator<Char>> SString; typedef std::basic_ifstream<Char,char_traits_Char> ifStream; typedef std::basic_ofstream<Char,char_traits_Char> ofStream; typedef std::basic_fstream<Char,char_traits_Char> fStream;
true
1c98b7f984f406c8e5e75e519683adb2e3193408
C++
kubonits/atcoder
/abc/100/130/abc139/abc139-f.cpp
UTF-8
688
2.5625
3
[]
no_license
#include<cstdio> #include<algorithm> #include<cstring> #include<vector> #include<queue> #include<deque> #include<cmath> using namespace std; int main(){ int n; double x[100],y[100],dis,ans=0.0,xx,yy,a,b; const double PI=3.14159265358979323846; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%lf%lf",&x[i],&y[i]); } for(double i=0;i<100000.0;i++){ xx=yy=0.0; a=cos(PI*i/1000.0); b=sin(PI*i/1000.0); for(int j=0;j<n;j++){ if(a*x[j]+b*y[j]>=0){ xx+=x[j]; yy+=y[j]; } } dis=xx*xx+yy*yy; ans=max(ans,sqrt(dis)); } printf("%.12f\n",ans); }
true
96fb7c891a3365af3ee149659ec9409871be6d48
C++
GunnerLab/Develop-MCCE
/yingying_delphi/Delphicpp_v8.4.2_Linux/src/dplt/ddm/view/Global.h
UTF-8
767
2.6875
3
[ "MIT" ]
permissive
#ifndef DDM__VIEW__GLOBAL_H__INCLUDED #define DDM__VIEW__GLOBAL_H__INCLUDED #include "../../ddm/view/ViewTraits.h" namespace ddm { /** * \concept{DDMViewConcept} */ template <class ViewType> constexpr typename std::enable_if< ddm::view_traits<ViewType>::is_view::value && ddm::view_traits<ViewType>::is_local::value, const typename ViewType::global_type & >::type global(const ViewType & v) { return v.global(); } /** * \concept{DDMViewConcept} */ template <class ContainerType> constexpr typename std::enable_if< !ddm::view_traits<ContainerType>::is_view::value || !ddm::view_traits<ContainerType>::is_local::value, ContainerType & >::type global(ContainerType & c) { return c; } } // namespace ddm #endif // DDM__VIEW__GLOBAL_H__INCLUDED
true
070073e867d62abb33cf8b3ab32db364c988cd1e
C++
Huasheng-hou/AOAPC-I
/AOAPC-I/Chapter 2. Mathematics/Counting/uva11529.cpp
UTF-8
1,830
2.59375
3
[]
no_license
// // uva11529.cpp // AOAPC-I // // Created by apple on 2019/8/16. // Copyright © 2019 huasheng. All rights reserved. // #include <iostream> #include <algorithm> #include <vector> #include <math.h> #include <string.h> // Strange tax, 点在三角形内, Accepted! 0.710s using namespace std; const int maxn = 1210; int n, kase = 0; double x[maxn], y[maxn]; long double r[maxn]; long count(int k) { vector<long double> angle; for (int i = 0; i < n; i++) { if (i == k) continue; angle.push_back(atan2l(y[i]-y[k], x[i]-x[k])); } sort(angle.begin(), angle.end()); int m = n-1; long long c = 0; int j = 1; for (int i = 0; i < m; i++) { while (j <= m-1) { long double p1 = angle[(i+j)%m]; long double p2 = angle[i]; long double cross = p1-p2; if (cross < 0) cross += 2*M_PI; if (cross > M_PI) { j--; break; } j++; } if (j > m-1) j--; c += (j)*(j-1)/2; j--; } return c; } void solve() { long double num = 0; for (int i = 0; i < n; i++) { num += count(i); } num = (unsigned long long)(n-3) * n * (n-1) / 2 * (n-2) / 3 - num; long double ans = num / n * 6 / (n-1) / (n-2); char out[100]; sprintf(out, "City %d: %.2Lf\n", kase, ans); cout << out; } int main() { freopen("/Users/apple/Develop/AOAPC-I/AOAPC-I/Inputs/input","r",stdin); remove("/Users/apple/Develop/AOAPC-I/AOAPC-I/Inputs/output"); freopen("/Users/apple/Develop/AOAPC-I/AOAPC-I/Inputs/output","w",stdout); while (cin >> n && n > 0) { kase++; for (int i = 0; i < n; i++) { cin >> x[i] >> y[i]; } solve(); } return 0; }
true
cebf27d98836c3d53c164c6eeb62425518cc3b3f
C++
suyash0103/Competitive-Coding
/Practice Comp code/maxSumContSubarray.cpp
UTF-8
620
2.65625
3
[]
no_license
int Solution::maxSubArray(const vector<int> &A) { int max = 0; int maxFinal = 0; int flag = 0; for(int i = 0; i < A.size(); i++) { if(A[i] > 0) { flag = 1; break; } } if(flag == 0) { int min = A[0]; for(int i = 1; i < A.size(); i++) { if(A[i] > min) min = A[i]; } return min; } for(int i = 0; i < A.size(); i++) { max += A[i]; if(max < 0) max = 0; if(maxFinal < max) maxFinal = max; } return maxFinal; }
true
9e430d6950713758f7b411e2321cfec5fcdbd5ce
C++
complabs/mpi-labs
/lab2/pi-nb.cpp
UTF-8
3,381
3.296875
3
[]
no_license
/** Calculate pi # Lab 2 Exercise 3: Find pi using non-blocking communications Use a non-blocking send to try to overlap communication and computation. Take the code from Exercise 1 as your starting point. */ #include <iostream> #include <iomanip> #include <random> #include <mpi.h> static inline double sqr( double x ) { return x * x; } static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0,1.0); static double dboard( int darts ) { // Throw darts at the board // unsigned long score = 0; for( int n = 1; n <= darts; ++n ) { // Generate random numbers for x and y coordinates // double x_coord = 2.0 * distribution(generator) - 1.0; double y_coord = 2.0 * distribution(generator) - 1.0; // If dart lands in circle, increment score // if( sqr(x_coord) + sqr(y_coord) <= 1.0 ) { ++score; } } return 4.0 * double(score) / darts; } int main( int argc, char** argv ) { /** Number of throws at dartboard */ int DARTS = argc >= 2 ? atoi( argv[1] ) : 50000; /** Number of times "darts" is iterated */ int ROUNDS = argc >= 10 ? atoi( argv[1] ) : 10; // Setup MPI // MPI_Init( &argc, &argv ); int myrank, worldsz; MPI_Comm_rank( MPI_COMM_WORLD, &myrank ); MPI_Comm_size( MPI_COMM_WORLD, &worldsz ); std::cout << "MPI task " << myrank << " has started..." << std::endl; if( myrank == 0 ) { std::cout << "Using " << worldsz << " tasks to compute pi" << std::endl; } generator.seed( myrank ); double avg_pi = 0; for( int i = 0; i < ROUNDS; ++i ) { double my_pi = dboard( DARTS ); if( myrank != 0 ) // Slave { MPI_Request request; int rc = MPI_Isend( &my_pi, 1, MPI_DOUBLE, 0, i, MPI_COMM_WORLD, &request ); if( rc != MPI_SUCCESS ) { std::cerr << myrank << ": ISend failed; round = " << i << std::endl; } if( i >= ROUNDS - 1 ) // Wait at the last round { MPI_Status status; MPI_Wait( &request, &status ); } } else // Master { // Get sum ov pi from the slaves // double slave_pi_sum = 0; for( int n = 1; n < worldsz; ++n ) { MPI_Status status; double recv_pi = 0; int rc = MPI_Recv( &recv_pi, 1, MPI_DOUBLE, MPI_ANY_SOURCE, i, MPI_COMM_WORLD, &status); if( rc != MPI_SUCCESS ) { std::cerr << myrank << ": Receive failed, round = " << i << std::endl; } slave_pi_sum += recv_pi; } // Update the average pi // double pi = ( slave_pi_sum + my_pi ) / worldsz; avg_pi = ( avg_pi * i + pi ) / ( i + 1 ); std::cout << DARTS * ( i + 1 ) << " throws, average pi = " << std::setprecision(14) << avg_pi << std::endl; } } MPI_Barrier( MPI_COMM_WORLD ); MPI_Finalize (); return 0; }
true
902a4ca133edb504b0ae9e67a3edef379a89e7b5
C++
NefarioDr/sample-code
/cpp/snippets/join_vector.cpp
UTF-8
541
3.109375
3
[]
no_license
#include <algorithm> #include <experimental/iterator> #include <iostream> #include <vector> #include <sstream> /** * the std::experimental is defined from c++14, so you must specific your compiler with '-std=c++14', * or it will throw an error: no member named 'experimental' in namespace 'std'. */ int main() { std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8}; std::stringstream ss; std::copy(v.begin(), v.end(), std::experimental::make_ostream_joiner(ss, ", ")); std::cout << ss.str() << std::endl; return 0; }
true
6e9eae74b00fca5bea437b636288d48459c45234
C++
savvynavi/Intro-to-cpp
/dynamic arrays/dynamic array question 2/dynamic array question 2/main.cpp
UTF-8
781
3.875
4
[]
no_license
#include<iostream> using namespace std; //create dynamic 2d array, print it, delete it int main(){ int width = 5; int height = 5; //creating the array, inner ones need to be made in a loop int **arr1 = new int *[height]; for(int i = 0; i < height; i++){ *(arr1 + i) = new int[width]; } //filling the array with junk (array[i][k] the same as *(*(array + i) + k)) for(int i = 0; i < height; i++){ for(int k = 0; k < width; k++){ *(*(arr1 + i) + k) = i + k + 6; } } for(int i = 0; i < height; i++){ for(int k = 0; k < width; k++){ cout << *(*(arr1 + i) + k) << " "; } cout << endl; } //deleting the sub arrays first, then the main outer one for(int i = 0; i < height; i++){ delete[]*(arr1 + i); } delete[] arr1; system("pause"); return 0; }
true
202a1f54b025b46daeb71b5bc571acd4b4396c6f
C++
LJBCPH/comp_fin_exam_1
/exam_1/Vasicek.cpp
UTF-8
1,864
2.71875
3
[]
no_license
#include "Vasicek.h" #include "RungeKutta.h" #include <cmath> #include <vector> #include <iostream> Vasicek::Vasicek(const double r_input, const double kappa_input, const double theta_input, const double sigma_input, const double step_length_input) :r(r_input), kappa(kappa_input), theta(theta_input), sigma(sigma_input), step_length(step_length_input) { T = 1; } std::vector<std::vector<double>> Vasicek::solveODE(const double T_) { std::vector<std::vector<double>> solODE(T_, std::vector<double>(2, 0)); //vector of dim Tx2 int j = 0; const double step_length_ = step_length; const double kappa_ = kappa; const double theta_ = theta; const double sigma_ = sigma; double z = 0; double y = 0; double k1, k2, k3, k4, l1, l2, l3, l4; for (int i = 0; i < T_ / step_length_; i++) { k1 = -step_length_ * BFunctionVasicek(kappa_, z); l1 = -step_length_ * AFunctionVasicek(kappa_, theta_, z, sigma_); k2 = -step_length_ * BFunctionVasicek(kappa_, z + 0.5 * k1); l2 = -step_length_ * AFunctionVasicek(kappa_, theta_, z + 0.5 * k1, sigma_); k3 = -step_length_ * BFunctionVasicek(kappa_, z + 0.5 * k2); l3 = -step_length_ * AFunctionVasicek(kappa_, theta_, z + 0.5 * k2, sigma_); k4 = -step_length_ * BFunctionVasicek(kappa_, z + k3); l4 = -step_length_ * AFunctionVasicek(kappa_, theta_, z + k3, sigma_); z = z + (k1 + 2 * k2 + 2 * k3 + k4) / 6; y = y + (l1 + 2 * l2 + 2 * l3 + l4) / 6; if (i == (j + 1.0) / step_length - 1) { solODE[j][0] = y; solODE[j][1] = z; j += 1; } } return sol = solODE; } std::vector<double> Vasicek::getODE(const double T_) { std::vector<double> solVector(2); solVector[0] = sol[T_-1][0]; solVector[1] = sol[T_-1][1]; return solVector; }
true
cb24c65bda7cbca3744aee0f314962d9bd2bc9d2
C++
OpenSuede/Suede
/server/src/http_response.cpp
UTF-8
3,420
2.6875
3
[ "MIT" ]
permissive
#include <openssl/sha.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/buffer.h> #include <http_response.hpp> #include <http_request.hpp> #include <stdlib.h> #include <cstring> #include <string> using std::string; /** * Getter for statusCode * @return response status code as a string */ const string& HTTP_Response::getStatusCode() const { return statusCode; } /** * Setter for statusCode * @param response status code as a string * @return void */ void HTTP_Response::setStatusCode(const string& code) { statusCode = code; } //Sort of based on solution from stack overflow, may need rewrite as it seems to have memory leak in valgrind void HTTP_Response::base64(unsigned char const* input, int length, char** buffer) { if ( (input != NULL) && (input[0] == (char)0) ) { *buffer = (char*)""; } else { BIO *bmem, *b64; BUF_MEM *bptr; b64 = BIO_new(BIO_f_base64());//This seems to be the source of some memory leaks that need to be resolved bmem = BIO_new(BIO_s_mem()); b64 = BIO_push(b64, bmem); BIO_write(b64, input, length); BIO_flush(b64); BIO_get_mem_ptr(b64, &bptr); *buffer = new char[bptr->length]; memcpy(*buffer, bptr->data, bptr->length); (*buffer)[bptr->length - 1] = 0; BIO_free_all(b64); // This should stop the memory leak } } string HTTP_Response::generateWebSocketAcceptVal(const string& clientKey) { unsigned char hashResult[20]; char *outBuffer = NULL; string localKeyCopy(clientKey.c_str()); string guid("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); string combined = clientKey + guid; SHA1((const unsigned char*) combined.c_str(), combined.size(), hashResult); base64(hashResult, 20, &outBuffer); string finalString(outBuffer); delete[] outBuffer; return finalString; } /** * This is a factory method that constructs HTTP_Response a * provided HTTP_Request request. * @param request pointer to HTTP_Request for which the response is created for * @return response A HTTP_Response constructed from the binary buffer contents */ HTTP_Response* HTTP_Response::buildResponseToRequest(const HTTP_Request *request) { HTTP_Response *response = new HTTP_Response(); if(!request->isValid()) { response->setStatusCode("400"); //TODO: Add explanation of failure to body (custom reason-phrase) return response; } string clientKey = request->getWebSocketKeyFieldValue(); string generatedKey = generateWebSocketAcceptVal(clientKey); //TODO: don't use setResponseString, build a real HTTP_Response object that can be used for other things //response->setResponseString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "+ generatedKey +"\r\nSec-WebSocket-Protocol: chat\r\n\r\n"); response->setResponseString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "+ generatedKey +"\r\n\r\n"); return response; } //temporary for emulating toString construction void HTTP_Response::setResponseString(const string& testIn) //temporary { responseString = testIn; } /** * toString Method generates text http response. * @return responseString String that is a text version of the http request, * fully prepared for transmission */ const string& HTTP_Response::toString() const { //TODO: make this a proper string construction return responseString; }
true
3bf7f26ba01a0fe70d02dd15cdf3f678e3c7de31
C++
DELTA-FORCE-CTF/Zeus_cpp
/src/util/Util.h
UTF-8
1,377
2.8125
3
[]
no_license
// // Created by aurailus on 28/04/19. // #ifndef ZEUS_UTIL_H #define ZEUS_UTIL_H #include <string> #include <sstream> #include <vec3.hpp> namespace Util { static std::string floatToString(float val) { std::ostringstream out; out.precision(2); out << std::fixed << val; return out.str(); } inline static std::string doubleToString(double val) { return floatToString((float)val); } static std::string vecToString(glm::vec3 vec) { std::ostringstream out; out << (int)vec.x << ", " << (int)vec.y << ", " << (int)vec.z; return out.str(); } static std::string floatVecToString(glm::vec3 vec) { std::ostringstream out; out.precision(2); out << std::fixed << vec.x << ", " << std::fixed << vec.y << ", " << std::fixed << vec.z; return out.str(); } inline static float packFloat(const glm::vec3& vec) { auto charX = static_cast<unsigned char>((vec.x + 1.0f) * 0.5f * 255.f); auto charY = static_cast<unsigned char>((vec.y + 1.0f) * 0.5f * 255.f); auto charZ = static_cast<unsigned char>((vec.z + 1.0f) * 0.5f * 255.f); unsigned int packedInt = (charX << 16) | (charY << 8) | charZ; return static_cast<float>(static_cast<double>(packedInt) / static_cast<double>(1 << 24)); } }; #endif //ZEUS_UTIL_H
true
cf069001ccf97cbc734f62c0369e23748f0c81f7
C++
stsewd/schedules_manager
/materias.cpp
UTF-8
3,869
2.78125
3
[ "MIT" ]
permissive
#include <string> #include <fstream> #include <iostream> #include <vector> #include <regex> #include <sstream> #include "materias.h" #include "docentes.h" #include "estudiantes.h" void Materias::set_docentes_file(std::string path) { docentes.set_docentes_file(path); } void Materias::set_materias_file(std::string path) { csv_materias.set_file(path); } void Materias::set_errorlog(Log* log) { errorlog = log; } void Materias::join_materias_docentes() { // int num_docentes = 0; init_streams(); std::string line; std::vector<std::string> materia_record; while ((line = csv_materias.next_record()) != "") { materia_record = parser_record(line); if (materia_record.empty()) { errorlog->write("Formato no correcto. Data: " + line + "\n"); continue; } auto docente_record = docentes.search_id(materia_record[2]); if (docente_record.empty()) { errorlog->write("Id no válido o no encontrado. Data: " + materia_record[2] + "\n"); continue; } if (!existe_docente(docente_record[0])) flujo_salida_docentes << docente_record[0] << "," << docente_record[1] << std::endl; flujo_salida_materias << materia_record[0] << "," << materia_record[1] << "," << docente_record[0] << std::endl; } } void Materias::init_streams() { flujo_salida_materias.open(MATERIAS_PATH); addcabecera_materias(); flujo_salida_docentes.open(DOCENTES_PATH); addcabecera_docentes(); } void Materias::addcabecera_docentes() { flujo_salida_docentes << "cedula" << "," << "nombre" << std::endl; } void Materias::addcabecera_materias() { flujo_salida_materias << "nombre" << "," << "horas" << "," << "profesor" << std::endl; } bool Materias::existe_docente(std::string docente_id) { std::ifstream docentes_new; char line[1000] = ""; docentes_new.open(DOCENTES_PATH); docentes_new.getline(line, sizeof(line)); // Leer cabecera while (!docentes_new.eof()) { docentes_new.getline(line, sizeof(line)); std::string str = line; if (str.find(docente_id) != std::string::npos) { docentes_new.close(); return true; } } docentes_new.close(); return false; } void Materias::finish() { flujo_salida_docentes.close(); flujo_salida_materias.close(); csv_materias.close(); docentes.finish(); } std::vector<std::string> Materias::parser_record(std::string record) { std::vector<std::string> records; std::regex regex_materia("^([^,]*),(\\d),(\\d{10})$"); std::smatch groups; if (!std::regex_match(record, groups, regex_materia)) return records; for (int i = 1; i < 4; i++) records.push_back(groups[i]); return records; } std::vector<std::string> Materias::parser_record_inner(std::string record) { std::vector<std::string> records; std::regex regex_materia("^([^,]*),(\\d),(\\d*)$"); std::smatch groups; if (!std::regex_match(record, groups, regex_materia)) return records; for (int i = 1; i < 4; i++) records.push_back(groups[i]); return records; } void Materias::initsearch() { csv_materias_entrada.set_file(MATERIAS_PATH); csv_materias_entrada.init(); } void Materias::finishsearch() { csv_materias_entrada.close(); } std::vector<std::string> Materias::next_materia(int minhours, int maxhours) { std::string line; std::vector<std::string> materia_record; while ((line = csv_materias_entrada.next_record()) != "") { materia_record = parser_record_inner(line); std::istringstream iss(materia_record[1]); int hours; iss >> hours; if (hours >= minhours && hours <= maxhours) return materia_record; } return {}; }
true
0037fd455a5b4b477410a756d5447375352764d8
C++
itiievskyi/42-CPP-Pool
/day04/ex02/TacticalMarine.cpp
UTF-8
1,768
2.6875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* TacticalMarine.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itiievsk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/05 16:06:03 by itiievsk #+# #+# */ /* Updated: 2018/10/05 16:06:04 by itiievsk ### ########.fr */ /* */ /* ************************************************************************** */ #include "TacticalMarine.hpp" TacticalMarine::TacticalMarine(void) { std::cout << "Tactical Marine ready for battle" << std::endl; return; } TacticalMarine::TacticalMarine(TacticalMarine const &src) { *this = src; return; } TacticalMarine &TacticalMarine::operator=(TacticalMarine const &src) { (void)src; return *this; } TacticalMarine::~TacticalMarine(void) { std::cout << "Aaargh ..." << std::endl; return; } ISpaceMarine *TacticalMarine::clone() const { TacticalMarine *unit = new TacticalMarine(*this); return unit; } void TacticalMarine::battleCry() const { std::cout << "For the holy PLOT !" << std::endl; return; } void TacticalMarine::rangedAttack() const { std::cout << "* attacks with bolter *" << std::endl; return; } void TacticalMarine::meleeAttack() const { std::cout << "* attacks with chainsword *" << std::endl; return; }
true
9a7fa9f24a24be01c1981fb580f7f9acff43362f
C++
sicojuy/leetcode
/contest/914.cpp
UTF-8
684
2.75
3
[]
no_license
#include <vector> using namespace std; class Solution { public: int gcd(int a, int b) { int t; while (b != 0) { t = b; b = a % b; a = t; } return a; } bool hasGroupsSizeX(vector<int>& deck) { int m[10000] = {0}; int x = 0; for (int i = 0; i < deck.size(); i++) { m[deck[i]]++; } for (int i = 0; i < 10000; i++) { if (m[i] == 0) continue; if (x == 0) { x = m[i]; continue; } x = gcd(m[i], x); if (x < 2) return false; } return x > 1; } };
true
097393f2d47729df212f8d3fef45869bab3eca35
C++
aman955/Competitive-Coding
/Before Novemeber 2017/Codechef/Easy/ADTRI2.cpp
UTF-8
750
2.703125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; bool isprime[5000010]; bool ishypotenus[5000010]; vector<int> prime; int lim=5000000; void process() { memset(isprime,true,sizeof(isprime)); isprime[0]=false;isprime[1]=false; isprime[2]=true; int i,j; for(i=2;i*i<=lim;i++) { if(isprime[i]) { for(j=i*i;j<=lim;j+=i) { isprime[j]=false; } } } for(i=2;i<=lim;i++) { if(isprime[i]&&(i%4)==1)prime.push_back(i); } int p; for(i=0;i<prime.size();i++) { p=prime[i]; for(j=p;j<=lim;j+=p)ishypotenus[j]=true; } } int main() { process(); int t; cin>>t; while(t--) { int n; cin>>n; if(ishypotenus[n])cout<<"YES"<<endl; else cout<<"NO"<<endl; } }
true
265ef5ec5b0dffbaed499fd227152830c05d397c
C++
jiffylubeyou/CS-236-Labs
/Lab 1 Datalog Scanner CS 236/Relation.h
UTF-8
2,505
3.09375
3
[]
no_license
#ifndef RELATION_H #define RELATION_H #include <set> #include<sstream> #include"Tuple.h" #include"Scheme.h" #include"Predicate.h" using namespace std; class Relation { public: Relation(string name, Predicate scheme) { this->name = name; this->scheme = scheme; }; ~Relation(); void addTuple(Tuple tuple) { tuples.insert(tuple); } string addRuleTuple(Tuple tuple) { ostringstream out; if (tuples.insert(tuple).second) { tuples.insert(tuple); out << " "; for (unsigned int i = 0; i < this->scheme.size(); ++i) { out << " " << this->scheme.at(i) << "=" << tuple.at(i); if (i != tuple.size() - 1) { out << ","; } } if (tuple.size() != 0) { out << endl; } else { return ""; } } return out.str(); } Relation select(string value, int index) { Relation tempRelation(this->name, this->scheme); for (Tuple tuple : tuples) { if (tuple.at(index) == value) { tempRelation.addTuple(tuple); } } return tempRelation; } Relation select(int index1, int index2) { Relation tempRelation(this->name, this->scheme); for (Tuple tuple : tuples) { if (tuple.at(index1) == tuple.at(index2)) { tempRelation.addTuple(tuple); } } return tempRelation; } Relation project(vector<int> toKeep) { Relation tempRelation(this->name, this->scheme); for (Tuple tuple : tuples) { Tuple tempTuple; for (unsigned int i = 0; i < toKeep.size(); ++i) { tempTuple.push_back(tuple.at(toKeep.at(i))); } tempRelation.addTuple(tempTuple); } return tempRelation; } Relation projectHeadPredicate(Predicate predicate); Relation rename(Predicate predicate) { Relation tempRelation(name, predicate); tempRelation.tuples = this->tuples; return tempRelation; } Predicate getScheme() { return this->scheme; } set<Tuple> getTuples() { return tuples; } int getNumTuples() { return tuples.size(); } string toString() { ostringstream out; for (Tuple tuple : tuples) { out << " "; for (unsigned int i = 0; i < scheme.size(); ++i) { out << " " << scheme.at(i) << "=" << tuple.at(i); if (i != tuple.size() - 1) { out << ","; } } if (tuple.size() != 0) { out << endl; } else { return ""; } } return out.str(); } Relation join(Relation relation); bool isJoinable(Predicate scheme1, Predicate scheme2, Tuple tuple1, Tuple tuple2); private: Predicate scheme; set<Tuple> tuples; string name; }; #endif
true
d4b426834b8410169f808a3f0fa5407e59dd5474
C++
JosefHF/DD1388
/lab2/matris.h
UTF-8
3,215
3.375
3
[]
no_license
#include <vector> #include <initializer_list> template <class T> class Matris { public: // constructors Matris(); Matris(T x); Matris(T rows, T columns); Matris(const Matris<T>& m); Matris(std::initializer_list<T> list); ~Matris(); //Operators T& operator()(const T& x, const T& y); // (x,y) operator const T& operator()(const T& x, const T& y) const; // const (x,y) operator Matris<T>& operator=(const Matris<T>& m); // = operator Matris<T> operator+(const Matris<T>& m); // + operator Matris<T> operator+(const T scalar); // + operator Matris<T> operator-(const Matris<T>& m); // - operator Matris<T> operator-(const T scalar); // - operator Matris<T> operator*(const Matris<T>& m); // * operator Matris<T> operator*(const T scalar); // * operator void operator+=(const Matris<T>& m); void operator-=(const Matris<T>& m); void operator*=(const Matris<T>& m); friend std::ostream& operator<<(std::ostream& out, const Matris<T>& m) { out << "Rows: " << m.m_rows << " Columns: " << m.m_cols << std::endl; for(int i=0; i<m.m_rows; i++){ for(int j=0; j<m.m_cols; j++){ out << m.m_vec[m.m_cols*i+j] << " "; } out << "" << std::endl; } return out; } friend std::istream& operator>>(std::istream& input, Matris<T>& m) { std::vector<T> v; T c; int rows = 0; int cols = 0; int total_num = 0; std::string line; while(std::getline(input,line)){ std::stringstream ss(line); rows += 1; while(!ss.eof()){ ss >> c; total_num += 1; while(ss.peek() != ' ' && ss.peek() != EOF){ ss >> c; total_num += 1; } //std::cout << c << std::endl; v.push_back(c); } } cols = total_num/rows; if(cols * rows != total_num){ std::cerr << "Bad dimensions" << std::endl; return input; } else{ m.m_rows = rows; m.m_cols = cols; m.m_capacity = rows*cols; m.m_vec = new T[m.m_capacity]; for(int i=0; i<m.m_capacity; i++){ m.m_vec[i] = v[i]; } return input; } //std::cout << rows << " " << total_num << " " << std::endl; return input; } //METHODS T getRows(); T getCols(); T getCapacity(); void setValue(int x, int y, T c); void reset(); Matris<T> identity(unsigned int); void insert_row(unsigned int row_number); void append_row(unsigned int row_number); void remove_row(unsigned int row_number); void remove_column(unsigned int column_number); void insert_column(unsigned int column_number); void append_column(unsigned int column_number); T* begin(); T* end(); private: T m_rows; T m_cols; T m_capacity; T * m_vec; };
true
b78d1e3091f3530b4512a57293e2814216a3d089
C++
cplab/klustakwik
/linalg.h
UTF-8
1,288
2.8125
3
[]
no_license
/* * linalg.h * * Linear algebra * * Created on: 13 Nov 2011 * Author: dan */ #ifndef LINALG_H_ #define LINALG_H_ #include "numerics.h" // Matrix which has the form of a block matrix and a nonzero diagonal // Unmasked gives the indices corresponding to the block matrix // Masked gives the indices corresponding to the diagonal class BlockPlusDiagonalMatrix { public: vector<scalar> Block; vector<scalar> Diagonal; vector<integer> *Unmasked; vector<integer> *Masked; integer NumUnmasked, NumMasked; BlockPlusDiagonalMatrix(vector<integer> &_Masked, vector<integer> &_Unmasked); void compare(scalar *Flat); }; integer Cholesky(SafeArray<scalar> &In, SafeArray<scalar> &Out, integer D); integer MaskedCholesky(SafeArray<scalar> &In, SafeArray<scalar> &Out, integer D, vector<integer> &Masked, vector<integer> &Unmasked); integer BPDCholesky(BlockPlusDiagonalMatrix &In, BlockPlusDiagonalMatrix &Out); void TriSolve(SafeArray<scalar> &M, SafeArray<scalar> &x, SafeArray<scalar> &Out, integer D); void MaskedTriSolve(SafeArray<scalar> &M, SafeArray<scalar> &x, SafeArray<scalar> &Out, integer D, vector<integer> &Masked, vector<integer> &Unmasked); void BPDTriSolve(BlockPlusDiagonalMatrix &M, SafeArray<scalar> &x, SafeArray<scalar> &Out); #endif /* LINALG_H_ */
true
4dce0fbf4864ecf16b1e46a953c3dc3d5e215ebc
C++
braeden-muller/hospitalBeds
/client.h
UTF-8
1,089
2.78125
3
[]
no_license
#ifndef HOSPITALBEDS_CLIENT_H #define HOSPITALBEDS_CLIENT_H #include <algorithm> #include <string> #include <chrono> #include <cpprest/http_client.h> #include <cpprest/json.h> #include <cwchar> #include "db_connection.h" #pragma comment(lib, "cpprest_2_10") using namespace web::http::client; /*! * The client sends requests to retrieve and modify resources * Authors: Charles Ranson */ class Client { public: /*! * Creates a new client at the specified address. Can only send DELETES and POSTS * \param addr The URL at which to listen on */ explicit Client(); ~Client(); /*! * \brief Sends request to the server in the form of a post and delete request * \param client command used to determine the type of commmand * \param hospital JSON value to be sent to the server */ web::json::value sendRequest(const std::string& command, const web::json::value& hospital); http_client * client; // The current client object being used to communicate with the server }; #endif //HOSPITALBEDS_CLIENT_H
true
92c48bcd836937d6b6c998208f9ae232866c8af2
C++
mattremmel/mrlib
/mrlib/container/String.hpp
UTF-8
24,547
3.234375
3
[]
no_license
// // String.hpp // Archimedes // // Created by Matthew Remmel on 7/29/15. // Copyright (c) 2015 Matthew Remmel. All rights reserved. // /* * The purpose of this class was to add a full featured string * class to C++. */ #ifndef MRLIB_STRING_HPP #define MRLIB_STRING_HPP #include <string> #include <fstream> #include <vector> #include <sstream> // Index Constants #ifndef NO_INDEX #define NO_INDEX -1ull #endif // String Constants static const std::string ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; static const std::string ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"; static const std::string ASCII_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; static const std::string ASCII_WHITESPACE = " \t\r\n\v\f"; static const std::string ASCII_PUNCTUATION = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"; static const std::string ASCII_DIGITS = "0123456789"; static const std::string ASCII_HEX_DIGITS = "0123456789abcdefABCDEF"; static const std::string ASCII_OCT_DIGITS = "01234567"; static const std::string ASCII_PRINTABLE = ASCII_LETTERS + ASCII_DIGITS + ASCII_PUNCTUATION + ASCII_WHITESPACE; namespace mrlib { class String { public: // Internal Data std::string _data; // Constructors String(); String(char character); String(const char* string); // String(const std::basic_string& string); String(const std::string& string); String(const String& string); // Numeric Constructors String(int value); String(long value); String(long long value); String(unsigned value); String(unsigned long value); String(unsigned long long value); String(float value); String(double value); String(long double value); // Operator Overloading char& operator[](size_t index); String& operator=(const String& string); const String operator+(const String& string) const; String& operator+=(const String& string); bool operator==(const String& string) const; bool operator!=(const String& string) const; // TODO: < and > overload <= >= // User Defined Conversions //operator std::string() const; // Creating and Initializing Strings static String StringWithContentsOfFile(const String& path); // Writing to a File void writeToFile(const String& path); void appendToFile(const String& path); // String Length size_t length() const; // Getting / Setting Characters char characterAtIndex(size_t i) const; void setCharacterAtIndex(const char c, size_t index); String& setValue(const String& string); // Changing Case String& toLowerCase(); String& toUpperCase(); String& toCapitalCase(); String& swapCase(); // Combining Strings String& append(const String& string); // Dividing Strings String substring(size_t from_index, size_t to_index) const; String substringFromIndex(size_t index) const; String substringToIndex(size_t index) const; std::vector<String> split(const String& delimiter) const; // Inserting String String& insert(const String& string, size_t index); // Trimming String String& trim(const String& characters = ASCII_WHITESPACE); String& trimLeading(const String& characters = ASCII_WHITESPACE); String& trimTrailing(const String& characters = ASCII_WHITESPACE); // TODO: remove extra spaces / whitespace in string // Reversing String String& reverse(); // Padding String String& pad(const String& string, size_t count); String& padLeft(const String& string, size_t count); String& padRight(const String& string, size_t count); // TODO: Pad to length. Pad if length is smaller than some parameter. Can use std::resize // TODO: Can be used for creating pretty printed tables and such // Replacing String String& replace(const String& old_string, const String& new_string); String& replaceLast(const String& old_string, const String& new_string); String& replaceAll(const String& old_string, const String& new_string); // TODO: Parameter as regex // Removing String String& remove(const String& string); String& removeLast(const String& string); String& removeRange(size_t from_index, size_t to_index); String& removeCharacters(const String& string); String& removeAll(const String& string); // Searching String bool contains(const String& string) const; size_t indexOf(const String& string) const; size_t indexOf(const String& string, size_t min_index) const; size_t indexOfLast(const String& string) const; size_t indexOfLast(const String& string, size_t max_index) const; // String Comparison bool isEqualTo(const String& string) const; bool isEqualToIgnoreCase(const String& string) const; int compare(const String& string) const; int compareIgnoreCase(const String& string) const; //int compareOverRange(const String& string, size_t from_index, size_t to_index); // Numeric Values int intValue() const; long longValue() const; long long longLongValue() const; unsigned unsignedValue() const; unsigned long unsignedLongValue() const; unsigned long long unsignedLongLongValue() const; float floatValue() const; double doubleValue() const; long double longDoubleValue() const; bool boolValue() const; // String Copy String copy() const; // Getting Standard Containers const char* c_string() const; std::string std_string() const; // String Representation std::string description() const; std::string inspect() const; // TODO: matches regex / index of regex pattern }; ///////////////////////////// // TEMPLATE IMPLEMENTATION // ///////////////////////////// // Constructors inline String::String() { this->_data = ""; } inline String::String(char character) { this->_data = character; } inline String::String(const char* string) { this->_data = string; } inline String::String(const std::string& string) { this->_data = string; } inline String::String(const String& string) { this->_data = string._data; } // Numeric Constructors inline String::String(int value) { this->_data = std::to_string(value); } inline String::String(long value) { this->_data = std::to_string(value); } inline String::String(long long value) { this->_data = std::to_string(value); } inline String::String(unsigned value) { this->_data = std::to_string(value); } inline String::String(unsigned long value) { this->_data = std::to_string(value); } inline String::String(unsigned long long value) { this->_data = std::to_string(value); } inline String::String(float value) { this->_data = std::to_string(value); this->trimTrailing("0"); } inline String::String(double value) { this->_data = std::to_string(value); this->trimTrailing("0"); } inline String::String(long double value) { this->_data = std::to_string(value); this->trimTrailing("0"); } // Operator Overloading inline char& String::operator[](size_t index) { if(index < this->_data.length()) { return this->_data[index]; } else { throw std::invalid_argument("Out of bounds exception"); } } inline String& String::operator=(const String& string) { // Check for self assignment if (this == &string) return *this; this->_data = string._data; return *this; } inline const String String::operator+(const String& string) const { return String(this->_data + string._data); } inline String& String::operator+=(const String& string) { this->_data += string._data; return *this; } inline bool String::operator==(const String& string) const { if (this == &string) return true; return this->_data == string._data; } inline bool String::operator!=(const String& string) const { if (this == &string) return false; return this->_data != string._data; } // Creating and Initializing Strings inline String String::StringWithContentsOfFile(const String& path) { try { std::ifstream ifs; ifs.open(path._data.c_str()); if (ifs.is_open()) { std::string _data((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); ifs.close(); return String(_data); } else { throw std::invalid_argument("Error opening file at path: " + path.std_string()); } } catch(int e) { throw std::invalid_argument("Exception opening file at: " + path.std_string() + " error: " + std::to_string(e)); } } // Writing to a File inline void String::writeToFile(const String& path) { try { std::ofstream ofs; ofs.open(path._data.c_str()); if (ofs.is_open()) { ofs << this->_data; ofs.close(); } else { throw std::invalid_argument("Error opening file at path: " + path.std_string()); } } catch (int e) { throw std::invalid_argument("Exception opening file at: " + path.std_string() + " error: " + std::to_string(e)); } } inline void String::appendToFile(const String& path) { try { std::ofstream ofs; ofs.open(path._data.c_str(), std::ios::app); if (ofs.is_open()) { ofs << this->_data; ofs.close(); } else { throw std::invalid_argument("Error opening file at path: " + path.std_string()); } } catch (int e) { throw std::invalid_argument("Exception opening file at: " + path.std_string() + " error: " + std::to_string(e)); } } // String Length inline size_t String::length() const { return this->_data.length(); } // Getting / Setting Characters inline char String::characterAtIndex(size_t i) const { if (i < this->_data.length()) { return this->_data[i]; } else { throw std::invalid_argument("Out of bounds exception"); } } inline void String::setCharacterAtIndex(char c, size_t index) { if (index < this->_data.length()) { this->_data[index] = c; } else { throw std::invalid_argument("Out of bounds exception"); } } inline String& String::setValue(const String& string) { this->_data = string._data; return *this; } // Changing Case inline String& String::toLowerCase() { for (size_t i = 0; i < this->_data.length(); ++i) { this->_data[i] = (char)tolower(this->_data[i]); } return *this; } inline String& String::toUpperCase() { for (size_t i = 0; i < this->_data.length(); ++i) { this->_data[i] = (char)toupper(this->_data[i]); } return *this; } inline String& String::toCapitalCase() { this->_data[0] = (char)toupper(this->_data[0]); for (size_t i = 1; i < this->_data.length(); ++i) { if (this->_data[i - 1] == ' ') { this->_data[i] = (char)toupper(this->_data[i]); } } return *this; } inline String& String::swapCase() { size_t length = this->_data.length(); for (size_t i = 0; i < length; ++i) { if (islower(this->_data[i])) { this->_data[i] = (char)toupper(this->_data[i]); } else if (isupper(this->_data[i])) { this->_data[i] = (char)tolower(this->_data[i]); } } return *this; } // Combining Strings inline String& String::append(const String& string) { this->_data.append(string._data); return *this; } // Dividing Strings inline String String::substring(size_t from_index, size_t to_index) const { if (from_index > to_index) throw std::invalid_argument("from_index must be less than to_index"); if (to_index < this->_data.length()) { return this->_data.substr(from_index, to_index - from_index); } else { throw std::invalid_argument("Out of range exception"); } } inline String String::substringFromIndex(size_t index) const { if (index < this->_data.length()) { return this->_data.substr(index); } else { throw std::invalid_argument("Out of range exception"); } } inline String String::substringToIndex(size_t index) const { if (index < this->_data.length()) { return this->_data.substr(0, index); } else { throw std::invalid_argument("Out of range exception"); } } inline std::vector<String> String::split(const String& delimiter) const { std::vector<String> output; size_t delim_length = delimiter._data.length(); if (delim_length == 0) { for (size_t i = 0; i < this->_data.length(); ++i) { output.push_back(this->_data[i]); } return output; } size_t element_begin = 0; size_t element_end = 0; while ((element_end = this->_data.find(delimiter.std_string(), element_end)) != NO_INDEX) { output.push_back(this->_data.substr(element_begin, element_end - element_begin)); element_end += delim_length; element_begin = element_end; } output.push_back(this->_data.substr(element_begin, this->_data.length() - element_begin)); return output; } // Inserting String inline String& String::insert(const String& string, size_t index) { if (index < this->_data.length()) { this->_data.insert(index, string.std_string()); return *this; } else { throw std::invalid_argument("Out of bounds exception"); } } // Trimming String inline String& String::trim(const String& characters) { this->trimLeading(characters); this->trimTrailing(characters); return *this; } inline String& String::trimLeading(const String& characters) { this->_data.erase(0, this->_data.find_first_not_of(characters.c_string())); return *this; } inline String& String::trimTrailing(const String& characters) { size_t last_not_of = this->_data.find_last_not_of(characters.c_string()) + 1; this->_data.erase(last_not_of, this->_data.length() - last_not_of); return *this; } // Reversing String inline String& String::reverse() { std::string buffer = ""; for (size_t i = this->_data.length(); i > 0; --i) { buffer += this->_data[i - 1]; } this->_data = buffer; return *this; } // Padding inline String& String::pad(const String& string, size_t count) { this->padLeft(string, count); this->padRight(string, count); return *this; } inline String& String::padLeft(const String& string, size_t count) { std::string pad_string = ""; for (size_t i = 0; i < count; ++i) { pad_string += string._data; } this->_data.insert(0, pad_string); return *this; } inline String& String::padRight(const String& string, size_t count) { std::string pad_string = ""; for (size_t i = 0; i < count; ++i) { pad_string += string._data; } this->_data.insert(this->_data.length(), pad_string); return *this; } // Replacing String inline String& String::replace(const String& old_string, const String& new_string) { size_t target_length = old_string._data.length(); size_t target_index = this->_data.find(old_string._data); if (target_index != NO_INDEX) { this->_data.replace(target_index, target_length, new_string._data); } return *this; } inline String& String::replaceLast(const String& old_string, const String& new_string) { size_t target_length = old_string._data.length(); size_t target_index = this->_data.rfind(old_string._data); if (target_index != NO_INDEX) { this->_data.replace(target_index, target_length, new_string._data); } return *this; } inline String& String::replaceAll(const String& old_string, const String& new_string) { size_t target_length = old_string._data.length(); size_t target_index = 0; while ((target_index = this->_data.find(old_string._data, target_index)) != NO_INDEX) { this->_data.replace(target_index, target_length, new_string._data); } return *this; } // Removing String inline String& String::remove(const String& string) { size_t target_length = string._data.length(); size_t target_index = this->_data.find(string._data); if (target_index != NO_INDEX) { this->_data.erase(target_index, target_length); } return *this; } inline String& String::removeLast(const String& string) { size_t target_length = string._data.length(); size_t target_index = this->_data.rfind(string._data); if (target_index != NO_INDEX) { this->_data.erase(target_index, target_length); } return *this; } inline String& String::removeRange(size_t from_index, size_t to_index) { if (from_index > to_index) throw std::invalid_argument("from_index must be less than to_index"); if (from_index < this->_data.length() && to_index < this->_data.length()) { this->_data.erase(from_index, to_index - from_index); return *this; } else { throw std::invalid_argument("Out of bounds exception"); } } inline String& String::removeCharacters(const String& string) { std::string buffer = ""; for (size_t i = 0; i < this->_data.length(); ++i) { if (!string.contains(this->_data[i])) { buffer += this->_data[i]; } } this->_data = buffer; return *this; } inline String& String::removeAll(const String& string) { size_t target_length = string._data.length(); size_t target_index = 0; while ((target_index = this->_data.find(string._data, target_index)) != NO_INDEX) { this->_data.erase(target_index, target_length); } return *this; } // Searching String inline bool String::contains(const String& string) const { size_t index = this->_data.find(string.std_string()); return index != NO_INDEX; } inline size_t String::indexOf(const String& string) const { return this->_data.find(string._data); } inline size_t String::indexOf(const String& string, size_t min_index) const { return this->_data.find(string._data, min_index); } inline size_t String::indexOfLast(const String& string) const { return this->_data.rfind(string._data); } inline size_t String::indexOfLast(const String& string, size_t max_index) const { return this->_data.rfind(string._data, max_index); } // String Comparison inline bool String::isEqualTo(const String& string) const { return this->_data == string._data; } inline bool String::isEqualToIgnoreCase(const String& string) const { size_t length = this->_data.length(); if (string._data.length() != length) { return false; } for (size_t i = 0; i < length; ++i) { if (tolower(this->_data[i]) != tolower(string._data[i])) { return false; } } return true; } inline int String::compare(const String& string) const { return this->_data.compare(string.std_string()); } inline int String::compareIgnoreCase(const String& string) const { return this->copy().toLowerCase()._data.compare(string.copy().toLowerCase()._data); } /* int String::compareOverRange(const String& string, size_t from_index, size_t to_index) { if (from_index > to_index) throw std::invalid_argument("from_index must be less than to_index"); if (from_index < this->_data.size() && to_index < this->_data.size() && from_index < string._data.size() && to_index < string._data.size()) { return this->_data.compare(from_index, to_index - from_index, string._data, from_index, to_index - from_index); } else { throw std::invalid_argument("Out of bounds exception"); } } */ // Numeric Values inline int String::intValue() const { return std::stoi(this->_data.c_str()); } inline long String::longValue() const { return std::stol(this->_data.c_str()); } inline long long String::longLongValue() const { return std::stoll(this->_data.c_str()); } inline unsigned String::unsignedValue() const { return std::stoul(this->_data.c_str()); } inline unsigned long String::unsignedLongValue() const { return std::stoul(this->_data.c_str()); } inline unsigned long long String::unsignedLongLongValue() const { return std::stoull(this->_data.c_str()); } inline float String::floatValue() const { return std::stof(this->_data.c_str()); } inline double String::doubleValue() const { return std::stod(this->_data.c_str()); } inline long double String::longDoubleValue() const { return std::stold(this->_data.c_str()); } inline bool String::boolValue() const { String string = this->copy().toLowerCase(); if (string == "false") return false; if (string == "true") return true; if (string == "no") return false; if (string == "yes") return true; if (string == "n") return false; if (string == "y") return true; if (string == "0") return false; if (string == "1") return true; throw std::invalid_argument("Invalid bool value: " + this->_data); } // String Copy inline String String::copy() const { return String(this->_data); } // Getting Standard Containers inline const char* String::c_string() const { return this->_data.c_str(); } inline std::string String::std_string() const { return this->_data; } // String Representation inline std::string String::description() const { return this->_data; } inline std::string String::inspect() const { std::ostringstream oss; // Array Address oss << "Address: " << this << " "; // Array Size oss << "Size: " << this->_data.size() << " "; // Array Contents oss << "\"" << this->_data << "\""; return oss.str(); } } #endif //MRLIB_STRING_HPP
true
8af9f8974a6162b3467e20dfe7e8b5a8ae536d16
C++
YuzukiTsuru/SingSyn
/lib/libSinsy/util/PhonemeTable.h
UTF-8
1,897
2.828125
3
[ "BSD-3-Clause" ]
permissive
#ifndef SINSY_PHONEME_TABLE_H_ #define SINSY_PHONEME_TABLE_H_ #include <map> #include <vector> #include <string> namespace sinsy { class PhonemeTable { public: typedef std::vector<std::string> PhonemeList; class Result { public: //! constructor Result(); //! constructor Result(const std::string &s, const PhonemeList *p); //! copy constructor Result(const Result &obj); //! destructor virtual ~Result(); //! assignment operator Result &operator=(const Result &obj); //! is valid or not bool isValid() const; //! get syllable const std::string &getSyllable() const; //! get phoneme list const PhonemeList *getPhonemeList() const; //! get mached length size_t getMatchedLength() const; private: //! syllable const std::string *syllable; //! phoneme list const PhonemeList *phonemeList; }; public: //! constructor PhonemeTable(); //! destructor virtual ~PhonemeTable(); //! clear void clear(); //! read from file bool read(const std::string &fname); //! find from table Result find(const std::string &syllable) const; //! return matched result Result match(const std::string &syllable) const; private: //! copy constructor (donot use) PhonemeTable(const PhonemeTable &); //! assignment operator (donot use) PhonemeTable &operator=(const PhonemeTable &); typedef std::map<std::string, PhonemeList *> ConvertTable; //! convert table ConvertTable convertTable; }; }; #endif // SINSY_PHONEME_TABLE_H_
true
f057d8a17a932bbf86d9c56d532469f4cea8579a
C++
dfr8938/coursera_repo
/cpp_white/const/main.cpp
UTF-8
434
3.234375
3
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { const int x = 5; // x = 6; // x += 4; cout << x << endl; const string s = "Hello, "; cout << s.size() << endl; // s += "World!"; cout << s.size() << endl; const vector<string> strings = {"hello", "world"}; // strings.push_back("!"); // strings[0][0] = 'H'; cout << strings.size() << endl; return 0; }
true
483f4b03a6b372630053bbfba9b1d2a2c939ca57
C++
km-9/cleanGITproject
/templateMatcher.h
UTF-8
1,251
2.640625
3
[]
no_license
#include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/imgproc.hpp" #include <iostream> using namespace std; using namespace cv; namespace templateMatch { class templateMatcher { public: //if the matching method uses a mask or not bool use_mask; //img: the frame captured from the camera Mat img; //templ: current template being used by matching method Mat templ; //mask: mask for template (if any) Mat mask; //result: the resulting image after processing Mat result; //template of left side of crib Mat leftTempl; //right side of crib Mat rightTempl; //face/front of crib Mat frontTempl; //scaling multiplyer for template double scale; //determines which side of the crib is being seen (according to which template is being used) int side; //always set to 4. int match_method; //calls getFrame(), checks if it was successful and then calls MatchingMethod; void lookAround(); private: //runs the matching method and processes the image void MatchingMethod( int, void* ); //returns a frame from a video stream Mat getFrame(); }; }
true
a3e445a2a63915073a01ba21352ca8896639a4f1
C++
FuckingError/Interesting-Algorithm
/4.4编辑距离/main.cpp
GB18030
1,329
3.6875
4
[]
no_license
#include <iostream> #include <cstring> /* 20181018 21:05:20 ַ һֲ ɾȥ 滻 dp[i][j] = min{dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+diff} diff=0 d[i-1]==d[j-1] 1 IJ һҪע ǷеȺŰ */ using namespace std; const int N = 100; char str1[N],str2[N]; int d[N][N]; //༭ ڵǰÿһԪصֵ ʱַӦʱIJ int min(int a,int b){ return a<b?a:b; //ؽСֵ } int editdistance(char *str1,char *str2){ int len1 = strlen(str1);//ַ int len2 = strlen(str2); //ʼһ һ for(int i=0;i<=len1;i++) d[i][0] = i; for(int j=0;j<=len2;j++) //IJ һҪע ǷеȺŰ d[0][j] = j; for(int i=1;i<=len1;i++){ for(int j=1;j<len2;j++){ int diff; diff = str1[i-1]==str2[j-1]?0:1; int temp = min(d[i-1][j]+1,d[i][j-1]+1); d[i][j] = min(temp,d[i-1][j-1]+diff); } } return d[len1][len2]; } int main() { cout<<"ַstr1:"<<endl; cin>>str1; cout<<"ַstr2:"<<endl; cin>>str2; cout<<str1<<""<<str2<<"ľΪ"<<editdistance(str1,str2); return 0; }
true
13507791a22a48d083dda8b4ec7977d7f9f1410d
C++
TheHappyHearse/Art_Car_Fire
/Art_Car_Fire.ino
UTF-8
4,369
3.421875
3
[]
no_license
/* Art Car Flame Effect 2015 ~-~-~-~-~-~-~-~-QUESTIONS: ~-~-~_~-~-~-~-~-~-~-~-~- Shold I be using ints where I put bytes instead? Can I use arrays instead of so much repetition in the "determineSequence" function? */ //The following go to the pins that control firing the effect const byte LeftFireSw=2; //Green button switch for left fire const byte RightFireSw=3; //Green button switch for right fire const byte ActivateSw=4; //Red button switch to start sequence //Next are pins that power the LEDs on the control switches const byte LeftLED=5; //LED for fire button (Green) const byte RightLED=6; //LED for fire button (Green) const byte ActivateLED=7; //LED for Activate button (Red) /*Now we have the pins that trigger the MOSFETs that open the solenoids and shoot fire. */ const byte LeftSol=8; //Left solenoid const byte RightSol=9; //Right solenoid /* Next are the input pins for the ternery number switches. These will control what sequence the Arduino will play when the activate button is pressed. */ const byte onesZero=10; //12's const byte onesTwo=11; const byte threesZero=12; const byte threesSix=13; const byte ninesZero=A0; const byte ninesEighteen=A1; const unsigned long dumbAssTimeOut=300000; //How long to wait if it's put into void setup() //"Safe Mode." { pinMode(LeftFireSw,INPUT); pinMode(RightFireSw,INPUT); pinMode(ActivateSw,INPUT); pinMode(LeftLED,OUTPUT); pinMode(RightLED,OUTPUT); pinMode(ActivateLED,OUTPUT); pinMode(LeftSol,OUTPUT); pinMode(RightSol,OUTPUT); pinMode(onesZero,INPUT); pinMode(onesTwo,INPUT); pinMode(threesZero,INPUT); pinMode(threesSix,INPUT); pinMode(ninesZero,INPUT); pinMode(ninesEighteen,INPUT); } void loop() { turnOnLEDs(); //Turns on all LED control lights, indicating it's ready byte selectedSequence = determineSequence(); digitalRead(LeftFireSw); //These 3 lines check the switches so the digitalRead(RightFireSw); //program can figure out what to do next. digitalRead(ActivateSw); if (ActivateSw==HIGH) activateIsPressed(); } /* What follows is a function to determine what to do when someone presses the activate button. Tt determines whether the operator is trying to send the program into idle mode, or if he is calling for a fire sequence. */ void activateIsPressed() { //To be filled in later } void dumbAss() { digitalWrite(LeftSol,LOW); digitalWrite(RightSol,LOW); turnOffLEDs; delay(dumbAssTimeOut); } /* Teh following function turns on all teh LEDs. */ void turnOnLEDs() { digitalWrite(LeftLED,HIGH); digitalWrite(RightLED,HIGH); digitalWrite(ActivateLED,HIGH); } void turnOffLEDs() //Shuts off all LEDs { digitalWrite(LeftLED,LOW); digitalWrite(RightLED,LOW); digitalWrite(ActivateLED,LOW); } byte determineSequence() //Can I use array?? { if (digitalRead(onesZero) == HIGH && digitalRead(onesTwo) == LOW && digitalRead(threesZero) == HIGH && digitalRead(threesSix) == LOW && digitalRead(ninesZero) == HIGH && digitalRead(ninesEighteen) == LOW) return 0; //sequence 0 is active if (digitalRead(onesZero) == LOW && digitalRead(onesTwo) == LOW && digitalRead(threesZero) == HIGH && digitalRead(threesSix) == LOW && digitalRead(ninesZero) == HIGH && digitalRead(ninesEighteen) == LOW) return 1; //sequence 1 is active if (digitalRead(onesZero) == LOW && digitalRead(onesTwo) == HIGH && digitalRead(threesZero) == HIGH && digitalRead(threesSix) == LOW && digitalRead(ninesZero) == HIGH && digitalRead(ninesEighteen) == LOW) return 2; //sequence 2 is active if (digitalRead(onesZero) == HIGH && digitalRead(onesTwo) == LOW && digitalRead(threesZero) == LOW && digitalRead(threesSix) == LOW && digitalRead(ninesZero) == HIGH && digitalRead(ninesEighteen) == LOW) return 3; //sequence 3 is active if (digitalRead(onesZero) == LOW && digitalRead(onesTwo) == LOW && digitalRead(threesZero) == LOW && digitalRead(threesSix) == LOW && digitalRead(ninesZero) == HIGH && digitalRead(ninesEighteen) == LOW) return 4; // sequence 4 is active //AND SO ON... }
true
ad62911e08192cda880d85a0b7b85295f5534a8d
C++
dmitriano/Awl
/Tests/TypeIndexTest.cpp
UTF-8
2,155
2.734375
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Product: AWL (A Working Library) // Author: Dmitriano ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include "Awl/Serializable.h" #include "Awl/Io/TypeIndex.h" #include <string> #include <vector> using namespace awl::io; namespace { struct A { bool x; int y; AWL_SERIALIZABLE(x, y) }; struct B { A a; double z; AWL_SERIALIZABLE(a, z) }; struct C { std::string d; B b; A a; std::vector<std::string> e; AWL_SERIALIZABLE(d, b, a, e) }; struct D { C c; B b; A a; AWL_SERIALIZABLE(c, b, a) }; static_assert(countof_fields<A>() == 2); static_assert(countof_fields<B>() == 3); static_assert(indexof_type<A, bool>() == 0); static_assert(indexof_type<A, int>() == 1); static_assert(indexof_type<B, bool>() == 0); static_assert(indexof_type<B, bool>() == 0); static_assert(indexof_type<B, int>() == 1); static_assert(indexof_type<B, double>() == 2); static_assert(indexof_type<B, std::string>() == no_type_index); static_assert(indexof_type<C, bool>() == 0 + 1); static_assert(indexof_type<C, int>() == 1 + 1); static_assert(indexof_type<C, double>() == 2 + 1); static_assert(indexof_type<C, std::string>() == 0); static_assert(indexof_type<C, std::vector<std::string>>() == countof_fields<B>() + countof_fields<A>() + 1); static_assert(indexof_type<C, std::vector<int>>() == no_type_index); static_assert(indexof_type<D, bool>() == 0 + 1); static_assert(indexof_type<D, int>() == 1 + 1); static_assert(indexof_type<D, double>() == 2 + 1); static_assert(indexof_type<D, std::string>() == 0); static_assert(indexof_type<D, std::vector<std::string>>() == countof_fields<B>() + countof_fields<A>() + 1); static_assert(indexof_type<D, std::vector<int>>() == no_type_index); }
true
793eab2c02aa38d97438c368e0636e51ea6e5e7d
C++
KorlaMarch/competitive-programming
/main.cpp
UTF-8
7,207
2.71875
3
[]
no_license
#include <cstdlib> #include <iostream> #include <windows.h> #include <queue> using namespace std; char buffer[80][24]; //0 = null //1 = menu //2 = play //3 = high score //4 = about //5 = Game over int score; int scene = 0; int currentMenu = 0; int inGame = 0; //0 = north //1 = south //2 = east //3 = west int direction = 0; string Menulist[4] = {"> play <", "high_score", "about", "exit"}; struct snakeBody { int x; int y; }; queue<snakeBody> snake; void render(){ string temp; for(int y = 0; y <= 23; y++){ for(int x = 0; x <= 79; x++){ temp += buffer[x][y]; //cout << buffer[x][y]; } } cout << temp; } void intGraphic(){ //draw box //head and bottom for(int n = 0; n <= 79; n++){ buffer[n][0] = 223; buffer[n][23] = 220; } buffer[0][0] = 219; buffer[79][0] = 219; buffer[0][23] = 219; buffer[79][23] = 219; //mid for(int n = 1; n <= 22; n++){ buffer[0][n] = 219; for(int n2 = 1; n2 <= 78; n2++){ buffer[n2][n] = 250; } buffer[79][n] = 219; } } void drawMenu(){ //make border //head and bottom for(int n = 23; n <= 55; n++){ buffer[n][8] = 205; buffer[n][15] = 205; } buffer[23][8] = 201; buffer[23][15] = 200; buffer[56][8] = 187; buffer[56][15] = 188; //mid for(int n = 9; n <= 14; n++){ buffer[23][n] = 186; buffer[56][n] = 186; } //drawbox 6*32 for(int n = 9; n <= 14; n++){ for(int n2 = 24; n2 <= 55; n2++){ buffer[n2][n] = ' '; } } //find mid point & print menu for(int n = 10; n <= 13; n++){ int mid = (int)((32 - Menulist[n-10].length()) / 2) + 24; for(int n2 = 0; n2 <= Menulist[n-10].length() - 1; n2++){ buffer[mid + n2][n] = (Menulist[n-10])[n2]; } } } void moveSnack(snakeBody nextMove, int addNew); void update(){ //menu update if(scene == 1){ if(GetAsyncKeyState(VK_UP) != 1 && GetAsyncKeyState(VK_UP) != 0){ //play sound cout << "\a"; //scroll manu up if(currentMenu == 0){ currentMenu = 3; Menulist[0] = "play"; Menulist[3] = "> exit <"; } else if(currentMenu == 1){ currentMenu = 0; Menulist[1] = "high_score"; Menulist[0] = "> play <"; } else if(currentMenu == 2){ currentMenu = 1; Menulist[2] = "about"; Menulist[1] = "> high_score <"; } else if(currentMenu == 3){ currentMenu = 2; Menulist[3] = "exit"; Menulist[2] = "> about <"; } drawMenu(); } else if(GetAsyncKeyState(VK_DOWN) != 1 && GetAsyncKeyState(VK_DOWN) != 0){ //play sound cout << "\a"; //scroll manu down if(currentMenu == 0){ currentMenu = 1; Menulist[0] = "play"; Menulist[1] = "> high_score <"; } else if(currentMenu == 1){ currentMenu = 2; Menulist[1] = "high_score"; Menulist[2] = "> about <"; } else if(currentMenu == 2){ currentMenu = 3; Menulist[2] = "about"; Menulist[3] = "> exit <"; } else if(currentMenu == 3){ currentMenu = 0; Menulist[3] = "exit"; Menulist[0] = "> play <"; } drawMenu(); } else if(GetAsyncKeyState(VK_RETURN) != 1 && GetAsyncKeyState(VK_RETURN) != 0){ //play sound cout << "\a"; if(currentMenu == 0){ scene = 2; }else if(currentMenu == 1){ scene = 3; }else if(currentMenu == 2){ scene = 4; return; }else if(currentMenu == 3){ exit(1); } } } //play scene if(scene == 2 && inGame == 0){ //clear screen intGraphic(); for(int n = 1; n <= 22; n++){ for(int n2 = 1; n2 <= 78; n2++){ buffer[n2][n] = ' '; } } //clear score score = 0; string text = "Score : 0000"; for(int n = 67; n <= 78; n++){ buffer[n][0] = text[n-67]; } buffer[66][0] = 35; //make starter snake snakeBody temp; for(int n = 35; n <= 38; n++){ temp.x = n; temp.y = 13; snake.push(temp); } temp.x = 38; temp.y = 13; moveSnack(temp, 0); direction = 2; //random ball buffer[rand() % 78 + 1][rand() % 22 + 1] = 15; inGame = 1; }else if(scene == 2 && inGame == 1){ snakeBody next; //check key if(GetAsyncKeyState(VK_UP) && direction != 1){ direction = 0; }else if(GetAsyncKeyState(VK_DOWN) && direction != 0){ direction = 1; }else if(GetAsyncKeyState(VK_RIGHT) && direction != 3){ direction = 2; }else if(GetAsyncKeyState(VK_LEFT) && direction != 2){ direction = 3; } //move snake if(direction == 0){ next.x = snake.back().x; next.y = snake.back().y - 1; moveSnack(next, 0); }else if(direction == 1){ next.x = snake.back().x; next.y = snake.back().y + 1; moveSnack(next, 0); }else if(direction == 2){ next.x = snake.back().x + 1; next.y = snake.back().y; moveSnack(next, 0); }else if(direction == 3){ next.x = snake.back().x - 1; next.y = snake.back().y; moveSnack(next, 0); } } //hight score scene if(scene == 3){ } //about if(scene == 4){ //clear screen intGraphic(); //check key prass if(GetAsyncKeyState(VK_RETURN) != 1 && GetAsyncKeyState(VK_RETURN) != 0){ scene = 1; currentMenu = 0; intGraphic(); drawMenu(); return; } //make border //head and bottom for(int n = 23; n <= 55; n++){ buffer[n][7] = 205; buffer[n][16] = 205; } buffer[23][7] = 201; buffer[23][16] = 200; buffer[56][7] = 187; buffer[56][16] = 188; //mid for(int n = 8; n <= 15; n++){ buffer[23][n] = 186; buffer[56][n] = 186; } //drawbox 6*32 for(int n = 8; n <= 15; n++){ for(int n2 = 24; n2 <= 55; n2++){ buffer[n2][n] = ' '; } } //find mid point & print about string about[3] = {"Snakey", "By", "KorlaMarch"}; for(int n = 10; n <= 12; n++){ int mid = (int)((32 - about[n-10].length()) / 2) + 24; for(int n2 = 0; n2 <= about[n-10].length() - 1; n2++){ buffer[mid + n2][n] = (about[n-10])[n2]; } } buffer[35][10] = 273; buffer[44][10] = 272; buffer[33][12] = 270; buffer[46][12] = 270; string printtext = "Enter to back"; for(int n2 = 0; n2 <= printtext.length() - 1; n2++){ buffer[43 + n2][8] = printtext[n2]; } } } void snakeEatEvent(){ //makeNewBall while(1){ int x = rand() % 78 + 1; int y = rand() % 22 + 1; if(buffer[x][y] != 'O'){ buffer[x][y] = 15; break; } } //update score score += 10; buffer[78][0] = score % 10 + 48; buffer[77][0] = ((score % 100) - (score % 10)) / 10 + 48; buffer[76][0] = ((score % 1000)- (score % 100) - (score % 10)) / 100 + 48; buffer[75][0] = ((score % 10000) - (score % 1000) - (score % 100) - (score % 10)) / 1000 + 48; } void moveSnack(snakeBody nextMove, int addNew){ //front = tail //back = head queue<snakeBody> Tempsnack; snake.push(nextMove); //check death if(buffer[nextMove.x][nextMove.y] != ' '){ if(buffer[nextMove.x][nextMove.y] != 15){ scene = 5; return; }else{ addNew = 1; //play sound cout << "\a"; snakeEatEvent(); } } //remove old snake tail if(addNew != 1){ buffer[snake.front().x][snake.front().y] = ' '; snake.pop(); } while(!snake.empty()){ //pop out and render buffer[snake.front().x][snake.front().y] = 'O'; Tempsnack.push(snake.front()); snake.pop(); } //return old snake value snake = Tempsnack; } int main(int argc, char *argv[]) { intGraphic(); drawMenu(); scene = 1; while(true){ update(); render(); Sleep(100); } return 1; }
true
5dcc8c540969ca478980a3f80dcb0fc488200d0f
C++
Oleg20502/infa_2sem
/Lab2/Task6.cpp
UTF-8
332
2.53125
3
[]
no_license
#include <iostream> using namespace std; int main() { int nmax, nummax = 1, a; cin >> a; nmax = a; while (a != 0){ cin >> a; if (a == nmax){ nummax++; } else if (a > nmax){ nmax = a; nummax = 1; } } cout << nummax; return 0; }
true
8b4c66fb670300bda6555f5ee48db55909d6ee50
C++
Zylann/SnowfeetFramework
/include/fm/scene/core/ComponentList.hpp
UTF-8
2,106
3.15625
3
[]
no_license
#ifndef HEADER_ZN_COMPONENTLIST_HPP_INCLUDED #define HEADER_ZN_COMPONENTLIST_HPP_INCLUDED #include <iostream> #include <cassert> #include <unordered_set> #include <fm/types.hpp> namespace zn { // Generic container gathering a specific type of component. template <class Cmp_T> class ComponentList { public: // Adds a component to the list. void add(Cmp_T * cmp) { #ifdef ZN_DEBUG if(cmp == nullptr) std::cout << "E: ComponentList::add: cannot add null" << std::endl; #endif assert(cmp != nullptr); #ifdef ZN_DEBUG auto it = m_all.find(cmp); if(it != m_all.end()) { std::cout << "E: ComponentList::add: already contains (" << cmp->objectType().name << ")" << std::endl; return; } #endif m_all.insert(cmp); } // Removes an existing component from the list (doesn't deletes it). void remove(Cmp_T * cmp) { assert(cmp != nullptr); if(m_all.erase(cmp) == 0) { std::cout << "E: ComponentList::remove: " << cmp->objectType().name << " was not found." << std::endl; } } // Updates all components in the list if their entity is active. // Uses a copy of the internal container to avoid concurrent modifications. void update() { // Iterate over a copy to avoid concurrent modifications auto updateList = m_all; for(auto it = updateList.begin(); it != updateList.end(); ++it) { Cmp_T & cmp = **it; if(cmp.enabled() && cmp.entity().active()) { cmp.update(); } } } inline u32 count() const { return m_all.size(); } inline bool empty() const { return m_all.empty(); } inline typename std::unordered_set<Cmp_T*>::iterator begin() { return m_all.begin(); } inline typename std::unordered_set<Cmp_T*>::iterator end() { return m_all.end(); } inline typename std::unordered_set<Cmp_T*>::const_iterator cbegin() const { return m_all.cbegin(); } inline typename std::unordered_set<Cmp_T*>::const_iterator cend() const { return m_all.cend(); } private: std::unordered_set<Cmp_T*> m_all; // References to all instances of the component in the scene }; } // namespace zn #endif // HEADER_ZN_COMPONENTLIST_HPP_INCLUDED
true
7ea7fd741b75a5142730f0d4141fffa0983ec151
C++
IamLena/s21_cpp
/cpp05/ex01/Form.cpp
UTF-8
1,617
3.40625
3
[]
no_license
#include "Form.hpp" Form::Form() : name(""), ifsigned(false), signgrade(150), executegrade(150) {} Form::Form(std::string const &name, int signgrade, int executegrade) : name(name), ifsigned(false), signgrade(signgrade), executegrade(executegrade) { if (signgrade < 1 || executegrade < 1) throw Form::GradeTooHighException() ; if (signgrade > 150 || executegrade > 150) throw Form::GradeTooLowException() ; } Form::Form(Form const &other) : name(other.getName()), ifsigned(other.issigned()), signgrade(other.getSignGrade()), executegrade(other.getExecuteGrade()) {} Form &Form::operator=(Form const &other) { this->~Form(); new (this) Form(other); return *this; } Form::~Form() {} std::string const &Form::getName() const{ return this->name; } bool Form::issigned() const { return this->ifsigned; } int Form::getSignGrade() const { return this->signgrade; } int Form::getExecuteGrade() const { return this->executegrade; } void Form::beSigned(const Bureaucrat &bureaucrat) { if (bureaucrat.getGrade() <= this->signgrade) this->ifsigned = true; else throw Form::GradeTooLowException(); } const char* Form::GradeTooHighException::what() const throw(){ return "Grade is too high."; }; const char* Form::GradeTooLowException::what() const throw(){ return "Grade is too low."; }; std::ostream &operator<<(std::ostream &out, Form const &form) { out << "Form " << form.getName(); if (form.issigned()) out << "; signed; "; else out << "; not signed; "; out << "sign grade: " << form.getSignGrade(); out << "; execute grade: " << form.getExecuteGrade() << "." << std::endl; return out; }
true
9b03d024fecf9c32c4b1a1be3362329d49f7e347
C++
sibsau-STF/Assembler-labs
/Main/main3.cpp
UTF-8
1,893
2.9375
3
[]
no_license
#include <locale.h> #include <iostream> #include <iomanip> #include <fstream> #include <time.h> #include "../Headers/CashTest.h" hash::sequenceAllocator* methods; void Init() { methods = new hash::sequenceAllocator[3]; methods[0] = hash::orderedSequence; methods[1] = hash::reversedSequence; methods[2] = hash::randomSequence2; } using std::cout; using std::endl; using std::fstream; using std::setprecision; using std::fixed; void Test(size_t MinKB, size_t MaxKB, float K) { Init(); const int sz = sizeof(int); //Килобайты перевожу в количество итераций // КБ * 1024 / sizeof(int) = Байты / sizeof(int) = количество итераций const size_t Min = MinKB * 1024 / sz; const size_t Max = MaxKB * 1024 / sz; const size_t RepeatCount = 20; double msec[3]; fstream csvFile = fstream("output.csv", std::ios::out); cout << "Size[KB]; Ordered; Reversed; Random" << endl; csvFile << "Size[KB];Ordered;Reversed;Random" << endl; for (size_t size = Min; size < Max; size*=K) { for (size_t m = 0; m < 3; m++) { int *arr = methods[m](size); hash::minimumTime(5, arr, size); // прогреваю кэш msec[m] = hash::minimumTime(RepeatCount,arr, size)/(double)size; // выполняю проход delete[] arr; } cout << size / (1024 / sz) << "; " << msec[0] << "; " << msec[1] << "; " << msec[2] << "; " << endl; csvFile << size / (1024 / sz) << ";" << setprecision(10) << fixed << msec[0] << ";" << setprecision(10) << fixed << msec[1] << ";" << setprecision(10) << fixed << msec[2] << ";" << endl; } csvFile.close(); } void main() { srand(time(0)); cout << "Min KB" << endl; size_t MinKB; std::cin >> MinKB; cout << "Max MB" << endl; float MaxMB; std::cin >> MaxMB; cout << "Growth coefficient" << endl; float K; std::cin >> K; Test(MinKB, 1024 * MaxMB, K); system("pause"); }
true
a50f8e9b9d7b89b4d38afa43046860bb5b70875d
C++
gcl8a/template
/list.h
UTF-8
23,148
3.109375
3
[]
no_license
/* * 16.07.21: added Pop() function to make FIFO queue * 12.05.16: added TListIterator::DeleteCurrent * 12.04.09: added GetFirst and GetLast() * 12.03.05: Add Jump() and JumpToFirst() methods * 12.03.04: added Find(string) method to list * 11/05/31: Add TSList, a sorted list * 11/05/31: general maintenance and upkeep -- it's been a while */ //TODO: Clean up Find and FindElement (which are now based too much on strings) //modified 02/28/01 /*\template\list.h contains basic direct and indirect lists Direct lists hold objects themselves, while indirect lists hold object pointers Each list has a double linked list of elements, which hold the objects or ptrs. */ #ifndef __TEMPLATE_LIST_H #define __TEMPLATE_LIST_H #ifndef __TEMPLATE_XERROR_H #include <template/xerror.h> #endif #include <string> template < class T > class TList; template < class T > class TListIterator; template < class T > class TListElement { public: T _tData; TListElement < T > * _ptNext; TListElement < T > * _ptPrev; protected: TListElement( void ) //: _tData(0) { _ptNext = 0; _ptPrev = 0; } TListElement( const T & t ) : _tData( t ) { _ptNext = 0; _ptPrev = 0; } int TestInvariant( void ) const; friend class TList < T >; friend class TListIterator < T >; }; template < class T > int TListElement < T >::TestInvariant(void) const { if (_ptNext) { if (_ptNext->_ptPrev != this) throw XError("Invariant error in TListElement!"); } if (_ptPrev) { if (_ptPrev->_ptNext != this) throw XError("Invariant error in TListElement!"); } return 0; } template < class T > class TList { protected: unsigned int _unItems; TListElement < T > * _ptHead; TListElement < T > * _ptTail; protected: virtual T* AddElement( TListElement < T > * ); virtual unsigned int DeleteElement( TListElement < T > * pt ); TListElement < T > * FindElement( const string & s ) const; //TListElement < T > * FindElement( const T & ) const; public: TList( void ) { _ptHead = _ptTail = 0; _unItems = 0; } TList( const TList < T > & tList ); TList < T > & operator = ( const TList < T > & tList ); virtual ~TList( void ) { Flush(); } T* Add( const T & t ) { return AddElement( new TListElement < T > ( t ) ); } T* GetHead(void) {if(_ptHead) return &_ptHead->_tData; else return NULL;} T* GetTail(void) {if(_ptTail) return &_ptTail->_tData; else return NULL;} /* unsigned int Delete( const T & t ) { TListElement < T > * ptElement = FindElement( t ); if ( ptElement ) return DeleteElement( ptElement ); else return -1; } */ T * Find( const T & t ) const { TListElement < T > * ptElement = FindElement( t ); if ( ptElement ) { return & ptElement->_tData; } else return 0; } T * Find( const string s ) const { TListElement < T > * ptElement = FindElement( s ); if ( ptElement ) { return & ptElement->_tData; } else return 0; } void Pop(void) //removes head from the list { if(_ptHead) { DeleteElement(_ptHead); } } int Flush( void ); int Destroy(void) {return Flush();} unsigned int GetItemsInContainer( void ) const { return _unItems; } unsigned int GetSize(void) {return GetItemsInContainer();} void TestInvariant( void ) const; void TestFullInvariant( void ) const; friend class TListIterator < T >; }; template < class T > T* TList < T >::AddElement( TListElement < T > * ptElement ) /*protected member function to add an element, with appropriate updating of prev, next, etc. */ { TestInvariant(); if ( !ptElement ) throw XError( "Error adding TListElement!" ); if ( _ptHead == 0 ) { _ptHead = _ptTail = ptElement; ptElement->_ptNext = 0; ptElement->_ptPrev = 0; ++_unItems; return &ptElement->_tData; } else { _ptTail->_ptNext = ptElement; ptElement->_ptPrev = _ptTail; ptElement->_ptNext = 0; _ptTail = ptElement; ++_unItems; return &ptElement->_tData; } } template<class T> unsigned int TList<T>::DeleteElement(TListElement<T> * ptElement) { TestInvariant(); if (!ptElement) throw XError("Error in TList<T>::DeleteElement!"); if (ptElement == _ptHead) { _ptHead = ptElement->_ptNext; } if (ptElement == _ptTail) { _ptTail = ptElement->_ptPrev; } if (ptElement->_ptPrev) ptElement->_ptPrev->_ptNext = ptElement->_ptNext; if (ptElement->_ptNext) ptElement->_ptNext->_ptPrev = ptElement->_ptPrev; delete ptElement; --_unItems; return 0; } /* template < class T > TListElement < T > * TList < T >::FindElement( const T & t ) const //returns a pointer to the element if found //returns NULL if not found { TListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( ptCurrent->_tData == t ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } */ template < class T > TListElement < T > * TList < T >::FindElement( const string & s ) const //returns a pointer to the element if found //returns NULL if not found { TListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( ptCurrent->_tData == s ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } template < class T > TList < T >::TList( const TList < T > & tList ) { _ptHead = 0; _ptTail = 0; _unItems = 0; TListElement < T > * ptCurrent = tList._ptHead; while ( ptCurrent ) { Add( ptCurrent->_tData ); ptCurrent = ptCurrent->_ptNext; } TestInvariant(); } template < class T > TList < T > & TList < T >::operator = ( const TList < T > & tList ) { _ptHead = 0; _ptTail = 0; _unItems = 0; TListElement < T > * ptCurrent = tList._ptHead; while ( ptCurrent ) { Add( ptCurrent->_tData ); ptCurrent = ptCurrent->_ptNext; } TestInvariant(); return * this; } template < class T > int TList < T >::Flush( void ) { TListElement < T > * ptCurrent; while (( ptCurrent = _ptHead )) { DeleteElement( ptCurrent ); } if ( _ptHead != 0 || _ptTail != 0 ) throw XError( "Error flushing TList!" ); TestInvariant(); return _unItems; } template < class T > void TList < T >::TestInvariant( void ) const { if ( _ptHead == 0 ) { if ( _ptTail || _unItems ) throw XError( "Invariant error in TList!" ); } else { if ( _ptHead == _ptTail && _unItems != 1 ) throw XError( "Invariant error in TList!" ); if ( _ptHead != _ptTail && _unItems <= 1 ) throw XError( "Invariant error in TList!" ); } } template < class T > void TList < T >::TestFullInvariant( void ) const { TestInvariant(); if ( !_unItems ) return; _ptHead->TestInvariant(); _ptTail->TestInvariant(); unsigned int unItems = 0; TListElement < T > * ptCurrent = _ptHead; if ( ptCurrent->_ptPrev ) throw XError( "Long invariant error in TList!" ); while ( ptCurrent != _ptTail ) { unItems++; ptCurrent->TestInvariant(); ptCurrent = ptCurrent->_ptNext; } if ( ++unItems != _unItems ) throw XError( "Long invariant error in TList!" ); if ( ptCurrent->_ptNext ) throw XError( "Long invariant error in TList!" ); while ( --unItems ) { ptCurrent = ptCurrent->_ptPrev; } if ( ptCurrent != _ptHead ) throw XError( "Long invariant error in TList!" ); } template < class T > class TListIterator { private: protected: TListElement < T > * _ptCurrent; TList < T > * _ptList; public: TListIterator(TList < T > & tList) { _ptList = &tList; Restart(); } operator int() { return _ptCurrent ? 1 : 0; } T * Restart(void) { _ptCurrent = _ptList->_ptHead; return Current(); } T * Last(void) { _ptCurrent = _ptList->_ptTail; return Current(); } T * Current(void) { if (_ptCurrent) return & _ptCurrent->_tData; else return NULL; } unsigned int DeleteCurrent(void) /* * deletes the current element and moves current to the next element */ { if (_ptCurrent) { TListElement < T > * next = _ptCurrent->_ptNext; _ptList->DeleteElement(_ptCurrent); _ptCurrent = next; return 0; } else return -1; } T * operator ++(int) { if (_ptCurrent) { TListElement < T > * current = _ptCurrent; _ptCurrent = _ptCurrent->_ptNext; return & current->_tData; } else return 0; } T* Jump(int jump_step) { if(jump_step >0) for(int i = 0; i < jump_step; i++) if(_ptCurrent) _ptCurrent = _ptCurrent->_ptNext; return (operator ++()); } T* JumpToFirst(const T& t) { //quickly finds the first occurrence Restart(); while (_ptCurrent) { if (t > *_ptCurrent->_tData) return _ptCurrent->_tData; _ptCurrent = _ptCurrent->_ptNext; } return NULL; } }; template < class T > class TSList : public TList<T> { public: virtual T* AddElement( TListElement < T > * ); virtual T* FindFirst(const T&); }; template < class T > T* TSList < T >::AddElement(TListElement < T > * ptElement) /*protected member function to add an element, with appropriate updating of prev, next, etc. SORTED! */ { TList<T>::TestInvariant(); if (!ptElement) throw XError("Error adding element in TSList::AddElement!"); //start at the END and work backwards TListElement < T > * current = TList<T>::_ptTail; while (current) { if (ptElement->_tData > current->_tData) { if (current == TList<T>::_ptTail) TList<T>::_ptTail = ptElement; if (current -> _ptNext) current -> _ptNext -> _ptPrev = ptElement; ptElement -> _ptNext = current -> _ptNext; current -> _ptNext = ptElement; ptElement->_ptPrev = current; ++TList<T>::_unItems; return &ptElement->_tData; } current = current->_ptPrev; } //if we've made it here, then add before the head if (TList<T>::_ptHead == 0) { TList<T>::_ptHead = TList<T>::_ptTail = ptElement; ptElement->_ptNext = 0; ptElement->_ptPrev = 0; ++TList<T>::_unItems; return &ptElement->_tData; } else { ptElement->_ptNext = TList<T>::_ptHead; ptElement->_ptPrev = 0; TList<T>::_ptHead->_ptPrev = ptElement; TList<T>::_ptHead = ptElement; ++TList<T>::_unItems; return &ptElement->_tData; } } template < class T > T* TSList < T >::FindFirst(const T& t) { TListElement < T > * ptCurrent = TList<T>::_ptHead; while (ptCurrent) { if (t > ptCurrent->_tData) return &ptCurrent->_tData; ptCurrent = ptCurrent->_ptNext; } return NULL; } template < class T > class TIList; template < class T > class TIListIterator; template < class T > class TIListElement /*TIListElement implements a list element for storing indirect lists Note that the element holds a pointer to T but does not delete it automatically upon destruction. Also, copying is done of the pointer only, not the underlying object */ { private: T * _ptData; TIListElement < T > * _ptNext; TIListElement < T > * _ptPrev; protected: TIListElement( void ) { _ptNext = 0; _ptPrev = 0; _ptData = 0; } TIListElement( T * pt ) : _ptData( pt ) { _ptNext = 0; _ptPrev = 0; } TIListElement( const TIListElement & tElement ) : _ptData( tElement._ptData ) //copies address, not contents { _ptPrev = 0; _ptNext = 0; } TIListElement & operator = ( const TIListElement & tElement ) { _ptData = tElement._ptData; //copies address, not contents _ptPrev = 0; _ptNext = 0; return * this; } ~TIListElement( void ) //NOTE! NO AUTOMATIC DELETE! { } void TestInvariant( void ) const; friend class TIList < T >; friend class TIListIterator < T >; }; template < class T > void TIListElement < T >::TestInvariant( void ) const { if ( _ptNext ) { if ( _ptNext->_ptPrev != this ) throw XError( "Invariant error in TIListElement!" ); } if ( _ptPrev ) { if ( _ptPrev->_ptNext != this ) throw XError( "Invariant error in TIListElement!" ); } if ( !_ptData ) throw XError( "Invariant error in TIListElement!" ); } template < class T > class TIList /*Implements an indirect list */ { private: unsigned int _unItems; TIListElement < T > * _ptHead; TIListElement < T > * _ptTail; protected: unsigned int AddElement( TIListElement < T > * ); unsigned int DetachElement( TIListElement < T > * ); unsigned int DeleteElement( TIListElement < T > * ); TIListElement < T > * FindElement( const T * pt ) const; //compares addresses TIListElement < T > * FindElement( const T & t ) const; //compares contents TIListElement < T > * FindElement( const string & s ) const; //compares string TIListElement < T > * FindOppositeElement( const T & t ) const; //requires ^ operator friend class TIListIterator < T >; public: TIList( void ) { _ptHead = _ptTail = 0; _unItems = 0; } TIList( const TIList < T > & tList ); TIList < T > & operator = ( const TIList < T > & tList ); ~TIList( void ) { Flush(); } unsigned int Add( const TIList < T > & ); unsigned int Add(T * pt) { #ifdef __VALIDATE__ TestInvariant(); #endif return AddElement(new TIListElement<T> (pt)); } unsigned int Detach( const T * pt ) { TIListElement < T > * ptiElement = FindElement( pt ); if ( ptiElement ) return DetachElement( ptiElement ); else return 0; } unsigned int Detach( const T & t ) { TIListElement < T > * ptiElement = FindElement( t ); if ( ptiElement ) return DetachElement( ptiElement ); else return 0; } unsigned int DetachOpposite( const T & t ) { TIListElement < T > * ptiElement = FindOppositeElement( t ); if ( ptiElement ) return DetachElement( ptiElement ); else return 0; } unsigned int Delete( const T * pt ) { TIListElement < T > * ptiElement = FindElement( pt ); if ( ptiElement ) return DeleteElement( ptiElement ); else return 0; } unsigned int Delete( const T & t ) { TIListElement < T > * ptiElement = FindElement( t ); if ( ptiElement ) return DeleteElement( ptiElement ); else return 0; } T * Find( const T * pt ) { TIListElement < T > * ptElement = FindElement( pt ); if ( ptElement ) { return ptElement->_ptData; } else return 0; } T * Find( const T & t ) { TIListElement < T > * ptElement = FindElement( t ); if ( ptElement ) { return ptElement->_ptData; } else return 0; } T * Find( const string & s ) { TIListElement < T > * ptElement = FindElement( s ); if ( ptElement ) { return ptElement->_ptData; } else return 0; } T * FindOpposite( const T & t ) { TIListElement < T > * ptElement = FindOppositeElement( t ); if ( ptElement ) { return ptElement->_ptData; } else return 0; } T * GetFirst( void ) { return _ptHead->_ptData; } T * GetRandomItem( void ); int Flush( void ); int Purge( void ); int Destroy( void ) { return Purge(); } unsigned int GetItemsInContainer( void ) const { return _unItems; } void TestInvariant( void ) const; void TestFullInvariant( void ) const; }; template < class T > TIListElement < T > * TIList < T >::FindElement( const T * pt ) const //returns a pointer to the element if found using pointer comparison //returns NULL if not found { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( ptCurrent->_ptData == pt ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } template < class T > TIListElement < T > * TIList < T >::FindElement( const T & t ) const //returns a pointer to the element if found using value comparison //returns NULL if not found { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( * (ptCurrent->_ptData) == t ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } template < class T > TIListElement < T > * TIList < T >::FindElement( const string & s ) const //returns a pointer to the element if found using value comparison //returns NULL if not found { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( * (ptCurrent->_ptData) == s ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } template < class T > TIListElement < T > * TIList < T >::FindOppositeElement( const T & t ) const //returns a pointer to the element if found using ^ operator //returns NULL if not found { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { if ( * ptCurrent->_ptData ^ t ) return ptCurrent; ptCurrent = ptCurrent->_ptNext; } return 0; } template < class T > unsigned int TIList < T >::AddElement( TIListElement < T > * ptElement ) { TestInvariant(); if ( !ptElement ) throw XError( "Error in TIList<T>::AddElement!" ); if ( _ptHead == 0 ) { _ptHead = _ptTail = ptElement; ptElement->_ptNext = 0; ptElement->_ptPrev = 0; return ++_unItems; } else { _ptTail->_ptNext = ptElement; ptElement->_ptPrev = _ptTail; ptElement->_ptNext = 0; _ptTail = ptElement; return ++_unItems; } } template < class T > unsigned int TIList < T >::DetachElement( TIListElement < T > * ptElement ) //remove data without deleting pointer { TestInvariant(); if ( ptElement == _ptHead ) { _ptHead = ptElement->_ptNext; } if ( ptElement == _ptTail ) { _ptTail = ptElement->_ptPrev; } if ( ptElement ) { if ( ptElement->_ptPrev ) ptElement->_ptPrev->_ptNext = ptElement->_ptNext; if ( ptElement->_ptNext ) ptElement->_ptNext->_ptPrev = ptElement->_ptPrev; delete ptElement; --_unItems; return 1; } else throw XError( "Error in TIList<T>::DetachElement!" ); } template < class T > unsigned int TIList < T >::DeleteElement( TIListElement < T > * ptElement ) //removes data, deleting pointer and freeing memory { TestInvariant(); if ( ptElement == _ptHead ) { _ptHead = ptElement->_ptNext; } if ( ptElement == _ptTail ) { _ptTail = ptElement->_ptPrev; } if ( ptElement ) { if ( ptElement->_ptPrev ) ptElement->_ptPrev->_ptNext = ptElement->_ptNext; if ( ptElement->_ptNext ) ptElement->_ptNext->_ptPrev = ptElement->_ptPrev; delete ptElement->_ptData; delete ptElement; --_unItems; return 1; } else return 0; } template < class T > TIList < T >::TIList( const TIList < T > & tiList ) { _ptHead = 0; _ptTail = 0; _unItems = 0; TIListElement < T > * ptCurrent = tiList._ptHead; while ( ptCurrent ) { Add( ptCurrent->_ptData ); ptCurrent = ptCurrent->_ptNext; } TestInvariant(); } template < class T > TIList < T > & TIList < T >::operator = ( const TIList < T > & tiList ) { _ptHead = 0; _ptTail = 0; _unItems = 0; TIListElement < T > * ptCurrent = tiList._ptHead; while ( ptCurrent ) { Add( ptCurrent->_ptData ); ptCurrent = ptCurrent->_ptNext; } TestInvariant(); return * this; } template < class T > unsigned int TIList < T >::Add( const TIList < T > & tiList ) /*adds all of the pointers from one list to another */ { TIListElement < T > * ptCurrent = tiList._ptHead; while ( ptCurrent ) { Add( ptCurrent->_ptData ); ptCurrent = ptCurrent->_ptNext; } TestInvariant(); return _unItems; } template < class T > int TIList < T >::Flush( void ) //flushes without deleting pointers { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { DetachElement( ptCurrent ); ptCurrent = _ptHead; } if ( _ptHead != 0 || _ptTail != 0 ) throw XError( "Error flushing TIList!" ); TestInvariant(); return 1; } template < class T > int TIList < T >::Purge( void ) //flushes and deletes pointers { TIListElement < T > * ptCurrent = _ptHead; while ( ptCurrent ) { DeleteElement( ptCurrent ); ptCurrent = _ptHead; } if ( _ptHead != 0 || _ptTail != 0 ) throw XError( "Error flushing TIList!" ); TestInvariant(); return 1; } template < class T > T * TIList < T >::GetRandomItem( void ) { if ( !GetItemsInContainer() ) return 0; int nRandom = random( GetItemsInContainer() ); TIListElement < T > * ptCurrent = _ptHead; while ( nRandom-- ) { ptCurrent = ptCurrent->_ptNext; } return ptCurrent->_ptData; } template < class T > void TIList < T >::TestInvariant( void ) const { if ( _ptHead == 0 ) { if ( _ptTail || _unItems ) throw XError( "Invariant error in TIList!" ); } else { if ( _ptHead == _ptTail && _unItems != 1 ) throw XError( "Invariant error in TIList!" ); if ( _ptHead != _ptTail && _unItems <= 1 ) throw XError( "Invariant error in TIList!" ); } } template < class T > void TIList < T >::TestFullInvariant( void ) const { TestInvariant(); if ( !_unItems ) return; _ptHead->TestInvariant(); _ptTail->TestInvariant(); unsigned int unItems = 0; TIListElement < T > * ptCurrent = _ptHead; if ( ptCurrent->_ptPrev ) throw XError( "Long invariant error in TIList!" ); while ( ptCurrent != _ptTail ) { unItems++; ptCurrent->TestInvariant(); ptCurrent = ptCurrent->_ptNext; } if ( ++unItems != _unItems ) throw XError( "Long invariant error in TIList!" ); if ( ptCurrent->_ptNext ) throw XError( "Long invariant error in TIList!" ); while ( --unItems ) { ptCurrent = ptCurrent->_ptPrev; } if ( ptCurrent != _ptHead ) throw XError( "Long invariant error in TIList!" ); } template < class T > class TIListIterator { private: protected : TIListElement < T > * _ptiCurrent; TIList < T > * _ptiList; public: TIListIterator( TIList < T > & tiList ) { _ptiList = & tiList; Restart(); } T * Restart( void ) { _ptiCurrent = _ptiList->_ptHead; return _ptiCurrent ? _ptiCurrent->_ptData : 0; } T * Current( void ) { return _ptiCurrent ? _ptiCurrent->_ptData : 0; } T * operator ++ ( int ) { if ( _ptiCurrent ) { T* curr = _ptiCurrent->_ptData; _ptiCurrent = _ptiCurrent->_ptNext; return curr; } else return 0; } }; #endif
true
e016c655d4e3dd0935b30414114ffbd52b766b8c
C++
ConnorOfLocke/3D_Math_Library
/NewThing/colour.cpp
UTF-8
7,605
3.046875
3
[]
no_license
#include "colour.h" colour::colour() : r(1.0f), g(1.0f), b(1.0f), a(1.0f) { } colour::colour(float a_r, float a_g, float a_b, float a_a) { //intresting way of setting of clamping between 1 and 0 if (a_r > 0.0f) r = (a_r > 1.0f) ? 1.0f: a_r; else r = 0.0f; if (a_g > 0.0f) g = (a_g > 1.0f) ? 1.0f: a_g; else g = 0.0f; if (a_b > 0.0f) b = (a_b > 1.0f) ? 1.0f: a_b; else b = 0.0f; if (a_a > 0.0f) a = (a_a > 1.0f) ? 1.0f: a_a; else a = 0.0f; } colour::colour(float a_r, float a_g, float a_b) { //intresting way of setting of clamping between 1 and 0 if (a_r > 0.0f) r = (a_r > 1.0f) ? 1.0f: a_r; else r = 0.0f; if (a_g > 0.0f) g = (a_g > 1.0f) ? 1.0f: a_g; else g = 0.0f; if (a_b > 0.0f) b = (a_b > 1.0f) ? 1.0f: a_b; else b = 0.0f; a = 1.0f; } colour::colour(unsigned int a_r, unsigned int a_g, unsigned int a_b, unsigned int a_a) { r = (a_r/255.0f < 1.0f) ? a_r/255.0f : 1.0f; g = (a_g/255.0f < 1.0f) ? a_g/255.0f : 1.0f; b = (a_b/255.0f < 1.0f) ? a_b/255.0f : 1.0f; a = (a_a/255.0f < 1.0f) ? a_a/255.0f : 1.0f; } colour::colour(unsigned int a_r, unsigned int a_g, unsigned int a_b) { r = (a_r/255.0f < 1.0f) ? a_r/255.0f : 1.0f; g = (a_g/255.0f < 1.0f) ? a_g/255.0f : 1.0f; b = (a_b/255.0f < 1.0f) ? a_b/255.0f : 1.0f; a = 1.0f; } colour::colour(colour& other) { r = other.a; g = other.g; b = other.b; a = other.a; } colour::colour(vec4& other) { r = other.x; g = other.y; b = other.z; a = other.w; } colour& colour::operator=(colour &other) { r = other.r; g = other.g; b = other.b; a = other.a; return *this; } colour& colour::operator=(vec4 &other) { r = other.x; g = other.y; b = other.z; a = other.w; return *this; } vec3 colour::getHSL() { //going off http://www.easyrgb.com/index.php?X=MATH&H=18#text18 float H,S,L; //gets the max and min values float minVal = r; float maxVal = r; if (g < minVal) minVal = g; if (g > maxVal) maxVal = g; if (b < minVal) minVal = b; if (b > maxVal) maxVal = b; int diffVal =(int)( maxVal - minVal); //LIGHTNESS L = ( maxVal + minVal ) / 2; if ( diffVal == 0 ) //This is a gray, no chroma... H = S = 0; else { //SATURATION if ( L <= 127.5f ) S = diffVal / ( maxVal + minVal); else S = diffVal / ( 2 - maxVal - minVal ); float del_R = ( ( ( maxVal - r ) / 6.0f ) + ( maxVal / 2.0f ) ) / maxVal; float del_G = ( ( ( maxVal - g ) / 6.0f ) + ( maxVal / 2.0f ) ) / maxVal; float del_B = ( ( ( maxVal - b ) / 6.0f ) + ( maxVal / 2.0f ) ) / maxVal; if ( r == maxVal) H = del_B - del_G; else if ( g == maxVal ) H = ( 1.0f / 3.0f ) + del_R - del_B; else if ( b == maxVal ) H = ( 2.0f / 3.0f ) + del_G - del_R; if ( H < 0 ) H += 1; if ( H > 1 ) H -= 1; } return vec3(H,S,L); //L from 0 to 1 } void colour::setHSL(float Hue, float Saturation, float Lightness) { //Going from http://www.easyrgb.com/index.php?X=MATH&H=19#text19 if ( Saturation == 0 ) //monochromatic { r = Lightness; g = Lightness; b = Lightness; } else { float Input1, Input2; if ( Lightness < 0.5 ) Input2 = Lightness * ( 1 + Saturation ); else Input2 = Lightness + Saturation - Saturation*Lightness; Input1 = 2 * Lightness - Input2; r = HueToRGB( Input1, Input2, Hue + ( 1.0f / 3.0f ) ); g = HueToRGB( Input1, Input2, Hue ); b = HueToRGB( Input1, Input2, Hue - ( 1.0f / 3.0f ) ); int llmaa = 1; } } float colour::HueToRGB(float v1, float v2, float vH) { if ( vH < 0 ) vH += 1.0f; if ( vH > 1 ) vH -= 1.0f; if ( vH < 1.0f/6.0f ) return v1 + ( v2 - v1 ) * 6.0f * vH ; if ( vH < 1.0f/2.0f ) return v2 ; if ( vH < 2.0f/3.0f ) return v1 + ( v2 - v1 ) * ( 2.0f / 3.0f - vH ) * 6.0f; return v1; } float colour::Hue() { return getHSL().x; } void colour::SetHue(float a_fHue) { vec3 curHSL = getHSL(); setHSL(a_fHue, curHSL.y, curHSL.z); } float colour::Saturation() { return getHSL().y; } void colour::SetSaturation(float a_fSaturation) { vec3 curHSL = getHSL(); setHSL(curHSL.x, a_fSaturation, curHSL.z); } float colour::Lightness() { return getHSL().z; } void colour::SetLightness(float a_fLightness) { vec3 curHSL = getHSL(); setHSL(curHSL.x, curHSL.y, a_fLightness); } colour colour::Lerp(colour Original, colour nextColour, float t) { return Original*(t-1) + nextColour*t; } colour colour::Red() { return colour(1.0f, 0.0f, 0.0f, 1.0f); } colour colour::Green() { return colour(0.0f, 1.0f, 0.0f, 1.0f); } colour colour::Blue() { return colour(0.0f, 0.0f, 1.0f, 1.0f); } colour colour::Magenta() { return colour(1.0f, 0.0f, 1.0f, 1.0f); } colour colour::Cyan() { return colour(0.0f, 1.0f, 1.0f, 1.0f); } colour colour::Yellow() { return colour(1.0f, 1.0f, 0.0f, 1.0f); } colour colour::NiceYellow() { return colour(1.0f, 0.92f, 0.016f, 1.0f); } colour colour::Black() { return colour(0.0f, 0.0f, 0.0f, 1.0f); } colour colour::Grey() { return colour(0.5f, 0.5f, 0.5f, 1.0f); } colour colour::White() { return colour(1.0f, 1.0f, 1.0f, 1.0f); } colour colour::Transparent() { return colour(1.0f, 1.0f, 1.0f, 0.5f); } colour colour::Clear() { return colour(0.0f, 0.0f, 0.0f, 0.0f); } //operators colour colour::operator + (colour rhs) { return colour(r + rhs.r, g + rhs.g, b + rhs.b, a + rhs.a); } colour colour::operator - (colour rhs) { return colour(r - rhs.r, g - rhs.g, b - rhs.b, a - rhs.a); } colour colour::operator + (vec4 rhs) { return colour(r + rhs.x, g + rhs.y, b + rhs.z, a + rhs.w); } colour colour::operator - (vec4 rhs) { return colour(r - rhs.x, g - rhs.y, b - rhs.z, a - rhs.w); } colour colour::operator * (float scalar) { return colour(r *scalar, g *scalar, b *scalar, a * scalar); } colour colour::operator / (float scalar) { return colour(r / scalar, g / scalar, b / scalar, a / scalar); } colour& colour::operator += (colour rhs) { r = a + rhs.r; g = g + rhs.g; b = b + rhs.b; a = a + rhs.a; return *this; } colour& colour::operator -= (colour rhs) { a = a - rhs.a; g = g - rhs.g; b = b - rhs.b; a = a - rhs.a; return *this; } colour& colour::operator += (vec4 rhs) { a = a + rhs.x; g = g + rhs.y; b = b + rhs.z; a = a + rhs.w; return *this; } colour& colour::operator -= (vec4 rhs) { a = a - rhs.x; g = g - rhs.y; b = b - rhs.z; a = a - rhs.w; return *this; } colour& colour::operator *= (float scalar) { a = a * scalar; g = g * scalar; b = b * scalar; a = a * scalar; return *this; } colour& colour::operator /= (float scalar) { a = a / scalar; g = g / scalar; b = b / scalar; a = a / scalar; return *this; } bool colour::operator == (colour rhs) { return (r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); } bool colour::operator != (colour rhs) { return !(r == rhs.r && g == rhs.g && b == rhs.b && a == rhs.a); } bool colour::operator == (vec4 rhs) { return (r == rhs.x && g == rhs.y && b == rhs.z && a == rhs.w); } bool colour::operator != (vec4 rhs) { return !(r == rhs.x && g == rhs.y && b == rhs.z && a == rhs.w); } std::ostream& operator << (std::ostream& stream, const colour& target) { std::string returnString; unsigned int new_r = ((int)target.r * 255); unsigned int new_g = ((int)target.g * 255); unsigned int new_b = ((int)target.b * 255); unsigned int new_a = ((int)target.a * 255); stream << "Colour: 0x" << std::hex << new_r << std::hex << new_g << std::hex << new_b << std::hex << new_a; return stream; } float* colour::ToArray() { float* returnArray = new float[4]; returnArray[0] = r; returnArray[1] = g; returnArray[2] = b; returnArray[3] = a; return returnArray; }
true
20a98c50aec6b07e8fddd1cd20d44b3da4e62b67
C++
nikakogho/codeforces
/Problems/899A.cpp
UTF-8
295
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n, ones = 0; cin >> n; for(int i = 0; i < n; i++) { short x; cin >> x; ones += x == 1; } int twos = n - ones; int min = twos > ones ? ones : twos; int teams = min; ones -= min; teams += ones / 3; cout << teams; }
true
eef5f950e1ce0ebacddea8353752ad2fa9ab9ad4
C++
mirgk/seat_assignment
/src/commondata.h
UTF-8
1,177
3.3125
3
[]
no_license
#ifndef COMMON_DATA_H #define COMMON_DATA_H #include <string> namespace seat_assignment { namespace data { /*! * \brief Represents a passenger. * Uses compiler generated copy constructor and assignment operator. */ struct Passenger { std::string mID; std::string mName; std::string mSurname; Passenger() : mID(""), mName(""), mSurname("") {} Passenger(const Passenger&) = default; Passenger& operator=(const Passenger&) = default; }; /*! * \brief Represents an aircraft. * Default constructor creates an aircraft without any id and seats. * Uses compiler generated copy constructor and assignment operator. */ struct AirCraft { std::string mID; int mRowCount; int mColumnCount; AirCraft() : mID(""), mRowCount(0), mColumnCount(0) {} AirCraft(const AirCraft&) = default; AirCraft& operator=(const AirCraft&) = default; }; } } #endif
true
96ca27e49b6af916de173c77a4e5a22478c8d0d1
C++
xgc820313/npapi-mdns
/project/_old/usocket.h
UTF-8
1,338
3.0625
3
[]
no_license
/** * @file usocket.h * * Created on: 2009-11-05 * Author: jldupont */ #ifndef USOCKET_H_ #define USOCKET_H_ #include <string> using namespace std; /** * uSocket Exception Class */ class uSocketException { public: /** * Create with an `errno` */ uSocketException( int _err ) { err = _err; } uSocketException( std::string s ) { m_desc=s; } ~uSocketException(); /** * Returns the last `errno` */ int getError(void) { return err; } private: std::string m_desc; int err; }; /** * Unix domain socket */ class uSocket { protected: // sockets[0] is always used when serving // sockets[1] is sent to the peer int sockets[2]; bool status; int code; std::string ibuffer; public: /** * Creates a socket pair */ uSocket(); /** * Creates a single socket */ uSocket(int s); ~uSocket(); /** * Returns the socket handle * that should be used by the peer */ int getPeerSocket(void); int getLastError(void); /** * Pops a "message" from the queue * * @throws uSocketException */ std::string popmsg(void); /** * Pushes a "message" in the queue * * @throws uSocketException */ void pushmsg(std::string msg); protected: std::string popFromBuffer(void); }; #endif /* USOCKET_H_ */
true
7c7027671ff3c1182bb107d098cf972d421f197a
C++
turi-code/GraphLab-Create-SDK
/graphlab/cppipc/common/authentication_base.hpp
UTF-8
2,983
2.921875
3
[ "BSD-3-Clause" ]
permissive
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef CPPIPC_COMMON_AUTHENTICATION_BASE_HPP #define CPPIPC_COMMON_AUTHENTICATION_BASE_HPP #include <string> #include <graphlab/cppipc/common/message_types.hpp> namespace cppipc { /** * Base class for all authentication method implementations. * * The class implements a few basic functions to attach and validate messages * sent between the client and the server. Messages sent from the client to * the server are \ref call_message objects. Messages sent from the server * to the client (in response to a call message) are \ref reply_message * objects. * * \ref authentication_base::apply_auth(call_message& msg) is called on the * client side to attach authentication information to the message. When the * server receives the message, * \ref authentication_base::validate_auth(call_message& msg) is called on the * server side to validate the message. If this function returns false, the * server discards the message. * The server then replies with a \ref reply_message and the function * \ref authentication_base::apply_auth(reply_message& msg) is called on the * server side to attach authentication information to the message. When the * client receives the message, * \ref authentication_base::validate_auth(reply_message& msg) is called on the * client side to validate the message. If this function returns false, the * function call is marked as failed. * * All of the implemented functions must be reentrant, and must not assume * synchronicity. (i.e. apply_auth can be called on the client side many * times in succession). * * Finally, authentication methods should be designed to be "stackable" with * other authentication methods. i.e. I should be able to apply two different * types of authentication methods on top of each other. */ class authentication_base { public: virtual inline ~authentication_base(){} /** * Attaches the authentication information to a message sent * from the client to the server. This function must be reentrant. */ virtual void apply_auth(call_message& msg) = 0; /** * Attaches the authentication information to a message sent * from the server to the client. This function must be reentrant. */ virtual void apply_auth(reply_message& msg) = 0; /** * Validates a message received on the server from a client. This function * must be reentrant. If the function returns true, the message is good. * Otherwise, the message is bad. */ virtual bool validate_auth(call_message& msg) = 0; /** * Validates a message received on the client from a server. This function * must be reentrant. If the function returns true, the message is good. * Otherwise, the message is bad. */ virtual bool validate_auth(reply_message& msg) = 0; }; } // cppipc #endif
true
8ad2e58f7da76cf70fb80633f23db7f5693ba2be
C++
ankan-ekansh/Competitive-Programming
/DEC18B/comas.cpp
UTF-8
1,728
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main(){ // #ifndef ONLINE_JUDGE // freopen("input.txt", "rt", stdin); // freopen("output.txt", "wt", stdout); // #endif ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; vector<int> v; while(t--){ int n; cin>>n; for(int i=1;i<=n-4;i++){ cout<<"? "<<i<<" "<<i+1<<" "<<i+2<<" "<<i+3<<" "<<i+4<<endl<<flush; int a,b; cin>>a>>b; v.push_back(a); v.push_back(b); } sort(v.begin(), v.end()); vector<int>::iterator ip; ip=unique(v.begin(),v.begin()+(n-4)*2); v.resize(distance(v.begin(), ip)); int s = v.size()/sizeof(int); int r=n-s; vector<int> v2; for(int i=0;i<s;i++){ v2.push_back(v[i]); } for(int i=0;i<s;i++){ for(int j=n-r;j<=n;j++){ cout<<"? "<<v[i]<<" "<<v[i+1]<<" "<<v[i+2]<<" "<<j<<" "<<j+1<<endl<<flush; int a,b; cin>>a>>b; v2.push_back(a); v2.push_back(b); } } vector<int>::iterator ip2; ip2=unique(v2.begin(),v2.begin()+(r+1)*2); sort(v2.begin(),v2.end()); v2.resize(distance(v.begin(),ip)); int s2=v2.size()/sizeof(int); for(int i=1;i<=n;i++){ for(int j=0;j<s2;j++){ if(i!=v2[j]){ cout<<"! "<<i<<endl<<flush; exit(0); } } } } #ifndef ONLINE_JUDGE cout<<"\nTime Elapsed : " << 1.0*clock() / CLOCKS_PER_SEC << " s\n"; #endif return 0; }
true
8e9d63bd36249ced280dc23a669679e4bdccfb21
C++
oscardh97/figure2d
/triangle.h
UTF-8
311
2.703125
3
[]
no_license
#pragma once #include "figure2d.h" #include "pointer.h" #include <string> using std::string; class Triangle : public Figure2D{ Pointer p1, p2, p3; double a, b, c; public: Triangle(Pointer, Pointer, Pointer); virtual ~Triangle(); double area()const; double perimeter()const; string toString()const; };
true
0dbca3e4be769ffc58ffef87930fbd17d1591263
C++
ChaofanChen/ogs5_bhe
/MSH/TM/dtm_plane.cpp
UTF-8
2,205
2.75
3
[]
no_license
/* dtm_plane.cpp >Plane class last update : 2003.11.24 */ #include "stdafx.h" /* MFC */ #include "dtm_plane.h" namespace dtm { // Plane ///03.11.24 Plane::Plane(Point* p0,Point* p1,Point* p2) { double x0,y0,z0; double x1,y1,z1; double x2,y2,z2; x0 = p0->getX(); y0 = p0->getY(); z0 = p0->getZ(); x1 = p1->getX(); y1 = p1->getY(); z1 = p1->getZ(); x2 = p2->getX(); y2 = p2->getY(); z2 = p2->getZ(); plane_vector[0] = y0 * z1 + y1 * z2 + y2 * z0 - y0 * z2 - y1 * z0 - y2 * z1; plane_vector[1] = z0 * x1 + z1 * x2 + z2 * x0 - z0 * x2 - z1 * x0 - z2 * x1; plane_vector[2] = x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1; /*//change basic vector double dist; dist = vect[0]*vect[0] + vect[1]*vect[1] + vect[2]*vect[2]; dist = sqrt(dist); vect[0] = vect[0]/dist; vect[1] = vect[1]/dist; vect[2] = vect[2]/dist; */ ///////////////////// plane_vector[3] = -plane_vector[0] * x0 - plane_vector[1] * y0 - plane_vector[2] * z0; } // setVector ///03.11.24 void Plane::setVector(Point* p0,Point* p1,Point* p2) { double x0,y0,z0; double x1,y1,z1; double x2,y2,z2; double a,b,c,d; x0 = p0->getX(); y0 = p0->getY(); z0 = p0->getZ(); x1 = p1->getX(); y1 = p1->getY(); z1 = p1->getZ(); x2 = p2->getX(); y2 = p2->getY(); z2 = p2->getZ(); a = y0 * z1 + y1 * z2 + y2 * z0 - y0 * z2 - y1 * z0 - y2 * z1; b = z0 * x1 + z1 * x2 + z2 * x0 - z0 * x2 - z1 * x0 - z2 * x1; c = x0 * y1 + x1 * y2 + x2 * y0 - x0 * y2 - x1 * y0 - x2 * y1; /*//change basic vector double dist; dist = a*a+b*b+c*c; dist = sqrt(dist); a = a/dist; b = b/dist; c = c/dist; */ ///////////////////// d = -1. * (a * x0 + b * y0 + c * z0); plane_vector[0] = a; plane_vector[1] = b; plane_vector[2] = c; plane_vector[3] = d; } } //////////////////////////////////////////////////////////////////EOF
true
11092d6a61aafce1af1fb7d60d2bbc23ecb5e9c4
C++
YorickBrain/BWT
/Sa.cpp
GB18030
3,477
2.78125
3
[]
no_license
int leq(int a1, int a2, int b1, int b2) //ıȽ { return (a1 < b1 || a1 == b1 && a2 < b2); } int leq(int a1, int a2, int a3, int b1, int b2, int b3) //ıȽ { return (a1 < b1 || a1 == b1 && leq(a2, a3, b2, b3)); } //stably sort a[0 .. n -1] to b[0 .. n-1] , with keys in 0 ... K from r static void radixPass(int * a, int *b, int * r, int n, int K) // { int * c = new int[K + 1]; int i, sum; for (i = 0; i <= K; i++) { c[i] = 0; } for (i = 0; i < n; i++) { c[r[a[i]]]++; } for (i = 0, sum = 0; i <= K; i++) { int t = c[i]; c[i] = sum; sum += t; } for (i = 0; i < n; i++) { b[c[r[a[i]]]++] = a[i]; } delete[] c; } void suffixArray(int * T, int *SA, int n, int K) //DC3 { int n0 = (n + 2) / 3, n1 = (n + 1) / 3, n2 = n / 3, n02 = n0 + n2; // printf("n= %d ,n0 = %d , n1 = %d ,n2 = %d,n02 = %d \n",n,n0 ,n1, n2,n02); //n0,n1,n2,n02ָʲô˼أ int *R = new int[n02 + 3]; R[n02] = R[n02 + 1] = R[n02 + 2] = 0; int *SA12 = new int[n02 + 3]; SA12[n02] = SA12[n02 + 1] = SA12[n02 + 2] = 0; int *R0 = new int[n0]; int *SA0 = new int[n0]; int i, j; //*******Step0 : Construct sample ********** //genearte positions of mod 1 and mod 2 suffixes // the (n0 - n1) adds a dummy mod 1 suffix if n %3 == 1 for (i = 0, j = 0; i < n + (n0 - n1); i++) if (i % 3 != 0) R[j++] = i; //********step1: Sort sample suffixes********************* radixPass(R, SA12, T + 2, n02, K); radixPass(SA12, R, T + 1, n02, K); radixPass(R, SA12, T, n02, K); //finde lexicographic names of triples and //write them to correct palces in R int name = 0, c0 = -1, c1 = -1, c2 = -1; for (i = 0; i< n02; i++) { if (T[SA12[i]] != c0 || T[SA12[i] + 1] != c1 || T[SA12[i] + 2] != c2) { name++; c0 = T[SA12[i]]; c1 = T[SA12[i] + 1]; c2 = T[SA12[i] + 2]; } if (SA12[i] % 3 == 1) { R[SA12[i] / 3] = name; } //write to R1 else { R[SA12[i] / 3 + n0] = name; } //write to R2 } // rucruse if names are not yet unique if (name < n02) { suffixArray(R, SA12, n02, name); //store unique names in R using the suffix array; for (i = 0; i < n02; i++) { R[SA12[i]] = i + 1; //ҪǰıһµĻR ֵǴ1 ʼġ } } else { for (i = 0; i < n02; i++) SA12[R[i] - 1] = i; //ȷġ } ///*********Step2: Sort nonsample suffixes********************* //stably sort the mode 0 suffixes from SA12 by their first character for (i = 0, j = 0; i < n02; i++) if (SA12[i] < n0) R0[j++] = SA12[i] * 3; radixPass(R0, SA0, T, n0, K); //n0Ӧøдjɣȵô ////*******Step3: Merge************ for (int p = 0, t = n0 - n1, k = 0; k <n; k++) { #define GetI() (SA12[t] < n0 ? SA12[t] *3 +1 :( SA12[t] - n0 )*3+2) int i = GetI(); int j = SA0[p]; if (SA12[t] < n0 ? leq(T[i], R[SA12[t] + n0], T[j], R[j / 3]) : leq(T[i], T[i + 1], R[SA12[t] - n0 + 1], T[j], T[j + 1], R[j / 3 + n0])) { //suffix from SA12 is smaller SA[k] = i; t++; if (t == n02) //done -- only SA0 suffixes left for (k++; p < n0; p++, k++) SA[k] = SA0[p]; } else { // suffix from SA0 is smaller SA[k] = j; p++; if (p == n0) //done -- noly SA12 suffixes left { for (k++; t < n02; t++, k++) SA[k] = GetI(); } } } delete[] R; delete[] SA12; delete[] SA0; delete[] R0; }
true
521783258972519661feb363635a1c6e42becc6f
C++
xuesongzh/cpp-concurrency
/multithread/30async参数详解.cpp
GB18030
2,641
3.875
4
[]
no_license
#include <future> #include <iostream> #include <string> #include <thread> using namespace std; int mythread() { cout << "߳id=" << std::this_thread::get_id() << endl; return 1; } int main(void) { cout << "main thread id =" << std::this_thread::get_id() << endl; //һ첽 std::future<int> result = std::async(mythread); std::future_status status = result.wait_for(std::chrono::seconds(0)); //Ƿִ if (status == std::future_status::ready) { cout << "ִ߳" << endl; } else if (status == std::future_status::deferred) { cout << "̱߳ӳٵ" << endl; } else if (status == std::future_status::timeout) { cout << "̳߳ʱ䣬ûִн" << endl; } cout << result.get() << endl; system("pause"); return 0; } /* *std::asyncϸ̸ --һ첽 1.std::async(std::launch::deferred)--ӳٵạ̃߳ӳٵfutureget(),wait()Żִ̺߳ͬ 2.std::async(std::launch::async);--ǿƴһ첽̣߳,ִ߳У첽 3.deferred | async ɲϵͳԼѡ񣬿Ǵִ̣߳УҲûд̣߳ӳٵget,waitִ̺߳ --ʵûָĬϲǣdeferred|async оʲô˼ôǷ񴴽̣߳ std::thread()ϵͳԴѷô㴴߳ʧܣthread()ķֵ̫ýգҪʹһȫֱֶνա std::async()첽񣨿ܴ̣߳Ҳ̵̣ܲ߳߳ķֵʹfutureա async()߳һ㲻ᱨ쳣ϵͳԴţӶĵasync()Ͳᴴ̣߳ Ǻ˭get()߳ںڵõ߳С ǿƴ̣߳Ҫʹstd::async(std::launch::async); ݾ飬һ߳Ŀ100-200߳л˷ѺܶcpuԴ std::async()ȷ Ӳasync()ãȷϵͳܷ񴴽̡߳ϵͳѡƳ ζmythread߳ںִУûеget()ѹͲִС дdeferred|asyncǷƳٴ̡߳Ҫʹstd::wait_for() */
true
8efb7b911646ce21f92e9644e133bae8ecc68c72
C++
tectronics/synit
/src/cnf2aig/aigHash.cpp
UTF-8
3,336
2.609375
3
[]
no_license
#include <cassert> #include <climits> #include <algorithm> #include "aigHash.h" using namespace QuteRSAT; size_t AigHashFunc::operator() ( const AigNode &a ) const { return 2000000011 * unsigned( a[0]._data ) + 2000000033 * unsigned( a[1]._data ); } /* size_t hash_value( const AigNode & node ) { size_t seed = 0; boost::hash_combine( seed, node._fanin[0]._data ); boost::hash_combine( seed, node._fanin[1]._data ); return seed; } */ AigHash::AigHash() { AigNode emp; emp[0]._data = UINT_MAX; emp[1]._data = UINT_MAX; _hashTable.set_empty_key( emp ); } void AigHash::perform( const AigCircuit &orgCircuit, AigCircuit &newCircuit ) { newCircuit.initialize( orgCircuit, _links ); for( unsigned i = 1; i < orgCircuit.size(); ++i ) { const AigNode &orgNode = orgCircuit[i]; if( orgNode.isPi() ) continue; AigIndex fanin0 = orgNode._fanin[0].getLink( _links ); AigIndex fanin1 = orgNode._fanin[1].getLink( _links ); if( fanin1 < fanin0 ) swap( fanin0, fanin1 ); const AigIndex link = hashNode( fanin0, fanin1, newCircuit.size(), true ); _links[i] = link; if( link._index == newCircuit.size() ) newCircuit.pushNode( fanin0, fanin1 ); } newCircuit.finalize( orgCircuit, _links ); } void AigHash::hashCircuit( const AigCircuit &circuit ) { for( unsigned i = 1; i < circuit.size(); ++i ) { const AigNode &node = circuit[i]; if( node.isPi() ) continue; if( node._fanin[0]._data <= node._fanin[1]._data ) hashNode( node._fanin[0], node._fanin[1], i, true ); else hashNode( node._fanin[1], node._fanin[0], i, true ); } } AigIndex AigHash::hashNode( AigIndex fanin0, AigIndex fanin1, unsigned index, bool insertHash ) { return hashNode( AigNode( fanin0, fanin1 ), index, insertHash ); /* assert( !(fanin1 < fanin0) ); if( fanin0._data == 0 ) return AigIndex(0); if( fanin0._data == 1 ) return fanin1; if( fanin0 == fanin1 ) return fanin0; if( fanin0._index == fanin1._index ) return AigIndex(0); if( fanin1._data == UINT_MAX ) return fanin1; const AigNode node( fanin0, fanin1 ); google::dense_hash_set<AigHashData, AigHashFunc, AigHashEqual>::const_iterator chi = _hashTable.find( node ); if( chi != _hashTable.end() ) return AigIndex( chi->second, 0 ); if( index == UINT_MAX ) return AigIndex( UINT_MAX ); if( insertHash ) _hashTable.insert( chi, ); return AigIndex( index, 0 ); */ } AigIndex AigHash::hashNode( const AigNode &node, unsigned index, bool insertHash ) { const AigIndex &fanin0 = node[0]; const AigIndex &fanin1 = node[1]; assert( !(fanin1 < fanin0) ); if( fanin0._data == 0 ) return AigIndex(0); if( fanin0._data == 1 ) return fanin1; if( fanin0 == fanin1 ) return fanin0; if( fanin0._index == fanin1._index ) return AigIndex(0); if( fanin1._data == UINT_MAX ) return fanin1; pair<google::dense_hash_map<AigNode, uint32_t, AigHashFunc>::iterator,bool> res = _hashTable.insert( make_pair( node, uint32_t(index) ) ); if( !res.second ) index = res.first->second; else if( !insertHash ) _hashTable.erase( res.first ); if( index == UINT_MAX ) return AigIndex( UINT_MAX ); return AigIndex( index, 0 ); }
true
1a0a47b53c92206351404e9056e6216996589650
C++
LandReagan/GameOfLife
/tests/Cell_tests.cpp
UTF-8
390
3.125
3
[]
no_license
#include <catch.hpp> #include <Cell.hpp> TEST_CASE("Cell class tests") { SECTION("Constructors") { SECTION("Default constructor") { gol::Cell cell; REQUIRE(cell.is_alive() == false); } } SECTION("Cell methods 'make_alive()' and 'kill()'") { gol::Cell cell; cell.make_alive(); REQUIRE(cell.is_alive() == true); cell.kill(); REQUIRE(cell.is_alive() == false); } }
true
41802ba6502ba67f3ea4ffa40097b384e684d9a9
C++
Ceruleanacg/Crack-Interview
/Legacy/53. Maximum Subarray [LeetCode]/main.cpp
UTF-8
982
3.109375
3
[ "MIT" ]
permissive
// // main.cpp // 53. Maximum Subarray [LeetCode] // // Created by Shuyu on 2018/4/9. // Copyright © 2018年 Shuyu. All rights reserved. // #include <iostream> #include <vector> class Solution { public: int maxSubArray(std::vector<int>& nums) { std::vector<int> dp(nums.size(), 0); dp[0] = nums[0]; int result = dp[0]; for (int i = 1; i < nums.size(); ++i) { dp[i] = std::max(nums[i], dp[i - 1] + nums[i]); if (result < dp[i]) { result = dp[i]; } } return result; } }; int main(int argc, const char * argv[]) { Solution solve; std::vector<int> nums; nums.push_back(-2); nums.push_back(1); nums.push_back(-3); nums.push_back(4); nums.push_back(-1); nums.push_back(2); nums.push_back(1); nums.push_back(-5); nums.push_back(4); printf("%d\n", solve.maxSubArray(nums)); return 0; }
true
d4b0ccf45584d07c398346d044f78f2b79dab0e2
C++
ijwilson/GenTL
/flowSeq.h
UTF-8
3,446
3.109375
3
[]
no_license
#ifndef FLOWSEQ_H__ #define FLOWSEQ_H__ #include <string> #include <algorithm> #include <vector> #include <utility> // for pair using std::ostream; using std::string; using std::vector; /** A class to represent a flow-wise version of a sequence */ class flowSeq { public: /** constructors for flowseq */ flowSeq(const std::string &seq, bool TrimFloatingStart, bool TrimFloatingEnd,const string &name="", const string &Floworder="TACG"); flowSeq(const std::string &seq,const string &name="",const string &Floworder="TACG"); flowSeq(size_t len,const string &Floworder="TACG"); flowSeq(){}; /** write the flowsequence to a stream */ ostream &print(ostream &o,const string &sep=",") const; /** convert a flowseq back into a sequence */ string sequence() const; /** What is the probability of a flowgram given this sequence * the flowgram starting at the correct point * assume means of 0,1,2,... and variances of sigma_i. Note that * I assume a lognormal distribution for the zeros and normals for the ones **/ double lprob(const vector<double> &flowgram, const vector<double> &zp, const vector<double> &pp ,const std::vector<int> &tag) const; double lprobsimple(const std::vector<double> &flowgram, const std::vector<double> &zp , const std::vector<double> &pp) const; int operator[](size_t ii) const { return copies[ii]; } /** helper function to return the number of copies at position ii */ int &operator[](size_t ii) { return copies[ii]; } /** What is the length of a sequence */ size_t length() const { return copies.size(); } const std::vector<int> &operator()() const { return copies; } /** an overloaded equality operator */ bool operator==(const flowSeq &rhs) const { return copies==rhs.copies; } /** extract subsequence copies */ std::vector<int> subcopies(size_t start,size_t len) { size_t mx=std::min(start+len,length()); return std::vector<int>(copies.begin()+start,copies.begin()+mx); } /** Is flowSeq a a subset of this flowSeq * If it is then this returns the first and last positions, otherwise return first<0 * This should allow us to categorise sequences by which ones partially match */ std::pair<int,int> subflowgram(const flowSeq &a) const { int start=0; size_t alen=a.copies.size(); size_t left=copies.size(); if (alen>left) return std::pair<int,int>(-1,-1); std::vector<int>::const_iterator ii=copies.begin(); std::vector<int>::const_iterator jj=a.copies.begin(); for (;;) { if (jj==a.copies.end()) { return std::pair<int,int>(start,std::distance(copies.begin(),ii)); // reached the end so a match } else if (*ii != *jj) { // a mismatch here - start again jj=a.copies.begin(); alen=a.copies.size(); left--;ii++; if (alen>left) return std::pair<int,int>(-1,-1); // can we fit it in start=std::distance(copies.begin(),ii); } else { alen--;left--;ii++;jj++; } } } void checkseq(string message,int maxCopies) const; private: std::vector<int> copies; string order; string name; }; std::ostream &operator<<(ostream &out, const flowSeq &a); #endif
true
b864d9f462149f55518a95340b9be557d65d64ba
C++
cpcsdk/z80tonops
/src/test.cpp
UTF-8
1,022
2.75
3
[]
no_license
/** * @author Romain Giot <giot.romain@gmail.com> * @licence GPL * @date 01/2017 */ #include <cassert> #include "z802nops.h" #include <string> #include <iostream> void T(const std::string & opcode, z80tonops::Timing nops) { const z80tonops::Timing duration = z80tonops::duration(opcode); std::cerr << "Opcode: " << opcode << " Duration: " << static_cast<std::string>(duration) << " Expected: " << static_cast<std::string>(nops) << std::endl; assert(duration == nops); assert(duration.hasSimpleTiming() == nops.hasSimpleTiming()); } int main(int argc, char** argv) { T(" LD A, 0", 2); T(" LD A, 10 + (5+2)", 2); T(" LD A, (0)", 4); T(" LD (10), A", 4); T(" LD HL, (50)", 5); T(" LD BC, (50)", 6); T(" LD SP, (50)", 6); T(" LD BC, 0xbc00 + 12", 3); T(" LD HL, XXX", 3); T(" OUT (C), C", 4); T(" INC B", 1); T(" OUT (C), H", 4); T(" INC C", 1); T(" DEC C", 1); T(" OUT (C), C", 4); T(" OUT (C), L", 4); T(" JR XXX", 3); T(" JR C, XXX", {3,2}); }
true
d0ff3e0bec783f5347155a31298deaf83a09dd5f
C++
wjddlsy/Algorithm
/Baekjoon/baek_4354_문자열제곱/baek_4354_문자열제곱/main.cpp
UTF-8
1,807
2.765625
3
[]
no_license
// // main.cpp // baek_4354_문자열제곱 // // Created by 윤정인 on 30/09/2018. // Copyright © 2018 윤정인. All rights reserved. // #include <iostream> using namespace std; #include <iostream> #include <string> #include <cstdio> #include <vector> using namespace std; vector<int> getPi(string p) { int m = (int)p.size(); int j = 0; vector<int> pi(m, 0); for (int i = 1; i< m; i++) { while (j > 0 && p[i] != p[j]) j = pi[j - 1]; if (p[i] == p[j]) pi[i] = ++j; } return pi; } vector<int> kmp(string s, string p) { vector<int> ans; auto pi = getPi(p); int n = (int)s.size(), m = (int)p.size(), j = 0; for (int i = 0; i < n; i++) { while (j>0 && s[i] != p[j]) j = pi[j - 1]; if (s[i] == p[j]) { if (j == m - 1) { ans.push_back(i - m + 1); j = pi[j]; } else { j++; } } } return ans; } int main(int argc, const char * argv[]) { // insert code here... // 약수에 대해서 하기 ios_base::sync_with_stdio(false); string s; while(s!="."){ cin>>s; vector<int> pi=getPi(s); int n=s.size(); int ret=n; for(int i=1; i<n; ++i){ bool chk=true; int t=i; if(n%i!=0) continue; while(t<n){ if(pi[t]==0){ chk=false; break; } t*=i; } if(chk){ ret=i; break; } } cout << n-ret+1 << endl; } std::cout << "Hello, World!\n"; return 0; }
true
3b44e281202506eb6386e6e747df5181e138e98a
C++
mgoyret/INFO_UTN
/INFO_II/tpc/tpc_12/tpc_12/intarr.cpp
UTF-8
727
3.25
3
[]
no_license
#include "intarr.h" IntArr::IntArr(int sz) { size = sz; used = 0; p = new int(size); } IntArr::IntArr(int sz,int qtty,int *vec) { int i; if(sz < qtty) size = qtty; else size = sz; p = new int [size]; for(i=0; i<qtty;i++) { p[i] = vec[i]; used++; } } void IntArr::prtArr(void) const { int i; if(used > 0) { cout << "Array: ["; /* size-1 para al ultimo elemento agregarle el corchete y no poner los ':' */ for(i=0; i<used-1; i++) { cout << p[i] << "; "; } cout << p[i] << "]" << endl; } else cout << "Array: VACIO" << endl; }
true
ed4cca60f22e23c0bb203caccfbe8ad5ca4ae2ce
C++
agloks/Cpp-Study
/Kata-digitalRoot.cpp
UTF-8
806
3.359375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> /* 1 - diminui os preços do carro a cada turno por percentLossByMonth 2 - fazer isso enquano savingperMonth + startPriceOld < startPriceNew 3 - retorna um vector com o total de turno + a sobra do processo 2 */ int digital_root(int n) { std::string number = std::to_string(n); int temp = 0; while(number.length() != 1) { temp = 0; for(int x = 0; x < number.length(); x++) { temp += number[x]-48; std::cout << "temp = " << temp << std::endl; } number = std::to_string(temp); std::cout << "number = " << number << std::endl; } return temp; } int main() { int a = digital_root(132189); std::cout << a << std::endl; return 0; }
true
e7b4c83157814eb04ef638a25936bde1adbd16e9
C++
rsgcaces/AVRFoundations
/MOTORS/DCMotorBasic/DCMotorBasic.ino
UTF-8
1,317
3.140625
3
[]
no_license
// PROJECT :DC Motor: User control // PURPOSE :Demonstrates interactive control over motor speed and direction // AUTHOR :C. D'Arcy // DATE :2018 07 03 // uC :328 // STATUS :Working // REFERENCE:http://mail.rsgc.on.ca/~cdarcy/Datasheets/sn754410.pdf uint8_t directionPin = 8; //slide switch control over forward/reverse uint8_t motorPin1 = 10; //one motor lead uint8_t motorPin2 = 11; //the other motor lead uint8_t currentDirection = HIGH; //let's assume forward uint8_t newDirection = currentDirection; //back it up to recognize changes void setup() { pinMode(motorPin1, OUTPUT); //motors lead pins pinMode(motorPin2, OUTPUT); //data direction delcared } void loop() { newDirection = digitalRead(directionPin); //poll the slide switch if (currentDirection != newDirection) { //check for direction change spin(newDirection); //start the motor currentDirection = newDirection; //backup for next change } } void spin(uint8_t dir) { //sets the motor spinning in a direction digitalWrite(motorPin1, dir); //whichever state is placed on one lead digitalWrite(motorPin2, ~dir); //the other state is placed on the other lead }
true
bfc77a941bf967d179e567c0298ed644a3a77f2d
C++
LeoBrilliant/LeetCodeLib
/P101~150/ConvertSortedArrayToBinarySearchTree.cpp
UTF-8
1,889
3.28125
3
[]
no_license
/* * ConvertSortedArrayToBinarySearchTree.cpp * * Created on: 2016年12月2日 * Author: user */ #include "ConvertSortedArrayToBinarySearchTree.h" ConvertSortedArrayToBinarySearchTree::ConvertSortedArrayToBinarySearchTree() { // TODO Auto-generated constructor stub } ConvertSortedArrayToBinarySearchTree::~ConvertSortedArrayToBinarySearchTree() { // TODO Auto-generated destructor stub } void ConvertSortedArrayToBinarySearchTree::TestSuite() { TreeNode * root; vector<int> nums; cout << "test case 1" << endl; nums = {}; root = this->sortedArrayToBST(nums); assert(root == NULL); DumpTreeByPosition(root); cout << "test case 2" << endl; nums = {1}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 1); DumpTreeByPosition(root); cout << "test case 3" << endl; nums = {1, 2}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 1); DumpTreeByPosition(root); cout << "test case 4" << endl; nums = {1, 2, 3}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 2); DumpTreeByPosition(root); cout << "test case 5" << endl; nums = {1, 2, 3, 4}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 2); DumpTreeByPosition(root); cout << "test case 6" << endl; nums = {1, 2, 3, 4, 5}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 3); DumpTreeByPosition(root); cout << "test case 7" << endl; nums = {1, 2, 3, 4, 5, 6}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 3); DumpTreeByPosition(root); cout << "test case 8" << endl; nums = {1, 2, 3, 4, 5, 6, 7}; root = this->sortedArrayToBST(nums); assert(root != NULL); assert(root->val == 4); DumpTreeByPosition(root); }
true
70fa8d6fc3eb26e0e3ca014a3c6fc1c3cf11f03d
C++
Millsy242/GameEngineSFML
/BaseProject/GameEngine/Game/Entity.cpp
UTF-8
1,503
2.75
3
[]
no_license
// // Entity.cpp // BaseProject // // Created by Daniel Harvey on 13/09/2019. // Copyright © 2019 Daniel Harvey. All rights reserved. // #include "Entity.hpp" void Entity::LoadTexture(std::string filepath) { Collision::CreateTextureAndBitmask(EntityTexture, filepath); EntitySprite.setTexture(EntityTexture); } void Entity::Render(std::shared_ptr<Window> window) { if(Active) window->draw(EntitySprite); } sf::Vector2f Entity::GetPosition() { return Position; } sf::Vector2f Entity::GetOldPosition() { return OldPosition; } void Entity::Update() { OldPosition = Position; EntityUpdate(); } void Entity::SetPosition(sf::Vector2f NewPosition) { Position = NewPosition; EntitySprite.setPosition(Position); } void Entity::SetPosition(float x, float y) { SetPosition(sf::Vector2f(x,y)); } void Entity::ResetPosition() { Position = OldPosition; SetPosition(OldPosition); } bool Entity::isCollision(sf::Sprite *sprite) { return Collision::PixelPerfectTest(EntitySprite, *sprite); } sf::Sprite Entity::GetSprite() { return EntitySprite; } void Entity::SetScale(sf::Vector2f scale) { EntitySprite.setScale(scale); } void Entity::FlipTexture(bool Vertical) { sf::Image temp = EntityTexture.copyToImage(); if(Vertical) temp.flipVertically(); else temp.flipHorizontally(); EntityTexture.loadFromImage(temp); Collision::CreateTextureAndBitmask(&EntityTexture); EntitySprite.setTexture(EntityTexture); }
true
8b3a09916bbfc9937bf9b1fb6294e67f312ae3ae
C++
minemile/afina
/src/storage/SimpleLRU.cpp
UTF-8
3,423
2.75
3
[]
no_license
#include "SimpleLRU.h" namespace Afina { namespace Backend { // See MapBasedGlobalLockImpl.h bool SimpleLRU::Put(const std::string &key, const std::string &value) { auto it = _lru_index.find(key); if (it == _lru_index.end()) { std::size_t size = key.size() + value.size(); CheckLRUCache(size); return InsertNode(key, value); } else { lru_node *node = &(it->second.get()); node->value = value; return UpdateNode(node); } } bool SimpleLRU::InsertNode(const std::string &key, const std::string &value) { std::size_t size = key.size() + value.size(); _cur_size += size; std::unique_ptr<lru_node> node(new lru_node(key, value, _lru_tail)); if (!_lru_head) { _lru_head = std::move(node); _lru_tail = _lru_head.get(); } else { _lru_tail->next = std::move(node); _lru_tail = _lru_tail->next.get(); } _lru_index.insert(std::pair<std::reference_wrapper<const std::string>, std::reference_wrapper<lru_node>>( _lru_tail->key, *_lru_tail)); return true; } bool SimpleLRU::CheckLRUCache(const std::size_t size) { if (_cur_size + size > _max_size) { while (_lru_head && (_cur_size + size > _max_size)) { std::size_t node_size = _lru_head->value.size() + _lru_head->key.size(); _cur_size -= node_size; _lru_index.erase(_lru_head->key); _lru_head = std::move(_lru_head->next); } } return true; } bool SimpleLRU::UpdateNode(lru_node *node) const { if (node == _lru_head.get() && _lru_head->next) { auto future_head = std::move(_lru_head->next); future_head->prev = nullptr; _lru_head->next = nullptr; _lru_head->prev = _lru_tail; _lru_tail->next = std::move(_lru_head); _lru_tail = _lru_tail->next.get(); _lru_head = std::move(future_head); } else if (node->next && node->prev) { node->next->prev = node->prev; node->prev->next.swap(node->next); node->prev = _lru_tail; node->next.release(); _lru_tail->next.reset(node); _lru_tail = _lru_tail->next.get(); } return true; } // See MapBasedGlobalLockImpl.h bool SimpleLRU::PutIfAbsent(const std::string &key, const std::string &value) { auto it = _lru_index.find(key); if (it == _lru_index.end()) { return false; } else { return InsertNode(key, value); } } // See MapBasedGlobalLockImpl.h bool SimpleLRU::Set(const std::string &key, const std::string &value) { auto it = _lru_index.find(key); if (it == _lru_index.end()) { return false; } lru_node *node = &(it->second.get()); node->value = value; return UpdateNode(node); } // See MapBasedGlobalLockImpl.h bool SimpleLRU::Delete(const std::string &key) { auto it = _lru_index.find(key); if (it == _lru_index.end()) { return false; } _cur_size -= key.size() + it->second.get().value.size(); _lru_index.erase(key); return true; } // See MapBasedGlobalLockImpl.h bool SimpleLRU::Get(const std::string &key, std::string &value) const { auto it = _lru_index.find(key); if (it == _lru_index.end()) { return false; } else { lru_node *node = &(it->second.get()); value = node->value; return UpdateNode(node); } } } // namespace Backend } // namespace Afina
true
788a2bd5294a08b5876cd4c70ed88cfa3791cd3b
C++
ruandaniel/PG
/11. 披萨.cpp
UTF-8
1,473
3.375
3
[]
no_license
//dp[i][j] means max pizza the first person can get when slices[i:j] remained, assume everyone is smart //dp[i][j] = max(slices[i] + sum[i+1:j] - dp[i+1][j], slices[j] + sum[i:j-1] - dp[i][j-1]) // = max(sum[i:j] - dp[i+1][j], sum[i:j] - dp[i][j-1]) //dfs with memory class Solution{ public: int pizza(vector<int> slices){ int n = slices.size(); vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) dp[i][i] = slices[i]; vector<int> sum(n + 1, 0); //sum[j] - sum[i] is sum[i : j - 1] for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + slices[i - 1]; return helper(slices, dp, sum, 0, n - 1); } int helper(vector<int> &slices, vector<vector<int>> &dp, vector<int> &sum, int l, int r){ if (dp[l][r]) return dp[l][r]; int s = sum[r + 1] - sum[l]; dp[l][r] = max(s - helper(slices, dp, sum, l + 1, r), s - helper(slices, dp, sum, l, r - 1)); return dp[l][r]; } }; //bottom-up DP class Solution{ public: int pizza(vector<int> slices){ int n = slices.size(); vector<int> sum(n + 1, 0); //sum[j] - sum[i] is sum[i : j - 1] for (int i = 1; i <= n; i++) sum[i] = sum[i - 1] + slices[i - 1]; vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) dp[i][i] = slices[i]; for (int j = 1; j < n; j++){ for (int i = 0; i + j < n; i++){ int s = sum[i + j + 1] - sum[i]; dp[i][i + j] = max(s - dp[i + 1][i + j], s - dp[i][i + j - 1]); } } return dp[0][n - 1]; } }; //O(n^2) time
true
9c07b38561d293a5af16234d020955bf9150d163
C++
thisjdzhang/Leet_Code
/[67] [Add Binary] [Easy] [Math String] [Facebook] [2 43 66].cpp
UTF-8
804
3.203125
3
[ "MIT" ]
permissive
/* Question# + Difficulty + Topic + Company + Similar_Question [67] [Add Binary] [Easy] [Math String] [Facebook] [2 43 66].cpp */ class Solution { public: string addBinary(string a, string b) { string str = ""; bool carry = 0; for(int i =a.size()-1,j = b.size()-1;i>=0||j>=0;i--,j--) { int sum = 0; sum+= i>=0? (int)(a[i]-'0'):0; sum+= j>=0? (int)(b[j]-'0'):0; if(carry) { sum++; carry = 0; } if(sum>1) { carry = 1; sum-=2; } cout<<"Add: "<<sum<<" Str is: "<<str<<endl; str = (char)(sum+'0')+str; } if(carry) str = "1"+str; return str; } };
true
9db018e6cd13562a02db95f2705866982b7301b9
C++
shubharthaksangharsha/institutional_training
/day5_assingment/q1.cpp
UTF-8
879
3.484375
3
[]
no_license
#include<iostream> using namespace std; class WaveType{ double wavelength; public: void input(){ cout<<"The program determines the type of electromagnetic wave\n"; cout<<"Please enter the wavelength in meters of an electromagnetic wave: "; cin>>wavelength; } void display(){ if(wavelength <=1e-11) cout<<"Gamma Ray Radiation Type \n"; else if(wavelength <=1e-8) cout<<"X-Ray Radiation Type \n"; else if(wavelength <=4e-7) cout<<"Ultraviolet Radiation Type \n"; else if(wavelength <=7e-7) cout<<"Visible Light Radiation Type \n"; else if(wavelength <=1e-3) cout<<"Infrared Radiation Type \n"; else if(wavelength <= 1e-2) cout<<"Microwave Radiation Type \n"; else cout<<"Radio Wave Radiatation Type \n"; } }; int main(){ WaveType obj; obj.input(); obj.display(); return 0; }
true
6543f7d1b1f2b256fc4dc475a24e1eee740672cb
C++
kojima0615/Algorithm_library
/code/BellmanFord.cpp
UTF-8
2,282
3.15625
3
[]
no_license
//ベルマンフォード class BellmanFord { public: typedef struct Edge { ll from; ll to; ll cost; Edge(ll f, ll t, ll c) : from(f), to(t), cost(c) {} } Edge; ll edge_num, vertex_num, start, goal; vector<Edge> edges; vector<ll> dist; vector<ll> afby_nc; BellmanFord(ll e, ll v, ll s, ll g) : edge_num(e), vertex_num(v), start(s), goal(g) { dist = vector<ll>(vertex_num, INF); dist[start] = 0; afby_nc = vector<ll>(vertex_num, false); } void connect(ll from, ll to, ll cost) { edges.push_back(Edge(from, to, cost)); } void relax() { REP(i, vertex_num) { for (auto edge : edges) { if (dist[edge.from] != INF && dist[edge.to] > dist[edge.from] + edge.cost) dist[edge.to] = dist[edge.from] + edge.cost; } } } void check_negative_cycle() { REP(i, vertex_num) { for (auto edge : edges) { if (dist[edge.from] == INF) continue; if (dist[edge.to] > dist[edge.from] + edge.cost) { afby_nc[edge.to] = true; dist[edge.to] = dist[edge.from] + edge.cost; } if (afby_nc[edge.from] == true) afby_nc[edge.to] = true; } } } ll distance() { this->relax(); //this->object内で自分のメンバ関数を呼び出すときに使う ll ans_dist = dist[goal]; //for(auto vv:dist)prllf("###%lld\n",vv); this->check_negative_cycle(); //for(auto vv:dist)prllf("######%lld\n",vv); if (ans_dist > dist[goal] || afby_nc[goal] == true) return -INF; else return ans_dist; } }; int main() { cin.tie(0); ios::sync_with_stdio(false); cin >> n >> m; ll a, b, c; BellmanFord bf(m, n, 0, n - 1); for (ll i = 0; i < m; i++) { cin >> a >> b >> c; bf.connect(a - 1, b - 1, -c); } ll dist = bf.distance(); if (dist == -INF) cout << "inf" << "\n"; else cout << -dist << "\n"; }
true
6508c2016196aeecd1e8021dfd81ca21b2c8eb05
C++
janos32783/UtilityCode
/TestDrivers/SmartPointerTestDriver.h
UTF-8
2,549
3.140625
3
[]
no_license
// // Created by molberding on 9/12/2017. // #ifndef UTILITYCODE_SMARTPOINTERTESTDRIVER_H #define UTILITYCODE_SMARTPOINTERTESTDRIVER_H #include "../DataTypes/SmartPointer.h" #include "TestDriver.h" using namespace smart_pointer; class TestObject { private: int val; public: TestObject() : val(0) {} TestObject(int num) : val(num) {} int get() { return val; } int set(int num) { val = num; } }; class SmartPointerTestDriver : public TestDriver { private: public: SmartPointerTestDriver() { init("Smart Pointer"); } void run() { int* temp = new int(5); SmartPointer<int> intPointer = SmartPointer<int>(temp); SmartPointer<TestObject> testObjectPointer = SmartPointer<TestObject>(new TestObject(7)); assert(5, *intPointer); assert(7, testObjectPointer->get()); for(int i = 0; i < 5; i++) { SmartPointer<TestObject> temp = testObjectPointer; assert(7, temp->get()); } assert(7, testObjectPointer->get()); SmartPointer<TestObject> newPointer = SmartPointer<TestObject>(new TestObject(11)); assert(11, newPointer->get()); testObjectPointer = newPointer; assert(11, testObjectPointer->get()); SmartPointer<TestObject> pointer1 = testObjectPointer; assert(11, pointer1->get()); SmartPointer<TestObject> pointer2 = testObjectPointer; assert(11, pointer2->get()); SmartPointer<TestObject> pointer3 = testObjectPointer; assert(11, pointer3->get()); SmartPointer<TestObject> pointer4 = testObjectPointer; assert(11, pointer4->get()); newPointer.destroy(); assert(11, pointer1->get()); assert(11, pointer2->get()); assert(11, pointer3->get()); assert(11, pointer4->get()); testObjectPointer.destroy(); assert(11, pointer1->get()); assert(11, pointer2->get()); assert(11, pointer3->get()); assert(11, pointer4->get()); pointer1.destroy(); assert(11, pointer2->get()); assert(11, pointer3->get()); assert(11, pointer4->get()); pointer2.destroy(); assert(11, pointer3->get()); assert(11, pointer4->get()); pointer3.destroy(); assert(11, pointer4->get()); TestObject* dumbPointer = pointer4.getPointer(); assert(11, dumbPointer->get()); assert(1, pointer4.numReferences()); pointer4.destroy(); } }; #endif //UTILITYCODE_SMARTPOINTERTESTDRIVER_H
true
c5f152a6a6053c386b6a19db6050c654d3d0a031
C++
jamessimonmorris/Lakeshore
/G53GRACW/TextureManager.cpp
UTF-8
2,917
2.796875
3
[]
no_license
#include "TextureManager.h" TextureManager::~TextureManager() { int n = textures.size(); if (n > 0) glDeleteTextures(n, &textures[0]); } GLuint TextureManager::loadImage(const char* filename) { BITMAPFILEHEADER fileHeader; BITMAPINFOHEADER infoHeader; GLuint texObject; unsigned char *pixelBuffer; FILE *bitmapFile; #ifdef _MSC_VER errno_t err = fopen_s(&bitmapFile, filename, "rb"); if (err != 0) return NULL; #else bitmapFile = fopen(filename, "rb"); #endif if (bitmapFile == NULL) return NULL; fread(&fileHeader, 14, 1, bitmapFile); if (fileHeader.bfType != 0x4D42) return NULL; fread(&infoHeader, sizeof(BITMAPINFOHEADER), 1, bitmapFile); if (infoHeader.biBitCount < 24) return NULL; fseek(bitmapFile, fileHeader.bfOffBits, SEEK_SET); pixelBuffer = new unsigned char[infoHeader.biWidth * infoHeader.biHeight * (infoHeader.biBitCount / 8)]; fread(pixelBuffer, sizeof(unsigned char), infoHeader.biWidth * infoHeader.biHeight * (infoHeader.biBitCount / 8), bitmapFile); fclose(bitmapFile); if (infoHeader.biBitCount == 32) { unsigned char c; for (int i = 0; i < infoHeader.biWidth * infoHeader.biHeight; i++) { c = pixelBuffer[i * 4]; pixelBuffer[i * 4] = pixelBuffer[i * 4 + 3]; pixelBuffer[i * 4 + 3] = c; c = pixelBuffer[i * 4 + 1]; pixelBuffer[i * 4 + 1] = pixelBuffer[i * 4 + 2]; pixelBuffer[i * 4 + 2] = c; } } // Enable texturing glEnable(GL_TEXTURE_2D); glEnable(GL_BLEND); // Generate a texture buffer glGenTextures(1, &texObject); // Bin to buffer glBindTexture(GL_TEXTURE_2D, texObject); // Set texture parameters with mipmapping glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Upload texture data - disable mipmapping for specific textures string fileNameStr = filename; string subStr = "Textures/skybox"; if (fileNameStr == "Textures/bark.bmp" || fileNameStr == "Textures/rotorfabric.bmp" || !strncmp(fileNameStr.c_str(), subStr.c_str(), subStr.size())) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, infoHeader.biBitCount == 32 ? GL_RGBA : GL_RGB, infoHeader.biWidth, infoHeader.biHeight, 0, infoHeader.biBitCount == 32 ? GL_RGBA : GL_BGR_EXT, GL_UNSIGNED_BYTE, pixelBuffer); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); gluBuild2DMipmaps(GL_TEXTURE_2D, 3, infoHeader.biWidth, infoHeader.biHeight, infoHeader.biBitCount == 32 ? GL_RGBA : GL_BGR_EXT, GL_UNSIGNED_BYTE, pixelBuffer); } // insert texture into texture list textures.push_back(texObject); // Delete old copy of pixel data delete[] pixelBuffer; glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); return texObject; }
true