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
31abcb80949ad5e187552c701810e4754035ffd3
C++
miro-balaz/tctl
/solutions/RotatingBot.cpp
UTF-8
4,114
2.828125
3
[]
no_license
//{{{b //}}}e #line 5 "RotatingBot.cpp" #include <string> #include <vector> #include <map> #include <algorithm> #include <set> #include <cctype> #include <sstream> #include <bitset> #include <iostream> using namespace std; #define REP(i,n) for(int i=0;i<(int)n;++i) class RotatingBot { public: //{{{b // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); if ((Case == -1) || (Case == 7)) test_case_7(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {15}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 16; verify_case(0, Arg1, minArea(Arg0)); } void test_case_1() { int Arr0[] = {3,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 44; verify_case(1, Arg1, minArea(Arg0)); } void test_case_2() { int Arr0[] = {1,1,1,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(2, Arg1, minArea(Arg0)); } void test_case_3() { int Arr0[] = {9,5,11,10,11,4,10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 132; verify_case(3, Arg1, minArea(Arg0)); } void test_case_4() { int Arr0[] = {12,1,27,14,27,12,26,11,25,10,24,9,23,8,22,7,21,6,20,5,19,4,18,3,17,2,16,1,15}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 420; verify_case(4, Arg1, minArea(Arg0)); } void test_case_5() { int Arr0[] = {8,6,6,1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(5, Arg1, minArea(Arg0)); } void test_case_6() { int Arr0[] = {8,6,6}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 63; verify_case(6, Arg1, minArea(Arg0)); } void test_case_7() { int Arr0[] = {5,4,5,3,3}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 30; verify_case(7, Arg1, minArea(Arg0)); } // END CUT HERE //}}}e int minArea(vector <int> moves) ; }; int dx[4]={1,0,-1,0}; int dy[4]={0,-1,0,1}; set<pair<int,int> > S; int mx,my,mix,miy; void compute() { mx=-10000000; my=-1000000; mix=1000000; miy=1000000; for(set<pair<int, int> >::iterator it=S.begin();it!=S.end();++it) { int x=it->first; int y=it->second; mx=max(mx,x); my=max(y,my); mix=min(x,mix); miy=min(y,miy); } } int RotatingBot::minArea(vector <int> moves){ int x=0; int y=0; S.clear(); S.insert(make_pair(0,0)); int s=0; REP(m, moves.size()) { REP(i,moves[m]) { int nx=x+dx[s]; int ny=y+dy[s]; if(S.count(make_pair(nx,ny))) { return -1; } if(m>=4 && (nx<mix || ny<miy || ny>my || nx>mx) ) return -1; S.insert(make_pair(nx,ny)); x=nx; y=ny; } int nx=x+dx[s]; int ny=y+dy[s]; bool ok=false; if(m<=4) compute(); if(S.count(make_pair(nx,ny)) ) ok=1; if(ny<miy || ny>my || nx<mix || nx>mx) ok=1; if(m==(int)moves.size()-1) ok=1; if(!ok) return -1; s=(s+1)%4; } compute(); int sx=mx-mix+1; int sy=my-miy+1; return sx*sy; } //{{{b int main() { RotatingBot ___test; ___test.run_test(-1); } //}}}e
true
9624c21b4c600be9234040805107cef4ba8205dd
C++
volecilevo/Proje2_4.Proje
/Util.h
UTF-8
3,333
2.734375
3
[]
no_license
// // Util.h // Ders 7 // // Created by Gurel Erceis on 4/15/13. // Copyright (c) 2013 Yogurt3D. All rights reserved. // #ifndef Ders_7_Util_h #define Ders_7_Util_h #ifdef _WIN32 #include <GL/glew.h> #include <GL/gl.h> #else if __APPLE__ #include <OpenGL/gl.h> #endif #include <fstream> #define fmax(a,b) (a>b)?a:b const char* fileNameToPath(const char * filename){ unsigned int const sz1 = strlen(filename); #ifdef RESOURCE_PATH unsigned int const sz2 = strlen(RESOURCE_PATH); #endif char *concat = (char*)malloc(sz1+sz2+1); #ifdef RESOURCE_PATH memcpy( concat , RESOURCE_PATH , sz2 ); memcpy( concat+sz2 , filename , sz1 ); concat[sz1+sz2] = '\0'; #else memcpy( concat , filename , sz1 ); concat[sz1] = '\0'; #endif fprintf(stdout, "FILE:%s\n",concat); return concat; } /** file_path - shader file to load type - GL_VERTEX_SHADER || GL_FRAGMENT_SHADER **/ GLuint createShader(const char* file_path, GLuint type){ GLuint ShaderID = glCreateShader(type); // Read the Vertex Shader code from the file std::string ShaderCode; std::ifstream ShaderStream(fileNameToPath(file_path), std::ifstream::in); if(ShaderStream.is_open()) { std::string Line = ""; while(getline(ShaderStream, Line)) ShaderCode += "\n" + Line; ShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Shader char const * SourcePointer = ShaderCode.c_str(); glShaderSource(ShaderID, 1, &SourcePointer , NULL); glCompileShader(ShaderID); // Check Shader glGetShaderiv(ShaderID, GL_COMPILE_STATUS, &Result); if(!Result) { glGetShaderiv(ShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ShaderErrorMessage(InfoLogLength); glGetShaderInfoLog(ShaderID, InfoLogLength, NULL, &ShaderErrorMessage[0]); fprintf(stdout, "ERROR:%s\n%sShaderErrorMessage: %s\n",file_path,(type==GL_VERTEX_SHADER)?"Vertex":"Fragment", &ShaderErrorMessage[0]); } return ShaderID; } GLuint createProgram(const char * vertex_file_path,const char * fragment_file_path){ // Create the shaders GLuint VertexShaderID = createShader(vertex_file_path, GL_VERTEX_SHADER); GLuint FragmentShaderID = createShader(fragment_file_path, GL_FRAGMENT_SHADER); if( VertexShaderID == 0 || FragmentShaderID == 0 ){ return 0; } GLint Result = GL_FALSE; int InfoLogLength; // Link the program fprintf(stdout, "Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); if(!Result) { glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); std::vector<char> ProgramErrorMessage( fmax(InfoLogLength, int(1)) ); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); fprintf(stdout, "ProgramErrorMessage: %s\n", &ProgramErrorMessage[0]); } glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } #endif
true
db952332da110b2f39fb3690816013aa1539c929
C++
jknight1725/yahtzee17
/include/scoreSheet.h
UTF-8
916
3.15625
3
[]
no_license
#include <array> #include <iostream> #pragma once /// Array of 15 <int/bool> pairs corresponding to different yahtzee scores. /// bool indicates if the score sheet has already recorded the respective score /// sheet can read/write/tally/print its scores class ScoreSheet final { public: ScoreSheet() noexcept { //by default all scores set to zero for(auto& [points, available] : scores) { points = 0; available = true; } } int upperScore() const; int lowerScore() const; int totalScore() const; bool available(int index) const; void makeUnavailable(int index); int const& operator [] (int index) const {return scores[index].first;} int& operator[] (int index) {return scores[index].first;} friend std::ostream & operator<<(std::ostream & out, const ScoreSheet& sheet); private: std::array<std::pair<int, bool>, 15> scores; };
true
b9c4f21938b6432b9568fae4015f1e45d0ad59e5
C++
sedihub/project_euler
/problems_001-050/euler_46.cpp
UTF-8
1,912
3.875
4
[ "Apache-2.0" ]
permissive
/* PROBLEM: It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? SOLUTION: With a few helper classes we can quickly find the answer. ANSWER: 5777 **/ #include "iostream" #include "set" #include "iterator" #include "math.h" typedef unsigned long int ulint; bool is_prime(ulint n) { if (n == 2) return true; else if (n % 2 == 0) return false; else if (n == 3) return true; else if (n % 3 == 0) return false; else if (n == 5) return true; else if (n % 5 == 0) return false; else if (n == 7) return true; else if (n == 11) return true; else if (n == 13) return true; else if (n == 17) return true; else if (n == 19) return true; ulint k = 6; while (k * k <= n) { if (n % (k + 1) == 0) return false; if (n % (k + 5) == 0) return false; k += 6; } return true; } bool is_square(ulint n) { double d = sqrt( (double)n ); return d == floor(d); } int main() { std::set<ulint> primes; ulint n = 1; ulint odd_num; bool satisfies_golbach_conjecture = true; while (satisfies_golbach_conjecture) { odd_num = 2 * n + 1; if (is_prime(odd_num)) { primes.insert(odd_num); n++; } else { for (std::set<ulint>::iterator it = primes.begin(); it != primes.end(); it++) { if (is_square((odd_num - *it) / 2)) { n++; goto proceed; } } satisfies_golbach_conjecture = false; } proceed:; } std::cout << "Smallest odd composite that violates Goldbach's conjecture: " << odd_num << std::endl; return 0; }
true
ff3afa86d7d0df7a750e9ad188b78e234cf30483
C++
TanviSutar/ADS
/ADS-implememtation/graph1.cpp
UTF-8
2,882
3.421875
3
[]
no_license
#include<bits/stdc++.h> #define node1 first #define nodelist second #define node2 second.first #define weight second.second using namespace std; template<typename T> class Graph{ private: map< T, vector<pair<T, int>> > edges; public: void addEdge(T n1, T n2, int wght, bool bidirec = 1){ edges[n1].push_back(make_pair(n2, wght)); if(bidirec) edges[n2].push_back(make_pair(n1, wght)); } void display(map< T, vector<pair<T, int>> > edges){ cout<< "Node1 " <<"\t"<< "Node2" <<"\t" << "Weight"<<endl; for(auto a: edges){ for(auto n: a.second){ cout<< a.first <<"\t"<< n.first <<"\t"<< n.second << endl; } } } void bfs(T node1){ queue<T> que; que.push(node1); map<T, bool> visited; cout<<"Following is the bfs traversal:\n"; while(!que.empty()){ T curr = que.front(); que.pop(); visited[curr] = true; cout<<curr<<" "; for(auto var : edges[curr]){ if(!visited[var.first]) que.push(var.first); } } } void dfs_helper(T node1, map<T, bool> &visited, map< T, vector<pair<T, int>> > edges){ //cout<<node1<<"* "; visited[node1] = true; for(auto var : edges[node1]){ if(!visited[var.first]){ dfs_helper(var.first, visited, edges); } } } void dfs(T node1){ map<T, bool> visited; cout<<"Following is dfs traversal:\n"; dfs_helper(node1, visited, edges); } bool isStronglyConnected(T node){//kosaraju's algo if(edges.size() == 0) return false; map<T, bool> visited; dfs_helper(node,visited, edges); if(visited.size() != edges.size()) return false; map< T, vector<pair<T, int>> > dummy; for(auto a : edges){//form the reverse edges for(auto b : a.second){ dummy[b.first].push_back(make_pair(a.first, b.second)); } } visited.clear(); dfs_helper(node, visited, dummy); if(visited.size() == edges.size()) return true; return false; } }; int main(){ //no. of vertices //no. of edges //edge list along with weight int n; cin>>n; int e; cin>>e; Graph<int> g; for(int i=0; i<e; i++){ int x, y, w; cin >> x >> y >> w; g.addEdge(x, y, w, 0); } int tmp; cin>>tmp; cout<<"\nStrongly connected?: "<<g.isStronglyConnected(tmp)<<endl; return 0; }
true
d33c5bc0fd5903c418575b0ab0dd8b4e2412e109
C++
ddc-iot/instructor_master
/L12_HelloParticle/L12_02_HelloNightLight/src/L12_02_HelloNightLight.cpp
UTF-8
1,117
2.59375
3
[]
no_license
/******************************************************/ // THIS IS A GENERATED FILE - DO NOT EDIT // /******************************************************/ #include "Particle.h" #line 1 "c:/Users/IoT_Instructor/Documents/IoT/instructor_master/L12_HelloParticle/L12_02_HelloNightLight/src/L12_02_HelloNightLight.ino" /* * Project L12_02_HelloNightLight * Description: Create a night light using Argon * Author: Brian Rashap * Date: 7-DEC-2020 */ void setup(); void loop(); #line 8 "c:/Users/IoT_Instructor/Documents/IoT/instructor_master/L12_HelloParticle/L12_02_HelloNightLight/src/L12_02_HelloNightLight.ino" const int LEDPIN = D4; const int PHOTOPIN = A0; const int THRESHOLD = 100; int photoValue; int ledValue; unsigned int currentTime, lastTime; void setup() { pinMode(LEDPIN,OUTPUT); pinMode(PHOTOPIN,INPUT); } void loop() { photoValue = analogRead(A0); /* Part 1 - digitalWrite if(photoValue < THRESHOLD ) { digitalWrite(LEDPIN,HIGH); } else { digitalWrite(LEDPIN,LOW); } */ ledValue = map(photoValue,0,4096,255,0); analogWrite(LEDPIN,ledValue); }
true
f2065ce0face3a4cab2545144ddc981858607e68
C++
WaerjakSC/3DObligFebruary
/visualobject.cpp
UTF-8
875
3.03125
3
[]
no_license
#include "visualobject.h" #include <fstream> VisualObject::VisualObject() {} VisualObject::~VisualObject() { glDeleteVertexArrays(1, &mVAO); glDeleteBuffers(1, &mVBO); } void VisualObject::readFile(std::string filnavn) { std::ifstream inn; inn.open(filnavn.c_str()); if (inn.is_open()) { int n; Vertex vertex; inn >> n; mVertices.reserve(n); for (int i = 0; i < n; i++) { inn >> vertex; mVertices.push_back(vertex); } inn.close(); } } void VisualObject::writeFile(std::string filename) { for (auto i : mVertices) { std::ofstream file(filename.c_str()); if (file.is_open()) { file << i; file.close(); } else { std::cout << "Unable to open file\n"; } } }
true
b7d2c91a86ff199a6847b1d608d3662aa265c702
C++
epled/planner
/plan.cpp
UTF-8
1,452
3.28125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <ctime> #include <bits/stdc++.h> using namespace std; const string planfile = "plan.txt"; enum days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY}; string dayString[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; struct task{ int quarters; int repeats; string name; }; string dayToString(int day){ switch(day){ case 0: return "Sunday"; break; case 1: return "Monday"; break; case 2: return "Tuesday"; break; case 3: return "Wednesday"; break; case 4: return "Thursday"; break; case 5: return "Friday"; case 6: return "Saturday"; } } void addOneTask(int day, ofstream & fout){ struct task newTask; string input; cout << "Enter the name of your task: "<< endl; cin >> input; newTask. fout << dayString[day] << ": " << input << endl; return; } int main(){ ifstream fin; ofstream fout; fin.open(planfile); fout.open(planfile); vector <task> Sunday; vector <task> Monday; vector <task> Tuesday; vector <task> Wednesday; vector <task> Thursday; vector <task> Friday; vector <task> Saturday; addOneTask(MONDAY, fout); addOneTask(TUESDAY, fout); struct tm now = *localtime(0); fout << now.tm_year; }
true
d7cd025d091197736751cda49e4a56cd083d7087
C++
cwx5319019/demo1
/C++/老师笔记/day1/6命名空间.cpp
UTF-8
323
2.5625
3
[]
no_license
#include<iostream> int main(int argc,char* argv[]){ //命名空间 { using namespace std; //cerr << "hello" << endl; cout << "hello, world" << endl; } //都在std里面 //std::cerr << "hello" << std::endl; std::cout << "hello ,iotek"<< std::endl; return 0; }
true
e4ea4b0b6723fc53f3b48333f1c576b052ce44c1
C++
ttyang/sandbox
/sandbox/SOC/2007/signals/libs/dataflow/example/signals/simple_example.cpp
UTF-8
1,617
2.796875
3
[ "BSL-1.0" ]
permissive
// Copyright 2007 Stjepan Rajko. // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //[ simple_example #include <boost/dataflow/signals/component/storage.hpp> #include <boost/dataflow/signals/component/timed_generator.hpp> #include <boost/dataflow/signals/connection.hpp> #include "simple_example_components.hpp" using namespace boost; int main(int, char* []) { // For our data source, we will use timed_generator, // which creates its own thread and outputs it's stored value // at a specified time interval. We'll store a value of 0 to be sent out. // The signature void(double) specifies that the signal carries a double, // and that there is no return value. signals::timed_generator<void (double)> input(0); // Data processor and output: processor proc; output out; // ---Connect the dataflow network --------------------- // // ,---------. ,---------. ,---------. // | input | --> | proc | --> | out | // `---------' `---------' `---------' // // ----------------------------------------------------- input >>= proc >>= out; // If you prefer, you can also do: // connect(input, proc); // connect(proc, out); // Tell the source to start producing data, every 0.5s: input.enable(0.5); // take a little nap :-) boost::xtime xt; boost::xtime_get(&xt, boost::TIME_UTC); xt.sec += 10; boost::thread::sleep(xt); input.join(); return 0; } //]
true
f8162a3819c6662fece03a3783e1de43e11c54bb
C++
AarneL/Chessgame
/src/headers/object.hpp
UTF-8
370
2.765625
3
[]
no_license
#ifndef OBJECT_H #define OBJECT_H #include <SFML/Graphics.hpp> enum ObjectState { Normal = 0, Highlighted = 1, Selected = 2 }; class Object { public: ObjectState getState() const; bool isVisible() const; virtual void setState(ObjectState state) = 0; virtual void draw(sf::RenderWindow &window) = 0; bool drawObject; protected: ObjectState state; }; #endif
true
43bb05a5a1d8a2c8499b641b0419521e5a6a3106
C++
Synaxis/cppTrainning
/workFolder/problem1/main.cpp
UTF-8
708
3.609375
4
[]
no_license
#include <cstdlib> #include <iostream> #include <string> #include <vector> #include <sstream> #include <limits> int main() { std::string UserAge = "0"; // age is a string std::cout << "Enter your age : \n"; // printf getline(std::cin, UserAge); // console input and assign to UserAge int intAge = std::stoi(UserAge); // strconv UserAge string to intAge int if (intAge < 10){ std::cout << "Go to kindergarten\n"; } else if ((intAge >=10) || (intAge <= 16)){ std::cout << "Teenage\n"; } else if (intAge > 17) { std::cout << "You are too old to school! go to university\n"; } else { std::cout << "You are an adult\n"; } return 0; }
true
78c621e9c5f8d2d756ae11874412d25340444a39
C++
darren-moore/corruption
/src/src_Core/Core/math/Vector.h
UTF-8
4,343
3.65625
4
[]
no_license
#pragma once #include <array> #include <cassert> #include <string> #include <sstream> namespace math { // <size, datatype> template <size_t N, typename T> class Vector { public: Vector() : data_{} {} // Initializes to default values, usually 0. ~Vector() = default; // Simply deletes our array of data. Vector(const T& s) { for (size_t i = 0; i < N; ++i) { data_[i] = s; } } template <typename ...Args> Vector(Args... args) : data_{ static_cast<T>(args)... } {} template <typename T2> Vector(const Vector<N, T2>& v) { // Allows conversion, like making a float vector with ints. for (size_t i = 0; i < N; ++i) { data_[i] = static_cast<T>(v[i]); } }; //Vector(Vector<N, T>&& v) { // data_ = std::move(v.data_); //} static Vector<N, T> Ones() { Vector<N, T> onesVec; for (size_t i = 0; i < N; ++i) { onesVec.data_[i] = static_cast<T>(1); } return onesVec; } static Vector<N, T> Zero() { static Vector<N, T> zeroVec; for (size_t i = 0; i < N; ++i) { zeroVec.data_[i] = static_cast<T>(0); } return zeroVec; } T dot(const Vector<N, T>& rhs) const { T out = (*this)[0] * rhs[0]; for (size_t i = 1; i < N; ++i) { out += data_[i] * rhs[i]; } return out; } T norm() const { return static_cast<T>(sqrt(static_cast<double>(dot(*this)))); } T norm2() const { return dot(*this); } Vector<N, T> normed() const { return (*this) / norm(); } template <size_t M = N> typename std::enable_if<M == 2, Vector<2, T>>::type normal() const { return Vector<2, T>(-data_[1], data_[0]); } template <size_t M = N> typename std::enable_if<M == 3, Vector<3, T>>::type cross(const Vector<3, T>& b) const { const Vector<3, T>& a = (*this); return Vector<3, T>(a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]); } const size_t size() const { return N; } T* data() { return data_.data(); } Vector<N, T>& operator+=(const Vector<N, T>& rhs) { for (size_t i = 0; i < N; ++i) { data_[i] += rhs[i]; } return *this; } Vector<N, T>& operator-=(const Vector<N, T>& rhs) { for (size_t i = 0; i < N; ++i) { data_[i] -= rhs[i]; } return *this; } Vector<N, T> operator+(const Vector<N, T>& rhs) const { Vector<N, T> lhs(*this); lhs += rhs; return lhs; } Vector<N, T> operator-(const Vector<N, T>& rhs) const { Vector<N, T> lhs(*this); lhs -= rhs; return lhs; } Vector<N, T>& operator*=(const T& rhs) { for (size_t i = 0; i < N; ++i) { data_[i] *= rhs; } return *this; } Vector<N, T>& operator/=(const T& rhs) { for (size_t i = 0; i < N; ++i) { data_[i] /= rhs; } return *this; } Vector<N, T> operator*(const T& rhs) const { Vector<N, T> lhs(*(this)); lhs *= rhs; return lhs; } friend Vector<N, T> operator*(const T& lhs, const Vector<N, T>& rhs) { return rhs * lhs; } Vector<N, T> operator/(const T& rhs) const { Vector<N, T> lhs(*(this)); lhs /= rhs; return lhs; } Vector<N, T> operator-() const { return -1 * *(this); } bool operator==(const Vector<N, T>& rhs) const { for (size_t i = 0; i < N; ++i) { if (data_[i] != rhs[i]) { return false; } } return true; } bool operator!=(const Vector<N, T>& rhs) const { return !((*this) == rhs); } T& operator[](size_t n) { assert(n >= 0 && n < N); return data_[n]; } const T& operator[](size_t n) const { assert(n >= 0 && n < N); return data_[n]; } friend std::ostream& operator<<(std::ostream& os, const Vector<N, T>& v) { os << "("; for (size_t i = 0; i < N - 1; ++i) { os << v.data_[i] << ", "; } os << v.data_.back() << ")"; return os; } std::string toString() const { std::stringstream ss; ss << *this; return ss.str(); } private: std::array<T, N> data_; }; using Vec2d = Vector<2, double>; using Vec2f = Vector<2, float>; using Vec2i = Vector<2, int>; using Vec2u = Vector<2, unsigned int>; using Vec3d = Vector<3, double>; using Vec3f = Vector<3, float>; using Vec3i = Vector<3, int>; using Vec3u = Vector<3, unsigned int>; using Vec4d = Vector<4, double>; using Vec4f = Vector<4, float>; using Vec4i = Vector<4, int>; using Vec4u = Vector<4, unsigned int>; }
true
55c6261883376340bffe1c3207714bcc79369be7
C++
Elsyrian/acmudec
/livearchive/2865.cpp
UTF-8
1,555
2.984375
3
[]
no_license
#include<iostream> /************************************************************************************************************************* * 2865 - Bikers Trip Odometer * http://livearchive.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=166&problem=866 * * Classification: calculos de distancia y velocidad * * Author: * Mauricio Echavarria <mechavarria@udec.cl> * * Description: * * un odometro es un instrumento usado en rutas que sirve para medir distancia, velocidad, tiempo de viaje, * etc. se pide programar un odometro para ser instalado en una bicicleta, donde los datos de entrada son * el aro de la rueda en pulgadas, el numero de vueltas que dio la rueda durante el viaje y la duracion de * este en segundos. los datos de salida son la distancia recorrida en millas y la veolocidad promedio en * millas por hora, ambos datos aproximados en 2 decimales. * */ using namespace std; int main(int argc,char *argv[]){ float p=3.1415927; float diametro,vueltas,tiempo,radio,perimetro,distancia,velocidad; int counter=1; cout.precision(2); while(1){ cin >> diametro; cin >> vueltas; cin >> tiempo; if(vueltas==0) return 0; radio = diametro/2; perimetro = 2*p*radio; distancia = perimetro * vueltas / 63360; velocidad = 3600 * distancia / tiempo; cout << "Trip #" << counter++ << ": " << fixed << distancia << " " << fixed << velocidad << endl; } return 0; }
true
b62c1e8c30e5a178d48b62ddb1ff78c36ac73f20
C++
xh286/leetcode
/366-Find-Leaves-of-Binary-Tree/solution.cpp
UTF-8
897
3.21875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: int processNode(TreeNode* p, vector<vector<int>>& r) { // return dist2leaf. For null p, do nothing, return -1. // For non-null, dist2leaf = max(processNode(p->left, r), processNode(p->right, r))+1. // insert into r[dist2leaf], then return dist2leaf. if(!p) return -1; int dist2leaf = max(processNode(p->left, r), processNode(p->right, r)) + 1; while(dist2leaf>=r.size()) r.push_back(vector<int>()); r[dist2leaf].push_back(p->val); return dist2leaf; } public: vector<vector<int>> findLeaves(TreeNode* root) { vector<vector<int>> r; processNode(root, r); return r; } };
true
5785eb54a6f3ba5515a2acfc7a89ee45b28a24c2
C++
accountos/LeetCodeLearning
/Array/zhanchengguo/0610-链表反转/main.cpp
UTF-8
2,090
4.3125
4
[ "MIT" ]
permissive
#include <iostream> struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *reverseList(ListNode *head); ListNode *reverseList2(ListNode *head); int main() { // 双指针 ListNode *a = new ListNode(1); ListNode *b = new ListNode(2); ListNode *c = new ListNode(3); ListNode *d = new ListNode(4); a->next = b; b->next = c; c->next = d; d->next = NULL; ListNode *result = reverseList(a); while (result != nullptr) { printf("method 1 value is %d\n", result->val); result = result->next; } // 递归 ListNode *e = new ListNode(1); ListNode *f = new ListNode(2); ListNode *g = new ListNode(3); ListNode *s = new ListNode(4); e->next = f; f->next = g; g->next = s; s->next = NULL; ListNode *result2 = reverseList2(e); while (result2 != nullptr) { printf("method 2 value is %d\n", result2->val); result2 = result2->next; } return 0; } /** * 思路:双指针的方式实现反转 * 1、定义两个指针分别指向前一个节点和当前节点 * 2、每次让当前节点的next指向前一个节点,实现局部反转 * 3、局部反转后,两指针向前移位 * 4、循环执行上述过程,直至当前节点为null * @return */ ListNode *reverseList(ListNode *head) { ListNode *pre = NULL; ListNode *current = head; while (current != NULL) { ListNode *next = current->next; current->next = pre; pre = current; current = next; } return pre; } /** * 思路:递归 * 从当前节点递归到最后一个节点,最后一个节点就是反转的头节点 * 每次返回,都让当前节点都next节点指向当前节点,当前节点指向null * 直至这个递归结束 * @return */ ListNode *reverseList2(ListNode *head) { if (head == NULL || head->next == NULL) { return head; } ListNode *lastNode = reverseList2(head->next); head->next->next = head; head->next = NULL; return lastNode; }
true
b5e82277d1aa712e6f195eab2bb8af783e719e9d
C++
Givemeurcookies/Snow-drone
/processor.ino
UTF-8
2,237
3.21875
3
[]
no_license
//Arduino Control int incomingByte = 0; // for incoming serial data int lastByte = 0; const int pwmA = 3; const int pwmB = 11; const int brakeA = 9; const int brakeB = 8; const int dirA = 12; const int dirB = 13; void setup() { // initialize the digital pin as an output: Serial.begin(9600); //Setup Channel A pinMode(dirA, OUTPUT); //Initiates Motor Channel A pin pinMode(brakeA, OUTPUT); //Initiates Brake Channel A pin //Setup Channel B pinMode(dirB, OUTPUT); //Initiates Motor Channel A pin pinMode(brakeB, OUTPUT); //Initiates Brake Channel A pin } // the loop() method runs over and over again, // as long as the Arduino has power void Move(int aDir,int bDir,int aSpeed=255,int bSpeed=255){ //Motor A digitalWrite(dirA, aDir); //Sets direction digitalWrite(brakeA, LOW); //Removes break analogWrite(pwmA, aSpeed); //Sets speed (max 255) //Motor B digitalWrite(dirB, bDir); //Sets direction digitalWrite(brakeB, LOW); //Removes break analogWrite(pwmB, bSpeed); //Sets speed (max 255) } void Turn(int turningDir, int pwm=255){ //Motor A digitalWrite(dirA, turningDir); //Sets direction digitalWrite(brakeA, LOW); analogWrite(pwmA, pwm); //Motor B digitalWrite(dirB, turningDir); //Sets direction digitalWrite(brakeB, LOW); analogWrite(pwmB, pwm); //Sets speed (max 255) } void stopAll(){ //Motor A digitalWrite(brakeA, HIGH); //Enables break for MotorA analogWrite(pwmA, 0); //Motor B digitalWrite(brakeB, HIGH); //Enables break for MotorB analogWrite(pwmB, 0); } void loop(){ if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); if (incomingByte != lastByte && incomingByte != 10) { Serial.println(incomingByte); lastByte = incomingByte; switch(incomingByte){ case 48: Move(0,1); //0 case 49: Move(1,0); //1 case 50: Turn(1); //2 case 51: Turn(0); //3 case 52: stopAll(); //4 break; case 53: //5 //ledStatus = digitalRead(inPin); //Serial.println(ledStatus); //ledStatus = !ledStatus; //digitalWrite(ledPin, ledStatus) break; } } } }
true
274e69597cbefa631f869256679eeb016cf6eb5e
C++
p-adic/cpp
/Mathematics/Arithmetic/Mod/Function/Euler/a_Body.hpp
UTF-8
3,179
2.828125
3
[ "MIT" ]
permissive
// c:/Users/user/Documents/Programming/Mathematics/Arithmetic/Mod/Function/Euler/a_Body.hpp #pragma once #include "a.hpp" #include "../../../Prime/Constexpr/a_Body.hpp" #include "../CRT/a_Body.hpp" #include "../../../Prime/a_Body.hpp" template <typename INT> inline INT EulerFunction( const INT& n ) { vector<INT> P{}; vector<INT> exponent{}; return EulerFunction( n , P , exponent ); } template <typename INT , INT val_limit , int length_max> inline INT EulerFunction( const PrimeEnumeration<INT,val_limit,length_max>& prime , const INT& n ) { vector<INT> P{}; vector<INT> exponent{}; return EulerFunction( prime , n , P , exponent ); } template <typename INT> INT EulerFunction( const INT& n , vector<INT>& P , vector<INT>& exponent ) { SetPrimeFactorisation( n , P , exponent ); EULER_FUNCTION; } template <typename INT , INT val_limit , int length_max> INT EulerFunction( const PrimeEnumeration<INT,val_limit,length_max>& prime , const INT& n , vector<INT>& P , vector<INT>& exponent ) { SetPrimeFactorisation( prime , n , P , exponent ); EULER_FUNCTION; } template <typename INT , INT val_limit , int length_max , int size , typename INT2> void MemoriseEulerFunction( const PrimeEnumeration<INT,val_limit,length_max>& prime , INT2 ( &memory )[size] ) { static INT quotient[size]; for( int n = 1 ; n < size ; n++ ){ memory[n] = quotient[n] = n; } for( int i = 0 ; i < prime.m_length ; i++ ){ const INT& p_i = prime.m_val[i]; int n = 0; while( ( n += p_i ) < size ){ INT2& memory_n = memory[n]; INT& quotient_n = quotient[n]; memory_n -= memory_n / p_i; while( ( quotient_n /= p_i ) % p_i == 0 ){} } } for( int n = val_limit ; n < size ; n++ ){ const INT& quotient_n = quotient[n]; if( quotient_n != 1 ){ INT2& memory_n = memory[n]; memory_n -= memory_n / quotient_n; } } return; } template <typename INT> inline INT CarmichaelFunction( const INT& n ) { vector<INT> P{}; vector<INT> exponent{}; vector<INT> P_power{}; return CarmichaelFunction( n , P , exponent , P_power ); } template <typename INT , INT val_limit , int length_max> inline INT CarmichaelFunction( const PrimeEnumeration<INT,val_limit,length_max>& prime , const INT& n ) { vector<INT> P{}; vector<INT> exponent{}; vector<INT> P_power{}; return CarmichaelFunction( prime , n , P , exponent , P_power ); } template <typename INT> INT CarmichaelFunction( const INT& n , vector<INT>& P , vector<INT>& exponent , vector<INT>& P_power ) { vector<INT> P{}; vector<INT> exponent{}; vector<INT> P_power{}; SetPrimeFactorisation( n , P , exponent , P_power ); CARMICHAEL_FUNCTION; } template <typename INT , INT val_limit , int length_max> INT CarmichaelFunction( const PrimeEnumeration<INT,val_limit,length_max>& prime , const INT& n , vector<INT>& P , vector<INT>& exponent , vector<INT>& P_power ) { vector<INT> P{}; vector<INT> exponent{}; vector<INT> P_power{}; SetPrimeFactorisation( prime , n , P , exponent , P_power ); CARMICHAEL_FUNCTION; }
true
f208634b28b03daf0e583e509fa3517f1f812f93
C++
williamliao28/SimToolbox
/MPI/MixPairInteraction.hpp
UTF-8
12,000
2.640625
3
[ "Apache-2.0" ]
permissive
/** * @file MixPairInteraction.hpp * @author wenyan4work (wenyan4work@gmail.com) * @brief interaction for two FDPS systems of different particle types * @version 0.1 * @date 2019-01-10 * * @copyright Copyright (c) 2019 * */ #ifndef MIXPAIRINTERACTION_HPP_ #define MIXPAIRINTERACTION_HPP_ #include "FDPS/particle_simulator.hpp" #include "Util/GeoCommon.h" #include <memory> #include <type_traits> #include <vector> #include <mpi.h> #include <omp.h> /** * Note about RSearch: * getRSearch() not needed for FP type * getRSearch() necessary for EPI type if Gather * getRSearch() necessary for EPJ type if Scatter * getRSearch() necessary for BOTH EPI and EPJ types if Symmetry * getRSearch() should not return zero in any cases * */ /** * @brief Mix Full Particle type. * One MixFP is created at every location of src and trg systems. * number of MixFP = number of src + number of trg * the actual behavior of one MixFP is controlled by the trgFlag switch * the field pos should always be valid * epTrg/epSrc data is valid only when the corresponding flag is set true * check before return * @tparam EPT * @tparam EPS */ template <class EPT, class EPS> struct MixFP { bool trgFlag; ///< switch. if true, this MixFP represents a trg particle. double maxRSearch; EPT epTrg; ///< data for trg type. valid if trgFlag==true EPS epSrc; ///< data for src type. valid if trgFlag==false /** * @brief Get position. * required interface for FDPS * * @return PS::F64vec3 */ PS::F64vec3 getPos() const { return trgFlag ? epTrg.getPos() : epSrc.getPos(); } /** * @brief Set position * required interface for FDPS * * @param newPos */ void setPos(const PS::F64vec3 &newPos) { trgFlag ? epTrg.setPos(newPos) : epSrc.setPos(newPos); } int getGid() const { return trgFlag ? epTrg.getGid() : epSrc.getGid(); } // void copyFromForce(Force &f) { force = f; } PS::F64 getRSearch() const { return trgFlag ? epTrg.getRSearch() : epSrc.getRSearch(); } }; /** * @brief EssentialParticleI (trg) type for use in FDPS tree * contains only target data. invalid and unsed if trgFlag==false * @tparam EPT */ template <class EPT> struct MixEPI { bool trgFlag; double maxRSearch; EPT epTrg; double getRSearch() const { return trgFlag ? epTrg.getRSearch() : maxRSearch * 0.5; } int getGid() const { return trgFlag ? epTrg.getGid() : GEO_INVALID_INDEX; } PS::F64vec3 getPos() const { return epTrg.getPos(); } void setPos(const PS::F64vec3 &newPos) { epTrg.setPos(newPos); } template <class EPS> void copyFromFP(const MixFP<EPT, EPS> &fp) { trgFlag = fp.trgFlag; maxRSearch = fp.maxRSearch; if (trgFlag) { epTrg = fp.epTrg; } else { // if not a trg particle, pos should be always valid setPos(fp.getPos()); } } }; /** * @brief EssentialParticleJ (src) type for use in FDPS tree * contains only src data. invalid and unsed if srcFlag==false * @tparam EPS */ template <class EPS> struct MixEPJ { bool srcFlag; double maxRSearch; EPS epSrc; double getRSearch() const { return srcFlag ? epSrc.getRSearch() : maxRSearch * 0.5; } int getGid() const { return srcFlag ? epSrc.getGid() : GEO_INVALID_INDEX; } PS::F64vec3 getPos() const { return epSrc.getPos(); } void setPos(const PS::F64vec3 &newPos) { epSrc.setPos(newPos); } template <class EPT> void copyFromFP(const MixFP<EPT, EPS> &fp) { srcFlag = !fp.trgFlag; maxRSearch = fp.maxRSearch; if (srcFlag) { epSrc = fp.epSrc; } else { // if not a src particle, pos should be always valid setPos(fp.getPos()); } } }; /** * @brief An example interaction class to be passed to computeForce() function * * @tparam EPT * @tparam EPS * @tparam Force */ template <class EPT, class EPS, class Force> class CalcMixPairForceExample { public: void operator()(const MixEPI<EPT> *const trgPtr, const PS::S32 nTrg, const MixEPJ<EPS> *const srcPtr, const PS::S32 nSrc, Force *const mixForcePtr) { for (int t = 0; t < nTrg; t++) { auto &trg = trgPtr[t]; if (!trg.trgFlag) { continue; } for (int s = 0; s < nSrc; s++) { auto &src = srcPtr[s]; if (!src.srcFlag) { continue; } // actual interaction force(trg, src, mixForcePtr[t]); } } } }; /** * @brief interaction between two FDPS systems of different particle types * This class does not exchange particles between mpi ranks * * @tparam FPT * @tparam FPS * @tparam EPT * @tparam EPS * @tparam Force */ template <class FPT, class FPS, class EPT, class EPS, class Force> class MixPairInteraction { static_assert(std::is_trivially_copyable<FPT>::value, "FPT is potentially unsafe for memcpy\n"); static_assert(std::is_trivially_copyable<FPS>::value, "FPS is potentially unsafe for memcpy\n"); static_assert(std::is_trivially_copyable<EPT>::value, "EPT is potentially unsafe for memcpy\n"); static_assert(std::is_trivially_copyable<EPS>::value, "EPS is potentially unsafe for memcpy\n"); static_assert(std::is_trivially_copyable<Force>::value, "Force is potentially unsafe for memcpy\n"); static_assert(std::is_default_constructible<FPT>::value, "FPT is not defalut constructible\n"); static_assert(std::is_default_constructible<FPS>::value, "FPS is not defalut constructible\n"); static_assert(std::is_default_constructible<EPT>::value, "EPT is not defalut constructible\n"); static_assert(std::is_default_constructible<EPS>::value, "EPS is not defalut constructible\n"); static_assert(std::is_default_constructible<Force>::value, "Force is not defalut constructible\n"); // result std::vector<Force> forceResult; ///< computed force result // internal FDPS stuff using EPIType = MixEPI<EPT>; using EPJType = MixEPJ<EPS>; using FPType = MixFP<EPT, EPS>; static_assert(std::is_trivially_copyable<EPIType>::value, ""); static_assert(std::is_trivially_copyable<EPJType>::value, ""); static_assert(std::is_trivially_copyable<FPType>::value, ""); static_assert(std::is_default_constructible<EPIType>::value, ""); static_assert(std::is_default_constructible<EPJType>::value, ""); static_assert(std::is_default_constructible<FPType>::value, ""); using SystemType = typename PS::ParticleSystem<FPType>; using TreeType = typename PS::TreeForForceShort<Force, EPIType, EPJType>::Scatter; // gather mode, search radius determined by EPI // scatter mode, search radius determined by EPJ // symmetry mode, search radius determined by larger of EPI and EPJ SystemType systemMix; ///< mixed FDPS system std::unique_ptr<TreeType> treeMixPtr; ///< tree for pair interaction int numberParticleInTree; ///< number of particles in tree int nLocalTrg, nLocalSrc; public: /** * @brief Construct a new MixPairInteraction object * */ MixPairInteraction() = default; /** * @brief initializer * must be called once after constructor * * @param systemTrg_ * @param systemSrc_ * @param dinfo_ */ void initialize() { // systemTrgPtr = systemTrgPtr_; // systemSrcPtr = systemSrcPtr_; // dinfoPtr = dinfoPtr_; systemMix.initialize(); numberParticleInTree = 0; }; /** * @brief Destroy the MixPairInteraction object * */ ~MixPairInteraction() = default; /** * @brief update systemMix * */ void updateSystem(const PS::ParticleSystem<FPT> &systemTrg, const PS::ParticleSystem<FPS> &systemSrc, PS::DomainInfo &dinfo); /** * @brief update treeMix * */ void updateTree(); /** * @brief Set the MaxRSearch looping over all obj in systemMix * */ void setMaxRSearch(); /** * @brief print the particles in systemMix * for debug use * */ void dumpSystem(); /** * @brief calculate interaction with CalcMixForce object * * @tparam CalcMixForce * @param calcMixForceFtr */ template <class CalcMixForce> void computeForce(CalcMixForce &calcMixForceFtr, PS::DomainInfo &dinfo); /** * @brief Get the calculated force * * @return const std::vector<Force>& */ const std::vector<Force> &getForceResult() { return forceResult; } }; template <class FPT, class FPS, class EPT, class EPS, class Force> void MixPairInteraction<FPT, FPS, EPT, EPS, Force>::updateSystem(const PS::ParticleSystem<FPT> &systemTrg, const PS::ParticleSystem<FPS> &systemSrc, PS::DomainInfo &dinfo) { nLocalTrg = systemTrg.getNumberOfParticleLocal(); nLocalSrc = systemSrc.getNumberOfParticleLocal(); // fill systemMix systemMix.setNumberOfParticleLocal(nLocalTrg + nLocalSrc); #pragma omp parallel for for (size_t i = 0; i < nLocalTrg; i++) { systemMix[i].epTrg.copyFromFP(systemTrg[i]); systemMix[i].trgFlag = true; // systemMix[i].setPos(systemTrg[i].getPos()); } #pragma omp parallel for for (size_t i = 0; i < nLocalSrc; i++) { const int mixIndex = i + nLocalTrg; systemMix[mixIndex].epSrc.copyFromFP(systemSrc[i]); systemMix[mixIndex].trgFlag = false; // systemMix[mixIndex].setPos(systemSrc[i].getPos()); } systemMix.adjustPositionIntoRootDomain(dinfo); // set maxRSearch setMaxRSearch(); } template <class FPT, class FPS, class EPT, class EPS, class Force> void MixPairInteraction<FPT, FPS, EPT, EPS, Force>::dumpSystem() { const int nLocalMix = systemMix.getNumberOfParticleLocal(); for (int i = 0; i < nLocalMix; i++) { const auto &pos = systemMix[i].getPos(); printf("%d,%d,%lf,%lf,%lf\n", systemMix[i].trgFlag, systemMix[i].getGid(), pos.x, pos.y, pos.z); } } template <class FPT, class FPS, class EPT, class EPS, class Force> void MixPairInteraction<FPT, FPS, EPT, EPS, Force>::setMaxRSearch() { const int nLocalMix = systemMix.getNumberOfParticleLocal(); double maxRSearchMix = 0; #pragma omp parallel for reduction(max : maxRSearchMix) for (int i = 0; i < nLocalMix; i++) { maxRSearchMix = std::max(maxRSearchMix, systemMix[i].getRSearch()); } MPI_Allreduce(MPI_IN_PLACE, &maxRSearchMix, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); // printf("Global maxRSearch %lf\n", maxRSearchMix); #pragma omp parallel for for (int i = 0; i < nLocalMix; i++) { systemMix[i].maxRSearch = maxRSearchMix; } } template <class FPT, class FPS, class EPT, class EPS, class Force> void MixPairInteraction<FPT, FPS, EPT, EPS, Force>::updateTree() { const int nParGlobal = systemMix.getNumberOfParticleGlobal(); // make a large enough tree if (!treeMixPtr || (nParGlobal > numberParticleInTree * 1.5)) { treeMixPtr.reset(); treeMixPtr = std::make_unique<TreeType>(); // build tree // be careful if tuning the tree default parameters treeMixPtr->initialize(2 * nParGlobal); numberParticleInTree = nParGlobal; } } template <class FPT, class FPS, class EPT, class EPS, class Force> template <class CalcMixForce> void MixPairInteraction<FPT, FPS, EPT, EPS, Force>::computeForce(CalcMixForce &calcMixForceFtr, PS::DomainInfo &dinfo) { // dumpSystem(); treeMixPtr->calcForceAll(calcMixForceFtr, systemMix, dinfo); forceResult.resize(nLocalTrg); #pragma omp parallel for for (int i = 0; i < nLocalTrg; i++) { forceResult[i] = treeMixPtr->getForce(i); } } #endif
true
dcdfa1d370081acd4e2c325b2160515cd961a715
C++
RayYoh/CppPrimerPlus
/C++PrimerPlus/Ex8.5.cpp
UTF-8
981
3.796875
4
[]
no_license
#include<iostream> using namespace std; template<typename T> T maxn(T arr[], int n ); template<> char * maxn(char * arr[], int n); int main() { int arr1[6] = { 1,2,3,4,5,6 }; double arr2[4] = { 2.1,3.2,5.4,6.5 }; int max_int = maxn(arr1,6); double max_double = maxn(arr2,4); cout << max_int << endl; cout << max_double << endl; char a[] = "a", b[] = "ab", c[] = "abc", d[] = "abcd", e[] = "abcde"; char * arr3[5] = { a,b,c,d,e }; char * max_add = maxn(arr3, 5); cout << static_cast <const void *>(arr3[4]) << endl; cout << static_cast <const void *>(max_add) << endl; return 0; } template<typename T> T maxn(T arr[], int n) { T max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } template<> char * maxn(char * arr[], int n) { char * max = arr[0]; int max_len = strlen(arr[0]); for (int i = 1; i < n; i++) { if (strlen(arr[i]) > max_len) { max = arr[i]; max_len = strlen(arr[i]); } } return max; }
true
cf9b95086e94210394d21a3124b431b131e42a4a
C++
skyfeature/cautious-potato
/minimum Steps To One.cpp
UTF-8
432
2.984375
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int n, ar[100000]; int min_num_steps(int n){ ar[1] = 0; for (int i = 2; i <= n; i++){ ar[i] = 1 + ar[i-1]; if (i%2 == 0){ ar[i] = min(ar[i], 1 + ar[i/2]); } if (i%3 == 0){ ar[i] = min(ar[i], 1 + ar[i/3]); } } return ar[n]; } int main(){ cin >> n; memset(ar, -1, sizeof(ar)); cout << min_num_steps(n) << "\n"; return 0; }
true
4d1aec00ff7714b73b489af09b9355bc94eba099
C++
artintel/Learning_Project
/设计模式/designpattern/factory1.cpp
UTF-8
998
3.296875
3
[]
no_license
#include <string> // 实现导出数据的接口, 导出数据的格式包含 xml,json,文本格式txt 后面可能扩展excel格式csv class IExport { public: virtual bool Export(const std::string &data) = 0; virtual ~IExport(){} }; class ExportXml : public IExport { public: virtual bool Export(const std::string &data) { return true; } }; class ExportJson : public IExport { public: virtual bool Export(const std::string &data) { return true; } }; class ExportTxt : public IExport { public: virtual bool Export(const std::string &data) { return true; } }; // =====1 int main() { std::string choose/* = */; if (choose == "txt") { IExport *e = new ExportTxt(); e->Export("hello world"); } else if (choose == "json") { IExport *e = new ExportJson(); e->Export("hello world"); } else if (choose == "xml") { IExport *e = new ExportXml(); e->Export("hello world"); } }
true
835ec9ae40ed8e37eba64e5f9a852ba92a594ded
C++
logic-life/C-learning
/pointer/passapointertoafunction.cpp
UTF-8
385
3.375
3
[]
no_license
#include <iostream> void getSeconds(unsigned long *pair); int main() { //无法使用空地址的指针变量由函数进行改变,空地址的指针指向内存空间不存在 unsigned long time_now; getSeconds(&time_now); std::cout << "输出当前时间:" << time_now << std::endl; return 0; } void getSeconds(unsigned long *pair) { *pair = time(NULL); }
true
a7cb2a288f12079ea59238230979754fb98b71ba
C++
gwanhyeon/algorithm_study
/beakjoon_algorithm/beakjoon_algorithm/CodingTestExam/Unix_Programming_hw1_kgh.cpp
UTF-8
11,702
3.390625
3
[]
no_license
// // Unix_Programming_hw1_kgh.cpp // Created by kgh on 5/4/2019. // Copyright © 2019 kgh. All rights reserved. #include <stdio.h> #include <iostream> #include <string.h> #include <fstream> #include <string> #include <vector> #include <sstream> #include <istream> #include <algorithm> #include <stdlib.h> // malloc, free 함수가 선언된 헤더 파일 using namespace std; // 학생 구조체 선언(변수: lastname,firstname,ssn,score1,2,3,4,5, grade, avg) typedef struct _Student{ char lastname[20]; char firstname[20]; char ssn[20]; char score1[5]; char score2[5]; char score3[5]; char score4[5]; char score5[5]; char grade[20]; float avg; }Student; // ## 1.함수 선언 ## // Insertion_Show 함수 : 새로운 데이터베이스 삽입이후에 출력시켜주는 함수 void Insertion_Show(Student *st, int cnt); // Sort_Show 함수 : 정렬된 이후에 구조체 값 출력시켜주는 함수 void Sort_Show(Student *st,int cnt); // Current 함수: 현재 데이터베이스 상태를 출력해주는 함수 void Current_Show(Student *st,int cnt); // New_Student_Create : 새로운 파일을 읽어들여 구조체에 추가 시키는 함수 int New_Student_Create(Student *st,int cnt); // Grade_Show : 성적 출력 함수 void Grade_Show(Student *st,int cnt); // ## 1. 함수구현 ## void Grade_Show(Student *st,int cnt){ char str[10]; // 등수값을 받기위한 변수 int num; // 몇등인지 파악 하기 위한 변수 cout << "===============================================================================\n"; cout << "KNUT 의왕캠퍼스 성적 출력 프로그램" << "\n"; cout << "등수(평균기준)를 입력하시면 해당 학생의 이름, 학번, 평균이 출력됩니다" << "\n"; cout << "원하는 등수를 보고 싶으시면 등수를 입력하세요.종료를 원하시면 Q를 입력하세요" << "\n"; cout << "프로그램을 종료하시는순간 새파일에서 데이터베이스가 추가 및 목록이 생성 됩니다." << "\n"; cout << "프로그램을 종료를 원하시면 Q를 입력하세요" << "\n"; cout << "===============================================================================\n"; //등수(평균기준)를 입력받고, 해당 학생의 이름, 학번, 평균을 출력시키는 기능 while(true){ cin >> str; num = atoi(str); // "Q"일경우 종료 if (!strcmp(str,"Q")){ break; } // 이름, 학번, 평균 출력 if(num < cnt-1 ){ cout << st[num].lastname << " "; cout << st[num].firstname << " "; cout << st[num].ssn << " "; cout << st[num].avg << endl; // 데이터베이스에 없는 값일 경우 재입력 }else{ cout << "해당 등수에 드는 학생이 없습니다." << endl; cout << "다시 입력 하세요." << endl; } } cout << "\n"; } // Sort_Show 함수 : 정렬된 이후에 구조체 값 출력시켜주는 함수 void Sort_Show(Student *st,int cnt){ cout << "===============================================================================\n"; cout << "===================유닉스프로그래밍 중간/기말고사 성적순==================================\n"; cout << "===============================================================================\n"; // 성적순으로 정렬된 값을 출력시켜주기위한 반복문 for(int i=0; i<cnt-1; i++){ cout << st[i].lastname <<" "; cout << st[i].firstname <<" "; cout << st[i].ssn << " "; cout << st[i].avg << " \n"; } cout << "\n"; } // Current 함수: 현재 데이터베이스 상태를 출력해주는 함수 void Current_Show(Student *st,int cnt){ cout << st[cnt].lastname <<" "; cout << st[cnt].firstname <<" "; cout << st[cnt].ssn << " "; cout << st[cnt].score1 <<" "; cout << st[cnt].score2 <<" "; cout << st[cnt].score3 <<" "; cout << st[cnt].score4 <<" "; cout << st[cnt].score5 <<" "; cout << st[cnt].grade <<" "; cout << st[cnt].avg << " \n"; } // Sort_Show 함수 : 정렬된 이후에 구조체 값 출력시켜주는 함수 void Sort(Student *st, int cnt) { Student tmp; // Student 구조체에 잠시 담을 임시 구좇 for (int i = 0; i < cnt; i++) { for (int j = 1; j < cnt; j++) { // 값 비교후 정렬 시간복잡도 면에서는 효율적이진 않음. if (st[j-1].avg < st[j].avg) { tmp = st[j - 1]; st[j - 1] = st[j]; st[j] = tmp; } } } } // New_Student_Create : 새로운 파일을 읽어들여 구조체에 추가 시키는 함수 int New_Student_Create(Student *st,int cnt){ // Student* st_new = (Student*)malloc( sizeof(Student)); string filePath = "/Users/kgh/Development/Algorithm_CodingTest/algorithm_study/beakjoon_algorithm/beakjoon_algorithm/grades1.csv"; ifstream openFile(filePath.data()); cnt =0; // 문자열에 "\0값을 제거하기위함\" if(openFile.is_open() ){ string line; // FILE에 한줄씩 읽어 들인다. while(getline(openFile, line)){ // string to char* vector<char> writable(line.begin(), line.end()); writable.push_back('\0'); char* ptr = &writable[0]; // strtok으로 문자열 자르기 char *ptr_tok = strtok(ptr, " \","); // " " 공백 문자를 기준으로 문자열을 자름, 포인터 반환 int i = 0; // 값을 임시 저장하기 위한 변수 char *store[30]; while (ptr_tok != NULL) // 자른 문자열이 나오지 않을 때까지 반복 { store[i] = ptr_tok; i++; ptr_tok = strtok(NULL," \","); } i =0; //출력 if(cnt == 0){ cout << "===============================================================================\n"; cout << "===================새로운 파일 데이터입니다.==================================\n"; cout << "===============================================================================\n"; cout << "lastName" << " "; cout << "firstName" << " "; cout << "SSN" << " "; cout << "test1" << " "; cout << "test2" << " "; cout << "test3" << " "; cout << "test4" << " "; cout << "final" << " "; cout << "Grade" << " "; cout << "Avg" << "\n"; }else{ // string 값 copy strcpy(st[cnt].lastname,store[i++]); strcpy(st[cnt].firstname,store[i++]); strcpy(st[cnt].ssn,store[i++]); strcpy(st[cnt].score1,store[i++]); strcpy(st[cnt].score2,store[i++]); strcpy(st[cnt].score3,store[i++]); strcpy(st[cnt].score4,store[i++]); strcpy(st[cnt].score5,store[i++]); strcpy(st[cnt].grade,store[i++]); float temp_avg = ((atof(st[cnt].score1) + atof(st[cnt].score2) + atof(st[cnt].score3) + atof(st[cnt].score4) + atof(st[cnt].score5)) / 5); st[cnt].avg = temp_avg; Current_Show(st,cnt); } cnt++; } } cout << "\n"; return cnt; } int main(void){ // Student *st = (Student*)malloc(sizeof(Student)); int Student_Num = 100; Student *st = (Student*)malloc(sizeof(Student)*Student_Num); Student *st_new = (Student*)malloc(sizeof(Student)*Student_Num); // Student st[100]; string filePath = "/Users/kgh/Development/Algorithm_CodingTest/algorithm_study/beakjoon_algorithm/beakjoon_algorithm/grades.csv"; // read File ifstream openFile(filePath.data()); // 1. 파일 오픈 int cnt=0; if( openFile.is_open() ){ // csv File Read string line; // FILE에 한줄씩 읽어 들인다. while(getline(openFile, line)){ // string to char* vector<char> writable(line.begin(), line.end()); writable.push_back('\0'); char* ptr = &writable[0]; // // | , 기준으로 값을 strtok시켜준다. char *ptr_tok = strtok(ptr, " \","); // " " 공백 문자를 기준으로 문자열을 자름, 포인터 반환 string str; int i = 0; // string 값을 담기 위한 변수 char *store[30]; // | , 기준으로 값을 strtok시켜준다. while (ptr_tok != NULL) // 자른 문자열이 나오지 않을 때까지 반복 { store[i] = ptr_tok; i++; ptr_tok = strtok(NULL," \","); } i =0; //출력 if(cnt == 0){ cout << "===============================================================================\n"; cout << "===================유닉스프로그래밍 중간/기말고사 성적==================================\n"; cout << "===============================================================================\n"; cout << "lastName" << "\t"; cout << "firstName" << "\t"; cout << "SSN" << " \t"; cout << "test1" << "\t"; cout << "test2" << "\t"; cout << "test3" << "\t"; cout << "test4" << "\t"; cout << "final" << "\t"; cout << "Grade" << "\t"; cout << "Avg" << "\n"; }else{ // store에 값을 담아서 st구조체에 값을 넣어준다. strcpy(st[cnt].lastname,store[i++]); strcpy(st[cnt].firstname,store[i++]); strcpy(st[cnt].ssn,store[i++]); strcpy(st[cnt].score1,store[i++]); strcpy(st[cnt].score2,store[i++]); strcpy(st[cnt].score3,store[i++]); strcpy(st[cnt].score4,store[i++]); strcpy(st[cnt].score5,store[i++]); strcpy(st[cnt].grade,store[i++]); // flaot형태로 평균값을 계산하기위해 atof로 변환 int to float float temp_avg = ((atof(st[cnt].score1) + atof(st[cnt].score2) + atof(st[cnt].score3) + atof(st[cnt].score4) + atof(st[cnt].score5)) / 5); st[cnt].avg = temp_avg; Current_Show(st,cnt); } cnt++; } } cout<< "\n"; Sort(st,cnt); // 구조체 정렬 Sort_Show(st,cnt); // 구조체 값 출력 Grade_Show(st,cnt); // 이름 학생 성적만 출력 int new_cnt = 0; new_cnt = New_Student_Create(st_new,new_cnt); // 새로운 파일을 읽어들여 데이터베이스 추가 // Insertion_Show(st_new,new_cnt); // 삽입된 값들만 출력 Sort(st_new,new_cnt); // 기존의 값 + 삽입된 값 구조체 정렬 Sort_Show(st_new,new_cnt); // 기존의 값 + 삽입된 값 구조체 출력 // 메모리초기화 memset(&st, 0, sizeof(st)); memset(&st_new, 0, sizeof(st_new)); openFile.close(); return 0; }
true
9ccdec0af3daaf055e03d51359a44e8442db2e44
C++
krishna6431/Data-Structure-Algorithms-Implementation-Using_CPP
/09_Stack/17_Paranthesis_Matching.cpp
UTF-8
1,473
3.84375
4
[ "Apache-2.0" ]
permissive
//Code is Written By Krishna //first u need to include __stack_functions_array__.cpp file #include "__stack_functions_array__.cpp" //Example // ((a+b) *(c-d)) //function for checking is parenthesis is balanced ort not int is_Balance(string exp) { struct stack s; s.size = exp.size(); s.top = -1; s.stk1 = new char[s.size]; for (int i = 0; i < s.size; i++) { if (exp[i] == '(') { push_c(&s, exp[i]); } else if (exp[i] == ')') { if (is_Empty(s)) { return false; } else { pop_c(&s); } } } if (is_Empty(s)) { return true; } else { return false; } } int main() { string s = "((a+b)*(c-d))"; int res = is_Balance(s); if (res) { cout << "Expression is: " << s << endl; cout << "Balanced Expression" << endl; } else { cout << "Expression is: " << s << endl; cout << "Not Balanced Expression" << endl; } string s1 = "((a+b)*)(c-d))"; res = is_Balance(s1); if (res) { cout << "Expression is: " << s1 << endl; cout << "Balanced Expression" << endl; } else { cout << "Expression is: " << s1 << endl; cout << "Not Balanced Expression" << endl; } }
true
9e5e8acec43f93d1c05d706a991ea16a30678a2c
C++
jasonjin34/Info2_Praktikum
/Aufgabenblock_3/AktivesVO.h
UTF-8
823
2.609375
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <iomanip> #include <map> using namespace std; extern double dGlobaleZeit; class AktivesVO { public: /*constructor and destructor*/ AktivesVO(); AktivesVO(string); AktivesVO(string, double); virtual ~AktivesVO(); /*rein virtual function for ostream operator overloading*/ virtual ostream& ostreamAusgabe(ostream& ) = 0; /*aktualize function*/ virtual void vAbfertigung(); virtual void vAusgabe(); void vInitialiserung(); /*operator overloading input function*/ istream& istreamEingabe(istream&); /*static variable and function*/ static int p_iMaxID; static map<string, AktivesVO*> map_VS; static AktivesVO* ptObject(string); protected: string p_sName; int p_iID; double p_dZeit; }; istream& operator >> (istream&, AktivesVO&);
true
bc77dbbf42f1d0c4bef86ef9133cf67f0e1faa72
C++
zihao-zheng/C-plus-Learn
/输入输出和文件操作.cpp/文件读写实例.cpp
UTF-8
1,357
3.359375
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; //从键盘输入几个学生的姓名的成绩,并以二进制文件形式保存 struct Student{ char name[20]; int score; }; int main(){ Student s; //写入信息 // ofstream OutFile( "students.dat",ios::out|ios::binary); // while( cin >> s.name >> s.score ) // OutFile.write( (char * ) & s, sizeof( s) ); // OutFile.close(); /*输入 Tom 60 Jack 80 Jane 40 <^Z+回车> */ //读取信息 ifstream inFile("students.dat",ios::in | ios::binary ); if(!inFile) { cout << "error" <<endl; return 0; } while( inFile.read( (char* ) & s, sizeof(s) ) ) { int readedBytes = inFile.gcount(); //看刚才读了多少字节 cout << s.name << " " << s.score << endl; } inFile.close(); //修改信息 fstream iofile( "students.dat", ios::in|ios::out|ios::binary); if( !iofile) { cout << "error" ; return 0; } iofile.seekp( 2 * sizeof(s),ios::beg); //定位写指针到第三个记录 iofile.write("Mike",strlen("Mike")+1); //+1是为了写\0 iofile.seekg(0,ios::beg); //定位读指针到开头 while( iofile.read( (char* ) & s, sizeof(s)) ) cout << s.name << " " << s.score << endl; iofile.close(); return 0; }
true
3b4d4138d9b9a0fbcb7447d4340c01d0cfb7d1be
C++
Dawidsoni/programming-competitions
/OI/XV/pla/Plakatowanie.cpp
UTF-8
498
2.984375
3
[]
no_license
#include<iostream> #include<stack> using namespace std; stack<int> stos; int ile, szer, wys, wynik; void dodaj(int licz) { while(stos.top() > licz) { wynik++; stos.pop(); } if(stos.top() != licz) stos.push(licz); } int main() { ios_base::sync_with_stdio(false); cin >> ile; stos.push(0); for(int i = 0; i < ile; i++) { cin >> szer >> wys; dodaj(wys); } dodaj(0); cout << wynik; return 0; }
true
a7dd0e8f303962a73b740d482733e015f1bca5cc
C++
kevmaltz/cgDNA
/cgDNA.cc
UTF-8
6,130
2.59375
3
[]
no_license
#include "Main.h" void helpExit() { cout << "cgDNA -p [DNA PDB]" << endl; exit(0); } void parsePDB(string *pdbFilename) { string buffer, linebuffer; int atomid = 0; string name; double mass, charge, radius; vertex crd; vector<vertex> coordinates; int natoms = 0; string atomtype; int resid = 0; char basetype; int basecount = 0; double basecoords[3] = {0., 0., 0.}; int sugcount = 0; double sugcoords[3] = {0., 0., 0.}; ifstream fd(pdbFilename->c_str()); while(getline(fd, buffer)) { if(buffer.compare(0, 4, "ATOM") == 0) //if the first word on the line is ATOM { bool printBead = false; atomtype = buffer.substr(13, 3); //grabs and stores atom type stored in column 3 of a PDB. May need to adjust to (12,4) but need //to check how trim works first. This is because some PDB have 4 char atomtypes. atomtype = trim(atomtype); //trims off everything but periodic symbol of atom, I think -9/14/17 @ 18:54 if(stoi(buffer.substr(25,1)) != resid) //checks 6th column to see if we have moved on to the next residue in the molecule yet { resid = stoi(buffer.substr(25,1)); //set resid to the now current resid number basetype = buffer[18]; //grab the letter of the base: A, G, T, C sugcoords[0] = sugcoords[1] = sugcoords[2] = 0.; //Reset suger coordinates to default sugcount = 0; basecoords[0] = basecoords[1] = basecoords[2] = 0.; //Reset base coordinates to default basecount = 0; } if((atomtype.compare(0, 3, "C1'") == 0) or (atomtype.compare(0, 3, "C2'") == 0) or (atomtype.compare(0, 3, "C3'") == 0) or (atomtype.compare(0, 3, "C4'") == 0) or (atomtype.compare(0, 3, "O4'") == 0)) { linebuffer = buffer.substr(30, 8); sugcoords[0] += stod(linebuffer); linebuffer = buffer.substr(38, 8); sugcoords[1] += stod(linebuffer); linebuffer = buffer.substr(46, 8); sugcoords[2] += stod(linebuffer); sugcount++; if(sugcount == 5) { sugcoords[0] /= 5; sugcoords[1] /= 5; sugcoords[2] /= 5; crd.x = sugcoords[0]; crd.y = sugcoords[1]; crd.z = sugcoords[2]; name = "S"; mass = 83.11; charge = -1.; radius = 3.5; printBead = true; } } else if(atomtype.length() == 2 or atomtype.compare(0, 3, "C5M") == 0) { linebuffer = buffer.substr(30, 8); basecoords[0] += stod(linebuffer); linebuffer = buffer.substr(38, 8); basecoords[1] += stod(linebuffer); linebuffer = buffer.substr(46, 8); basecoords[2] += stod(linebuffer); basecount++; if((basetype == 'A' && basecount == 10) or (basetype == 'G' && basecount == 11) or (basetype == 'C' && basecount == 8) or (basetype == 'T' && basecount == 9)) { basecoords[0] /= basecount; basecoords[1] /= basecount; basecoords[2] /= basecount; crd.x = basecoords[0]; crd.y = basecoords[1]; crd.z = basecoords[2]; name = basetype; name.append("b"); if(basetype == 'A') { mass = 134.1; radius = 4.0; } if(basetype == 'G') { mass = 150.1; radius = 4.0; } if(basetype == 'T') { mass = 125.1; radius = 3.7; } if(basetype == 'C') { mass = 110.1; radius = 3.7; } charge = 0.; printBead = true; } } if(printBead) { natoms++; coordinates.push_back(crd); cout << "particle "; cout.width(10); cout.precision(4); cout << fixed << crd.x; cout << " "; cout.width(8); cout.precision(4); cout << fixed << crd.y; cout << " "; cout.width(8); cout.precision(4); cout << fixed << crd.z; cout << " "; cout.width(8); cout.precision(4); cout << fixed << charge; cout << " "; cout.width(8); cout.precision(4); cout << fixed << radius; cout << " "; cout.width(8); cout.precision(4); cout << fixed << mass; cout << endl; } } } /* for(int i=0; i < natoms; i++) { vertex crdi = coordinates[i]; for(int j=i+1; j < natoms; j++) { vertex crdj = coordinates[j]; vertex rij = { crdi.x-crdj.x, crdi.y-crdj.y, crdi.z-crdj.z }; double lij = sqrt(rij.x*rij.x + rij.y*rij.y + rij.z*rij.z); if(lij < 9.) { cout << "BOND "; cout.width(5); cout << fixed << i << " "; cout.width(5); cout << fixed << j << " "; cout.width(8); cout.precision(3); cout << lij << " "; cout.width(8); cout.precision(3); cout << 200.0 << endl; } } } */ } bool getInputWithFlag( int argc, char **argv, //system arguments prog called char flag, //flag used to indicate filename string *value) //pointer to filename variable { bool bopt = false; //is proper input flag entered? //Not sure what these to do, however no longer used in function. 9-12-2017 // int opt; // char gopt[2] = { flag, ':' }; for(int i=1; i < argc; i++) { if(argv[i][0] == '-' && argv[i][1] == flag) { if(argv[i+1][0] != '-') { *value = argv[i+1]; bopt = true; i++; } } } return bopt; } int main(int argc, char **argv) { string pfn; //filename of PDB to be parsed and converted to PQR string ofn; // // Parse command line arguments if(argc < 1) helpExit(); if(! getInputWithFlag(argc, argv, 'p', &pfn)) helpExit(); // Parse the PDB file parsePDB(&pfn); return 0; }
true
70423dbe6cc7eb40d260b69459a51a5cfe157ee2
C++
lkuwada/CSCI60
/smatrix/entry.h
UTF-8
656
2.96875
3
[]
no_license
#ifndef ENTRY_H #define ENTRY_H #include <cstdlib> #include <iostream> struct entry { entry(std::size_t init_r = -1, std::size_t init_c = -1, double init_v = 0.0) { r = init_r; c = init_c; v = init_v; } std::size_t r, c; double v; }; std::ostream & operator << (std::ostream & os, const entry & e); std::istream & operator >> (std::istream &is, entry & e); bool operator ==(const entry &e1, const entry &e2); bool operator !=(const entry &e1, const entry &e2); bool operator >(const entry &e1, const entry &e2); bool operator <(const entry &e1, const entry &e2); #endif // ENTRY_H
true
ca5184cdbc4da850c294783d0524d701cfe3825f
C++
aeparks/Movie-Store
/list.h
UTF-8
1,603
3.140625
3
[ "MIT" ]
permissive
/* Aaron Parks * Prof. Carol Zander * CSS 343 : Winter 2010 * Lab 4v4 - MOVIE Store */ /*-- List ---------------------------------------------------------------------- * List creates and maintains a linked list of ListNodes. List will search as * a dynamically sized container that will resize as necessary be inserting new * nodes to the front of the list. * *-- Assumptions --------------------------------------------------------------- * - insert * -> no check is main against insufficient memory. it is assumed that that * much memory will not be used. * - makeEmpty * -> will delete ListNodes and data in 'data' pointers. will not delete any * Movies pointed to by Transactions *----------------------------------------------------------------------------*/ #ifndef LIST_H #define LIST_H #include "transaction.h" #include <iostream> using namespace std; class List { public: //constructor List(); //inserts new ListNode into list virtual bool insert(Transaction*); //returns if head == NULL virtual bool isEmpty() const; //deletes ListNodes and data virtual void makeEmpty(); //displays the information held in ListNodes virtual void displayHistory() const; protected: struct ListNode { ListNode* next; //pointer to next linked ListNode in memory Transaction* data; //pointer to a Trans object }; ListNode* head; //pointer to first ListNode in list //recursive helper for 'displayInOrder' virtual void displayHistory(ListNode*) const; }; #endif
true
7f61a2f781876034406c32863326142d01248869
C++
jlstr/practice-cpp
/DynamicProgramming/coin_change_top_down.cpp
UTF-8
1,194
3.4375
3
[]
no_license
#include <iostream> #include <limits> #include <map> using namespace std; int minimumChange(int, int*, const int, map<int, int>); void printArray(int*, const int); int main() { int coins[] = { 1, 2, 3 }; const int SIZE = sizeof(coins) / sizeof(int); map<int, int> memo; int money = 4; int result = minimumChange(money, coins, SIZE, memo); cout << "\nMinimum number of coins to give a change of $" << money << " is " << result << endl; cout << "with coins: "; printArray(coins, SIZE); cout << endl; return 0; } int minimumChange(int money, int *coins, const int N, map<int, int> memo) { if (money == 0) return 0; if (memo[money] != 0) return memo[money]; const int INF = std::numeric_limits<int>::max(); int min = INF; for (int i = 0; i < N; ++i) { if (coins[i] > money) continue; int val = minimumChange(money - coins[i], coins, N, memo); if (val < min) min = val; } min = (min == INF) ? min : min + 1; memo[money] = min; return min; } void printArray(int *array, const int SIZE) { cout << "[\t"; for (int *p = array, *q = array + SIZE; p != q; ++p) { cout << *p << "\t"; } cout << "]" << endl; }
true
1b021b54ebd50ec5d550c7d604d77ddad1e3866f
C++
AdamBilchouris/Cpp---Uni-Assignemnt-1
/distance.cpp
UTF-8
4,359
3.65625
4
[]
no_license
#include <iostream> #include <iomanip> #include <fstream> #include <string> using std::cout; using std::cin; using std::string; using std::endl; int main() { string tempLine; cout << "Enter file name >> "; string fileName; std::getline(cin, fileName); int lineNumber {0}; double minimumDistance {0}; double maximumDistance {0}; string line; std::ifstream fin; fin.open(fileName); if(fin.fail()) { cout << "The file \"" << fileName << "\" does not exist" << endl; fin.close(); return -1; } else { if(fin.peek() == EOF) //CHECKS IF FILE IS EMPTY, peek() goes to the next character, returns EOF if file is empty { cout << "File \"" << fileName << "\" is empty" << endl; return -1; } else { double tempDistanceDouble {0}; int counter {0}; string tempMinimumDistance; string tempMaximumDistance; cout << "Enter minimum distance >> "; getline(cin, tempMinimumDistance); cout << "Enter maximum distance >> "; getline(cin, tempMaximumDistance); minimumDistance = std::stod(tempMinimumDistance); maximumDistance = std::stod(tempMaximumDistance); if(minimumDistance < 0 || maximumDistance < 0) { if(maximumDistance < 0 && minimumDistance < 0) { cout << "Both distances are less than 0" << endl; return -1; } else if(minimumDistance < 0) { cout << "Minimum distance must be greater than or equal to 0" << endl; return -1; } else if(maximumDistance < 0) { cout << "Maximum distance must be greater than or equal to 0" << endl; return -1; } } if(minimumDistance > maximumDistance) { cout << "Maximum distance is lower than the minimum distance, thus no stars could be found" << endl; return -1; } while(fin) { getline(fin, tempLine); int lastTilde = tempLine.rfind("~"); string tempDistanceString = tempLine.substr(lastTilde + 1); if(!tempDistanceString.empty()) { tempDistanceDouble = std::stod(tempDistanceString); } if(tempDistanceDouble <= maximumDistance && tempDistanceDouble >= minimumDistance && !tempLine.empty()) { counter++; //Increment Counter //EXTRACTING INFORMATION FROM THE LINE int firstTilde = tempLine.find("~", 0); string commonName = tempLine.substr(0, firstTilde); int secondTilde = tempLine.find("~", firstTilde + 1); int thirdTilde = tempLine.find("~", secondTilde + 1); string properName = tempLine.substr(firstTilde + 1); properName = properName.substr(0, properName.find("~", 0)); //CREATE A NEW STRING string newTempLine = tempLine.substr(secondTilde + 1, thirdTilde); int fourthTilde = newTempLine.find("~", 0); string hrNumber = newTempLine.substr(0, fourthTilde); int fifthTilde = newTempLine.find("~", fourthTilde + 1); //CREATES ANOTHER NEW STRING string newerTempLine = newTempLine.substr(fourthTilde + 1, fifthTilde); int sixthTilde = newerTempLine.find("~", 0); string hdNumber = newerTempLine.substr(0, sixthTilde); int seventhTilde = newerTempLine.find("~", sixthTilde); string distance = newerTempLine.substr(seventhTilde + 1); double tempDistance = std::stod(tempDistanceString); cout << "Star: proper name: " << properName << " distance: " << std::setprecision(6) << tempDistance << " light years HD num: " << hdNumber << "\n HR num: " << hrNumber << " common name: " << commonName << endl; } } fin.close(); if(counter == 0) { cout << "No star within " << minimumDistance << " and " << maximumDistance << " light years was found" << endl; } } } return 0; }
true
c47f1ac50251742f1fa7976a2d7a7c2b2961dec1
C++
ir0nc0w/cross-compile_for_Windows
/VS2012/vc/include/xtgmath.h
UTF-8
3,759
2.625
3
[]
no_license
/* xtgmath.h internal header */ #pragma once #ifndef _XTGMATH #define _XTGMATH #ifndef RC_INVOKED #if defined(__cplusplus) #include <xtr1common> #pragma pack(push,_CRT_PACKING) #pragma warning(push,3) #pragma push_macro("new") #undef new _STD_BEGIN template<class _Ty> struct _Promote_to_float { // promote integral to double typedef typename conditional<is_integral<_Ty>::value, double, _Ty>::type type; }; template<class _Ty1, class _Ty2> struct _Common_float_type { // find type for two-argument math function typedef typename _Promote_to_float<_Ty1>::type _Ty1f; typedef typename _Promote_to_float<_Ty2>::type _Ty2f; typedef typename conditional<is_same<_Ty1f, long double>::value || is_same<_Ty2f, long double>::value, long double, typename conditional<is_same<_Ty1f, double>::value || is_same<_Ty2f, double>::value, double, float>::type>::type type; }; _STD_END #define _CRTDEFAULT #define _CRTSPECIAL _CRTIMP #define _GENERIC_MATH1(FUN, CRTTYPE) \ extern "C" CRTTYPE double __cdecl FUN(_In_ double); \ template<class _Ty> inline \ typename _STD enable_if< _STD is_integral<_Ty>::value, double>::type \ FUN(_Ty _Left) \ { \ return (_CSTD FUN((double)_Left)); \ } #define _GENERIC_MATH1X(FUN, ARG2, CRTTYPE) \ extern "C" CRTTYPE double __cdecl FUN(_In_ double, ARG2); \ template<class _Ty> inline \ typename _STD enable_if< _STD is_integral<_Ty>::value, double>::type \ FUN(_Ty _Left, ARG2 _Arg2) \ { \ return (_CSTD FUN((double)_Left, _Arg2)); \ } #define _GENERIC_MATH2(FUN, CRTTYPE) \ extern "C" CRTTYPE double __cdecl FUN(_In_ double, _In_ double); \ template<class _Ty1, \ class _Ty2> inline \ typename _STD _Common_float_type<_Ty1, _Ty2>::type \ FUN(_Ty1 _Left, _Ty2 _Right) \ { \ typedef typename _STD _Common_float_type<_Ty1, _Ty2>::type type; \ return (_CSTD FUN((type)_Left, (type)_Right)); \ } _C_STD_BEGIN extern "C" double __cdecl pow(_In_ double, _In_ double); float __CRTDECL pow(_In_ float, _In_ float); long double __CRTDECL pow(_In_ long double, _In_ long double); template<class _Ty1, class _Ty2> inline typename _STD enable_if< _STD _Is_numeric<_Ty1>::value && _STD _Is_numeric<_Ty2>::value, typename _STD _Common_float_type<_Ty1, _Ty2>::type>::type pow(const _Ty1 _Left, const _Ty2 _Right) { // bring mixed types to a common type typedef typename _STD _Common_float_type<_Ty1, _Ty2>::type type; return (_CSTD pow(type(_Left), type(_Right))); } //_GENERIC_MATH1(abs, _CRTDEFAULT) // has integer overloads _GENERIC_MATH1(acos, _CRTDEFAULT) _GENERIC_MATH1(asin, _CRTDEFAULT) _GENERIC_MATH1(atan, _CRTDEFAULT) _GENERIC_MATH2(atan2, _CRTDEFAULT) _GENERIC_MATH1(ceil, _CRTSPECIAL) _GENERIC_MATH1(cos, _CRTDEFAULT) _GENERIC_MATH1(cosh, _CRTDEFAULT) _GENERIC_MATH1(exp, _CRTDEFAULT) //_GENERIC_MATH1(fabs, _CRT_JIT_INTRINSIC) // not required _GENERIC_MATH1(floor, _CRTSPECIAL) _GENERIC_MATH2(fmod, _CRTDEFAULT) _GENERIC_MATH1X(frexp, _Out_ int *, _CRTSPECIAL) _GENERIC_MATH1X(ldexp, _In_ int, _CRTSPECIAL) _GENERIC_MATH1(log, _CRTDEFAULT) _GENERIC_MATH1(log10, _CRTDEFAULT) //_GENERIC_MATH1(modf, _CRTDEFAULT) // types must match //_GENERIC_MATH2(pow, _CRTDEFAULT) // hand crafted _GENERIC_MATH1(sin, _CRTDEFAULT) _GENERIC_MATH1(sinh, _CRTDEFAULT) _GENERIC_MATH1(sqrt, _CRTDEFAULT) _GENERIC_MATH1(tan, _CRTDEFAULT) _GENERIC_MATH1(tanh, _CRTDEFAULT) _C_STD_END #endif /* defined(__cplusplus) */ #pragma pop_macro("new") #pragma warning(pop) #pragma pack(pop) #endif /* RC_INVOKED */ #endif /* _XTGMATH */ /* * Copyright (c) 1992-2012 by P.J. Plauger. ALL RIGHTS RESERVED. * Consult your license regarding permissions and restrictions. V6.00:0009 */
true
29c5681bc95a192e33fbbf5539b7d86f6a52a1d9
C++
harveylabis/SamsTeachCplusplus
/Lesson21_FunctionObjects/L21_4_UnaryPredicateUsage_find.cpp
UTF-8
1,008
4.0625
4
[]
no_license
#include <algorithm> #include <vector> #include <iostream> template <typename numberType> struct IsMultiple{ numberType Divisor; IsMultiple(const numberType &divisor){ Divisor = divisor; } bool operator()(const numberType &element){ return ((element % Divisor) == 0); } }; int main(void){ std::vector<int> numsInVec {25, 26, 27, 28, 29, 30, 31}; std::cout << "The vector contains: 25, 26, 27, 28, 29, 30, 31" << std::endl; std::cout << "Enter divisor (> 0): "; int divisor = 2; std::cin >> divisor; // Find the first element that is a multiple of divisor auto element = std::find_if(numsInVec.cbegin(), numsInVec.cend(), IsMultiple<int>(divisor)); if (element != numsInVec.cend()){ std::cout << "First element in vector divisible by " << divisor; std::cout << ": " << *element << std::endl; // } else { // std::cout << "No element is divisible by " << divisor << std::endl; // } return 0; }
true
49dd11b84ef1538a0ddeb64a5ec621d4001cdfd2
C++
chunnoo/viz
/include/vector.hpp
UTF-8
3,443
3.453125
3
[]
no_license
#pragma once #include <iostream> #include <cmath> #include <array> template<unsigned int N> class Vector { private: std::array<float, N> m_values; public: Vector(); Vector(const std::array<float, N> &values); Vector<N> copy() const; void set(const unsigned int i, const float v); float get(const unsigned int i) const; float length() const; Vector<N> normalized() const; float dot(const Vector<N> &rhs) const; Vector<3> cross(const Vector<N> &rhs) const; Vector<N> to(const Vector<N> &rhs) const; Vector<N> add(const Vector<N> &rhs) const; }; template<unsigned int N> std::ostream& operator<<(std::ostream &stream, const Vector<N> &vector); template<unsigned int N> Vector<N>::Vector() { m_values.fill(0.0f); } template<unsigned int N> Vector<N>::Vector(const std::array<float, N> &values) { for (unsigned int i = 0; i < N; i++) { m_values[i] = values[i]; } } template<unsigned int N> Vector<N> Vector<N>::copy() const { Vector<N> copy; for (unsigned int i = 0; i < N; i++) { copy.set(i, m_values[i]); } return copy; } //TODO: validate indices template<unsigned int N> void Vector<N>::set(const unsigned int i, const float v) { m_values[i] = v; } template<unsigned int N> float Vector<N>::get(const unsigned int i) const { return m_values[i]; } template<unsigned int N> float Vector<N>::length() const { float squaredSum = 0.0f; for (unsigned int i = 0; i < N; i++) { squaredSum += m_values[i]*m_values[i]; } return squaredSum; } template<unsigned int N> Vector<N> Vector<N>::normalized() const { float length = this->length(); Vector<N> normalized; for (unsigned int i = 0; i < N; i++) { normalized.set(i, m_values[i]/length); } return normalized; } template<unsigned int N> float Vector<N>::dot(const Vector<N> &rhs) const { float result = 0; for (unsigned int i = 0; i < N; i++) { result += this->get(i)*rhs.get(i); } return result; } template<> Vector<3> Vector<3>::cross(const Vector<3> &rhs) const { Vector<3> result; result.set(0, m_values[1]*rhs.get(2) - rhs.get(1)*m_values[2]); result.set(1, m_values[2]*rhs.get(0) - rhs.get(2)*m_values[0]); result.set(2, m_values[0]*rhs.get(1) - rhs.get(1)*m_values[0]); return result; } template<> Vector<3> Vector<2>::cross(const Vector<2> &rhs) const { Vector<3> result; result.set(0, 0); result.set(1, 0); result.set(2, m_values[0]*rhs.get(1) - rhs.get(1)*m_values[0]); return result; } template<unsigned int N> Vector<3> Vector<N>::cross(const Vector<N> &rhs) const { Vector<3> result; result.set(0, m_values[1]*rhs.get(2) - rhs.get(1)*m_values[2]); result.set(1, m_values[2]*rhs.get(0) - rhs.get(0)*m_values[2]); result.set(2, m_values[0]*rhs.get(1) - rhs.get(1)*m_values[0]); return result; } template<unsigned int N> Vector<N> Vector<N>::to(const Vector<N> &rhs) const { Vector<N> result; for (unsigned int i = 0; i < N; i++) { result.set(i, rhs.get(i) - m_values[i]); } return result; } template<unsigned int N> Vector<N> Vector<N>::add(const Vector<N> &rhs) const { Vector<N> sum; for (unsigned int i = 0; i < N; i++) { sum.set(i, m_values[i] + rhs.get(i)); } return sum; } template<unsigned int N> std::ostream& operator<<(std::ostream &stream, const Vector<N> &vector) { for (unsigned int i = 0; i < N; i++) { stream << vector.get(i) << " "; }; return stream; }
true
e838f35c35b37c8a4b4f7f3b19e25311a4afa47c
C++
Masters-Akt/CS_codes
/leetcode_sol/221-Maximal_Square.cpp
UTF-8
511
2.59375
3
[]
no_license
class Solution { public: int maximalSquare(vector<vector<char>>& matrix) { int ans = 0; vector<vector<int>> dp(matrix.size()+1, vector<int>(matrix[0].size()+1, 0)); for(int i=1;i<dp.size();i++){ for(int j=1;j<dp[i].size();j++){ if(matrix[i-1][j-1]=='1'){ dp[i][j] = 1 + min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}); ans = max(ans, dp[i][j]); } } } return ans*ans; } };
true
c9bf7922d9cceac1b4629b6501709e25391e9f12
C++
Cyvid7-Darus10/Algorithms
/Hanoi_Recursion.cpp
UTF-8
931
3.53125
4
[]
no_license
#include <iostream> #include <stack> /* Classic Hanoi tower problem Using stacks to represent each tower */ using st = std::stack<int>; struct augmentedStack { st stack; std::string name; }; using as = augmentedStack; void transferDisk(as& from, as& to) { to.stack.push(from.stack.top()); std::cout << "Moving " << from.stack.top() << " from " << from.name << " to " << to.name <<"\n"; from.stack.pop(); } void arrange(as& from, as& aux, as& to, int numDiscs) { if (numDiscs == 1) { transferDisk(from, to); return; } arrange(from, to, aux, numDiscs - 1); transferDisk(from, to); arrange(aux, from, to, numDiscs - 1); } int main() { int numDiscs = 3; as initStack, midStack, endStack; initStack.name = "Source"; midStack.name = "Auxilary"; endStack.name = "Destination"; for (int i=numDiscs-1; i >= 0; i--) { initStack.stack.push(i); } arrange(initStack, midStack, endStack, numDiscs); return 0; }
true
2738f725a7ba34161916e2de921b09fb9902a12b
C++
Leo8D/Leo-Kroll
/Bonus 5/main.cpp
UTF-8
1,653
3.21875
3
[]
no_license
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; int main() { int tot, bet, en = 0, fem = 0, tio = 0, femtio = 0, hundra = 0, femhundra = 0, tusen = 0, vexel, tjugo = 0; cout << "Totala konstaden" << endl; cin >> tot; cout << "Totala betalningen" << endl; cin >> bet; vexel = bet - tot; while(vexel >= 1000){ vexel = vexel - 1000; tusen++; } while(vexel >= 500) { vexel = vexel - 500; femhundra++; } while(vexel >= 100) { vexel = vexel - 100; hundra++; } while(vexel >= 50) { vexel = vexel - 50; femtio++; } while(vexel >= 20) { vexel = vexel - 20; tjugo++; } while(vexel >= 10) { vexel = vexel - 10; tio++; } while(vexel >= 5) { vexel = vexel - 5; fem++; } while(vexel >= 1){ vexel = vexel - 1; en++; } if(tusen > 0) { cout << tusen << "st tusenlappar" << endl; } if(hundra > 0) { cout << hundra<< "st hundralappar" << endl; } if(femhundra > 0) { cout << femhundra << "st femhundralappar" << endl; } if(femtio > 0) { cout << femtio<< "st femtiolappar" << endl; } if(tjugo > 0) { cout << tjugo << "st tjugolappar" << endl; } if(tio > 0) { cout << tio << "st tiokronor" << endl; } if(fem > 0) { cout << fem << "st femkronor" << endl; } if(en > 0) { cout << en << "st enkronor" << endl; } return 0; }
true
e0fbd52b102ddc9546451cccce81e6268bf5e881
C++
tlahoda/Particles
/ConnectionModel.h
UTF-8
2,658
2.5625
3
[ "MIT" ]
permissive
/** * \file ConnectionModel.h, Contains the ConnectionModel class. * * Copyright (C) 2005 Thomas P. Lahoda * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef PARTICLE_CONNECTIONMODEL_H #define PARTICLE_CONNECTIONMODEL_H #include "gl/Primitive.h" namespace particle { /** * \class ConnectionModel, Draws a vertex for a primitive. * * \param GlType, The type of the primitive. */ class ConnectionModel { public: /** * \typedef GlType glType, * The type of the primitive. */ typedef gl::Lines glType; /** * Renders a vertex for a primitive. * * \param Particle, The type of the particle. * * \param particle const Particle&, The particle to render. * * \return void. */ template<class Particle> void operator() (const Particle& particle) const { glColor3f (1.0f, 0.0f, 0.0f); glVertex3f (constraint->connection ().first ().position ()[0], constraint->connection ().first ().position ()[1], constraint->connection ().first ().position ()[2]); glVertex3f (constraint->connection ().second ().position ()[0], constraint->connection ().second ().position ()[1], constraint->connection ().second ().position ()[2]); }; }; //ConnectionModel }; //particle #endif //PARTICLE_CONNECTIONMODEL_H
true
7a27e65e7f15d4e26d1a821e30256104cebcea5f
C++
melizalab/jill
/jill/dsp/triggered_data_writer.cc
UTF-8
5,819
2.578125
3
[]
no_license
#include <boost/type_traits/make_signed.hpp> #include "triggered_data_writer.hh" #include "../types.hh" #include "../logging.hh" #include "../midi.hh" #include "../dsp/block_ringbuffer.hh" using namespace std; using namespace jill; using namespace jill::dsp; /** A data type for comparing differences between frame counts */ using framediff_t = boost::make_signed<nframes_t>::type; namespace jill { std::ostream & operator<<(std::ostream & os, data_block_t const & b) { os << "time=" << b.time << ", id=" << b.id() << ", type=" << b.dtype << ", frames=" << b.nframes(); return os; } } triggered_data_writer::triggered_data_writer(std::unique_ptr<data_writer> writer, string trigger_port, nframes_t pretrigger_frames, nframes_t posttrigger_frames) : buffered_data_writer(std::move(writer)), _trigger_port(std::move(trigger_port)), _pretrigger(pretrigger_frames), _posttrigger(std::max(posttrigger_frames, 1U)), _recording(false) { DBG << "triggered_data_writer initializing"; } triggered_data_writer::~triggered_data_writer() { DBG << "triggered_data_writer closing"; stop(); join(); } /* * This function handles opening a new entry and writing data in the prebuffer. * The event_time argument indicates the time when the trigger event occurred, * so we start at the tail of the ringbuffer and search for the sample with * index event_time - _pretrigger */ void triggered_data_writer::start_recording(nframes_t event_time) { nframes_t onset = event_time - _pretrigger; /* * Start at tail of queue and find onset. This may not be in the buffer * if it has not had enough time to fill. */ data_block_t const * ptr = _buffer->peek(); assert(ptr); /* skip any earlier periods */ while (ptr->time + ptr->nframes() < onset) { DBG << "prebuffer frame (discarded): " << *ptr; _buffer->release(); ptr = _buffer->peek(); } /* write partial period(s) */ while (ptr->time <= onset) { DBG << "prebuf frame (partial): " << *ptr << ", on=" << onset - ptr->time; _writer->write(ptr, onset - ptr->time, 0); _buffer->release(); ptr = _buffer->peek(); } /* write additional periods in prebuffer, up to current period */ while (ptr->time + ptr->nframes() <= event_time) { DBG << "prebuffer frame (complete): " << *ptr; _writer->write(ptr, 0, 0); _buffer->release(); ptr = _buffer->peek(); } _recording = true; } /* * this function doesn't close the entry immediately, but sets flags so that * write() will do this at the appropriate time */ void triggered_data_writer::stop_recording(nframes_t event_time) { _recording = false; _last_offset = event_time + _posttrigger; INFO << "writing posttrigger data from " << event_time << "--" << _last_offset; } void triggered_data_writer::write(data_block_t const * data) { std::string id = data->id(); nframes_t nframes = data->nframes(); /* handle trigger channel */ if (data->dtype == EVENT && id == _trigger_port) { if (_recording) { if (midi::is_offset(data->data(), data->sz_data)) { DBG << "trigger off event: time=" << data->time; stop_recording(data->time); } } else { if (midi::is_onset(data->data(), data->sz_data)) { DBG << "trigger on event: time=" << data->time; start_recording(data->time); } } } if (_recording) { // Executed when an onset trigger has occurred and // stop_recording was not called, so write full block. // sanity check if data is flushed. can't compare pointers // directly because the same data may have multiple addresses in // the buffer data_block_t const * tail = _buffer->peek(); assert(tail->time == data->time && tail->id() == id); _writer->write(data, 0, 0); _buffer->release(); if (__sync_bool_compare_and_swap(&_reset, true, false)) { stop_recording(data->time + nframes); } } else if (_writer->ready()) { // executed when stop_recording was called, so we're writing // post-trigger periods. If enough data has been written, close // entry. framediff_t compare = _last_offset - data->time; DBG << "postbuffer frame: " << *data; if (compare < 0) { _writer->close_entry(); } else { _writer->write(data, 0, 0);//(nframes_t)compare); _buffer->release(); } } else { // not writing: drop blocks on tail of queue as needed data_block_t const * tail = _buffer->peek(); while (tail && (data->time + nframes) - (tail->time + nframes) > _pretrigger) { _buffer->release(); tail = _buffer->peek(); } // clear reset flag; otherwise it won't happen until the next // recording starts __sync_bool_compare_and_swap(&_reset, true, false); } }
true
311cf0a6d9fe7e99add2c127f67cfa7146b93b63
C++
adamelha/advanced-programming
/Battleship/Battleship/smartAlgo.cpp
UTF-8
2,520
3.0625
3
[]
no_license
#include "smartAlgo.h" #define isPointOnBoard(i , j) ( i < arrSize && i > -1 && j < arrSize && j > -1 ) //enum { up = 0, right = 1, buttom = 2, left = 3 }; Point smartAlgo::getNextPotentialPoint() { return Point(); } Point * smartAlgo::potentialLegalMoves() { return nullptr; } int smartAlgo::getPotentialMovesSize() { return potentialMovesSize; } void smartAlgo::setBoard(int player, const char ** board, int numRows, int numCols) { } std::pair<int, int> smartAlgo::attack() { int r; Point attack; srand(time(NULL)); if (this->strike) // playr indeed Hit! (in prev turn) { //TBD: local enviorment: return point from local env,the point who got hit is this; } else { r = rand() % potentialMovesSize; attack = this->potentialMoves[r]; this->potentialMoves[r] = this->potentialMoves[potentialMovesSize]; PointerForPotentialMove[this->potentialMoves[r].x][this->potentialMoves[r].y] = &this->potentialMoves[r]; potentialMovesSize -= 1; return std::pair<int, int>(attack.x, attack.y); } return std::pair<int, int>(-1, -1); } void smartAlgo::notifyOnAttackResult(int player, int row, int col, AttackResult result) { } bool smartAlgo::init(const std::string & path) { return false; } //changes unvalid points near a point with player ship void smartAlgo::changeEnvalopPointsToFalse(bool arr[][arrSize], int i, int j) { arr[i][j] = false; if (isPointOnBoard(i + 1, j)) arr[i + 1][j] = false; if (isPointOnBoard(i, j + 1)) arr[i][j + 1] = false; if (isPointOnBoard(i, j - 1)) arr[i][j - 1] = false; if (isPointOnBoard(i - 1, j)) arr[i - 1][j] = false; } //updated two dimientional isPointLegal[10[10],detemine which point (x,y) is valid=> isPointLegal[x][y] = true, else isPointLegal[x][y] = false void smartAlgo::initIsPointLegal(const vector<Ship*>& shipList) { memset(isPointLegal, true, sizeof(isPointLegal[0][0]) * arrSize * arrSize); //all initialized to true for (int i = 0; i < shipList.size(); i++) { for (int j = 0; j < shipList[i]->size; j++) { changeEnvalopPointsToFalse(isPointLegal, shipList[i]->pointList[j].x, shipList[i]->pointList[j].y); } } } void smartAlgo::initPotentialMoves(const vector<Ship*>& shipList) { int index = 0; smartAlgo::initIsPointLegal(shipList); for (int i = 0; i < arrSize; i++) { for (int j = 0; j < arrSize; j++) { if (isPointLegal[i][j]) { potentialMoves[index] = Point(i, j); index += 1; potentialMovesSize += 1; } } } //memset(array, 0, sizeof(array[0][0]) * m * n); }
true
52f1cdfa74ea2e15a5959761df26c9515dd7d92f
C++
cuongnh28/DSAFall2019
/Test3/sxepStruct.cpp
UTF-8
349
2.828125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; struct Mau{ char c; int dem; }; bool cmp(Mau a, Mau b){ return (a.dem>b.dem); } int main(){ Mau m[100]; int n; cin>>n; for(int i=0;i<n;i++){ cin>>m[i].c>>m[i].dem; } sort(m,m+n,cmp); for(int i=0;i<n;i++){ cout<<m[i].c<<" "<<m[i].dem<<endl; } }
true
a24bef5c63dff9169e9a473272ef7f044bd78751
C++
nhatduong01/Assignment-2-semeter-201
/treeLib.h
UTF-8
9,092
3.578125
4
[]
no_license
#include <iostream> #include <utility> #include <functional> template <typename T> class BSTree { protected: struct Node { T data; Node *pLeft, *pRight; Node(const T &a, Node *pL = nullptr, Node *pR = nullptr) : data(a), pLeft(pL), pRight(pR) {} Node(const T &&a, Node *pL = nullptr, Node *pR = nullptr) : data(std::move(a)), pLeft(pL), pRight(pR) {} }; void clear(Node *pR) { if (pR) { clear(pR->pLeft); clear(pR->pRight); delete pR; } } void NLT_traserse(std::function<void(T &)> op, Node *pR) { op(pR->data); if (pR->pLeft) NLR_traverse(op, pR->pLeft); if (pR->pRight) NLR_traverse(op, pR->pRight); } public: Node *pRoot; BSTree() : pRoot(nullptr) { } ~BSTree() { clear(); } void clear() { clear(pRoot); } void insert(const T &a, Node *&pR) { if (pR) { if (a < pR->data) insert(a, pR->pLeft); else { insert(a, pR->pRight); } } else { pR = new Node(a); } } void BFTraserse(std::function<void(T &)> op) { } void NLP_Traverse(std::function<void(T &)> op, Node *pR) { op(pR->data); if (pR->pLeft) NLP_Traverse(op, pR->pLeft); if (pR->pRight) NLP_Traverse(op, pR->pRight); } // Now we come to delete a node of a binary tree // Maximum on the left or minimum on the right ???? /* */ void remove(const T &a, Node *&pR) { if (pR) { if (pR->data == a) { if (pR->pLeft && pR->pRight) { Node *p = pR->pRight; while (p->pLeft) { p = p->pLeft; } pR->data = p->data; remove(p->data, pR->right); } else if (pR->pLeft) { Node *p = pR; pR = pR->pLeft; delete p; } else if (pR->pRight) { Node *p = pR; pR = pR->pRight; delete p; } else { delete pR; } } else if (pR->data > a) { remove(a, pR->pLeft); } else { remove(a, pR->pRight); } } else { pR = new Node(a); } } }; /* AVL tree Balance Factor: EH, LH, RH */ enum BalanceFactor { EH, LH, RH }; template <typename T> class AVLTree { protected: Node *pRoot; struct Node { T data; BalanceFactor b; Node *pLeft, *pRight; Node(const T &a, BalanceFactor _b, Node *pL = nullptr, Node *pR = nullptr) : data(a), pLeft(pL), pRight(pR), b(_b) {} Node(const T &&a, Node *pL = nullptr, Node *pR = nullptr) : data(std::move(a)), pLeft(pL), pRight(pR) {} }; void clear(Node *pR) { if (pR) { clear(pR->pLeft); clear(pR->pRight); delete pR; } } void rotL(Node *&pR) { Node *p = pR->pRight; pR->pRight = p->pLeft; p->pLeft = pR; pR = p; } void rotR(Node *&pR) { Node *p = pR->pLeft; pR->pLeft = p->pRight; p->pRight = pR; pR = p; } bool balanceLeft(Node *&pR) //insert to the left and the left get higher // this will balance the tree in this context { if (pR == nullptr) { pR = new Node(a); return true; } if (pR->data > a) { if (insert(a, pR->pLeft)) { if (pR->b == LH) { // WE have 3 case if (pR->pLeft->b == LH) { rotR(pR); pR->b = pR->pRight->b = EH; return false; } else if (pR->pLeft->b == EH) { rotR(pR); pR->b = RH; pR->pRight->b = LH; return true; } else { rotL(pR->pLeft); rotR(pR); if (pR->b == LH) { //pr->b == pR->pLeft->b = } } } // difficult case else if (pR->b == EH) //modify only the status { pR->b = LH; return true; } else { pR->b = EH; return false; } } else return 0; } else { if (insert(a, pR->pRight)) { } else return 0; } } void NLT_traserse(std::function<void(T &)> op, Node *pR) { op(pR->data); if (pR->pLeft) NLR_traverse(op, pR->pLeft); if (pR->pRight) NLR_traverse(op, pR->pRight); } bool insert(const T &a, Node *&pR) // REturn true if the tree get higher { if (pR == nullptr) { pR = new Node(a); return true; } if (pR->data > a) { if (insert(a, pR->pLeft)) { if (pR->b == LH) { // WE have 3 case if (pR->pLeft->b == LH) { rotR(pR); pR->b = pR->pRight->b = EH; return false; } else if (pR->pLeft->b == EH) { rotR(pR); pR->b = RH; pR->pRight->b = LH; return true; } else { rotL(pR->pLeft); rotR(pR); if (pR->b == LH) { //pr->b == pR->pLeft->b = } } } // difficult case else if (pR->b == EH) //modify only the status { pR->b = LH; return true; } else { pR->b = EH; return false; } } else return 0; } else { if (insert(a, pR->pRight)) { } else return 0; } } public: AVLTree() : pRoot(nullptr) { } ~AVLTree() { clear(); } void clear() { clear(pRoot); } void BFTraserse(std::function<void(T &)> op) { } void NLP_Traverse(std::function<void(T &)> op, Node *pR) { op(pR->data); if (pR->pLeft) NLP_Traverse(op, pR->pLeft); if (pR->pRight) NLP_Traverse(op, pR->pRight); } // Now we come to delete a node of a binary tree // Maximum on the left or minimum on the right ???? /* */ void remove(const T &a, Node *&pR) { if (pR) { if (pR->data == a) { if (pR->pLeft && pR->pRight) { Node *p = pR->pRight; while (p->pLeft) { p = p->pLeft; } pR->data = p->data; remove(p->data, pR->right); } else if (pR->pLeft) { Node *p = pR; pR = pR->pLeft; delete p; } else if (pR->pRight) { Node *p = pR; pR = pR->pRight; delete p; } else { delete pR; } } else if (pR->data > a) { remove(a, pR->pLeft); } else { remove(a, pR->pRight); } } else { pR = new Node(a); } } };
true
070d3ff678fcd7253abf98bf8abcff54c017c8f9
C++
StevenRincon24/Library
/main.cpp
UTF-8
2,707
3.234375
3
[]
no_license
// // Created by Steven on 22/11/2020. // #include <iostream> #include "Author.h" #include "Book.h" #include "ServiceLibrary.h" using namespace std; ServiceLibrary* library = new ServiceLibrary(); void addAuthor() { string idAuthor , nationality; string name; cout<<"Author Id "<<endl; cin>>idAuthor; cout<<"Author Name"<<endl; cin.ignore(); getline(cin, name); cout<<"Author Nationality"<<endl; cin>> nationality; if (library->addAuthor(idAuthor, name , nationality) == true){ cout<<"Author add successfully"<<endl; }else if (library->addAuthor(idAuthor, name , nationality) != true){ cout<<"Error add author"<<endl; } } void addBook(){ string IdAuthor, IdBook, name; short int pages; cout<<"Author Id "<<endl; cin>> IdAuthor; cout<<"Book Id "<<endl; cin>> IdBook; getline(cin, name); cout<<"Book Name "<<endl; getline(cin, name); cout<<"Book Pages "<<endl; cin>> pages; if (library->addBook(IdAuthor,IdBook, name, pages)==true){ cout<<"Book add successfully"<<endl; }else if (library->addBook(IdAuthor,IdBook, name, pages)!=true){ cout<<"Error add book"<<endl; } } std::string showAuthor() { return library->showAuthor(); } std::string showBooks(){ return library->showBook(); } std::string showBooksAuthor() { string AuthorId; cout<<"Author Id "<<endl; cin>>AuthorId; return library->showBookAuthor(AuthorId); } void menu(){ int option; cout<<"Enter a option"<<endl<<"1. Add author"<<endl<<"2. Show authors"<<endl<<"3. Add book" <<endl<<"4. Show book"<<endl<<"5. Author Books"<<endl<<"6. Exit"<<endl; cin>>option; do{ if (option == 1){ cout<<"Add Author"<<endl; addAuthor(); menu(); }else if ( option == 2 ){ cout<<showAuthor()<<endl; menu(); }else if ( option == 3 ){ addBook(); menu(); cout<<"Add book"<<endl; }else if ( option == 4 ){ cout<<showBooks()<<endl; menu(); }else if( option == 5 ){ cout<<showBooksAuthor(); menu(); } else if ( option == 6 ){ cout<<"Thank for use the system"<<endl; exit(0); } }while (option < 7); } int main() { /*cout << "Escribe tu nombre : "; string nombre; getline(cin, nombre); cout << "Escribe tu nombre : "; string departamento; getline(cin, departamento); cout << "Hola " << nombre << endl; int num = nombre.size(); cout << "Tu nombre tiene " << num << " caracteres" << endl;*/ menu(); }
true
3225fe13fed8de76094a90358fc13d391cf349b7
C++
liqiyang1908/LintCode
/610_Two_Sum_Difference_Equals_To_Target.cpp
UTF-8
1,672
3.328125
3
[]
no_license
class Solution { public: /** * @param nums: an array of Integer * @param target: an integer * @return: [num1, num2] (num1 < num2) */ vector<int> twoSum7(vector<int>& nums, int target) { vector<int>res; if (nums.size() < 2) return res; unordered_set<int>mymap; if (target < 0) target = 0 - target; for (auto num: nums) { int first_num = num - target; if (mymap.find(first_num) != mymap.end()) { res.push_back(first_num); res.push_back(num); return res; } if (mymap.find(num) == mymap.end()) mymap.insert(num); } return res; } }; //同向双指针 class Solution { public: /** * @param nums: an array of Integer * @param target: an integer * @return: [num1, num2] (num1 < num2) */ vector<int> twoSum7(vector<int>& nums, int target) { vector<int>res; if (nums.size() < 2) return res; int i, j = 1; if (target < 0) target = 0 - target; for (i = 0; i < nums.size(); i++) { j = max(i + 1, j); while (j < nums.size() && nums[j] - nums[i] < target) j++; if (j >= nums.size()) break; if (nums[j] - nums[i] == target) { res.push_back(nums[i]); res.push_back(nums[j]); return res; } } return res; } };
true
1b197d552a273591168125bd39b5397de5d1142b
C++
nikhilYadala/blurt
/blurt_cpp_80211/fft.cc
UTF-8
3,360
2.8125
3
[ "MIT" ]
permissive
#include "fft.h" #include <stdint.h> #include <cmath> #include <map> #include <float.h> typedef float real; class FFT { private: size_t n; bool forward; int *rev_idx, *rev_idx_end; complex *factors; real scale; inline void rev_in_place(complex *x); public: FFT(size_t n, bool forward); ~FFT(); void transform(complex *x); }; static uint32_t rev_byte(uint8_t b) { return ((b * 0x80200802ULL) & 0x0884422110ULL) * 0x0101010101ULL >> 32; } static uint32_t rev_word(uint32_t w) { return (rev_byte((w >> 24) & 0xFF) << 0) | (rev_byte((w >> 16) & 0xFF) << 8) | (rev_byte((w >> 8) & 0xFF) << 16) | (rev_byte((w >> 0) & 0xFF) << 24); } static uint32_t rev(uint32_t w, size_t logn) { return rev_word(w) >> (32 - logn); } inline void FFT::rev_in_place(complex *x) { int *idx = rev_idx, *end = rev_idx_end; while (idx != end) { int i = *idx++; int j = *idx++; complex temp = x[j]; x[j] = x[i]; x[i] = temp; } } static inline complex omega(int e, size_t logn, bool forward) { if (e == 0) return 1.f; if (!forward) e = -e; double theta = -2*M_PI*e/(1<<logn); return complex(float(cos(theta)), float(sin(theta))); } FFT::FFT(size_t n_, bool forward_) : n(n_), forward(forward_) { rev_idx = new int [2 * (1<<n)]; rev_idx_end = rev_idx; for (uint32_t i=0; i<(1<<n); i++) { uint32_t j = rev(i, n); if (j>i) { *rev_idx_end++ = int(i); *rev_idx_end++ = int(j); } } factors = new complex [1<<(n-1)]; for (uint32_t i=0; i<(1<<(n-1)); i++) factors[i] = omega(int(rev(i, n-1)), n, forward); // 1/N scaling of IFFT scale = forward ? 1.f : powf(2.f, -float(n)); } FFT::~FFT() { delete [] rev_idx; delete [] factors; } void FFT::transform(complex *x) { rev_in_place(x); for (size_t m=0; m<n-1; m++) { size_t jmax = 1<<m, imax = (1<<(n-m-1)); complex *x0 = x, *x1 = x; for (size_t i=0; i<imax; i++) { x1 += jmax; complex factor = factors[i]; for (size_t j=0; j<jmax; j++) { complex _x1 = *x1, y1 = (*x0-_x1) * factor; *x0 += _x1; *x1 = y1; x0 += 1; x1 += 1; } x0 = x1; } } int jmax = 1<<(n-1); complex *x0 = x, *x1 = x + jmax; if (!forward) { for (int j=jmax; j; j--) { complex _x0 = *x0, _x1 = *x1; *x0++ = (_x0+_x1) * scale; *x1++ = (_x0-_x1) * scale; } } else { for (int j=jmax; j; j--) { complex _x1 = *x1, y1 = (*x0-_x1); *x0++ += _x1; *x1++ = y1; } } } int log2(size_t n) { int logn; for (logn=0; n>1; n>>=1, logn++); return logn; } void fft(complex *x, size_t n) { static std::map<size_t, FFT *> fft_objects; if (fft_objects.find(n) == fft_objects.end()) fft_objects[n] = new FFT(size_t(log2(n)), true); fft_objects[n]->transform(x); } void ifft(complex *x, size_t n) { static std::map<size_t, FFT *> ifft_objects; if (ifft_objects.find(n) == ifft_objects.end()) ifft_objects[n] = new FFT(size_t(log2(n)), false); ifft_objects[n]->transform(x); }
true
22675b3a72afd4fa50be513ded6ec04e4ebcc517
C++
chenrudan/leetcode
/WordPattern/debug.cpp
UTF-8
748
3.328125
3
[]
no_license
#include<iostream> #include<map> #include<set> #include<sstream> using namespace std; bool wordPattern(string pattern, string str){ map<char, string> pattern_str; set<string> appeared_char; stringstream ss(str); string buf; for(int i=0; i<pattern.length(); i++){ ss >> buf; if(pattern_str.find(pattern[i]) == pattern_str.end()){ if(appeared_char.find(buf) != appeared_char.end()) return false; pattern_str[pattern[i]] = buf; appeared_char.insert(buf); }else{ if(pattern_str[pattern[i]] != buf) return false; } } if(ss >> buf) return false; return true; } int main(){ string pattern = "abba"; string str = "dog dog dog dog"; cout << "is word pattern? " << wordPattern(pattern, str) << endl; return 0; }
true
c68900cea355e967fcd664e0f36cd026b745ce08
C++
ishine/athena-1
/runtime/server/x86/utils/thread_pool.h
UTF-8
4,453
2.734375
3
[ "Apache-2.0" ]
permissive
// Copyright (C) 2022 ATHENA DECODER AUTHORS; Rui Yan // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================== #ifndef THREADPOOL_H_ #define THREADPOOL_H_ #include <stdio.h> #include <queue> #include <unistd.h> #include <pthread.h> #include <malloc.h> #include <stdlib.h> #include <assert.h> namespace athena { class Task { public: Task() = default; virtual ~Task() = default; virtual void run()=0; }; // Reusable thread class class Thread { public: Thread() { state = EState_None; handle = 0; } virtual ~Thread() { assert(state != EState_Started); } void start() { assert(state == EState_None); // in case of thread create error I usually FatalExit... if (pthread_create(&handle, nullptr, threadProc, this)) abort(); state = EState_Started; } void join() { // A started thread must be joined exactly once! // This requirement could be eliminated with an alternative implementation but it isn't needed. assert(state == EState_Started); pthread_join(handle, nullptr); state = EState_Joined; } protected: virtual void run() = 0; private: static void* threadProc(void* param) { auto thread = reinterpret_cast<Thread*>(param); thread->run(); return nullptr; } private: enum EState { EState_None, EState_Started, EState_Joined }; EState state; pthread_t handle; }; // Wrapper around std::queue with some mutex protection class WorkQueue { public: WorkQueue() { pthread_mutex_init(&qmtx,nullptr); // wcond is a condition variable that's signaled // when new work arrives pthread_cond_init(&wcond, nullptr); } ~WorkQueue() { // Cleanup pthreads pthread_mutex_destroy(&qmtx); pthread_cond_destroy(&wcond); } // Retrieves the next task from the queue Task *nextTask() { // The return value Task *nt = nullptr; // Lock the queue mutex pthread_mutex_lock(&qmtx); while (tasks.empty()) pthread_cond_wait(&wcond, &qmtx); nt = tasks.front(); tasks.pop(); // Unlock the mutex and return pthread_mutex_unlock(&qmtx); return nt; } // Add a task void addTask(Task *nt) { // Lock the queue pthread_mutex_lock(&qmtx); if (tasks.size() < 100000) { // Add the task tasks.push(nt); } // signal there's new work pthread_cond_signal(&wcond); // Unlock the mutex pthread_mutex_unlock(&qmtx); } private: std::queue<Task*> tasks; pthread_mutex_t qmtx; pthread_cond_t wcond; }; // Thanks to the reusable thread class implementing threads is // simple and free of pthread api usage. class PoolWorkerThread : public Thread { public: explicit PoolWorkerThread(WorkQueue& _work_queue) : work_queue(_work_queue) {} protected: void run() override { while (Task* task = work_queue.nextTask()){ task->run(); delete task; } } private: WorkQueue& work_queue; }; class ThreadPool { public: // Allocate a thread pool and set them to work trying to get tasks explicit ThreadPool(int n) { printf("Creating a thread pool with %d threads\n", n); for (int i=0; i<n; ++i) { threads.push_back(new PoolWorkerThread(workQueue)); threads.back()->start(); } } // Wait for the threads to finish, then delete them ~ThreadPool() { finish(); } // Add a task void addTask(Task *nt) { workQueue.addTask(nt); } // Asking the threads to finish, waiting for the task // queue to be consumed and then returning. void finish() { for (size_t i=0,e=threads.size(); i<e; ++i) workQueue.addTask(nullptr); for (auto it : threads) { it->join(); delete it; } threads.clear(); } private: std::vector<PoolWorkerThread*> threads; WorkQueue workQueue; }; } // namespace athena #endif//THREADPOOL_H_
true
f6944f49f494a2fa675a073e7e4ea2c2678b5dd2
C++
Ro6afF/hangman
/lib/User.cpp
UTF-8
6,011
3.25
3
[ "MIT" ]
permissive
#include "User.hpp" #include "bcrypt/BCrypt.hpp" #include "exceptions.hpp" #include <algorithm> #include <cstring> #include <fstream> bool User::logedIn = false; User User::user; User::User() : User("", "", "") {} User::User(const char *username, const char *email, const char *password) { strcpy(this->username, username); strcpy(this->email, email); strcpy(this->password, BCrypt::generateHash(password).c_str()); } void User::loadGuessed() { std::ifstream db(std::string(username) + "_guessed"); int num; db >> num; if (!db.good()) num = 0; std::string s; for (int i = 0; i < num; i++) { db >> s; this->guessedWords.insert(s); } db.close(); } void User::signUp(const char *username, const char *email, const char *password) { if (logedIn) throw UserException("Already loged in!"); std::fstream db("users.db", std::ios::in | std::ios::binary); int cnt; db.seekg(0, std::ios::beg); db.read(reinterpret_cast<char *>(&cnt), sizeof(cnt)); if (!db.good()) cnt = 0; User u; for (int i = 0; i < cnt; i++) { db.seekg(sizeof(cnt) + i * sizeof(u), std::ios::beg); db.read(reinterpret_cast<char *>(&u), sizeof(u)); if (strcmp(username, u.username) == 0) throw UserException("User with this username exists!"); if (strcmp(email, u.email) == 0) throw UserException("User with this email exists!"); } db.close(); u = User(username, email, password); cnt++; // create file if not exists db.open("users.db", std::ios::app); db.close(); db.open("users.db", std::ios::out | std::ios::binary | std::ios::in); db.seekp(0, std::ios::beg); db.write(reinterpret_cast<char *>(&cnt), sizeof(cnt)); // writes guessedWords too, but it is ignored when reading db.seekp(0, std::ios::end); db.write(reinterpret_cast<char *>(&u), sizeof(u)); db.close(); } void User::signIn(const char *username, const char *password) { if (logedIn) throw UserException("Already loged in!"); std::fstream db("users.db", std::ios::in | std::ios::binary); int cnt; db.seekg(0, std::ios::beg); db.read(reinterpret_cast<char *>(&cnt), sizeof(cnt)); if (!db.good()) cnt = 0; User u; for (int i = 0; i < cnt; i++) { db.seekg(sizeof(cnt) + i * sizeof(u), std::ios::beg); db.read(reinterpret_cast<char *>(&u), sizeof(u)); if (strcmp(username, u.username) != 0) continue; if (BCrypt::validatePassword(password, u.password)) { db.close(); // ignore what is in guessedWords u.guessedWords = std::set<std::string>(); u.guessedWords.clear(); u.loadGuessed(); logedIn = true; user = u; return; } else break; } db.close(); throw UserException("Wrong username or password!"); } void User::resetPassword(const char *username, const char *email, const char *password) { if (logedIn) throw UserException("Already loged in!"); std::fstream db("users.db", std::ios::in | std::ios::binary | std::ios::out); int cnt; db.seekg(0, std::ios::beg); db.read(reinterpret_cast<char *>(&cnt), sizeof(cnt)); if (!db.good()) cnt = 0; User u; for (int i = 0; i < cnt; i++) { db.seekg(sizeof(cnt) + i * sizeof(u), std::ios::beg); db.read(reinterpret_cast<char *>(&u), sizeof(u)); if (strcmp(username, u.username) != 0) continue; if (strcmp(email, u.email) != 0) continue; // ignore what is in guessedWords u.guessedWords = std::set<std::string>(); u.guessedWords.clear(); u.loadGuessed(); strcpy(u.password, BCrypt::generateHash(password).c_str()); db.seekp(sizeof(cnt) + i * sizeof(u), std::ios::beg); db.write(reinterpret_cast<char *>(&u), sizeof(u)); db.close(); return; } db.close(); throw UserException("No user found with the given mail and password!"); } std::vector<std::pair<int, std::string>> User::getStanding() { if (!logedIn) throw UserException("User not logged in!"); std::fstream db("users.db", std::ios::in | std::ios::binary); int cnt; db.seekg(0, std::ios::beg); db.read(reinterpret_cast<char *>(&cnt), sizeof(cnt)); if (!db.good()) cnt = 0; std::vector<std::pair<int, std::string>> standing; standing.reserve(cnt); User u; for (int i = 0; i < cnt; i++) { db.seekg(sizeof(cnt) + i * sizeof(u), std::ios::beg); db.read(reinterpret_cast<char *>(&u), sizeof(u)); // ignore what is in guessedWords u.guessedWords = std::set<std::string>(); u.loadGuessed(); standing.push_back(std::make_pair(u.guessedWords.size(), u.username)); } std::sort(standing.begin(), standing.end(), [](std::pair<int, std::string> a, std::pair<int, std::string> b) { if (a.first == b.first) return a.second < b.second; return a.first > b.first; }); return standing; } User *User::getUser() { if (!logedIn) return nullptr; return &user; } void User::addGuessed(const char *word) { std::ofstream file(std::string(this->username) + "_guessed"); this->guessedWords.insert(word); file << this->guessedWords.size() << std::endl; for (const std::string &x : this->guessedWords) file << x << std::endl; file.close(); } int User::guessedWordsCount() const { return this->guessedWords.size(); } const char *User::getUsername() const { return this->username; } const char *User::getEmail() const { return this->email; } const char *User::getPassword() const { return this->password; }
true
14d72bffb0360f8f98b7ad64f7fd95bf797a4707
C++
yanhongjuan/Algorithm
/bigNum_17.cpp
UTF-8
2,321
3.90625
4
[]
no_license
/*@brief:打印1到最大的n位数,比如:输入3则打印出1,2,3......一直到999*/ /*题目没有给出n的限制,所以是大数问题,n可能无限大,采用字符串的加法求解*/ #include <iostream> #include <string> #include <string.h> using namespace std; bool Increment(char *number); void PrintNumber(char *number); void printToMax_1(int n) { if(n<=0) return; char *number = new char[n+1]; memset(number,'0',n);//必须进行初始值设定,因为后面是直接用这个值进行 number[n]='\0'; while(!Increment(number))//判断有没有达到最高位 { PrintNumber(number); } cout<<endl; delete []number; } bool Increment(char *number) { int nLen = strlen(number); bool isOverflow = false; int nTakeover = 0;//只有在最低位时它为0 for(int i = nLen-1;i>=0;--i) { int nSum = number[i]-'0'+nTakeover; if(i==nLen-1) nSum++; if(nSum>=10) { if(i==0) isOverflow=true;//最低位为进位,则已经是最大值 else { nSum = nSum-10; nTakeover = 1; number[i] = '0'+nSum; } } else { number[i] = '0'+nSum; break; } } return isOverflow; } void PrintNumber(char *number) { //一个一个打印,从第一个非0元素开始打印 bool isBeging = true;//打印标志位 int nLen = strlen(number); for(int i=0;i<nLen;i++) { if(isBeging && number[i]!='0') isBeging = false; if(!isBeging) cout<<number[i]; } cout<<" "; } void printToMaxOfDigitsRecursively(char *number,int n,int index) { if(index == n-1) { PrintNumber(number); return; } for(int i=0;i<10;i++) { number[index+1] = i+'0'; printToMaxOfDigitsRecursively(number,n,index+1); } } void printToMax_2(int n) { if(n<=0) return; char *number = new char[n+1]; number[n] = '\0'; for(int i=0;i<10;i++) { number[0] = i+'0';//第一位的值 printToMaxOfDigitsRecursively(number,n,0); } delete []number; } int main() { int n; cin>>n; //printToMax_1(n); cout<<endl<<endl; printToMax_2(n); cout<<endl; return 0; }
true
9eea09f2d99500586efcc6015526eb648dc1741f
C++
thiagofsr97/RT-Template
/perspective_camera.cpp
UTF-8
2,084
2.53125
3
[ "MIT" ]
permissive
#include "perspective_camera.h" const float PerspectiveCamera::kDegreesToRadians_ = static_cast< float >( M_PI ) / 180.0f; PerspectiveCamera::PerspectiveCamera( void ) { } PerspectiveCamera::PerspectiveCamera( const glm::ivec2 &resolution, const glm::vec3 &position, const glm::vec3 &up_vector, const glm::vec3 &look_at, const float min_x, const float max_x, const float min_y, const float max_y, float aspect, float fov_degrees ) : Camera::Camera{ resolution, position, up_vector, look_at }, min_x_{ min_x }, max_x_{ max_x }, min_y_{ min_y }, max_y_{ max_y }, aspect_{ aspect }, fov_degrees_{ fov_degrees } { } Ray PerspectiveCamera::getWorldSpaceRay( const glm::vec2 &pixel_coord ) const { float witdh = max_x_ - min_x_; float height = max_y_ - min_y_; float x_value = ((witdh * pixel_coord[0]/static_cast< float >(resolution_[0])) - (witdh/2) ) * aspect_ * tan(fov_degrees_ * 0.5f * PerspectiveCamera::kDegreesToRadians_); // float x_value = ((8 * pixel_coord[0]/static_cast< float >(resolution_[0])) - 4 ) * aspect_ * tan(fov_degrees_ * 0.5f * PerspectiveCamera::kDegreesToRadians_); float y_value = ((witdh/2) - (witdh*(pixel_coord[1]/static_cast< float >(resolution_[1])))) * tan(fov_degrees_ * 0.5f * PerspectiveCamera::kDegreesToRadians_); // float y_value = (4 - (8*(pixel_coord[1]/static_cast< float >(resolution_[1])))) * tan(fov_degrees_ * 0.5f * PerspectiveCamera::kDegreesToRadians_); glm::vec3 ray_local_dir{ x_value , y_value , -1.0f}; return Ray{ position_, glm::normalize( onb_.getBasisMatrix() * ray_local_dir ) }; }
true
4df57444a240250a4860b3665e03c9ec4375b5da
C++
Shylie/shyll
/shyll/scanner.h
UTF-8
1,331
3.125
3
[ "MIT" ]
permissive
#pragma once #include <string> class Token { public: enum class Type { Long, Double, String, True, False, Identifier, AsLong, AsDouble, AsString, Store, Load, Delete, Create, FunctionCall, FunctionHeader, Add, Subtract, Multiply, Divide, Exponent, Negate, LessThan, LessThanEqual, GreaterThan, GreaterThanEqual, Equal, NotEqual, LogicalAnd, LogicalOr, LogicalNot, Duplicate, Pop, If, Else, EndIf, Do, While, Loop, Print, PrintLn, Trace, ShowTraceLog, ClearTraceLog, Comment, Error, End } TokenType; std::string Lexeme; int Line; bool HadWhitespace; Token(); Token(Type type, const std::string& lexeme, int line, bool hadWhitespace); }; class Scanner { public: Scanner(const std::string& source); Token ScanToken(); private: std::string source; size_t start; size_t current; int line; bool hadWhitespace; char Advance(); char Peek(int offset = 0) const; bool IsAtEnd() const; bool Match(char expected); void SkipWhitespace(); Token::Type IdentifierType() const; Token::Type CheckKeyword(const std::string& expected, Token::Type type) const; Token MakeToken(Token::Type type) const; Token ErrorToken(const std::string& message) const; static bool IsDigit(char c); static bool IsAlpha(char c); };
true
d15446a861e796d78a50171a4a6e331fa70f1417
C++
amos42/TinyHan
/Lib/UTF8.cpp
UTF-8
1,138
3.09375
3
[ "MIT" ]
permissive
#include <stdio.h> #include "UTF8.h" /// <summary> /// UTF8 문자열을 Unicode 문자열로 변환 /// </summary> /// <param name="str">UTF8 입력 문자열</param> /// <param name="output">Unicode 출력 문자열 버퍼</param> /// <returns>결과 문자열 포인터</returns> wchar_t* utf8_to_usc2(char* str, wchar_t *output) { unsigned char ch; wchar_t* p = output; while ((ch = *str++) != '\0') { if (!(ch & 0x80)) { *p++ = (wchar_t)ch; } else if ((ch >> 5) == 0x6) { unsigned char ch2 = *str++; if ((ch2 >> 6) == 2) { *p++ = (((unsigned short)ch & 0x1F) << 6) | ((unsigned short)ch2 & 0x3F); } } else if ((ch >> 4) == 0xE) { unsigned char ch2 = *str++; if ((ch2 >> 6) == 2) { unsigned char ch3 = *str++; if ((ch3 >> 6) == 2) { *p++ = (((unsigned short)ch & 0x0F) << 12) | (((unsigned short)ch2 & 0x3F) << 6) | ((unsigned short)ch3 & 0x3F); } } } } *p = L'\0'; return output; }
true
489f19bba47e1800daa687ec413591134faee1a8
C++
VolodymyrShkykavyi/cpp_piscine
/d04/ex03/Ice.cpp
UTF-8
700
3.1875
3
[]
no_license
#include "Ice.hpp" Ice::Ice(void): AMateria("ice") { } AMateria* Ice::clone() const { AMateria *clone = new Ice(); return clone; } void Ice::use(ICharacter& target) { AMateria::use(target); std::cout << "* shoots an ice bolt at "<< target.getName() <<" *" << std::endl; } Ice& Ice::operator=(Ice const & rhs) { std::cout << "(Ice) assignation operator called"; this->setXP(rhs.getXP()); return *this; } std::ostream& operator<<(std::ostream& out, Ice const &i) { out << "(Ice) WARNING ! ADD A LOGIC <<" << std::endl; (void)i; return out; } Ice::Ice(Ice const & src) { std::cout << "(Ice) copy constructor called" << std::endl; *this = src; return ; } Ice::~Ice(void) { }
true
f37fe274cd08de5df37f903be509b198439eba7a
C++
joemlevin/LevinJoseph_CSC17a_43950
/Lab/AbstractBaseDerivedClass/main.cpp
UTF-8
649
3.484375
3
[]
no_license
/* * File: main.cpp * Author: Joe * * Created on May 13, 2015, 12:53 PM */ //System Libraries #include <iostream> #include <cstdlib> using namespace std; //User Libraries #include "BaseDeck.h" #include "Card.h" //Execution begins here! int main(int argc, char** argv) { //Declare our deck BaseDeck deck; //Shufle the deck deck.shuffle(); //Deal some cards int *hand=deck.deal(); //Display the hand for(int card=0;card<5;card++){ Card a(hand[card]); cout<<a.face()<<" "<<a.suit()<<" "<<a.value()<<endl; } //Delete the hand delete []hand; //Exit Stage Right return 0; }
true
7b1976c569ec41aa0a74b2040d7f868eab7bf0d3
C++
Harrypotterrrr/ShenJ-programming
/Chapter 3/3-2.cpp
GB18030
743
3.09375
3
[]
no_license
/*1651574 1 */ #include <iostream> #include <iomanip> #include <cmath> #define pai 2*asin(1) using namespace std; int main() { double r = 1.5, h = 3; double roundCircum, roundSquare, sphereSquare, \ sphereVolume,cylinVolume; roundCircum = 2 * pai*r; roundSquare = pai * r * r; sphereSquare = 4 * pai*r*r; sphereVolume = 4. / 3.*pai*r*r*r; cylinVolume = roundCircum*h; cout <<setiosflags(ios::fixed)<< setprecision(2); //ʽ cout << "ԲܳΪ " << roundCircum << endl // << "ԲΪ " << roundSquare << endl << "ԲΪ " << sphereSquare << endl << "ԲΪ " << sphereVolume << endl << "ԲΪ " << cylinVolume << endl; return 0; }
true
99c2dc96c42577bad0e38d6540d96d57d0da188c
C++
cyendra/ACM_Training_Chapter_One
/2123 An easy problem/main.cpp
UTF-8
594
2.578125
3
[]
no_license
#include <iostream> #include <cstdio> using namespace std; int main() { int n,c; int a[10][10]; for (int i=0;i<=9;i++) { for (int j=0;j<=9;j++) { a[i][j]=i*j; } } for (int i=1;i<=9;i++) { a[1][i]=i; a[i][1]=i; } scanf("%d",&c); for (int loop=1;loop<=c;loop++) { scanf("%d",&n); for (int i=1;i<=n;i++) { for (int j=1;j<n;j++) { printf("%d ",a[i][j]); } printf("%d\n",a[i][n]); } } return 0; }
true
02ca8c7877ba0f9f3bf76fd7821e44f68ec3dd70
C++
VlShvets/Visualizer
/mainthread.cpp
UTF-8
5,464
2.75
3
[]
no_license
#include "mainthread.h" namespace Visualizer { /// Класс главного потока вычислений MainThread::MainThread(Painter *_painter, Status *_status, const QString _deltaTime) : painter(_painter), status(_status), sleepTime(_deltaTime.toInt()), isCompleted(false), isPause(false) { imitation = new Imitation; preliminaryProcessingOfData = new PreliminaryProcessingOfData; tertiaryProcessingOfData = new TertiaryProcessingOfData; /// -------------------------------------------------- /// Имитация /// -------------------------------------------------- /// Получение поверхностных стацционарных объектов // stationary = imitation->getStationary(); /// Получение эталонов etalons = imitation->getEtalons(); /// -------------------------------------------------- /// Предварительная обработка данных /// -------------------------------------------------- /// Установка указателя на статический массив эталонов preliminaryProcessingOfData->setTPubEtalon(imitation->getTPubEtalon()); /// Установка указателя на статический массив сообщений об эталонах preliminaryProcessingOfData->setTMsgTrc(imitation->getTMsgTrc()); /// -------------------------------------------------- /// Третичная обработка данных /// -------------------------------------------------- /// Установка указателя на статический массив сообщений об эталонах tertiaryProcessingOfData->setTUTrcMsg(preliminaryProcessingOfData->getTUTrcMsg()); /// Получение воздушных трасс airTracks = tertiaryProcessingOfData->getAirTracks(); /// Получение поверхностных трасс surfaceTracks = tertiaryProcessingOfData->getSurfaceTracks(); /// -------------------------------------------------- /// Отрисовка /// -------------------------------------------------- /// Отправление ЗКВ на виджет отрисовки // painter->setStationary(*stationary); /// Отправление эталонов на виджет отрисокви painter->setEtalons(*etalons); /// Отправление воздушных трасс на виджет отрисовки painter->setAirTracks(*airTracks); /// Отправление поверхностных трасс на виджет отрисовки painter->setSurfaceTracks(*surfaceTracks); } MainThread::~MainThread() { /// Удаление объекта класса внутренней третичной обработки данных delete tertiaryProcessingOfData; tertiaryProcessingOfData = nullptr; /// Удаление объекта класса внутренней предварительной обработки данных delete preliminaryProcessingOfData; preliminaryProcessingOfData = nullptr; /// Удаление объекта класса внутренней имитации delete imitation; imitation = nullptr; /// Очищение виджета отрисовки painter->clearing(); painter = nullptr; /// Очищение виджета отображения текущего состояния потока вычислений status->clearing(); status = nullptr; /// Очищение указателей на словари параметров ЗКВ, эталонов и трасс // stationary = nullptr; etalons = nullptr; airTracks = nullptr; surfaceTracks = nullptr; } /// Поток вычислений void MainThread::run() { float time = 0.0; /// Время int count = 0; /// Количество сообщений для третичной обработки данных /// Флаг завершения потока вычислений while(!isCompleted) { /// Флаг приостановки потока вычислений if(isPause) { msleep(PAUSE_T); continue; } msleep(sleepTime); time += DELTA_T; status->showInfo(Time, time); /// Имитация count = imitation->run(time); /// Предварительная обработка данных preliminaryProcessingOfData->run(count, time); /// Третичная обработка данных tertiaryProcessingOfData->run(count, time); /// Определение количества воздушных объектов status->showInfo(AirTrack, airTracks->count()); /// Определение количества поверхностных объектов status->showInfo(SurfaceTrack, surfaceTracks->count()); /// Обнуление количества сообщений для третичной обработки данных count = 0; } } }
true
2a8e101131b1248a99937b75d8f9180b1fae0ee9
C++
andrewstevens59/HadoopSearchEngine
/DyableWebGraph/DyableClusterGraph/DyableCommand/SummaryLinks.h
UTF-8
11,526
2.6875
3
[]
no_license
#include "./TestSubsumedSLinkBounds.h" // In order to approximate the webgraph using a compressed graph, // it's necessary to store a number of summary links for each merged // node. A summary link is a link with high traversal probability. // Due to the large number of links attatched to a node as a result // of continued compression, it's not possible to store all the // links for a merged node. Instead only a select number of links // are chosen to represent a certain percentage of the traversal // probability. It's also highly likely that links will be merged // together in the compression process giving them higher weight. // Merged links are therefore more likely to be chosen as summary // links as the compression continues. Note that a summary link // could be a forward or backward link. // The LocalData structure used to store cut links is as follows. Each // cut link is stored along with it's node in a link cluster. This // means that only the dst node has to be stored for a link. Now // the dst node stored is the cluster index. This means that each // node must in turn store it's cluster index along with its // traversal probability. The size of the link cluster is stored // along with the src node sequentially in memory. Link clusters // are also packed into blocks of external memory in a semi-breadth // first fashion allowing efficeint access to a link cluster // The approach taken to embed summary links in nodes based upon // their traversal probability is as follows. Every time a link // is merged, a new summary link is created. The creation level // is the level at which a link is first merged. All original // links have a creation level of zero. When a link is subsumed // becuase the two nodes it joins have been merged then the subsume // level needs to be recorded. A summary link cannot exist any // higher then its subsume level. When a summary link is subsumed // it needs to be recorded. Each subsumed link needs to be matched // up to its creation link counterpart. This is so each summary // link can be sorted appropriately. class CSummaryLinks : public CCommunication { // This stores the s_link node file CSegFile m_s_link_node_file; // This stores the base cluster mapping CSegFile m_base_clus_map_file; public: CSummaryLinks() { } // This takes the set of existing s_links and updates the cluster // mapping for each node. A supplied cluster map file is needed // to know what to map which node to. An external hash map is used // to update the entire node set. // @param map_file - this stores the mapping between each node and // - it's updated cluster mapping // @param CNodeStat::GetHashDivNum() - the number of hash division void UpdateSLinkMapping() { m_base_clus_map_file.SetFileName(CUtility::ExtendString ("LocalData/base_node_map", GetInstID(), ".set")); m_s_link_node_file.SetFileName(CUtility::ExtendString (SLINK_NODE_DIR, CNodeStat::GetHiearchyLevelNum(), ".set")); CMapReduce::ExternalHashMap("WriteOrderedMapsOnly", m_s_link_node_file, m_base_clus_map_file, m_s_link_node_file, CUtility::ExtendString ("LocalData/s_link_node_map", GetInstID()), sizeof(S5Byte), sizeof(S5Byte)); CNodeStat::SetHiearchyLevelNum(CNodeStat::GetHiearchyLevelNum() + 1); } }; // This is used to test for the correct functionality of s_link // creation and mapping after each compression cycle. class CTestSummaryLinks : public CNodeStat { // This stores the set of s_links CTrie m_s_link_map; // This stores the id of unique s_links CArrayList<int> m_s_link_id; // This stores the accumulated s_link node set CArrayList<S5Byte> m_acc_node_set; // This stores the global cluster mapping CTrie m_global_node_map; // This stores the set of global nodes CArrayList<SClusterMap> m_global_node_set; // This stores all the s_links that belong to this client CHDFSFile m_acc_s_link_file; // This checks the s_links for both the accumulative file and also the current file void CheckSLinks(CHDFSFile &s_link_file, _int64 &check_sum, CArrayList<SSummaryLink> &s_link_set) { SSummaryLink s_link; while(s_link.ReadSLink(s_link_file)) { int id = m_s_link_map.FindWord((char *)&s_link, 10); id = m_s_link_id[id]; check_sum += s_link.src.Value() + s_link.dst.Value(); if(s_link.create_level != s_link_set[id].create_level) { cout<<"Create Level Mismatch";getchar(); } if(s_link.src.Value() != s_link_set[id].src.Value()) { cout<<"src Mismatch";getchar(); } if(s_link.dst.Value() != s_link_set[id].dst.Value()) { cout<<"dst Mismatch";getchar(); } if(abs(s_link.trav_prob - s_link_set[id].trav_prob) > 0.000001) { cout<<"Traversal Probability Mismatch "<<s_link.trav_prob <<" "<<s_link_set[id].trav_prob;getchar(); } if(s_link.subsume_level != s_link_set[id].subsume_level) { cout<<"Subsume Level Mismatch";getchar(); } } } // This remaps the s_links to the new cluster mapping void RemapSLinks(CArrayList<SSummaryLink> &s_link_set) { SBLink b_link; _int64 check_sum = 0; SSummaryLink s_link; m_s_link_id.Initialize(4); for(int i=0; i<s_link_set.Size(); i++) { SSummaryLink &s_link = s_link_set[i]; check_sum += s_link.src.Value() + s_link.dst.Value(); m_s_link_map.AddWord((char *)&s_link, 10); if(!m_s_link_map.AskFoundWord()) { m_s_link_id.PushBack(i); } } CHDFSFile s_link_file; _int64 comp_check_sum = 0; for(int i=0; i<CNodeStat::GetHashDivNum() << 1; i++) { s_link_file.OpenReadFile(CUtility::ExtendString (ACC_S_LINK_DIR, CNodeStat::GetHiearchyLevelNum()-1, ".set", i)); CheckSLinks(s_link_file, comp_check_sum, s_link_set); } if(check_sum != comp_check_sum) { cout<<"Checksum Error4 "<<check_sum<<" "<<comp_check_sum;getchar(); } } // This checks the s_links for duplicates void CheckSLinkDuplicates(CArrayList<SSummaryLink> &s_link_set) { CTrie s_link_lookup(4); for(int i=0; i<s_link_set.Size(); i++) { SSummaryLink &s_link = s_link_set[i]; s_link_lookup.AddWord((char *)&s_link, 11); if(s_link_lookup.AskFoundWord()) { cout<<"Duplicate SLink Error "<< s_link.src.Value()<<" "<<s_link.dst.Value()<<" "<<(int)s_link.create_level<<" "<<i;getchar(); } } } public: CTestSummaryLinks() { } // This loads the accumulated s_links void LoadAccSLinks() { S5Byte node; CHDFSFile node_file; m_acc_node_set.Initialize(); for(int i=0; i<CNodeStat::GetHashDivNum() << 1; i++) { node_file.OpenReadFile(CUtility::ExtendString (SLINK_NODE_DIR, CNodeStat::GetHiearchyLevelNum(), ".set", i)); while(node_file.ReadCompObject(node)) { m_acc_node_set.PushBack(node); } } } // This checks the s_link mapping for accumulated s_links void CheckAccumulatedSLinks() { m_global_node_map.Initialize(4); SClusterMap clus_map; CHDFSFile global_clus_map_file; m_global_node_set.Initialize(); for(int i=0; i<GetHashDivNum(); i++) { global_clus_map_file.OpenReadFile(CUtility::ExtendString ("LocalData/base_node_map", GetInstID(), ".set", i)); while(clus_map.ReadClusterMap(global_clus_map_file)) { m_global_node_map.AddWord((char *)&clus_map.base_node, sizeof(S5Byte)); m_global_node_set.PushBack(clus_map); } } for(int i=0; i<m_acc_node_set.Size(); i++) { int id = m_global_node_map.FindWord((char *)&m_acc_node_set[i], sizeof(S5Byte)); m_acc_node_set[i] = m_global_node_set[id].cluster; } S5Byte node; int offset = 0; CSegFile node_file; for(int i=0; i<CNodeStat::GetHashDivNum() << 1; i++) { node_file.OpenReadFile(CUtility::ExtendString (SLINK_NODE_DIR, CNodeStat::GetHiearchyLevelNum()-1, ".set", i)); while(node_file.ReadCompObject(node)) { if(node != m_acc_node_set[offset++]) { cout<<"Node Mismatch";getchar(); } } } } // This is the entry function void TestSummaryLinks(CArrayList<SSummaryLink> &s_link_set) { m_s_link_map.Initialize(4); m_s_link_id.Initialize(4); CheckSLinkDuplicates(s_link_set); RemapSLinks(s_link_set); } }; // This class remaps the test links set originally present using // the global cluster mapping. It then checks that the composed // set of s_links and c_links are all accounted for in the test // link set. class CTestLinkSet : public CNodeStat { // This stores the global cluster mapping CTrie m_node_map; // This stores the cluster mapping CArrayList<SClusterMap> m_cluster_map; // This stores the link weight CArrayList<float> m_link_weight; // This stores the set of test links CTrie m_test_link_set; // This is true if a test link has been found CArrayList<bool> m_test_link_used; // This loads the base node mapping void LoadBaseNodeMapping() { SClusterMap clus_map; m_node_map.Initialize(4); m_cluster_map.Initialize(4); CHDFSFile global_map_file; for(int i=0; i<CNodeStat::GetHashDivNum(); i++) { global_map_file.OpenReadFile(CUtility::ExtendString ("LocalData/base_node_map", GetInstID(), ".set", i)); while(clus_map.ReadClusterMap(global_map_file)) { m_node_map.AddWord((char *)&clus_map.base_node, sizeof(S5Byte)); if(m_node_map.AskFoundWord()) { cout<<"Node Already Exists";getchar(); } m_cluster_map.PushBack(clus_map); } } } // This checks the c_links void CheckCLinks() { SClusterLink c_link; CHDFSFile c_link_file; for(int i=0; i<CNodeStat::GetHashDivNum(); i++) { c_link_file.OpenReadFile(CUtility::ExtendString ("GlobalData/LinkSet/bin_link_set", GetInstID(), ".set", i)); while(c_link.ReadLink(c_link_file)) { SBLink &b_link = c_link.base_link; int src_id = m_node_map.FindWord((char *)&b_link.src, sizeof(S5Byte)); int dst_id = m_node_map.FindWord((char *)&b_link.dst, sizeof(S5Byte)); b_link.src = m_cluster_map[src_id].cluster; b_link.dst = m_cluster_map[dst_id].cluster; int id = m_test_link_set.FindWord((char *)&b_link, sizeof(SBLink)); if(id < 0) { continue; } if(m_test_link_used[id] == true) { cout<<"link already used";getchar(); } m_test_link_used[id] = true; } } } // This checks the s_links void CheckSLinks() { SBLink b_link; CHDFSFile s_link_node_file; for(int j=0; j<CNodeStat::GetHiearchyLevelNum(); j++) { for(int i=0; i<CNodeStat::GetHashDivNum() << 1; i++) { s_link_node_file.OpenReadFile(CUtility::ExtendString (SLINK_NODE_DIR, j, ".set", i)); while(b_link.ReadBinaryLink(s_link_node_file)) { int id = m_test_link_set.FindWord((char *)&b_link, sizeof(SBLink)); if(id < 0) { continue; } m_test_link_used[id] = true; } } } } public: CTestLinkSet() { } // This loads the test link set void LoadTestLinkSet() { LoadBaseNodeMapping(); m_test_link_set.Initialize(4); m_test_link_used.Initialize(4); SBLink b_link; CHDFSFile test_link_file; test_link_file.OpenReadFile(CUtility::ExtendString ("GlobalData/LinkSet/test_link_set", (int)0)); float link_weight; while(b_link.ReadBinaryLink(test_link_file)) { test_link_file.ReadCompObject(link_weight); m_test_link_set.AddWord((char *)&b_link, sizeof(SBLink)); if(!m_test_link_set.AskFoundWord()) { m_test_link_used.PushBack(false); } } CheckCLinks(); CheckSLinks(); for(int i=0; i<m_test_link_used.Size(); i++) { SBLink b_link = *(SBLink *)m_test_link_set.GetWord(i); if(m_test_link_used[i] == false) { cout<<"Test Link Not Found "<<b_link.src.Value()<<" "<<b_link.dst.Value();getchar(); } } } };
true
a172bce37306516a05ff91f83ef7f5d173297565
C++
IliaGodlevsky/Arena-v-2.0
/Level/Level.h
UTF-8
944
2.90625
3
[]
no_license
#ifndef LEVEL_H_ #define LEVEL_H_ #include "../Globals/Globals.h" class Level; using LevelPtr = std::unique_ptr<Level>; class Level { public: Level(); Level(Unit* unit); Level(const Level&) = default; virtual Level& operator++(); virtual void setOwner(Unit* unit)final; virtual void setLevel(int level)final; virtual ~Level() = default; operator int()const; virtual LevelPtr clone()const = 0; protected: int m_level; private: virtual int getStartLevelValue()const; virtual int getAddedHpPerLevel()const = 0; virtual int getAddedMpPerLevel()const = 0; virtual int getAddedHpRegenPerLevel()const = 0; virtual int getAddedMpRegenPerLevel()const = 0; virtual int getAddedDamagePerLevel()const = 0; virtual int getAddedArmorPerLevel()const = 0; virtual int getHpRestorePercent()const = 0; virtual int getMpRestorePercent()const = 0; virtual int getMaxLevel()const; Unit* m_unit; // unit, that have this level class }; #endif
true
4a25c7401559cd73da8e2c2402a414f07efdfcc9
C++
RobotLocomotion/drake
/multibody/fem/fem_state.h
UTF-8
4,768
2.734375
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <memory> #include <vector> #include "drake/common/copyable_unique_ptr.h" #include "drake/multibody/fem/fem_indexes.h" #include "drake/multibody/fem/fem_state_system.h" #include "drake/systems/framework/context.h" namespace drake { namespace multibody { namespace fem { /** %FemState provides access to private workspace FEM state and per-element state-dependent data. %FemState comes in two flavors, an "owned" version that owns the state and data stored in the private workspace, and a "shared" version that doesn't own them. Because the "owned" version owns the state, one can modify it (e.g. through SetPositions). On the other hand, the "shared" version only provides a window into the const state and data, so one cannot modify it. For example, calling SetPositions on a "shared" FemState throws an exception. A "shared" FemState is cheap to construct and should never persist. It is advisable to acquire it for evaluation in a limited scope (e.g., in a calc method of a cache entry) and then discard it. @tparam_nonsymbolic_scalar */ template <typename T> class FemState { public: DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FemState); /** Creates an "owned" version of %FemState that allocates and accesses states and cached data using the provided `system`. The %FemState created with this constructor owns the states and data. @pre system != nullptr. */ explicit FemState(const internal::FemStateSystem<T>* system); /** Creates a "shared" version of %FemState that accesses states and cached data in the given `context`. The %FemState created with this constructor doesn't own the states and data. @pre system != nullptr. @pre context != nullptr. @pre system and context are compatible. */ FemState(const internal::FemStateSystem<T>* system, const systems::Context<T>* context); /** Returns an std::vector of per-element data in `this` %FemState. @param[in] cache_index The cache index of the per-element data. @tparam Data the per-element data type. @throws std::exception if the per-element data value doesn't actually have type `Data`. */ template <typename Data> const std::vector<Data>& EvalElementData( const systems::CacheIndex cache_index) const { const systems::Context<T>& context = get_context(); return system_->get_cache_entry(cache_index) .template Eval<std::vector<Data>>(context); } /** @name Getters and setters for the FEM states @anchor fem_state_setters_and_getters The FEM states include positions, time step positions (the positions at the previous time step t₀), velocities, and accelerations. Positions and velocities are actual state variables, while the accelerations are the saved result of previous calculations required by certain integrators such as NewmarkScheme. @{ */ const VectorX<T>& GetPositions() const; const VectorX<T>& GetPreviousStepPositions() const; const VectorX<T>& GetVelocities() const; const VectorX<T>& GetAccelerations() const; void SetPositions(const Eigen::Ref<const VectorX<T>>& q); void SetTimeStepPositions(const Eigen::Ref<const VectorX<T>>& q0); void SetVelocities(const Eigen::Ref<const VectorX<T>>& v); void SetAccelerations(const Eigen::Ref<const VectorX<T>>& a); /* @} */ /** Returns the number of degrees of freedom in the FEM model and state. */ int num_dofs() const { return get_context() .get_discrete_state(system_->fem_position_index()) .size(); } /** Returns the number of nodes in the FEM model. */ int num_nodes() const { return num_dofs() / 3; } /** Returns true if this FemState is constructed from the given system. */ bool is_created_from_system(const internal::FemStateSystem<T>& system) const { return &system == system_; } /** Returns an identical copy of `this` FemState. */ std::unique_ptr<FemState<T>> Clone() const; private: const systems::Context<T>& get_context() const { DRAKE_DEMAND((owned_context_ == nullptr) ^ (context_ == nullptr)); return context_ ? *context_ : *owned_context_; } systems::Context<T>& get_mutable_context() { if (owned_context_ == nullptr) throw std::runtime_error("Trying to mutate a shared FemState."); return *owned_context_; } const internal::FemStateSystem<T>* system_{nullptr}; /* One and only one of `owned_context_` and `context_` should be non-null for a given FemState. */ /* Owned context that contains the FEM states and data. */ copyable_unique_ptr<systems::Context<T>> owned_context_{nullptr}; /* Referenced context that contains the FEM states and data. */ const systems::Context<T>* context_{nullptr}; }; } // namespace fem } // namespace multibody } // namespace drake
true
f63c9b1f7c655e05eb7b9c394133bb1b3ee4f150
C++
calumjiao/fondational-courses
/data structure/hashtable implementation/hashtable.h
UTF-8
3,968
3.515625
4
[]
no_license
//----------------------------------------hashtable.h------------------------------------- /*This file is a declearation part of the class template HashTable, which stored a hash table by the chaining with separate list. Programmed by: Chaolun Wang at: 11/10/2015 */ #ifndef HASHTABLE_H #define HASHTABLE_H #include <utility> #include <vector> #include <iostream> #include <list> #include <fstream> #include <algorithm> #include <string> namespace cop4530 { static const unsigned int max_prime = 1301081; // max_prime is used by the helpful functions provided static const unsigned int default_capacity = 11; // the default_capacity is used if the initial capacity of the underlying vector of the hash table is zero. template <typename K, typename V> class HashTable { public: explicit HashTable(size_t size = 101); // constructor. Create a hash table, where the size of the vector is set to prime_below(size) (where size is default to 101), where prime_below() is a private member function of the HashTable and provided to you. ~HashTable(); // destructor. Delete all elements in hash table. bool contains(const K & k) const; // check if key k is in the hash table. bool insert(const std::pair<K, V> & kv); // add the key-value pair kv into the hash table. If the key is the hash table but with a different value, the value should be updated to the new one with kv. Return true if kv is inserted or the value is updated,false otherwise. bool insert (std::pair<K, V> && kv); // move version of insert. bool remove(const K & k); // delete the key k and the corresponding value if it is in the hash table. Return true if k is deleted, return false otherwise (i.e., if key k is not in the hash table). void clear(); // delete all elements in the hash table bool load(const char *filename); // load the content of the file with name filename into the hash table. In the file, each line contains a single pair of key and value, separated by a white space. void dump() const; //display all entries in the hash table. If an entry contains multiple key-value pairs, separate them by a semicolon character (:) bool write_to_file(const char *filename) const; //write all elements in the hash table into a file with name filename. size_t getSize() const; //get the size of Hash table size_t getCapacity() const; //get the capacity of Hash table bool match(const std::pair<K, V> &kv) const; // check if key-value pair is in the hash table private: std::vector< std::list< std::pair<K,V> > > mList; // memberdata container size_t mSize; // number of elements in hash table void makeEmpty(); // delete all elements in the hash table. void rehash(); // Rehash function. Called when the number of elements in the hash table is greater than the size of the vector. size_t myhash(const K &x) const; // return the index of the vector entry where x should be stored. unsigned long prime_below (unsigned long) const; // function to determine the proper prime numbers used in setting up the vector size void setPrimes(std::vector<unsigned long>&) const; // function to determine the proper prime numbers used in setting up the vector size }; #include "hashtable.hpp" }//end of namespace cop4530 #endif //end of hashtable.h
true
4ba67b733314c3b146ae9c1dc92526553ed568b7
C++
mserafin/Excavator-Simulator
/Axis.cpp
UTF-8
1,090
2.703125
3
[ "MIT" ]
permissive
#include "Axis.h" Axis::Axis() {} Axis::Axis(int rangeAxis, unsigned long responseDelay) { this->rangeAxis = rangeAxis; this->responseDelay = responseDelay; } void Axis::begin(int pin, void (*callback)(int value)) { this->pin = pin; this->onChange = callback; pinMode(this->pin, INPUT); } void Axis::refresh() { int reading = this->readAxis(this->pin); if (reading != 0) { this->checkDelayAxis(reading, story); if (!story.state) { this->onChange(reading); } } } int Axis::readAxis(int pin) { int reading = analogRead(pin); reading = map(reading, 0, 1023, 0, (rangeAxis * 2)); int distance = reading - rangeAxis; if (abs(distance) < 2) { distance = 0; } return distance; } void Axis::checkDelayAxis(int reading, Store &store) { float diff = rangeAxis - abs(reading); if (diff == 0) { diff = 0.1; } unsigned long currentMillis = millis(); if ((currentMillis - store.lastReadMillis) > (diff * responseDelay)) { store.lastReadMillis = currentMillis; store.state = false; return; } store.state = true; }
true
04eca54960074ad77f69046d18a7f2b0afcc79be
C++
FServais/SushiPP
/compiler/inference/Types.hpp
UTF-8
2,404
3.5625
4
[]
no_license
#ifndef TYPES_HPP_DEFINED #define TYPES_HPP_DEFINED #include <string> #include <vector> namespace inference { /** * @brief SPP types */ enum ShallowType { NO_TYPE = 0, // can be used for indicating that no type were specified BOOL = 1, INT = 2, FLOAT = 4, STRING = 8, CHAR = 16, ARRAY = 32, LIST = 64, FUNCTION = 128, VOID = 256 }; std::string to_string(ShallowType); /** * @class A class for representing a set of possible types */ class TypesHint { public: // default constructor : contains all the types TypesHint(); // constructed with a mask a mask of shallow type explicit TypesHint(int); // constructured with the set of shallow types composing it explicit TypesHint(const std::vector<ShallowType>&); /** * @brief Check the compatibility between the given types hint and the given ShallowType mask * @param int mask The shallow type mask * @retval bool True if they are compatible, false otherwise * @note They are compatible if they have at least one type in common */ bool compatible(int) const; /** * @brief Check the compatibility between the given types hint and another one * @param TypesHint the other type hint object * @retval bool True if they are compatible, false otherwise * @note They are compatible if they have at least one type in common */ bool compatible(const TypesHint&) const; /** * @brief Add some new types in the current types hint * @param int mask A mask of shallow type * @param TypesHint The type hint containing the new types to add */ void hints_union(int); void hints_union(const TypesHint&); /** * @brief Update the set of types by taking the intersection between the current set and the given one * @param int mask A mask of shallow type */ void hints_intersection(int); void hints_intersection(const TypesHint&); /** * @brief Remove some types from the current types hint * @param int mask A mask of shallow types * @note Can be considered as a set difference */ void remove(int); void remove(const TypesHint&); /** * @brief Convert the TypesHint objectinto a string * @retval std::string The TypesHint string */ std::string str() const; private: int hints; // a mask defining the types containing in the object // Values taken from ShallowType }; } #endif // TYPES_HPP_DEFINED
true
272f98ec5c450e128e2f0dfd93877f5e2b9b0c38
C++
faelribeiro22/BullCowGame
/Section_02/FBullCowGame.cpp
UTF-8
2,312
3.171875
3
[]
no_license
#include "FBullCowGame.h" #include <map> #define TMap std::map FBullCowGame::FBullCowGame() { Reset(); } void FBullCowGame::Reset() { constexpr int32 MAX_TRIES = 8; const FString HIDDEN_WORD = "ant"; MaxTries = MAX_TRIES; MyHiddenWord = HIDDEN_WORD; MyCurrentTry = 1; setbWinGame(false); return; } int32 FBullCowGame::GetMaxTries() const { return MaxTries; } int32 FBullCowGame::GetMyCurrentTry() const { return MyCurrentTry; } int32 FBullCowGame::GetHiddenWorldLength() const { return MyHiddenWord.length(); } bool FBullCowGame::IsGameWon() const { return GetbWinGame(); } bool FBullCowGame::GetbWinGame() const { return bWinGame; } void FBullCowGame::setbWinGame(bool winGame) { bWinGame = winGame; } EGuessStatus FBullCowGame::CheckGuessValidity(FString Guess) const { if (!IsIsogram(Guess)) // if the guess isn't an isogran { return EGuessStatus::Not_Isogram; } else if (false) // if the guess isn't all lowercase { return EGuessStatus::Not_Lowercase; // TODO write function } else if (GetHiddenWorldLength() != Guess.length()) // if the guess length is wrong { return EGuessStatus::Wrong_Length; } else { return EGuessStatus::OK; } } // received a VALID guess, increments turn, and returns count FBullCowCount FBullCowGame::SubmitValidGuess(FString Guess) { MyCurrentTry++; FBullCowCount BullCowCount; // loop through all letters in the guess int32 WorldLength = MyHiddenWord.length(); // assuming same length as guess for (int32 MHWChar = 0; MHWChar < WorldLength; MHWChar++) { // compare letters agains the guess for (int32 GChar = 0; GChar < WorldLength; GChar++) { if (Guess[GChar] == MyHiddenWord[MHWChar]) { // if they match then if (MHWChar == GChar) { BullCowCount.Bulls++; // increment bulls } else { BullCowCount.Cows++; // increment cows } } } if (BullCowCount.Bulls == WorldLength) { setbWinGame(true); }else { setbWinGame(false); } } return BullCowCount; } bool FBullCowGame::IsIsogram(FString Guess) const { // treat 0 and 1 letter words as isograms // loop through all the letters of the word // if the letters is in the map // we do NOT Isogram // otherwise // add the letter to the map as seen return true; // for example in cases where /0 is entered }
true
4bab08715ab54247c931e2caa3529bfa5b120529
C++
LuLuPan/lc1
/spiralMatrix.cpp
UTF-8
1,043
3.046875
3
[]
no_license
class Solution { public: vector<int> matrixOrder(vector<vector<int> > &matrix) { vector<int> results; if (matrix.empty()) results; size_t beginX = 0, endX = matrix[0].size() - 1; size_t beginY = 0, endY = matrix.size() - 1; while (1) { // --> for (size_t i = beginX; i <= endX; i++) results.push_back(matrix[beginY][i]); if (++beginY > endY) break; // | // v for (size_t i = beginY; i <= endY; i++) results.push_back(matrix[i][endX]); if (beginX > --endX) break; // <-- for (size_t i = endX; i >= beginX; i--) results.push_back(matrix[endY][i]); if (beginY > --endX) break; // ^ // | for (size_t i = endY; i >= beginY; i--) results.push_back(matrix[i][beginX]); if (++beginX > endX) break; } return results; } };
true
f7404e93cb3a5f073dcfdfd87c31a26d5a7e1f64
C++
ridoo/IlwisCore
/ilwiscoreui/tableoperations/sortcolumn.cpp
UTF-8
3,437
2.65625
3
[]
no_license
#include "kernel.h" #include "ilwisdata.h" #include "datadefinition.h" #include "columndefinition.h" #include "table.h" #include "tablemodel.h" #include "tableoperation.h" #include "sortcolumn.h" using namespace Ilwis; using namespace Desktop; SortColumn::SortColumn() : TableOperation("Column Sort", QUrl("SortColumn.qml"),TR("Sorts columns in ascending or decending order")) { } bool Ilwis::Desktop::SortColumn::canUse(TableModel *tblModel, const QVariantMap& parameter) const { bool ok; quint32 colIndex = parameter["columnindex"].toInt(&ok); if ( !ok || colIndex >= tblModel->getColumnCount()) return false; IDomain dom = tblModel->table()->columndefinition(colIndex).datadef().domain(); return hasType(dom->valueType(), itNUMBER | itSTRING | itDOMAINITEM); } template<typename T> struct OrderedPair{ OrderedPair(){} OrderedPair(const T& value, quint32 order) : _sortableValue(value), _order(order){} T _sortableValue; quint32 _order; }; void SortColumn::execute(const QVariantMap& parameters ) { bool ok; quint32 colIndex = parameters["columnindex"].toInt(&ok); if ( !ok || colIndex >= tableModel()->getColumnCount()) return ; QString direction = parameters["order"].toString(); if ( direction != "ascending" && direction != "decending") return ; IlwisTypes valueType = table()->columndefinition(colIndex).datadef().domain()->valueType(); std::vector<QVariant> values = table()->column(colIndex); std::vector<quint32> order(values.size()); quint32 index = 0; if ( hasType(valueType, itNUMBER)){ std::vector<OrderedPair<double>> numbers(values.size()); for(auto& opair : numbers){ opair = OrderedPair<double>(values[index].toDouble(), index); index++; } std::sort(numbers.begin(), numbers.end(),[](const OrderedPair<double>& opair1,const OrderedPair<double>& opair2)->bool { return opair1._sortableValue < opair2._sortableValue;}); index = 0; for(const auto& opair : numbers) order[index++] = opair._order; } if ( hasType(valueType, itSTRING)){ std::vector<OrderedPair<QString>> strings(values.size()); for(auto& opair : strings){ opair = OrderedPair<QString>(values[index].toString(), index); index++; } index = 0; std::sort(strings.begin(), strings.end(),[](const OrderedPair<QString>& opair1,const OrderedPair<QString>& opair2)->bool { return opair1._sortableValue < opair2._sortableValue;}); for(const auto& opair : strings) order[index++] = opair._order; } if ( hasType(valueType, itDOMAINITEM)){ std::vector<OrderedPair<QString>> strings(values.size()); IDomain dom = table()->columndefinition(colIndex).datadef().domain(); for(auto& opair : strings){ opair = OrderedPair<QString>(dom->impliedValue(values[index]).toString(), index); index++; } index = 0; std::sort(strings.begin(), strings.end(),[](const OrderedPair<QString>& opair1,const OrderedPair<QString>& opair2)->bool { return opair1._sortableValue < opair2._sortableValue;}); for(const auto& opair : strings) order[index++] = opair._order; } tableModel()->order(order); tableModel()->update(); } TableOperation *SortColumn::create() { return new SortColumn(); }
true
d0b4f66272f6a6a61f377704f5a95a344ab06ba8
C++
HaoYang0123/Kickstart
/Alphabet cake.cpp
UTF-8
2,993
2.59375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <fstream> using namespace std; void updateMap(char map[][27], int R, int C, int i, int j) { char cc[4] = {' ', ' ', ' ', ' '}; vector<pair<int, int>> pos; pos.push_back(pair<int, int>(-1,-1)); pos.push_back(pair<int, int>(-1,-1)); pos.push_back(pair<int, int>(-1,-1)); pos.push_back(pair<int, int>(-1,-1)); for(int k = i - 1; k >= 0; --k) { if(map[k][j] != '?') { cc[0] = map[k][j]; pos[0] = pair<int, int>(k, j); break; } } for(int k = i + 1; k < R; ++k) { if(map[k][j] != '?') { cc[1] = map[k][j]; pos[1] = pair<int, int>(k, j); break; } } for(int k = j - 1; k >= 0; --k) { if(map[i][k] != '?') { cc[2] = map[i][k]; pos[2] = pair<int, int>(i, k); break; } } for(int k = j + 1; k < C; ++k) { if(map[i][k] != '?') { cc[3] = map[i][k]; pos[3] = pair<int, int>(i, k); break; } } for(int k = 0; k < 4; ++k) { if(cc[k] == ' ') continue; char cur = cc[k]; pair<int, int> curPos = pos[k]; if(k < 2) { int curI = curPos.first; int minJ = j, maxJ = j; while(minJ >= 0 && map[curI][minJ] == map[curI][j]) --minJ; while(maxJ < C && map[curI][maxJ] == map[curI][j]) ++maxJ; map[i][j] = cur; bool flag = true; if(k == 0) { for(int i2 = curI + 1; i2 <= i; ++i2) { for(int j2 = minJ + 1; j2 < maxJ; ++j2) { if(map[i2][j2] != cur && map[i2][j2] != '?') { flag = false; break; } } } } else { for(int i2 = i; i2 < curI; ++i2) { for(int j2 = minJ + 1; j2 < maxJ; ++j2) { if(map[i2][j2] != cur && map[i2][j2] != '?') { flag = false; break; } } } } if(flag) return; } else { int curJ = curPos.second; int minI = i, maxI = i; while(minI >= 0 && map[minI][curJ] == map[i][curJ]) --minI; while(maxI < R && map[maxI][curJ] == map[i][curJ]) ++maxI; map[i][j] = cur; bool flag = true; if(k == 2) { for(int j2 = curJ + 1; j2 <= j; ++j2) { for(int i2 = minI + 1; i2 < maxI; ++i2) { if(map[i2][j2] != cur && map[i2][j2] != '?') { flag = false; break; } } } } else { for(int j2 = j; j2 < curJ; ++j2) { for(int i2 = minI + 1; i2 < maxI; ++i2) { if(map[i2][j2] != cur && map[i2][j2] != '?') { flag = false; break; } } } } if(flag) return; } } } int main() { ifstream fi("A-small-practice.in"); ofstream fo("res.txt"); int T; fi>>T; for(int t = 1; t <= T; ++t) { int R, C; fi>>R>>C; char map[27][27]; for(int i = 0; i < R; ++i) { for(int j = 0; j < C; ++j) { char tmp; fi>>tmp; map[i][j] = tmp; } } for(int i = 0; i < R; ++i) { for(int j = 0; j < C; ++j) { if(map[i][j] != '?') continue; updateMap(map, R, C, i, j); } } fo<<"Case #"<<t<<":"<<endl; for(int i = 0; i < R; ++i) { for(int j = 0; j < C; ++j) { fo<<map[i][j]; } fo<<endl; } } fo.close(); return 1; }
true
8e995a8b8b01883129cde9cfeac55e5bb02c6b2c
C++
rajonesiv/CS142
/PI/piec.cpp
UTF-8
1,525
2.96875
3
[]
no_license
//Andrew Jones // This version uses broadcast and reduce (instead of send and receive) //to compute pi. This program also uses striping. #include<iostream> #include<cmath> #include "mpi.h" using namespace std; /* thomas:$ module load openmpi-x86_64 thomas:$ mpicxx multihello.cpp thomas:$ mpirun -np 5 a.out */ double dosum(int id, int np, int n) //striping method. each processor will //compute every nth process { double sum=0; char sign; for(int k=id; k<=n; k=k+np) { if(k%2==0) //determine whether the numerator is positive or negative { sign=1; } else { sign=-1; } sum=sum+sign/((2*k)+1); //Leibniz series formula for pi } cout << "id=" << id << " sum=" << sum << endl; return sum; } int main(int argc, char *argv[]) { int n; int np,id; //I didn't add 'b' since I wasn't blocking MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&id); MPI_Comm_size(MPI_COMM_WORLD,&np); if(id==0) //our process is 0 { cout << "Please enter \"large\" n: "; cin >> n; } MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD); //broadcast to the world: don't need to //get processor id. double sum=dosum(id,np,n); double bigsum; //the sum of all the sums that each processor produces. MPI_Reduce(&sum,&bigsum,1,MPI_DOUBLE, //obtain answers from the world. MPI_SUM,0,MPI_COMM_WORLD); if(id==0) { double pi=4*bigsum; //solve for pi cout << "pi="<<pi<<endl; } MPI_Finalize(); return 0; }
true
15eaeb8fa44bcdd3aab951fe06820172fffc8967
C++
dicentra13/doctpl
/doc_template/src/fields/fieldxmlconvertor.cpp
UTF-8
2,248
2.546875
3
[]
no_license
#include "fieldxmlconvertor.h" #include "field.h" #include "../template/templatelayout.h" #include "../xmlconvertor.h" #include <QDomElement> #include <QDomDocument> #include <QDomNodeList> #include <QString> FieldXMLConvertor::FieldXMLConvertor(TemplateLayout *layout, XMLConvertor *convertor) : x_(0.0) , y_(0.0) , width_(0.0) , height_(0.0) , layout_(layout) , convertor_(convertor) {} std::unique_ptr<Field> FieldXMLConvertor::processFieldElement(size_t page, const QDomElement &fieldElement) { name_ = convertor_->getString(fieldElement, "name"); type_ = convertor_->getString(fieldElement, "type"); processCommonElement(fieldElement); return processSpecificElement(page, fieldElement); } void FieldXMLConvertor::writeFieldElement(const QString &fieldName, QDomElement *fieldElement) { fieldElement->setTagName("field"); fieldElement->setAttribute("name", fieldName); fieldElement->setAttribute("type", layout_->field(fieldName)->fieldType()); writeCommonElement(layout_->field(fieldName), fieldElement); writeSpecificElement(fieldName, fieldElement); } void FieldXMLConvertor::processCommonElement(const QDomElement &commonElement) { processPosElement(convertor_->getSingleChild(commonElement, "pos")); processSizeElement(convertor_->getSingleChild(commonElement, "size")); } void FieldXMLConvertor::processPosElement(const QDomElement &posElement) { x_ = convertor_->getDouble(posElement, "x"); y_ = convertor_->getDouble(posElement, "y"); } void FieldXMLConvertor::processSizeElement(const QDomElement &sizeElement) { width_ = convertor_->getDouble(sizeElement, "width"); height_ = convertor_->getDouble(sizeElement, "height"); } void FieldXMLConvertor::writeCommonElement(Field *field, QDomElement *commonElement) { QDomElement pos = commonElement->ownerDocument().createElement("pos"); pos.setAttribute("x", field->x()); pos.setAttribute("y", field->y()); commonElement->appendChild(pos); QDomElement size = commonElement->ownerDocument().createElement("size"); size.setAttribute("width", field->width()); size.setAttribute("height", field->height()); commonElement->appendChild(size); }
true
0bf695d8b37747c1c273697a8b2ad12b9f97dfe6
C++
LeeRainFish/blog_about_tech_maybe_plus_life
/cpp_skills/pointerpointer.cc
UTF-8
657
2.96875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> // const并未区分出编译期常量和运行期常量 // constexpr限定在了编译期常量 // it must be use pointer's pointer // do not know how mush num of resutl it is // so function arg trans a pointer which did not be allocate memory int compute(int **ppResult,int &count){ // int *pResult; // pResult = new int[count]; srand(time(NULL)); count = rand() % 10; *ppResult = new int[count]; for(int i = 0; i < count;i++){ (*ppResult)[i]= rand(); } } int main(){ int *pResult; int count; count = 0; compute(&pResult, count); }
true
85e9d73d3c6aa30202d0fc158807d27021fcea79
C++
JayRx/Prog-Projeto2
/BoardBuilder/ScrabbleJunior/player.h
UTF-8
622
2.96875
3
[]
no_license
#ifndef PLAYER_h #define PLAYER_h #include<iostream> #include<vector> using namespace std; typedef unsigned long IdNum; class Player{ public: Player(const string &name); void setName(const string &name); void setScore(int score); IdNum getId(); int getScore(); string getName(); vector<char> getHand(); void addTile(char tile); bool removeTile(char tile); bool isTileOnHand(char tile); bool isHandEmpty(); void showTiles(); private: static IdNum numPlayers; IdNum id; string playerName; int score; vector<char> playerHand; }; #endif /* player_h */
true
7e2fea99d1c0c549b2a10774f3d7f475f61f9fc8
C++
asritha13/crt-program
/7-12-19/largest amongst 3 numbers.cpp
UTF-8
324
3.484375
3
[]
no_license
/* largest amongst three numbers*/ #include<stdio.h> main() { int a,b,c; printf("\n enter three numbers:"); scanf("%d%d%d",&a,&b,&c); if(a==b && b==c) printf("\n all are equal"); else if(a>b && a>c) printf("\n a is big"); else if(b>c) printf("\n b is big"); else printf("\n c is big"); }
true
c49c755c5dac47c989f12704c1b836301334d53c
C++
yiZhuaMi/cPlusPlus
/LeetCode/DoublePointer/#763/src/main.cpp
UTF-8
1,507
3.796875
4
[]
no_license
// #763. 划分字母区间 // 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一个字母只 // 会出现在其中的一个片段。返回一个表示每个字符串片段的长度的列表。 // 示例 1: // 输入:S = "ababcbacadefegdehijhklij" // 输出:[9,7,8] // 解释: // 划分结果为 "ababcbaca", "defegde", "hijhklij"。 // 每个字母最多出现在一个片段中。 // 像 "ababcbacadefegde", "hijhklij" 的划分是错误的,因为划分的片段数较少。 #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; class Solution { public: vector<int> partitionLabels(string S) { vector<int> res; int start = 0, end = 0; // 用来记录字符char在s中的最大下标 unordered_map<char,int> m; // 利用map不可重复,遍历一趟得到每个字母的最大下标 for (int i = 0; i < S.size(); i++) m[S[i]] = i; for (int i = 0; i < S.size(); i++) { // 复习:不停的更新end!!!!!!max!!!!区间中有更长的,就扩大end end = max(end,m[S[i]]); // 如果i追上了end 就添加 if (i == end) { res.push_back(end - start + 1); start = end + 1; } } return res; } }; int main() { Solution s; s.partitionLabels("ababcbacadefegdehijhklij"); }
true
d72cadd7b29a097057fb0310845db9e9bcfac5b2
C++
platypus999/GraphicManager
/GraphicManager.cpp
UTF-8
1,034
2.734375
3
[]
no_license
#include "GraphicManager.h" using namespace graph_man; GraphicManager& grm = GraphicManager::getInstance(); int GraphicManager::group() { return ++gr; } GraphicManager::GraphicManager() :gr(0),pass(""),extension(".png") {} GraphicNode GraphicManager::load(std::string key, std::string filename) { int gh = LoadGraph((pass + (filename.empty() ? key : (filename + extension))).c_str()); data.emplace(key, std::make_shared<GraphicData>(gh, gr)); return (*this)[key]; } int GraphicManager::erase() { for (auto itr = data.begin(); itr != data.end();) { if (itr->second->getgroup() == gr) { itr = data.erase(itr); } else { ++itr; } } return --gr; } void GraphicManager::setPass(std::string p_) { pass = std::move(p_); } void GraphicManager::setExtension(std::string e_) { extension = std::move(e_); } GraphicNode GraphicManager::operator[](std::string n) { auto itr = data.find(n); if (itr != data.end()) { return GraphicNode(itr->second); } return GraphicNode(std::weak_ptr<GraphicData>()); }
true
46b82dd1062eb8e033aa0ee6dbd4c986e9d31a82
C++
hzqtc/zoj-solutions
/src/zoj3179.cpp
UTF-8
793
3.4375
3
[]
no_license
#include <iostream> #include <string> using namespace std; const int LineLength = 6; int sum(int a, int b) { return (a + b) * (b - a + 1) / 2; } int main() { int cse; cin >> cse; while(cse--) { int x, y, n = 0; string line; cin >> x >> y; for(int i = 0; i < 2; i++) { cin >> line; for(int k = 0, weight = 500000; k < LineLength; k++) { if(line[k] == '|') n += weight * (1 - i); weight /= 10; } } cin >> line; for(int i = 0; i < 5; i++) { cin >> line; for(int k = 0, weight = 100000; k < LineLength; k++) { if(line[k] == '|') n += weight * i; weight /= 10; } } if(sum(x, y) == n) cout << "No mistake" << endl; else cout << "Mistake" << endl; } }
true
805e7aed04e0d619c419008bd7416af2c5f64c5e
C++
DoctorLai/ACM
/leetcode/532. K-diff Pairs in an Array/532-2.cpp
UTF-8
883
2.90625
3
[]
no_license
// https://helloacm.com/how-to-find-the-k-diff-pairs-in-an-array-with-two-pointer-or-hash-map/ // https://leetcode.com/problems/k-diff-pairs-in-an-array/ class Solution { public: int findPairs(vector<int>& nums, int k) { sort(begin(nums), end(nums)); int n = nums.size(); int res = 0; int i = 0, j = 0; while (j < n) { if (i == j) { j ++; } if ((j < n) && (nums[j] - nums[i] == k)) { res ++; i ++; // skip duplicates while (i < n && (nums[i] == nums[i - 1])) i ++; while (j < n && (nums[j] == nums[j - 1])) j ++; } else if (j < n && (nums[j] - nums[i]) > k) { i ++; } else { j ++; } } return res; } };
true
84a304e63b7d35e3bf416910a0aa2b94cbfc1acb
C++
zjohnx3/zjohnx3
/zj/d452.cpp
UTF-8
855
3.078125
3
[]
no_license
#include<iostream> using namespace std; int bubble_sort(int m,int a[]){ int tmp,a_len=m; while (a_len>1){ //at least (m-1)times to bubble_sort a_len--; for (int i=1;i<=m;i++){ a[0]=a[1]; if (a[i]<a[i-1]){ tmp=a[i]; a[i]=a[i-1]; a[i-1]=tmp; } } } /* for (int i=1;i<=m;i++){ cout<<a[i]<<' '; } cout<<endl; */ return a[m]; } double fun_Qmid(int m,int a[]){ double Qmid=0; if (m%2==0){ Qmid=(a[m/2]+a[(m/2)+1])/2; } else { Qmid=a[(m+1)/2]; } return Qmid; } int main(){ int n; cin>>n; while (n>0){ n--; int m,a[1000],tmp; cin>>m; for (int i=1;i<=m;i++){ cin>>a[i]; } a[m]=bubble_sort(m,a); double Qmid=fun_Qmid(m,a); int difsum=0; for (int i=1;i<=m;i++){ if (a[i]>Qmid){ difsum+=a[i]-Qmid; } else { difsum+=Qmid-a[i]; } } cout<<difsum<<endl; } return 0; }
true
8cffe9604a868665a429114aa581b295a6bc24cd
C++
Huy-coder/BaiTapKyThuatLapTrinh
/bai22.cpp
UTF-8
304
2.859375
3
[]
no_license
#include<stdio.h> int Tich(int n) { int nhan = 1; for(int i = 1; i <= n; i++) { if(n % i == 0) nhan *= i; } return nhan; } void nhap(int &n) { printf("nhap n : "); scanf("%d",&n); } int main() { int n; nhap(n); printf("tich uoc cua n la : %d",Tich(n)); return 0; }
true
15813b9952b8aa50547318c18c19708e06663b4b
C++
lld2006/my-c---practice-project
/238/238.cpp
UTF-8
2,317
2.609375
3
[]
no_license
#include <cstdio> #include <cassert> #include <numeric> #include <vector> #include <bitset> #include "../lib/tools.h" #include "../lib/typedef.h" using namespace std; vector<int> get_vector(int num) { vector<int> vr; int sum = 0; while(num){ sum = num%10; vr.push_back(sum); num/=10; } return vr; } void create_vns(i64 seed, vector<int>& vns, vector<short>& vds, i64& span, i64& period) { i64 nmod = 20300713; i64 n0 = seed; vds.resize(20000000); int iter = 0; while(true){ vns.push_back(seed); vector<int> vt = get_vector(seed); for(unsigned int j = vt.size(); j> 0; --j) vds[iter++] = vt[j-1]; seed *= seed; seed %= nmod; if(n0 == seed) break; } span = accumulate(vds.begin(), vds.begin()+iter, 0LL); period = iter; for(unsigned int i = 0; i < 200; ++i){ vector<int> vt = get_vector(seed); for(unsigned int j = vt.size(); j> 0; --j) vds[iter++] = vt[j-1]; seed *= seed; seed %= nmod; } vds.resize(iter+1); } int main() { timer mytime; vector<int> vn; const int val = 80846691; const int val2 = val+1; bitset<val2>* pbit = new bitset<val2>; bitset<val2>& mybit = *pbit; mybit.reset(); vector<short> vds; i64 span, period; create_vns(14025256, vn, vds, span, period); i64 sum = 0; //the starting digit is nth+1; i64 limit = 2000000000000000LL; //limit = 1000; mybit.set(0); printf("%.6f\n", mytime.getTime()); int nmod = limit % span; int value = limit/span; for(unsigned int nth = 0; nth < 200; ++nth){ //if(nth % 10 ==0) // printf("%d %lld\n", nth, sum); if(nth > 0 && !vds[nth-1]) continue; int dsum = 0; for(unsigned int j = nth; j< nth+period; ++j){ int nt = j; dsum += vds[nt]; if(!mybit.test(dsum)){ mybit.set(dsum); // the following code is necessary when limit is small //if(dsum > limit) break; if(dsum <= nmod) sum += (value+1) * (nth+1); else sum += (value) * (nth+1); } } } printf("%lld\n", sum); }
true
5fbecdcfcfc8566f643318f285233fa1c9a25239
C++
ChebbiL/barrier-and-look-back-options
/src/european_option.cpp
UTF-8
6,263
3.015625
3
[ "Apache-2.0" ]
permissive
#include "european_option.hpp" double european_option::stock_price_single(){ return stock_price_single(T,t); } double european_option::stock_price_single(double time_final, double time_inital){ return St * exp((r - 0.5*sigma*sigma) * (time_final - time_inital) + sigma * sqrt(time_final - time_inital) * get_Nrandom()); } double european_option::stock_price_single(double S0, double T1, double t1){ return S0*exp((r - 0.5*pow(sigma, 2))*(T1 - t1) + sigma*sqrt(T1 - t1)*get_Nrandom()); } double european_option::stock_price_single(double Z){ return St * exp((r - 0.5*sigma*sigma) * (T - t) + sigma * sqrt(T - t) * Z); } double european_option::call_payoff_single(){ double current_value = stock_price_single(); current_value > K ? current_value = discount*(current_value - K) : current_value = 0; return current_value; } double european_option::call_payoff_single(double Z){ double current_value = stock_price_single(Z); current_value > K ? current_value = discount*(current_value - K) : current_value = 0; return current_value; } double european_option::d1_calculate() { return (log(St/K)+(r+0.5*sigma*sigma)*tau)/sigma*sqrt(tau); } double european_option::d1_calculate(double St_given, double strike_given) { return (log(St_given/strike_given)+(r+0.5*sigma*sigma)*tau)/sigma*sqrt(tau); } double european_option::d1_calculate(double a, double b, double c) { return (a+(b+0.5*c*c)*tau)/c*sqrt(tau); } double european_option::d2_calculate() { return (log(St/K)+(r-0.5*sigma*sigma)*(tau))/sigma*sqrt(tau); } double european_option::d2_calculate(double St_given, double strike_given) { return (log(St_given/strike_given)+(r-0.5*sigma*sigma)*(tau))/sigma*sqrt(tau); } // MAIN FUNCTIONS double european_option::payoff_theoretic() { return St*normal_cdf(d1) - K*discount*normal_cdf(d2); } double european_option::payoff_theoretic(double initial_value_given, double strike_given) { return initial_value_given*normal_cdf(d1_calculate(initial_value_given, strike_given)) - strike_given*discount*normal_cdf(d2_calculate(initial_value_given, strike_given)); } double european_option::delta_theoretic() { return normal_cdf(d1); } double european_option::delta_theoretic_call(double S0, double k){ double d = (log(S0 / k) + (r + sigma*sigma / 2)*tau) / (sigma*sqrt(tau)); return normal_cdf(d); } double european_option::gamma_theoretic() { return (exp(-0.5*d1*d1) / sqrt(2 * M_PI)) / (St*sigma*sqrt(T)); } double european_option::gamma_theoretic_call(double S0, double k){ double d = (log(S0 / k) + (r + sigma*sigma / 2)*(tau)) / (sigma*sqrt(tau)); return normal_pdf(d) / (S0*sigma*sqrt(tau)); } double european_option::vega_theoretic() { return St*sqrt(T)*(exp(-0.5*d1*d1) / sqrt(2 * M_PI)); } double european_option::vega_theoretic_call(double S0, double k){ double d = (log(S0 / k) + (r + sigma*sigma / 2)*tau) / (sigma*sqrt(tau)); return S0*normal_pdf(d)*sqrt(tau); } double european_option::delta_lr(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount * (stock_price_at_maturity[i] - K) * random_sample[i] : result += 0; } return result / (St * sigma * sqrt(tau) * number_iterations); } double european_option::delta_pw(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount * stock_price_at_maturity[i] /St : result += 0; } return result / number_iterations; } double european_option::gamma_lrpw(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount * K * random_sample[i] : result += 0; } return result / (number_iterations * St * St * sigma * sqrt(tau)); } double european_option::gamma_pwlr(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount*(stock_price_at_maturity[i] / (St*St)) * (random_sample[i] / (sigma * sqrt(tau)) - 1) : result += 0; } return result / number_iterations; } double european_option::gamma_lrlr(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount*(stock_price_at_maturity[i] - K) * (( pow(random_sample[i], 2) - 1) / (St*St*sigma*sigma*(tau)) - random_sample[i] / (St*St*sigma*sqrt(tau))) : result += 0; } return result / number_iterations; } double european_option::vega_lr(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount * (stock_price_at_maturity[i] - K) * ((pow(random_sample[i], 2) - 1) / sigma - random_sample[i] * sqrt(tau)) : result += 0; } return result / number_iterations; } double european_option::vega_pw(){ double result = 0.0; for (long int i = 0; i < number_iterations; i++){ (stock_price_at_maturity[i] > K) ? result += discount * stock_price_at_maturity[i] * (-sigma*tau + sqrt(tau)*random_sample[i]) : result += 0; } return result / number_iterations; } // -------------- // PUBLIC // -------------- // ACCESS FUNCTIONS double european_option::price(){ double result = 0.0; for (int i=0; i< number_iterations; i++){ result += call_payoff_single(random_sample[i]); } return result/number_iterations; } double european_option::delta(std::string method){ if (method=="pw") {return delta_pw();} if (method=="lr") {return delta_lr();} return delta_theoretic(); } double european_option::delta(){return delta("th");} double european_option::gamma(std::string method){ if (method=="lrpw") {return gamma_lrpw();} if (method=="lrlr") {return gamma_lrlr();} if (method=="pwlr") {return gamma_pwlr();} return gamma_theoretic(); } double european_option::gamma(){return gamma("th");} double european_option::vega(std::string method){ if (method=="pw") {return vega_pw();} if (method=="lr") {return vega_lr();} return vega_theoretic(); } double european_option::vega(){return vega("th");} // SERVICE FUNCTIONS
true
df796215c5ec32f9fa493bd94c5cb8a6484412a6
C++
15831944/arbi6
/arbi5_runing/LogPriceStrategy.cpp
UTF-8
782
2.6875
3
[]
no_license
// LogPriceStrategy.cpp: implementation of the LogPriceStrategy class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "LogPriceStrategy.h" #include "Contract.h" #include <iostream> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// LogPriceStrategy::LogPriceStrategy() { } LogPriceStrategy::LogPriceStrategy(int i) { } LogPriceStrategy::~LogPriceStrategy() { } void LogPriceStrategy::trig() { cout << Contract::get(contract)->getPrice().getAsk() << ":"; cout << Contract::get(contract)->getPrice().getBid() << endl; } void LogPriceStrategy::set(string contract) { this->contract = contract; }
true
5e1d96aaf03aee07be91489f2a86a30fefb3e0a1
C++
MrGunerhanal/Algorithm-DataStrucure_Programming
/HackerEarth/I:O/array.cpp
UTF-8
663
3.578125
4
[]
no_license
#include <iostream> using namespace std; // function declaration int Insert(int* pList, int& listSize, int value); int main () { bool ret; int listSize = 5; int* pList [listSize]; ret = Insert(pList, &listSize, 1); std::cout << ret << std::endl; return 0; } bool Insert(int* pList, int& listSize, int value) { // local variable declaration int i, j; for (i = 0; i < listSize; i++) { if (value > pList[i]) { for (j = 0; j < listSize; j++) { pList[j + 1] = pList[j]; } pList[j] = value; return (true); } } return (false); }
true
bf0d2fd46c648a26cd26df1a05025d44c202f4e3
C++
ReemHossain/Gesture-Control-Robot
/robot_code/robot_code.ino
UTF-8
1,559
3.140625
3
[]
no_license
int rightMotorR = 23; int rightMotorB = 22; int leftMotorR = 24; int leftMotorB = 25; int rightMotorS = 45; int leftMotorS = 44; void setup() { // put your setup code here, to run once: pinMode(rightMotorR, OUTPUT); pinMode(rightMotorB, OUTPUT); pinMode(rightMotorS, OUTPUT); pinMode(leftMotorR, OUTPUT); pinMode(leftMotorB, OUTPUT); pinMode(leftMotorS, OUTPUT); analogWrite(rightMotorS, 100); //0 - 255 speed of the car analogWrite(leftMotorS, 100); } void loop() { // put your main code here, to run repeatedly: car_forward(); delay(2000); car_backward(); delay(2000); car_right(); delay(2000); car_left(); delay(2000); car_stop(); delay(2000); } void car_forward(){ digitalWrite(rightMotorR, HIGH); digitalWrite(rightMotorB, LOW); digitalWrite(leftMotorR, HIGH); digitalWrite(leftMotorB, LOW); } void car_backward(){ digitalWrite(rightMotorR, LOW); digitalWrite(rightMotorB, HIGH); digitalWrite(leftMotorR, LOW); digitalWrite(leftMotorB, HIGH); } void car_right(){ digitalWrite(rightMotorR, HIGH); digitalWrite(rightMotorB, LOW); digitalWrite(leftMotorR, LOW); digitalWrite(leftMotorB, HIGH); } void car_left(){ digitalWrite(rightMotorR, LOW); digitalWrite(rightMotorB, HIGH); digitalWrite(leftMotorR, HIGH); digitalWrite(leftMotorB, LOW); } void car_stop(){ digitalWrite(rightMotorR, LOW); digitalWrite(rightMotorB, LOW); digitalWrite(leftMotorR, LOW); digitalWrite(leftMotorB, LOW); }
true
6956d1cf37f6e1a9a4b1160c763f01d74757c6a3
C++
chienpm304/Data-Structure---Algorithm
/Projects/Dictionary-with-B-tree/ConsoleApplication1/ConsoleApplication1/Source.cpp
UTF-8
982
2.96875
3
[]
no_license
#include <iostream> using namespace std; class MayLoc { private: float m_tgian; protected: virtual float congSuat(); void setTgian(float t); public: MayLoc(); virtual ~MayLoc(){ cout << "huy cha" << endl; }; float tinhLuongNuoc(); }; MayLoc::MayLoc() { this->m_tgian = 0; } void MayLoc::setTgian(float t) { this->m_tgian = t; } float MayLoc::tinhLuongNuoc() { return congSuat()* m_tgian; } float MayLoc::congSuat() { return 0; } class MayLyTam : public MayLoc { private: float m_cs; protected: float congSuat(); public: ~MayLyTam(){ cout << "huy con" << endl; } MayLyTam(float cs, float t); }; MayLyTam::MayLyTam(float cs, float t) { this->m_cs = cs; this->setTgian(t); //this->m_tgian = t; /*1*/ //(float*)(this); } float MayLyTam::congSuat() { return this->m_cs; } void main() { MayLoc *pm = new MayLoc(); //if (pm->congSuat() < 5) /*2*/ { MayLyTam ml(81.9, 10); pm = &ml; /*3*/ cout << "Luong nuoc = " << pm->tinhLuongNuoc(); } delete pm; /*4*/ }
true
0340456403e2efad786647bcea1d7451ba93b163
C++
meganvanwelie/quick-imps
/comp_vision/active_contour_edge_based/characterization.cpp
UTF-8
3,343
2.78125
3
[ "Unlicense" ]
permissive
#include "characterization.hpp" vector<Point> foreground(Mat& src, int obj_id) { vector<Point> foreground; int row, col; for ( row = 0; row < src.rows; ++row ) { for ( col = 0; col < src.cols; ++col ) { if (src.at<uchar>(row, col) == obj_id) { Point p = Point(col, row); foreground.push_back(p); } } } return foreground; } /* Normalize values in vector between a and b. In-place. */ void normalize(vector<double>& vec, double a, double b) { double minv, maxv; minMaxLoc(vec, &minv, &maxv); transform(vec.begin(), vec.end(), vec.begin(), [=](double d){return a + ((d - minv) * (b - a) / (maxv - minv));}); } int area(vector<Point> object) { return object.size(); } Point centroid(vector<Point> object) { Point p; double xbar = 0.0; double ybar = 0.0; double area = 0.0; for ( int i = 0; i < object.size(); ++i ) { p = object[i]; xbar += p.x; ybar += p.y; area += 1; } xbar = xbar / area; ybar = ybar / area; return Point(xbar, ybar); } double circularity(vector<Point> object) { Point center = centroid(object); double a = 0.0; double b = 0.0; double c = 0.0; Point p; for ( int i = 0; i < object.size(); ++i ) { p = object[i]; a += pow((p.x - center.x), 2); b += (p.x - center.x) * (p.y - center.y); c += pow((p.y - center.y), 2); } b = 2 * b; double circularity = -1; if ( b != 0 && a != c ) { double h = sqrt(((a-c)*(a-c)) + (b*b)); double emin = ((a+c)/2) - (((a-c)/2)*((a-c)/h)) - ((b/2)*(b/h)); double emax = ((a+c)/2) + (((a-c)/2)*((a-c)/h)) + ((b/2)*(b/h)); circularity = emin / emax; } return circularity; } double orientation(vector<Point> object) { Point center = centroid(object); double a = 0.0; double b = 0.0; double c = 0.0; Point p; for ( int i = 0; i < object.size(); ++i ) { p = object[i]; a += pow((p.x - center.x), 2); b += (p.x - center.x) * (p.y - center.y); c += pow((p.y - center.y), 2); } //double theta = (b != 0 && a != c) ? (0.5 * atan( 2*b / (a - c) )) : -1; double theta = (b != 0 && a != c) ? (0.5 * acos( (a-c) / sqrt(pow(b, 2) + pow(a-c, 2)))) : 0; return theta; } double curvature(Point l, Point m, Point n) { double dxi = (m.x - l.x); double dxi1 = (n.x - m.x); double dyi = (m.y - l.y); double dyi1 = (n.y - m.y); double dsi = sqrt(pow(dxi,2) + pow(dyi,2)); double dsi1 = sqrt(pow(dxi1,2) + pow(dyi1,2)); double ds = (dsi + dsi1) / 2.0; double c = (1/ds) * sqrt(pow((dxi/dsi) - (dxi1/dsi1), 2) + pow((dyi/dsi) - (dyi1/dsi1), 2)); c = pow(c, 2); return c; } vector<double> curvature(vector<Point> contour) { vector<double> cs; // adjust contour to handle start and end positions contour.insert(contour.begin(), contour[contour.size() - 1]); contour.push_back(contour[1]); // assign contour calculation for all points in original contour int i; for ( i = 1; i < contour.size() - 1; ++i ) { cs.push_back(curvature(contour[i-1], contour[i], contour[i+1])); } normalize(cs); return cs; }
true
84da4a0fb7931429ab990adb7ed54ba010cad2d5
C++
sang96qn/Node_MCU
/TimerBlynk.ino
UTF-8
2,075
2.578125
3
[]
no_license
// Them chuc nang cap nhat Wifi #include <ESP8266WiFi.h> #include <BlynkSimpleEsp8266.h> #include <SimpleTimer.h> SimpleTimer timer; const char *ssid = "viettel1234"; const char* pass = "1223334444"; char auth[] ="97adedf7831747ef8c971f8c6e5a3e6b"; #define LED 16 // GPIO 16 #define buttonPin 0 int buttonPushCounter =0; int buttonState =0; int lastButtonState=0; bool isFirstConnect = true; bool check =false; long startSecond ; long stopSecond; long nowSecond; BLYNK_WRITE(V5) { //0-1 v5 //1-0 gp2 int pinValue = param.asInt(); if(pinValue == 1) { check =true; } else { check =false; } buttonPushCounter++; } BLYNK_WRITE(V2) { int checkTime = param.asInt(); if(checkTime ==1) { check =true; Blynk.virtualWrite(V5,1); } else { check =false; Blynk.virtualWrite(V5,0); } } BLYNK_CONNECTED() { if (isFirstConnect) { Blynk.syncAll(); // Blynk.notify("TIMER STARTING!!!!"); isFirstConnect = false; } } void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(buttonPin,INPUT); pinMode(LED,OUTPUT); digitalWrite(LED,1); Blynk.begin(auth,ssid,pass); timer.setInterval(5000L,reconnectBlynk); } void checkButton() { buttonState = digitalRead(buttonPin); if(buttonState != lastButtonState ) { if(buttonState == HIGH) { buttonPushCounter++; } else { // Serial.println("Release"); if(buttonPushCounter %2 ==0) { // Serial.println("Tat led"); Blynk.virtualWrite(V5,0); check = false; } else { // Serial.println("Bat led"); Blynk.virtualWrite(V5,1); check =true; } } } lastButtonState = buttonState; if(check == 1) digitalWrite(LED,0); else digitalWrite(LED,1); } void reconnectBlynk() { if (!Blynk.connected()) { if(Blynk.connect()) { BLYNK_LOG("Reconnected"); } else { BLYNK_LOG("Not reconnected"); } } } void loop() { // put your main code here, to run repeatedly: Blynk.run(); timer.run(); checkButton(); }
true
c1f64427c1b4c204e519a030935f384fadfb9703
C++
codypotter/CS300TermProject
/ServiceEntry.cpp
UTF-8
707
2.921875
3
[]
no_license
// // Created by enjoi on 11/26/2019. // #include "ServiceEntry.h" /** * Constructor for the ServiceEntry class * @param serviceEntryRef - A reference to the json value in the directory * @param key - the service code */ ServiceEntry::ServiceEntry(Json::Value &serviceEntryRef, std::string key){ name = serviceEntryRef["name"].asString(); id = key; fee = serviceEntryRef["fee"].asInt(); } /** * Gets a JSON Value representation of the data * @return - JSON Value of the service entry */ Json::Value ServiceEntry::getJsonValue() { Json::Value jsonValue; jsonValue["name"] = name; jsonValue["id"] = id; jsonValue["fee"] = fee; return jsonValue; }
true
e2bcae978e4e0a93b5a9597934624922445ede59
C++
LewisSean/SEU-compilers-project
/LR1.cpp
GB18030
10,900
2.6875
3
[]
no_license
#include<vector> #include<map> #include<set> #include<string> #include<stack> #include<vector> #include<iostream> #include<algorithm> #include"LR1.h" #include <chrono> #include<queue> using namespace std; using namespace chrono; bool Item::productionEqual(const Item& it)const { if (it.pos == pos && production == it.production)return true; else return false; } bool Item::operator == (const Item& it) const{ if (it.pos == pos && production == it.production && it.predict_set == predict_set)return true; else return false; } bool Item::operator != (const Item& it) const { return !(*this == it); } set<string> LR1State::getStrFirst(vector<string>& str, map<string, set<string>>& myFirst, set<string>& VT, set<string>& VN) { set<string> result; int index; for (index = 0; index < str.size(); index++) { string term = str[index]; if (VT.count(term)) { result.emplace(term); break; } else if(VN.count(term)){ bool noEplison = true; for (auto& i : myFirst[term]) { if (i == myEpsilon)noEplison = false; else result.emplace(i); } if (noEplison)break; } else { cout << term <<" :"<<"calculate First error!" << endl;break; } } if (index == str.size())result.emplace(myEpsilon); return result; } void LR1State::closure(map<string, vector<vector<string>>>& grammar, map<string, set<string>>& myFirst, set<string>& VT, set<string>& VN) { bool unchanged; while (1) { unchanged = true; set<Item> items2add; for (auto& item : items) { if (item.pos == item.end)continue; string B = item.production.second[item.pos]; if (item.pos < item.end && VN.count(B)) { for (auto& p : grammar[B]) { //First vector<string> beta(item.production.second.begin()+item.pos+1, item.production.second.end()); set<string> itemFirst = getStrFirst(beta,myFirst,VT,VN); if (itemFirst.count(myEpsilon)) { itemFirst.erase(myEpsilon); itemFirst.insert(item.predict_set.begin(),item.predict_set.end()); } //µitemµpredict Item tmp(make_pair(B, p)); tmp.predict_set = itemFirst; if (!items.count(tmp)) { items2add.emplace(tmp); unchanged = false; } else { for (auto& i : tmp.predict_set) { if (items.find(tmp)->predict_set.count(i) == 0) { unchanged = false; for (auto& i : items.find(tmp)->predict_set)if (!tmp.predict_set.count(i)) { tmp.predict_set.emplace(i); } items2add.emplace(tmp); break; } } } } } } for (auto& i : items2add) { if (items.count(i)) { items.erase(items.find(i)); } items.emplace(i); } /* cout << "-------------------" << endl; for (auto& i : items) i.printItem(); */ if (unchanged)break; } } bool LR1State::isEqual(const LR1State& target) { if (items.size() != target.items.size())return false; for (auto& i : items) { if (target.items.count(i) == 0) return false; if (*target.items.find(i) != i) return false; } return true; } bool LR1State::itemsEqual(const LR1State& target) { if (items.size() != target.items.size())return false; for (auto& i : items) { if (target.items.count(i) == 0) return false; if (target.items.find(i)->pos != i.pos) return false; } return true; } LR1State LR1::GOTO(LR1State& I, const string& X, int id) { LR1State newState(id); for (auto& item : I.items) { if (item.pos != item.end && item.production.second[item.pos] == X) { Item newItem(item); newItem.pos++; newState.items.emplace(move(newItem)); } } newState.closure(grammar, myFirst,VT_names,VN); return newState; } LR1State LR1::GOTO_Epsilon(LR1State& I, const string& X, int id) { LR1State newState(id); for (auto& item : I.items) { if (item.pos != item.end && item.production.second[item.pos] == X) { Item newItem(item); newItem.pos+=2; newState.items.emplace(move(newItem)); } } newState.closure(grammar, myFirst, VT_names, VN); return newState; } void LR1::generateDFA() { stack<int> statesToDo; statesToDo.push(0); while (!statesToDo.empty()) { int id = statesToDo.top(); statesToDo.pop(); vector<string> nextSymbols = LR1States[id].getNextSymbol(); for (auto& i : nextSymbols) { LR1State newState = GOTO(LR1States[id], i, totalStates); int dst = contain(newState); if (dst >= 0) { LR1States[id].addEdge(i, dst);continue; } LR1States[id].addEdge(i, totalStates); totalStates++; LR1States.emplace(make_pair(newState.id, newState)); statesToDo.push(newState.id); //newState.printState(); } /* for (auto& i : nextSymbols) { if (myFirst[i].size() == 1 && myFirst[i].count(myEpsilon)) { for (auto& item : LR1States[id].items) { if (item.pos + 1 < item.end && item.production.second[item.pos] == i) { string nextnext = item.production.second[item.pos + 1]; LR1State newState = GOTO_Epsilon(LR1States[id], i, totalStates); int dst = contain(newState); if (dst >= 0) { LR1States[id].addEdge(nextnext, dst);continue; } LR1States[id].addEdge(nextnext, totalStates); totalStates++; LR1States.emplace(make_pair(newState.id, newState)); statesToDo.push(newState.id); //newState.printState(); } } } } */ } cout << "generate LR1 Parsing Table successfully! Total state: "<< totalStates << endl; } //-iԼi﷨ Ȼ״̬ void LR1::generateParsingTable() { for (int i = 0; i < totalStates; i++) { parsing_table.emplace_back(map<string,int>()); for (auto& edge : LR1States[i].edges) { parsing_table[i].emplace(make_pair(edge.first, edge.second)); } for (auto& item : LR1States[i].items) { if (item.pos == item.end) { vector<string> p(1,item.production.first); p.insert(p.end(), item.production.second.begin(), item.production.second.end()); int id = find(grammar_names.begin(), grammar_names.end(), p)-grammar_names.begin() + 1; //עһȫ for (auto& predict : item.predict_set) { //ƽ/Լͻ if (parsing_table[i].count(predict)) { if (SRconflict(predict, p)) { //Լ parsing_table[i][predict] = -id; //ԼrulerŵĸʾԼ } } else { parsing_table[i].emplace(make_pair(predict, -id)); } } } } } } //0ƽ 1Լ /* a grammar rule's precedence is determined by looking at the precedence of its right-most terminal symbol 1.If the current token has higher precedence than the rule on the stack, it is shifted. 2.If the grammar rule on the stack has higher precedence, the rule is reduced. 3.If the current token and the grammar rule have the same precedence, the rule is reduced for left associativity, whereas the token is shifted for right associativity. 4.If nothing is known about the precedence, shift/reduce conflicts are resolved in favor of shifting (the default). */ bool LR1::SRconflict(const string& predict, const vector<string>& ruler) { int ruler_level = -1; for (int i = ruler.size() - 1; i > 0; i--) { if (VT_names.count(ruler[i]))ruler_level = VT[ruler[i]].first; } int predict_level = VT[predict].first; if (predict_level > ruler_level)return 0; //case 1 else if (predict_level < ruler_level)return 1; //case 2 else { if (predict_level == -1)return 0; //case 4 //case 3 01 if (VT[predict].second)return 0; //ҽ-ƽ else return 0; //-Լ } } void LR1::printParsingTable() { cout << endl <<"grammar ruler are as follows:" << endl; for (int i = 0; i < grammar_names.size();i++) { cout << i+1 << ". " << grammar_names[i][0] << " -> "; for (int j = 1; j < grammar_names[i].size(); j++)cout << grammar_names[i][j] << " "; cout << endl; } for (int i = 0; i < parsing_table.size(); i++) { cout << "------LR1 state: " << i <<"--------"<< endl; for (auto& g : parsing_table[i]) { if (g.second < 0)cout << g.first << ": reduce " << -g.second << endl; else { if(VT_names.count(g.first))cout << g.first << ": shift " << g.second << endl; else cout << g.first << ": goto " << g.second << endl; } } } } void LR1::printParsingTable2file() { ofstream ofs("LR1_Parsing_table.out"); ofs << endl << "grammar ruler are as follows:" << endl; for (int i = 0; i < grammar_names.size();i++) { ofs << i + 1 << ". " << grammar_names[i][0] << " -> "; for (int j = 1; j < grammar_names[i].size(); j++)ofs << grammar_names[i][j] << " "; ofs << endl; } for (int i = 0; i < parsing_table.size(); i++) { ofs << "------LR1 state: " << i << "--------" << endl; for (auto& g : parsing_table[i]) { if (g.second < 0)ofs << g.first << ": reduce " << -g.second << endl; else { if (VT_names.count(g.first))ofs << g.first << ": shift " << g.second << endl; else ofs << g.first << ": goto " << g.second << endl; } } } ofs.close(); } void LR1::generateDFA_BFS() { auto start = system_clock::now(); queue<int> statesToDo; statesToDo.push(0); while (!statesToDo.empty()) { int id = statesToDo.front(); statesToDo.pop(); vector<string> nextSymbols = LR1States[id].getNextSymbol(); for (auto& i : nextSymbols) { LR1State newState = GOTO(LR1States[id], i, totalStates); int dst = contain(newState); if (dst >= 0) { LR1States[id].addEdge(i, dst);continue; } LR1States[id].addEdge(i, totalStates); totalStates++; LR1States.emplace(make_pair(newState.id, newState)); statesToDo.emplace(newState.id); //newState.printState(); } for (auto& i : nextSymbols) { if (myFirst[i].size() == 1 && myFirst[i].count(myEpsilon)) { for (auto& item : LR1States[id].items) { if (item.pos + 1 < item.end && item.production.second[item.pos] == i) { string nextnext = item.production.second[item.pos + 1]; LR1State newState = GOTO_Epsilon(LR1States[id], i, totalStates); int dst = contain(newState); if (dst >= 0) { LR1States[id].addEdge(nextnext, dst);continue; } LR1States[id].addEdge(nextnext, totalStates); totalStates++; LR1States.emplace(make_pair(newState.id, newState)); statesToDo.emplace(newState.id); //newState.printState(); } } } } } auto end = system_clock::now(); auto duration = duration_cast<microseconds>(end - start); cout << "" << double(duration.count()) * microseconds::period::num / microseconds::period::den << "" << endl; cout << "generate LR1 Parsing Table successfully! Total state: " << totalStates << endl; }
true
14b0576fabb5123f8d57519409b86166b2e924ca
C++
PapaDabrowski/-Studies-Project-Object-Orientated-Programing
/App.h
UTF-8
17,526
2.984375
3
[]
no_license
//Created by PAPA Dąbrowski #include "App.h" #include "Handgun.h" #include <iostream> #include <cstdlib> #include <fstream> #include <ostream> #include <iostream> #include <string> #include <vector> using namespace std; App_Singleton * App_Singleton::instance=0; App_Singleton * App_Singleton::getInstance() { if(instance==0) { instance=new App_Singleton; } else return instance; } App_Singleton::App_Singleton() { Menu(); } void App_Singleton::Create(unsigned int X) { cout<<"What type od Weapon you want to create"<<endl; cout<<"Wybierz 1 by stworzyć Pasazerski:"<<endl; cout<<"Wybierz 2 by stworzyć Towarowy"<<endl; cout<<"Wybierz 3 by wybrać Wojskowy"<<endl; cout<<"Wybierz 4 by wybrać Odrzutowiec"<<endl; cout<<"Wybierz 5 by wybrać Myśliwiec"<<endl; try{ cin>>select; if(cin.fail()) { throw WrongValue(9); system("clear"); } if((select>7) || (select<0)) { throw WrongValue(9); system("clear"); } } catch(WrongValue obj) { system("clear"); cout<<obj.what()<<endl<<endl; cin.clear(); cin.ignore(300, '\n'); } catch(...) { std::cout << "Undefined behaviour!" <<endl<<endl; } try{ switch(select) { bool Silencer_; unsigned int MagSize_,Range_,Weight_,Rate_,Scope_,MuzzleVelocity_; float LiczbaSilnikow_; case 1: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cout<<"Enter the Fire Rate of your Weapon"<<endl<<"Type number: "; cin>>Rate_; if(cin.fail()) throw WrongValue(6); if(Rate_==0) throw WrongValue(6); Weapon *Object=new AssaultRifle(X,LiczbaSilnikow_,MagSize_,MuzzleVelocity_, Range_,Weight_,Rate_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } case 2: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cout<<"Enter the Scope of your Weapon"<<endl<<"Type number: "; cin>>Scope_; if(cin.fail()) throw WrongValue(7); if((Scope_%2!=0)||(Scope_==0)) throw WrongValue(7); Weapon *Object=new SniperRifle(X,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Scope_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } case 3: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cout<<"Do you want a Silencer to your Handgun"<<endl<<"Type number [1/0]: "; cin>>Silencer_; if(cin.fail()) throw WrongValue(8); if((Silencer_!=0) && (Silencer_!=1)) throw WrongValue(8); Weapon *Object= new Handgun(X,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Silencer_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } case 4: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cin>>Rate_; if(cin.fail()) throw WrongValue(6); if(Rate_==0) throw WrongValue(6); cout<<"Do you want a Silencer to your PDW"<<endl<<"Type number [1/0]: "; cin>>Silencer_; if(cin.fail()) throw WrongValue(8); if((Silencer_!=0) && (Silencer_!=1)) throw WrongValue(8); Weapon *Object=new PDW(X,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_,Silencer_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } case 5: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cout<<"Enter the Fire Rate of your Weapon"<<endl<<"Type number: "; cin>>Rate_; if(cin.fail()) throw WrongValue(6); if(Rate_==0) throw WrongValue(6); Weapon *Object=new LMG(X,LiczbaSilnikow_,MagSize_,MuzzleVelocity_, Range_,Weight_,Rate_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } case 6: { cout<<"Enter the LiczbaSilnikow of your Weapon"<<endl<<"Type number: "; cin>>LiczbaSilnikow_; if(cin.fail()) throw WrongValue(1); if(LiczbaSilnikow_<=0) throw WrongValue(1); cout<<"Enter the MagSize of your Weapon"<<endl<<"Type number: "; cin>>MagSize_; if(cin.fail()) throw WrongValue(2); if(MagSize_==0)throw WrongValue(2); cout<<"Enter the MuzzleVelocity of your Weapon"<<endl<<"Type number: "; cin>>MuzzleVelocity_; if(cin.fail()) throw WrongValue(3); if(MuzzleVelocity_==0) throw WrongValue(3); cout<<"Enter the Range of your Weapon"<<endl<<"Type number: "; cin>>Range_; if(cin.fail()) throw WrongValue(4); if(Range_==0) throw WrongValue(4); cout<<"Enter the Weight of your Weapon"<<endl<<"Type number: "; cin>>Weight_; if(cin.fail()) throw WrongValue(5); if(Weight_==0) throw WrongValue(5); cout<<"Enter the Fire Rate of your Weapon"<<endl<<"Type number: "; cin>>Rate_; if(cin.fail()) throw WrongValue(6); if(Rate_==0) throw WrongValue(6); cout<<"Enter the Scope of your Weapon"<<endl<<"Type number: "; cin>>Scope_; if(cin.fail()) throw WrongValue(7); if((Scope_%2!=0)||(Scope_==0)) throw WrongValue(7); Weapon *Object=new DMR(X,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_,Scope_); Case.AddElement(Object); system("clear"); cout<<endl<<"Object has been created!"<<endl<<endl; break; } } } catch(WrongValue obj) { system("clear"); cout<<obj.what()<<endl<<endl; cin.clear(); cin.ignore(300,'\n'); } catch(...) { std::cout << "Undefined behaviour!" <<endl<<endl; } } void App_Singleton::Menu() { int i=0; int j,k; unsigned int ID=1; while(i!=1) { if(Case.GetCounter()==0) { cout<<"Welcome to App which create and store Wepons"<<endl; cout<<"Options:"<<endl; cout<<"1-Create"<<endl; cout<<"2-Load"<<endl; cout<<"3-End Program"<<endl; cout<<"Type number: "; do { cin>>k; if(cin.fail()) { cout<<"You have typed wrong thing!"<<endl<<"Type Again: "; cin.clear(); cin.ignore(300, '\n'); continue; } else break; }while(true); if((k==1)||(k==2)||(k==3)) { switch(k) { case 1: { bool IDstatus=false; int w=0; system("clear"); while(Case.GetCounter()!=w) { for(int h=0;h<Case.GetCounter();h++) if(Case[h]->GetId()==ID) IDstatus=true; if(IDstatus==true) { ID+=1; w=0; } else w+=1; IDstatus=false; } Create(ID); ID+=1; break; } case 2: { system("clear"); Load(); break; } case 3: { i+=1; break; } } } else cout<<"Wrong Number!"<<endl; } if(Case.GetCounter()!=0) { cout<<"Options:"<<endl; cout<<"1-Create"<<endl; cout<<"2-Remove"<<endl; cout<<"3-Show All Objects"<<endl; cout<<"4-Save"<<endl; cout<<"5-End Program"<<endl; cout<<"Type number: "; do { cin>>j; if(cin.fail()) { cout<<"You have typed wrong number!"<<endl<<"Type Again: "; cin.clear(); cin.ignore(300, '\n'); continue; } else break; }while(true); if((j>0)&&(j<6)) { switch(j) { case 1: { system("clear"); int m,w,z; w=0; z=0; while(w!=1) { z=0; for(m=0;m<Case.GetCounter();m++) { if(ID==Case[m]->GetId()) { ID++; break; } else z++; } if(z==Case.GetCounter()) w++; } Create(ID); ID+=1; break; } case 2: { bool status=false; unsigned int X; cout<<"Id of Weapon which you want remove"<<endl<<"Type number: "; cin>>X; for(int k=0;k<Case.GetCounter();k++) { if(Case[k]->GetId()==X) status=true; } if(status==true) { Case.RemoveElement(X); system("clear"); cout<<endl<<"Object have been removed!"<<endl<<endl; } else { system("clear"); cout<<endl<<"Error: Object with that Id don't exist!"<<endl; } break; } case 3: { system("clear"); ShowAll(); break; } case 4: { Save(); system("clear"); cout<<endl<<"SavedData Complited!"<<endl; break; } case 5: { i++; break; } } } else { system("clear"); cout<<"Undefined behaviour!"<<endl<<endl; } } } } void App_Singleton::ShowAll() { cout<<endl<<"Objects:"<<endl; for(int i=0; i<Case.GetCounter();i++){ cout<<Case[i]->GetType(); cout<<" ID: "<<Case[i]->GetId()<<" Info: "<<Case[i]->GetInfo()<<" Range: "<<Case[i]->GetRange()<<endl;} cout<<endl; } void App_Singleton::Save() { std::ofstream FILE; FILE.open("SavedData.txt",std::ios::out); FILE<<Case.GetCounter()<<endl; for(int i=0;i<Case.GetCounter();i++) { Case[i]->Save(FILE); } } void App_Singleton::Load() { int Counter; unsigned int MuzzleVelocity_,Range_,MagSize_,Weight_,Id_,Scope_,Silencer_,Rate_; float LiczbaSilnikow_; std::string temp,temp1,temp2,temp3,temp4,temp5,temp6,temp7; std::ifstream FILE; FILE.open("SavedData.txt",std::ios::in); getline(FILE,temp); Counter=atoi(temp.c_str()); if(Counter!=0) { for(int g=0;g<=Counter;g++) { getline(FILE,temp1); if(temp1=="AssaultRifle") { getline(FILE,temp2); Id_=atoi(temp2.c_str()); getline(FILE,temp3); LiczbaSilnikow_=atof(temp3.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp4); MuzzleVelocity_=atoi(temp4.c_str()); getline(FILE,temp5); Range_=atoi(temp5.c_str()); getline(FILE,temp6); Weight_=atoi(temp6.c_str()); getline(FILE,temp7); Rate_=atoi(temp7.c_str()); Weapon *Object=new AssaultRifle(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_); Case.AddElement(Object); } if(temp1=="SniperRifle") { getline(FILE,temp2); Id_=atoi(temp2.c_str()); getline(FILE,temp3); LiczbaSilnikow_=atof(temp3.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp4); MuzzleVelocity_=atoi(temp4.c_str()); getline(FILE,temp5); Range_=atoi(temp5.c_str()); getline(FILE,temp6); Weight_=atoi(temp6.c_str()); getline(FILE,temp); Scope_=atoi(temp.c_str()); Weapon *Object=new SniperRifle(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Scope_); Case.AddElement(Object); } if(temp1=="Handgun") { getline(FILE,temp); Id_=atoi(temp.c_str()); getline(FILE,temp); LiczbaSilnikow_=atof(temp.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp); MuzzleVelocity_=atoi(temp.c_str()); getline(FILE,temp); Range_=atoi(temp.c_str()); getline(FILE,temp); Weight_=atoi(temp.c_str()); getline(FILE,temp); Silencer_=atoi(temp.c_str()); Weapon *Object=new Handgun(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Silencer_); Case.AddElement(Object); } if(temp1=="LMG") { getline(FILE,temp); Id_=atoi(temp.c_str()); getline(FILE,temp); LiczbaSilnikow_=atof(temp.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp); MuzzleVelocity_=atoi(temp.c_str()); getline(FILE,temp); Range_=atoi(temp.c_str()); getline(FILE,temp); Weight_=atoi(temp.c_str()); getline(FILE,temp); Rate_=atoi(temp.c_str()); Weapon *Object=new LMG(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_); Case.AddElement(Object); } if(temp1=="PDW") { getline(FILE,temp); Id_=atoi(temp.c_str()); getline(FILE,temp); LiczbaSilnikow_=atof(temp.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp); MuzzleVelocity_=atoi(temp.c_str()); getline(FILE,temp); Range_=atoi(temp.c_str()); getline(FILE,temp); Weight_=atoi(temp.c_str()); getline(FILE,temp); Rate_=atoi(temp.c_str()); getline(FILE,temp); Silencer_=atoi(temp.c_str()); Weapon *Object=new PDW(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_,Silencer_); Case.AddElement(Object); } if(temp1=="DMR") { getline(FILE,temp); Id_=atoi(temp.c_str()); getline(FILE,temp); LiczbaSilnikow_=atof(temp.c_str()); getline(FILE,temp); MagSize_=atoi(temp.c_str()); getline(FILE,temp); MuzzleVelocity_=atoi(temp.c_str()); getline(FILE,temp); Range_=atoi(temp.c_str()); getline(FILE,temp); Weight_=atoi(temp.c_str()); getline(FILE,temp); Rate_=atoi(temp.c_str()); getline(FILE,temp); Scope_=atoi(temp.c_str()); Weapon *Object=new DMR(Id_,LiczbaSilnikow_, MagSize_,MuzzleVelocity_,Range_,Weight_,Rate_,Scope_); Case.AddElement(Object); } } FILE.close(); } else cout<<endl<<"File is empty!"<<endl<<endl; }
true
1a757779171507f9746bcd84c6e135ea14878900
C++
Igincan/AUS-sem-2
/Semestralka2/UzemnaJednotkaZucastneniVolici.cpp
UTF-8
664
2.59375
3
[]
no_license
#include "KUzemnaJednotkaZucastneniVolici.h" int KUzemnaJednotkaZucastneniVolici::operator()(UzemnaJednotka* objekt) { int pocetZucastnenych = 0; zrataj(objekt, pocetZucastnenych); return pocetZucastnenych; } void KUzemnaJednotkaZucastneniVolici::zrataj(UzemnaJednotka* UJ, int& pocetZucastnenych) { if (UJ->getTypUzemnejJednotky() == TypUzemnejJednotky::OBEC) { Obec* obec = dynamic_cast<Obec*>(UJ); for (int i = 1; i <= obec->getPocetOkrskov(); i++) { pocetZucastnenych += obec->getVolebnaUcastOkrsku(i)->pocetZucastnenych_; } } else { for (auto item : *UJ->getPatriaDonho()) { zrataj(item->accessData(), pocetZucastnenych); } } }
true
ed25be4b950d8160033fe7941240722af4e7bd01
C++
simawn/comp345w19
/Gas.h
UTF-8
352
3.03125
3
[]
no_license
#ifndef GAS_H #define GAS_H #include "Resources.h" /**Derived class from Resource to make gas resource*/ class Gas : public Resource { public: /**Gas constructor calls the super to set the value.*/ Gas(int v) :Resource(v) {}; /**Sets the name of the resource to know which one it is.*/ std::string getName() { return "Gas"; } }; #endif // !GAS_H
true
a77cad2f56344fe7c45e9c71ba568864b844dc20
C++
xtr01/spoj
/przyklad funkcji.cpp
UTF-8
635
3.203125
3
[]
no_license
#include<iostream> using namespace std; float metry; //zmienna globalna float ile_cali(float argument); float ile_jardow(float argument); int main() { cout << "podaj ile metrow chcesz przeliczyc na cale" << endl; cin >> metry; cout << "wartosc " << metry << " m po przeliczeniu na cale wynosi: " << ile_cali(metry) << ", w przeliczeniu na jardy: " << ile_jardow << endl; system("pause"); return 0; } float ile_cali(float argument) { float zmienna_pomocnicza = argument * 39.37; //zmienna lokalna return zmienna_pomocnicza; } float ile_jardow(float argument) { return argument * 1.0936; }
true
a9795cdb0bfdb91890a72d47d3542c2c74d0c7e4
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/14_7104_55.cpp
UTF-8
1,554
3.046875
3
[]
no_license
import java.util.HashSet; import java.util.Scanner; import java.util.Set; /** * Created by pratyush.verma on 12/04/14. */ public class MagicTrick { public static void main(String[] args) { int T; int index = 1; Scanner cin = new Scanner(System.in); T = cin.nextInt(); while (T-- != 0) { int board[][] = new int[4][4]; int row = cin.nextInt(); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; j++) { board[i][j] = cin.nextInt(); } } Set<Integer> rowInt = new HashSet<Integer>(); for (int i = 0; i < 4; i++) { rowInt.add(board[row - 1][i]); } board = new int[4][4]; row = cin.nextInt(); for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; j++) { board[i][j] = cin.nextInt(); } } Set<Integer> newRowInt = new HashSet<Integer>(); for (int i = 0; i < 4; i++) { newRowInt.add(board[row - 1][i]); } rowInt.retainAll(newRowInt); System.out.print("Case #" + index++ + ": "); if (rowInt.size() == 0) { System.out.println("Volunteer cheated!"); } else if (rowInt.size() > 1) { System.out.println("Bad magician!"); } else { System.out.println(rowInt.iterator().next()); } } } }
true
d2e3457b164ed709bbe4b70cf001b7ceb5b6e8f9
C++
HakureiAnna/UVA-OnlineJudge
/P755/p755.cpp
UTF-8
2,562
3.125
3
[]
no_license
#include <iostream> #include <map> using namespace std; string parsePhone(string phone); int main() { map<string, int> directory; int n; int numPhones; string phone; map<string, int>::iterator itor; bool duplicate; cin >> n; cin.ignore(); getline(cin, phone); for (int i = 0; i < n; ++i) { getline(cin, phone); numPhones = 0; for (int j = 0; j < phone.length(); ++j) { if (phone[j] < '0' || phone[j] > '9') break; numPhones *= 10; numPhones += phone[j] - '0'; } //cout << numPhones << endl; directory.clear(); duplicate = false; for (int j = 0; j < numPhones; ++j) { getline(cin, phone); //cout << "'" << phone << "'->"; phone = parsePhone(phone); //cout << "'" << phone << "'" << endl; itor = directory.find(phone); if (itor == directory.end()) directory.insert(pair<string, int>(phone, 1)); else { itor->second++; duplicate = true; } } getline(cin, phone); //cout << "'" << phone << "'" << endl; if (duplicate) { for (itor = directory.begin(); itor != directory.end(); ++itor) if (itor->second > 1) cout << itor->first << " " << itor->second << endl; } else cout << "No duplicates.\n"; if (i < n-1) cout << endl; } return 0; } string parsePhone(string phone) { int sLen = phone.length(); string nPhone = "--------"; int j = 0; for (int i = 0; i < sLen; ++i) { if (phone[i] >= '0' && phone[i] <= '9') { nPhone[j++] = phone[i]; } else if (phone[i] >= 'A' && phone[i] <= 'Z') { switch (phone[i]) { case 'A': case 'B': case 'C': nPhone[j++] = '2'; break; case 'D': case 'E': case 'F': nPhone[j++] = '3'; break; case 'G': case 'H': case 'I': nPhone[j++] = '4'; break; case 'J': case 'K': case 'L': nPhone[j++] = '5'; break; case 'M': case 'N': case 'O': nPhone[j++] = '6'; break; case 'P': case 'R': case 'S': nPhone[j++] = '7'; break; case 'T': case 'U': case 'V': nPhone[j++] = '8'; break; case 'W': case 'X': case 'Y': nPhone[j++] = '9'; break; } } if (j == 3) ++j; } return nPhone; }
true
734607948387a3da6516cba1dc526eeff4e2890d
C++
HALO-04/HIT
/1004.cpp
GB18030
2,157
2.9375
3
[]
no_license
#include <stdio.h> #include <cmath> using namespace std; int callength(long int x){ //㳤 int count=1; while( x=x/10 ) count++; return count; } bool check(long int x){ // for(long int i=2;i<=sqrt(x);i++) if(x%i==0 || x==0) return false; return true; } int increase(int x[],int len){ // int count = 1; for(int i=0;i<len+1;i++){ x[i]++; if(x[i]<10) break; else{ x[i] = 0; count++; } } if(count>len) return count; else return len; } int main(void) { int a,num[5]; int a_len,b_len; int i = 0; long int b,tsum; while (scanf("%d %d", &a, &b)==2){ a_len = callength(a); b_len = callength(b); int temp_len,new_len; if(a_len%2==0){ //洢ǰ벿 temp_len = a_len/2; for(i=0;i<temp_len;i++){ a = a/10; } for(i=0;i<temp_len;i++){ num[i] = a%10; a = a/10; } }else{ temp_len = (a_len+1)/2; for(i=0;i<temp_len-1;i++){ a = a/10; } for(i=0;i<temp_len;i++){ num[i] = a%10; a = a/10; } } while(a_len<=b_len){ //żл tsum = 0; if(a_len%2==0){ temp_len = a_len/2; new_len = temp_len; for(i=temp_len-1;i>=0;i--) tsum = tsum*10+num[i]; for(i=0;i<temp_len;i++) tsum = tsum*10+num[i]; if(tsum>b) break; if(check(tsum) && tsum!=0) printf("%ld\n",tsum); new_len = increase(num,temp_len); if(new_len>temp_len){ a_len++; num[new_len-1]=1; for(i=0;i<new_len-1;i++) num[i]=0; } }else{ temp_len = (a_len+1)/2; new_len = temp_len; for(i=temp_len-1;i>=0;i--) tsum = tsum*10+num[i]; for(i=1;i<temp_len;i++) tsum = tsum*10+num[i]; if(tsum>b) break; if(check(tsum) && tsum!=0) printf("%ld\n",tsum); new_len = increase(num,temp_len); if(new_len>temp_len){ a_len++; num[temp_len-1]=1; for(i=0;i<temp_len-1;i++) num[i]=0; } } } } return 0; }
true
d58b3439c4e41566529fe4bd55440fae27c17c94
C++
ShibaSouls/CS2
/test files/test_ctor_charArray_in.cpp
UTF-8
248
2.9375
3
[]
no_license
//test #include "string.hpp" #include <cassert> #include <iostream> int main() { { String s1(10, "abc"); assert(s1.capacity() == 10); assert(s1 == "abc"); } std::cout << "Done testing char int ctor." << std::endl; }
true
869f7364aca5c6411f0c52f34e80a579e188c653
C++
Lordloss56/IntroToCpp
/2-variables/main.cpp
UTF-8
2,286
3.53125
4
[]
no_license
#include <iostream> int main() { std::cout << "its the second program!" << std::endl; int age = 21; //my age std::cout << "here is my age" << age << std::endl; //prompt for users age int userAge = -1; std::cout << "what is your age?" << std::endl; std::cin >> userAge; std::cout << "Geez, your age is" << userAge << "youre old" << std::endl; //A) int numberA = 5; numberA = 9; numberA = 11; numberA = 14; std::cout << "A) " << numberA << std::endl; //B) int numberB = 10; numberB = 9; int thingB = 55; thingB = 22; std::cout << "B) " << numberB << std::endl; //C) int numberC = 3; numberC = 7; numberC = 1; int somethingC = 23; somethingC = 21; numberC = somethingC; std::cout << "C) " << numberC << std::endl; //D) int numberD = 1; int somethingD = 3; numberD = somethingD; std::cout << "D " << somethingD << std::endl; //E) int x = 13; x = x / 2; std::cout << "E) " << x << std::endl; //F) float y = 13; y = y / 2; std::cout << "F) " << y << std::endl; //celsius converter int celsius = -2; int farenheight = -1; std::cin >> celsius; farenheight = celsius * 1.8 + 32; std::cout << farenheight << std::endl; system("pause"); //average of Five float a, b, c, d, e; float avg; avg = a = b = c = d = e = 0.0f; std::cout << "whats the first vnumber" << std::endl; std::cin >> a; std::cout << "whats the second vnumber" << std::endl; std::cin >> b; std::cout << "whats the third vnumber" << std::endl; std::cin >> c; std::cout << "whats the fourth vnumber" << std::endl; std::cin >> d; std::cout << "whats the last vnumber" << std::endl; std::cin >> e; avg = (a + b + c + d + e) / 5.0f; std::cout << "Average of Five)" << std::endl; std::cout << a << "," << b << "," << c << "," << d << "," << e << std::endl; std::cout << "avg: " << avg << std::endl; system("pause"); int x = 13; int y = 24; int temp = x; x = y; y = x; std::cout << "Number Swap)" << std::endl; std::cout << "x is " << x << std::endl; std::cout << "y is " << y << std::endl; system("pause"); int age = -1; std::cout << "how old are you in years" << std::endl; std::cin >> age; std::cout << "Youve been alive for" << age << "years" << std::endl; std::cout << "thats" << age / 10 << "decades" << std::endl; std::cout << "thats" << age / 20 << "decades" << std::endl; return 0; }
true
2dc9c7456f590ae29eb36fb5fc60226d9a767798
C++
gmarais/Cpp
/Pool/D03/ex00/FragTrap.cpp
UTF-8
8,913
2.578125
3
[]
no_license
// ************************************************************************** // // // // ::: :::::::: // // FragTrap.cpp :+: :+: :+: // // +:+ +:+ +:+ // // By: gmarais <gmarais@student.42.fr> +#+ +:+ +#+ // // +#+#+#+#+#+ +#+ // // Created: 2015/01/08 19:23:47 by gmarais #+# #+# // // Updated: 2015/01/08 19:23:47 by gmarais ### ########.fr // // // // ************************************************************************** // #include "FragTrap.hpp" #include <cstdlib> #include <ctime> typedef void (FragTrap::*FragTrapMember)(std::string const & target); //--------------------------------------------------------------/ STATICS INIT / //------------------------------------------------------/ CONSTRUCT & DESTRUCT / FragTrap::FragTrap(std::string name) : _hit_points(100), _max_hit_points(100), _energy_points(100), _max_energy_points(100), _level(1), _name(name), _melee_attack_damage(30), _ranged_attack_damage(20), _armor_damage_reduction(5) { std::cout << "<FR4G-TP><" << this->_name << "> Directive one: protect humanity!" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Directive two: obey Jack at all costs." << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Directive three: dance!" << std::endl; std::cout << "<Jack> No no no no! Cancel directive three!" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Commencing directive three! Uhntssuhnssuhntss--" << std::endl; std::cout << "<Jack> Ugh, friggin' hate that guy..." << std::endl << std::endl; } FragTrap::FragTrap() : _hit_points(100), _max_hit_points(100), _energy_points(100), _max_energy_points(100), _level(1), _name("Claptrap"), _melee_attack_damage(30), _ranged_attack_damage(20), _armor_damage_reduction(5) { std::cout << "<FR4G-TP><" << this->_name << "> Directive one: protect humanity!" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Directive two: obey Jack at all costs." << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Directive three: dance!" << std::endl; std::cout << "<Jack> No no no no! Cancel directive three!" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Commencing directive three! Uhntssuhnssuhntss--" << std::endl; std::cout << "<Jack> Ugh, friggin' hate that guy." << std::endl << std::endl; } FragTrap::FragTrap(FragTrap const & src) { *this = src; } FragTrap::~FragTrap() { std::cout << "<FR4G-TP><" << this->_name << "> Crit-i-cal!" << std::endl; } //-------------------------------------------------------------------/ GETTERS / int FragTrap::getHitPoints() const { return this->_hit_points; } int FragTrap::getMaxHitPoints() const { return this->_max_hit_points; } int FragTrap::getEnergyPoints() const { return this->_energy_points; } int FragTrap::getMaxEnergyPoints() const { return this->_max_energy_points; } int FragTrap::getLevel() const { return this->_level; } std::string FragTrap::getName() const { return this->_name; } int FragTrap::getMeleeAttackDamage() const { return this->_melee_attack_damage; } int FragTrap::getRangedAttackDamage() const { return this->_ranged_attack_damage; } int FragTrap::getArmorReduction() const { return this->_armor_damage_reduction; } //-------------------------------------------------------------------/ ATTACKS / void FragTrap::rangedAttack(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at range, causing \033[1;31m" << this->_ranged_attack_damage << "\033[0;0m points of damage !" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } void FragTrap::meleeAttack(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " at melee, causing \033[1;31m" << this->_melee_attack_damage << "\033[0;0m points of damage !" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } void FragTrap::laserInfernoAttack(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with a laser inferno attack, causing \033[1;31m" << this->_ranged_attack_damage * 2 << "\033[0;0m points of damage !" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Everybody, dance time! Da-da-da-dun-daaa-da-da-da-dun-daaa" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } void FragTrap::electricAttack(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with an electric attack, causing \033[1;31m" << (int)(this->_ranged_attack_damage * 1.25) << "\033[0;0m points of damage !" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Dadadada. It's electric!" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } void FragTrap::buttAttack(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with a butt attack, causing \033[1;31m" << (int)(this->_melee_attack_damage / 10) << "\033[0;0m points of damage !" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Do not look behind my curtain!" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } void FragTrap::MinionTrap(std::string const & target) { if (this->_hit_points) { std::cout << "FR4G-TP " << this->_name << " attacks " << target << " with a minion trap attack, causing \033[1;31m" << (int)(this->_ranged_attack_damage * 1.10) << "\033[0;0m points of damage !" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> Ratattattattatta! Powpowpowpow! Powpowpowpow! Pew-pew-pew!" << std::endl; } else std::cout << "FR4G-TP " << this->_name << " has 0 hp and cannot attack..." << std::endl; } //-----------------------------------------------------------------/ FUNCTIONS / void FragTrap::vaulthunter_dot_exe(std::string const & target) { FragTrapMember _attacks[] = { &FragTrap::rangedAttack, &FragTrap::meleeAttack, &FragTrap::laserInfernoAttack, &FragTrap::electricAttack, &FragTrap::buttAttack, &FragTrap::MinionTrap }; int index; static int counter = 0; counter++; std::srand(std::time(0) + counter); if (this->_energy_points >= 25) { this->_energy_points -= 25; index = std::rand() % 5; (this->*(_attacks[index]))(target); } else { if (this->_energy_points > 0) std::cout << this->_name << " is out of energy..." << std::endl; else std::cout << this->_name << " has not enough energy..." << std::endl; } } void FragTrap::takeDamage(unsigned int amount) { this->_hit_points = ( (this->_hit_points + this->_armor_damage_reduction >= (int)amount) ? this->_hit_points + this->_armor_damage_reduction - amount : 0 ); std::cout << "FR4G-TP " << this->_name << " receives \033[1;31m" << amount << "\033[0;0m points of damage !" << std::endl; if (this->_hit_points) { std::cout << "<FR4G-TP><" << this->_name << "> That looks like it hurt!" << std::endl; } } void FragTrap::beRepaired(unsigned int amount) { this->_hit_points = ( (this->_hit_points + amount <= (unsigned int)this->_max_hit_points) ? this->_hit_points + amount : this->_max_hit_points ); std::cout << "FR4G-TP " << this->_name << " was repaired for \033[1;32m" << amount << "\033[0;0m points of damage !" << std::endl; std::cout << "<FR4G-TP><" << this->_name << "> AYE! does this mean I can start dancing? Pleeeeeeaaaaase?" << std::endl; } //-----------------------------------------------------------------/ OPERATORS / FragTrap & FragTrap::operator=(FragTrap const & rhs) { this->_hit_points = rhs.getHitPoints(); this->_max_hit_points = rhs.getMaxHitPoints(); this->_energy_points = rhs.getEnergyPoints(); this->_max_energy_points = rhs.getMaxEnergyPoints(); this->_level = rhs.getLevel(); this->_name = rhs.getName(); this->_melee_attack_damage = rhs.getMeleeAttackDamage(); this->_ranged_attack_damage = rhs.getRangedAttackDamage(); this->_armor_damage_reduction = rhs.getArmorReduction(); return *this; } //-------------------------------------------------------------/ OUTSIDE SCOPE /
true