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
4e303d9e6a277be98be4210e795aaeadac1897ac
C++
Mallocsizeofint/Praktikum
/laplace_matrix_IC.hpp
UTF-8
925
2.8125
3
[]
no_license
#ifndef LAPLACE_MATRIX_IC_HPP #define LAPLACE_MATRIX_IC_HPP #include "laplace_matrix.hpp" #include <iostream> namespace FDM { class LaplaceMatrixIC : public LaplaceMatrix { private: mutable estd::vector_t<double> diag_; mutable estd::vector_t<double> subdiag_; mutable estd::vector_t<double> subsubdiag_; //Applies the upper and the lower cholesky matrix to a vector //private member because they must read the decomposition void apply_upper_cholesky (estd::vector_t<double>& x) const; void apply_lower_cholesky (estd::vector_t<double>& x) const; public: // constructor LaplaceMatrixIC(const std::size_t size) : LaplaceMatrix(size), diag_(size*size,4), subdiag_(size*size-1,-1), subsubdiag_(size*size-size,-1) { initPrecond();} void initPrecond() const; // destructor ~LaplaceMatrixIC() { } // methods void applyPrecond(estd::vector_t<double>& x) const; }; }//FDM #endif //fileguard
true
bf891d254f82d4b3e895072beb34cc01b5e95b0d
C++
keisuke-kanao/my-UVa-solutions
/Problem Set Volumes/Volume 9 (900-999)/UVa_939_Genes.cpp
UTF-8
1,929
2.953125
3
[]
no_license
/* UVa 939 - Genes To build using Visual Studio 2012: cl -EHsc -O2 UVa_939_Genes.cpp */ #include <iostream> #include <string> #include <map> using namespace std; const int N_max = 3100; map<string, int> names; enum {non_existent, recessive, dominant}; const int nr_status = dominant - non_existent + 1; const string status_strings[nr_status] = { "non-existent", "recessive", "dominant" }; const int hypothesis[nr_status][nr_status] = { {non_existent, non_existent, recessive}, {non_existent, recessive, dominant}, {recessive, dominant, dominant} }; struct person { int parent_, other_parent_; int status_; } persons[N_max]; int get_status(int pi) { if (persons[pi].status_ != -1) return persons[pi].status_; int parent_status = get_status(persons[pi].parent_), other_parent_status = get_status(persons[pi].other_parent_); return persons[pi].status_ = hypothesis[parent_status][other_parent_status]; } int main() { int N; cin >> N; for (int i = 0; i < N; i++) persons[i].parent_ = persons[i].other_parent_ = persons[i].status_ = -1; int nr_persons = 0; while (N--) { string s, t; cin >> s >> t; pair<map<string, int>::iterator, bool> result = names.insert(make_pair(s, nr_persons)); int pi = result.first->second; if (result.second) nr_persons++; int i; for (i = 0; i < nr_status; i++) if (t == status_strings[i]) { persons[pi].status_ = i; break; } if (i == nr_status) { result = names.insert(make_pair(t, nr_persons)); person& c = persons[result.first->second]; if (c.parent_ == -1) c.parent_ = pi; else c.other_parent_ = pi; if (result.second) nr_persons++; } } for (map<string, int>::const_iterator ni = names.begin(), ne = names.end(); ni != ne; ++ni) cout << ni->first << ' ' << status_strings[get_status(ni->second)] << endl; return 0; }
true
522657a1d7bdb8c8042428776dbd4409585784eb
C++
GameOrga/RepositoryName
/Sample/GameProgramming/CCharacter.cpp
SHIFT_JIS
887
2.578125
3
[]
no_license
#include"CCharacter.h" #include"CTaskManager.h" CCharacter::CCharacter() :mpModel(0), mTag(ENONE) { //^XNXgɒlj TaskManager.Add(this); } //XV void CCharacter::Update(){ //gks̐ݒ mMatrixScale.Scale(mScale.mX, mScale.mY, mScale.mZ); //]s̐ݒ mMartixRotate = CMatrix().RotateZ(mRotation.mZ)* CMatrix().RotateX(mRotation.mX)* CMatrix().RotateY(mRotation.mY); //sړs̐ݒ mMatrixTranslate.Translate(mPosition.mX, mPosition.mY, mPosition.mZ); //s̐ݒ mMatrix = mMatrixScale*mMartixRotate*mMatrixTranslate; } //`揈 void CCharacter::Render(){ //mpModel0ȊOȂ` if (mpModel){ //f̕` mpModel->Render(mMatrix); } } CCharacter::~CCharacter(){ //^XNXg̍폜 TaskManager.Remove(this); }
true
4025a8dcda088ef283d8396c80af5e022c87cf1f
C++
AlexaAndreas99/Faculty
/ObjectOrientedProgramming/test7/test7/UI.cpp
UTF-8
1,708
3.109375
3
[]
no_license
#include "UI.h" void UI::add() { char name[50] ,country[50]; std::cout << "----------Adding a team----------\n"; std::cout << "Team name: "; std::cin >> name; std::cout << "Team country: "; std::cin >> country; if (this->ctrl.add_team(name, country, 0)) std::cout << "Added succesfully\n"; else std::cout << "Duplicate team added\n"; } void UI::print_all() { DynamicVector<Domain> dv = this->ctrl.get_repo().get_dv(); dv=this->ctrl.sort(); for (int i = 0; i < dv.get_size(); i++) { std::cout << dv[i].get_name().c_str()<<"|"; std::cout << dv[i].get_country().c_str()<<"|"; std::cout << dv[i].get_score(); std::cout << std::endl; } } void UI::match() { char name[50], name2[50],name3[50]; std::cout << "----------Match time----------\n"; std::cout << "First team name: "; std::cin >> name; std::cout << "Second team name: "; std::cin >> name2; std::cout << "Winning team name: "; std::cin >> name3; if (this->ctrl.win(name, name2, name3) == false) std::cout << "The selected teams cannot play\n"; else this->ctrl.win(name, name2, name3); } void UI::set_up() { this->ctrl.add_team("Larvik", "Norway", 0); this->ctrl.add_team("CSM", "Romania", 0); this->ctrl.add_team("HCM", "Montenegro", 0); this->ctrl.add_team("Rostov-Don", "Russia", 0); this->ctrl.add_team("FTC", "Hungary", 0); } void UI::run() { char input; while (true) { std::cout << "1.ADD TEAM\n"; std::cout << "2.SHOW ALL TEAMS\n"; std::cout << "3.PLAY MATCH\n"; std::cout << "0.EXIT\n"; std::cin >> input; if (input == '0') return; if (input == '1') this->add(); if (input == '2') this->print_all(); if (input == '3') this->match(); } } UI::~UI() { }
true
338008b5f58e54e4ace7e74549204c2139e2fde8
C++
wai2016/pa3_rt
/src/scene/light.h
UTF-8
3,341
2.984375
3
[]
no_license
#ifndef __LIGHT_H__ #define __LIGHT_H__ #include "scene.h" class Light : public SceneElement { public: virtual vec3f shadowAttenuation(const vec3f& P) const = 0; virtual double distanceAttenuation( const vec3f& P ) const = 0; virtual vec3f getColor( const vec3f& P ) const = 0; virtual vec3f getDirection( const vec3f& P ) const = 0; protected: Light( Scene *scene, const vec3f& col ) : SceneElement( scene ), color( col ) {} vec3f color; }; class DirectionalLight : public Light { public: DirectionalLight( Scene *scene, const vec3f& orien, const vec3f& color ) : Light( scene, color ), orientation( orien ) {} virtual vec3f shadowAttenuation(const vec3f& P) const; virtual double distanceAttenuation( const vec3f& P ) const; virtual vec3f getColor( const vec3f& P ) const; virtual vec3f getDirection( const vec3f& P ) const; protected: vec3f orientation; }; class PointLight : public Light { public: PointLight( Scene *scene, const vec3f& pos, const vec3f& color, const double& cac, const double& lac, const double& qac) : Light( scene, color ), position( pos ), cac(cac), lac(lac), qac(qac) {} virtual vec3f shadowAttenuation(const vec3f& P) const; virtual double distanceAttenuation( const vec3f& P ) const; virtual vec3f getColor( const vec3f& P ) const; virtual vec3f getDirection( const vec3f& P ) const; protected: vec3f position; double cac, lac, qac; // constant_attenuation_coeff, linear_attenuation_coeff, quadratic_attenuation_coeff }; class AmbientLight : public Light { public: AmbientLight(Scene *scene, const vec3f& color) : Light(scene, color) {} virtual vec3f shadowAttenuation(const vec3f& P) const; virtual double distanceAttenuation(const vec3f& P) const; virtual vec3f getColor(const vec3f& P) const; virtual vec3f getDirection(const vec3f& P) const; }; class SpotLight : public Light // inherit pointlight will be better? { public: SpotLight(Scene *scene, const vec3f& pos, const vec3f& d, const double& a, const vec3f& color, const double& cac, const double& lac, const double& qac) : Light(scene, color), position(pos), direction(d), angle(a), cac(cac), lac(lac), qac(qac) {} virtual vec3f shadowAttenuation(const vec3f& P) const; virtual double distanceAttenuation(const vec3f& P) const; virtual vec3f getColor(const vec3f& P) const; virtual vec3f getDirection(const vec3f& P) const; protected: vec3f position, direction; double angle; // coneAngle double cac, lac, qac; // constant_attenuation_coeff, linear_attenuation_coeff, quadratic_attenuation_coeff }; class AreaLight : public Light { public: AreaLight(Scene *scene, const vec3f& pos, const vec3f& color, const double& cac, const double& lac, const double& qac, const vec3f& up) : Light(scene, color), position(pos), cac(cac), lac(lac), qac(qac), up(up), pl1(scene, pos - up, color, cac, lac, qac), pl2(scene, pos, color, cac, lac, qac), pl3(scene, pos + up, color, cac, lac, qac) {} virtual vec3f shadowAttenuation(const vec3f& P) const; virtual double distanceAttenuation(const vec3f& P) const; virtual vec3f getColor(const vec3f& P) const; virtual vec3f getDirection(const vec3f& P) const; protected: vec3f position, up; double cac, lac, qac; // constant_attenuation_coeff, linear_attenuation_coeff, quadratic_attenuation_coeff PointLight pl1, pl2, pl3; }; #endif // __LIGHT_H__
true
902d9be301ecb85de833fedb781e2826992bfa5f
C++
lint89/TestOpengGL
/TestOpenGL/OpenGLIntroduce/CH12_AlphaTest.cpp
WINDOWS-1252
4,633
2.71875
3
[]
no_license
#include <gl/glut.h> #include <stdio.h> #include <stdlib.h> #define WindowWidth 400 #define WindowHeight 400 #define WindowTitle "OpenGL " #define BMP_Header_Length 54 int power_of_two(int n) { if (n <= 0) { return 0; } return(n & (n-1)) == 0; } GLuint load_texture(const char* file_name) { GLint width, height, total_bytes; GLubyte* pixels = 0; GLuint texture_ID = 0; GLint last_texture_ID; FILE* pFile = fopen(file_name, "rb"); if (pFile == 0) { return 0; } fseek(pFile, 0x0012, SEEK_SET); fread(&width, 4, 1, pFile); fread(&height, 4, 1, pFile); fseek(pFile, BMP_Header_Length, SEEK_SET); GLint line_bytes = width * 3; while (line_bytes % 4 != 0) { ++line_bytes; } total_bytes = line_bytes * height; pixels = (GLubyte*)malloc(total_bytes); if (pixels == 0) { fclose(pFile); return 0; } if (fread(pixels, total_bytes, 1, pFile) <= 0) { free(pixels); fclose(pFile); return 0; } GLint max; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &max); if (!power_of_two(width) || !power_of_two(height) || width > max || height > max) { const GLint new_width = 256; const GLint new_height = 256; GLint new_line_bytes, new_total_bytes; GLubyte* new_pixels = 0; new_line_bytes = new_width * 3; while (new_line_bytes % 4 != 0) { ++new_line_bytes; } new_total_bytes = new_line_bytes * new_height; new_pixels = (GLubyte*)malloc(new_total_bytes); if (new_pixels == 0) { free(pixels); fclose(pFile); return 0; } gluScaleImage(GL_RGB, width, height, GL_UNSIGNED_BYTE, pixels, new_width, new_height, GL_UNSIGNED_BYTE, new_pixels); free(pixels); pixels = new_pixels; width = new_width; height = new_height; } glGenTextures(1, &texture_ID); if (texture_ID == 0) { free(pixels); fclose(pFile); return 0; } glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture_ID); glBindTexture(GL_TEXTURE_2D, texture_ID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixels); glBindTexture(GL_TEXTURE_2D, last_texture_ID); free(pixels); return texture_ID; } void texture_colorkey(GLubyte r, GLubyte g, GLubyte b, GLubyte absolute) { GLfloat width, height; GLubyte* pixels = 0; glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); pixels = (GLubyte*)malloc(width * height * 4); if (pixels == 0) { return; } glGetTexImage(GL_TEXTURE_2D, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels); GLint i; GLint count = width * height; for (i = 0; i < count; ++i) { if (abs(pixels[i*4] - b) <= absolute && abs(pixels[i*4 + 1] - g) <= absolute && abs(pixels[i*4 + 2] - r) <= absolute) { pixels[i*4 + 3] = 0; } else { pixels[i*4 + 3] = 255; } } glTexImage2D(GL_TEXTURE_2D, 0, GLUT_RGBA, width, height, 0, GL_BGRA_EXT, GL_UNSIGNED_BYTE, pixels); free(pixels); } void display(void) { static int initialized = 0; static GLuint texWindow = 0; static GLuint texPicture = 0; if (!initialized) { texPicture = load_texture("pic.bmp"); texWindow = load_texture("window.bmp"); glBindTexture(GL_TEXTURE_2D, texWindow); texture_colorkey(255, 255, 255, 10); glEnable(GL_TEXTURE_2D); initialized = 1; } glClear(GL_COLOR_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, texPicture); glDisable(GL_ALPHA_TEST); glBegin(GL_QUADS); { glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f); } glEnd(); glBindTexture(GL_TEXTURE_2D, texWindow); glEnable(GL_ALPHA_TEST); glAlphaFunc(GL_GREATER, 0.5f); glBegin(GL_QUADS); { glTexCoord2f(0.0f, 0.0f); glVertex2f(-1.0f, -1.0f); glTexCoord2f(0.0f, 1.0f); glVertex2f(-1.0f, 1.0f); glTexCoord2f(1.0f, 1.0f); glVertex2f( 1.0f, 1.0f); glTexCoord2f(1.0f, 0.0f); glVertex2f( 1.0f, -1.0f); } glEnd(); glutSwapBuffers(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(WindowWidth, WindowHeight); glutCreateWindow(WindowTitle); glutDisplayFunc(&display); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glutMainLoop(); return 0; }
true
9adde6c0c9a367acf2fcb8787e4988ef7c0e897b
C++
tkekan/programming
/wordbreak_bfs.cpp
UTF-8
881
3.328125
3
[]
no_license
#include<iostream> #include<queue> #include<unordered_set> using namespace std; bool wordBreak(string s, vector<string>& wordDict) { unordered_set<string> myset; queue<int> myq; if (s.length() == 0) return false; myq.push(0); for (const string &s: wordDict){ myset.insert(s); } while (!myq.empty()) { int start = myq.front(); myq.pop(); for (int end = start; end < s.length(); end++){ if (myset.count(s.substr(start,end-start+1)) > 0) { myq.push(end+1); if (end+1 == s.length()) return true; } } } return false; } int main() { vector<string> words = {"l","leet","code","e"}; string s = "leetcode"; cout << wordBreak(s,words); }
true
c67d98bae2e33534cd9da37ba553d31606806062
C++
Tackwin/Poker
/src/IA/Genome.cpp
UTF-8
9,010
2.625
3
[]
no_license
#include "Genome.hpp" #include "Random/Random.hpp" #include <algorithm> void Genome::add_connection_mutation() noexcept { size_t in = random(node_genes.size()); size_t out = std::max(n_inputs, in) + random(node_genes.size() - std::max(n_inputs, in)); auto& n_in = node_genes[in]; auto& n_out = node_genes[out]; if (in == out) return; for (auto& x : connection_genes) if ((x.in == in && x.out == out) || (x.in == out && x.out == in)) return; bool reversed = (n_in.kind == NodeGene::Kind::Hidden && n_out.kind == NodeGene::Kind::Input) || (n_in.kind == NodeGene::Kind::Output && n_out.kind == NodeGene::Kind::Hidden) || (n_in.kind == NodeGene::Kind::Output && n_out.kind == NodeGene::Kind::Input); ConnectionGene new_gene; new_gene.in = reversed ? out : in; new_gene.out = reversed ? in : out; new_gene.innov = ConnectionGene::Innov_N++; new_gene.w = randomf() * 2 - 1; new_gene.enabled = true; connection_genes.push_back(new_gene); } void Genome::add_node_mutation() noexcept { auto& connection = connection_genes[random(connection_genes.size())]; connection.enabled = false; NodeGene new_node; new_node.id = node_genes.size(); new_node.kind = NodeGene::Kind::Hidden; new_node.func = NodeGene::Activation::Relu; ConnectionGene first; first.in = connection.in; first.out = new_node.id; first.w = 1; first.enabled = true; first.innov = ConnectionGene::Innov_N++; ConnectionGene second; second.in = new_node.id; second.out = connection.out; second.w = connection.w; second.enabled = true; second.innov = ConnectionGene::Innov_N++; node_genes.push_back(new_node); connection_genes.push_back(first); connection_genes.push_back(second); } void Genome::del_node_mutation(size_t i) noexcept { //for (auto& x : connection_genes) { // if (x.in == i || x.out == i) x.enabled = false; //} } void Genome::weight_mutation(size_t i) noexcept { connection_genes[i].w += randomnorm(0, mutation_weight_step); } void Genome::activation_func_mutation(size_t i) noexcept { auto x = (NodeGene::Activation)random((uint32_t)NodeGene::Activation::Count); node_genes[i].func = x; } void Genome::remove_connection_mutation(size_t i) noexcept { connection_genes[i].enabled = false; } Genome Genome::crossover(const Genome& parent1, const Genome& parent2) noexcept { Genome offspring; offspring.n_inputs = parent1.n_inputs; offspring.n_outputs = parent1.n_outputs; offspring.connection_genes.reserve(parent1.connection_genes.size()); offspring.node_genes = parent1.node_genes; for (size_t i = 0; i < parent1.connection_genes.size(); ++i) { auto x = parent1.connection_genes[i]; bool matching = false; const ConnectionGene* other = nullptr; for (size_t j = 0; j < parent2.connection_genes.size(); ++j) { auto& y = parent2.connection_genes[j]; if (x.innov < y.innov) break; if (x.innov == y.innov) { matching = true; other = &y; x.w = (x.w + y.w) / 2; break; } } if (matching) offspring.connection_genes.push_back(randomf() > .5 ? x : *other); else offspring.connection_genes.push_back(x); } return offspring; } float Genome::speciation_coeff(const Genome& a, const Genome& b) noexcept { size_t N = std::max(a.connection_genes.size(), b.connection_genes.size()); size_t disjoints = 0; size_t excess = 0; size_t avg_n = 0; float avg_w = 0; size_t i = 0; size_t j = 0; for(; i < a.connection_genes.size() && j < b.connection_genes.size();) { auto& x = a.connection_genes[i]; auto& y = b.connection_genes[j]; if (x.innov == y.innov) { // Matching avg_w += std::abs(x.w - y.w); avg_n ++; i++; j++; } if (x.innov > y.innov) { disjoints ++; j++; } if (y.innov > x.innov) { disjoints ++; i++; } } excess += a.connection_genes.size() - i; excess += b.connection_genes.size() - j; float mult = 1.f * std::max(a.node_genes.size(), b.node_genes.size()) / 1.f * std::min(a.node_genes.size(), b.node_genes.size()); return mult * (a.c1 * excess + a.c2 * disjoints) / N + a.c3 * avg_w / avg_n; } Genome Genome::generate(size_t n_inputs, size_t n_outputs) noexcept { Genome g; // g.n_inputs = n_inputs; g.n_outputs = n_outputs; // for (size_t i = 0; i < n_inputs; ++i) { NodeGene node_gene; node_gene.kind = NodeGene::Kind::Input; node_gene.func = NodeGene::Activation::Linear; node_gene.id = i; g.node_genes.push_back(node_gene); } // for (size_t i = 0; i < n_outputs; ++i) { NodeGene node_gene; node_gene.kind = NodeGene::Kind::Output; node_gene.func = NodeGene::Activation::Linear; node_gene.id = i + n_inputs; g.node_genes.push_back(node_gene); } // for (size_t i = 0; i < n_inputs; ++i) { for (size_t j = 0; j < n_outputs; ++j) { ConnectionGene connec; connec.innov = ConnectionGene::Innov_N++; connec.w = randomf() * 2 - 1; connec.enabled = true; connec.in = i; connec.out = j + n_inputs; g.connection_genes.push_back(connec); } } return g; static Genome genome; static bool flag = true; if (flag) { NodeGene node; node.kind = NodeGene::Kind::Input; node.id = 0; genome.node_genes.push_back(node); node.id = 1; genome.node_genes.push_back(node); node.id = 2; genome.node_genes.push_back(node); node.kind = NodeGene::Kind::Output; node.id = 3; genome.node_genes.push_back(node); node.kind = NodeGene::Kind::Hidden; node.id = 4; genome.node_genes.push_back(node); node.kind = NodeGene::Kind::Hidden; node.id = 5; genome.node_genes.push_back(node); ConnectionGene connec; //connec.enabled = true; //connec.in = 0; //connec.out = 3; //connec.w = -.5f; ////connec.w = randomf() * 2 - 1; //connec.innov = ConnectionGene::Innov_N++; //genome.connection_genes.push_back(connec); // //connec.in = 1; //connec.out = 3; //connec.w = 1; ////connec.w = randomf() * 2 - 1; //connec.innov = ConnectionGene::Innov_N++; //genome.connection_genes.push_back(connec); // //connec.in = 2; //connec.out = 3; //connec.w = 1; ////connec.w = randomf() * 2 - 1; //connec.innov = ConnectionGene::Innov_N++; //genome.connection_genes.push_back(connec); connec.in = 4; connec.out = 3; connec.w = -2; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 0; connec.out = 4; connec.w = -1.5f; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 1; connec.out = 4; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 2; connec.out = 4; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 0; connec.out = 5; connec.w = -1.5f; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 1; connec.out = 5; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 2; connec.out = 5; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 5; connec.out = 3; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; genome.connection_genes.push_back(connec); connec.in = 0; connec.out = 3; connec.w = 1; //connec.w = randomf() * 2 - 1; connec.innov = ConnectionGene::Innov_N++; //genome.connection_genes.push_back(connec); genome.n_inputs = 3; genome.n_outputs = 1; flag = false; } return genome; } std::string Genome::to_string() noexcept { std::string result = "Age: " + std::to_string(age) + "\n[ :node: \n"; for (auto& x : node_genes) { result += "{ "; switch (x.kind) { case NodeGene::Kind::Input: result += "Input"; break; case NodeGene::Kind::Hidden: result += "Hidden"; break; case NodeGene::Kind::Output: result += "Output"; break; case NodeGene::Kind::LSTM: result += "LTSM"; break; default: break; } result += ", "; switch (x.func) { case NodeGene::Activation::Relu: result += "Relu"; break; case NodeGene::Activation::Linear: result += "Linear"; break; case NodeGene::Activation::Sig: result += "Sigmoid"; break; case NodeGene::Activation::Sign: result += "Sign"; break; default: break; } result += ", " + std::to_string(x.id) = " }\n"; } result.back() = ']'; result += "\n[ :connection: \n"; for (auto& x : connection_genes) { result += "{ in: " + std::to_string(x.in) + " out: " + std::to_string(x.out) + " innov: " + std::to_string(x.innov) + " w: " + std::to_string(x.w) + " enabled: " + (x.enabled ? "true" : "false") + "}\n"; } result.back() = ']'; return result; }
true
5bda5958a0ca91325b315228238929ee4b13d787
C++
yosupo06/library-checker-problems
/graph/min_cost_b_flow/gen/anti_ssp.cpp
UTF-8
1,022
2.96875
3
[ "Apache-2.0" ]
permissive
#include "common.h" Graph gen_anti_ssp(const size_t k) { const Flow max_flow = 5 * ((Flow)(1) << (k-2)) - 2; const Flow inf = max_flow + 2; const size_t n = 2 * k + 2; Graph graph(n); graph.bs[0] += max_flow; graph.bs[n-1] -= max_flow; rep(i, k) { graph.add_edge(0, i + 1, 0, i == 0 ? 1 : i == 1 ? 3 : ((Flow)(5) << (i - 2)), 0); } graph.add_edge(1, k + 1, 0, inf, 0); rep(i, k) rep(j, k) if (i != j) { graph.add_edge(i+1, k+j+1, 0, inf, ((Flow)(1) << (std::max(i, j))) - 1); } rep(i, k) { graph.add_edge(i+1+k, 2*k+1, 0, i < 2 ? 2 : ((Flow)(5) << (i - 2)), 0); } return graph; } int main(const int, const char**) { using namespace std; size_t k = 3; Graph g = gen_anti_ssp(k); assert(g.satisfies_constraints()); while (true) { ++k; Graph h = gen_anti_ssp(k); if (h.satisfies_constraints()) { g = h; } else { break; } } g.output(); return 0; }
true
cb80c32727e21364fc44ce07a30086f4897b3937
C++
dmargala/turbo-octo-spice
/turbooctospice/ThreadPool.h
UTF-8
830
2.875
3
[]
no_license
#ifndef TURBOOCTOSPICE_THREAD_POOL #define TURBOOCTOSPICE_THREAD_POOL #include <list> #include <boost/smart_ptr.hpp> #include <boost/function.hpp> namespace turbooctospice { class ThreadPool { public: /// Creates a new thread pool with the specified number of threads. /// @param nthreads Number of threads to use. ThreadPool(int nthreads); virtual ~ThreadPool(); /// A task takes no arguments and returns a status bool. typedef boost::function<bool ()> Task; /// Runs the list of tasks provided and returns the logical AND of all status bools /// when they are all complete. // @param tasks List of tasks to process. bool run(std::list<Task> tasks); private: class Implementation; boost::scoped_ptr<Implementation> _pimpl; }; // ThreadPool } // turbooctospice #endif // TURBOOCTOSPICE_THREAD_POOL
true
436c282d8791cd080436bfc5de819719b7347d3b
C++
nathalie-raffray/GameEngine
/src/System.h
UTF-8
1,784
2.6875
3
[]
no_license
#pragma once #include "Entity.h" #include "EventManager.h" /* struct EntityCompareDefault { static bool cmp(const EntityHandle& lhs, const EntityHandle& rhs) { return lhs.m_index < rhs.m_index; } }; */ //template<class Comparator> class System { public: //System() : m_entities(std::set<EntityHandle, bool(*)(const EntityHandle&, const EntityHandle&)>(EntityCompareDefault::cmp)) {} //template<class Comparator> //System(Comparator cmp) : m_entities(std::set<EntityHandle, decltype(cmp)>) {} //System(bool(*cmp)(const EntityHandle&, const EntityHandle&)) : m_entities(std::set<EntityHandle, bool(*)(const EntityHandle&, const EntityHandle&)>(cmp)) {} //std::set<int, decltype(cmp)*> s(cmp) //System() : m_entities(std::set<EntityHandle, std::less<EntityHandle>>()) {} //template<class Comparator> //System(Comparator cmp) : m_entities(std::set<EntityHandle, Comparator>()) {} //System(bool(*cmp)(const EntityHandle&, const EntityHandle&)) : m_entities(std::set<EntityHandle>(cmp)) {} virtual ~System() {} virtual void add(EntityHandle h) { if (isValid(h)) { m_entities.emplace_back(h); init(h); } } virtual void refresh() { m_entities.erase(std::remove_if(std::begin(m_entities), std::end(m_entities), [](EntityHandle h) { return (!(*h) || !h->m_Active); } ), std::end(m_entities)); /*for (auto& entity : m_entities) { if (!(*entity) || !entity->m_Active) { m_entities.erase(entity); } }*/ } virtual bool isValid(EntityHandle) const = 0; virtual void init(EntityHandle){} virtual void update(float) {} public: //std::set<EntityHandle> m_entities; std::vector<EntityHandle> m_entities; }; //using System = TSystem<std::less<EntityHandle>>; //template class System<std::less<EntityHandle>>;
true
3a52ba76fb09b1a88f9ce6d2b109c138228542ec
C++
dilawar/eyesthatblink
/core/helpers.cpp
UTF-8
4,677
2.640625
3
[ "MIT" ]
permissive
#include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <queue> #include <stdio.h> #include <thread> #include <chrono> #include <boost/algorithm/string.hpp> #include <boost/regex.hpp> #include <iomanip> #include <ctime> #include "constants.h" #include "globals.h" #include "helpers.h" #include "pstream.h" #if USE_BOOST_PROCESS #include <boost/process.hpp> #endif bool rectInImage(cv::Rect rect, cv::Mat image) { return rect.x > 0 && rect.y > 0 && rect.x+rect.width < image.cols && rect.y+rect.height < image.rows; } bool inMat(cv::Point p,int rows,int cols) { return p.x >= 0 && p.x < cols && p.y >= 0 && p.y < rows; } cv::Mat matrixMagnitude(const cv::Mat &matX, const cv::Mat &matY) { cv::Mat mags(matX.rows,matX.cols,CV_64F); for (int y = 0; y < matX.rows; ++y) { const double *Xr = matX.ptr<double>(y), *Yr = matY.ptr<double>(y); double *Mr = mags.ptr<double>(y); for (int x = 0; x < matX.cols; ++x) { double gX = Xr[x], gY = Yr[x]; double magnitude = sqrt((gX * gX) + (gY * gY)); Mr[x] = magnitude; } } return mags; } double computeDynamicThreshold(const cv::Mat &mat, double stdDevFactor) { cv::Scalar stdMagnGrad, meanMagnGrad; cv::meanStdDev(mat, meanMagnGrad, stdMagnGrad); double stdDev = stdMagnGrad[0] / sqrt(mat.rows*mat.cols); return stdDevFactor * stdDev + meanMagnGrad[0]; } /** * @brief Sleep for given milliseconds. * * @param milliseconds */ void _sleep( size_t x ) { std::this_thread::sleep_for(std::chrono::milliseconds(x)); } /** * @brief Compute difference of two time stamps. * * @param t1 First time. * @param t2 Second time. * * @return Difference in milli-seconds. */ int diff_in_ms( time_type_ t1, time_type_ t2 ) { return abs( std::chrono::duration_cast< std::chrono::milliseconds >( t2 - t1 ).count( ) ); } /* --------------------------------------------------------------------------*/ /** * @Synopsis Expand user in given path. * * @Param path * * @Returns */ /* ----------------------------------------------------------------------------*/ std::string expand_user(std::string path) { string home = getenv("HOME"); if (! path.empty() && path[0] == '~') { assert(path.size() == 1 or path[1] == '/'); // or other error handling if ( home.size( ) > 0 || (home == getenv("USERPROFILE")) ) path.replace(0, 1, home); else { char const *hdrive = getenv("HOMEDRIVE"), *hpath = getenv("HOMEPATH"); path.replace(0, 1, std::string(hdrive) + hpath); } } // If there is $HOME. if( path.find( "$HOME" ) != string::npos ) boost::replace_all( path, "$HOME", home ); return path; } /* --------------------------------------------------------------------------*/ /** * @Synopsis Swapn a child process. * * @Param command * * @Returns */ /* ----------------------------------------------------------------------------*/ string spawn( const string& command ) { vector<string> cmdVec; boost::algorithm::split( cmdVec, command, boost::is_any_of(" ") ); #if USE_BOOST_PROCESS namespace bp = boost::process; #ifdef OS_IS_UNIX LOG_INFO << "Spawning " << command << endl; #ifdef OS_IS_APPLE bp::spawn( command ); #else bp::spawn( command ); #endif #endif #else // NOT USING BOOST SUBPROCESS LOG_INFO << "Executing " << command; redi::ipstream proc( command ); stringstream ss; string line; while( std::getline( proc.out( ), line ) ) ss << line << endl; return ss.str( ); #endif return ""; } /* --------------------------------------------------------------------------*/ /** * @Synopsis Find the display using xrander. * * @Returns */ /* ----------------------------------------------------------------------------*/ vector<string> find_display( ) { const string out = spawn( "xrandr -q" ); boost::smatch what; boost::regex disp_regex( "^(\\S+)\\s+connected" ); vector<string> res; string line; istringstream f( out ); while( std::getline(f, line ) ) { if(boost::regex_search( line, what, disp_regex )) res.push_back( what[1] ); } return res; } #if 0 // WARN: Require gcc-5.0 void print_time( time_type_ time, const std::string end ) { std::time_t now = std::chrono::system_clock::to_time_t( time ); std::cout << std::put_time( std::localtime(&now), "%F %T" ) << end; } #endif
true
a8b21cc9a80fa5dd98d5cd365f305dccac24644a
C++
dechimal/desalt
/include/desalt/format/detail/numeric_formatter.hpp
UTF-8
7,828
2.546875
3
[ "WTFPL" ]
permissive
#if !defined DESALT_FORMAT_DETAIL_NUMERIC_FORMATTER_HPP_INCLUDED_ #define DESALT_FORMAT_DETAIL_NUMERIC_FORMATTER_HPP_INCLUDED_ #include <type_traits> #include <desalt/require.hpp> #include <desalt/format/constexpr/algorithm.hpp> #include <desalt/format/detail/make_charset_pred.hpp> #include <desalt/format/detail/find_index_specifier.hpp> #include <desalt/format/detail/toi.hpp> #include <iterator> namespace desalt { namespace format { namespace detail { template<typename I, typename T> constexpr bool contains(I f, I l, T x) { return here::find(f, l, x) != l; } template<typename I, typename P> constexpr bool any(I f, I l, P p) { return here::find_if(f, l, p) != l; } template<char const * String, std::size_t I, std::size_t E, typename T> struct integer_formatter { static constexpr std::size_t flags_end = here::find_if(String+I, String+E, here::make_charset_pred("#0- +"))-String; static constexpr std::size_t width_digits_end = here::find_if(String+flags_end, String+E, here::make_charset_pred("0123456789"))-String; static constexpr std::size_t width_var_end = here::find_if(String+flags_end, String+E, here::make_charset_pred("*"))-String; static constexpr std::size_t width_end = width_digits_end != flags_end ? width_digits_end : width_var_end != flags_end ? width_var_end : flags_end; static constexpr std::size_t precision_sep_end = here::find_if(String+width_end, String+E, here::make_charset_pred("."))-String; static constexpr std::size_t precision_digits_end = here::find_if(String+precision_sep_end, String+E, here::make_charset_pred("0123456789"))-String; static constexpr std::size_t precision_var_end = here::find_if(String+precision_sep_end, String+E, here::make_charset_pred("*"))-String; static constexpr std::size_t precision_end = precision_digits_end != precision_sep_end ? precision_digits_end : precision_var_end != precision_sep_end ? precision_var_end : precision_sep_end; static constexpr std::size_t type_end = here::find_if(String+precision_end, String+E, here::make_charset_pred("diouxX"))-String; static_assert(type_end != precision_end, "the numeric format placeholder is not valid."); static constexpr char type = String[type_end-1]; static constexpr bool alternative = here::contains(String+I, String+E, '#'); static_assert(!alternative || type != 'd' && type != 'i' && type != 'u', "the numeric format placeholder is not valid."); static constexpr bool has_precision = precision_sep_end != width_end; static constexpr bool has_variable_precision = precision_var_end != precision_sep_end; static constexpr bool has_width = String+flags_end != String+width_end; static constexpr unsigned width = here::toi<unsigned>(String+flags_end, String+width_end); static constexpr unsigned precision = !has_precision || has_variable_precision ? 0 : here::toi<unsigned>(String+precision_sep_end, String+precision_end); static constexpr bool left_align = here::contains(String+I, String+flags_end, '-'); static constexpr bool zerofill = here::contains(String+I, String+flags_end, '0') && !(left_align || has_precision); static constexpr bool sign = here::contains(String+I, String+flags_end, '+') && type != 'u'; static constexpr bool space = here::contains(String+I, String+flags_end, ' ') && !sign && type != 'u'; static constexpr unsigned base = type == 'o' ? 8 : type == 'd' || type == 'i' || type == 'u' ? 10 : 16; static constexpr unsigned prefix_size = alternative && type == 'x' || type == 'X' ? 2 : 1; static constexpr std::size_t end_pos = type_end; static constexpr std::size_t used_indexes_count = has_width + has_precision; using this_type = integer_formatter; template<typename OStream, typename ...Args> static void format(OStream & ost, T const & val, Args const & ...) { constexpr unsigned upper_bound_size = 1 + prefix_size + here::max(precision, width, integer_formatter::upper_bound_size(sizeof(val)*8, base)); std::array<typename OStream::char_type, upper_bound_size + 1> buf; buf.back() = '\0'; auto f = buf.rbegin() + 1; auto precision_pos = f + precision; auto i = f; this_type::format_impl<type>(val, i, precision_pos); constexpr char fill_char = zerofill ? '0' : ' '; auto width_pos = f + width; while (i < width_pos) *i++ = fill_char; ost << buf.data() + (buf.rend() - i); } template<char Type, typename It, DESALT_REQUIRE_C(Type == 'd' || Type == 'i')> static void format_impl(T const & val, It & i, It precision_pos) { auto abs = val < 0 ? -val : val; while (abs) { *i++ = abs % 10 + '0'; abs /= 10; } while (i < precision_pos) *i++ = '0'; if (val < 0) *i++ = '-'; else if (sign) *i++ = '+'; else if (space) *i++ = ' '; } template<char Type, typename It, DESALT_REQUIRE_C(Type == 'u')> static void format_impl(T const & val, It & i, It precision_pos) { auto uval = static_cast<typename std::make_unsigned<T>::type>(val); while (uval) { *i++ = uval % 10 + '0'; uval /= 10; } while (i < precision_pos) *i++ = '0'; } template<char Type, typename It, DESALT_REQUIRE_C(Type == 'o')> static void format_impl(T const & val, It & i, It precision_pos) { auto uval = static_cast<typename std::make_unsigned<T>::type>(val); while (uval) { *i++ = (uval & 7) + '0'; uval >>= 3; } while (i < precision_pos) *i++ = '0'; if (alternative && *std::prev(i) != '0') *i++ = '0'; } template<char Type, typename It, DESALT_REQUIRE_C(Type == 'x' || Type == 'X')> static void format_impl(T const & val, It & i, It precision_pos) { auto uval = static_cast<typename std::make_unsigned<T>::type>(val); constexpr char const * table = type == 'x' ? "0123456789abcdef" : "0123456789ABCDEF"; while (uval) { *i++ = table[uval & 0xf]; uval >>= 4; } while (i < precision_pos) *i++ = '0'; if (alternative && val != 0) { *i++ = type; *i++ = '0'; } } // n進k桁でn^k種類の数を表現できる // 2^bits種類の数を表わすには何桁あれば十分か // (n, bits は非負整数) // n^k>2^bits // log_n(n^k)>log_n(2^bits) // k>log_n(2^bits) // k>bits*log_n(2) // k>bits/log_2(n) // <== // k>bits/log_2_int(n) // (log_2_int(n)をlog_2(n)の整数部分とする. // log_2(n) >= log_2_int(n) // であるので // bits/log_2(n) <= bits/log_2_int(n) // がいえる) static constexpr auto upper_bound_size(unsigned bits, unsigned base) { return bits / integer_formatter::log_2_int(base); } static constexpr auto log_2_int(unsigned n) { struct t { static constexpr unsigned impl(unsigned n, unsigned ret) { return n != 0 ? t::impl(n>>1, ret+1) : ret; } }; return !n ? 0 : t::impl(n, 0)-1; } }; } namespace traits { template<char const * String, std::size_t I, std::size_t E, typename T> struct argument_formatter<String, I, E, T, typename std::enable_if<std::is_integral<T>::value>::type> : detail::integer_formatter<String, I, E, T> { using base = detail::integer_formatter<String, I, E, T>; using base::end_pos; using base::used_indexes_count; using base::format; }; } }} #endif
true
14182271d596dd0151ab209d6f62d14b9129b959
C++
DoubleTimeOnly/Battleship-Puzzle-
/ship.cpp
UTF-8
1,097
3.34375
3
[]
no_license
// File: board.cpp #include "ship.h" #include <iostream> using namespace std; //sorts by length,then row, then column bool longest_first(Ship s1,Ship s2){ if (s1.length>s2.length) { return true; } else if( s1.length==s2.length && s1.row<s2.row) { return true; } else if (s1.length==s2.length && s1.row==s2.row && s1.column<s2.column) { return true; } else if (s1.length==s2.length && s1.row==s2.row && s1.column==s2.column && s1.orientation<s2.orientation) { return true; } return false; } void Ship::printShip() const { cout.width(10);cout<<left<<name<<" "; cout<<row<<" "<<column; if (length!=1) { if (orientation==0) {cout<<" horizontal"<<endl;} else {cout<<" vertical"<<endl;} } else {cout<<endl;} } bool Ship::operator==(const Ship& ship1) const { return (ship1.length==length && ship1.row==row && ship1.column==column && ship1.orientation==orientation); } bool Ship::operator!=(const Ship& ship1) const { return not (ship1.length==length && ship1.row==row && ship1.column==column && ship1.orientation==orientation) ; }
true
2ec0df72c1c3c6b177f1e2b7c5cbef717852d780
C++
vsmreddy/TessySamples
/CppCmdLine/source/point.cpp
UTF-8
326
3.390625
3
[ "MIT" ]
permissive
#include "point.h" Point::Point() : X(0), Y(0) { } Point::Point(int x, int y) : X(x), Y(y) { } Point::Point(Point &p) : X(p.X), Y(p.Y) { } bool Point::operator==(Point &p) { return (X == p.X && Y == p.Y); } void Point::move(Point &p) { X += p.X; Y += p.Y; } void Point::move(int x, int y) { X += x; Y += y; }
true
646a1e6d6d520ab933412df6154aa5ea7cea870d
C++
h6294443/2DFDTD-CUDA-Hexagons-VBO
/user_input.cpp
UTF-8
2,675
3.0625
3
[]
no_license
/* This source file belongs to project "Ch8_8.4 (TMz Example) */ #include <stdio.h> #include <stdlib.h> #include "global.h" void initialize_parameters(Grid g*) { //double src_f; //double Sc; //double X, Y; //double N_lambda; // Step 1: Specify source frequency printf("Enter source frequency in kHz: "); scanf_s(" %g", &src_f); // Step 2: Calculate wavelength const double lambda = c / src_f; // Wavelength of the source (for a sine or cosine) // Step 3: Specify Sc: printf("\n\nEnter desired Courant number (0.1-0.8): "); scanf_s(" %g", &Sc); if (Sc < 0.1) Sc = 0.1; if (Sc > 0.8) Sc = 0.8; // Step 4: Specify physical domain size in meters printf("\n\nEnter the domain width (X) in meters: "); scanf_s(" %g", &X); printf("\n\nEnter the domain height (Y) in meters: "); scanf_s(" %g", &Y); // Step 5: Specify desired points-per-wavelength N_lambda printf("\n\nEnter points-per-wavelength (can be a float): "); scanf_s(" %g", &N_lambda); // Step 6: Calculate dx (this may not be dx as defined) const double dx = lambda / N_lambda; // This is the largest distance possible within one hexagon - from one point to the opposing pointy point // Step 7: Calculate dt const double dt = Sc*dx / c; // Step 8: Calculate M and N int M = (2 * X) / (sqrt(3.0) * dx); int N = (4 * Y) / (3.0 * dx); // Step 8: Specify source position (and soon, type) const int src_pos_x = (int)(0.15*M); const int src_pos_y = (int)(0.5*N); // Step 9: Specify desired slowdown, if any. const int slowdown = 25; // Step 1: Specify source frequency //const double src_f = 1.1e7; // Frequency of the source (for a sine or cosine) // Step 2: Calculate wavelength //const double lambda = c / src_f; // Wavelength of the source (for a sine or cosine) // Step 3: Specify Sc: //double Sc = sqrt(2.f / 3.f) - 0.15; // Force 0.1 - 0.8 // Step 4: Specify physical domain size in meters //const double X = 30; //const double Y = 30; // Step 5: Specify desired points-per-wavelength N_lambda //const double N_lambda = 250; // Step 6: Calculate dx (this may not be dx as defined) //const double dx = lambda / N_lambda; // This is the largest distance possible within one hexagon - from one point to the opposing pointy point // Step 7: Calculate dt //const double dt = Sc*dx / c; // Step 8: Calculate M and N //int M = (2 * X) / (sqrt(3.0) * dx); //int N = (4 * Y) / (3.0 * dx); // Step 8: Specify source position (and soon, type) //const int src_pos_x = (int)(0.15*M); //const int src_pos_y = (int)(0.5*N); // Step 9: Specify desired slowdown, if any. //const int slowdown = 25; return; }
true
d7b40d4cee177df5206cae6226ca2128c5168fc9
C++
bonfa/ACTR_Cpp_VisualModule
/BaseClass/src/utils.h
UTF-8
1,504
2.703125
3
[]
no_license
/* * utils.h * * Created on: 02/nov/2012 * Author: enrico */ #ifndef UTILS_H_ #define UTILS_H_ #define MAX_X 1 #define MAX_Y 2 #define MIN_X 3 #define MIN_Y 4 #define EPSILON 0.00001 #include <opencv/cv.h> #include <vector> #include <math.h> #include <ios> #include "MyPoint.h" #include "StraightLine.h" #include "FeatureGetterExceptions.h" #include <fstream> int getMinMax(const std::vector<Point>& coords, int type); std::vector<Point> Sort4PointsClockwise(std::vector<Point> points); double erone(Point a, Point b, Point c); /** * Given three 2D points, this method calculates if all of them * belong to the same line * */ bool inLinePoints(int ax, int ay, int bx, int by, int cx, int cy ); /** * Given two 2D points, this method calculates the distance between them. * The distance is calculated as * * sqrt((a.x-b.x)^2 + (a.y-b.y)^2) * * @author: francesco * * */ double myDistance(Point a, Point b); /** * This method tells if two double values are equal under a certain values * * The precision is determined by a variable called EPSILON which * is defined externally to the function * */ bool areSame(double a, double b); /** * This method returns the minimum value of the input list * */ double getMin(const std::vector<double>& values); /** Return true if the file exists, otherwise false*/ bool fileExists(char * path); /** Converts the integer input value to a string value //TODO testing*/ string intToString(int a); #endif /* UTILS_H_ */
true
c3b57a1a84e15c5d92bf10e023a324d0c61bbaa8
C++
sergiobanegas/ShoppingList-cpp
/src/ItemProcessor.cpp
UTF-8
1,670
3.140625
3
[]
no_license
/* * ItemProcessor.cpp * * Created on: Dec 19, 2015 * Author: sergio */ #include "ItemProcessor.h" ItemProcessor::ItemProcessor() { this->items=NULL; this->numberOfItems=0; } ItemProcessor::~ItemProcessor() { for (int i=0;i<this->numberOfItems;i++){ delete this->items[i]; } delete [] this->items; } bool ItemProcessor::load(const char* file) const{ ifstream myFile; myFile.open(file, ifstream::in); string line; if (myFile){ int i=0; myFile >> this->numberOfItems; this->items= new Item*[this->numberOfItems]; while ((getline(myFile, line))&&(i<this->numberOfItems)){ int type; myFile >> type; int amount; string name, author, brand; double price; if (type==1){ myFile >> name >> author >> price; this->items[i]=new Book(name, price, author); } else if (type==2){ myFile >> name >> amount >> price; this->items[i]=new SupermarketProduct(name, price, amount); } else if (type==3){ myFile >> brand >> name >> amount >> price; this->items[i]=new Toy(name, price, brand, amount); } ++i; } myFile.close(); return true; } else{ cout << "Error: el fichero input.txt no existe"; exit(0); } } double ItemProcessor::pvp() const{ double totalPrice=0.0; for (int i=0;i<this->numberOfItems;i++){ totalPrice+=roundf(this->items[i]->pvp()*100)/100; } return roundf(totalPrice*100)/100; } string ItemProcessor::generateTicket() const{ stringstream ticket; ticket << "\n"; for (int i=0;i<this->numberOfItems;i++){ ticket << (this->items[i]->getInfo()) << "\n"; } ticket << this->pvp() << " €" << "\n"; return (ticket.str()); }
true
53ed10fc56681895eccf30ba8b3590db41fabf77
C++
stevenGarciaDev/MessageQueue
/MessageQueue/ProbeA.cpp
UTF-8
3,223
2.78125
3
[]
no_license
// // ProbeA.cpp // MessageQueue // #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <cstring> #include <iostream> #include <unistd.h> #include <sys/wait.h> #include <cstdlib> #include <limits> #include <string> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <bits/stdc++.h> using namespace std; const int MTYPE = 555; const int HUBTYPE = 556; const int MAGIC_SEED_ALPHA = 997; const int DATA_HUB_MTYPE = 117; const int MAX_INT = std::numeric_limits<int>::max(); int main() { srand( time(0) ); bool isExecuting = true; bool isAcknowledged = false; string sendingMsg = ""; // generates system wide key for the queue int qid = msgget(ftok(".",'u'), 0); cout << "qid is " << qid << endl; // declare my message buffer struct buf { long mtype; // required char greeting[50]; // mesg content }; buf msg; int size = sizeof(msg)-sizeof(long); cout << size << endl; cout << MAGIC_SEED_ALPHA << endl; cout << "/* ----------- Probe A --------------- */" << endl; while (isExecuting) { // generate a valid random number int randomValue = MAX_INT; randomValue = rand() % MAX_INT; if (randomValue <= 100) { cout << "Probe A will terminate as random value is less than 100: value is " << randomValue << endl; msg.mtype = MTYPE; sendingMsg = "PROBEA:" + to_string(getpid()) + ":EXIT"; strcpy(msg.greeting, sendingMsg.c_str() ); msgsnd(qid, (struct msgbuf *)&msg, size, 0); // send message to queue isExecuting = false; continue; } if (randomValue % MAGIC_SEED_ALPHA == 0) { cout << "The random value is " << randomValue << endl; // send to DataHub msg.mtype = MTYPE; sendingMsg = "PROBEA:" + to_string(getpid()) + ":" + to_string(randomValue); strcpy(msg.greeting, sendingMsg.c_str() ); msgsnd(qid, (struct msgbuf *)&msg, size, 0); // send message to queue cout << "Sending Message: " << msg.greeting << endl; // wait for acknowledgement from DataHub while (!isAcknowledged) { msgrcv(qid, (struct msgbuf *)&msg, size, HUBTYPE, 0); // read incoming message vector <string> tokens; // Vector containing split string string currentMsg = msg.greeting; // Load message into a string stringstream check1(currentMsg); // Stringstream currentMsg string intermediate; // Temp string for iteration // Tokenizing by ':' while(getline(check1, intermediate, ':')) { tokens.push_back(intermediate); } if ((tokens[0].compare("HUB") == 0) && (tokens[2].compare("ACKNOWLEDGED") == 0)) { isAcknowledged = true; cout << "Receive acknowledgement from DataHub\n" << endl; } } isAcknowledged = false; } } return 0; }
true
09c33df91c8c720d220b8a32239f25a634bb5015
C++
Crayzero/LeetCodeProgramming
/Solutions/Path Sum II/main.cpp
UTF-8
2,180
3.546875
4
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x): val(x), left(NULL), right(NULL) {} }; class Solution { public: bool hasPathSum(TreeNode *root, int sum) { if (root == NULL) { return false; } cout<<root->val<<" "<<sum<<endl; if (root ->left == NULL && root->right == NULL) { if (sum == root->val) { return true; } else { return false; } } return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > res; if (root == NULL) { return res; } if (root ->left == NULL && root->right == NULL) { if (sum == root->val) { res.push_back(vector<int>(1,root->val)); return res; } else { return res; } } vector<vector<int> > left_res = pathSum(root->left, sum - root->val); vector<vector<int> > right_res = pathSum(root->right, sum - root->val); for (auto iter = left_res.begin(); iter != left_res.end(); iter++) { iter->insert(iter->begin(), root->val); res.push_back(*iter); } for (auto iter = right_res.begin(); iter != right_res.end(); iter++) { iter->insert(iter->begin(), root->val); res.push_back(*iter); } return res; } }; int main() { TreeNode *a = new TreeNode(5); TreeNode *b = new TreeNode(4); TreeNode *c = new TreeNode(8); TreeNode *d = new TreeNode(11); TreeNode *e = new TreeNode(13); TreeNode *f = new TreeNode(4); TreeNode *g = new TreeNode(7); TreeNode *h = new TreeNode(2); TreeNode *i = new TreeNode(1); a->left = b; a->right = c; b->left = d; c->left = e; c->right = f; d->left = g; d->right = h; f->right = i; Solution s; cout<<s.hasPathSum(a, 18)<<endl; return 0; }
true
0d0d383fc174548e3a1c03715516e4ec28baeeb0
C++
Dhanush123/Lab6
/inputValidation.cpp
UTF-8
1,060
3.421875
3
[]
no_license
// Lab 6 // Programmer: Dhanush Patel // Editor(s) used: Eclipse // Compiler(s) used: Eclipse #include <iomanip> #include <iostream> #include <string> using namespace std; #include <cmath> int main() { cout << "Programmer: Dhanush Patel" << endl; cout << "Description: This program calculates a mortgage given a predetermined amount of money borrowed after a correct password has been entered." << endl; // input values int years = 15; int D = 1000; // output (calculated) values double p = 0.065 / 12; // 6.5% annual interest rate double T = years * 12; double S = D * ((pow(1 + p, T) - 1) / p); cout << endl; //password entering string password = "pass123"; string passwordEntered; do{ cout << "Enter your password: "; cin >> passwordEntered; }while(password != passwordEntered); cout << endl; // formatting output (see 4.2) cout << "In " << years << " years, " << "$" << D << " deposited per month will grow to " << "$"; cout.setf(ios::fixed|ios::showpoint); cout << setprecision(2); cout << S << "." << endl; }
true
287f0c1b39382cfac911b47b20711168b736135e
C++
DanyFids/Business-of-Bandits
/BoB-FileHandler_CPP_CODE/BoB-FileHandler/Object.cpp
UTF-8
974
2.828125
3
[]
no_license
#include "Object.h" Object::Object(std::string i, std::string p, Transform t) { id = i; prefab = p; transform = t; } Object::Object(std::string i, std::string p, Vector3 pos, Vector3 rot, Vector3 siz) { id = i; prefab = p; transform = Transform(pos, rot, siz); } std::string Object::GetId() { return id; } std::string Object::ToString() { std::string ret = ""; ret += "\"" + id + "\"\n"; ret += "{\n"; ret += "\tprefab: \"" + prefab + "\"\n"; ret += "\tposition: (" + std::to_string(transform.position.x) + "," + std::to_string(transform.position.y) + ", " + std::to_string(transform.position.z) + ")\"\n"; ret += "\trotation: (" + std::to_string(transform.rotation.x) + "," + std::to_string(transform.rotation.y) + ", " + std::to_string(transform.rotation.z) + ")\"\n"; ret += "\tscale: (" + std::to_string(transform.scale.x) + "," + std::to_string(transform.scale.y) + ", " + std::to_string(transform.scale.z) + ")\"\n"; ret += "}\n"; return ret; }
true
bba3022c3beb81aac24872b7dde754d62dc49f99
C++
kevinawongw/CSCI1300-IntroToProgrammingCPP
/Homework/hmwk10EC/Program.cpp
UTF-8
2,866
3.15625
3
[]
no_license
#include <iostream> #include <iomanip> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <regex> #include <algorithm> #include "Program.h" #include "Words.h" using namespace std; Program :: Program (){ } void Program :: readVocabulary(string fileName){ string line; int i=0; ifstream file (fileName.c_str()); if (file.is_open()){ while (getline(file, line)){ wordVec.push_back(line); i++; } cout << "Read " << i << " words from " << fileName << endl; } else{ cout << fileName << " does not exist" << endl; } } void Program :: readMisspelling(string fileName){ string line; int i=0; ifstream file (fileName.c_str()); if (file.is_open()){ while (getline(file, line)){ stringstream wordList(line); string right; wordList >> right; correctSpelling.push_back(right); string wrong; wordList >> wrong; incorrectSpelling.push_back(wrong); i++; } cout << "Read " << i << " words from " << fileName << endl; } else{ cout << fileName << " does not exist" << endl; } } void Program :: fixSpelling(){ cout << "Enter the phrase you would like to correct:" << endl; string sentence; getline (cin,sentence); stringstream sent(sentence); string wordss; int b =0; while (getline (sent,wordss,' ')){ if (b ==0){ for (int i =0;i<wordss.length();i++){ char c = wordss [i]; if (!(c >= 65 && c <= 90) && !(c >= 97 && c <= 122)){ wordss = ""; cout << ""; b++; } } } bool c = false; if (wordss=="I" || wordss == "i"){ cout << wordss; c=true; } bool a = false; for (int i=0;i<incorrectSpelling.size();i++){ if (regex_match(wordss,regex(incorrectSpelling[i]))){ cout << correctSpelling[i]; a = true; break; } else if (toLowerCase(wordss)==toLowerCase(correctSpelling[i])){ cout << correctSpelling[i]; a=true; break; } else if (toLowerCase(wordss)==toLowerCase(wordVec[i])){ cout << wordVec[i]; a=true; break; } } if (a==false){ if (wordss != ""){ cout << "unknown"; } } cout << " "; } } string Program :: toLowerCase(string str){ string ans = ""; for(int i = 0; i < str.length(); i++){ ans += tolower(str[i]); } return ans; }
true
6bb1d63ee43234acbb770403b304b889e2ba12d9
C++
possientis/Prog
/poly/DesignPatterns/Decorator/decorator.cpp
UTF-8
4,454
3.96875
4
[]
no_license
// Decorator Design Pattern #include <iostream> #include <iomanip> // std::setprecision #include <string> #include <assert.h> // interface or abstract class of components class Pizza { protected: Pizza(){} public: virtual ~Pizza(){} virtual std::string getDescription() const = 0; virtual double getCost() const = 0; }; // concrete component class PlainPizza : public Pizza { public: PlainPizza(); virtual std::string getDescription() const override { return "Plain pizza"; } virtual double getCost() const override { return 3.0; } virtual ~PlainPizza(); }; PlainPizza::PlainPizza(){ // std::cerr << "Creating pizza " << std::hex << this << std::endl; } PlainPizza::~PlainPizza(){ // std::cerr << "Deleting pizza " << std::hex << this << std::endl; } // root abstract class of decorators implementing component interface // a decorator object is therefore a component and will hold a // concrete component as data member. Default implementation // achieved simply by forwarding class PizzaDecorator : public Pizza { protected: const Pizza* _pizza; public: PizzaDecorator(Pizza* pizza): _pizza(pizza){ assert(_pizza != nullptr); } virtual std::string getDescription() const override; virtual double getCost() const override; virtual ~PizzaDecorator(); }; // default implementation std::string PizzaDecorator::getDescription() const { return _pizza->getDescription(); } // default implementation double PizzaDecorator::getCost() const { return _pizza->getCost(); } PizzaDecorator::~PizzaDecorator(){ delete _pizza; } // first concrete decorator class WithExtraCheese : public PizzaDecorator { public: WithExtraCheese(Pizza* pizza) : PizzaDecorator(pizza) {} virtual std::string getDescription() const override; virtual double getCost() const override; virtual ~WithExtraCheese(){} }; std::string WithExtraCheese::getDescription() const { return _pizza->getDescription() + " + extra cheese"; } double WithExtraCheese::getCost() const { return _pizza->getCost() + 0.5; } // second concrete decorator class WithExtraOlives : public PizzaDecorator { public: WithExtraOlives(Pizza* pizza) : PizzaDecorator(pizza) {} virtual std::string getDescription() const override; virtual double getCost() const override; virtual ~WithExtraOlives(){} }; std::string WithExtraOlives::getDescription() const { return _pizza->getDescription() + " + extra olives"; } double WithExtraOlives::getCost() const { return _pizza->getCost() + 0.7; } // third concrete decorator class WithExtraAnchovies : public PizzaDecorator { public: WithExtraAnchovies(Pizza* pizza) : PizzaDecorator(pizza) {} virtual std::string getDescription() const override; virtual double getCost() const override; virtual ~WithExtraAnchovies(){} }; std::string WithExtraAnchovies::getDescription() const { return _pizza->getDescription() + " + extra anchovies"; } double WithExtraAnchovies::getCost() const { return _pizza->getCost() + 0.8; } int main(){ Pizza* plainPizza = new PlainPizza(); Pizza* nicePizza = new WithExtraCheese( new PlainPizza()); Pizza* superPizza = new WithExtraOlives( new WithExtraCheese( new PlainPizza())); Pizza* ultraPizza = new WithExtraAnchovies( new WithExtraOlives( new WithExtraCheese( new PlainPizza()))); std::cout << "Plain Pizza: " << std::fixed << std::setprecision(1) << "\tCost: " << plainPizza->getCost() << "\tDescription: " << plainPizza->getDescription() << std::endl; std::cout << "Nice Pizza: " << std::fixed << std::setprecision(1) << "\tCost: " << nicePizza->getCost() << "\tDescription: " << nicePizza->getDescription() << std::endl; std::cout << "Super Pizza: " << std::fixed << std::setprecision(1) << "\tCost: " << superPizza->getCost() << "\tDescription: " << superPizza->getDescription() << std::endl; std::cout << "Ultra Pizza: " << std::fixed << std::setprecision(1) << "\tCost: " << ultraPizza->getCost() << "\tDescription: " << ultraPizza->getDescription() << std::endl; delete ultraPizza; delete superPizza; delete nicePizza; delete plainPizza; return 0; }
true
e5c5ec13b024646349412132a0b0293c7215b0fb
C++
iurisevero/Exercicios-PPC
/LeetCode/missingNumber.cpp
UTF-8
340
2.78125
3
[]
no_license
class Solution { public: int missingNumber(vector<int>& nums) { int actual_sum = 0, real_sum = 0; for(int n : nums) actual_sum += n; int _size = nums.size(); real_sum = (_size % 2? _size * ((_size + 1) / 2) : (_size / 2) * (_size + 1)); return real_sum - actual_sum; } };
true
0ec194b89723a15b5ffce0df23d8e80c21a6d7ef
C++
Rohitm911/1BM17CS079_ADA
/lab10_dijkstra.cpp
UTF-8
1,375
3.03125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int getMinV(bool* visi, int* dist, int n){ int minV = -1; for (int i = 0; i < n; i++){ if (!visi[i] && (minV == -1 || dist[i] < dist[minV])) minV = i; } return minV; } void dijkstra(int** edges, int n){ bool visi[n]; int dist[n]; int parent[n]; for (int i = 0; i < n; i++){ visi[i] = false; dist[i] = INT_MAX; } dist[0] = 0; parent[0] = -1; for (int i = 0; i < n - 1; i++){ int minV = getMinV(visi, dist, n); visi[minV] = true; for (int j = 0; j < n; j++){ if (!visi[j] && edges[minV][j] && (dist[j] > dist[minV] + edges[minV][j])){ dist[j] = dist[minV] + edges[minV][j]; parent[j] = minV; } } } for (int i = 0; i < n; i++){ cout << "Distance from Source (1) to "<< i+1 <<" : " << dist[i] << endl; } } int main(){ int n; cin >> n; int** edges = new int*[n]; for (int i = 0; i < n; i++){ edges[i] = new int[n]; for (int j = 0; j < n; j++) edges[i][j] = 0; } int m; cin >> m; for (int i = 0; i < m; i++){ int v1, v2, w; cin >> v1 >> v2 >> w; edges[v1-1][v2-1] = w; edges[v2-1][v1-1] = w; } dijkstra(edges, n); return 0; }
true
2de87f437b73ecef0c6c5d4c27f4956e426b9306
C++
Chandrika372/snapCode
/_submissions/18UEI056_Prashun/Day10/Evalute_exp.cpp
UTF-8
1,392
3.3125
3
[]
no_license
/*bool isOperator(string a) { if(a=="+"||a=="*"||a=="-"||a=="/") return true; else return false; } string opSum(string a,string b,string op) { int n1=stoi(a); int n2=stoi(b); // n1=max(n1,n2); // n2=min(n1,n2); if(op=="+") return to_string(n1+n2); if(op=="-") return to_string(abs(n1-n2)); if(op=="*") return to_string(n1*n2); if(op=="/") { int x=max(n1,n2); int y=min(n1,n2); return to_string(floor(x/y)); } } int Solution::evalRPN(vector<string> &A) { int n=A.size(); // string a="",b=""; stack<string>s; for(int i=0;i<n;i++) {string a="",b=""; if(!isOperator(A[i])) s.push(A[i]); else { a=s.top();s.pop(); b=s.top();s.pop(); s.push(opSum(a,b,A[i])); } } string c=s.top();s.pop(); return stoi(c); }*/ int Solution::evalRPN(vector<string> &A) { stack<string>k; for(int i = 0; i < A.size(); i++) if(A[i] == "/" || A[i] == "*" || A[i] == "+" || A[i] == "-") { int y = stoi(k.top());k.pop(); int x = stoi(k.top());k.pop(); switch(A[i][0]) { case '+': k.push(to_string(x + y));break; case '-': k.push(to_string(x - y));break; case '*': k.push(to_string(x * y));break; case '/': k.push(to_string(x / y));break; } } else k.push(A[i]); return stoi(k.top()); }
true
3bc45f4f627a4311efde9f43f59cbd1502c1a5dd
C++
fablab02/shipinlab_teensy
/gps_reader.cpp
UTF-8
3,611
2.75
3
[]
no_license
#include "gps_reader.h" #include "WProgram.h" GpsReader::GpsReader() :m_lastFix(0) { resetBuffer(); } void GpsReader::resetBuffer(){ m_bufferIndLast = 0; } bool GpsReader::readChar(char c){ if(c == '$'){ Serial.printf("readChar $\n"); resetBuffer(); } else if(c == '\n'){ Serial.printf("readChar \\n\n"); parseBuffer(); return true; } else { this->m_buffer[m_bufferIndLast] = c; m_bufferIndLast++; } return false; } void GpsReader::error(){ Serial.print("error"); } void GpsReader::debug(){ Serial.print(m_tempInd); Serial.print(" "); Serial.print(m_buffer[m_tempInd-1]); Serial.print(m_buffer[m_tempInd]); Serial.print(m_buffer[m_tempInd+1]); Serial.print("\n"); } void GpsReader::readUntilCommat(){ while(m_tempInd < m_bufferIndLast){ if(m_buffer[m_tempInd] == ','){ ++m_tempInd; return; } ++m_tempInd; } error(); } int GpsReader::getOneInt(){ char c = m_buffer[m_tempInd]; m_tempInd++; if(c =='0'){ return 0; } else if(c =='1'){ return 1; } else if(c =='2'){ return 2; } else if(c =='3'){ return 3; } else if(c =='4'){ return 4; } else if(c =='5'){ return 5; } else if(c =='6'){ return 6; } else if(c =='7'){ return 7; } else if(c =='8'){ return 8; } else if(c =='9'){ return 9; } else { error(); } return 0; } double GpsReader::readDouble(){ double res = 0; double virgule_part = 1; bool virgule = false; while(m_tempInd < m_bufferIndLast){ char c = m_buffer[m_tempInd]; int number = 0; if(c == ','){ ++m_tempInd; return res; } else if(c =='0'){ number = 0; } else if(c =='1'){ number = 1; } else if(c =='2'){ number = 2; } else if(c =='3'){ number = 3; } else if(c =='4'){ number = 4; } else if(c =='5'){ number = 5; } else if(c =='6'){ number = 6; } else if(c =='7'){ number = 7; } else if(c =='8'){ number = 8; } else if(c =='9'){ number = 9; } else if(c =='.'){ virgule = true; } if(!virgule){ res = res * 10 + number; } else { res = res + number * virgule_part; virgule_part = virgule_part * 0.1; } ++m_tempInd; } error(); } //$GPGGA,114608.00,4905.46094,N,00332.09303,E,2,07,1.46,87.8,M,46.3,M,,0000*6B void GpsReader::parseBuffer(){ for(int i = 0; i < m_bufferIndLast; ++i){ Serial.print(m_buffer[i]); } Serial.print("\n"); m_tempInd = 0; readUntilCommat(); readUntilCommat(); //debug(); m_lastLatitudeDeg = readDouble(); readUntilCommat(); //debug(); m_lastLongitudeDeg = readDouble(); m_lastFix = getOneInt(); } void GpsReader::readNextFrame(){ while(true){ while ( Serial2.available()){ char c = Serial2.read(); if(this->readChar(c)){ return; } } } } double GpsReader::convertDegMinToDecDeg (float degMin) { // Serial.println(degMin); int h = degMin/100; int minu = (degMin-(h*100)); float sec =(degMin-((h*100)+minu))*100.0; float minum = minu +(sec/60.0); float decDeg = h + (minum/60.0) ; // Serial.println(decDeg,6); return decDeg; }
true
f039954f6c87dddb3077fecb6f891104f54312be
C++
osamahatem/CompetitiveProgramming
/Codeforces/917A. The Monster.cpp
UTF-8
859
2.71875
3
[]
no_license
/* * 917A. The Monster.cpp * * Created on: Jan 29, 2018 * Author: Osama Hatem */ /* Greedily try to always replace all '?' with ')', and swap them later as needed. */ #include <bits/stdtr1c++.h> #include <ext/numeric> using namespace std; int main() { #ifndef ONLINE_JUDGE freopen("in.in", "r", stdin); // freopen("out.out", "w", stdout); #endif cin.tie(0); cout.tie(0); ios::sync_with_stdio(false); string s; cin >> s; int ans = 0; for (int i = 0; i < (int) s.size(); i++) { int op = 0, w = 0; for (int j = i; j < (int) s.size(); j++) { if (s[j] == '(') { op++; } else if (s[j] == ')') { if (!op && !w) { op = -1; break; } if (op) op--; else w--, op++; } else { if (op) op--, w++; else op++; } if (op == 0) ans++; } } cout << ans << endl; return 0; }
true
f8ebad4d5fd38392ad0b2483b2db49364d90fbc7
C++
msrLi/portingSources
/ACE/ACE_wrappers/protocols/ace/INet/HTTP_Status.inl
UTF-8
1,155
2.828125
3
[ "Apache-2.0" ]
permissive
// -*- C++ -*- ACE_BEGIN_VERSIONED_NAMESPACE_DECL namespace ACE { namespace HTTP { ACE_INLINE void Status::set_status(Code status) { this->code_ = status; } ACE_INLINE Status::Code Status::get_status() const { return this->code_; } ACE_INLINE void Status::set_reason(const ACE_CString& reason) { this->reason_ = reason; } ACE_INLINE const ACE_CString& Status::get_reason() const { return this->reason_; } ACE_INLINE void Status::set_status_and_reason(Code status) { this->reason_ = get_reason (this->code_ = status); } ACE_INLINE bool Status::is_valid () const { return this->code_ != INVALID; } ACE_INLINE bool Status::is_ok () const { return this->code_ >= HTTP_OK && this->code_ < HTTP_BAD_REQUEST; } ACE_INLINE Status::operator bool() const { return this->is_valid (); } ACE_INLINE bool Status::operator !() const { return !this->is_valid (); } } } ACE_END_VERSIONED_NAMESPACE_DECL
true
b25a589785386ac066d89564dd21f56501f1c1eb
C++
CDPS/Competitive-Programming
/UVA/10474 - Where is the Marble.cpp
UTF-8
920
2.890625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int a[1000000]; int binarySearch(int l, int h, int t){ while(l <= h){ int m = (l+h)/2; if(a[ m] == t) return m; else if( t < a[m]) h = m-1; else l = m+1; } return -1; } //also solvable with lower_bound function //just practicing the classic binary search version. int main(){ int n,m,caseno=1; while(scanf("%d %d",&n,&m)){ if(n==0 && m==0) break; for(int i=0;i<n;i++) scanf("%d",a+i); sort(a,a+n); int q; printf("CASE# %d:\n",caseno++); while(m--){ scanf("%d",&q); int idx = binarySearch(0,n-1,q); if(idx==-1) printf("%d not found\n",q); else{ for(int i=idx-1;i >=0 && a[i]==q;i--) idx--; printf("%d found at %d\n",q, idx+1); } } } return 0; }
true
a4a7501ba6c9d9062cc1c620368c4c45907a5ca4
C++
ShakilAhammed/OnlineJudge
/UVA OJ/12468.cpp
UTF-8
606
2.5625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); int a,b; while(cin>>a>>b) { int diffChannel=0; if(a==-1 || b==-1)break; if((a==0 && b==99 )|| (a==99 && b==0)) { diffChannel=1; cout<<diffChannel<<endl; } else if((a-b)==0 || (b-a)==0)cout<<diffChannel<<endl; else { int tempDiffChannel=abs(a-b); if(tempDiffChannel>50) { if(a>50)a=99-a; else b=99-b; diffChannel=a+b+1; } else { diffChannel=tempDiffChannel; } cout<<diffChannel<<endl; } } return 0; }
true
beb3a5e2330c3f1699bcfb3710be4f1c5a0262a3
C++
devmichalek/Skipper
/Commands/cmd_rename.h
UTF-8
1,413
3.03125
3
[ "MIT" ]
permissive
#pragma once #include "cmd.h" class Command_Rename final : public Command { bool m_bEmpty; bool m_bHelp; bool m_bDirectory; bool m_bRecursive; bool m_bIgnore; bool m_bOmit; std::string m_sDirectory; std::string m_sRegex; std::string m_sNewName; public: explicit Command_Rename(std::vector<std::string> options); ~Command_Rename() {} bool parse(const char* filename, int &line); int run(); static std::string help() { std::string a = "\nDefinition:\n"; std::string b = "\trename - renames files\n"; std::string c = "\nSyntax:\n"; std::string d = "\t[-h --help] - prints help\n"; std::string e = "\t[-d --directory <directory name>] - searches in requested directory, if not specified searches in current directory\n"; std::string f = "\t[-r --recursive] - searches recursively\n"; std::string g = "\t[-i --ignore] - ignores errors and warnings, no break on error\n"; std::string h = "\t[-o --omit] - tries to omit digits at the end of the new name (in case of duplicates)\n"; std::string i = "\t[<regular expression> <new name>] - specifies regular expression key and new name for matched objects\n"; std::string j = "\n"; return a + b + c + d + e + f + g + h + i + j; } static std::string assist() { return " rename\n\t[-h --help]\n\t[-d --directory <directory name>]\n\t[-r --recursive]\n\t[-i --ignore]\n\t[-o --omit]\n\t[<regular expression> <new name>]\n"; } };
true
038c8b910a22c6ef60d39f57fc810e4a7fc77ea3
C++
xeon2007/LightSDK
/Source/Branch/MediaUICommon/Src/Include/AudioVolumeChangeHandler.h
UTF-8
1,095
2.609375
3
[]
no_license
/*! * @file AudioVolumeChangeHandler.h * * @brief This file defines class AudioVolumeChangeHandler, which defines functions for notification when * volume is changed. * * Copyright (C) 2010, Toshiba Corporation. * * @author Li Hong * @date 2011/03/08 */ #ifdef __cplusplus #ifndef _AUDIOVOLUMECALLBACK_H_ #define _AUDIOVOLUMECALLBACK_H_ #include "Common.h" #include "CommonMacro.h" BEGIN_NAMESPACE_COMMON class AudioVolumeController; /*! * @brief The AudioVolumeChangeHandler class. */ class CLASS_DECLSPEC AudioVolumeChangeHandler { public: /*! * @brief The destructor function. */ virtual ~AudioVolumeChangeHandler(); /*! * @brief Called when audio volume is changed. * * @param pVolumeController [I/ ] The AudioVolumeController instance, from which you can * get information about the audio volume. */ virtual void OnAudioVolumeChange(AudioVolumeController *pVolumeController); }; END_NAMESPACE #endif // _AUDIOVOLUMECALLBACK_H_ #endif // __cplusplus
true
6a2b7fb78ff7f250bfd442b4de779d83984d85d1
C++
rikonor/smallstuff
/particle_tmp36/tmp36.h
UTF-8
727
2.984375
3
[]
no_license
#ifndef TMP36_H #define TMP36_H const float tempSensorVoltageDivider = 4095.0; const float tempSensorReferenceVoltage = 3.3; const float tempSensorOffsetVoltage = 0.5; class TMP36TemperatureSensor { public: TMP36TemperatureSensor(int sensorPin); float temperatureCelcius(); private: int tempSensorPin; }; TMP36TemperatureSensor::TMP36TemperatureSensor(int pin) { tempSensorPin = pin; pinMode(tempSensorPin, INPUT); } float TMP36TemperatureSensor::temperatureCelcius() { float tempSensorVoltage = (tempSensorReferenceVoltage * analogRead(tempSensorPin)) / tempSensorVoltageDivider; float tempSensorTemperature = (tempSensorVoltage - tempSensorOffsetVoltage) * 100; return tempSensorTemperature; } #endif
true
b3a8e71d566601507ff5398a8055c159ab942bd0
C++
gkishard-workingboy/Algorithm-challenger
/kuangbin专题/专题一_简单搜索/POJ-3087.cc
UTF-8
1,144
2.71875
3
[ "MIT" ]
permissive
/* * Author : OFShare * E-mail : OFShare@outlook.com * Created Time : 2020-02-05 18:25:20 PM * File Name : POJ-3087.cc */ #include <iostream> #include <queue> #include <set> #include <cstring> #include <string> void debug() { #ifdef Acui freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif } int T, C; std::string s1, s2, target; std::set<std::string> st; struct node { std::string s; int step; }; int bfs(node s) { st.clear(); std::queue<node> que; que.push(s); while (!que.empty()) { node p = que.front(); que.pop(); std::string s = p.s, tmp; int step = p.step; // 找到了 if (s == target) { return step; } st.insert(s); // 转移即洗牌 for (int i = 0; i < C; ++i) { tmp += s[i + C]; tmp += s[i]; } if (st.count(tmp) == 0) { st.insert(tmp); que.push({tmp, step + 1}); } } return -1; } int main() { std::cin >> T; for (int kase = 1; kase <= T; ++kase) { std::cin >> C; std::cin >> s1 >> s2 >> target; std::cout << kase << " " << bfs({s1 + s2, 0}) << std::endl; } return 0; }
true
6d1437851b3526f80435ac93af67e0eefa451350
C++
TarekHasan011/Problem-Solving
/CodeForces/754B/31591104_AC_31ms_8kB.cpp
UTF-8
1,951
2.796875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; const int INF = 0x7f7f7f7f; char arr[4][4]; bool valid(int i, int j) { return i>=0 && i<4 && j>=0 && j<4; } bool win() { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(arr[i][j]=='x') { int first_i = i; int first_j = j-1; int first_ii = i; int first_jj = j+1; if(valid(first_i,first_j) && valid(first_ii,first_jj) && arr[first_i][first_j]=='x' && arr[first_ii][first_jj]=='x') return true; first_i = i-1; first_j = j; first_ii = i+1; first_jj = j; if(valid(first_i,first_j) && valid(first_ii,first_jj) && arr[first_i][first_j]=='x' && arr[first_ii][first_jj]=='x') return true; first_i = i-1; first_j = j-1; first_ii = i+1; first_jj = j+1; if(valid(first_i,first_j) && valid(first_ii,first_jj) && arr[first_i][first_j]=='x' && arr[first_ii][first_jj]=='x') return true; first_i = i+1; first_j = j-1; first_ii = i-1; first_jj = j+1; if(valid(first_i,first_j) && valid(first_ii,first_jj) && arr[first_i][first_j]=='x' && arr[first_ii][first_jj]=='x') return true; } } } return false; } bool solve() { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(arr[i][j]=='.') { arr[i][j] = 'x'; if(win()) return true; arr[i][j] = '.'; } } } return false; } int main() { #ifdef TarekHasan freopen("input.txt","r",stdin); #endif // TarekHasan for(int i=0;i<4;i++) for(int j=0;j<4;j++) cin >> arr[i][j]; cout << (solve() ? "YES" : "NO") << "\n"; return 0; }
true
21c639ef3b4e45cd2462a1ee9dde5085a080965e
C++
distroman/code
/search-rotated.cpp
UTF-8
970
3.640625
4
[]
no_license
//https://leetcode.com/problems/search-in-rotated-sorted-array/ class Solution { public: int searcher(vector<int>& nums, int beg, int end, int target) { if(beg > end) return -1; if(beg == end) return nums[beg] == target ? beg : -1; int mid = (beg + end) / 2; if(nums[mid] == target) return mid; if( nums[beg] <= nums[mid]) { if (target < nums[mid] && target >= nums[beg]) return searcher(nums, beg, mid - 1, target); return searcher(nums, mid + 1, end, target); } else { if(target <= nums[end] && target > nums[mid]) return searcher(nums, mid + 1, end, target); return searcher(nums, beg, mid - 1, target); } } int search(vector<int>& nums, int target) { if(nums.size() == 0) return -1; return searcher(nums, 0, nums.size() - 1, target); } };
true
a769bdf9f83c9ee81e38e806fef3faaa624f011a
C++
jgarciapueyo/stoc
/src/AST/ASTPrinter.cpp
UTF-8
8,128
2.828125
3
[]
no_license
//===- src/AST/ASTPrinter.cpp - Implementation of a printer for AST -----------------*- C++ -*-===// // //===------------------------------------------------------------------------------------------===// // // This file implements the ASTPrinter class. // It prints the AST in a pretty way with information about every node-> // //===------------------------------------------------------------------------------------------===// #include "stoc/AST/ASTPrinter.h" #include <iostream> #include "stoc/AST/BasicNode.h" #include "stoc/AST/Decl.h" #include "stoc/AST/Expr.h" #include "stoc/AST/Stmt.h" void ASTPrinter::increaseDepthLevel() { if (pre.length() > 0 && pre.at(pre.length() - 1) == '`') { pre.at(pre.length() - 1) = ' '; } pre += " |"; // add information to pre string (add 1 depth level) } void ASTPrinter::lastChild() { pre = pre.substr(0, pre.length() - 2); // restore pre string pre += " `"; // add information to pre string (add 1 depth level) // different from previous for being last child } void ASTPrinter::decreaseDepthLevel() { pre = pre.substr(0, pre.size() - 2); // restore pre string } void ASTPrinter::print(const std::shared_ptr<BasicNode> &ast) { ast->accept(this); } void ASTPrinter::visit(std::shared_ptr<VarDecl> node) { // print variable declaration token std::cout << pre << "-VarDecl <l." << node->getVarKeywordToken().line << ":c." << node->getVarKeywordToken().column << "> '" << node->getIdentifierToken().value << "' " << node->getTypeToken().tokenType << std::endl; increaseDepthLevel(); lastChild(); node->getValue()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<ConstDecl> node) { // print constant declaration token std::cout << pre << "-ConstDecl <l." << node->getConstKeywordToken().line << ":c." << node->getConstKeywordToken().column << "> '" << node->getIdentifierToken().value << "' " << node->getTypeToken().tokenType << std::endl; increaseDepthLevel(); lastChild(); node->getValue()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<ParamDecl> node) { std::cout << pre << "-ParamDecl <l." << node->getKeywordToken().line << ":c." << node->getKeywordToken().column << "> '" << node->getIdentifierToken().value << "' " << node->getTypeToken().tokenType << std::endl; } void ASTPrinter::visit(std::shared_ptr<FuncDecl> node) { std::cout << pre << "-FuncDecl <l." << node->getFuncKeywordToken().line << ":c" << node->getFuncKeywordToken().column << "> '" << node->getIdentifierToken().value << "' "; if (node->isHasReturnType()) { std::cout << node->getReturnTypeToken().tokenType; } std::cout << std::endl; increaseDepthLevel(); int size = node->getParams().size(); for (int i = 0; i < size; i++) { node->getParams().at(i)->accept(this); } lastChild(); node->getBody()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<BinaryExpr> node) { std::cout << pre << "-BinaryExpr <l." << node->getOp().line << ":c." << node->getOp().column << "> " << node->getOp().tokenType << " " << node->getType() << std::endl; increaseDepthLevel(); node->getLhs()->accept(this); lastChild(); node->getRhs()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<UnaryExpr> node) { std::cout << pre << "-UnaryExpr <l." << node->getOp().line << ":c." << node->getOp().column << "> " << node->getOp().tokenType << " " << node->getType() << std::endl; increaseDepthLevel(); lastChild(); node->getRhs()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<LiteralExpr> node) { std::cout << pre << "-LiteralExpr <l." << node->getToken().line << ":c." << node->getToken().column << "> " << node->getToken().tokenType << " '" << node->getToken().value << "' " << node->getType() << std::endl; } void ASTPrinter::visit(std::shared_ptr<IdentExpr> node) { std::cout << pre << "-IdentExpr <l." << node->getIdent().line << ":c." << node->getIdent().column << "> '" << node->getName() << "'" << " " << node->getType() << std::endl; } void ASTPrinter::visit(std::shared_ptr<CallExpr> node) { std::cout << pre << "-CallExpr " << node->getType() << std::endl; int size = node->getArgs().size(); if (size > 0) { increaseDepthLevel(); node->getFunc()->accept(this); for (int i = 0; i < size - 1; i++) { node->getArgs().at(i)->accept(this); } lastChild(); node->getArgs().at(size - 1)->accept(this); decreaseDepthLevel(); } else { increaseDepthLevel(); lastChild(); node->getFunc()->accept(this); decreaseDepthLevel(); } } void ASTPrinter::visit(std::shared_ptr<ExpressionStmt> node) { std::cout << pre << "-ExpressionStmt" << std::endl; increaseDepthLevel(); lastChild(); node->getExpr()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<DeclarationStmt> node) { std::cout << pre << "-DeclarationStmt" << std::endl; increaseDepthLevel(); lastChild(); node->getDecl()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<BlockStmt> node) { std::cout << pre << "-BlockStmt <l." << node->getLbrace().line << ":c." << node->getLbrace().column << "> - <l." << node->getRbrace().line << ":c." << node->getRbrace().column << ">" << std::endl; int size = node->getStmts().size(); if (size > 0) { increaseDepthLevel(); for (int i = 0; i < size - 1; i++) { node->getStmts().at(i)->accept(this); } lastChild(); node->getStmts().at(node->getStmts().size() - 1)->accept(this); decreaseDepthLevel(); } } void ASTPrinter::visit(std::shared_ptr<IfStmt> node) { std::cout << pre << "-IfStmt <l." << node->getIfKeyword().line << ":c." << node->getIfKeyword().column << ">" << std::endl; increaseDepthLevel(); node->getCondition()->accept(this); if (node->isHasElse()) { node->getThenBranch()->accept(this); lastChild(); node->getElseBranch()->accept(this); decreaseDepthLevel(); } else { lastChild(); node->getThenBranch()->accept(this); decreaseDepthLevel(); } } void ASTPrinter::visit(std::shared_ptr<ForStmt> node) { std::cout << pre << "-ForStmt <l." << node->getForKeyword().line << ":c." << node->getForKeyword().column << ">" << std::endl; increaseDepthLevel(); if (node->getInit() != nullptr) { node->getInit()->accept(this); } else { std::cout << pre << "- <<no initialization>>" << std::endl; } if (node->getCond() != nullptr) { node->getCond()->accept(this); } else { std::cout << pre << "- <<no condition>>" << std::endl; } if (node->getPost() != nullptr) { node->getPost()->accept(this); } else { std::cout << pre << "- <<no post statement>>" << std::endl; } lastChild(); node->getBody()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<WhileStmt> node) { std::cout << pre << "-WhileStmt <l." << node->getWhileKeyword().line << ":c." << node->getWhileKeyword().column << ">" << std::endl; increaseDepthLevel(); node->getCond()->accept(this); lastChild(); node->getBody()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<AssignmentStmt> node) { std::cout << pre << "-AssignmentStmt <l." << node->getEqualToken().line << ":c." << node->getEqualToken().column << ">" << std::endl; increaseDepthLevel(); node->getLhs()->accept(this); lastChild(); node->getRhs()->accept(this); decreaseDepthLevel(); } void ASTPrinter::visit(std::shared_ptr<ReturnStmt> node) { std::cout << pre << "-ReturnStmt <l." << node->getReturnKeyword().line << ":c." << node->getReturnKeyword().column << ">" << std::endl; if (node->getValue() != nullptr) { increaseDepthLevel(); lastChild(); node->getValue()->accept(this); decreaseDepthLevel(); } }
true
f37c5127f544d06fb1c62830943d53eaea6886ab
C++
maverick-zhang/Algorithms-Leetcode
/leetcode_day5/Q131_partition_palindrome.h
UTF-8
1,481
3.46875
3
[]
no_license
// // Created by maverick on 2020/1/6. // #ifndef ALGORITHMS_Q131_PARTITION_PALINDROME_H #define ALGORITHMS_Q131_PARTITION_PALINDROME_H //给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。 // //返回 s 所有可能的分割方案。 //输入: "aab" //输出: //[ //["aa","b"], //["a","a","b"] //] #include <vector> #include <string> using namespace std; //回溯法 class Solution { private: bool is_palindrome(const string & str) { int i = 0, j = str.size() - 1; while (i < j) { if (str[i] != str[j]) return false; i ++; j --; } return true; } vector<vector<string>> res; void __partition(const string & s, int index, vector<string> & vt) { if (index == s.size()) { res.push_back(vt); return; } for (int i = 1; i + index <= s.size(); ++i) { string temp; for (int j = 0; j < i; ++j) temp += s[index + j]; if (is_palindrome(temp)) { vector<string> new_vt(vt); new_vt.push_back(temp); __partition(s, index + i, new_vt); } } } public: vector<vector<string>> partition(string s) { vector<string> vt; __partition(s, 0, vt); return res; } }; #endif //ALGORITHMS_Q131_PARTITION_PALINDROME_H
true
5c241b7aba3765669081f06746823760d5882077
C++
Accacio/matcg
/src/matcg.cpp
UTF-8
1,063
2.671875
3
[]
no_license
#include <game.hpp> #include <cemetery.hpp> #include <card.hpp> #include <monster.hpp> #include <player.hpp> #include <deck.hpp> #include <vector> #include <iostream> int main(int argc, char *argv[]) { Monster guerreiro2("guerreiro2", 2, 4, 0); Monster goblin("goblin", 1, 1); Monster guerreiro3("guerreiro3", 2, 3); Deck j; j.addtodeck(&guerreiro3); j.addtodeck(&goblin); j.showdeck(); // show vector std::cout << "Before shuffling "; j.showdeck(); std::cout << "After shuffling "; j.shuffledeck(); // std::cout <<guerreiro; std::cout <<guerreiro2; // std::cout << "Guerreiro is alive?"<<guerreiro.alive_<<std::endl; // using namespace std;::cout // << "Guerreiro 2 is alive?"<<guerreiro2.alive_<<std::endl; // std::cout<<std::endl<<"guerreiro ataca guerreiro2"<<std::endl; // guerreiro>>guerreiro2; // Cemetery cemetery; // if(!guerreiro2.alive_) // { // cemetery<=guerreiro2; // } // if(!guerreiro.alive_) // { // cemetery<=guerreiro; // } // cemetery.showcemetery(); return 0; }
true
6d1929f6172598639ed3b4c9a273970eab3b0f4e
C++
amarjotgill/Vector-Explainer
/tempCodeRunnerFile.cpp
UTF-8
18
2.515625
3
[]
no_license
Nathenael Dereb on 2/8/21.
true
286a2e61a06838ab0a6e3051f50ee7b119711fe7
C++
sniper0110/image_processing_GUI
/functions.cpp
UTF-8
6,721
2.890625
3
[]
no_license
#include "functions.h" void salt(cv::Mat &image, int n) { for (int k=0; k<n; k++) { // rand() is the MFC random number generator // try qrand() with Qt int i= rand()%image.cols; int j= rand()%image.rows; if (image.channels() == 1) { // gray-level image image.at<uchar>(j,i)= 255; } else if (image.channels() == 3) { // color image image.at<cv::Vec3b>(j,i)[0]= 255; image.at<cv::Vec3b>(j,i)[1]= 255; image.at<cv::Vec3b>(j,i)[2]= 255; } } } void saltVid(cv::Mat &image1, cv::Mat &image2){ int n=1000; image2 = image1; salt(image2, n); } void logoVid(cv::Mat &image1, cv::Mat &image2){ //outputImage = inputImage; image2 = image1; cv::Mat logo = cv::imread("logo.jpeg"); // to contain resized image cv::resize(logo,logo, cv::Size(logo.cols/3,logo.rows/3)); // 1/3 resizing // define image ROI cv::Mat imageROI; imageROI= image2(cv::Rect(image2.cols-10-logo.cols,10,logo.cols,logo.rows)); // add logo to image cv::addWeighted(imageROI,1.0,logo,1,0.,imageROI); } void HLSVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::cvtColor(image2, image2, CV_BGR2HLS); } void equalHistVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::cvtColor(image2, image2, CV_BGR2GRAY); cv::equalizeHist(image2, image2); } void blurVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::blur(image2,image2,cv::Size(5,5)); } void sobelVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::Sobel(image2,image2, CV_8U,1,0,3,0.4,128); // X direction cv::Sobel(image2,image2, CV_8U,0,1,3,0.4,128); // THEN Y direction } void laplaceVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::Laplacian(image2, image2, CV_32F, 3); } void sharpenVid(cv::Mat &image, cv::Mat &result){ result.create(image.size(), image.type()); for (int j= 1; j<image.rows-1; j++) { // for all rows // (except first and last) const uchar* previous=image.ptr<const uchar>(j-1); // previous row const uchar* current=image.ptr<const uchar>(j); // current row const uchar* next=image.ptr<const uchar>(j+1); // next row uchar* output= result.ptr<uchar>(j); // output row for (int i=1; i<image.cols-1; i++) { *output++= cv::saturate_cast<uchar>( 5*current[i]-current[i-1] -current[i+1]-previous[i]-next[i]); } } // Set the unprocess pixels to 0 result.row(0).setTo(cv::Scalar(0)); result.row(result.rows-1).setTo(cv::Scalar(0)); result.col(0).setTo(cv::Scalar(0)); result.col(result.cols-1).setTo(cv::Scalar(0)); } void dilateVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::dilate(image2,image2,cv::Mat()); } void erodeVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::erode(image2,image2,cv::Mat()); } void openVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::Mat element5(5,5,CV_8U,cv::Scalar(1)); cv::morphologyEx(image2,image2,cv::MORPH_OPEN,element5); } void closeVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::Mat element5(5,5,CV_8U,cv::Scalar(1)); cv::morphologyEx(image2,image2,cv::MORPH_CLOSE,element5); } void houghCircleVid(cv::Mat &image1, cv::Mat &image2){ image2=image1; cv::cvtColor(image2, image2, CV_BGR2GRAY); cv::GaussianBlur(image2,image2,cv::Size(5,5),1.5); std::vector<cv::Vec3f> circles; cv::HoughCircles(image2, circles, CV_HOUGH_GRADIENT, 2, // accumulator resolution (size of the image / 2) 50, // minimum distance between two circles 200, // Canny high threshold 100, // minimum number of votes 5, 100); // min and max radius std::vector<cv::Vec3f>:: const_iterator itc= circles.begin(); while (itc!=circles.end()) { cv::circle(image2, cv::Point((*itc)[0], (*itc)[1]), // circle centre (*itc)[2], // circle radius cv::Scalar(0), // color 2); // thickness ++itc; } } void fastVid(cv::Mat &image1, cv::Mat &image2){ image2 = image1; cv::cvtColor(image2, image2, CV_BGR2GRAY); // vector of keypoints std::vector<cv::KeyPoint> keypoints; // Construction of the Fast feature detector object cv::Ptr<cv::FastFeatureDetector> fast = cv::FastFeatureDetector::create(40); // threshold for detection //fast.setThreshold(40); // feature point detection fast->detect(image2,keypoints); cv::drawKeypoints(image2, // original image keypoints, // vector of keypoints image2, // the output image cv::Scalar(255,255,255), // keypoint color cv::DrawMatchesFlags::DRAW_OVER_OUTIMG); //drawing flag } void harrisVid(cv::Mat &image1, cv::Mat &image2){ image2=image1; cv::cvtColor(image2, image2, CV_BGR2GRAY); // Detect Harris Corners cv::Mat cornerStrength; cv::cornerHarris(image2, cornerStrength, 3, // neighborhood size 3, // aperture size 0.01 // Harris parameter ); // threshold the corner strengths cv::Mat harrisCorners; double threshold = 0.0001; cv::threshold(cornerStrength, harrisCorners, threshold, 255, cv::THRESH_BINARY_INV); image2=harrisCorners; } void sharpen(const cv::Mat &image, cv::Mat &result) { // allocate if necessary result.create(image.size(), image.type()); for (int j= 1; j<image.rows-1; j++) { // for all rows // (except first and last) const uchar* previous=image.ptr<const uchar>(j-1); // previous row const uchar* current=image.ptr<const uchar>(j); // current row const uchar* next=image.ptr<const uchar>(j+1); // next row uchar* output= result.ptr<uchar>(j); // output row for (int i=1; i<image.cols-1; i++) { *output++= cv::saturate_cast<uchar>( 5*current[i]-current[i-1] -current[i+1]-previous[i]-next[i]); } } // Set the unprocess pixels to 0 result.row(0).setTo(cv::Scalar(0)); result.row(result.rows-1).setTo(cv::Scalar(0)); result.col(0).setTo(cv::Scalar(0)); result.col(result.cols-1).setTo(cv::Scalar(0)); } void canny(cv::Mat& img, cv::Mat& out) { // Convert to gray if (img.channels()==3) cv::cvtColor(img,out,CV_BGR2GRAY); // Compute Canny edges cv::Canny(out,out,100,200); // Invert the image cv::threshold(out,out,128,255,cv::THRESH_BINARY_INV); } void saltAndPepper(cv::Mat& img, cv::Mat& out){ } void nothing(cv::Mat& img, cv::Mat& out) { // Convert to gray if (img.channels()==3) cv::cvtColor(img,out,CV_BGR2GRAY); // Compute Canny edges //cv::Canny(out,out,100,200); // Invert the image //cv::threshold(out,out,128,255,cv::THRESH_BINARY_INV); }
true
3d593e21bf7383c1842f25669aa001af1a327a78
C++
ddayzzz/algorithm-and-basic-apps
/data-structure/03.Sort/Node.h
GB18030
5,277
3.390625
3
[]
no_license
#pragma once #include "../stdafx.h" #include <stdexcept> #include <initializer_list> template<typename T> struct Node { template<typename X> Node(X e):pdata(e){} T pdata; Node *next=nullptr; Node *operator++(int) { return next; } Node *operator++() { return next; } }; template<typename T> class List { public: typedef T elementtype;//Ԫ typedef struct Node<T> *PtrtoList;//ָ͵ͱ typedef PtrtoList Position;//λõָͱ //캯(йظƵĻԺʵ) List() :header(new Node<elementtype>(0)) {} List(const List&) = delete; List(List&&) = delete; //ֵ List &operator=(const List&) = delete; List &operator=(List&&) = delete; // ~List() { delete_after_all(header); delete header; } //ӿ ݷ elementtype &getdata(unsigned i) //صǰڵ { Position p = index(i); if (p != nullptr) { return p->pdata; } else { throw std::runtime_error("ڵЧ! "); } } elementtype &getdata(Position p) //صǰڵ { if (p != nullptr) { return p->pdata; } else { throw std::runtime_error("ڵЧ! "); } } template<typename X> void push_back(X e) { Position ek = getlast(); if (ek != nullptr) { add_element_after(e, ek); } }//ݼ뵽ĩβ template<typename X> Position insert_after(X e, Position pos) { return add_element_after(e, pos); }//eӵposĺ ӺԪؽڵַ Position erase_after(Position pos) { return delete_after(pos); }//ɾpos֮һԪ ɾԪ֮Ľڵַ //Position erase_range(Position pos, Position end) { return delete_range(pos, end); }//ɾ[pos,end)Ԫ end void clear() { delete_after_all(header); }//ɾԪ Dzɾͷ //ӿ Ϣ Position head() { return header; }//رͷڵַ Position begin() { return header->next; }//Ԫصĵַ Position back() { return getlast(); }//һԪصĵӵַ unsigned int size() { return getsize(); }//صǰĴС ͷ Position find(elementtype t) { return find_matched(t); }//صһָԪصĽڵַ bool empty() { return header->next == nullptr; } //ӿ elementtype &operator[](unsigned int i) { return getdata(i); }//ͨ private: Position header = nullptr;//ͷԪ //Ԫ template<typename X> Position add_element_after(X t, Position pos) { if (header == nullptr) { return nullptr; } else { Position p = new Node<elementtype>(t); p->next = pos->next; pos->next = p; return p; } } Position delete_after(Position pos) { if (pos != nullptr) { Position te = pos->next; if (te != nullptr) { pos->next = te->next; delete te; return pos->next; } else { //βԪزɾ return nullptr; } } else { return nullptr; } } Position delete_after_all(Position pos) { if (pos != nullptr) { Position te = pos->next; Position p; pos->next = nullptr; while (te != nullptr) { p = te->next; delete te; te = p; } } else { return nullptr; } } Position index(unsigned i) { unsigned id = 0; Position p = header->next; while (p != nullptr && id < i) { ++id; p = p->next; } return p; } //ҵһƥԪ Position find_matched(elementtype t) { Position pos = head(); pos = pos->next; while (pos != nullptr && pos->pdata != t) { pos = pos->next; } return pos; } Position getlast() { Position pos = head(); while (pos !=nullptr && pos->next != nullptr) { pos = pos->next; } return pos; } unsigned getsize() { unsigned id = 0; Position p = header->next; while (p != nullptr) { ++id; p = p->next; } return id; } Position delete_range(Position pos,Position end) { if (pos != nullptr) { if (pos != head()) { Position te = pos; Position p; pos->next = end; while (te != end) { p = te->next; delete te; te = p; } return end; } else { throw std::runtime_error("ɾͷԪ. "); } } else { return nullptr; } } }; template<typename CONTAINER> class list_iterator { public: typedef CONTAINER eletype;//ʾԪ list_iterator() : pos(nullptr){} list_iterator(Node<eletype> *p) :pos(p) {} list_iterator &operator=(const list_iterator<eletype> &p) { pos = p.pos; return *this; } list_iterator &operator++() { pos = pos->next; return *this; } list_iterator operator++(int) { Node<eletype> *temp = pos; pos = pos->next; return temp; } bool operator==(const list_iterator<eletype> &i) { return i.pos == pos; } bool operator!=(const list_iterator<eletype> &i) { return i.pos != pos; } operator Node<eletype> *() { return pos; } eletype &operator*() { if (pos != nullptr) { return pos->pdata; } else { throw std::runtime_error("! һڵλ"); } } private: Node<eletype> *pos; };
true
bb213ffd2f43b4cc70b96a589a46500033b954ee
C++
ssraghuvanshi/FP_AOA_CodeToFlowchart
/test_case/Test Cases/testcase18.cpp
UTF-8
642
3
3
[]
no_license
int input; int i=30; int j=10; cout << "enter number :"; cin >> input; if (input > 10){ while(j < 20){ if( i < j){ cout << "What is this"; } cout << "Hello"; cout << "No"; } cout << "Added"; while( i < 5){ cout << "Still smaller than 5"; } cout << "Nice"; } cout << "enter number :"; cin >> input; if (input > 10){ while(j < 20){ if( i < j){ cout << "What is this"; } cout << "Hello"; cout << "No"; } cout << "Added"; while( i < 5){ cout << "Still smaller than 5"; } cout << "Nice"; }
true
0b28bce40986cb54d1f4f78b15aa575450461753
C++
hope-kim/Course3
/pa1/zombies.cpp
UTF-8
3,750
3.5
4
[]
no_license
/******************************************************** * CS 103 Zombie-pocalypse PA * Name: Hope Kim * USC email: hopekim@usc.edu * Comments (you want us to know): * Runs similuations that determine the average, minimum, * and maximum # of nights that it will take for a * zombie-pocalypse to take over a certain population ********************************************************/ // Add other #includes if you need #include <iostream> #include <cstdlib> #include <ctime> #include <climits> using namespace std; const int MAXPOP = 100000; int main() { // Array with enough entries for the maximum population size possible bool pop[MAXPOP]; // User input variables int N = 0; int k = 0; int M = 0; int s = 0; // Output for user input cout << "Enter the following: N k M seed" << endl; cout << "-> "; cin >> N >> k >> M >> s; // Seeding the random number generator with the seed provided by user srand(s); // Quits program if k > N if (k > N) { cout << "Quitting!" << endl; } // Valid program execution else { // Holds the variables for number of nights (sum for average, min, max) double sumNights = 0; int min_nights = 1000000000; int max_nights = -1; // Goes through the simulation M times for (int simulation = 0; simulation < M; simulation++) { // Sets indices from 0 to N-1 in the array to humans for (int human = 0; human < N; human++) { pop[human] = false; } // Sets indices from 0 to k-1 in the array to zombies for (int zombie = 0; zombie < k; zombie++) { pop[zombie] = true; } // Variables to hold counts of nights, humans, zombies int numberNights = 0; int numberHumans = N-k; int numberZombies = k; int numberZombiesStart = k; // While loop for each night that there are still humans while (numberHumans > 0) { // Each zombie gets a bite for (int bite = 0; bite < numberZombiesStart; bite++) { // Creates a random zombie int zombieIndex = rand() % N; // Makes the zombie and adjusts counts if human before if (pop[zombieIndex] == false) { numberHumans--; numberZombies++; pop[zombieIndex] = true; } } // Changes the number of zombies that start out the next day numberZombiesStart = numberZombies; // Increases the number of nights numberNights++; } // Compares the number of nights after a simulation to the one before if (numberNights < min_nights) { min_nights = numberNights; } if (numberNights > max_nights) { max_nights = numberNights; } // Adds to the sum of the nights sumNights += numberNights; } // Prints out average, max, and min number of nights double avg_nights = 0; avg_nights = sumNights/M; cout << "Average nights: " << avg_nights << endl; cout << "Max nights: " << max_nights << endl; cout << "Min nights: " << min_nights << endl; } return 0; }
true
b315d0dd647c508247b62b88c9c58fef3d53d681
C++
HTBalazs/raylite
/src/Plane.cpp
UTF-8
1,949
2.53125
3
[]
no_license
/* Copyright 2016-2017 Balazs Toth This file is part of Raylite. Raylite is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Raylite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Raylite. If not, see <http://www.gnu.org/licenses/>. For more information please visit: https://bitbucket.org/Rayliteproject/ */ #include "Plane.h" Plane::Plane(Vect3 p, Vect3 n, float gs, Material mat) { pos = p; normal = n.normalize(); gridsize = gs; material = mat; } Vect3 Plane::getIntersection(Rayptr const& ray, bool& intersect) const { float vn = ray->direction*normal; // return if the ray is parallel with the plane if(vn==0) { intersect = false; return Vect3(-1,-1,-1); } float d = (pos-ray->start)*normal / vn; Vect3 tmp = Vect3{d*ray->direction.x, d*ray->direction.y, d*ray->direction.z}; Vect3 p = tmp + ray->start; // return if intersection occurs at the wrong side of the ray (backwards) if(tmp*ray->direction < 0.0001) { intersect = false; return Vect3(-1,-1,-1); } intersect = true; return p; } Vect3 Plane::getNormal(Rayptr const& ray, Vect3& ip) const { bool intersect = false; ip = getIntersection(ray, intersect); return normal; } Color Plane::getColor(Rayptr const& ray) const { Color c = (((((int)floor((ray->start.x-pos.x)/gridsize)) + (int)floor((ray->start.z-pos.z)/gridsize))%2) == 0) ? material.color1 : material.color2; return c; }
true
5b0a335ecc6fe9d69f11000cbcc0d8d8dab0762f
C++
zach-pike/BrainFuckInterpreter
/src/main.cpp
UTF-8
2,062
3.09375
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <algorithm> #include "Interp.hpp" #include "argparse.hpp" std::string LoadStringFromFile(const char* filename) { std::stringstream ss; ss << std::ifstream(filename).rdbuf(); return ss.str(); } template <typename T> bool vectIncludes(const std::vector<T>& haystack, const T needle) { return std::count(haystack.begin(), haystack.end(), needle) > 0; } int main(int _argc, const char** _args) { auto args = std::vector<std::string>{ _args + 1, _args + _argc }; auto pArgs = parseArgs(args); bool unFuck = vectIncludes(pArgs.flags, std::string{"unfuck"}); if (vectIncludes(pArgs.flags, std::string{"minify"})) { // Load the code to minify auto code = LoadStringFromFile(pArgs.settings["in"].c_str()); // To store the final string std::string finalCode = ""; // Where to write the output file auto writeTo = pArgs.settings["out"]; // All valid symbols auto symbols = BFInterp{false, unFuck}.getRecognizedSymbols(); // Loop thru each char and determine if we keep it ot not for (auto letter : code) { if (vectIncludes(symbols, letter)) finalCode += letter; } // Write it to the specified output dest std::ofstream outfile(writeTo); outfile << finalCode; outfile.close(); } else if (pArgs.text.size() == 0) { // Start REPL mode printf("REPL started\n"); BFInterp interp(true, unFuck); while(true) { std::string inp; // Print prompt string std::cout << ":" << std::flush; // Get input std::cin >> inp; interp.Run(inp); } } else if (pArgs.text.size() == 1) { printf("Interp started!\n"); auto code = LoadStringFromFile(args[0].c_str()); BFInterp interp(false, unFuck); interp.Run(code); } return 0; }
true
f58f600474dbef2bc79040e164fb2138c209f560
C++
wenjing219/Cpp-How-To-Program-9E
/Chapter09/exercises/9.05/Complex.h
UTF-8
1,158
3.15625
3
[]
no_license
/* * ===================================================================================== * * Filename: Complex.h * * Description: Exercise 9.05 - Complex Class * Complex number class representation * * Version: 1.0 * Created: 09/06/16 14:20:47 * Revision: none * Compiler: gcc * * Author: Siidney Watson - siidney.watson.work@gmail.com * Organization: LolaDog Studio * * ===================================================================================== */ #pragma once #include <iostream> class Complex{ public: Complex(double = 1, double = 1); ~Complex(); // overloaded operators Complex operator+(Complex c) const{ return Complex(real + c.real, imaginary + c.imaginary); } Complex operator-(Complex c) const{ return Complex(real - c.real, imaginary - c.imaginary); } friend std::ostream& operator<<(std::ostream& out, Complex& c){ return c.printComplex(out); } private: double real; double imaginary; std::ostream& printComplex(std::ostream&); };
true
5bffcb84940ee037e266f955e0c1b526484773f0
C++
manishrdmishra/Code
/programming_contest/12th-week/treasure_hunt.cpp
UTF-8
21,855
2.921875
3
[]
no_license
#include<iostream> #include<cmath> #include<vector> #include <stdio.h> #include <iostream> #include <math.h> #include<cstring> // http://www.softwareandfinance.com/CPP/Matrix_Inverse.html using namespace std; const int POINTS = 9; struct Point { double x; double y; double z; Point( double x_ , double y_ , double z_) { x = x_; y = y_; z = z_; } Point(){} }; struct equation { int A[3][3]; Point x; Point b; }; /*equation generate_equation(int i , std::vector<Point> points) { } */ class CMatrix { private: int m_rows; int m_cols; char m_name[128]; CMatrix(); public: double **m_pData; CMatrix(const char *name, int rows, int cols) : m_rows(rows), m_cols(cols) { strcpy(m_name, name); m_pData = new double*[m_rows]; for(int i = 0; i < m_rows; i++) m_pData[i] = new double[m_cols]; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { m_pData[i][j] = 0.0; } } } CMatrix(const CMatrix &other) { strcpy(m_name, other.m_name); m_rows = other.m_rows; m_cols = other.m_cols; m_pData = new double*[m_rows]; for(int i = 0; i < m_rows; i++) m_pData[i] = new double[m_cols]; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { m_pData[i][j] = other.m_pData[i][j]; } } } ~CMatrix() { for(int i = 0; i < m_rows; i++) delete [] m_pData[i]; delete [] m_pData; m_rows = m_cols = 0; } void SetName(const char *name) { strcpy(m_name, name); } const char* GetName() const { return m_name; } void GetInput() { std::cin >> *this; } void FillSimulatedInput() { static int factor1 = 1, factor2 = 2; std::cout << "\n\nEnter Input For Matrix : " << m_name << " Rows: " << m_rows << " Cols: " << m_cols << "\n"; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1 << " = "; int data = ((i + 1) * factor1) + (j + 1) * factor2; m_pData[i][j] = data / 10.2; std::cout << m_pData[i][j] << "\n"; factor1 += (rand() % 4); factor2 += (rand() % 3); } std::cout << "\n"; } std::cout << "\n"; } double Determinant() { double det = 0; double **pd = m_pData; switch(m_rows) { case 2: { det = pd[0][0] * pd[1][1] - pd[0][1] * pd[1][0]; return det; } break; case 3: { /*** a b c d e f g h i a b c a b c d e f d e f g h i g h i // det (A) = aei + bfg + cdh - afh - bdi - ceg. ***/ double a = pd[0][0]; double b = pd[0][1]; double c = pd[0][2]; double d = pd[1][0]; double e = pd[1][1]; double f = pd[1][2]; double g = pd[2][0]; double h = pd[2][1]; double i = pd[2][2]; double det = (a*e*i + b*f*g + c*d*h); det = det - a*f*h; det = det - b*d*i; det = det - c*e*g; return det; } break; case 4: { CMatrix *temp[4]; for(int i = 0; i < 4; i++) temp[i] = new CMatrix("", 3,3); for(int k = 0; k < 4; k++) { for(int i = 1; i < 4; i++) { int j1 = 0; for(int j = 0; j < 4; j++) { if(k == j) continue; temp[k]->m_pData[i-1][j1++] = this->m_pData[i][j]; } } } double det = this->m_pData[0][0] * temp[0]->Determinant() - this->m_pData[0][1] * temp[1]->Determinant() + this->m_pData[0][2] * temp[2]->Determinant() - this->m_pData[0][3] * temp[3]->Determinant(); return det; } break; case 5: { CMatrix *temp[5]; for(int i = 0; i < 5; i++) temp[i] = new CMatrix("", 4,4); for(int k = 0; k < 5; k++) { for(int i = 1; i < 5; i++) { int j1 = 0; for(int j = 0; j < 5; j++) { if(k == j) continue; temp[k]->m_pData[i-1][j1++] = this->m_pData[i][j]; } } } double det = this->m_pData[0][0] * temp[0]->Determinant() - this->m_pData[0][1] * temp[1]->Determinant() + this->m_pData[0][2] * temp[2]->Determinant() - this->m_pData[0][3] * temp[3]->Determinant() + this->m_pData[0][4] * temp[4]->Determinant(); return det; } case 6: case 7: case 8: case 9: case 10: case 11: case 12: default: { int DIM = m_rows; CMatrix **temp = new CMatrix*[DIM]; for(int i = 0; i < DIM; i++) temp[i] = new CMatrix("", DIM - 1,DIM - 1); for(int k = 0; k < DIM; k++) { for(int i = 1; i < DIM; i++) { int j1 = 0; for(int j = 0; j < DIM; j++) { if(k == j) continue; temp[k]->m_pData[i-1][j1++] = this->m_pData[i][j]; } } } double det = 0; for(int k = 0; k < DIM; k++) { if( (k %2) == 0) det = det + (this->m_pData[0][k] * temp[k]->Determinant()); else det = det - (this->m_pData[0][k] * temp[k]->Determinant()); } for(int i = 0; i < DIM; i++) delete temp[i]; delete [] temp; return det; } break; } } CMatrix& operator = (const CMatrix &other) { if( this->m_rows != other.m_rows || this->m_cols != other.m_cols) { std::cout << "WARNING: Assignment is taking place with by changing the number of rows and columns of the matrix"; } for(int i = 0; i < m_rows; i++) delete [] m_pData[i]; delete [] m_pData; m_rows = m_cols = 0; strcpy(m_name, other.m_name); m_rows = other.m_rows; m_cols = other.m_cols; m_pData = new double*[m_rows]; for(int i = 0; i < m_rows; i++) m_pData[i] = new double[m_cols]; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { m_pData[i][j] = other.m_pData[i][j]; } } return *this; } CMatrix CoFactor() { CMatrix cofactor("COF", m_rows, m_cols); if(m_rows != m_cols) return cofactor; if(m_rows < 2) return cofactor; else if(m_rows == 2) { cofactor.m_pData[0][0] = m_pData[1][1]; cofactor.m_pData[0][1] = -m_pData[1][0]; cofactor.m_pData[1][0] = -m_pData[0][1]; cofactor.m_pData[1][1] = m_pData[0][0]; return cofactor; } else if(m_rows >= 3) { int DIM = m_rows; CMatrix ***temp = new CMatrix**[DIM]; for(int i = 0; i < DIM; i++) temp[i] = new CMatrix*[DIM]; for(int i = 0; i < DIM; i++) for(int j = 0; j < DIM; j++) temp[i][j] = new CMatrix("", DIM - 1,DIM - 1); for(int k1 = 0; k1 < DIM; k1++) { for(int k2 = 0; k2 < DIM; k2++) { int i1 = 0; for(int i = 0; i < DIM; i++) { int j1 = 0; for(int j = 0; j < DIM; j++) { if(k1 == i || k2 == j) continue; temp[k1][k2]->m_pData[i1][j1++] = this->m_pData[i][j]; } if(k1 != i) i1++; } } } bool flagPositive = true; for(int k1 = 0; k1 < DIM; k1++) { flagPositive = ( (k1 % 2) == 0); for(int k2 = 0; k2 < DIM; k2++) { if(flagPositive == true) { cofactor.m_pData[k1][k2] = temp[k1][k2]->Determinant(); flagPositive = false; } else { cofactor.m_pData[k1][k2] = -temp[k1][k2]->Determinant(); flagPositive = true; } } } for(int i = 0; i < DIM; i++) for(int j = 0; j < DIM; j++) delete temp[i][j]; for(int i = 0; i < DIM; i++) delete [] temp[i]; delete [] temp; } return cofactor; } CMatrix Adjoint() { CMatrix cofactor("COF", m_rows, m_cols); CMatrix adj("ADJ", m_rows, m_cols); if(m_rows != m_cols) return adj; cofactor = this->CoFactor(); // adjoint is transpose of a cofactor of a matrix for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { adj.m_pData[j][i] = cofactor.m_pData[i][j]; } } return adj; } CMatrix Transpose() { CMatrix trans("TR", m_cols, m_rows); for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { trans.m_pData[j][i] = m_pData[i][j]; } } return trans; } CMatrix Inverse() { CMatrix cofactor("COF", m_rows, m_cols); CMatrix inv("INV", m_rows, m_cols); if(m_rows != m_cols) return inv; // to find out Determinant double det = Determinant(); cofactor = this->CoFactor(); // inv = transpose of cofactor / Determinant for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { //inv.m_pData[j][i] = cofactor.m_pData[i][j] / det; inv.m_pData[j][i] = cofactor.m_pData[i][j] ; } } return inv; } CMatrix operator + (const CMatrix &other) { if( this->m_rows != other.m_rows || this->m_cols != other.m_cols) { std::cout << "Addition could not take place because number of rows and columns are different between the two matrices"; return *this; } CMatrix result("", m_rows, m_cols); for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { result.m_pData[i][j] = this->m_pData[i][j] + other.m_pData[i][j]; } } return result; } CMatrix operator - (const CMatrix &other) { if( this->m_rows != other.m_rows || this->m_cols != other.m_cols) { std::cout << "Subtraction could not take place because number of rows and columns are different between the two matrices"; return *this; } CMatrix result("", m_rows, m_cols); for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { result.m_pData[i][j] = this->m_pData[i][j] - other.m_pData[i][j]; } } return result; } CMatrix operator * (const CMatrix & other) { if( this->m_cols != other.m_rows) { std::cout << "Multiplication could not take place because number of columns of 1st Matrix and number of rows in 2nd Matrix are different"; return *this; } CMatrix result("", this->m_rows, other.m_cols); for(int i = 0; i < this->m_rows; i++) { for(int j = 0; j < other.m_cols; j++) { for(int k = 0; k < this->m_cols; k++) { result.m_pData[i][j] += this->m_pData[i][k] * other.m_pData[k][j]; } } } return result; } bool operator == (const CMatrix &other) { if( this->m_rows != other.m_rows || this->m_cols != other.m_cols) { std::cout << "Comparision could not take place because number of rows and columns are different between the two matrices"; return false; } CMatrix result("", m_rows, m_cols); bool bEqual = true; for(int i = 0; i < m_rows; i++) { for(int j = 0; j < m_cols; j++) { if(this->m_pData[i][j] != other.m_pData[i][j]) bEqual = false; } } return bEqual; } friend std::istream& operator >> (std::istream &is, CMatrix &m); friend std::ostream& operator << (std::ostream &os, const CMatrix &m); void fillInput(std::vector<Point> points) { int c = 0; for(int i = 0; i <= 6; i = i+2, ++c) { m_pData[i][0] = points[c].x; m_pData[i][1] = points[c].y; m_pData[i][2] = 1 ; m_pData[i][3] = 0 ; m_pData[i][4] = 0 ; m_pData[i][5] = 0 ; m_pData[i][6] = - (points[c].x * points[c + 5].x); m_pData[i][7] = -( points[c].y * points[c + 5].x); //fill second row m_pData[i+1 ][0] = 0; m_pData[i+1][1] = 0; m_pData[i+1][2] = 0 ; m_pData[i+1][3] = points[c].x ; m_pData[i+1][4] = points[c].y; m_pData[i+1][5] = 1 ; m_pData[i+1][6] = - (points[c].x * points[c + 5].y); m_pData[i+1][7] = -( points[c].y * points[c + 5].y); } } void createVector(std::vector<Point>points) { m_pData[0][0] = points[5].x; m_pData[1][0] = points[5].y; m_pData[2][0] = points[6].x; m_pData[3][0] = points[6].y; m_pData[4][0] = points[7].x; m_pData[5][0] = points[7].y; m_pData[6][0] = points[8].x; m_pData[7][0] = points[8].y; } }; std::istream& operator >> (std::istream &is, CMatrix &m) { //std::cout << "\n\nEnter Input For Matrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: " << m.m_cols << "\n"; for(int i = 0; i < m.m_rows; i++) { for(int j = 0; j < m.m_cols; j++) { // std::cout << "Input For Row: " << i + 1 << " Col: " << j + 1 << " = "; is >> m.m_pData[i][j]; } // std::cout << "\n"; } //std::cout << "\n"; return is; } std::ostream& operator << (std::ostream &os,const CMatrix &m) { os << "\n\nMatrix : " << m.m_name << " Rows: " << m.m_rows << " Cols: " << m.m_cols << "\n\n"; for(int i = 0; i < m.m_rows; i++) { os << " | "; for(int j = 0; j < m.m_cols; j++) { char buf[32]; double data = m.m_pData[i][j]; if( m.m_pData[i][j] > -0.00001 && m.m_pData[i][j] < 0.00001) data = 0; sprintf(buf, "%10.2lf ", data); os << buf; } os << "|\n"; } os << "\n\n"; return os; } long int gcd_iter(long int u,long int v) { long int t; while (v) { t = u; u = v; v = t % v; } return u < 0 ? -u : u; /* abs(u) */ } int main() { int t; cin>>t; for(int i = 1; i<= t; i++) { std::vector< Point > points; for(int j = 1; j<=POINTS ; j++) { Point p; cin>>p.x>>p.y; p.z = 1; points.push_back(p); } CMatrix a("A", 8,8); // std::cin >> a; a.fillInput(points); //a.FillSimulatedInput(); CMatrix aadj = a.Inverse(); CMatrix b("B",8,1); b.createVector(points); CMatrix H = aadj * b; //std::cout << a; // std::cout << aadj; //std::cout<< H; int det = a.Determinant(); //compute the new point long int x_1 = H.m_pData[0][0] * points[4].x + H.m_pData[1][0] * points[4].y + H.m_pData[2][0]; long int y_1 = H.m_pData[3][0] * points[4].x + H.m_pData[4][0] * points[4].y + H.m_pData[5][0]; long int z_1 = H.m_pData[6][0] * points[4].x + H.m_pData[7][0] * points[4].y + det; long int div = gcd_iter( std::abs(x_1), std::abs(z_1)); std::cout<<"Case #"<<i<<": "; if(z_1 < 0) { x_1 = -x_1; y_1 = -y_1; z_1 = -z_1; } if(z_1/div == 1) { std::cout<<x_1/z_1<<" "; } else { std::cout<<x_1/div<<"/"<<z_1/div<<" "; } div = gcd_iter(std::abs( y_1), std::abs(z_1)); if( z_1/div == 1) { std::cout<<y_1/div<<" "; } else { std::cout<<y_1/div<<"/"<<z_1/div; } cout<<endl; } return 0; } /* int main() { int t; cin>>t; for ( int i =1 ; i<= t; i++) { std::vector< Point > points; for(int j = 1; j<POINTS ; j++) { Point p; cin>>p.x>>p.y; p.z = 1; points.push_back(p); } generate_equation(1,points); } return 0; } */
true
c4304ad14b247eb5d079d233e83aebe08fe7d1dc
C++
BITERP/PinkRabbitMQ
/src/amqpcpp/linux_tcp/tcpparent.h
UTF-8
2,211
2.75
3
[ "BSD-3-Clause", "MIT" ]
permissive
/** * TcpParent.h * * Interface to be implemented by the parent of a tcp-state. This is * an _internal_ interface that is not relevant for user-space applications. * * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * @copyright 2018 - 2021 Copernica BV */ /** * Include guard */ #pragma once /** * Dependencies */ #include <openssl/ssl.h> /** * Begin of namespace */ namespace AMQP { /** * Forward declarations */ class TcpState; class Buffer; /** * Class definition */ class TcpParent { public: /** * Destructor */ virtual ~TcpParent() = default; /** * Method that is called when the TCP connection has been established * @param state */ virtual void onConnected(TcpState *state) = 0; /** * Method that is called right before a connection is secured and that allows userspac to change SSL * @param state * @param ssl * @return bool */ virtual bool onSecuring(TcpState *state, SSL *ssl) = 0; /** * Method that is called when the connection is secured * @param state * @param ssl * @return bool */ virtual bool onSecured(TcpState *state, const SSL *ssl) = 0; /** * Method to be called when data was received * @param state * @param buffer * @return size_t */ virtual size_t onReceived(TcpState *state, const Buffer &buffer) = 0; /** * Method to be called when we need to monitor a different filedescriptor * @param state * @param fd * @param events */ virtual void onIdle(TcpState *state, int socket, int events) = 0; /** * Method that is called when an error occurs (the connection is lost) * @param state * @param error * @param connected */ virtual void onError(TcpState *state, const char *message, bool connected = true) = 0; /** * Method to be called when it is detected that the connection was lost * @param state */ virtual void onLost(TcpState *state) = 0; /** * The expected number of bytes * @return size_t */ virtual size_t expected() = 0; }; /** * End of namespace */ }
true
5a713afa43f8be634da3d94b63af06ecfea3f0d3
C++
deskata666/UPupr
/Upr3_5.cpp
UTF-8
532
3.34375
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; int main() { int array[20], length,value; cout << "Length of the array: "; cin >> length; for (int i = 0; i < length; i++) { cout << "array[" << i + 1 << "]= "; cin>>array[i]; } for (int i = 1; i < length ; i++) { value = array[i]; int j = i - 1; while ((j >= 0) && (array[j]>value)) { array[j+1] = array[j]; j = j - 1; } array[j + 1] = value; } cout << "Sorted: "; for (int i = 0; i < length; i++) { cout<<array[i]<<" "; } system("pause"); return 0; }
true
bf624daf23fb3e186b81f553fd483dd5535e9da4
C++
kyabe2718/sandbox_coroutine
/include/coro/utility/concepts.hpp
UTF-8
3,050
3.109375
3
[]
no_license
#pragma once #if __has_include(<coroutine>) #include <coroutine> #elif __has_include(<experimental/coroutine>) #include <experimental/coroutine> namespace std { using namespace std::experimental; } #else #error cannot include a header for coroutine #endif #include "type_traits.hpp" namespace coro { template<typename P> concept Promise = requires(P p) { // Promiseオブジェクトをデフォルト構築する requires std::is_default_constructible_v<P>; // コルーチンオブジェクトを取得 p.get_return_object(); // 初期サスペンドポイント /*co_await*/ p.initial_suspend(); // co_return v; -> p.return_value(v); // co_return; -> p.return_void(); // 戻り値をpromiseオブジェクト経由で持ち出す requires(!detail::found_return_value<P> && detail::found_return_void<P>) || (detail::found_return_value<P> && !detail::found_return_void<P>); // 例外が投げられていれば,それを処理する必要がある { p.unhandled_exception() } -> std::same_as<void>; // 最終サスペンドポイント // ここで中断されている時のみ,coroutine_handle::done()はtrueを返す /*co_await*/ p.final_suspend(); requires !std::is_copy_constructible_v<P>; requires !std::is_copy_assignable_v<P>; }; // co_await expr; とすると,exprは一定の規則に従ってawaitableに変換される // yield式,初期サスペンドポイント,最終サスペンドポイントならexprそのまま // p.await_transform(expr) が有効ならその値 // そうでなければexprそのまま // awaitableは,operator co_await (メンバ関数or非メンバ関数)によってawaiterに変換される // 適合するoperator co_awaitが見つからなければ,awaitableはそのままawaiterとして扱われる template<typename Awaitable> using awaitable_to_awaiter_t = typename awaitable_traits<Awaitable>::awaiter_type; template<typename A> concept Awaiter = !std::is_void_v<A> && requires(A a) { // trueならコルーチンを中断せずにco_await式が即座に返る { a.await_ready() } -> std::same_as<bool>; // コルーチンを中断する前の処理 現在のコルーチンに対応するhandle // void -> 現在のコルーチンを中断し,その呼び出し元・再開元へ返る // bool -> trueならvoidと同じ falseならco_await式が即座に返る // coroutine_handle -> 現在のコルーチンを中断し,await_suspendの返り値に対応するコルーチンが再開される { a.await_suspend(std::coroutine_handle<>{} /* caller */) } -> convertible_to_any_of<void, bool, std::coroutine_handle<>>; // コルーチンが再開された直後の動作 // この返り値がco_await式の返り値になる a.await_resume(); }; template<typename A> concept Awaitable = Awaiter<typename awaitable_traits<A>::awaiter_type>; static_assert(Awaitable<std::suspend_never>); static_assert(Awaitable<std::suspend_always>); }// namespace coro
true
95aa51c66aa145ebd2fa8ae8946502474b77a852
C++
UTNuclearRoboticsPublic/temoto2
/temoto_2/src/tools/broken_node_1.cpp
UTF-8
662
2.84375
3
[ "BSD-3-Clause" ]
permissive
#include "ros/ros.h" #include <vector> int main(int argc, char **argv) { ros::init(argc, argv, "language_input"); ros::NodeHandle nh; int n = 3; std::vector<int> test_vec(n); try { // Access the vector by index and deliberately // try to access values out of the size range for( int i=0; i<n+6; i++ ) { std::cout << "test_vec[" << i << "] = " << test_vec.at(i) << std::endl; } } catch(...) { std::cout << "Exception: Oh boy, you're in trouble ...\n"; return 1; } while (ros::ok()) { ros::Duration(0.5).sleep(); } return 0; }
true
37f285198a8f160806b54ed20c5097fafafa0905
C++
mousse2cell/SimulationPlus4000
/Simul/Triangle.cpp
UTF-8
3,905
2.8125
3
[]
no_license
/* * Triangle.cpp * * Created on: 8 févr. 2012 * Author: mobilette */ #include "Triangle.h" #include "Arete.h" #include "CentreFace.h" #include "Sommet.h" #include "Segment.h" #include "Ligne.h" Triangle::Triangle() { // TODO Auto-generated constructor stub } Triangle::Triangle(int id):ID(id){ } Triangle::Triangle(int id, CentreFace *cent, std::vector<Sommet*> som, Arete *ar, std::vector<Segment*> seg):ID(id),centreFace(cent),sommets(som),arete(ar),segments(seg) { } Triangle::Triangle(int id, std::vector<Segment*> seg):ID(id),segments(seg){ } Triangle::~Triangle() { // TODO Auto-generated destructor stub } int Triangle::getID() const { return ID; } std::vector<Segment*> Triangle::getSegments() const { return segments; } void Triangle::setID(int id) { ID = id; } void Triangle::setSegments(std::vector<Segment*> lignes) { this->segments = lignes; } CentreFace *Triangle::getCentreFace() const { return centreFace; } std::vector<Sommet*> Triangle::getSommets() const { return sommets; } void Triangle::setCentreFace(CentreFace *centreFace) { this->centreFace = centreFace; } void Triangle::setSommets(std::vector<Sommet*> sommets) { this->sommets = sommets; } void Triangle::addSegment(Segment *s) { if(segments.size()>2){ std::cout<<"Erreur : tentative d'insertion d'un 3ième segment à un triangle"<<std::endl; return; } segments.push_back(s); } void Triangle::removeSegment(int id) { std::vector<Segment*>::iterator i; for(i=segments.begin();i!=segments.end();++i){ Segment* cs = *i; if(id==cs->getID()){ segments.erase(i); return; } } } void Triangle::addSommet(Sommet *s) { if(sommets.size()>2){ std::cout<<"Erreur : tentative d'insertion d'un 3ième sommet à un triangle"<<std::endl; return; } sommets.push_back(s); } void Triangle::removeSommet(int id) { std::vector<Sommet*>::iterator i; for(i=sommets.begin();i!=sommets.end();++i){ Sommet* cs = *i; if(id==cs->getID()){ sommets.erase(i); return; } } } void Triangle::buildLignes() { if(sommets.size()>1){ if(Simulation::ARETES.find(to_string(sommets[0]->getID())+"--"+to_string(sommets[1]->getID()))==Simulation::ARETES.end()){ Arete* ar = new Arete(); ar->setID(Simulation::ARETES.size()+1); ar->addSommet(sommets[0]); ar->addSommet(sommets[1]); ar->addTriangle(this); Simulation::ARETES[to_string(sommets[0]->getID())+"--"+to_string(sommets[1]->getID())] = ar; this->arete = Simulation::ARETES[to_string(sommets[0]->getID())+"--"+to_string(sommets[1]->getID())]; }else{ this->arete = Simulation::ARETES[to_string(sommets[0]->getID())+"--"+to_string(sommets[1]->getID())]; this->arete->addTriangle(this); } if(centreFace->getID()!=-1){ for(int i=0;i<2;i++){ if(Simulation::SEGMENTS.find(to_string(centreFace->getID())+"--"+to_string(sommets[i]->getID()))==Simulation::SEGMENTS.end()){ Segment* s = new Segment(); s->setID(Simulation::SEGMENTS.size()+1); s->setCentreFace(centreFace); s->setSommet(sommets[i]); s->addTriangle(this); Simulation::SEGMENTS[to_string(centreFace->getID())+"--"+to_string(sommets[i]->getID())] = s; addSegment(Simulation::SEGMENTS[to_string(centreFace->getID())+"--"+to_string(sommets[i]->getID())]); }else{ addSegment(Simulation::SEGMENTS[to_string(centreFace->getID())+"--"+to_string(sommets[i]->getID())]); Simulation::SEGMENTS[to_string(centreFace->getID())+"--"+to_string(sommets[i]->getID())]->addTriangle(this); } } } } } void Triangle::print(int level) const { std::string tab = ""; for(int i=0;i<level;i++){ tab+="\t"; } std::cout<<tab<<"Triangle ID : "<<this->ID<<std::endl; std::cout<<tab<<"Arete : "<<std::endl; arete->print(level+1); std::cout<<tab<<"Segments : "<<std::endl; for(unsigned int i = 0; i < segments.size();i++){ segments[i]->print(level+1); } }
true
8bebc031b53337e80c5b7885a3c590525bfa4bd7
C++
GIBIS-UNIFESP/BIAL
/bial/inc/Adjacency.hpp
UTF-8
4,729
2.96875
3
[]
no_license
/* Biomedical Image Analysis Library * See README file in the root instalation directory for more information. */ /** * @date 2012/Jul/05 * @brief Adjacency relation to be used over an image or matrix. */ #include "Common.hpp" #include "Matrix.hpp" #include "Vector.hpp" #ifndef BIALADJACENCY_H #define BIALADJACENCY_H /* Declarations -------------------------------------------------------------------------------------------------------- */ namespace Bial { template< class D > class Image; union Color; /** * @brief Adjacency relation and forward iteratior related to a matrix. */ class Adjacency { protected: /** * @brief * 2D matrix. First dimension refers to the number of dimensions of adjacency relation and the second dimension * refers to the size of the adjacency relation, that is, the number of elements in it. * Definition: relation(dims, size) */ Matrix< int > relation; size_t dims; public: /** * @date 2012/Jul/06 * @param none * @return none. * @brief Basic Constructor. * @warning Uninitialized adjacency is created. */ Adjacency( ); /** * @date 2012/Jul/06 * @param size: number of elements of the adjacency relation. * @param dims: number of dimensions. * @return none. * @brief Basic Constructor. * @warning Uninitialized adjacency is created. */ Adjacency( size_t size, size_t dims ); /** * @date 2012/Jul/06 * @param elem: Adjacency element index. * @param dim: Number of dimension of the element. * @return Data pointed by index ( elem, dim ). * @brief Returns data pointed by index ( elem, dim ). * @warning Adjacency dimensions and bounds are not verified. */ const int &operator()( size_t elem, size_t dim ) const; /** * @date 2012/Jul/06 * @param elem: Adjacency element index. * @param dim: Number of dimension of the element. * @return Reference of data pointed by index ( elem, dim ). * @brief Returns the reference for data pointed by index ( elem, dim ). * @warning Adjacency dimensions and bounds are not verified. */ int &operator()( size_t elem, size_t dim ); /** * @date 2012/Jul/06 * @param increasing_order: true for sorting in reverse mode. * @return A Vector containing the position of the elements prior to sorting. * @brief Sort adjacency elements in increasing (or decreasing) order with respect to the distance from t * reference element * @warning none. */ Vector< size_t > SortByDistance( bool increasing_order = true ); /** * @date 2017/Apr/04 * @param elm: adjacency relation element. * @return The displacement of elm from origin. * @brief Returns the displacement of elm from origin. * @warning none. */ float Displacement( size_t elm ); /** * @date 2012/Jul/13 * @param none. * @return Number of dimensions of the adjacency relation. * @brief Returns the number of dimensions of the adjacency relation. * @warning none. */ size_t Dims( ) const; /** * @date 2012/Jul/13 * @param none. * @return Number of elements of the adjacency relation. * @brief Returns the number of elements of the adjacency relation. * @warning none. */ size_t Size( ) const; /** * @date 2012/Jul/13 * @param none. * @return Number of elements of the adjacency relation. * @brief Same as Size( ). Just for coherence with Image.size( ). * @warning none. */ size_t size( ) const; /** * @date 2016/Dec/12 * @param none. * @return Reference to the adjacency relation matrix. * @brief Returns a reference to adjacency relation matrix. * @warning none. */ const Matrix< int > &Relation( ) const; /** * @date 2012/Jun/21 * @param os: an output stream. * @return os output stream. * @brief Prints adjacency relation dimensions to output stream os. * @warning none. */ template< class O > O &PrintDimensions( O &os ) const; /** * @date 2014/Oct/13 * @param os: an output stream. * @return The output stream. * @brief Prints adjacency to output stream os. * @warning none. */ template< class O > O &Print( O &os ) const; }; /** * @param os: output stream. * @param adj: an adjacency relation. * @return Reference to os. * @brief Prints the adjacency relation in a friendly way. * @warning none. */ template< class O > O &operator<<( O &os, const Adjacency &adj ); } #include "Adjacency.cpp" #endif
true
c47c2aa96721250a72810da81556baab2bbc8eac
C++
mutexre/SceneGraph
/SceneGraph/Object.cpp
UTF-8
726
2.5625
3
[]
no_license
// // Created by mutexre on 22/10/15. // Copyright © 2015 mutexre. All rights reserved. // #include <SceneGraph/SceneGraph.hpp> using namespace SG; using namespace std; using namespace glm; Object::Object() : name("") {} Object::Object(const string& name) : name(name) {} Object::Object(string&& name) : name(move(name)) {} Object::~Object() {} const shared_ptr<Context>& Object::getContext() const { return context; } void Object::setContext(const shared_ptr<Context>& context) { this->context = context; } const string& Object::getName() const { return name; } void Object::setName(const string& name) { this->name = name; } void Object::setName(string&& name) { this->name = move(name); }
true
f7969886792f9b8e41a4aa53e71e4daf7330c262
C++
peterwzhang/DCP-Solutions
/solutions/011/Peter/main.cpp
UTF-8
735
3.3125
3
[]
no_license
#include <iostream> #include <set> #include <vector> using namespace std; // O(nk) n = size of set, k = length of s vector<string> return_autocomplete(set<string> set, string s) { auto start = set.upper_bound(s); if (start == set.end()) return {}; vector<string> ans; for (auto it = start; it != set.end(); it++) { if (s == it->substr(0, s.length())) ans.push_back(*it); } return ans; } int main() { set<string> s; s.insert("dog"); s.insert("deer"); s.insert("deal"); s.insert("detrimental"); s.insert("alabama"); s.insert("doctor"); string str = "de"; vector<string> ans = return_autocomplete(s, str); for (string x : ans) cout << x << " "; cout << endl; }
true
90391eb9906ecbaf505cdd993eb34db09cc66635
C++
lineCode/darcel
/library/source/syntax_tests/literal_expression_tester.cpp
UTF-8
375
2.625
3
[ "MIT" ]
permissive
#include <catch.hpp> #include "darcel/syntax/literal_expression.hpp" using namespace darcel; using namespace std; TEST_CASE("test_literal_expression", "[LiteralExpression]") { LiteralExpression e(Location::global(), *parse_literal("3.1415")); REQUIRE(e.get_literal().get_value() == "3.1415"); REQUIRE(*e.get_literal().get_type() == *FloatDataType::get_instance()); }
true
e4a17111a0466e543c39831cdc5db0ab63ce94f1
C++
rane1700/ex4
/DriverData.cpp
UTF-8
307
2.53125
3
[]
no_license
// // Created by ran on 01/01/17. // #include "DriverData.h" DriverData::DriverData(int id,Node* loc) { driverId = id; location = loc; } DriverData::~DriverData(){ delete location; } int DriverData::getDriverId() { return driverId; } Node* DriverData::getLocation() { return location; }
true
a992b1813685e7782053814a524284ee3c9e3325
C++
deltj/advent_of_code_2020
/day3/part1.cpp
UTF-8
1,767
3.5
4
[ "MIT" ]
permissive
/** * Given a map describing the locations of trees (#), identify the number of * trees encountered by traversing a path from the top-left to the bottom right * with a slope of -1/3. */ #include <cstdlib> #include <fstream> #include <iostream> #include <vector> #include <sstream> #include <opencv2/core.hpp> void usage() { std::cout << "day3 <input.txt>" << std::endl; } int main(int argc, char *argv[]) { if(argc != 2) { usage(); return EXIT_FAILURE; } std::ifstream ifs(argv[1], std::ifstream::in); std::string testLine; std::getline(ifs, testLine); ifs.seekg(0, std::ios::beg); int rows = 1000; int cols = testLine.length(); cv::Mat treemat(rows, cols, CV_8UC1); std::string line; int row = 0; while(std::getline(ifs, line)) { if(line.length() != cols) { std::cerr << "unexpected line length: " << line.length() << std::endl; break; } for(int col=0; col<cols; ++col) { if(line.at(col) == '#') { // This cell contains a tree treemat.at<uchar>(row, col) = 1; } else { // This cell does not contain a tree treemat.at<uchar>(row, col) = 0; } } row++; } rows = row; std::cout << "read " << rows << " lines" << std::endl; int treesHit = 0; for(int row=0; row<rows; row += 1) { int col = (row * 3) % cols; std::cout << "checking row/col: " << row << "/" << col << std::endl; if(treemat.at<uchar>(row, col) == 1) treesHit++; } std::cout << "hit " << treesHit << " trees" << std::endl; ifs.close(); }
true
6a0a31caff107f7a51b7210ee5f307eb476c8007
C++
YgorCruz/Listas-de-C
/Lista 04/Ex15.cpp
ISO-8859-1
279
2.84375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <locale.h> main(){ int num; float h=0; setlocale(LC_ALL,"Portuguese"); printf("Digite um nmero : "); scanf("%i",&num); for(int cont = 1; cont <= num; cont ++){ h+=(float)1/(cont); } printf("O valor de H %.2f",h); }
true
7c66636ee4bc7bbce5afdcc5e8ad8fd6e1308daa
C++
Murami/rtype
/Server/include/Util/Vec2.hh
UTF-8
752
3
3
[]
no_license
#ifndef UTIL_VEC2 #define UTIL_VEC2 namespace Util { class Vec2 { public: float x; float y; public: Vec2(); Vec2(const Vec2& vec); Vec2(float p_x, float p_y); ~Vec2(); const Vec2& operator=(const Vec2& vec); const Vec2& operator+=(const Vec2& vec); const Vec2& operator-=(const Vec2& vec); const Vec2& operator*=(float factor); const Vec2& operator/=(float factor); Vec2 operator+() const; Vec2 operator+(const Vec2& vec) const; Vec2 operator-() const; Vec2 operator-(const Vec2& vec) const; Vec2 operator*(float factor) const; Vec2 operator/(float factor) const; void normalize(); static float dot(const Vec2& v1, const Vec2& v2); }; }; #endif /* UTIL_VEC2 */
true
158be6ac19ea3aff6cfa76cbb3a1f25cc39c9fa6
C++
nicomatex/taller_argentum
/client/engine/components/position_component.h
UTF-8
1,289
3.328125
3
[]
no_license
#ifndef POSITION_COMPONENT_H #define POSITION_COMPONENT_H #include <mutex> #include "../ECS/component.h" #include "../SDL/sdl_timer.h" /** * @brief Componente de posicion. Usada en NPCs y jugadores. * */ class PositionComponent : public Component { private: int x; int y; std::mutex m; /* Indica si se llamo a set_position al menos una vez. */ bool initialized; public: PositionComponent(); /** * @brief Crea un objeto Position Component * * @param x X inicial. * @param y Y inicial. */ PositionComponent(int x, int y); ~PositionComponent(); void init() override; void update() override; /** * @brief Devuelve la coordenada X. * * @return int */ int get_x(); /** * @brief Devuelve la coordenada Y. * * @return int */ int get_y(); /** * @brief Setea la posicion. * * @param x Nueva coordenada X de la posicion. * @param y Nueva coordenada Y de la posicion. */ void set_position(int x, int y); /** * @brief Indica si ya hubo un set_position. * * @return true si ya hubo un set_position. * @return false si no hubo un set_position. */ bool position_initialized(); }; #endif
true
e4c8ac4f5e324d8d175432bff401eb4b164c31cc
C++
tituswinters/hmc-clinic-examples
/auto/ex5.cc
UTF-8
172
2.8125
3
[]
no_license
#include <map> void f() { std::map<int, int> some_map; int count = 0; for (const std::pair<int, int> item : some_map) { count += item.first + item.second; } }
true
ccc8499f49433794f72d3806acb0317573a04f9a
C++
pratyushvatsalshukla/CodeForces
/A. In Search of an Easy Problem.cpp
UTF-8
310
2.53125
3
[]
no_license
#include<bits/stdc++.h> using namespace std ; int main(){ int n ; cin >> n ; int arr[n] ; for(int i = 0 ; i < n ; i++) { cin >> arr[i] ; } sort(arr,arr+n) ; // for(int i = 0 ; i < n ; i++) // { // cout << arr[i] ; // } if(arr[n-1] == 1) { cout << "HARD" ; } else { cout << "EASY" ; } }
true
cb3ec0508e29dce47cb05aebfdf1497876b961fb
C++
someoneAlready/ZZU
/personal/contest1/F.cpp
UTF-8
618
2.53125
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <climits> #include <iostream> #include <algorithm> #include <queue> #include <stack> #include <vector> using namespace std; typedef long long ll; struct P{ ll x, y; P(){} P(ll x, ll y):x(x),y(y){} P operator + (const P&p)const{ return P(x+p.x, y+p.y); } }; int i,j,k,m,n,l,p; int main(){ while (~scanf("%d%d", &p, &n) && p+n){ P x=P(1, 1), y=P(1, 0), z; double pp=sqrt(1.*p); while (true){ z = x + y; if (z.x>n) break; if (z.x*1./z.y<pp) x=z; else y=z; } cout<<y.x<<'/'<<y.y<<endl; } return 0; }
true
ea1f8b54b0dc7e97085873a821540afcf5d62c92
C++
Sunil2120/Coding_questions
/geeks_for_geeks/binary_trees/diagonal_view.cpp
UTF-8
680
3.328125
3
[]
no_license
// diagonal view // same as top view,left view,bottom view,right view // only difference is when we go left increament and when we go right do nothing. void solve(Node* root,int d,map<int,vector<int>>& hash) { if(root==NULL) { return ; } hash[d].push_back(root->data); //left solve(root->left,d+1,hash); //right solve(root->right,d,hash); return ; } vector<int> diagonal(Node *root) { map<int,vector<int>> hash; vector<int> output; solve(root,0,hash); for(auto it:hash) { vector<int> temp = it.second; for(auto i:temp) { output.push_back(i); } } return output; }
true
9a32ad615565db55c1fa223938c0b76e69a4aa38
C++
yangjietadie/db
/mysql/MySQLConn.hpp
UTF-8
765
2.703125
3
[]
no_license
/* ** Copyright (C) 2015 Wang Yaofu ** All rights reserved. ** **Author:Wang Yaofu voipman@qq.com **Description: The header file of class MySQLConn. */ #pragma once #include <string> #include <mysql.h> // START_NAMESPACE class MySQLConn { public: enum Status { OK, FAILED }; struct Options { std::string host = {"127.0.0.1"}; int port = {3306}; std::string user = {"root"}; std::string passwd; std::string database; }; MySQLConn(); MySQLConn(const Options& opt); virtual ~MySQLConn(); void init(const Options& opt); virtual int connect(); virtual int close(); virtual MYSQL* handler(); private: MYSQL* conn_; Options option_; }; // END_NAMESPACE
true
c443f83ec66c82380dbf9fc3cf4bfdac5838ab65
C++
paweldata/Technologie-sieciowe
/lista3/zad2/src/Frame.h
UTF-8
461
2.96875
3
[]
no_license
#ifndef FRAME_H #define FRAME_H #include "Direction.h" class Frame { public: Frame(int owner, Direction direction, bool collision); int getOwner() const; Direction getDirection() const; bool ifCollision() const; bool operator==(const Frame &frame) const { return (frame.owner == this->owner && frame.direction == this->direction); } private: int owner; Direction direction; bool collision; }; #endif //FRAME_H
true
4eae727d0cf40c2c640644975491b66890e56294
C++
Zcc/Algorithms
/Chap4_BinSearch/main.cpp
GB18030
842
3.859375
4
[]
no_license
#include <iostream> using namespace std; //arrдfirstlocationlastlocationλünum int BinSearch(const int arr[],int firstlocation,int lastlocation,const int num) { int mid = (firstlocation+lastlocation)/2; if(firstlocation>lastlocation) { return -1; } if(num==arr[mid-1]) { return mid; } if(num<arr[mid-1]) { return BinSearch(arr,firstlocation,mid-1,num); } if(num>arr[mid-1]) { return BinSearch(arr,mid+1,lastlocation,num); } } int main() { int arr[10]={2,4,6,8,10,100,200,300,400,500},num,tmp; cout<<"зǵݼ飬һжϴǷڴڣ"<<endl; cin>>num; tmp = BinSearch(arr,1,10,num); if(tmp==-1) { cout<<"С"<<endl; } else { cout<<"ĵ"<<tmp<<"λ"<<endl; } return 0; }
true
51ac7a35c262f22c9de09fd8e9c6772ef3f6019f
C++
PauloFer1/VisualAutomationWin7
/VisualAutomation/Constants.cpp
UTF-8
2,658
2.796875
3
[]
no_license
#include "stdafx.h" #include "Constants.h" Constants::Constants() { } Constants::~Constants() { } bool Constants::instanceFlag = false; Constants* Constants::single = NULL; Constants* Constants::getInstance(){ if (!instanceFlag) { single = new Constants(); instanceFlag = true; return(single); } else return(single); } void Constants::setCalibMM(int val) { this->calibMM = val; } void Constants::setBlur(int val){ this->blur = val; } void Constants::setBright(int val){ this->brightnessVal = val; } void Constants::setCanny(int val){ this->cannyVal = val; } void Constants::setConstrast(int val){ this->constastVal = val; } void Constants::setZoom(int val){ this->zoomVal = val; } void Constants::setExposure(int val){ this->exposureVal = val; } void Constants::setObjHeight(int val){ this->objectHeight = val; } void Constants::setObjWidth(int val){ this->objectWidth = val; } void Constants::setTypeThresh(int val){ this->typeThreshold = val; } void Constants::setHasThreshold(bool val){ this->hasThreshold = val; } void Constants::setCalibVal(int val){ this->calibrationVal = val; } void Constants::setThresholdVal(int val){ this->thresholdVal = val; } void Constants::connectMachine() { this->isConnectedMachine = true; } void Constants::disconnectMachine() { this->isConnectedMachine = false; } void Constants::setInitialX(int x){ this->initialX = x; } void Constants::setInitialY(int y){ this->initialY = y; } void Constants::setInitialRot(int rot){ this->initialRot = rot; } int Constants::getCalibVal(){ return(this->calibrationVal); } int Constants::getThresholdVal(){ return(this->thresholdVal); } int Constants::getBlur() { return this->blur; } int Constants::getCalibMM() { return(this->calibMM); } int Constants::getCanny() { return this->cannyVal; } int Constants::getConstrast() { return this->constastVal; } int Constants::getZoom() { return this->zoomVal; } int Constants::getExposure() { return this->exposureVal; } int Constants::getObjHeight() { return this->objectHeight; } int Constants::getObjWidth() { return this->objectWidth; } int Constants::getTypeThresh() { return this->typeThreshold; } int Constants::getBright() { return this->brightnessVal; } bool Constants::getHasThreshold() { return this->hasThreshold; } int Constants::getHasThresholdInt() { int has = 0; if (this->hasThreshold) has = 1; return has; } bool Constants::checkConnection() { return(this->isConnectedMachine); } int Constants::getInitialX(){ return(this->initialX); } int Constants::getInitialY(){ return(this->initialY); } int Constants::getInitialRot(){ return(this->initialRot); }
true
de4558a467ffa854d2a6217c9cb2b51863462c61
C++
rdzhao/LeetCode
/024SwapNodesInPairs/code.cpp
UTF-8
693
3.5625
4
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* fir = NULL; ListNode* sec = NULL; ListNode* thi = NULL; ListNode* fou = NULL; if (!head == NULL && !head->next == NULL) { sec = head; thi = head->next; fou = head->next->next; head = thi; thi->next = sec; sec->next = fou; } while (fou != NULL && fou->next != NULL) { fir = sec; sec = fou; thi = fou->next; fou = fou->next->next; fir->next = thi; thi->next = sec; sec->next = fou; } return head; } };
true
fbe26560a1d918d65bdc0090b90fe08c0118a1d5
C++
theshrewedshrew/BakerLabsC
/PROB#10.CPP
UTF-8
1,416
3.390625
3
[]
no_license
// Program: Even // By: Bryan J. Baker #include <iostream.h> #include <conio.h> #include <iomanip.h> #include <apstring.h> //Const Section //Var Section int Hours; apstring F_Name, L_Name, Address, Ssn; char Answer; double Cost; void main() { clrscr(); cout<<setiosflags(ios::showpoint)<<setprecision(2); cout<<"Enter your First Name:"; cin>>F_Name; cout<<"Enter your Last Name:"; cin>>L_Name; cout<<"Please use the underscore ""_"" instead of a space when"; cout<<" answering"<<endl<<" the following question."<<endl<<endl; cout<<"Address:"; cin>>Address; cout<<"Are you a resident Y/N"; cin>>Answer; cout<<"Please enter your SSN (000-00-0000):"; cin>>Ssn; cout<<"Please enter the number of hours taken:"; cin>>Hours; if(Answer=='Y' || Answer=='y') { if (Hours<5) Cost=Hours*80.00; else if (Hours<12) Cost= Hours*70.00; else Cost = 900.00; } else { if (Hours<5) Cost=Hours*120.00; else if (Hours<12) Cost= Hours*110.00; else Cost = 1400.00; } clrscr(); cout<<"First Name:"<<F_Name<<endl; cout<<"Last Name:"<<L_Name<<endl; cout<<"Address:"<<Address<<endl; cout<<"State Resident:"; if (Answer=='Y' || Answer =='y') cout<<"Yes"; else cout<<"No"; cout<<endl<<"Your total cost is:$"<<Cost<<endl<<endl; cout<<"Please press return to continue."<<endl; getch(); }
true
613bfe703fb0e7b2aa4a170671151cd83df4e01b
C++
zzzmfps/PAT
/Basic-Level-Practice/1005 继续(3n+1)猜想 (25).cc
UTF-8
1,205
3.109375
3
[]
no_license
#include <algorithm> #include <iostream> using namespace std; static int x = []() { ios_base::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); class Solution { private: // -1: temp important, 0: not mentioned yet, 1: not important int marks[10000]{}; // may larger than 100 while calculating 3n + 1 int *record; int n; public: Solution() { cin >> n; record = new int[n]; for (int i = 0; i < n; ++i) { cin >> record[i]; int tmp = record[i]; if (marks[tmp] > 0) continue; marks[tmp] = -1; while ((tmp = (tmp & 1 ? 3 * tmp + 1 : tmp) / 2) > 1) { int start = marks[tmp]; if (start <= 0) marks[tmp] = 1; if (start != 0) break; } } sort(record, record + n, greater<int>()); } void printImportantNumber() { int count = 0; for (int i = 0; i < n; ++i) if (marks[record[i]] < 0) cout << (count++ ? " " : "") << record[i]; } }; int main(void) { Solution s; s.printImportantNumber(); return 0; }
true
20e07461a0b7ead83b2d0ff4231ac038ee42858a
C++
malavikarajeshvikraman/DS-basics
/Trees/Basics/traversals.cpp
UTF-8
2,023
4.15625
4
[ "Apache-2.0" ]
permissive
#include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; struct node { int data; struct node* left; struct node* right; }; void inorder (struct node* root) { if(root==NULL) return; inorder(root->left); cout<<root->data; inorder(root->right); } void preorder (struct node* root) { if(root==NULL) return; cout<<root->data; preorder(root->left); preorder(root->right); } void postorder (struct node* root) { if(root==NULL) return; postorder(root->left); postorder(root->right); cout<<root->data; } /* This function is creating memory for new node struct and allocating values to data and left-right pointers */ struct node* newNode(int data) { // Using malloc to create memory for new node to be created struct node* node = (struct node*)malloc(sizeof(struct node)); // Assigning data node->data = data; // Here we assign left-right children nodes to NULL node->left = NULL; node->right = NULL; //finally returning node return(node); } int main() { /*Root is created first*/ struct node* root = newNode(1); /* This is how the tree looks now..... 1 / \ NULL NULL */ root->left = newNode(2); root->right = newNode(3); /* 2 and are now left and right children to root node 1 / \ 2 3 / \ / \ NULL NULL NULL NULL */ root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); /* 4 and 5 becomes children of 2 1 / \ 2 3 / \ / \ 4 5 6 NULL / \ / \ / \ NULL N N N N N */ printf("The tree has been created"); printf("\nWe will understand printing later"); cout<<"\n Preorder : "; preorder(root); cout<<"\n Postorder : "; postorder(root); cout<<"\n Inorder : "; inorder(root); return 0; }
true
01ab681d2cd1af09756889bbbc7e1b17bd91aa42
C++
daneshvar-amrollahi/JomeBazaar
/Shop.cpp
UTF-8
37,697
2.625
3
[ "MIT" ]
permissive
#include "Shop.hpp" #include "Admin.hpp" #include "BadRequestException.hpp" #include "PermissionDeniedException.hpp" #include "NotFoundException.hpp" #define ADMIN_EMAIL "admin@gmail.com" #include "Product.hpp" #include "Mobile.hpp" #include "Car.hpp" #include "Tv.hpp" #include <iostream> #include <fstream> #include <algorithm> #define POST "POST" #define GET "GET" #define firstIndex 0 #define SINGUP_INDEX 1 #define QUESTIONMARK_INDEX 2 #define EMAIL_INDEX 3 #define USERNAME_INDEX 5 #define PASSWORD_INDEX 7 #define TYPE_INDEX 9 #define TYPE_INDEXX 10 #define LOGIN_INDEX 1 #define LOGOUT_INDEX 1 #define IMPORT_INDEX 1 #define PATH_INDEX 5 #define OFFER_INDEX 1 #define CHANGE_OFFER_INDEX 1 using namespace std; Shop::Shop() { Admin* newAdmin = new Admin; admin = newAdmin; currentUser = admin; users_count = 0; products_count = 0; offers_count = 0; MOD = 1e9 + 7; base = 727; } long long Shop::getHash(string s) { long long h = 0; for (int i = 1 ; i <= s.size() ; i++) { h *= base; h %= MOD; h += (s[i - 1] - '0' + 1); h %= MOD; } return h; } void Shop::signUp(vector <string> query) { if (query.size() > 11) throw &not_found; if (query.size() < 9) throw &bad_request; if (query.size() == 10) throw &bad_request; string type; if (query.size() == 9) type = BUYER; else type = query[10]; if (query[QUESTIONMARK_INDEX] != "?" || query[3] != "email" || query[5] != "username" || query[7] != "password") throw &bad_request; if (query.size() == 11) if (query[9] != "type") throw &bad_request; string email = query[4]; string username = query[6]; long long password = getHash(query[8]); if (this->duplicateUsername(username)) { throw &bad_request; return; } users_count++; if (type == SELLER) { Seller* newSeller = new Seller(email, username, password, users_count); sellers.push_back(newSeller); currentUser = newSeller; } if (type == BUYER) { Buyer* newBuyer = new Buyer(email, username, password, users_count); buyers.push_back(newBuyer); currentUser = newBuyer; } } bool Shop::duplicateUsername(string username) { for (int i = 0 ; i < sellers.size() ; i++) if (sellers[i]->getUsername() == username) return 1; for (int i = 0 ; i < buyers.size() ; i++) if (buyers[i]->getUsername() == username) return 1; if (username == "admin") return 1; return 0; } void Shop::logIn(vector <string> query) { if (query.size() < 7) throw &bad_request; if (query.size() > 7) throw &not_found; if (query[LOGIN_INDEX] != "login" || query[QUESTIONMARK_INDEX] != "?" || query[EMAIL_INDEX] != "email" || query[PASSWORD_INDEX - 2] != "password") throw &bad_request; string email = query[EMAIL_INDEX + 1]; long long password = getHash(query[6]); for (int i = 0 ; i < sellers.size() ; i++) if (sellers[i]->getEmail() == email && sellers[i]->getPassword() == password) { currentUser = sellers[i]; return; } for (int i = 0 ; i < buyers.size() ; i++) if (buyers[i]->getEmail() == email && buyers[i]->getPassword() == password) { currentUser = buyers[i]; return; } if (email == ADMIN_EMAIL && query[6] == "admin") { currentUser = admin; return; } throw &bad_request; } void Shop::logOut(vector <string> query) { if (query.size() > 2) throw &not_found; if (currentUser == NULL) { throw &permission_denied; return; } if (isBuyer(currentUser->getUsername())) { Buyer* buyer = findBuyer(currentUser->getUsername()); buyer->emptyCart(); } currentUser = NULL; } #define MOBILE 0 #define CAR 1 #define TV 2 vector <string> split_by_comma(string line) { vector <string> ans; string cur = ""; for (int i = 0 ; i < line.size() ; i++) { if (line[i] == ',') { ans.push_back(cur); cur = ""; continue; } cur += line[i]; } ans.push_back(cur); return ans; } int getType(string path) { char c = path[path.size() - 5]; if (c == 'e') return 0; if (c == 'r') return 1; if (c == 'V' || c == 'v') return 2; } int string_to_int(string s) { int ans = 0; for (int i = 0 ; i < s.size() ; i++) ans *= 10, ans += (s[i] - 'a'); return ans; } Car* Shop::getNewCar(vector <string> splitted) { string name = splitted[0]; int weight = stoi(splitted[1]); int num_of_seats = stoi(splitted[2]); int num_of_cylinders = stoi(splitted[3]); int engine_capacity = stoi(splitted[4]); int reverse_parking_sensors = stoi(splitted[5]); return new Car(name, weight, num_of_seats, num_of_cylinders, engine_capacity, reverse_parking_sensors, ++products_count); } Mobile* Shop::getNewMobile(vector <string> splitted) { string name = splitted[0]; int weight = stoi(splitted[1]); double cpu_frequency = stod(splitted[2]); int built_in_memory = stoi(splitted[3]); int ram = stoi(splitted[4]); double display_size = stod(splitted[5]); int camera_resolution = stoi(splitted[6]); string operating_system = splitted[7]; return new Mobile(name, weight, cpu_frequency, built_in_memory, ram, display_size, camera_resolution, operating_system, ++products_count); } Tv* Shop::getNewTv(vector <string> splitted) { string name = splitted[0]; int screen_size = stoi(splitted[1]); string screen_type = splitted[2]; string resolution = splitted[3]; int three_d = stoi(splitted[4]); int hdr = stoi(splitted[5]); return new Tv(name, screen_size, screen_type, resolution, three_d, hdr, ++products_count); } string get_name(string loc) { if ((loc[0] >= 'a' && loc[0] <= 'z') || (loc[0] >= 'A' && loc[0] <= 'Z')) return loc; string ret = ".//"; for (int i = 3 ; i < loc.size() ; i++) { if (loc[i] == '/') ret += "//"; else ret += loc[i]; } return ret; } void Shop::importMobile(string path) { ifstream fin(path.c_str()); string line; getline(fin, line); while (getline(fin, line)) { vector<string> splitted = split_by_comma(line); Mobile* newMobile = getNewMobile(splitted); mobiles.push_back(newMobile); } } void Shop::importCar(string path) { ifstream fin(get_name(path).c_str()); string line; getline(fin, line); while (getline(fin, line)) { vector<string> splitted = split_by_comma(line); Car* newCar = getNewCar(splitted); cars.push_back(newCar); } } void Shop::importTv(string path) { cout << "importing tvzzzzzzzz" << endl; ifstream fin(get_name(path).c_str()); string line; getline(fin, line); while (getline(fin, line)) { vector<string> splitted = split_by_comma(line); Tv* newTv = getNewTv(splitted); tvs.push_back(newTv); } } void Shop::import(vector <string> query) { if (currentUser->getUsername() != ADMIN) throw &permission_denied; if (query.size() < 7) throw &bad_request; if (query.size() > 7) throw &not_found; if(query[QUESTIONMARK_INDEX] != "?" || query[3] != "type" || (query[4] != "mobile" && query[4] != "car" && query[4]!= "tv") || (query[PATH_INDEX] != "filePath") ) throw &bad_request; string path = query[PATH_INDEX + 1]; int type = getType(path); if (type == MOBILE) this->importMobile(path); if (type == CAR) this->importCar(path); if (type == TV) this->importTv(path); } bool cmp(pair<int, string> A, pair<int, string> B) { return A.first < B.first; } bool Shop::isSeller(string username) { for (int i = 0 ; i < sellers.size() ; i++) if (sellers[i]->getUsername() == username) return 1; return 0; } vector < pair<int, string> > Shop::getProducts(vector <string> query) { if (currentUser->getType() != SELLER && currentUser->getType() != BUYER) throw &permission_denied; if (query.size() > 2) throw &not_found; vector < pair<int, string> > products; for (int i = 0 ; i < mobiles.size() ; i++) { Mobile* current = mobiles[i]; products.push_back(make_pair(current->getProductId(), current->getName())); } for (int i = 0 ; i < cars.size() ; i++) { Car* current = cars[i]; products.push_back(make_pair(current->getProductId(), current->getName())); } for (int i = 0 ; i < tvs.size() ; i++) { Tv* current = tvs[i]; products.push_back(make_pair(current->getProductId(), current->getName())); } sort(products.begin(), products.end(), cmp); cout << "productId | productName" << endl; for (int i = 0 ; i < products.size() ; i++) { int id = products[i].first; string name = products[i].second; cout << id << " | "<< name << endl; } return products; } bool Shop::duplicateOffer(int product_id) { vector <Offer*> offers = (this->findSeller(currentUser->getUsername()))->getOffers(); for (int i = 0 ; i < offers.size() ; i++) if (offers[i]->getProductId() == product_id) return 1; return 0; } Seller* Shop::findSeller(string username) { for (int i = 0 ; i < sellers.size() ; i++) if (sellers[i]->getUsername()== username) return sellers[i]; } Buyer* Shop::findBuyer(string username) { for (int i = 0 ; i < buyers.size() ; i++) if (buyers[i]->getUsername() == username) return buyers[i]; } void Shop::addOffer(vector <string> query) { if (query.size() < 9) throw &bad_request; if (query.size() > 9) throw &not_found; if (query[OFFER_INDEX] != "offer" || query[QUESTIONMARK_INDEX] != "?" || query[3] != "productId" || query[5] != "offerUnitPrice" || query[7] != "offerAmount") throw &bad_request; int product_id = stoi(query[4]); double price = stod(query[6]); int amount = stoi(query[8]); if (this->duplicateOffer(product_id)) throw &bad_request; if (!(this->existsProductId(product_id))) throw &not_found; Offer* newOffer = new Offer(product_id, ++offers_count, price, amount); Seller* current_seller = this->findSeller(currentUser->getUsername()); current_seller->addNewOffer(newOffer); } bool Shop::existsProductId(int product_id) { for (int i = 0 ; i < mobiles.size() ; i++) if (mobiles[i]->getProductId() == product_id) return 1; for (int i = 0 ; i < cars.size() ; i++) if (cars[i]->getProductId() == product_id) return 1; for (int i = 0 ; i < tvs.size() ; i++) if (tvs[i]->getProductId() == product_id) return 1; return 0; } vector < vector <string> > Shop::getMyOffers(vector <string> query) { if (!isSeller(currentUser->getUsername())) throw &permission_denied; if (query.size() > 2) throw &not_found; Seller* current_seller = this->findSeller(currentUser->getUsername()); vector <Offer*> offers = current_seller->getOffers(); vector < vector<string> > res; cout << "productId | offerId | offerUnitPrice | offerAmount" << endl; for (int i = 0 ; i < offers.size() ; i++) { vector <string> current; Offer* current_offer = offers[i]; cout << current_offer->getProductId() << " | "<< current_offer->getId() << " | " << current_offer->getUnitPrice() << " | " << current_offer->getAmount() << endl; current.push_back(to_string(current_offer->getProductId())); current.push_back(to_string(current_offer->getId())); current.push_back(to_string(current_offer->getUnitPrice())); current.push_back(to_string(current_offer->getAmount())); res.push_back(current); } return res; } void Shop::changeOffer(vector <string> query) { if (query.size() < 9) throw &bad_request; if (query[QUESTIONMARK_INDEX] != "?" || query[3] != "offerId" || query[5] != "offerUnitPrice" || query[7] != "offerAmount") throw &bad_request; int offer_id = stoi(query[4]); double offer_unit_price = stod(query[6]); int offer_amount = stoi(query[8]); Seller* current_seller = this->findSeller(currentUser->getUsername()); vector <Offer*> offers = current_seller->getOffers(); for (int i = 0 ; i < offers.size() ; i++) { Offer* current_offer = offers[i]; if (offers[i]->getId() == offer_id) { offers[i]->setUnitPrice(offer_unit_price); offers[i]->setAmount(offer_amount); return; } } throw &not_found; } Offer getOffer(Offer* current_offer) { int product_id = current_offer->getProductId(); int id = current_offer->getId(); double price = current_offer->getUnitPrice(); int amount = current_offer->getAmount(); return Offer(product_id, id, price, amount); } bool cmp1(Offer A, Offer B) { return A.getId() < B.getId(); } bool cmp2(Offer A, Offer B) { return A.getUnitPrice() < B.getUnitPrice(); } bool cmp3(Offer A, Offer B) { return A.getId() > B.getId(); } bool cmp4(Offer A, Offer B) { return A.getUnitPrice() > B.getUnitPrice(); } void printOffers(vector <Offer> offers) { cout << "productId | offerId | offerUnitPrice | offerAmount" << endl; for (int i = 0 ; i < offers.size() ; i++) { Offer offer = offers[i]; cout << offer.getProductId() << " | " << offer.getId() << " | " << offer.getUnitPrice() << " | " << offer.getAmount() << endl; } } bool getOffersHasBadRequest(vector <string> query) { if (query.size() < 7) return 1; if (query[2] != "?") return 1; if (query[3] != "order" || query[5] != "field") return 1; if ((query[4] != "ASCEND" && query[4] != "DESCEND") || (query[6] != "offerId" && query[6]!= "offerPrice")) return 1; return 0; } void Shop::printOffersForBuyer(vector <Offer> offers) { cout << "productId | productName | offerId | offerUnitPrice | offerAmount" << endl; for (int i = 0 ; i < offers.size() ; i++) { Offer offer = offers[i]; int product_id = offer.getProductId(); string name; if (isMobile(product_id)) { Mobile* mobile = getMobileById(product_id); name = mobile->getName(); } if (isTv(product_id)) { Tv* tv = getTvById(product_id); name = tv->getName(); } if (isCar(product_id)) { Car* car = getCarById(product_id); name = car->getName(); } cout << offer.getProductId() << " | " << name << " | " << offer.getId() << " | " << offer.getUnitPrice() << " | " << offer.getAmount() << endl; } } void Shop::getOffersForBuyer() { vector <Offer> offers; for (int i = 0 ; i < sellers.size() ; i++) { vector <Offer*> current_offers = sellers[i]->getOffers(); for (int j = 0 ; j < current_offers.size() ; j++) { Offer* current_offer = current_offers[j]; offers.push_back(getOffer(current_offer)); } } sort(offers.begin(), offers.end(), cmp1); printOffersForBuyer(offers); } void Shop::getOffers(vector <string> query) { if (query.size() == 2) { if (isBuyer(currentUser->getUsername())) { this->getOffersForBuyer(); return; } } if (getOffersHasBadRequest(query)) throw &bad_request; if (currentUser->getUsername() != ADMIN) throw &permission_denied; if (query.size() > 7) throw &not_found; vector <Offer> offers; for (int i = 0 ; i < sellers.size() ; i++) { vector <Offer*> current_offers = sellers[i]->getOffers(); for (int j = 0 ; j < current_offers.size() ; j++) { Offer* current_offer = current_offers[j]; offers.push_back(getOffer(current_offer)); } } if (query[4] == "ASCEND") { if (query[6] == "offerId") sort(offers.begin(), offers.end(), cmp1); if (query[6] == "offerPrice") sort(offers.begin(), offers.end(), cmp2); } if (query[4] == "DESCEND") { if (query[6] == "offerId") sort(offers.begin(), offers.end(), cmp3); if (query[6] == "offerPrice") sort(offers.begin(), offers.end(), cmp4); } printOffers(offers); } vector < vector<string> > printOffersOnProduct(vector <Offer> offers, string name) { vector < vector<string> > ret; cout << "productId | productName | offerId | offerUnitPrice | offerAmount" << endl; for (int i = 0 ; i < offers.size() ; i++) { Offer current_offer = offers[i]; vector <string> current; current.push_back(to_string(current_offer.getId())); current.push_back(to_string(current_offer.getUnitPrice())); current.push_back(to_string(current_offer.getAmount())); ret.push_back(current); cout << current_offer.getProductId() << " | " << name << " | " << current_offer.getId() << " | " << current_offer.getUnitPrice() << " | " << current_offer.getAmount() << endl; } return ret; } string Shop::getNameById(int id) { for (int i = 0 ; i < mobiles.size() ; i++) if (mobiles[i]->getProductId() == id) return mobiles[i]->getName(); for (int i = 0 ; i < cars.size() ; i++) if (cars[i]->getProductId() == id) return cars[i]->getName(); for (int i = 0 ; i < tvs.size() ; i++) if (tvs[i]->getProductId() == id) return tvs[i]->getName(); return "product_not_found"; } vector< vector<string> > Shop::getOffersOnProduct(vector <string> query) { if (query.size() < 5) throw &bad_request; if (query[2] != "?" || query[3] != "productId") throw &bad_request; if (query.size() > 5) throw &not_found; int product_id = stoi(query[4]); vector <Offer> offers_on_product; for (int i = 0 ; i < sellers.size() ; i++) { vector <Offer*> current_offers = sellers[i]->getOffers(); for (int j = 0 ; j < current_offers.size() ; j++) { Offer* current_offer = current_offers[j]; if (current_offer->getProductId() == product_id) offers_on_product.push_back(getOffer(current_offer)); } } string name = this->getNameById(product_id); if (name == "product_not_found") throw &not_found; sort(offers_on_product.begin(), offers_on_product.end(), cmp1); return printOffersOnProduct(offers_on_product, name); } bool Shop::isMobile(int id) { for (int i = 0 ; i < mobiles.size() ; i++) if (mobiles[i]->getProductId() == id) return 1; return 0; } bool Shop::isCar(int id) { for (int i = 0 ; i < cars.size() ; i++) if (cars[i]->getProductId() == id) return 1; return 0; } bool Shop::isTv(int id) { for (int i = 0 ; i < tvs.size() ; i++) if (tvs[i]->getProductId() == id) return 1; return 0; } Mobile* Shop::getMobileById(int id) { for (int i = 0 ; i < mobiles.size() ; i++) if (mobiles[i]->getProductId() == id) return mobiles[i]; } Car* Shop::getCarById(int id) { for (int i = 0 ; i < cars.size() ; i++) if (cars[i]->getProductId() == id) return cars[i]; } Tv* Shop::getTvById(int id) { for (int i = 0 ; i < tvs.size() ; i++) if (tvs[i]->getProductId() == id) return tvs[i]; } vector <string> printTv(Tv* tv) { vector <string> res; cout << tv->getName() << endl; res.push_back(tv->getName()); cout << "Screen Size: " << tv->getScreenSize() << endl; res.push_back("Screen Size: " + to_string(tv->getScreenSize())); cout << "Screen Type: " << tv->getScreenType() << endl; res.push_back("Screen Type: " + tv->getScreenType()); cout << "Resolution: " << tv->getResolution() << endl; res.push_back("Resolution: " + tv->getResolution()); cout << "3D: " << tv->getThreeD() << endl; res.push_back("3D: " + to_string(tv->getThreeD())); cout << "HDR: " << tv->getHdr() << endl; res.push_back("HDR: " + to_string(tv->getHdr())); return res; } vector <string> printMobile(Mobile* mobile) { vector <string> res; cout << mobile->getName() << endl; res.push_back(mobile->getName()); cout << "Weight: " << mobile->getWeight() << endl; res.push_back("Weight: " + to_string(mobile->getWeight())); cout << "CPUFrequency: " << mobile->getCpuFrequency() << endl; res.push_back("CPUFrequency: " + to_string(mobile->getCpuFrequency())); cout << "Built-in Memory: " << mobile->getBuiltInMemory() << endl; res.push_back("Built-in Memory: " + to_string(mobile->getBuiltInMemory())); cout << "RAM: " << mobile->getRam() << endl; res.push_back("RAM: " + to_string(mobile->getRam())); cout << "Display Size: " << mobile->getDisplaySize() << endl; res.push_back("Display Size: " + to_string(mobile->getDisplaySize())); cout << "Camera Resolution: " << mobile->getCameraResolution() << endl; res.push_back("Camera Resolution: " + to_string(mobile->getCameraResolution())); cout << "Operating System: " << mobile->getOperatingSystem() << endl; res.push_back("Operating System: " + mobile->getOperatingSystem()); return res; } vector <string> printCar(Car* car) { vector <string> res; cout << car->getName() << endl; res.push_back(car->getName()); cout << "Weight: " << car->getWeight() << endl; res.push_back("Weight: " + to_string(car->getWeight())); cout << "Num. of Seats: " << car->getNumOfSeats() << endl; res.push_back("Num. of Seats: " + to_string(car->getNumOfSeats())); cout << "Num. of Cylinders: " << car->getNumOfCylinders() << endl; res.push_back("Num. of Cylinders: " + to_string(car->getNumOfCylinders())); cout << "Engine Capacity: " << car->getEngineCapacity() << endl; res.push_back("Engine Capacity: " + to_string(car->getEngineCapacity())); cout << "Reverse Parking Sensors: " << car->getReverseParkingSensors() << endl; res.push_back("Reverse Parking Sensors: " + to_string(car->getReverseParkingSensors())); return res; } bool Shop::isBuyer(string username) { for (int i = 0 ; i < buyers.size() ; i++) if (buyers[i]->getUsername() == username) return 1; return 0; } vector <string> Shop::getProductDetail(vector <string> query) { if (query.size() < 5) throw &bad_request; if (query.size() > 5) throw &not_found; if (query[2] != "?" || query[3] != "productId") throw &bad_request; if (!isBuyer(currentUser->getUsername())) throw &permission_denied; int id = stoi(query[4]); if (isTv(id)) { Tv* tv = getTvById(id); return printTv(tv); } if (isMobile(id)) { Mobile* mobile = getMobileById(id); return printMobile(mobile); } if (isCar(id)) { Car* car = getCarById(id); return printCar(car); } throw &not_found; } void Shop::addCommentForId(int id, string s, string username) { if (isTv(id)) { Tv* tv = this->getTvById(id); tv->addComment(username, s); } if (isCar(id)) { Car* car = this->getCarById(id); car->addComment(username, s); } if (isMobile(id)) { Mobile* mobile = this->getMobileById(id); mobile->addComment(username, s); } } void Shop::postComment(vector <string> query) { if (query.size() < 7) throw &bad_request; if (query[2] != "?" || query[3] != "productId" || query[5] != "comment") throw &not_found; if (!isBuyer(currentUser->getUsername())) throw &permission_denied; int product_id = stoi(query[4]); if (!(this->existsProductId(product_id))) throw &not_found; string comment = ""; for (int i = 6 ; i < query.size() ; i++) comment += query[i] + " "; while (comment[comment.size() - 1] == ' ') comment.resize(comment.size() - 1); unordered_map<string, double> good = this->getGoods(); unordered_map<string, double> bad = this->getBads(); if (isBad(comment, good, bad)) { return; } addCommentForId(product_id, comment, currentUser->getUsername()); } vector <string> Shop::getCommentsById(int id) { vector <string> ans; if (isTv(id)) { Tv* tv = this->getTvById(id); vector < pair<string, string> > comments = tv->getComments(); ans.push_back(tv->getName()); for (int i = 0 ; i < comments.size() ; i++) ans.push_back((comments[i].first) + " | " + (comments[i].second)); } if (isCar(id)) { Car* car = this->getCarById(id); vector < pair<string, string> > comments = car->getComments(); ans.push_back(car->getName()); for (int i = 0 ; i < comments.size() ; i++) ans.push_back((comments[i].first) + " | " + (comments[i].second)); } if (isMobile(id)) { Mobile* mobile = this->getMobileById(id); vector < pair<string, string> > comments = mobile->getComments(); ans.push_back(mobile->getName()); for (int i = 0 ; i < comments.size() ; i++) ans.push_back((comments[i].first) + " | " + (comments[i].second)); } return ans; } void Shop::getComments(vector <string> query) { if (query.size() < 5) throw &bad_request; if (query[2] != "?" || query[3] != "productId") throw &bad_request; if (query.size() > 5) throw &bad_request; int product_id = stoi(query[4]); if (!(this->existsProductId(product_id))) throw &not_found; vector <string> comments = this->getCommentsById(product_id); for (int i = 0 ; i < comments.size() ; i++) cout << comments[i] << endl; } void Shop::compareTvs(int id1, int id2) { Tv* tv1 = this->getTvById(id1); Tv* tv2 = this->getTvById(id2); cout << tv1->getName() << " | " << tv2->getName() << endl; cout << "Screen Size: " << tv1->getScreenSize() << " | " << tv2->getScreenSize() << endl; cout << "Screen Type: " << tv1->getScreenType() << " | " << tv2->getScreenType() << endl; cout << "Resolution: " << tv1->getResolution() << " | " << tv2->getResolution() << endl; cout << "3D: " << tv1->getThreeD() << " | " << tv2->getThreeD() << endl; cout << "HDR: " << tv1->getHdr() << " | " << tv2->getHdr() << endl; } void Shop::compareCars(int id1, int id2) { Car* car1 = this->getCarById(id1); Car* car2 = this->getCarById(id2); cout << car1->getName() << " | " << car2->getName() << endl; cout << "Weight: " << car1->getWeight() << " | " << car2->getWeight() << endl; cout << "Num. of Seats: " << car1->getNumOfSeats() << " | " << car2->getNumOfSeats() << endl; cout << "Num. of Cylinders: " << car1->getNumOfCylinders() << " | " << car2->getNumOfCylinders() << endl; cout << "Engine Capacity: " << car1->getEngineCapacity() << " | " << car2->getEngineCapacity() << endl; cout << "Reverse Parking Sensors: " << car1->getReverseParkingSensors() << " | " << car2->getReverseParkingSensors() << endl; } void Shop::compareMobiles(int id1, int id2) { Mobile* mobile1 = this->getMobileById(id1); Mobile* mobile2 = this->getMobileById(id2); cout << mobile1->getName() << " | " << mobile2->getName() << endl; cout << "Weight: " << mobile1->getWeight() << " | " << mobile2->getWeight() << endl; cout << "CPUFrequency: " << mobile1->getCpuFrequency() << " | " << mobile2->getCpuFrequency() << endl; cout << "Built-in Memory: " << mobile1->getBuiltInMemory() << " | " << mobile2->getBuiltInMemory() << endl; cout << "RAM: " << mobile1->getRam() << " | " << mobile2->getRam() << endl; cout << "Display Size: " << mobile1->getDisplaySize() << " | " << mobile2->getDisplaySize() << endl; cout << "Camera Resolution: " << mobile1->getCameraResolution() << " | " << mobile2->getCameraResolution() << endl; cout << "salam" << endl; cout << mobile1->getOperatingSystem() << endl; cout << mobile2->getOperatingSystem() << endl; string temp1 = mobile1->getOperatingSystem(); string temp2 = mobile2->getOperatingSystem(); cout << temp1 << endl << temp2 << endl; cout << "Operating System: " << mobile1->getOperatingSystem() << " | " << mobile2->getOperatingSystem() << endl; } void Shop::getCompare(vector <string> query) { if (query.size() < 7) throw &bad_request; if (query[2] != "?" || query[3] != "productId1" || query[5] != "productId2") throw &not_found; int product_id1 = stoi(query[4]); int product_id2 = stoi(query[6]); if (!(this->existsProductId(product_id1))) throw &not_found; if (!(this->existsProductId(product_id2))) throw &not_found; if (!isBuyer(currentUser->getUsername())) throw &permission_denied; if (isTv(product_id1) && isTv(product_id2)) { compareTvs(product_id1, product_id2); return; } if (isCar(product_id1) && isCar(product_id2)) { compareCars(product_id1, product_id2); return; } if (isMobile(product_id1) && isMobile(product_id2)) { compareMobiles(product_id1, product_id2); return; } throw &bad_request; } void Shop::chargeWallet(vector <string> query) { if (query.size() < 5) throw &bad_request; if (query[2] != "?" || query[3] != "amount") throw &bad_request; if (query.size() > 5) throw &not_found; if (!(this->isBuyer(currentUser->getUsername()))) throw &permission_denied; double charge = stod(query[4]); if (charge <= 0) throw &bad_request; Buyer* currentBuyer = findBuyer(currentUser->getUsername()); currentBuyer->addToWallet(charge); } Offer* Shop::getOfferById(int id) { for (int i = 0 ; i < sellers.size() ; i++) { vector <Offer*> offers = sellers[i]->getOffers(); for (int j = 0 ; j < offers.size() ; j++) { Offer* current_offer = offers[j]; if (current_offer->getId() == id) return current_offer; } } return NULL; } Discount* Shop::getDiscountByCode(string code) { for (int i = 0 ; i < discounts.size() ; i++) if (discounts[i]->getCode() == code) return discounts[i]; return NULL; } void Shop::addToCart(vector <string> query) { if (query.size() > 9) throw &not_found; if (query.size() != 7 && query.size() != 9) throw &bad_request; if (query[2] != "?" || query[3] != "offerId" || query[5] != "amount") throw &bad_request; if (query.size() == 9) if (query[7] != "discountCode") throw &bad_request; if (!(this->isBuyer(currentUser->getUsername()))) throw &permission_denied; Buyer* buyer = findBuyer(currentUser->getUsername()); int offer_id = stoi(query[4]); Offer* offer = getOfferById(offer_id); int want = stoi(query[6]); if (want > offer->getAmount()) throw &bad_request; double disc = 0; if (query.size() == 9) { Discount* d = getDiscountByCode(query[8]); if (d == NULL) throw &bad_request; //discount besooze for (int i = 0 ; i < discounts.size() ; i++) if (discounts[i]->getCode() == query[8]) { discounts.erase(discounts.begin() + i); return; } if (d->getOffer() != offer) throw &bad_request; disc = d->getPercent(); } buyer->addToCart(offer, want, disc); } void Shop::generateDiscount(vector <string> query) { if (!isSeller(currentUser->getUsername())) throw &permission_denied; if (query.size() < 9) throw &bad_request; if (query.size() > 9) throw &not_found; if (query[2] != "?" || query[3] != "offerId" || query[5] != "discountPercent" || query[7] != "discountNumber") throw &not_found; int offer_id = stoi(query[4]); Offer* offer = this->getOfferById(offer_id); if (offer == NULL) throw &bad_request; double percent = stod(query[6]); int number = stoi(query[8]); for (int i = 0 ; i < number ; i++) { Discount* d = new Discount(percent, offer); cout << d->getCode() << endl; discounts.push_back(d); } } Seller* Shop::getSellerByOfferId(int id) { for (int i = 0 ; i < sellers.size() ; i++) { Seller* seller = sellers[i]; vector <Offer*> offers = seller->getOffers(); for (int j = 0 ; j < offers.size() ; j++) if (offers[j]->getId() == id) return seller; } return NULL; } vector<string> Shop::getCart(vector <string> query) { if (!isBuyer(currentUser->getUsername())) throw &permission_denied; Buyer* buyer = findBuyer(currentUser->getUsername()); vector < pair< Offer* , pair<int, double> > > cart = buyer->getCart(); if (cart.size() == 0) { cout << "Empty" << endl; vector <string> ans; return ans; } vector <string> ret; cout << "productId | productName | offerId | sellerId | totalPriceConsideringDiscount | amount" << endl; ret.push_back("productId | productName | offerId | sellerId | totalPriceConsideringDiscount | amount"); for (int i = 0 ; i < cart.size() ; i++) { pair< Offer* , pair<int, double> > current = cart[i]; Offer* offer = cart[i].first; int product_id = offer->getProductId(); string product_name = (this->getNameById(product_id)); int offer_id = offer->getId(); Seller* seller = getSellerByOfferId(offer_id); int seller_id = seller->getId(); int amount = current.second.first; double price = amount * (offer->getUnitPrice()); ret.push_back(to_string(product_id) + " | " + product_name + " | " + to_string(offer_id) + " | " + to_string(seller_id) + " | " + to_string(price) + " | " + to_string(amount)); cout << product_id << " | " << product_name << " | " << offer_id << " | " << seller_id << " | " << price << " | " << amount << endl; } return ret; } void Shop::getWalletCount(vector <string> query) { if (query.size() < 5) throw &bad_request; if (query.size() > 5) throw &not_found; if (query[2] != "?" || query[3] != "count") throw &bad_request; int count = stoi(query[4]); vector <double> wallet = currentUser->getWallet(); cout << "credit" << endl; for (int i = wallet.size() - 1 ; i >= 0 && count > 0 ; i--, count--) cout << wallet[i] << endl; } Order* Shop::getOrderFromCart(pair< Offer* , pair<int, double> > current) { Offer* offer = current.first; int product_id = offer->getProductId(); string product_name = getNameById(product_id); int offer_id = offer->getId(); Seller* seller = getSellerByOfferId(offer_id); int seller_id = seller->getId(); double discount = current.second.second; int amount = current.second.first; double total_price = amount * (offer->getUnitPrice()); double price = total_price - (discount / 100.0) * total_price; return new Order(product_id, product_name, offer_id, seller_id, price, amount); } void Shop::submitCart(vector <string> query) { if (query.size() > 2) throw &not_found; if (!isBuyer(currentUser->getUsername())) throw &permission_denied; Buyer* buyer = findBuyer(currentUser->getUsername()); vector < pair< Offer* , pair<int, double> > > cart = buyer->getCart(); vector <Order*> currentOrders;; double total_price_buyer = 0; for (int i = 0 ; i < cart.size() ; i++) { pair< Offer* , pair<int, double> > current = cart[i]; Order* currentOrder = this->getOrderFromCart(current); total_price_buyer += currentOrder->getSoldPrice(); currentOrders.push_back(currentOrder); } if (total_price_buyer > buyer->getCredit()) throw &bad_request; buyer->reduceWallet(total_price_buyer); for (int i = 0 ; i < cart.size() ; i++) { pair< Offer* , pair<int, double> > current = cart[i]; Offer* offer = current.first; int offer_id = offer->getId(); Seller* seller = getSellerByOfferId(offer_id); double discount = current.second.second; int amount = current.second.first; double total_price = amount * (offer->getUnitPrice()); double price = total_price - (discount / 100.0) * total_price; seller->addToWallet(price); offer->setAmount(offer->getAmount() - amount); } buyer->emptyCart(); buyer->addToOrders(currentOrders); } void Shop::getOrders(vector <string> query) { if (!isBuyer(currentUser->getUsername())) throw &permission_denied; if (query.size() < 5) throw &bad_request; if (query.size() > 5) throw &not_found; if (query[2] != "?" || query[3] != "count") throw &bad_request; Buyer* buyer = findBuyer(currentUser->getUsername()); vector < vector <Order*> > orders = buyer->getOrders(); if (orders.size() == 0) throw &not_found; cout << "ProductId | productName | offerId | sellerId | soldPrice | amount" << endl; for (int i = 0 ; i < orders.size() ; i++) { for (int j = 0 ; j < orders[i].size() ; j++) { Order* currentOrder = orders[i][j]; int product_id = currentOrder->getProductId(); string product_name = currentOrder->getProductName(); int offer_id = currentOrder->getOfferId(); int seller_id = currentOrder->getSellerId(); double sold_price = currentOrder->getSoldPrice(); int amount = currentOrder->getAmount(); cout << product_id << " | " << product_name << " | " << offer_id << " | " << seller_id << " | " << sold_price << " | " << amount << endl; if (i != orders.size() - 1) cout << "****" << endl; } } } unordered_map<string, double> Shop::getGoods() { unordered_map <string, double> good; ifstream fin("train.csv"); string line; getline(fin, line); while (getline(fin, line)) { if (line[0] - '0' >= 0 && line[0] - '0' < 10) continue; vector <string> q = split_by_comma(line); string word = q[0]; double p_good = stod(q[1]); good[word] = p_good; } return good; } unordered_map<string, double> Shop::getBads() { unordered_map <string, double> bad; ifstream fin("train.csv"); string line; getline(fin, line); while (getline(fin, line)) { if (line[0] - '0' >= 0 && line[0] - '0' < 10) continue; vector <string> q = split_by_comma(line); string word = q[0]; double p_bad = stod(q[2]); bad[word] = p_bad; } return bad; } vector < pair<string, int> > Shop::readComments() { ifstream fin("test.csv"); string line; vector < pair<string, int> > ans; getline(fin, line); while (getline(fin, line)) { int last = line[line.size() - 1] - '0'; line.resize(line.size() - 1); ans.push_back(make_pair(line, last)); } return ans; } vector <string> split_by_space(string line) { vector <string> ans; string cur = ""; for (int i = 0 ; i < line.size() ; i++) { if (line[i] == ' ') { if (cur != "") ans.push_back(cur); cur = ""; continue; } cur += line[i]; } if (cur != "") ans.push_back(cur); return ans; } int Shop::isBad(string comment, unordered_map<string, double> good, unordered_map<string, double> bad) { long double spam = 0, ham = 0; vector <string> words = split_by_space(comment); for (int i = 0 ; i < words.size() ; i++) { string word = words[i]; if (good.find(word) != good.end()) { ham += (long double)(log(good[word])); spam += (long double)(log(bad[word])); } } ham += (long double)(log(0.91175)); spam += (long double)(log(1-0.91175)); return (spam > ham); } void Shop::evaluate(vector < pair<string, int> > comments, unordered_map<string, double> good, unordered_map<string, double> bad) { int correct_detected_appropriate = 0, all_appropriate = 0; int detected_appropriate = 0, correct_detected = 0; for (int i = 0 ; i < comments.size() ; i++) { string comment = comments[i].first; int is_bad = comments[i].second; int detected_bad = isBad(comment, good, bad); correct_detected_appropriate += ( (!is_bad) && (!detected_bad) ); all_appropriate += (!is_bad); detected_appropriate += (!detected_bad); correct_detected += (is_bad == detected_bad); } cout << "Recall: " << (double(correct_detected_appropriate) / double(all_appropriate)) * 100.0 << endl; cout << "Precision: " << (double(correct_detected_appropriate) / double(detected_appropriate)) * 100.0 << endl; cout << "Accuracy: " << (double(correct_detected) / double(comments.size())) * 100.0 << endl; } void Shop::evaluateModel() { unordered_map<string, double> good = this->getGoods(); unordered_map<string, double> bad = this->getBads(); vector < pair<string, int> > comments = this->readComments(); this->evaluate(comments, good, bad); }
true
4e75b65a32f950c61c83f28874f3278169fbdd72
C++
balintdbene/Chess
/Final/move.cc
UTF-8
1,083
3.296875
3
[]
no_license
#include"move.h" Move::Move(){ //constructor for move start = " "; end = " "; capLocation = " "; capType = ' '; promotedTo = ' '; thisHasMoved = false; capturedHasMoved = false; castling = false; } bool Move::operator==(const Move& other){ //equality overload bool startSame = other.start == start; bool endSame = other.end == end; bool capTypeSame = other.capType == capType; bool capLocationSame = other.capLocation == capLocation; bool promotedToSame = other.promotedTo == promotedTo; bool hasMovedSame = other.thisHasMoved == thisHasMoved && other.capturedHasMoved == capturedHasMoved; bool castlingSame = other.castling == castling; return startSame && endSame && capTypeSame && capLocationSame && promotedToSame && hasMovedSame && castlingSame; } Move& Move::operator=(const Move& other){ //assignment overload start = other.start; end = other.end; capLocation = other.capLocation; capType = other.capType; promotedTo = other.promotedTo; thisHasMoved = other.thisHasMoved; capturedHasMoved = other.capturedHasMoved; castling = other.castling; }
true
b15ad8ac51f4407d264726fefa6fb3e28983eab9
C++
adamtew/USU
/2014/CS1400/Challenges/Chapter 4/4.6_Change_for_a_Dollar_Games.cpp
UTF-8
1,365
4.0625
4
[]
no_license
/*Create a change-counting game that asks the user to enter what coins to use to make exactly one dollar. The program should ask the user to enter the number of pennies, nickels, dimes, and quarters. If the total value of the coins entered is equal to on dollar, the program should congratulate the user for winning the game. Otherwise, the program should display a message indicating where the amount was more or less than one dollar. Use constant variables to hold the coing values.*/ // Adam Tew ---- CS1400 #include <iostream> #include <iomanip> using namespace std; int main(){ const float penny = .01, nickel = .05, dime = .10, quarter = .25; int numPen = 0, numNic = 0, numDim = 0., numQua = 0; float total; cout << "\n\tHow close to a dollar can you get?"; cout << "\n\tPennies: "; cin >> numPen; cout << "\tNickels: "; cin >> numNic; cout << "\tDimes: "; cin >> numDim; cout << "\tQuarters: "; cin >> numQua; total += (numPen * penny); total += (numNic * nickel); total += (numDim * dime); total += (numQua * quarter); cout << fixed << setprecision(2); if(total == 1){ cout << "\n\tPerfect score! Good job! " << total << endl; }else if(total < 1){ cout << "\n\tYou came in under $1.00 with a total of " << total << endl; }else if(total > 1){ cout << "\n\tYou went over with a total of " << total << endl; } return 0; }
true
74ab9ef523692f944b14fd64462f77e4ecf08497
C++
marciz1/Analyzing-the-intensity-of-road-traffic
/functions.cpp
UTF-8
5,681
2.578125
3
[ "MIT" ]
permissive
#include "functions.h" void on_trackbar_blur(int alpha_slider, void* param) { Parameters* p = (Parameters*)param; p->medianImage.copyTo(p->blurImage); alpha_slider = alpha_slider + 1; blur(p->blurImage, p->blurImage, Size(alpha_slider, alpha_slider)); //imshow("blurImage", p->blurImage); } void on_trackbar_closing(int alpha_slider, void* param) { Parameters* p = (Parameters*)param; p->blurImage.copyTo(p->closingImage); dilate(p->closingImage, p->closingImage, Mat()); for (int i = 0; i < alpha_slider; i++) { erode(p->closingImage, p->closingImage, Mat()); } //imshow("closingImage", p->closingImage); } void on_trackbar_threshold(int alpha_slider, void* param) { Parameters* p = (Parameters*)param; p->closingImage.copyTo(p->thresholdImage); threshold(p->thresholdImage, p->thresholdImage, alpha_slider, p->prog_slider_max_threshold, THRESH_BINARY); } Mat Parameters::przyblizonaMediana(Mat I, Mat& B) { Mat dst; int numberOfElemnts = I.rows * I.cols; uchar* i = I.data; uchar* b = B.data; for (int j = 0; j < numberOfElemnts; ++j) { if (i[j] > b[j]) b[j] = b[j] + 1; if (i[j] < b[j]) b[j] = b[j] - 1; } absdiff(I, B, dst); return dst; } void Line::checkCrossedLineLeft(vector<Rect> rect) { if (blockCounterLeft == blockCounterLeftMax) { blockCounterLeft = 0; blockLeft = false; } if (blockLeft == true) { blockCounterLeft++; } for (unsigned int i = 0; i < rect.size(); i++) { Point centre1(rect[i].x , rect[i].y + rect[i].height); //car left if (rect[i].area() > areaCarLeft[0] && rect[i].area() < areaCarLeft[1]) { if (centre1.x < p11.x + activationSensity && centre1.x > p11.x - activationSensity) { if (centre1.y > p11.y && centre1.y < p12.y) { if (blockLeft == false) { cout << "Car Left: " << rect[i].area() << endl; carsLeft++; blockLeft = true; } } } } //truck left if (rect[i].area() > areaTruckLeft[0] && rect[i].area() < areaTruckLeft[1]) { if (centre1.x < p11.x + activationSensity && centre1.x > p11.x - activationSensity) { if (centre1.y > p11.y && centre1.y < p12.y) { if (blockLeft == false) { cout << "Truck Left: " << rect[i].area() << endl; trucksLeft++; blockLeft = true; } } } } } } void Line::checkCrossedLineRight(vector<Rect> rect) { if (blockCounterRight == blockCounterRightMax) { blockRight = false; blockCounterRight = 0; } if (blockRight == true) { blockCounterRight++; } for (unsigned int i = 0; i < rect.size(); i++) { Point centre1(rect[i].x + rect[i].width, rect[i].y + rect[i].height); //car right if (rect[i].area() > areaCarRight[0] && rect[i].area() < areaCarRight[1]) { if (centre1.x < p31.x + activationSensity && centre1.x > p31.x - activationSensity) { if (centre1.y > p31.y && centre1.y < p32.y) { if (blockRight == false) { cout << "Car Right: " << rect[i].area() << endl; carsRight++; blockRight = true; } } } } //truck right if (rect[i].area() > areaTruckRight[0] && rect[i].area() < areaTruckRight[1]) { if (centre1.x < p31.x + activationSensity && centre1.x > p31.x - activationSensity) { if (centre1.y > p31.y && centre1.y < p32.y) { if (blockRight == false) { cout << "Truck Right: " << rect[i].area() << endl; trucksRight++; blockRight = true; } } } } } } void Line::checkCrossedLinePeople(vector<Rect> rect) { if (blockCounterPeople == blockCounterPeopleMax) { blockPeople = false; blockCounterPeople = 0; } if (blockPeople == true) { blockCounterPeople++; } for (unsigned int i = 0; i < rect.size(); i++) { Point centre1(rect[i].x + rect[i].width, rect[i].y + rect[i].height / 2); if (rect[i].area() > areaPeople[0] && rect[i].area() < areaPeople[1]) { if (centre1.x < p21.x + activationSensity && centre1.x > p21.x - activationSensity) { if (centre1.y > p21.y && centre1.y < p22.y) { if (blockPeople == false) { people++; cout << "People: " << rect[i].area() << endl; blockPeople = true; } } } } } } void Line::checkCrossedLineTrams(vector<Rect> rect) { if (blockCounterTramsLeft == blockCounterTramsLeftMax) { blockCounterTramsLeft = 0; blockTramsLeft = false; } if (blockTramsLeft == true) { blockCounterTramsLeft++; } if (blockCounterTramsRight == blockCounterTramsRightMax) { blockCounterTramsRight = 0; blockTramsRight = false; } if (blockTramsRight == true) { blockCounterTramsRight++; } for (unsigned int i = 0; i < rect.size(); i++) { Point centre1(rect[i].x, rect[i].y + rect[i].height); //trams left if (rect[i].area() > areaTramLeft[0] && rect[i].area() < areaTramLeft[1]) { if (centre1.x < p41.x + 50 && centre1.x > p42.x - 50) { if (centre1.y > p41.y && centre1.y < p42.y) { if (blockTramsLeft == false) { cout << "Trams: " << rect[i].area() << endl; trams++; blockTramsLeft = true; } } } } //trams right Point centre2(rect[i].x + rect[i].width, rect[i].y + rect[i].height); if (rect[i].area() > areaTramRight[0] && rect[i].area() < areaTramRight[1]) { if (centre2.x < p43.x + 30 && centre2.x > p44.x - 30) { if (centre2.y > p43.y && centre2.y < p44.y) { if (blockTramsRight == false) { cout << "Trams: " << rect[i].area() << endl; trams++; blockTramsRight = true; } } } } } }
true
bacef95eeff395e30ce6dad4b9566a9c53cc7ee4
C++
lsils/mockturtle
/test/networks/crossed.cpp
UTF-8
4,086
2.546875
3
[ "MIT" ]
permissive
#include <catch.hpp> #include <mockturtle/algorithms/cleanup.hpp> #include <mockturtle/networks/buffered.hpp> #include <mockturtle/networks/crossed.hpp> #include <mockturtle/networks/klut.hpp> using namespace mockturtle; TEST_CASE( "type traits", "[crossed]" ) { CHECK( !is_crossed_network_type_v<klut_network> ); CHECK( !has_create_crossing_v<klut_network> ); CHECK( !has_insert_crossing_v<klut_network> ); CHECK( !has_is_crossing_v<klut_network> ); CHECK( !has_merge_into_crossing_v<klut_network> ); CHECK( is_crossed_network_type_v<crossed_klut_network> ); CHECK( has_create_crossing_v<crossed_klut_network> ); CHECK( has_insert_crossing_v<crossed_klut_network> ); CHECK( has_is_crossing_v<crossed_klut_network> ); CHECK( is_crossed_network_type_v<buffered_crossed_klut_network> ); CHECK( !has_merge_into_crossing_v<crossed_klut_network> ); CHECK( has_merge_into_crossing_v<buffered_crossed_klut_network> ); } TEST_CASE( "insert crossings in reversed topological order, then cleanup (topo-sort)", "[crossed]" ) { crossed_klut_network crossed; auto const x1 = crossed.create_pi(); auto const x2 = crossed.create_pi(); auto const n3 = crossed.create_and( x1, x2 ); auto const n4 = crossed.create_or( x1, x2 ); auto const n5 = crossed.create_xor( x1, x2 ); crossed.create_po( n3 ); crossed.create_po( n4 ); crossed.create_po( n5 ); auto const c6 = crossed.insert_crossing( x1, x2, crossed.get_node( n4 ), crossed.get_node( n3 ) ); auto const c7 = crossed.insert_crossing( x1, x2, crossed.get_node( n5 ), crossed.get_node( n4 ) ); auto const c8 = crossed.insert_crossing( x1, x2, c7, c6 ); (void)c8; crossed = cleanup_dangling( crossed ); crossed.foreach_po( [&]( auto const& po ) { crossed.foreach_fanin_ignore_crossings( crossed.get_node( po ), [&]( auto const& f, auto i ) { if ( i == 0 ) CHECK( f == x1 ); else CHECK( f == x2 ); } ); } ); } TEST_CASE( "create crossings in topological order", "[crossed]" ) { crossed_klut_network crossed; auto const x1 = crossed.create_pi(); auto const x2 = crossed.create_pi(); auto const [c3x1, c3x2] = crossed.create_crossing( x1, x2 ); auto const [c4x1, c4x2] = crossed.create_crossing( x1, c3x2 ); auto const [c5x1, c5x2] = crossed.create_crossing( c3x1, x2 ); auto const n6 = crossed.create_and( x1, c4x2 ); auto const n7 = crossed.create_or( c4x1, c5x2 ); auto const n8 = crossed.create_xor( c5x1, x2 ); crossed.create_po( n6 ); crossed.create_po( n7 ); crossed.create_po( n8 ); crossed.foreach_po( [&]( auto const& po ) { crossed.foreach_fanin_ignore_crossings( crossed.get_node( po ), [&]( auto const& f, auto i ) { if ( i == 0 ) CHECK( f == x1 ); else CHECK( f == x2 ); } ); } ); } TEST_CASE( "transform from klut to crossed_klut", "[crossed]" ) { klut_network klut; auto const x1 = klut.create_pi(); auto const x2 = klut.create_pi(); auto const n3 = klut.create_and( x1, x2 ); auto const n4 = klut.create_or( x1, x2 ); auto const n5 = klut.create_xor( x1, x2 ); klut.create_po( n3 ); klut.create_po( n4 ); klut.create_po( n5 ); crossed_klut_network crossed = cleanup_dangling<klut_network, crossed_klut_network>( klut ); CHECK( klut.size() == crossed.size() ); } TEST_CASE( "merge buffers into a crossing cell", "[crossed]" ) { buffered_crossed_klut_network klut; auto const x1 = klut.create_pi(); auto const x2 = klut.create_pi(); auto const w1 = klut.create_buf( x1 ); auto const w2 = klut.create_buf( x2 ); auto const w3 = klut.create_buf( w1 ); auto const w4 = klut.create_buf( w2 ); auto const a1 = klut.create_and( w3, w4 ); klut.create_po( a1 ); auto const cx = klut.merge_into_crossing( klut.get_node( w1 ), klut.get_node( w2 ) ); CHECK( klut.is_crossing( cx ) ); klut.foreach_fanin( cx, [&]( auto const& f, auto i ) { if ( i == 0 ) CHECK( f == x1 ); else CHECK( f == x2 ); } ); CHECK( klut.size() == 10 ); klut = cleanup_dangling( klut ); CHECK( klut.size() == 8 ); }
true
76f785aabcf0e9a034494bfa76fc955e8edc74d9
C++
huangzsdy/my_code
/c++/stl/src/test_func_obj.cpp
UTF-8
1,185
3.46875
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <iterator> #include <algorithm> using namespace std; /* * 1.函数对象,可以达到类似静态变量的功能,m_a,每次调用add都会累加 * 2.generate_n (iter,n,op),调用n次的op(),返回值赋给iter,且iter++ * 3.lambda 表达式,[]代表传参的作用域及传参的方式,()代表参数,-> 代表返回值 */ class Sort1{ public: Sort1(int a):m_a(a){} int operator () (){ cout<<"m_a:"<<m_a<<endl; add(); return m_a; } private: void add(){m_a++;} int m_a; }; int main(int argc,char** argv){ int a[] = {1,2,3,4,5,6,7,8,9,0}; vector<int>dest(a,a+10); cout<<"generate_n 之前:"<<endl; for_each(dest.begin(),dest.end(),[](int arg){cout<<arg<<" ";}); cout<<endl; cout<<"generate_n 之后:"<<endl; //generate_n(back_inserter(dest),10,Sort1(2)); back_insert_iterator<vector<int>> b_iter (dest); //generate_n(b_iter,10,Sort1(2)); back_inserter(dest) = 199;//back_inserter是函数,返回dest的back_insert_iterator指针 for_each(dest.begin(),dest.end(),[](int arg){cout<<arg<<" ";}); return 0; }
true
8d7c877e1f59650510ec832e7793b2da96a21470
C++
jstiefel/ThorlabsTDC_ROS
/src/CommunicationFunctions.cpp
UTF-8
17,617
2.65625
3
[ "BSD-3-Clause" ]
permissive
//============================================================================ // Name : CommunicationFunctions.cpp // Author : Julian Stiefel // Version : 1.0.0 // Created on : 28.03.2018 // Copyright : BSD 3-Clause // Description : Device communication class for Thorlabs stages with // TDC001 controller. Based on Daniel Lehmann's tdc_manager // and completed/edited. //============================================================================ #include "thorlabs_tdc/CommunicationFunctions.hpp" namespace thorlabs_tdc { CommunicationFunctions::CommunicationFunctions() { ftStatus = 0; keyHandle = NULL; written = 0; homingCheck = 0; stage_type = 0; } CommunicationFunctions::~CommunicationFunctions() { } void CommunicationFunctions::set_stage_type(int stageType){ //global stage type variable from launch file is set //1: linear, 2: rotational stage_type = stageType; } float CommunicationFunctions::countsTomm(int counts){ //see calculations, called mm, but also means deg in case 2 float mm; switch(stage_type){ case 1: mm = counts/34304.; break; case 2: //actually degree mm = (360/589824.) * counts; break; } return mm; } int CommunicationFunctions::mmToCounts(float mm){ //see calculations int counts; switch(stage_type){ case 1: counts = 34304 * mm; break; case 2: //actually degree counts = (589824/360.) * mm; break; } return counts; } bool CommunicationFunctions::initializeKeyHandle(std::string serialnumber){ //INITIALIZATION// /* * This function initializes the TDC motor controller and finds its corresponding keyhandle. * * @param serialnumber Serial number of TDC controller * @return A boolean indicating the success of the method. */ keyHandle = NULL; // To open the device the Vendor and Product ID must set correct ftStatus = FT_SetVIDPID(0x403,0xfaf0); if(ftStatus != FT_OK) { ROS_ERROR("FT_SetVIDPID failed \n"); return false; } sleep(2); //2s sleep is necessary here, otherwise device will not be opened DWORD iNumDevs; ftStatus = FT_CreateDeviceInfoList(&iNumDevs); if (FT_OK != ftStatus) { ROS_INFO_STREAM("Error: FT_CreateDeviceInfoList:" << (int)ftStatus); } ROS_INFO_STREAM("Devices: " << iNumDevs); /* * Now it is time to open the device. If it does not initialize within 20 * tries, then there is likely a connection error */ const char* tmp = serialnumber.c_str(); int numAttempts=0; while (keyHandle ==0){ ftStatus = FT_OpenEx(const_cast<char*>(tmp),FT_OPEN_BY_SERIAL_NUMBER, &keyHandle); if (numAttempts++>20){ ROS_ERROR("Device Could Not Be Opened \n"); return false; } } printf("Device Opened \n"); /* * Once the device is connected, we must set the baudrate and timeout according to the * specifications provided by the manufacturer in the APT Communication Protocol */ // Set baud rate to 115200 ftStatus = FT_SetBaudRate(keyHandle,115200); if(ftStatus != FT_OK) { ROS_ERROR("FT_SetBaudRate failed \n"); return false; } // // Set USB request transfer size // DWORD InTransferSize = 64; // ftStatus = FT_SetUSBParameters(keyHandle, InTransferSize, 0); // if(ftStatus != FT_OK){ // ROS_ERROR("FT_SetUSBParameters failed \n"); // return false; // } // // // Set latency timer // UCHAR LatencyTimer = 10; // ftStatus = FT_SetLatencyTimer(keyHandle, LatencyTimer); // if(ftStatus != FT_OK){ // ROS_ERROR("FT_SetUSBParameters failed \n"); // return false; // } // 8 data bits, 1 stop bit, no parity ftStatus = FT_SetDataCharacteristics(keyHandle, FT_BITS_8, FT_STOP_BITS_1, FT_PARITY_NONE); if(ftStatus != FT_OK) { ROS_ERROR("FT_SetDataCharacteristics failed \n"); return false; } // Pre purge dwell 50ms. usleep(50); // Purge the device. ftStatus = FT_Purge(keyHandle, FT_PURGE_RX | FT_PURGE_TX); if(ftStatus != FT_OK) { ROS_ERROR("FT_Purge failed \n"); return false; } // Post purge dwell 50ms. usleep(50); // Reset device. ftStatus = FT_ResetDevice(keyHandle); if(ftStatus != FT_OK) { ROS_ERROR("FT_ResetDevice failed \n"); return false; } // Set flow control to RTS/CTS. ftStatus = FT_SetFlowControl(keyHandle, FT_FLOW_RTS_CTS, 0, 0); if(ftStatus != FT_OK) { ROS_ERROR("FT_SetFlowControl failed \n"); return false; } // Set RTS. ftStatus = FT_SetRts(keyHandle); if(ftStatus != FT_OK) { ROS_ERROR("FT_SetRts failed \n"); return false; } return true; } bool CommunicationFunctions::initializeController(){ /* * This function initializes the motor controller. Additionally, the minimal/maximal velocity * and acceleration of the movements are set. * Optional: MGMSG_HW_START_UPDATEMSGS can be set here to fill the queue of TDC with update * messages. We do not rely on complete data and just need actual position and velocity. * Therefore, we will send a separate request each time we need the data and there is no * need to search the queue for the most recent data. * @return A boolean indicating whether or not the controller is initialized correctly. */ // Start Update Message uint8_t startUpdateMsgs[6] = {0x11,0x0,0xa,0x0,0x50,0x1}; // Set command to device ftStatus = FT_Write(keyHandle, startUpdateMsgs, (DWORD)6, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted. StartUpdateMsg"); return false; } // Set min./max. velocity and acceleration // max velocity of hardware is 2.4mm/s float min_velocity_mm = 0; // [mm/s] float max_velocity_mm = 90; // [mm/s] //default: 45 float acceleration_mm = 0.4; // [mm/s^2] //default: 0.2 int32_t min_velocity_count = (int32_t)mmToCounts(min_velocity_mm); int32_t max_velocity_count = (int32_t)mmToCounts(max_velocity_mm); int32_t acc_count = (int32_t)mmToCounts(acceleration_mm); uint8_t max_vel_buf[4] = {0}; uint8_t min_vel_buf[4] = {0}; uint8_t acc_buf[4] = {0}; // Change from integer to 8-bit sequences int2hexLE(max_velocity_count,max_vel_buf); int2hexLE(min_velocity_count,min_vel_buf); int2hexLE(acc_count,acc_buf); uint8_t setVelbuf[20] = {0x13,0x04,0x0e,0x00,0x81,0x01,0x01,0x00,min_vel_buf[0],min_vel_buf[1],min_vel_buf[2],min_vel_buf[3],acc_buf[0],acc_buf[1],acc_buf[2],acc_buf[3],max_vel_buf[0],max_vel_buf[1],max_vel_buf[2],max_vel_buf[3]}; // Set command to device ftStatus = FT_Write(keyHandle, setVelbuf, (DWORD)20, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted. Set min./max. velocity and acceleration \n"); return false; } // Set homing parameters float home_velocity_mm = 15; // [mm/s] int32_t home_velocity_count = (int32_t)mmToCounts(home_velocity_mm); uint8_t home_vel_buf[4] = {0}; int2hexLE(home_velocity_count,home_vel_buf); uint8_t setHomebuf[20] = {0x40,0x04,0x0e,0x00,0x81,0x01,0x01,0x00,0x00,0x00,0x00,0x00,home_vel_buf[0],home_vel_buf[1],home_vel_buf[2],home_vel_buf[3],0x00,0x00,0x00,0x00}; // Set command to device ftStatus = FT_Write(keyHandle, setHomebuf, (DWORD)20, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted. Set homing parameters \n"); return false; } ROS_INFO("Initializing Controller completed \n"); return true; } bool CommunicationFunctions::int2hexLE(int32_t value_int, uint8_t* value_hexLE){ /* * This function takes in a 32-bit integer value_int, split it in four 8-bit sequences * and saves the result in the Little-Endian format in the array value_hexLE. * @param value_int: 32-bit integer values * @param value_hexLE: A pointer to an 8-bit array, where the integer value will be saved in the Little-Endian format */ value_hexLE[0] = value_int; value_hexLE[1] = value_int>>8; value_hexLE[2] = value_int>>16; value_hexLE[3] = value_int>>24; return true; } bool CommunicationFunctions::manualPurge(){ // Pre purge dwell 50ms. usleep(50); // Purge the device. ftStatus = FT_Purge(keyHandle, FT_PURGE_RX | FT_PURGE_TX); if(ftStatus != FT_OK) { ROS_ERROR("FT_Purge failed \n"); return false; } // Post purge dwell 50ms. usleep(50); return true; } bool CommunicationFunctions::getStatus(){ DWORD receive_queueRx; DWORD transmit_queueTx; DWORD event_status; ftStatus = FT_GetStatus(keyHandle, &receive_queueRx, &transmit_queueTx, &event_status); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Request status \n"); return false; } ROS_INFO_STREAM("Receive queue: " << receive_queueRx << " Transmit queue: " << transmit_queueTx << " Event status: " << event_status); return true; } bool CommunicationFunctions::getLatency(){ unsigned char latency; ftStatus = FT_GetLatencyTimer(keyHandle, &latency); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Request latency \n"); return false; } ROS_INFO_STREAM("Latency: " << (unsigned)latency); return true; } bool CommunicationFunctions::read_tdc(float* position, float* velocity){ /* * This function reads out the TDC motor controller and saves the actual position * and velocity in encoder counts. * Optional: If we would use MGMSG_HW_START_UPDATEMSGS, we would need to send a * "server alive" message in every call (MGMSG_MOT_ACK_DCSTATUSUPDATE) to confirm * that the host computer is still listening, otherwise, the motor controller * would stop sending update messages after 50 messages. * * Velocity is faulty. Probably error from Thorlabs. * @param position A pointer to a variable, where the position will be stored. * @param velocity A pointer to a variable, where the velocity will be stored. * @return A boolean indicating whether or not the read out was successful. */ /** Server alive message buffer */ uint8_t serverAlive[6] = {0x92,0x04,0x0,0x0,0x50,0x01}; uint8_t *RxBuffer = new uint8_t[256]; DWORD RxBytes = 0; DWORD BytesReceived = 0; /* Note about regular messages: * If we turn regular messages on and we read all data which is available in * queue of TDC001 in the RxBuffer, this could exceed the 256 bytes * length of RxBuffer, because not only the recent data is in queue. It is * then not too easy to get the right data (most recent and right message). */ // Set command to device that the host computer is still listening ftStatus = FT_Write(keyHandle, serverAlive, (DWORD)6, &written); if(ftStatus != FT_OK){ //*****only for DEBUGGING***** //ROS_ERROR("Command could not be transmitted: Server alive"); return false; } // Get number of bytes in queue of TDC001 FT_GetQueueStatus(keyHandle,&RxBytes); // Check if there are bytes in queue before reading them, otherwise do // not read anything in, frequency of new data in TDC queue is low if(RxBytes>0){ ftStatus=FT_Read(keyHandle,RxBuffer,RxBytes,&BytesReceived); if(ftStatus != FT_OK){ ROS_ERROR("Read device failed! \n"); return false; } } /* * Check if enough bytes are received, i.e. if signal is right. * If not 20 bytes are received, there was either no new data available. * (BytesReceived initialized as 0) or data received was wrong. */ if(!(BytesReceived == 20)){ // ROS_INFO("No new status update in queue \n"); return false; } // // Output number of bytes received // ROS_INFO_STREAM("Bytes received: " << BytesReceived); int32_t position_counts; uint16_t velocity_counts; getPosVel(&position_counts,&velocity_counts,RxBuffer); //convert to mm/degree: *position = countsTomm((int)position_counts); *velocity = countsTomm((int)velocity_counts); // // Output whole RxBuffer: // ROS_INFO_STREAM("RxBuffer:"); // for (int i=0; i<int(RxBytes); i++){ // ROS_INFO_STREAM(unsigned(RxBuffer[i]) << "\n"); // } // Delete receive buffer delete[] RxBuffer; RxBuffer = NULL; return true; } bool CommunicationFunctions::getPosVel(int32_t* position, uint16_t* velocity, uint8_t* RxBuffer){ /* * This function saves the information of position and velocity from the receive buffer (Rx) * in the specified position and velocity variables. The function only reads in update messages. * * Used message is 0x0491 * @param position A pointer to a variable, where the position in a 32-bit integer is stored. * @param velocity A pointer to a variable, where the velocity in a unsigned 16-bit integer is * stored. * @param RxBuffer A pointer to RxBuffer, where the information of position and velocity is stored * in the Little-Endian format. */ // Check if received message is MGMSG_MOT_GET_DCSTATUSUPDATE and check if we have a data // packet length of 14 bytes if((RxBuffer[0] == 0x91) && (RxBuffer[2] == 0xE)){ *position = (RxBuffer[8])|(RxBuffer[9]<<8)|(RxBuffer[10]<<16)|(RxBuffer[11]<<24); *velocity = (RxBuffer[12])|(RxBuffer[13]<<8); } return true; } bool CommunicationFunctions::stopMot(){ uint8_t stop_msgs[6] = {0x65,0x04,0x01,0x01,0x50,0x01}; ftStatus = FT_Write(keyHandle, stop_msgs, (DWORD)6, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Motor stop \n"); return false; } return true; } bool CommunicationFunctions::setPosAbs(float setpoint){ /* * This function moves the stage to the specified absolute position in encoder counts. * @param setpoint float which has to be converted to 32-bit integer value to move in encoder counts * @return A boolean indicating whether or not the command is sent successfully. */ //target position in mm or degree is converted to int (counts) if(setpoint >= -33 && setpoint <= 49 && homingCheck==1){ uint8_t absPos[4]={0}; int2hexLE(mmToCounts(setpoint),absPos); uint8_t AbsPosBuf[12]={0x53,0x04,0x06,0x00,0x81,0x01,0x01,0x00,absPos[0],absPos[1],absPos[2],absPos[3]}; ftStatus = FT_Write(keyHandle, AbsPosBuf, (DWORD)12, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Move absolute position \n"); return false; } } else{ ROS_ERROR("Setpoint out of range or not homed"); } return true; } bool CommunicationFunctions::setPosRel(float setpoint){ /* * This function moves the stage to the specified relative position in encoder counts. * @param setpoint 32-bit integer value to move in encoder counts * @return A boolean indicating whether or not the command is sent successfully. */ //target position in mm/degree converted to int (counts) uint8_t relPos[4]={0}; int2hexLE(mmToCounts(setpoint),relPos); uint8_t RelPosBuf[12]={0x48,0x04,0x06,0x00,0x81,0x01,0x01,0x00,relPos[0],relPos[1],relPos[2],relPos[3]}; ftStatus = FT_Write(keyHandle, RelPosBuf, (DWORD)12, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Move relative position \n"); return false; } return true; } bool CommunicationFunctions::setHoming(int stage_type){ /* * This function homes the stage, which depends on the stage type. MTS50 linear * stages are homed by using limit switches. CR1 rotational stages are homed by * moving the stage manually to the desired position and set the position counter * of the motor controller to zero. The stage type is specified in the launch file. * 1 is linear, 2 is rotational. * This function checks if homing was completed. * @return A boolean indicating whether or not the command is sent successfully. */ uint8_t *RxBuffer = new uint8_t[256]; DWORD RxBytes = 0; DWORD BytesReceived = 0; // Stage type 1 uint8_t bufHome[6]={0x43,0x04,0x1,0x0,0x50,0x1}; // Stage type 2 uint8_t bufHomePos[12]={0x09,0x04,0x06,0x81,0x01,0x01,0x00,0x0,0x0,0x0,0x0}; switch(stage_type){ case 1: //move a short relative distance, because homing does not work if already at homing point setPosRel(0.2); sleep(1); ftStatus = FT_Write(keyHandle, bufHome, (DWORD)6, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Thorlabs Homing \n"); return false; //stops execution of function immediately and returns value } else { bool success = 0; while(success==0){ //wait for homing completed, this works only if homing was executed and not if limit is already reached: FT_GetQueueStatus(keyHandle,&RxBytes); // Check if there are bytes in queue before reading them, otherwise do // not read anything in if(RxBytes>0){ ftStatus=FT_Read(keyHandle,RxBuffer,RxBytes,&BytesReceived); if(ftStatus != FT_OK){ ROS_ERROR("Read device failed! \n"); return false; } } if((RxBuffer[0] == 0x44) && (RxBuffer[1] == 0x04)){ ROS_INFO("Thorlabs Homing reached"); success=1; } } } ROS_INFO("Thorlabs Homing completed \n"); break; case 2: //zero is set at the current position ftStatus = FT_Write(keyHandle, bufHomePos, (DWORD)12, &written); if(ftStatus != FT_OK){ ROS_ERROR("Command could not be transmitted: Homing \n"); return false; } else { ROS_INFO("Thorlabs revolute homing completed \n"); } break; } homingCheck = 1; //homing was completed check var. return true; } bool CommunicationFunctions::closeDevice(){ FT_Close(keyHandle); if (ftStatus == FT_OK){ ROS_INFO("Device successfully closed. \n"); return true; } else { return false; } } } /* namespace */
true
4fcf56bd1b81e32b2015e055faa861988ef72588
C++
FreeLike76/kpi_pa_3
/Ant.cpp
UTF-8
380
2.546875
3
[]
no_license
#include "Ant.h" void Ant::calcAntPath(Graph& graph) { _pathLen = 0; for (int i = 0; i < pathHist.size()-1; i++) { _pathLen += graph.adj[pathHist[i]][pathHist[i + 1]]; } _pathLen += graph.adj[pathHist.back()][pathHist.front()]; } int Ant::getPathLen() { return _pathLen; } void Ant::clearMemory() { _pathLen = 0; pathHist.clear(); } Ant::~Ant() { clearMemory(); }
true
5ab8cddc64ee40805f8ce3988baf1f2a10dc1074
C++
smhemel/Codeforces-Online-Judge
/Codeforces Round #206 (Div. 2) - A. Vasya and Digital Root/Codeforces Round #206 (Div. 2) - A. Vasya and Digital Root/main.cpp
UTF-8
438
2.640625
3
[]
no_license
// // main.cpp // Codeforces Round #206 (Div. 2) - A. Vasya and Digital Root // // Created by S M HEMEL on 3/12/17. // Copyright © 2017 Eastern University. All rights reserved. // #include <iostream> using namespace std; int main() { int k, d; cin >> k >> d; if (d == 0 && k > 1) cout << "No solution"; else { cout << d; for(int i=0; i<k-1; i++) cout << 0; } return 0; }
true
e7d34a8629e2b92255e2cce7df1440fa16c5c90d
C++
Dimbelio/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
/Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter21TryThis6.cpp
WINDOWS-1252
1,554
3.28125
3
[ "MIT" ]
permissive
/* TITLE Iostream Iterators Chapter21TryThis6.cpp "Bjarne Stroustrup "C++ Programming: Principles and Practice."" COMMENT Objective: Get the program from 21.7.2 to run and test with small files of few hundred words. Try (the not recommended) guessing of the input size, potentially leading to buffer overflow. Input: - Output: - Author: Chris B. Kirov Date: 26. 02. 2017 */ #include <iostream> #include <fstream> #include <iterator> #include <string> #include <vector> #include <numeric> #include <algorithm> //-------------------------------------------------------------------- int main() { try { std::string from("Chapter21TryThis6From.txt"), to("Chapter21TryThis6To.txt"); std::ifstream ifs(from.c_str()); std::ofstream ofs(to.c_str()); if (!ifs || !ofs) { throw std::runtime_error("Can't open input/output file!\n"); } std::istream_iterator<std::string> ii(ifs); std::istream_iterator<std::string> eos; // default constructor as end-of-stream iterator std::ostream_iterator<std::string> oo(ofs, "\n"); // use newline as delimiter to separate each word /* std::vector<std::string> b(50); // buffer overflow as size 50 and words > 100 std::copy(ii, eos, b.begin()); */ std::vector<std::string> b(ii, eos); // initialize vector from file using iterators std::sort(b.begin(), b.end()); std::copy(b.begin(), b.end(), oo); // write vectir to output file using iterators } catch(std::exception& e) { std::cerr << e.what(); } getchar(); }
true
f617e83760efd7083eb5f85414eebdd8d9a9d3d7
C++
l19g2004/Computer-Vision
/Sheet01/src/sheet01.cpp
UTF-8
17,076
2.84375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <opencv2/opencv.hpp> #include <math.h> using namespace std; using namespace cv; int main(int argc, char** argv) { // ==================== Load image ========================================= // Read the image file - bonn.png is of type CV_8UC3 const Mat bonn = imread(argv[1], IMREAD_COLOR); // Create gray version of bonn.png Mat bonn_gray; cvtColor(bonn, bonn_gray, CV_BGR2GRAY); // ========================================================================= // ==================== Solution of task 1 ================================= // ========================================================================= cout << "Task 1:" << endl; //====(a)==== draw random rectangles ==== // Create a copy of the input image to draw the rectangles into Mat img_task1; bonn_gray.copyTo(img_task1); // Create a random number generator RNG rng(getTickCount()); Rect rects[100]; for (auto& r : rects) { // Random coordinates of the rectangle const int x1 = rng.uniform(0, bonn_gray.cols); const int x2 = rng.uniform(0, bonn_gray.cols); const int y1 = rng.uniform(0, bonn_gray.rows); const int y2 = rng.uniform(0, bonn_gray.rows); // set points to the top-left corner r = Rect(Point(x1, y1), Point(x2,y2)); // Draw the rectangle into the image "img_task1" rectangle(img_task1, r.tl(), r.br(), Scalar(255,255,255)); } // Display the image "img_task1" with the rectangles namedWindow("Task1: (a) draw random rectangles", WINDOW_AUTOSIZE); imshow("Task1: (a) draw random rectangles", img_task1); //====(b)==== summing up method ==== // Variables for time measurements int64_t tick, tock; double sumOfPixels; double sumOfPixelsPerRect; // Measure the time tick = getTickCount(); // Repeat 10 times for (size_t n = 0; n < 10; ++n) { sumOfPixels = 0.0; sumOfPixelsPerRect = 0.0; for (auto& r : rects) { for (int y = r.y; y < r.y + r.height; ++y) { for (int x = r.x; x < r.x+r.width; ++x) { //TODO: Sum up all pixels at "bonn_gray.at<uchar>(y,x)" inside the rectangle and store it in "sumOfPixels" // ... sumOfPixels += bonn_gray.at<uchar>(y,x); sumOfPixelsPerRect++; } } } } // normalize sumOfPixels /= sumOfPixelsPerRect; tock = getTickCount(); cout << "Summing up each pixel gives " << sumOfPixels << " computed in " << (tock-tick)/getTickFrequency() << " seconds." << endl; // //====(c)==== integral image method - using OpenCV function "integral" ==== // Measure the time tick = getTickCount(); Mat rectIntegral; integral(bonn_gray, rectIntegral, bonn_gray.depth()); double meanIntegrals; for (size_t n = 0; n < 10; ++n) { meanIntegrals = 0.0; for (auto& r : rects) { //cout << "Point " << r.tl() << " - " << r.br() << " : " << r.width << " , "<< r.height << endl; // . . // . . // .....D-------C // | | // .....B-------A meanIntegrals += ((double)( rectIntegral.at<int>(r.br()) // A - rectIntegral.at<int>(Point(r.tl().x, r.tl().y + r.height)) // B - rectIntegral.at<int>(Point(r.tl().x + r.width, r.tl().y)) // C + rectIntegral.at<int>(r.tl()) // D )/(double)(r.height*r.width)); } } // normalize meanIntegrals /= (double)(sizeof(rects)/(double)sizeof(*rects)); tock = getTickCount(); cout << "computing an integral image gives " << meanIntegrals << " computed in " << (tock-tick)/getTickFrequency() << " seconds." << endl; //====(d)==== integral image method - custom implementation==== //TODO: implement your solution here // ... tick = getTickCount(); //initalize a new matrix for computing the integral matrix //Mat integralImage = Mat::zeros(bonn_gray.size().height, bonn_gray.size().width, bonn_gray.type()); Mat integralImage; integralImage = Mat::zeros(bonn_gray.rows+1, bonn_gray.cols+1, 4); //iterate through the original gray image for (int i=0; i < integralImage.rows; ++i) { for (int j=0; j < integralImage.cols; ++j) { if (i != 0 && j != 0) { integralImage.at<int>(i,j) = bonn_gray.at<uchar>(i - 1, j - 1); } if (i == 0) { integralImage.at<int>(i,j) = 0; } else { integralImage.at<int>(i,j) += integralImage.at<int>(i-1, j); } if (j == 0) { integralImage.at<int>(i,j) = 0; } else { integralImage.at<int>(i,j) += integralImage.at<int>(i , j-1); } if (i != 0 && j != 0) { integralImage.at<int>(i,j) -= integralImage.at<int>(i-1, j-1); } } } //The same like task c) //double meanIntegrals; for (size_t n = 0; n < 10; ++n) { meanIntegrals = 0.0; for (auto& r : rects) { //cout << "Point " << r.tl() << " - " << r.br() << " : " << r.width << " , "<< r.height << endl; // . . // . . // .....D-------C // | | // .....B-------A meanIntegrals += ((double)( integralImage.at<int>(r.br()) // A - integralImage.at<int>(Point(r.tl().x, r.tl().y + r.height)) // B - integralImage.at<int>(Point(r.tl().x + r.width, r.tl().y)) // C + integralImage.at<int>(r.tl()) // D )/(double)(r.height*r.width)); } } // normalize meanIntegrals /= (double)(sizeof(rects)/(double)sizeof(*rects)); tock = getTickCount(); cout << "computing an integral image gives " << meanIntegrals << " computed in " << (tock-tick)/getTickFrequency() << " seconds." << endl; waitKey(0); // waits until the user presses a button and then continues with task 2 -> uncomment this destroyAllWindows(); // closes all open windows -> uncomment this // ========================================================================= // ==================== Solution of task 2 ================================= // ========================================================================= cout << "Task 2:" << endl; //====(a)==== Histogram equalization - using opencv "equalizeHist" ==== Mat ocvHistEqualization; equalizeHist(bonn_gray, ocvHistEqualization); //====(b)==== Histogram equalization - custom implementation ==== Mat myHistEqualization(bonn_gray.size(), bonn_gray.type()); // Count the frequency of intensities Vec<double,256> hist(0.0); for (int y=0; y < bonn_gray.rows; ++y) { for (int x=0; x < bonn_gray.cols; ++x) { ++hist[bonn_gray.at<uchar>(y,x)]; } } // Normalize vector of new intensity values to sum up to a sum of 255 hist *= 255. / sum(hist)[0]; // Compute integral histogram - representing the new intensity values for (size_t i=1; i < 256; ++i) { hist[i] += hist[i-1]; } // Fill the matrix "myHistEqualization" -> replace old intensity values with new intensities taken from the integral histogram for (int y=0; y < bonn_gray.rows; ++y) { for (int x=0; x < bonn_gray.cols; ++x) { myHistEqualization.at<uchar>(y,x) = hist[bonn_gray.at<uchar>(y,x)]; } } // Show the results of (a) and (b) imshow("original", bonn_gray); namedWindow("Task2: (a) with equalizeHist", WINDOW_AUTOSIZE); imshow("Task2: (a) with equalizeHist", ocvHistEqualization); namedWindow("Task2: (b) without equalizeHist", WINDOW_AUTOSIZE); imshow("Task2: (b) without equalizeHist", ocvHistEqualization); //====(c)==== Difference between openCV implementation and custom implementation ==== // Compute absolute differences between pixel intensities of (a) and (b) using "absdiff" Mat diff; absdiff(myHistEqualization, ocvHistEqualization, diff); double minVal, maxVal; minMaxLoc(diff, &minVal, &maxVal); cout << "maximum pixel error: " << maxVal << endl; waitKey(0); destroyAllWindows(); // ========================================================================= // ==================== Solution of task 4 ================================= // ========================================================================= cout << "Task 4:" << endl; Mat img_gb; Mat img_f2D; Mat img_sepF2D; const double sigma = 2. * sqrt(2.); // ====(a)==== 2D Filtering - using opencv "GaussianBlur()" ==== tick = getTickCount(); GaussianBlur(bonn_gray, img_gb, Size(0,0), sigma); tock = getTickCount(); cout << "OpenCV GaussianBlur() method takes " << (tock-tick)/getTickFrequency() << " seconds." << endl; // ====(b)==== 2D Filtering - using opencv "filter2D()" ==== // Compute gaussian kernel manually const int k_width = 3.5 * sigma; tick = getTickCount(); Matx<float, 2*k_width+1, 2*k_width+1> kernel2D; for (int y = 0; y < kernel2D.rows; ++y) { const int dy = abs(k_width - y); for (int x = 0; x < kernel2D.cols; ++x) { const int dx = abs(k_width - x); // Fill kernel2D matrix with values of a gaussian kernel2D(y,x) = (1/(2*M_PI*sigma*sigma))*exp(-((dx*dx+dy*dy)/(2*sigma*sigma))); } } //cout << "kernel2D: "<< "("<< kernel2D.rows << ", " << kernel2D.cols <<")"<< kernel2D << endl; kernel2D *= 1. / sum(kernel2D)[0]; // TODO: implement your solution here - use "filter2D" filter2D(bonn_gray, img_f2D, bonn_gray.depth(), kernel2D); tock = getTickCount(); cout << "OpenCV filter2D() method takes " << (tock-tick)/getTickFrequency() << " seconds." << endl; // ====(c)==== 2D Filtering - using opencv "sepFilter2D()" ==== tick = getTickCount(); // TODO: implement your solution here Matx<float, 2*k_width+1, 1>kernelX = kernel2D.col(0); Matx<float, 1, 2*k_width+1>kernelY = kernel2D.row(0); sepFilter2D(bonn_gray, img_sepF2D, bonn_gray.depth(), kernelX.t(), kernelY.t()); tock = getTickCount(); cout << "OpenCV sepFilter2D() method takes " << (tock-tick)/getTickFrequency() << " seconds." << endl; // Show result images imshow("Task4: grayimage", bonn_gray); imshow("Task4: (a) GaussianBlur", img_gb); imshow("Task4: (b) filter2D", img_f2D); imshow("Task4: (c) sepFilter2D", img_sepF2D); // compare blurring methods // Compute absolute differences between pixel intensities of (a), (b) and (c) using "absdiff" Mat diff1; Mat diff2; Mat diff3; absdiff(img_gb, img_f2D, diff1); absdiff(img_gb, img_sepF2D, diff2); absdiff(img_f2D, img_sepF2D, diff3); // Find the maximum pixel error using "minMaxLoc" double minVal2, maxVal2; minMaxLoc(diff1, &minVal2, &maxVal2); cout << "maximum pixel error (img_gb vs. img_f2D): " << maxVal2 << endl; minMaxLoc(diff2, &minVal2, &maxVal2); cout << "maximum pixel error (img_gb vs. img_sepF2D): " << maxVal2 << endl; minMaxLoc(diff3, &minVal2, &maxVal2); cout << "maximum pixel error (img_f2D vs. img_sepF2D): " << maxVal2 << endl; waitKey(0); destroyAllWindows(); // ========================================================================= // ==================== Solution of task 6 ================================= // ========================================================================= cout << "Task 6:" << endl; // ====(a)================================================================== // twice with a Gaussian kernel with σ = 2 Mat twiceGaussianKernel; GaussianBlur(bonn_gray, twiceGaussianKernel, Size(0,0), 2); GaussianBlur(twiceGaussianKernel, twiceGaussianKernel, Size(0,0), 2); // ====(b)================================================================== // once with a Gaussian kernel with σ = 2*sqrt(2) Mat onceGaussianKernel; GaussianBlur(bonn_gray, onceGaussianKernel, Size(0,0), (2*sqrt(2))); //compute the absolute pixel-wise difference between the // results, and print the maximum pixel error. Mat diff6; absdiff(twiceGaussianKernel, onceGaussianKernel, diff6); double minVal6, maxVal6; minMaxLoc(diff6, &minVal6, &maxVal6); cout << "maximum pixel error: " << maxVal6 << endl; // Show result images namedWindow("Task6: (a) twiceGaussian", WINDOW_AUTOSIZE); imshow("Task6: (a) twiceGaussian", twiceGaussianKernel); namedWindow("Task6: (b) onceGaussian", WINDOW_AUTOSIZE); imshow("Task6: (b) onceGaussian", onceGaussianKernel); waitKey(0); destroyAllWindows(); // ========================================================================= // ==================== Solution of task 7 ================================= // ========================================================================= cout << "Task 7:" << endl; // Create an image with salt and pepper noise Mat bonn_salt_pepper(bonn_gray.size(), bonn_gray.type()); randu(bonn_salt_pepper, 0, 100); // Generates an array of random numbers for (int y = 0; y < bonn_gray.rows; ++y) { for (int x=0; x < bonn_gray.cols; ++x) { uchar& pix = bonn_salt_pepper.at<uchar>(y,x); if (pix < 15) { // Set set pixel "pix" to black bonn_salt_pepper.at<uchar>(y,x) = 0; }else if (pix >= 85) { // Set set pixel "pix" to white bonn_salt_pepper.at<uchar>(y,x) = 255; }else { // Set set pixel "pix" to its corresponding intensity value in bonn_gray bonn_salt_pepper.at<uchar>(y,x) = bonn_gray.at<uchar>(y,x); } } } imshow("Task7: bonn.png with salt and pepper", bonn_salt_pepper); // ====(a)================================================================== // Gaussian kernel Mat imageGaussianFilter; GaussianBlur(bonn_salt_pepper, imageGaussianFilter, Size(0,0), 2.2); // ====(b)================================================================== // Median filter medianBlur Mat imageMedianBlurFilter; medianBlur(bonn_salt_pepper, imageMedianBlurFilter, 5); // ====(c)================================================================== // Bilateral filter Mat imageBilateralFilter; bilateralFilter(bonn_salt_pepper, imageBilateralFilter, 30, 250, 250); imshow("Task7: Gaussian kernel", imageGaussianFilter); imshow("Task7: Median filter", imageMedianBlurFilter); imshow("Task7: Bilateral", imageBilateralFilter); waitKey(0); destroyAllWindows(); // ========================================================================= // ==================== Solution of task 8 ================================= // ========================================================================= cout << "Task 8:" << endl; // Declare Kernels Mat kernel1 = (Mat_<float>(3,3) << 0.0113, 0.0838, 0.0113, 0.0838, 0.6193, 0.0838, 0.0113, 0.0838, 0.0113); Mat kernel2 = (Mat_<float>(3,3) << -0.8984, 0.1472, 1.1410, -1.9075, 0.1566, 2.1359, -0.8659, 0.0573, 1.0337); // ====(a)================================================================== Mat imagefilter2DKernel1; Mat imagefilter2DKernel2; filter2D(bonn_gray, imagefilter2DKernel1, bonn_gray.depth() , kernel1); filter2D(bonn_gray, imagefilter2DKernel2, bonn_gray.depth() , kernel2); imshow("Task8: filter2D kernel 1", imagefilter2DKernel1); imshow("Task8: filter2D kernel 2", imagefilter2DKernel2); // ====(b)================================================================== Mat imageSVDKernel1, w1, u1, vt1; Mat imageSVDKernel2; bonn_gray.convertTo(imageSVDKernel1, CV_32F, 1.0/255); SVD::compute(imageSVDKernel1, w1, u1, vt1); //Here is an error but we do not know why //sepFilter2D(bonn_gray, imageSVDKernel1, bonn_gray.depth(), u1, vt1); bonn_gray.copyTo(imageSVDKernel1); bonn_gray.copyTo(imageSVDKernel2); imshow("Task8: SVD kernel 1", imageSVDKernel1); imshow("Task8: SVD kernel 2", imageSVDKernel2); // ====(c)================================================================== // compute the absolute pixel-wise difference between the // results, and print the maximum pixel error. Mat diff8; double minVal8, maxVal8; absdiff(imagefilter2DKernel1, imageSVDKernel1, diff8); minMaxLoc(diff8, &minVal8, &maxVal8); cout << "maximum pixel error (kernel 1): " << maxVal8 << endl; absdiff(imagefilter2DKernel2, imageSVDKernel2, diff8); minMaxLoc(diff8, &minVal8, &maxVal8); cout << "maximum pixel error (kernel 2): " << maxVal8 << endl; waitKey(0); cout << "Program finished successfully" << endl; destroyAllWindows(); return 0; }
true
85abe58550750b27f8de18b50002d8919954fd35
C++
nazgob/sexp_cpp
/src/Func.hpp
UTF-8
878
2.578125
3
[ "MIT" ]
permissive
#ifndef ADD_FUNC_H #define ADD_FUNC_H #include "Utils.hpp" #include "Procedure.hpp" #include "ValExp.hpp" #include "EmptyListExp.hpp" #include <string> #include <stdexcept> #include <boost/lexical_cast.hpp> namespace sexp_cpp { class Context; class Func : public Exp { public: Func(pProc add) : mProc(add), mList(EmptyListExp::Create()) {} virtual ~Func() {} static pFunc Create(pProc proc) {return pFunc(new Func(proc));} virtual pExp Evaluate(Context& context) const { return mProc->Apply(mList, context); } virtual std::string WhoAmI() const {return "Func";} virtual std::string Write() const { return "#<procedure>"; } void SetList(pExp list) {mList = list;} protected: pProc mProc; pExp mList; }; } // sexp_cpp #endif // ADD_FUNC_H
true
8a8a219399d625e61d2d341aa63ea35fe8d3ee0b
C++
stuckat1/CPP_Design_Patterns_and_Derivatives_Pricing
/ch04/Ex4.1_new_performance/Ex4.1_new_performance/Main.cpp
UTF-8
397
3.28125
3
[]
no_license
#include <iostream> #include <time.h> #include <cmath> using namespace std; int main() { clock_t t_start = clock(); double* ptr; for (int i = 1; i < 8; i++) { int k = (int)pow(10, i); for (int j = 0; j < 10000; j++) { ptr = new double[k]; delete[] ptr; } clock_t t_delta = clock() - t_start; cout << k << " doubles took " << t_delta << " clock ticks" << endl; } }
true
57d8484b0fc3bbbd128c68e2388ee0666fb74c23
C++
Bartlomiej-Kochutek/symulator-zycia-w-oceanie
/src/K_pozostale.h
WINDOWS-1250
14,821
2.96875
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <fstream> #include <math.h> #include <limits> #include <vector> #include <iterator> #include <stdlib.h> #include <ctime> #include <thread> #include <SFML/Graphics.hpp> //Funkcja pobierajca od uytkownika liczb z zadanego przedziau domknitego unsigned int pobierz_unsigned(unsigned int min, unsigned int max) { long long liczba = 0; do { if (std::cin.fail()) { std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "niepoprawna wartosc \n"; } std::cin >> static_cast<long long>(liczba); } while (liczba < min || liczba > max || std::cin.fail()); unsigned wynik = static_cast<unsigned int>(liczba); std::cout << "pobrano liczbe: " << wynik << "\n"; return wynik; } //klasa suca do ustawiania parametrw programu (w wikszoci przed kompilacj) class Ustawienia { public: //wymiary okna (w pikselach) const static int rozmiar_x = 1024; const static int rozmiar_y = 540; //pozycja okna (w pikselach) const static int pozycja_x = 250; const static int pozycja_y = 155; const static int szerokosc_dna = 60; //okrela do jakiego poziomu mog pojawia si i pywa organizmy const static int wysokosc_dna = rozmiar_y - szerokosc_dna; //sr oznacza redni warto const static int temperatura_sr = 10; const static int glebokosc_sr = 1000; const static int procentowe_odchylenie_przystosowan = 25; const static int odchylenie_temperatury = static_cast<int>(temperatura_sr * (procentowe_odchylenie_przystosowan / 100.0)); const static int odchylenie_glebokosci = static_cast<int>(glebokosc_sr * (procentowe_odchylenie_przystosowan / 100.0)); //jeli uytkownik korzysta z wasnych ustawie to ta zmienna ma warto "true" bool ustawienia_wlasne; const static int liczba_skal = 5; int Xliczba_skal; const static int ilosc_ryb_na_poczatku = 240; int Xilosc_ryb_na_poczatku; const static int ilosc_gabek_na_poczatku = 100; int Xilosc_gabek_na_poczatku; const static int max_ilosc_ryb = 300; int Xmax_ilosc_ryb; const static int max_ilosc_gabek = 200; int Xmax_ilosc_gabek; //okrela ile procent organizmw przeyje eliminacj metod ruletki const static int ile_po_ruletce = 92; const static int co_ktora_gabka_sie_rozmnaza = 2; const static int sredni_czas_zycia_ryby = 40; const static int sredni_czas_zycia_gabki = 60; const static int srednia_liczba_rozmnozen = 3; const static int odchylenie_sredniego_czasu_zycia = 15; const static int co_ile_cykli_rozmnozenie = sredni_czas_zycia_ryby / srednia_liczba_rozmnozen; const static int klatki_na_sekunde = 9; const static int max_ilo_przebiegow_sieci = 4; float wylosowane_skalowania_wsp_x[2][liczba_skal]; Ustawienia(); //Funkcja pobierajca od uytkownika parametry symulacji void wlasne_ustawienia(); }; inline Ustawienia::Ustawienia() { for (int i = 0; i < liczba_skal; i++) { wylosowane_skalowania_wsp_x[0][i] = (std::rand() % 10 + 5) / static_cast<float>(10); wylosowane_skalowania_wsp_x[1][i] = static_cast<float>(std::rand() % (static_cast<int>(Ustawienia::rozmiar_x * 0.9))); } } inline void Ustawienia::wlasne_ustawienia() { std::cout << "Podaj liczbe skal <0, 10> \n"; this->Xliczba_skal = pobierz_unsigned(0, 10); std::cout << "Podaj ilosc ryb na poczatku <2, 300> \n"; Xilosc_ryb_na_poczatku = pobierz_unsigned(2, 300); std::cout << "Podaj ilosc gabek na poczatku <1, 200> \n"; Xilosc_gabek_na_poczatku = pobierz_unsigned(1, 200); std::cout << "Podaj maksymalna ilosc ryb <50, 500> \n"; Xmax_ilosc_ryb = pobierz_unsigned(50, 500); std::cout << "Podaj maksymalna ilosc gabek <40, 400> \n"; Xmax_ilosc_gabek = pobierz_unsigned(40, 400); } //Klasa zawierajca cz wspln klasy: Ryba i Gbka class Organizm { public: //Ps oznacza przystosowanie do redniej wartoci int temperatura_Ps; unsigned glebokosc_Ps; //okrela cakowite przystosowanie do danych warunkw double przystosowanie_calkowite; //wsprzdne int x, y; //okrela przez ile cykli dany organizm bdzie jeszcze y, jest zmniejszana przez funkcj "uplyw_czasu" int czas_do_smierci; //kolor organizmu sf::Color kolor; //rozmiar (przy wywietlaniu) int rozmiar; //okrela czy dany organizm ma przey selekcje metod ruletki bool ruletka = false; Organizm(const int& temperatura, const unsigned& glebokosc, const unsigned& _x, const unsigned& _y, const sf::Color& color); }; inline Organizm::Organizm(const int& temperatura, const unsigned& glebokosc, const unsigned& _x, const unsigned& _y, const sf::Color& color) : temperatura_Ps(temperatura), glebokosc_Ps(glebokosc), x(_x), y(_y), kolor(color) {} class Ryba : public Organizm { public: Ryba(const int & temperatura, const unsigned & glebokosc, const unsigned & _x, const unsigned & _y, const sf::Color & color); }; inline Ryba::Ryba(const int& temperatura, const unsigned& glebokosc, const unsigned& _x, const unsigned& _y, const sf::Color& color) : Organizm(temperatura, glebokosc, _x, _y, color) { czas_do_smierci = Ustawienia::sredni_czas_zycia_ryby + std::rand() % (2 * Ustawienia::odchylenie_sredniego_czasu_zycia) - Ustawienia::odchylenie_sredniego_czasu_zycia; rozmiar = std::rand() % 9 + 3; } class Gabka : public Organizm { public: Gabka(const int & temperatura, const unsigned & glebokosc, const unsigned & _x, const unsigned & _y, const sf::Color & color); }; inline Gabka::Gabka(const int& temperatura, const unsigned& glebokosc, const unsigned& _x, const unsigned& _y, const sf::Color& color) : Organizm(temperatura, glebokosc, _x, _y, color) { czas_do_smierci = Ustawienia::sredni_czas_zycia_gabki + std::rand() % (2 * Ustawienia::odchylenie_sredniego_czasu_zycia) - Ustawienia::odchylenie_sredniego_czasu_zycia; rozmiar = std::rand() % 14 + 2; } //Funkcja zwraca "true" z prawdopodobiestwem "p" static bool z_prawdopodobienstwem(const double & p) { return rand() / (RAND_MAX + 1.0) < p; } //Klasa odpowiedzialna za selekcj i rozmnaanie organizmw class Algorytm_genetyczny { //Podprocedura funkcji "ocena_przystosowania" static double oblicz_skladni(const int & _Ps, const int & _sr); //Funkcja usuwa organizmy wskazane metod ruletki static void wynik_ruletki(std::vector<Ryba*> & wektor); void wynik_ruletki(std::vector<Gabka*> & wektor); //Funkcja ocenia przystosowanie organizmw static double ocena_przystosowania(std::vector<Ryba*> & wektor); double ocena_przystosowania(std::vector<Gabka*> & wektor); //Funkcja wykorzystujc metod ruletki decyduje, ktre organizmy zostan usunite z powodu zbyt sabego przystosowania //do otoczenia (pozostae bd si mnoy) static void selekcja(std::vector<Ryba*> & wektor); void selekcja(std::vector<Gabka*> & wektor); //Funkcja wywoywana tylko przez funkcje "krzyzowanie" i "mutacja"; tworzy jeden organizm danego typu static void rozmnoz_organizmy(const std::vector<Ryba*>::iterator & it, const std::vector<Ryba*>::iterator & it_temp,std::vector<Ryba*> & wektor_temp); void rozmnoz_organizmy(std::vector<Gabka*> & gabki, const int & licznik_gabek); //Funkcja rozmnaajca obiekty typu Ryba. Parametry nowej ryby s obliczane w nastpujcy sposb: //przystosowanie do rednich wartoci s dziedziczone po osobno po jednym z rodzicw z rwnym prawdopodobiestwem, //pooenie to rednia wsprzdnych rodzicw, kolor to zoenie poowy koloru kadego z rodzicw static void krzyzowanie(std::vector<Ryba*> & ryby); //Funkcja rozmnaajca obiekty typu Gabka. Parametry nowej gbki s obliczane w nastpujcy sposb: //przystosowanie do rednich wartoci i kolor s obliczane tak jak przy generacji organizmw pocztkowych, //pooenia s losowe ale zblione do danej gbki, ktra mutuje void mutacja(std::vector<Gabka*>& gabki); //obliczenia dla zbioru ryb static void watek_ryby(std::vector<Ryba*>& ryby); public: //Funkcja uruchamiajca funkcje algorytmu genetycznego void rozpocznij(std::vector<Ryba*>& ryby, std::vector<Gabka*>& gabki); //Funkcja "postarza" i usuwa organizmy void uplyw_czasu(std::vector<Ryba*>& wektor); void uplyw_czasu(std::vector<Gabka*>& wektor); }; inline double Algorytm_genetyczny::oblicz_skladni(const int& _Ps, const int& _sr) { int granica = 4; int roznica = abs(_Ps - _sr); if (roznica < granica) return 100; if (roznica < granica * 3) return 50; if (roznica < granica * 6) return 20; return 0.1; } inline void Algorytm_genetyczny::wynik_ruletki(std::vector<Ryba*>& wektor) { std::vector<Ryba*>::iterator it = wektor.begin(); while (it != wektor.end()) { if (!(*it)->ruletka) { delete (*it); it = wektor.erase(it); } else { (*it)->ruletka = false; ++it; } } } inline void Algorytm_genetyczny::wynik_ruletki(std::vector<Gabka*>& wektor) { std::vector<Gabka*>::iterator it = wektor.begin(); while (it != wektor.end()) { if (!(*it)->ruletka) { delete (*it); it = wektor.erase(it); } else { (*it)->ruletka = false; ++it; } } } inline double Algorytm_genetyczny::ocena_przystosowania(std::vector<Ryba*>& wektor) { double suma = 0; for (std::vector<Ryba*>::iterator it = wektor.begin(); it < wektor.end(); it++) { double skladnikT = oblicz_skladni((*it)->temperatura_Ps, Ustawienia::temperatura_sr); double skladnikG = oblicz_skladni((*it)->glebokosc_Ps, Ustawienia::glebokosc_sr); (*it)->przystosowanie_calkowite = skladnikT * skladnikG; suma += (*it)->przystosowanie_calkowite; } return suma; } inline double Algorytm_genetyczny::ocena_przystosowania(std::vector<Gabka*>& wektor) { double suma = 0; for (std::vector<Gabka*>::iterator it = wektor.begin(); it < wektor.end(); it++) { double skladnikT = oblicz_skladni((*it)->temperatura_Ps, Ustawienia::temperatura_sr); double skladnikG = oblicz_skladni((*it)->glebokosc_Ps, Ustawienia::glebokosc_sr); (*it)->przystosowanie_calkowite = skladnikT * skladnikG; suma += (*it)->przystosowanie_calkowite; } return suma; } inline void Algorytm_genetyczny::selekcja(std::vector<Ryba*>& wektor) { double suma_przystosowan = ocena_przystosowania(wektor); for (int i = 0; i < static_cast<int>(wektor.size() * (Ustawienia::ile_po_ruletce / 100.0)); i++) { float prawdopodobienstwo = (std::rand() % 10000) / static_cast<float>(10000); float suma_prawdopodobienstw = 0; for (unsigned j = 0; j < wektor.size(); j++) { //obliczenie przystosowania danego organizmu w stosunku do sumy przystosowa wszystkich organizmw suma_prawdopodobienstw += wektor[j]->przystosowanie_calkowite / suma_przystosowan; if (!wektor[j]->ruletka) { if (prawdopodobienstwo < suma_prawdopodobienstw) { wektor[j]->ruletka = true; break; } } } } wynik_ruletki(wektor); } inline void Algorytm_genetyczny::selekcja(std::vector<Gabka*>& wektor) { double suma_przystosowan = ocena_przystosowania(wektor); for (int i = 0; i < static_cast<int>(wektor.size() * (Ustawienia::ile_po_ruletce / 100.0)); i++) { float prawdopodobienstwo = (std::rand() % 10000) / 10000.0; float suma_prawdopodobienstw = 0; for (int j = 0; j < wektor.size(); j++) { suma_prawdopodobienstw += wektor[j]->przystosowanie_calkowite / suma_przystosowan; if (!wektor[j]->ruletka) { if (prawdopodobienstwo < suma_prawdopodobienstw) { wektor[j]->ruletka = true; break; } } } } wynik_ruletki(wektor); } inline void Algorytm_genetyczny::rozmnoz_organizmy(const std::vector<Ryba*>::iterator& it, const std::vector<Ryba*>::iterator& it_temp, std::vector<Ryba*>& wektor_temp) { int temperatura; if (z_prawdopodobienstwem(0.5)) temperatura = (*it)->temperatura_Ps; else temperatura = (*it_temp)->temperatura_Ps; int glebokosc; if (z_prawdopodobienstwem(0.5)) glebokosc = (*it)->glebokosc_Ps; else glebokosc = (*it_temp)->glebokosc_Ps; sf::Color kolor(0, (*it)->kolor.g, (*it)->kolor.b); wektor_temp.push_back(new Ryba(temperatura, glebokosc, std::rand() % Ustawienia::rozmiar_x, std::rand() % Ustawienia::wysokosc_dna, kolor)); } inline void Algorytm_genetyczny::rozmnoz_organizmy(std::vector<Gabka*>& gabki, const int& licznik_gabek) { int wspolrzedna_y = gabki.at(licznik_gabek)->y + std::rand() % 10 - 5; if (wspolrzedna_y > Ustawienia::szerokosc_dna) { wspolrzedna_y = Ustawienia::szerokosc_dna - std::rand() % 8; } wspolrzedna_y += Ustawienia::wysokosc_dna; sf::Color kolor(std::rand() % 55 + 170, 0, std::rand() % 155); gabki.push_back(new Gabka(std::rand() % Ustawienia::odchylenie_temperatury - Ustawienia::odchylenie_temperatury / 2 + Ustawienia::temperatura_sr, std::rand() % Ustawienia::odchylenie_glebokosci - Ustawienia::odchylenie_glebokosci / 2 + Ustawienia::glebokosc_sr, (gabki.at(licznik_gabek)->x + std::rand() % 20 - 10) % Ustawienia::rozmiar_x, wspolrzedna_y, kolor)); } inline void Algorytm_genetyczny::krzyzowanie(std::vector<Ryba*>& ryby) { std::vector<Ryba*> ryby_temp; std::vector<Ryba*>::iterator it = ryby.begin(); if (it == ryby.end()) return; ++it; std::vector<Ryba*>::iterator it_temp = ryby.begin(); while (true) { if (it == ryby.end()) break; rozmnoz_organizmy(it, it_temp, ryby_temp); ++it; if (it == ryby.end()) break; it_temp = it; ++it; } int rozmiar = ryby_temp.size(); for (int i = 0; i < rozmiar; i++) { ryby.push_back(ryby_temp.back()); ryby_temp.pop_back(); } } inline void Algorytm_genetyczny::mutacja(std::vector<Gabka*>& gabki) { int licznik_gabek = 0; int ilosc_gabek_przed_rozmnazaniem = gabki.size(); while (true) { if (licznik_gabek >= ilosc_gabek_przed_rozmnazaniem) return; if (licznik_gabek % Ustawienia::co_ktora_gabka_sie_rozmnaza == 0) { rozmnoz_organizmy(gabki, licznik_gabek); } licznik_gabek++; } } inline void Algorytm_genetyczny::watek_ryby(std::vector<Ryba*>& ryby) { selekcja(ryby); krzyzowanie(ryby); } inline void Algorytm_genetyczny::rozpocznij(std::vector<Ryba*>& ryby, std::vector<Gabka*>& gabki) { //obliczenia dla zbioru ryb odbywaj si w osobnym wtku, natomiast dla gbek wtku gwnym std::thread watek(&Algorytm_genetyczny::watek_ryby, std::ref(ryby)); selekcja(gabki); mutacja(gabki); watek.join(); } inline void Algorytm_genetyczny::uplyw_czasu(std::vector<Ryba*>& wektor) { for (std::vector<Ryba*>::iterator it = wektor.begin(); it != wektor.end();) { (*it)->czas_do_smierci--; if ((*it)->czas_do_smierci <= 0) { delete (*it); it = wektor.erase(it); } else ++it; } } inline void Algorytm_genetyczny::uplyw_czasu(std::vector<Gabka*>& wektor) { for (std::vector<Gabka*>::iterator it = wektor.begin(); it != wektor.end();) { (*it)->czas_do_smierci--; if ((*it)->czas_do_smierci <= 0) { delete (*it); it = wektor.erase(it); } else ++it; } }
true
42cb40989af6e6582775c882789fb48f710ba7fa
C++
apache/trafficserver
/lib/swoc/include/swoc/string_view_util.h
UTF-8
2,408
3.140625
3
[ "TCL", "LicenseRef-scancode-proprietary-license", "BSD-3-Clause", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "ISC", "OpenSSL", "MIT", "HPND", "Apache-2.0", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain", "Licen...
permissive
// SPDX-License-Identifier: Apache-2.0 // Copyright Apache Software Foundation 2019 /** @file Additional handy utilities for @c string_view and hence also @c TextView. */ #pragma once #include <bitset> #include <iosfwd> #include <memory.h> #include <string> #include <string_view> #include <memory> #include <limits> /** Compare views with ordering, ignoring case. * * @param lhs input view * @param rhs input view * @return The ordered comparison value. * * - -1 if @a lhs is less than @a rhs * - 1 if @a lhs is greater than @a rhs * - 0 if the views have identical content. * * If one view is the prefix of the other, the shorter view is less (first in the ordering). */ int strcasecmp(const std::string_view &lhs, const std::string_view &rhs); /** Compare views with ordering. * * @param lhs input view * @param rhs input view * @return The ordered comparison value. * * - -1 if @a lhs is less than @a rhs * - 1 if @a lhs is greater than @a rhs * - 0 if the views have identical content. * * If one view is the prefix of the other, the shorter view is less (first in the ordering). * * @note For string views, there is no difference between @c strcmp and @c memcmp. * @see strcmp */ int memcmp(const std::string_view &lhs, const std::string_view &rhs); /** Compare views with ordering. * * @param lhs input view * @param rhs input view * @return The ordered comparison value. * * - -1 if @a lhs is less than @a rhs * - 1 if @a lhs is greater than @a rhs * - 0 if the views have identical content. * * If one view is the prefix of the other, the shorter view is less (first in the ordering). * * @note For string views, there is no difference between @c strcmp and @c memcmp. * @see memcmp */ inline int strcmp(const std::string_view &lhs, const std::string_view &rhs) { return memcmp(lhs, rhs); } /** Copy bytes. * * @param dst Destination buffer. * @param src Original string. * @return @a dest * * This is a convenience for * @code * memcpy(dst, src.data(), size.size()); * @endcode * Therefore @a dst must point at a buffer large enough to hold @a src. If this is not already * determined, then presuming @c DST_SIZE is the size of the buffer at @a dst * @code * memcpy(dst, src.prefix(DST_SIZE)); * @endcode * */ inline void * memcpy(void *dst, const std::string_view &src) { return memcpy(dst, src.data(), src.size()); }
true
307b9b80f31237b9c295aaf15a7a938b64c9414d
C++
jaybroker/dstore
/dstore/network/epoll.cpp
UTF-8
4,084
2.765625
3
[ "MIT" ]
permissive
#include "epoll.h" #include <errno.h> #include "errno_define.h" #include "log.h" #include "memory.h" #include "event_loop.h" using namespace dstore::common; using namespace dstore::network; EpollAPI::EpollAPI(EventLoop *lop) : epfd_(0), events_(nullptr), loop_size_(0), loop_(lop) { } EpollAPI::~EpollAPI() { destory(); } int EpollAPI::init(void) { int ret = DSTORE_SUCCESS; events_ = static_cast<struct epoll_event *>(dstore_malloc(sizeof(struct epoll_event) * LOOP_INIT_SIZE)); if (nullptr == events_) { ret = DSTORE_MEMORY_ALLOCATION_FAILED; LOG_ERROR("allocate memory failed for epoll events, ret=%d", ret); return ret; } loop_size_ = LOOP_INIT_SIZE; epfd_ = epoll_create(1024); if (-1 == epfd_) { ret = DSTORE_EPOLL_ERROR; LOG_ERROR("epoll_create failed, errno=%d, ret=%d", errno, ret); dstore_free(events_); return ret; } return ret; } int EpollAPI::register_event(int fd, int type) { int ret = DSTORE_SUCCESS; struct epoll_event event; int sys_ret = 0; event.events = 0; event.data.fd = fd; if (type & Event::kEventRead) { event.events |= EPOLLIN; } if (type & Event::kEventWrite) { event.events |= EPOLLOUT; } sys_ret = epoll_ctl(epfd_, EPOLL_CTL_ADD, fd, &event); if (-1 == sys_ret) { ret = DSTORE_EPOLL_ERROR; LOG_WARN("epoll_ctl failed, epfd=%d, fd=%d, event=%d, errno=%d", epfd_, fd, event.events, errno); } return ret; } int EpollAPI::unregister_event(int fd, int type) { int ret = DSTORE_SUCCESS; struct epoll_event event; int sys_ret = 0; event.events = 0; event.data.fd = fd; if (type & Event::kEventRead) { event.events |= EPOLLIN; } if (type & Event::kEventWrite) { event.events |= EPOLLOUT; } sys_ret = epoll_ctl(epfd_, EPOLL_CTL_DEL, fd, &event); if (-1 == sys_ret) { ret = DSTORE_EPOLL_ERROR; LOG_WARN("epoll_ctl failed, epfd=%d, fd=%d, event=%d, errno=%d", epfd_, fd, event.events, errno); } return ret; } int EpollAPI::modify_event(int fd, int type) { struct epoll_event event; int sys_ret = 0; int ret = DSTORE_SUCCESS; event.events = 0; event.data.fd = fd; if (type & Event::kEventRead) { event.events |= EPOLLIN; } if (type & Event::kEventWrite) { event.events |= EPOLLOUT; } sys_ret = epoll_ctl(epfd_, EPOLL_CTL_MOD, fd, &event); if (-1 == sys_ret) { ret = DSTORE_EPOLL_ERROR; LOG_WARN("epoll_ctl failed, epfd=%d, fd=%d, event=%d, errno=%d", epfd_, fd, event.events, errno); } return ret; } int EpollAPI::resize(int set_size) { int ret = DSTORE_SUCCESS; struct epoll_event *events_ptr = nullptr; events_ptr = static_cast<struct epoll_event *>(dstore_realloc(events_, sizeof(struct epoll_event) * set_size)); if (nullptr == events_ptr) { ret = DSTORE_MEMORY_ALLOCATION_FAILED; LOG_WARN("allocate memory failed, ret=%d", ret); return ret; } events_ = events_ptr; loop_size_ = set_size; return ret; } int EpollAPI::loop(int timeout) { int ret = DSTORE_SUCCESS; int events_num = 0; events_num = epoll_wait(epfd_, events_, loop_size_, timeout); if (-1 == events_num) { ret = DSTORE_EPOLL_ERROR; LOG_WARN("epoll wait failed, epfd_=%d, loop_size=%d, errno = %d, ret=%d", epfd_, loop_size_, errno, ret); return ret; } for (int64_t i = 0; i < events_num; ++i) { int event_type = 0; struct epoll_event *e = events_ + i; if (e->events & EPOLLERR) { event_type |= Event::kEventError; } if (e->events & (EPOLLIN | EPOLLHUP)) { event_type |= Event::kEventRead; } if (e->events & EPOLLOUT) { event_type |= Event::kEventWrite; } loop_->add_ready_event(e->data.fd, event_type); } if (events_num == loop_size_) { int tmp_ret = DSTORE_SUCCESS; if (DSTORE_SUCCESS != (tmp_ret = resize(loop_size_ * 2))) { LOG_WARN("epoll resize failed, loop_size_=%d, expand_to=%d, ret=%d", loop_size_, loop_size_ * 2, ret); } } return ret; } void EpollAPI::destory(void) { if (nullptr != events_) { dstore_free(events_); events_ = nullptr; } }
true
90b11940b8f9677290b90322628bb4962d0852b1
C++
ankitsharma1999/CPP
/1005B.cpp
UTF-8
620
3.1875
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int solve(string, string); int main() { string str1 = "", str2 = ""; cin >> str1; cin >> str2; cout << solve(str1, str2) << "\n"; } int solve(string str1, string str2) { reverse(str1.begin(), str1.end()); reverse(str2.begin(), str2.end()); int lim = min(str1.length(), str2.length()); int i, ctr = 0; for (i = 0; i < lim; i++) { if (str1[i] == str2[i]) { ctr++; } else { break; } } return (str1.length() + str2.length()) - (2 * ctr); }
true
beacae294e05db3a3bfd31b784a029ca651958dc
C++
rickarkin/PyMesh-win
/tests/tools/Wires/Parameters/OffsetParameterTest.h
UTF-8
3,927
2.609375
3
[]
no_license
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #pragma once #include <WireTest.h> #include <Wires/Parameters/OffsetParameters.h> #include <Wires/Parameters/ParameterCommon.h> class OffsetParameterTest : public WireTest { }; TEST_F(OffsetParameterTest, DefaultValue) { WireNetwork::Ptr wire_network = load_wire_shared("brick5.wire"); const size_t dim = wire_network->get_dim(); const size_t num_vertices = wire_network->get_num_vertices(); OffsetParameters params(wire_network, ParameterCommon::VERTEX, 0.0); ASSERT_FLOAT_EQ(0.0, params.get_default()); ASSERT_EQ(wire_network, params.get_wire_network()); ParameterCommon::Variables vars; MatrixFr offset = params.evaluate(vars); ASSERT_EQ(num_vertices, offset.rows()); ASSERT_EQ(dim, offset.cols()); ASSERT_FLOAT_EQ(0.0, offset.minCoeff()); ASSERT_FLOAT_EQ(0.0, offset.maxCoeff()); } TEST_F(OffsetParameterTest, AddValue) { WireNetwork::Ptr wire_network = load_wire_shared("brick5.wire"); const size_t dim = wire_network->get_dim(); const size_t num_vertices = wire_network->get_num_vertices(); OffsetParameters params(wire_network, ParameterCommon::VERTEX, 0.0); ASSERT_FLOAT_EQ(0.0, params.get_default()); ASSERT_EQ(wire_network, params.get_wire_network()); // This roi is carefully chosen to exclude any boundary vertices. // All vertices of this roi lies on a unit box. VectorI roi(4); roi << 0, 1, 2, 3; params.add(roi, "", 0.1, 0); params.add(roi, "", 0.1, 1); params.add(roi, "", 0.1, 2); const VectorF bbox_half_size = wire_network->get_bbox_max() - wire_network->center(); const Float half_size = bbox_half_size[0]; ParameterCommon::Variables vars; MatrixFr offset = params.evaluate(vars); ASSERT_EQ(num_vertices, offset.rows()); ASSERT_EQ(dim, offset.cols()); ASSERT_TRUE((offset.block(0, 0, 4, dim).cwiseAbs().array() == 0.1 * half_size).all()); ASSERT_TRUE((offset.block(4, 0, offset.rows() - 4, dim).array() == 0.0) .all()); } TEST_F(OffsetParameterTest, AddFormula) { WireNetwork::Ptr wire_network = load_wire_shared("brick5.wire"); const size_t dim = wire_network->get_dim(); const size_t num_vertices = wire_network->get_num_vertices(); const VectorF bbox_half_size = wire_network->get_bbox_max() - wire_network->center(); OffsetParameters params(wire_network, ParameterCommon::VERTEX, 0.0); // This roi is carefully chosen to exclude any boundary vertices. // All vertices of this roi lies on a unit box. VectorI roi(4); roi << 0, 1, 2, 3; params.add(roi, "x", 0.0, 0); params.add(roi, "y", 0.0, 1); params.add(roi, "z", 0.0, 2); ParameterCommon::Variables vars; vars["x"] = 0.1; vars["y"] = 0.2; vars["z"] = 0.3; MatrixFr offset = params.evaluate(vars); ASSERT_EQ(num_vertices, offset.rows()); ASSERT_EQ(dim, offset.cols()); for (size_t i=0; i<4; i++) { const VectorF& u = offset.row(i); ASSERT_FLOAT_EQ(0.1 * bbox_half_size[0], fabs(u[0])); ASSERT_FLOAT_EQ(0.2 * bbox_half_size[1], fabs(u[1])); ASSERT_FLOAT_EQ(0.3 * bbox_half_size[2], fabs(u[2])); } ASSERT_TRUE((offset.block(4, 0, offset.rows() - 4, dim).array() == 0.0) .all()); } TEST_F(OffsetParameterTest, InvalidDof) { WireNetwork::Ptr wire_network = load_wire_shared("cube.wire"); OffsetParameters params(wire_network, ParameterCommon::VERTEX, 0.0); // Since all vertices of cube are on boundary, no matter what roi is, there // is no degree of freedom for offseting them. VectorI roi(2); roi << 0, 2; params.add(roi, "", 1.0, 0); ASSERT_EQ(0, params.get_num_dofs()); ParameterCommon::Variables vars; MatrixFr offset = params.evaluate(vars); ASSERT_FLOAT_EQ(0.0, offset.maxCoeff()); ASSERT_FLOAT_EQ(0.0, offset.minCoeff()); }
true
15918714212604e788ebe22f321b66af333c3db5
C++
lokeon-university/AAED
/TADS/Lista/ListaCircular.hpp
UTF-8
5,147
3.609375
4
[]
no_license
#ifndef LISTA_CIRCULAR #define LISTA_CIRCULAR #include <cassert> #include <cstdio> #define POS_NULL NULL template <typename T> class ListaCir { struct nodo; // declaraci�n adelantada privada public: typedef nodo *posicion; // posici�n de un elemento ListaCir(); // constructor, requiere ctor. T() ListaCir(const ListaCir<T> &l); // ctor. de copia, requiere ctor. T() ListaCir<T> &operator=(const ListaCir<T> &l); // asignaci�n delistas void insertar(const T &x, posicion p); void eliminar(posicion p); T elemento(posicion p) const; // acceso a elto, lectura T &elemento(posicion p); // acceso a elto, lectura/escritura posicion buscar(const T &x) const; // T requiere operador == posicion siguiente(posicion p) const; posicion anterior(posicion p) const; posicion inipos() const; ~ListaCir(); // destructor private: struct nodo { T elto; nodo *ant, *sig; nodo(const T &e, nodo *a = 0, nodo *s = 0) : elto(e), ant(a), sig(s) {} }; nodo *L; // lista doblemente enlazada de nodos void copiar(const ListaCir<T> &l); }; // M�todo privado template <typename T> void ListaCir<T>::copiar(const ListaCir<T> &l) { if (l.inipos() != POS_NULL) //Si la lista a copiar tiene algun elemento, se copian { L = new nodo(l.elemento(l.inipos()), 0, 0); L->sig = L->ant = L; nodo *q; q = L; for (nodo *r = l.L->sig; r != l.L; r = r->sig) { q->sig = new nodo(r->elto, q, L); q = q->sig; } L->ant = q; } else { L = 0; //Si no se crea una lista vacia normal } } template <typename T> inline ListaCir<T>::ListaCir() : L(POS_NULL) {} //Devuelve una lista vac�a en la que L ser� un puntero nulo template <typename T> inline ListaCir<T>::ListaCir(const ListaCir<T> &l) { copiar(l); } //Const copia template <typename T> ListaCir<T> &ListaCir<T>::operator=(const ListaCir<T> &l) // sobrecarga asignaci�n { if (this != &l) { // evitar autoasignaci�n this->~ListaCir(); // vaciar la lista actual copiar(l); } return *this; } template <typename T> inline void ListaCir<T>::insertar(const T &x, ListaCir<T>::posicion p) { if (L == POS_NULL) //Si la posici�n es nula creamos el primer nodo de la lista { L = new nodo(x, p, p); L->ant = L->sig = L; } else p->sig = p->sig->ant = new nodo(x, p, p->sig); // el nuevo nodo con x queda en la posici�n p } template <typename T> inline void ListaCir<T>::eliminar(ListaCir<T>::posicion p) { p = p->sig; if (p == L) //Si el elemento a borrar es al que apunta L, L apunta al que ahora ocupa p { L = p->sig; p->ant->sig = p->sig; p->sig->ant = p->ant; } else // el nodo siguiente queda en la posici�n p { p->ant->sig = p->sig; p->sig->ant = p->ant; } if (p == p->sig) // Si la lista solo tiene un elemento antes de eliminarlo apuntamos L a 0 L = 0; delete p; } template <typename T> inline T ListaCir<T>::elemento(ListaCir<T>::posicion p) const { return p->sig->elto; // La direccion del un elemento se consigue pasando la posici�n del anterior } template <typename T> inline T &ListaCir<T>::elemento(ListaCir<T>::posicion p) { return p->sig->elto; } template <typename T> typename ListaCir<T>::posicion ListaCir<T>::buscar(const T &x) const { assert(L == POS_NULL); //Precondicion para evitar errores de ejecuci�n nodo *q; bool encontrado; encontrado = false; q = inipos(); while (q->sig != inipos() && !encontrado) { if (q->sig->elto == x) encontrado = true; else q = q->sig; } if (q->elto != x) q == POS_NULL; //Si no est� en la lista devuelve POS_NULL return q; } template <typename T> inline typename ListaCir<T>::posicion ListaCir<T>::siguiente(ListaCir<T>::posicion p) const { return p->sig; } template <typename T> inline typename ListaCir<T>::posicion ListaCir<T>::anterior(ListaCir<T>::posicion p) const { return p->ant; } template <typename T> inline typename ListaCir<T>::posicion ListaCir<T>::inipos() const { nodo *posicion; if (L == POS_NULL) //Si la lista no tiene elementos se devuelve pos_null posicion = POS_NULL; else posicion = L->ant; return posicion; } // Destructor: Vac�a la lista y destruye el nodo cabecera template <typename T> ListaCir<T>::~ListaCir() { if (L != 0) //Si la lista est� vacia solo se elimina el puntero L { nodo *q; while (L->sig != L) { q = L->sig; L->sig = q->sig; delete q; } } delete L; } #endif // listacircular
true
91d301f854bfe84a5d2efd6c0528bb73a042b8b2
C++
fernandafallas/progra
/untitled/Professor.cpp
UTF-8
654
3.25
3
[]
no_license
// // Created by mafef on 11/08/2020. // #include "Professor.h" Professor::Professor(){ this->salary = 0.0; } Professor::Professor(double salary) { this->salary = salary; } Professor::Professor(const string& name, string& id, double ) : Person (name, id){ this->salary = salary; } double Professor::getSalary(){ return salary; } void Professor::setSalary(double salary){ this->salary = salary; } string Professor::toString() const{ stringstream s; s << "Professor :\n" << Person::toString() << "Salary: " << getSalary() << endl; return s.str(); } Professor::~Professor(){ }
true
6f817e7904676cd2188c4657b2583be01e934aa8
C++
brycelelbach/agency
/agency/execution/executor/concurrent_executor.hpp
UTF-8
5,127
2.84375
3
[]
no_license
#pragma once #include <agency/future.hpp> #include <agency/execution/execution_categories.hpp> #include <agency/detail/invoke.hpp> #include <agency/detail/type_traits.hpp> #include <thread> #include <vector> #include <memory> #include <algorithm> #include <utility> namespace agency { class concurrent_executor { public: using execution_category = concurrent_execution_tag; size_t unit_shape() const { constexpr size_t default_result = 1; size_t hw_concurrency = std::thread::hardware_concurrency(); // hardware_concurency() is allowed to return 0, so guard against a 0 result return hw_concurrency ? hw_concurrency : default_result; } template<class Function, class Future, class ResultFactory, class SharedFactory> std::future< detail::result_of_t<ResultFactory()> > bulk_then_execute(Function f, size_t n, Future& predecessor, ResultFactory result_factory, SharedFactory shared_factory) { return bulk_then_execute_impl(f, n, predecessor, result_factory, shared_factory); } private: template<class Function, class Future, class ResultFactory, class SharedFactory> std::future<agency::detail::result_of_t<ResultFactory()>> bulk_then_execute_impl(Function f, size_t n, Future& predecessor, ResultFactory result_factory, SharedFactory shared_factory, typename std::enable_if< !std::is_void< typename agency::future_traits<Future>::value_type >::value >::type* = 0) { if(n > 0) { using predecessor_type = typename agency::future_traits<Future>::value_type; return agency::detail::monadic_then(predecessor, std::launch::async, [=](predecessor_type& predecessor) mutable { // put all the shared parameters on the first thread's stack auto result = result_factory(); auto shared_parameter = shared_factory(); // create a lambda to handle parameter passing auto g = [&,f](size_t idx) { agency::detail::invoke(f, idx, predecessor, result, shared_parameter); }; size_t mid = n / 2; std::future<void> left = agency::detail::make_ready_future(); if(0 < mid) { left = this->async_execute(g, 0, mid); } std::future<void> right = agency::detail::make_ready_future(); if(mid + 1 < n) { right = this->async_execute(g, mid + 1, n); } g(mid); left.wait(); right.wait(); return std::move(result); }); } return agency::detail::make_ready_future(result_factory()); } template<class Function, class Future, class ResultFactory, class SharedFactory> std::future<agency::detail::result_of_t<ResultFactory()>> bulk_then_execute_impl(Function f, size_t n, Future& predecessor, ResultFactory result_factory, SharedFactory shared_factory, typename std::enable_if< std::is_void< typename agency::future_traits<Future>::value_type >::value >::type* = 0) { if(n > 0) { return agency::detail::monadic_then(predecessor, std::launch::async, [=]() mutable { // put all the shared parameters on the first thread's stack auto result = result_factory(); auto shared_parameter = shared_factory(); // create a lambda to handle parameter passing auto g = [&,f](size_t idx) { agency::detail::invoke(f, idx, result, shared_parameter); }; size_t mid = n / 2; std::future<void> left = agency::detail::make_ready_future(); if(0 < mid) { left = this->async_execute(g, 0, mid); } std::future<void> right = agency::detail::make_ready_future(); if(mid + 1 < n) { right = this->async_execute(g, mid + 1, n); } g(mid); left.wait(); right.wait(); return std::move(result); }); } return agency::detail::make_ready_future(result_factory()); } // first must be less than last template<class Function> std::future<void> async_execute(Function f, size_t first, size_t last) { return std::async(std::launch::async, [=]() mutable { size_t mid = (last + first) / 2; std::future<void> left = detail::make_ready_future(); if(first < mid) { left = this->async_execute(f, first, mid); } std::future<void> right = detail::make_ready_future(); if(mid + 1 < last) { right = this->async_execute(f, mid + 1, last); } agency::detail::invoke(f,mid); left.wait(); right.wait(); }); } }; } // end agency
true
7456d589608709abdd76db488f981cb1f9e3c046
C++
ProCodersfromIS/JiMP2-zad2
/aghMatrix.h
WINDOWS-1250
14,714
3.5625
4
[]
no_license
/** * \file aghMatrix.h * \author Kamil Dawidw & Beata Giebaga * \date 15.5.2014 * \brief Szablon klasy aghMatrix, zadanie numer 2 na JiMP2, IS2014 */ // ------------------------------------------------------ #ifndef AGHMATRIX_H #define AGHMATRIX_H // --------------------- using namespace std; // ----------------------- /** * \class aghMatrix * \author Kamil Dawidw & Beata Giebaga * \date 15.5.2014 * \brief Szablon klasy aghMatrix opisujcy obiekt - macierz */ template <class T> class aghMatrix { private: int rows; ///< liczba wierszy macierzy int cols; ///< liczba kolumn macierzy T** mat; ///< wskanik do tablicy tablic wartoci macierzy bool is_free = true; ///< true jeli pami jest zaalokowana, false gdy zwolniona /// \brief Metoda przydziela pami dla macierzy /// /// \param r - nowa ilo wierszy macierzy /// \param c - nowa ilo kolumn void alloc(int r, int c); /// \brief Metoda zwalnia przydzielon pami dla macierzy void free(); public: /// \brief Konstruktor bezparametrowy klasy aghMatrix(); /// \brief Konstruktor parametrowy klasy /// /// \param r - ilo kolumnn macierzy /// \param c - ilo wierszy macierzy aghMatrix(int r, int c); /// \brief Konstruktor kopiujcy klasy /// /// \param orig - referencja do obiektu macierzystego - wzorca aghMatrix(const aghMatrix<T>& orig); /// \brief Destruktor klasy ~aghMatrix(); /// \brief Metoda zwraca ilo wierszy macierzy int getRows() const; /// \brief Metoda zwraca ilo kolumn macierzy int getCols() const; /// \brief Metoda zwraca dany element macierzy /// /// \param r - indeks wiersza elementu /// \param c - indeks kolumny elementu /// \return - warto danego elementu T get(int r, int c) const; /// \brief Metoda wywietla macierz void show() const; /// \brief Metoda przypisuje warto konkretnemu elementowi macierzy /// /// \param r - indeks wiersza elementu /// \param c - indeks kolumny elementu /// \param val - warto elementu, ktra zostanie mu przypisana void setItem(int r, int c, T val); /// \brief Metoda przypisuje macierzy kolejne wartoci przekazane w tablicy /// /// \param tab - wskanik do pocztku tablicy z ktrej pobierane s wspczynniki void setItems(T* tab); /// \brief Metoda ta zmienia wielko macierzy i wpisuje w ni nowe wartoci /// /// \param r - ilo wierszy macierzy /// \param c - ilo kolumn macierzy /// \param ... - rightumenty, ktre s wpisywane w macierz void setItems(int r, int c, ...); /// \brief Przeadowanie operatora przypisania "=" /// /// \param orig - referencja do obiektu macierzystego - wzorca const aghMatrix & operator= (const aghMatrix<T> & orig); /// \brief Przeadowanie operatora dodawania "+", pozwala dodawa obiekty do siebie /// /// \param right - referencja do drugiego skadnika dodawania /// \return - obiekt, ktry jest wynikiem dodawania aghMatrix operator+ (const aghMatrix<T> & right); /// \brief Przeadowanie operatora mnoenia "*" /// /// \param right - referencja do drugiego czynnika mnoenia /// \return - obiekt, ktry jest wynikiem mnoenia aghMatrix operator* (const aghMatrix<T> & right); /// \brief Przeadowanie operatora porwnania "==" /// /// \param right - referencja do drugiego rightumentu operacji porwnania bool operator== (const aghMatrix<T>& right); /// \brief Przeadowanie operatora porwnania "!=" /// /// \param right - referencja do drugiego rightumentu operacji porwnania bool operator!= (const aghMatrix<T>& right); /// \brief Przeadowanie operatora "()", pozwala odnie si do konkretnego elementu macierzy /// /// \param r - indeks wiersza elementu /// \param c - indeks kolumny elementu /// \return - warto dane elementu T& operator() (int r, int c); }; // --------------------------------------------------------------------- // Deklaracje metod specjalizowanych // --------------------------------------- /// \brief - specjalizowana metoda setItems dla char, pozwalajca zmieni wpisane wartoci w macierz /// /// \param r - ilo wierszy macierzy /// \param c - ilo kolumn macierzy /// \param tab - tablica wartoci, ktre s wpisywane w macierz template <> void aghMatrix<char>::setItems(int r, int c, ...); /// \brief Przeadowanie operatora specjalizowanego "+" dla typu char. /// /// \details Traktuje on kolejne mae litery alfabetu jako kolejne liczby, a=0, b=1, itd. /// Daje poprawne wyniki w zakresie maych liter. /// /// \param right - referencja do drugiego skadnika dodawania /// \return - obiekt, ktry jest wynikiem dodawania template <> aghMatrix<char> aghMatrix<char>::operator+ (aghMatrix<char> const & orig); /// \brief Przeadowanie operatora specjalizowanego "*" dla typu char. /// /// \details Traktuje on kolejne mae litery alfabetu jako kolejne liczby np. a=0, b=1, itd. /// Daje poprawne wyniki w zakresie maych liter. /// /// \param right - referencja do drugiego czynnika mnoenia /// \return - obiekt, ktry jest wynikiem mnoenia template <> aghMatrix<char> aghMatrix<char>::operator* (aghMatrix<char> const & orig); /// \brief Specjalizowana metoda free dla char* template<> void aghMatrix<char*>::free(void); /// \brief Specjalizowany konstruktor parametrowy dla char* template<> aghMatrix<char*>::aghMatrix(int r, int c); /// \brief Specjalizowany konstruktor kopiujcy /// /// \param orig - obiekt wzorzec template <> aghMatrix<char*>::aghMatrix(aghMatrix<char*> const & orig); /// \brief Specjalizowany destruktor klasy template <> aghMatrix<char*>::~aghMatrix(); /// \brief Specjalizowana metoda dla char* pozwalajca zmieni warto konkretnego elementu /// /// \param r - indeks wiersza /// \param c - indeks kolumn /// \param val - wyraz ktry zostanie wpisany w podane miejsce w macierzy template <> void aghMatrix<char*>::setItem(int r, int c, char* val); /// \brief Specjalizowana metoda dla char* /// /// \param tab - wskanik do tablicy wyrazw, ktre zostan wpisane do macierzy template <> void aghMatrix<char*>::setItems(char** tab); /// \brief - specjalizowana metoda setItems dla char, pozwalajca zmieni wpisane wartoci w macierz /// /// \param r - ilo wierszy macierzy /// \param c - ilo kolumn macierzy /// \param tab - tablica wartoci, ktre s wpisywane w macierz template <> void aghMatrix<char*>::setItems(int r, int c, ...); /// \brief Przeadowanie operatora przypisania "=" /// /// \param right - referencja do obiektu macierzystego - wzorca template <> const aghMatrix<char*>& aghMatrix<char*>::operator= (const aghMatrix<char*>& right); /// \brief - specjalizowane przeadowanie operatora porwnania dla typu char* /// /// \param right - referencja do obiektu do ktrego porwnujemy template <> bool aghMatrix<char*>::operator== (const aghMatrix<char*>& right); /// \brief - specjalizowane przeadowanie operatora porwnania dla typu char* /// /// \param right - referencja do obiektu do ktrego porwnujemy template <> bool aghMatrix<char*>::operator!= (const aghMatrix<char*>& right); /// \brief Przeadowanie operatora specjalizowanego "+" dla typu char*. /// /// \details rightumentami operacji dodawania s wyrazy, traktowane jako zbiory liter. /// Wynikiem dodawania s zbiory liter. /// /// \param right - referencja do drugiego skadnika dodawania /// \return - obiekt, ktry jest wynikiem dodawania template <> aghMatrix<char*> aghMatrix<char*>::operator+ (aghMatrix<char*> const & right); /// \brief Przeadowanie operatora specjalizowanego "*" dla typu char*. /// /// \details rightumentami operacji dodawania s wyrazy, traktowane jako zbiory liter. /// Wynikiem mnoenia jest cz wsplna obu zbiorw liter. /// /// \param right - referencja do drugiego czynnika mnoenia /// \return - obiekt, ktry jest wynikiem mnoenia template<> aghMatrix<char*> aghMatrix<char*>::operator* (aghMatrix<char*> const & right); // ----------------------------------------------------------------------------- //Definicje metod szablonu klasy aghMatrix // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::alloc(int r, int c) { if (r < 0 || c < 0) throw aghException(0, "Index out of range", __FILE__, __LINE__); if (is_free) { rows = r; cols = c; mat = new T*[r]; for (int i = 0; i < rows; ++i) { mat[i] = new T[cols]; } is_free = false; } } // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::free() { if (!is_free) { for (int i = 0; i < rows; ++i) delete[] mat[i]; delete[] mat; mat = nullptr; is_free = true; rows = 0; cols = 0; } } // ----------------------------------------------------------------------------- template <class T> aghMatrix<T>::aghMatrix() { rows = 0; cols = 0; mat = nullptr; } // ----------------------------------------------------------------------------- template <class T> aghMatrix<T>::aghMatrix(int r, int c) { this->alloc(r, c); } // ----------------------------------------------------------------------------- template <class T> aghMatrix<T>::aghMatrix(const aghMatrix<T>& orig) { this->alloc(orig.getRows(), orig.getCols()); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { mat[i][j] = orig.get(i, j); } } } // ----------------------------------------------------------------------------- template <class T> aghMatrix<T>::~aghMatrix() { this->free(); } // ----------------------------------------------------------------------------- template <class T> int aghMatrix<T>::getRows() const { return rows; } // ----------------------------------------------------------------------------- template <class T> int aghMatrix<T>::getCols() const { return cols; } // ----------------------------------------------------------------------------- template <class T> T aghMatrix<T>::get(int r, int c) const { if (r < 0 || r >= rows || c < 0 || c >= cols) { throw aghException(1, "Index out of range", __FILE__, __LINE__); } else { return mat[r][c]; } } // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::show() const { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) cout << this->get(i, j) << " "; cout << endl; } } // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::setItem(int r, int c, T val) { if (r < 0 || r >= rows || c < 0 || c >= cols) { throw aghException(1, "Index out of range", __FILE__, __LINE__); } else { mat[r][c] = val; } } // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::setItems(T* tab) { for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { mat[i][j] = *tab; ++tab; } } } // ----------------------------------------------------------------------------- template <class T> void aghMatrix<T>::setItems(int r, int c, ...) { this->free(); this->alloc(r, c); va_list listOfValues; va_start(listOfValues, c); for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { mat[i][j] = va_arg(listOfValues, T); } } va_end (listOfValues); } // ----------------------------------------------------------------------------- template <class T> const aghMatrix<T> & aghMatrix<T>::operator= (const aghMatrix<T> & orig) { if (*this != orig) { this->free(); int r = orig.getRows(); int c = orig.getCols(); this->alloc(r, c); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { this->setItem(i, j, orig.get(i, j)); } } } return *this; } // ----------------------------------------------------------------------------- template <class T> aghMatrix<T> aghMatrix<T>::operator+ (const aghMatrix<T> & right) { if (rows != right.getRows() || cols != right.getCols()) { throw aghException(2, "Incompatible matrices' sizes, cannot sum", __FILE__, __LINE__); } else { aghMatrix<T> result(rows, cols); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { result.setItem(i, j, (this->get(i, j) + right.get(i, j))); } } return result; } } // ---------------------------------------------------------------------------- template <class T> aghMatrix<T> aghMatrix<T>::operator* (const aghMatrix<T> & right) { int r = rows; //ilo wierszy macierzy wyniku int c = right.getCols(); //ilo kolumn macierzy wyniku if (cols != right.getRows()) { throw aghException(2, "Incompatible matrices' sizes, cannot multiply", __FILE__, __LINE__); } else { aghMatrix<T> result(r, c); for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { result.setItem(i, j, 0); for (int k = 0; k < cols; ++k) { result.setItem(i, j, result.get(i, j) + this->get(i, k) * right.get(k, j)); } } } return result; } } // ---------------------------------------------------------------------------- template <class T> bool aghMatrix<T>::operator== (const aghMatrix<T>& right) { if (rows != right.getRows() || cols != right.getCols()) { return false; } bool result = true; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (this->get(i, j) != right.get(i, j)) { result = false; } } } return result; } // ----------------------------------------------------------------------------- template <class T> bool aghMatrix<T>::operator!= (const aghMatrix<T>& right) { return !(this->operator==(right)); } // ----------------------------------------------------------------------------- template <class T> T& aghMatrix<T>::operator() (int r, int c) { return mat[r][c]; } // ------------------------------------------------------------------------------ #endif
true
41f36a8e476f67bb6292107170696fb6f1e2b10e
C++
Speedclocker/StayInTheLight
/includes/game/Character.h
UTF-8
2,970
2.921875
3
[]
no_license
#ifndef __CHARACTER_H__ #define __CHARACTER_H__ #include <SFML/Graphics.hpp> #include <iostream> #include <math.h> #include "collision.h" #include "Animation.h" #include "Entity.h" #define PI 3.14159 class Character; // Class Attack class Attack { public: //Constructeurs et Destructeurs Attack(); Attack(int nbr_frames, std::vector< sf::IntRect > zones_collision, Character* emitter, int damages); ~Attack(); // Accesseurs int getDamages(); int getActualFrame(); int getNbrFrames(); sf::IntRect getCurZone(); Character* getEmitter(); std::vector< Character* > getMetTargets(); // Methodes bool update(); private: int m_damages; int m_nbr_frames; int m_actual_frame; bool m_push_effect; int m_push_percent; std::vector< sf::IntRect > m_zones_collision; Character *m_emitter; std::vector< Character* > m_met_targets; }; // Class Character class Character : public CollisionableEntity { public: enum State { ATTACKING, MOVING, STANDING, DEFAULT_STATE }; //Constructeurs et Destructeurs Character(); Character(std::string id, sf::Texture* texture, Map* map); Character(std::string id, std::string file_name, sf::Texture* texture, Map* map); Character(std::string id, std::string file_name, ResourcesManager* resources_manager, Map* map); virtual ~Character(); //Getters int getHealth(); int getSpeed(); State getState() const; sf::Clock getClock(); sf::Time getLastTimeAttack(); std::vector< Character* > getAvTargets(); // Setters void setTexture(sf::Texture* texture); void setHealth(int health); void setSpeed(int speed); void setState(State state); void setLastTimeAttack(sf::Time last_time_attack); void addAvTarget(Character* target); // Methods void update(); void updateAttack(); void getDrawn(sf::RenderWindow* window); void move(sf::Vector2f movement); void move(int mov_x, int mov_y); void attack(); void takeDamages(int damages); void drawPart(sf::RenderWindow* window, unsigned int height); void drawPartAndAbove(sf::RenderWindow* window, unsigned int height); protected: virtual void readFeaturesFromString(std::string string); virtual void readAnimationFromString(std::string string); private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; int m_health; // Health of a character entity int m_speed; // Speed of a character entity std::map< std::pair<Character::State, Sense> , AnimationParameters > m_animation_parameters; // Animation parameters of a character entity identified with the state and the sense of entity State m_state; sf::Clock m_clock; sf::Time m_last_time_attack; Attack* m_actual_attack; std::vector< Character* > m_av_targets; }; #endif
true
97440c4d2f2423ba593c49f96fccdce8b04fe4d0
C++
KevinHaoranZhang/Leetcode
/Sequence/q1-q99/q40-q49/q41/q41.cpp
UTF-8
1,550
3.21875
3
[]
no_license
class Solution { public: int firstMissingPositive(vector<int>& nums) { // change elements that are less than 1 to 1// // at the same time, check if 1 is in the array// // if not, return 1; int count = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] == 1) count++; if (nums[i] <= 0) nums[i] = 1; } // if 1 is not in the array, return 1// if (count == 0) return 1; // use nums[nums[i]] to change element from positive to negative// // negative number is a mark that this element(index) was visited// // also need to make sure index is within size// int index; for (int i = 0; i < nums.size(); i++) { index = abs(nums[i])-1; if(index <= nums.size()-1 && nums[index] > 0) nums[index] = -nums[index]; } // find the first element that is positive// // return that index plus one// int ans = 0; for(int i = 0; i < nums.size(); i++){ if (nums[i] > 0) { ans = i; break; } } // if all elements are negative// // return size+1, because all the smallest numbers are in the array// if (ans == 0) return nums.size()+1; return ans+1; } };
true