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
088c2673dde6a0317c2daa3434b79f8519227f57
C++
wagnerhsu/packt-CPP-Templates-Up-and-Running
/Chapter_3/non_type_ptr.cpp
UTF-8
279
3.015625
3
[ "MIT" ]
permissive
#include <iostream> #include <string.h> #include <malloc.h> char *ptr; template<char * str> void print_str() { std::cout << str << std::endl; } int main() { ptr = (char *) malloc(256 * sizeof(char)); strcpy(ptr, "Hello World"); print_str<ptr>(); return 0; }
true
ac4079c0587d6220b80bea742134bcfcb307a5ab
C++
han-s/SW_TEST
/beakjoon/10875.cpp
UTF-8
1,554
2.796875
3
[]
no_license
#include<iostream> #include<queue> #include<vector> int direction[4] = { 0, 1, 2, 3 }; int dx[4] = { 0, -1, 0, 1}; int dy[4] = { -1, 0, 1, 0}; using namespace std; typedef struct snake { int y,x; char dir; }snake; int main(void) { long long result =0; int L, v_temp=0; queue<snake> q; cin >> L; int size = L*2 +3; int board[size][size]; snake s; for(int i=0 ; i<size ; i++) for(int j=0 ; j<size; j++) { if(i!=0 && j !=0 && i != size-1 && j != size-1) board[i][j] = 0; else board[i][j] = 1; } int N; cin >> N; vector< pair <int, char> > v; v.resize(N+1); for(int i=1; i<=N; i++) { int i_tmp; char c_tmp; cin >> i_tmp >> c_tmp; v[i].first = i_tmp; v[i].second = c_tmp; } s.dir = 3; s.x = s.y = size/2; board[s.y][s.x] = 1; q.push(s); while(!q.empty()) { bool check = false; snake n = q.front(); q.pop(); int cnt = v[v_temp].first; int nx=n.x, ny=n.y, ndir=n.dir; while(cnt--) { result++; ny = ny + dy[ndir]; nx = nx + dx[ndir]; if(board[ny][nx] == 1) { //cout << board[ny][nx] << endl; //cout << ny << " " << nx << " " << ndir << endl; check = true; break; } board[ny][nx] = 1; } if(check) break; if(v[v_temp].second == 'L') ndir = (n.dir + 1) % 4; if(v[v_temp].second == 'R') ndir = (n.dir + 3) % 4; n.dir = ndir; n.x = nx; n.y = ny; q.push(n); v_temp++; } for(int i=0 ; i<size ;i++) { cout << endl; for(int j=0; j<size ; j++) cout << board[i][j] << " "; } // cout << result << endl; return 0; }
true
1bfe359448b07506497438e9ff95423763fda5a4
C++
KkukYang/CodingTestStudy
/Project1/Project1/main.cpp
UHC
31,622
3.46875
3
[]
no_license
/* //̳ʺ dfs bfs #include <iostream> #include <string> #include <vector> #include <unordered_map> #include <algorithm> using namespace std; vector<string> solution(vector<vector<string>> tickets) { vector<string> answer; sort(tickets.begin(), tickets.end(), greater<vector<string>>()); unordered_map<string, vector<string>> routes; for (int i = 0; i < tickets.size(); i++) { routes[tickets[i][0]].push_back(tickets[i][1]); } vector<string> s = vector<string>{ "ICN" }; while (!s.empty()) { string airport = s.back(); if (routes.find(airport) == routes.end() || routes[airport].size() == 0) { answer.push_back(airport); s.pop_back(); } else { s.push_back(routes[airport].back()); routes[airport].pop_back(); } } reverse(answer.begin(), answer.end()); return answer; } void main() { vector<vector<string>> tickets = { {"ICN","SFO"},{"ICN","ATL"},{"SFO","ATL"},{"ATL","ICN"},{"ATL","SFO"} }; vector<string> result = solution(tickets); return; } */ /* //ȹ dynamic programming nǥ #include <iostream> #include <unordered_set> using namespace std; int solution(int N, int number) { int answer = -1; unordered_set<int> s[8]; int base = 0; //⺻ 5 55 555 5555 . for (int i = 0; i < 8; i++) { base = 10 * base + 1; s[i].insert(base * N); } //5 55,555,555 . for (int i = 1; i < 8; i++) { for (int j = 0; j < i; j++) { for (auto& op1 : s[j]) { for (auto& op2 : s[i - j - 1]) { s[i].insert(op1 + op2); s[i].insert(op1 - op2); s[i].insert(op1 * op2); if(op2 != 0) s[i].insert(op1 / op2); } } } // ϴ . if (s[i].count(number) > 0) { answer = i + 1; break; } } return answer; } int main() { cout << solution(5, 12) << endl; return 0; } */ /* // ʰ #include <iostream> #include <vector> #include <queue> using namespace std; int solution(vector<int> scoville, int K) { int answer = 0; priority_queue<int, vector<int>, greater<int>> q; for (auto& i : scoville) { q.push(i); } while (1) { int min1 = q.top(); q.pop(); if (min1>= K) { break; } else if (q.empty()) { answer = -1; break; } int min2 = q.top(); q.pop(); q.push(min1 + 2 * min2); answer++; } return answer; } ////Ѱ. //bool normal = true; // //bool cmp(int _left, int _right) //{ // return _left > _right; //} // //bool ifif(vector<int>& scoville, int K) //{ // if (scoville.size() > 1) // { // sort(scoville.begin(), scoville.end(), cmp); // if (scoville[scoville.size() - 1] >= K) // { // return false; // } // else // { // return true; // } // } // else // { // normal = false; // return false; // } // // return true; //} // //int solution(vector<int> scoville, int K) { // int answer = 0; // int mix = 0; // int first = 0; // int second = 0; // // while (ifif(scoville, K)) // { // first = scoville[scoville.size()-1]; // scoville.pop_back(); // second = scoville[scoville.size() - 1]; // scoville.pop_back(); // // mix = first + (second * 2); // scoville.push_back(mix); // // answer++; // } // // return (normal) ? answer : -1; //} void main() { //int n = 5; //vector<int> lost = { 3, 30, 34, 5, 9 }; //string str = "4177252841"; vector<int> v = { 1, 2, 3, 9, 10, 12 }; int k = 7; cout << solution(v, k) << endl; } */ /* //ū greedy Ž #include <iostream> #include <string> #include <vector> using namespace std; string solution(string number, int k) { string answer = ""; for (int i = 0; i < number.size(); i++) { while(!answer.empty() && answer.back() < number[i] && k > 0) { answer.pop_back(); k--; } if(k == 0) { answer += (number.substr(i, number.size() - i)); break; } answer.push_back(number[i]); } return answer.substr(0, answer.length() - k); } void main() { //int n = 5; //vector<int> lost = { 3, 30, 34, 5, 9 }; vector<int> v; string str = "4177252841"; int k = 4; cout << solution(str, k) << endl; } */ /* //90 ȸ #include <iostream> #include <vector> using namespace std; int main() { //vector<vector<int>> origin = { {1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16} }; vector<vector<int>> origin = { {1,2,3,4,5} ,{6,7,8,9,10} ,{11,12,13,14,15} ,{16,17,18,19,20} ,{21,22,23,24,25} }; int size = origin.size(); vector<vector<int>> temp(size, vector<int>(size, 0)); for (vector<int> _vec : origin) { for (int _int : _vec) { printf("%3d", _int); } cout << endl; } cout << endl; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { //temp[j][size - i - 1] = origin[i][j]; //ð 90 temp[size - j - 1][i] = origin[i][j]; //ݽð 90 } } for (vector<int> _vec : temp) { for (int _int : _vec) { printf("%3d", _int); } cout << endl; } return 0; } */ /////////////////////////////////////////////////////////////////////////////////kongStudio /* #include <iostream> #include <vector> #include <map> using namespace std; // Template for C++ class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { map<int, int> memo;//numsVal(ʿѼ), index for (int i = 0; i < nums.size(); i++) { // nums[i] Ÿ Ƿ target-nums[i] ʿѵ ֳ? if (memo.count(target - nums[i])) { //־? return { memo[target - nums[i]], i }; } else { // ڿ ʿ 𸣴 . ʿ Ű. memo[nums[i]] = i; } } return {}; } }; int main() { vector<int> a = { 2, 7, 11, 15 }; vector<int> result; Solution* s = new Solution(); result = s->twoSum(a, 9); for (int _r : result) { cout << _r; } return 0; } */ /* #include <iostream> #include <stack> #include <string> using namespace std; // Template for C++ class Queue { public: stack<int> _mainStack; stack<int> _subStack; // Push element x to the back of queue. void push(int x) { while (_mainStack.size()>0) { _subStack.push(_mainStack.top()); _mainStack.pop(); } //ݿ° . _mainStack.push(x); // ٽ ױ. while (_subStack.size() > 0) { _mainStack.push(_subStack.top()); _subStack.pop(); } } // Removes the element from in front of queue. void pop(void) { if (_mainStack.size() > 0) { _mainStack.pop(); } else { cout << "empty" << endl; } } // Get the front element. int peek(void) { return _mainStack.top(); } // Return whether the queue is empty. bool empty(void) { return (_mainStack.size() == 0) ? true : false; } }; int main() { Queue* q = new Queue(); q->push(1); q->push(2); q->push(3); q->push(4); q->push(5); cout << to_string(q->empty()) << endl; cout << q->peek() << endl; q->push(6); cout << q->peek() << endl; q->pop(); cout << q->peek() << endl; q->pop(); cout << q->peek() << endl; q->pop(); cout << q->peek() << endl; q->pop(); cout << q->peek() << endl; q->pop(); q->pop(); q->pop(); cout << to_string(q->empty()) << endl; q->pop(); return 0; } //_mainStack ִ _subStack ״  ְ-> ִ _mainStack ߰ ְ ٽ _subStack // ε ڰ ÿ ֵ ִ 2 Ͽϴ. */ /* #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> plusOne(vector<int>& digits) { if (digits.size() == 0) { return digits; } digits[digits.size() - 1]++; //vector ϳ ڸ Ƿ dz ڸ Ǿٸ, ڸ üũ մϴ. if (digits[digits.size() - 1] > 9) { for (int i = digits.size() - 1; i >= 0; i--) { if (digits[i] > 9) { digits[i] %= 10; if (i == 0) { digits.insert(digits.begin(), 1); } else { digits[i - 1]++; } } else { break; } } } return digits; } }; int main() { vector<int> a = { 9, 9, 9, 9 }; vector<int> result; Solution* s = new Solution(); result = s->plusOne(a); for (int _r : result) { cout << _r; } return 0; } */ /* #include <iostream> #include <string> #include <stack> using namespace std; class Solution { public: string reverseVowels(string s) { // ÿ ȸ , ö ÿ ϴ. stack<char> _stack; for (int i = 0; i < s.length(); i++) { if (s[i] == 'a' || s[i] == 'i' || s[i] == 'u' || s[i] == 'e' || s[i] == 'o' || s[i] == 'A' || s[i] == 'I' || s[i] == 'U' || s[i] == 'E' || s[i] == 'O') { _stack.push(s[i]); } } for (int i = 0; i < s.length(); i++) { if (s[i] == 'a' || s[i] == 'i' || s[i] == 'u' || s[i] == 'e' || s[i] == 'o' || s[i] == 'A' || s[i] == 'I' || s[i] == 'U' || s[i] == 'E' || s[i] == 'O') { s[i] = _stack.top(); _stack.pop(); } } return s; } }; int main() { Solution* s = new Solution(); cout << s->reverseVowels("hEllo") << endl; return 0; } */ /* #include <iostream> #include <map> using namespace std; class Solution { public: map<int, int> memo; int Fibonacci(int n) { if (n <= 1) { return n; } else if (memo[n] != 0) { return memo[n]; } else { return memo[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } } }; int main() { Solution* s = new Solution(); cout << s->Fibonacci(10) << endl; return 0; } //ش簪 ص״ٰ ̹ ߴ ̷ִ ͸ Ͽ ѹ ϴ մϴ. */ /////////////////////////////////////////////////////////////////////////////////kongStudio /* string solution(int _i) { string str = "123"; int s = 3; cout << str[1] << endl; str += to_string(s); cout << str << endl; return str; } int main() { cout << solution(5) << endl; return 0; } */ /* #include <iostream> #include <string> using namespace std; void printReverse(string str) { // Print first word int i = 0; for (i = 0; i < str.length() && str[i] != ' '; i++) cout << str[i]; // Print middle words string word = ""; for (; i < str.length(); i++) { if (str[i] != ' ') word += str[i]; else { reverse(word.begin(), word.end()); cout << word << " "; word = ""; } } // Print last word cout << word << " "; } int main() { string str = "Hi how are you geeks"; printReverse(str); return 0; } */ /* #include <iostream> #include <map> using namespace std; class Solution { public: map<int, int> memo; int Fibonacci(int n) { if (n <= 1) { return n; } else if (memo[n] != 0) { return memo[n]; } else { return memo[n] = Fibonacci(n - 1) + Fibonacci(n - 2); } } }; int main() { Solution* s = new Solution(); cout << s->Fibonacci(10) << endl; return 0; } //ش簪 ص״ٰ ̹ ߴ ̷ִ ͸ Ͽ ѹ ϴ մϴ. */ /* #include <iostream> #include <string> #include <vector> #include <map> using namespace std; void Add(char* _cArrLeft, char* _cArrRight) { for (int i = 0; i < 1024; ++i) { _cArrRight[i] = _cArrLeft[i] + _cArrRight[i]; //ڸ 10 Ѿ üũ NumberCheck(_cArrRight, i); } } void NumberCheck(char* _cArrRight, int _idx) { //ڸ 10 Ѿ? if (_cArrRight[_idx] >= 10) { int iAddIdx = _idx + 1; _cArrRight[_idx] %= 10; _cArrRight[iAddIdx] += 1; //Ȥ ڸ 10̻ ˻; Լ NumberCheck(_cArrRight, iAddIdx); } } int main() { char cArrLeft[1024] = { 0 }; char cArrRight[1024] = { 0 }; char cArrResult[1024] = { 0 }; int iCalCnt = 1; int iMaxFibonacciCnt = 1000; //Left & Right Init cArrLeft[0] = 0; cArrRight[0] = 1; // while (1) { // ׿  Ǻġ Add(cArrLeft, cArrRight); iCalCnt++; if (iCalCnt == iMaxFibonacciCnt) { break; } } bool bContinueControl = false; for (int i = 1023; i >= 0; --i) { if (cArrResult[i] == 0 && false == bContinueControl) { continue; } printf("%d", cArrResult[i]); bContinueControl = true; } printf("\n"); return 0; } */ //׸ ü /* #include <iostream> #include <vector> #include <unordered_set> #include <set> using namespace std; int solution(int n, vector<int> lost, vector<int> reserve) { int answer = 0; unordered_set<int> l(lost.begin(), lost.end());//Ҿֵ. set<int> r; //о. unordered_set<int> inter;// Ҿ+о for (auto& x : reserve) { if (l.find(x) == l.end()) { //Ҿ Ͽ . //о ߰. r.insert(x); } else { //Ҿ Ͽ ִ. //ȿ Ͽ . inter.insert(x); } } //ȿϿ Ҿ+о for (auto& x : inter) { //Ҿ Ͽ . l.erase(x); } for (auto& x : r) { if (l.find(x - 1) != l.end()) { l.erase(x - 1); } else if (l.find(x + 1) != l.end()) { l.erase(x + 1); } } return n - l.size(); } void main() { int n = 5; vector<int> lost = { 2,4 }; vector<int> reserve = { 1,3,5 }; cout << solution(n, lost, reserve) << endl; } */ /* #include <iostream> #include <vector> #include <unordered_map> using namespace std; int solution(int n, vector<int> lost, vector<int> reserve) { int answer = 0; vector<int> u(n + 2, 1); for (int i = 0; i < reserve.size(); i++) { u[reserve[i]]++; } for (int i = 0; i < lost.size(); i++) { u[lost[i]]--; } for (int i = 1; i <= n; i++) { if (u[i - 1] == 0 && u[i] == 2) { u[i - 1] = u[i] = 1; } else if (u[i] == 2 && u[i + 1] == 0) { u[i] = u[i + 1] = 1; } } for (int i = 1; i <= n; i++) { if (u[i] > 0) { answer++; } } return answer; } void main() { int n = 5; vector<int> lost = { 2,4 }; vector<int> reserve = { 1,3,5 }; cout << solution(n, lost, reserve) << endl; }*/ /* #include <iostream> #include <string> #include <vector> using namespace std; int student[35]; int solution(int n, vector<int> lost, vector<int> reserve) { int answer = 0; for (int i : reserve) student[i] += 1; for (int i : lost) student[i] += -1; for (int i = 1; i <= n; i++) { if (student[i] == -1) { if (student[i - 1] == 1) student[i - 1] = student[i] = 0; else if (student[i + 1] == 1) student[i] = student[i + 1] = 0; } } for (int i = 1; i <= n; i++) if (student[i] != -1) answer++; return answer; } //#include <string> //#include <vector> // //using namespace std; // //int solution(int n, vector<int> lost, vector<int> reserve) { // int answer = 0; // // // vector<int> total; // total.assign(5, 1); // // for (int _r : reserve) // { // total[_r-1] = 2; // } // // for (int _l : lost) // { // total[_l - 1] = 0; // } // // for (int i = 0; i < total.size(); i++) // { // if (total[i] == 0) // { // if (i > 0 && total[i - 1] == 2) // { // total[i - 1]--; // total[i]++; // } // else if (i < total.size() - 1 && total[i + 1] == 2) // { // total[i + 1]--; // total[i]++; // } // } // } // // for (int _t : total) // { // if (_t == 1 || _t == 2) // { // answer++; // } // } // // // // return answer; //} void main() { int n = 5; vector<int> lost = {2,4}; vector<int> reserve = {1,3,5}; cout << solution(n, lost, reserve) << endl; } //5 [2, 4][1, 3, 5] 5 //5 [2, 4][3] 4 //3 [3] [1] 2 */ //̺Ž Աɻ /* #include <iostream> //#include <string> //#include <vector> // //using namespace std; // //long long solution(int n, vector<int> times) { // long long answer = 0; // // vector<long long> expectTime; // expectTime.assign(times.size(), 0); // // // //for (int i = 0; i < times.size(); i++) // //{ // // expectTime.push_back(times[i]); // //} // // // int min = 0; // int minIdx = 0; // // for (int i = 0; i < n; i++) //ο // { // min = expectTime[0] + times[0]; // // for (int j = 0; j < expectTime.size(); j++) // { // if (expectTime[j] + times[j] <= min) // { // //expectTime[j] += times[j]; // min = expectTime[j] + times[j]; // minIdx = j; // } // } // // expectTime[minIdx] += times[minIdx]; // // } // // for (int i = 0; i < expectTime.size(); i++) // { // if (answer <= expectTime[i]) // { // answer = expectTime[i]; // } // } // // return answer; //} #include <string> #include <vector> #include <algorithm> using namespace std; long long solution(int n, vector<int> times) { sort(times.begin(), times.end()); long long left = (long long)times[0]; long long right = (long long)times[times.size() - 1] * n; long long answer = right; while (left <= right) { long long mid = (right + left) / 2; long long pass = 0; for (int i = 0; i < times.size(); ++i) pass += mid / (long long)times[i]; if (pass >= n) { right = mid - 1; if (mid <= answer) answer = mid; } else left = mid + 1; } return answer; } void main() { int n = 6; vector<int> times = { 7,10 }; cout << solution(n, times) << endl; } //6 [7, 10] 28 */ //̺Ž /* #include <string> #include <vector> #include<algorithm> #include<iostream> using namespace std; int solution(vector<int> budgets, int M) { int answer = 0; sort(budgets.begin(),budgets.end()); int total=0; int left = 0; int right=budgets[budgets.size()-1]; for(int i=0;i<budgets.size();i++) { total+=budgets[i]; } if(total<=M) return right; while(left<=right) { total = 0; int mid = (left+right)/2; for(int i=0;i<budgets.size();i++) { if(budgets[i]<mid) { total+=budgets[i]; } else total+=mid; } if(total>M) { right=mid-1; } else { left=mid+1; } } return right; } */ /* #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; //ü 485 //ճ -> ߰ ƴҼִ. ->߰ !!! //պ Ѿֵ ̰ // Ѱ ̵ ֵ ŭ -> !!! //̶߰ + = Ѿ // ̶µ. int solution(vector<int> budgets, int M) { int answer = 0; int numbers = budgets.size(); sort(budgets.begin(), budgets.end()); for (auto itr = budgets.begin(); itr != budgets.end(); itr++) { if (*itr > (M / numbers)) return M / numbers; else { M -= *itr; numbers--; } } return budgets.back(); } //int solution(vector<int> budgets, int M) { // int answer = 0; // // //. M // //int nbLeft = M % budgets.size(); // int nb = M / budgets.size(); // int collectLess = 0; //Ѱź Ʒ Ѱ. // int collectLessIdx = 0; // // int divCollectLess = 0; // int divCollectLessLeft = 0; // // sort(budgets.begin(), budgets.end()); // // for (int i = 0; i< budgets.size(); i++) // { // if (budgets[i] <= nb) // { // collectLess += (nb - budgets[i]); // collectLessIdx = i; // } // } // // divCollectLess = collectLess / (budgets.size() - (collectLessIdx + 1)); // //divCollectLessLeft = collectLess % (budgets.size() - (collectLessIdx + 1)); // // return nb + divCollectLess;// +nbLeft + divCollectLessLeft; // // //return answer; //} int main() { vector<int> budgets = { 120, 110, 140, 150 }; int M = 485; cout << solution(budgets, M) << endl; return 0; } // 120, 110, 140, 150 485 */ // hindex /* #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int solution(vector<int> citations) { int answer = 0; std::sort(citations.begin(), citations.end()); for (int i = 0; i < citations.size(); i++) { if (citations.size() - i <= citations[i]) { answer = citations.size() - i; break; } } return answer; } //int solution(vector<int> citations) { // int answer = 0; // vector<int> citationsCopy; // //citationsCopy.insert(citations.begin(),) // sort(citations.begin(), citations.end()); // // for (int i = 0; i < citations.size(); i++) // { // for (int j = citations[0]; j <= citations[citations.size() - 1]; j++) // { // if (citations[i] >= j) // { // if (j <= citations.size() - i + 1 && j >= i + 1) // { // return j; // } // } // } // } // // // return answer; //} int main() { vector<int> citation = { 3, 0, 6, 1, 5 }; cout << solution(citation) << endl; return 0; } //[3, 0, 6, 1, 5] */ // ū /* #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; bool cmp(int a, int b) { //ش ̽. return s1 > s2; //a ռ° true. //b ռ° false. string s1 = to_string(a) + to_string(b); string s2 = to_string(b) + to_string(a); return s1 > s2; } string solution(vector<int> numbers) { string answer = ""; sort(numbers.begin(), numbers.end(), cmp); for (auto& i : numbers) { answer += to_string(i); } return answer[0] == '0' ? "0" : answer; } void main() { int n = 5; vector<int> lost = { 3, 30, 34, 5, 9 }; cout << solution(lost) << endl; } */ /* #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; bool compare(const string& a, const string& b) { if (b + a < a + b) return true; return false; } string solution(vector<int> numbers) { string answer = ""; vector<string> strings; for (int i : numbers) strings.push_back(to_string(i)); sort(strings.begin(), strings.end(), compare); for (auto iter = strings.begin(); iter < strings.end(); ++iter) answer += *iter; if (answer[0] == '0') answer = "0"; return answer; } //#include <string> //#include <vector> //#include <math.h> //#include <algorithm> // //using namespace std; // ////. //bool compare(int _left, int _right) //{ // int leftMok = _left, rightMok = _right; // int leftNam = 0, rightNam = 0; // // int i = 0; // //ǿʿ ϳ ; . // while (true) // { // i++; // leftNam = leftMok % 10; // rightNam = rightMok % 10; // leftMok /= pow(10, i); // rightMok /= pow(10, i); // // if (!(leftMok > 0 && rightMok > 0)) // { // if (leftNam < rightNam) // { // return false; // } // else // { // return true; // } // } // } // //} //string solution(vector<int> numbers) { // string answer = ""; // // sort(numbers.begin(), numbers.end(), compare); // // for (int _num : numbers) // { // answer += to_string(_num); // } // // return answer; //} int main() { vector<int> numbers = { 30, 300, 34, 512, 9 }; cout<<solution(numbers)<<endl; return 0; } //[3, 30, 34, 5, 9] */ // k° /* #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; vector<int> solution(vector<int> array, vector<vector<int>> commands) { vector<int> answer; for (vector<int> _info : commands) { vector<int> _vecTemp; for (int i = _info[0]-1;//ε i <= _info[1]-1;//ε i++) { _vecTemp.push_back(array[i]); } //sort sort(_vecTemp.begin(), _vecTemp.end()); answer.push_back(_vecTemp[_info[2] - 1]); } return answer; } int main() { vector<int> array = { 1, 5, 2, 6, 3, 7, 4 }; vector<vector<int>> commands = { {2, 5, 3} ,{4, 4, 1},{1, 7, 3} }; vector<int> result = solution(array, commands); for (int _val : result) { cout << _val << endl; } return 0; } //[1, 5, 2, 6, 3, 7, 4] [[2, 5, 3], [4, 4, 1], [1, 7, 3]] [5, 6, 3] */ //ؽ Ʈٹ /* #include <iostream> //#include <string> //#include <vector> //#include <unordered_map> //#include <algorithm> //#include <utility> // //using namespace std; //bool compare(pair<int, int> left, pair<int, int> right) { // if (left.first > right.first) { // return true; // } // else if (left.first == right.first) { // if (left.second < right.second) { // return true; // } // } // return false; //} //vector<int> solution(vector<string> genres, vector<int> plays) { // vector<int> answer; // unordered_map<string, int> summap; // unordered_map<string, vector<pair<int, int>>> genmap; // // for (int i = 0; i < genres.size(); i++) { // summap[genres[i]] += plays[i]; // genmap[genres[i]].push_back(make_pair(plays[i], i)); // } // // vector<pair<int, string>> fororder; // // for (auto x : summap) { // fororder.push_back(make_pair(x.second, x.first)); // } // // sort(fororder.begin(), fororder.end()); // // while (fororder.size() > 0) { // pair<int, string> temp = fororder.back(); // fororder.pop_back(); // vector<pair<int, int>> a = genmap[temp.second]; // sort(a.begin(), a.end(), compare); // //sort(a.begin(), a.end()); // int lastn = 2; // if (a.size() < 2) { // lastn = a.size(); // } // for (int i = 0; i < lastn; i++) { // answer.push_back(a[i].second); // } // } // // return answer; //} #include <string> #include <vector> #include <map> #include <algorithm> using namespace std; bool compare1(pair<int, int> _left, pair<int, int> _right) { if (_left.second > _right.second) { return true; } else if (_left.second == _right.second) { if(_left.first < _right.first) return true; } return false; //return _left.second > _right.second; } bool compare2(pair<string, int> _left, pair<string, int> _right) { if (_left.second < _right.second) { return false; } else { return true; } } vector<int> solution(vector<string> genres, vector<int> plays) { vector<int> answer; map<string, vector<pair<int, int>>> genreByIndexValue; //index, value map<string, int> genreBySumValue; vector<pair<string, int>> vecGenreBySumValue; for (int i = 0; i < genres.size(); i++) { vector < pair<int, int>> _valuesByIndex = { pair<int,int>(i, plays[i]) }; if (genreByIndexValue.count(genres[i]) == 0) { genreByIndexValue.insert(pair<string, vector < pair<int, int>>>(genres[i], _valuesByIndex)); } else { genreByIndexValue[genres[i]].push_back(_valuesByIndex[0]); } genreBySumValue[genres[i]] += plays[i]; } //// ε . genreByIndexValue //for (pair<string, vector<pair<int,int>>> _pair : genreByIndexValue) //{ // sort(_pair.second.begin(), _pair.second.end(), compare1); // //answer.push_back(_pair.second[0] % 100); // //answer.push_back(_pair.second[1] % 100); //} for (auto iter = genreByIndexValue.begin(); iter != genreByIndexValue.end(); iter++) { sort(iter->second.begin(), iter->second.end(), compare1); } //帣 켱 -> . for (pair<string, int> _pair : genreBySumValue) { vecGenreBySumValue.push_back(_pair); } sort(vecGenreBySumValue.begin(), vecGenreBySumValue.end(), compare2); //answerۼ for (pair<string, int> _pair : vecGenreBySumValue) { answer.push_back(genreByIndexValue[_pair.first][0].first); if (genreByIndexValue[_pair.first].size() > 1) { answer.push_back(genreByIndexValue[_pair.first][1].first); } } return answer; } int main() { vector<string> genres = { "classic","pop", "classic", "classic", "pop" }; vector<int> plays = { 500, 600, 150, 800, 2500 }; vector<int> answer = solution(genres, plays); for (int i = 0; i < answer.size(); i++) { cout << answer[i] << endl; } return 0; } //[classic, pop, classic, classic, pop] //[500, 600, 150, 800, 2500] */ /* //ؽ . #include <iostream> #include <string> #include <vector> #include <map> using namespace std; int solution(vector<vector<string>> clothes) { int answer = 1; map<string, int> countByType; for (vector<string> _vec : clothes) { if (countByType.count(_vec[1]) == 0) { countByType.insert(pair<string, int>(_vec[1], 1)); } else { countByType[_vec[1]] += 1; } } //ŭ ߵ. Ÿ for (auto i = countByType.begin(); i != countByType.end(); i++) { answer *= (i->second + 1); } answer--; return answer; } int main() { vector<vector<string>> clothes = { {"yellow_hat","headgear"} ,{"blue_sunglasses","eyewear"} ,{"green_turban","headgear"} }; cout << solution(clothes) << endl; return 0; } */ //ؽ ȭȣ /* //#include <string> #include <iostream> #include <vector> #include <algorithm> using namespace std; bool solution(vector<string> phoneBook) { bool answer = true; sort(phoneBook.begin(), phoneBook.end()); for (int i = 0; i < phoneBook.size() - 1; i++) { if (phoneBook[i] == phoneBook[i + 1].substr(0, phoneBook[i].size())) { answer = false; break; } } return answer; } int main() { vector<string> phone_book = { "119", "97674223", "1195524421" }; cout << solution(phone_book) << endl; return 0; } //Ǭ #include <iostream> #include <string> #include <vector> using namespace std; bool solution(vector<string> phone_book) { bool answer = true; vector<string> strMinLength; int minLength = 21; for (string _str : phone_book) { if (_str.length() <= minLength) { minLength = _str.length(); strMinLength.push_back(_str); } } for (string _strMinLength : strMinLength) { for (string _str : phone_book) { if (_str != _strMinLength && _str.find(_strMinLength) != string::npos) { return false; } } } return answer; } int main() { vector<string> phone_book = { "119", "123", "1195524421" }; cout << solution(phone_book) << endl; return 0; } */ //α׷ӽ ڵ׽Ʈ ؽ ٸ Ǯ /* #include <iostream> #include <string> #include <vector> #include <unordered_map> using namespace std; string solution(vector<string> participant, vector<string> completion) { string answer = ""; unordered_map<string, int> d; for (auto& i : participant) d[i]++; for (auto& i : completion) d[i]--; for (auto& i : d) { if (i.second > 0) { answer = i.first; break; } } return answer; } int main() { vector<string> participant = { "leo", "kiki","eden" }; vector<string> completion = { "kiki","eden" }; cout << solution(participant, completion) << endl; return 0; } */ /* #include <iostream> #include <string> #include <vector> #include <map> using namespace std; string solution(vector<string> participant, vector<string> completion) { string answer = ""; map<string, int> countByName; for (string _str : completion) { if (countByName.count(_str) == 0) { //not found countByName.insert(pair<string, int>(_str, 1)); } else { //found countByName[_str] += 1; } } for (string _str : participant) { if (countByName.count(_str) == 0) { return _str; } else { //found countByName[_str] += 1; } } map<string, int >::iterator iter; for (iter = countByName.begin(); iter != countByName.end(); iter++) { if (iter->second % 2 == 1) { return iter->first; } } return answer; } int main() { vector<string> participant = { "leo", "kiki","eden" }; vector<string> completion = { "kiki","eden" }; cout << solution(participant, completion) << endl; return 0; } */
true
e8052dd1e9bb022afb91d9d943ddef2f2e1230bc
C++
ibioesc/Arduino
/arduino/pruebas/motorpaso/motorpaso.ino
UTF-8
2,258
3
3
[]
no_license
#define VELOCIDAD 2000 //velocidad de giro del motor, cuanto menos valor + velocidad int pasos = 26; //definimos como «entero» pin digital 13 para dar los pasos al servo int direccion = 27; //definimos como «entero» pin digital 9 para dar el sentido de giro int reset = 25; //definimos como «entero» pin digital 10 para poner en «enable» el motor int totalpasos = 400; //definimos como «entero» totalpasos para completar un avance void setup() { pinMode(pasos, OUTPUT); //definimos pasos como salida digital pinMode(direccion, OUTPUT); //definimos direccion como salida digital pinMode(reset, OUTPUT); //definimos reset como salida digital } void loop() { digitalWrite(reset, LOW); //Mientras reset este en LOW, el motor permanece apagado delay(2000); //Retardo en la instruccion digitalWrite(reset, HIGH); //Cuando reset se encuentre en HIGH el motor arranca digitalWrite(direccion, HIGH); //mandamos direccion al servo for (int i = 0; i<totalpasos; i++) //Equivale al numero de vueltas (200 pasos son 360º grados de servo ) { digitalWrite(pasos, HIGH); // ponemos a high «pasos» digitalWrite(pasos, LOW); // ponemos a low «pasos» delayMicroseconds(VELOCIDAD); // leemos la referencia de velocidad } //—————————Cambio de sentido de giro——————————– digitalWrite(reset, LOW); //Mientras reset este en LOW, el motor permanece apagado delay(2000); //Retardo en la instruccion digitalWrite(reset, HIGH); //Cuando reset se encuentre en HIGH el motor arranca digitalWrite(direccion, LOW); //mandamos direccion al servo for (int i = 0; i<totalpasos; i++) //Equivale al numero de vueltas (200 pasos son 360º grados de servo ) { digitalWrite(pasos, LOW); // ponemos a high «pasos» digitalWrite(pasos, HIGH); // ponemos a low «pasos» delayMicroseconds(VELOCIDAD); // leemos la referencia de velocidad } }
true
975b73586d1c2cea8da47f8bdf5c87c4a5081162
C++
redevilsss/leetcode
/201-250/211 添加与搜索单词.cpp
GB18030
2,432
3.890625
4
[]
no_license
#include<iostream> #include<vector> #include<list> #include<queue> using namespace std; //211 /* һֲ֧ݽṹ void addWord(word) bool search(word) search(word) ֻʽַַֻĸ . a-z . Աʾκһĸ ʾ: addWord("bad") addWord("dad") addWord("mad") search("pad") -> false search("bad") -> true search(".ad") -> true search("b..") -> true */ //˼뻹ֵǰ208񣬲ͬڶһƥ //Ҳsearchʱǰλǡ.˵26ĸһλȥжϺĵǷܲҵ class WordDictionary { class Node { public: bool isWord; vector<Node*> next; Node() { next.resize(26, nullptr); isWord = false; } ~Node() { for (int i = 0; i<26; i++) delete next[i]; } }; public: /** Initialize your data structure here. */ Node* root; WordDictionary() { root = new Node(); } /** Adds a word into the data structure. */ void addWord(string word) { Node* node = root; for (int i = 0; i<word.length(); i++) { if (node->next[word[i] - 'a'] == nullptr) node->next[word[i] - 'a'] = new Node(); node = node->next[word[i] - 'a']; } node->isWord = true; } /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ bool serach(Node* node, string word, int index) { if (!node) return false; if (word.length() == index) return node->isWord; if (word[index] == '.') { for (int i = 0; i<26; i++) if (node->next[i] && serach(node->next[i], word, index + 1)) return true; } else { if (node->next[word[index] - 'a'] && serach(node->next[word[index] - 'a'], word, index + 1)) return true; } return false; } bool search(string word) { return serach(root, word, 0); } }; int main() { WordDictionary* dict = new WordDictionary{}; dict->addWord("a"); dict->addWord("a"); bool res1=dict->search("."); bool res2 = dict->search("a"); bool res3 = dict->search("aa"); bool res4 = dict->search("a"); bool res5 = dict->search(".a"); bool res6 = dict->search("a."); return 0; }
true
efb33b71973bb7816f0c930c1b2af92980304090
C++
finem50/lab8
/lab8postlab.cpp
UTF-8
2,830
4.21875
4
[]
no_license
//Rules for calculation will be: // a/b + c/d = (a*d + b*c) / (b*d) // a/b - c/d = (a*d - b*c) / (b*d) // (a/b) * (c/d) = (a*c) / (b*d) // (a/b) / (c/d) = (a*d) * (c*b) #include <iostream> #include <cmath> using namespace std; class Rational{ public: Rational(); Rational(int a, int b, int c, int d); //Four variables, for each quarter of the equation void set(); friend Rational operator +(int a, int b, int c, int d); friend Rational operator -(int a, int b, int c, int d); friend Rational operator *(int a, int b, int c, int d); friend Rational operator /(int a, int b, int c, int d); private: int a, b, c, d, total; //These will be used to construct the fractions }; Rational operator +(int a, int b, int c, int d); Rational operator -(int a, int b, int c, int d); Rational operator *(int a, int b, int c, int d); Rational operator /(int a, int b, int c, int d); int main(){ int a, b, c, d; char oper; Rational rational; cout << "Please enter stuff: "; rational.set(); cout << "Which operator would you like to perform? i.e. +, -, *, / " << endl; cin >> oper; switch(oper){ case '+': a + b + c + d; break; case '-': a - b - c - d; break; case '*': a * b * c * d; break; case '/': a / b / c / d; break; default: cout << "Invalid input\n"; break; } } Rational::Rational(){ //Default constructor } Rational::Rational(int numA, int denA, int numB, int denB){ a = numA; b = denA; c = numB; d = denB; } void Rational::set(){ cout << "Please enter the first numerator: "; cin >> a; cout << "Please enter the first denominator: "; cin >> b; cout << "Please enter the second numerator: "; cin >> c; cout << "Please enter the second denominator: "; cin >> d; } Rational operator +(int a, int b, int c, int d){ Rational temp; int total; temp.total = (temp.a * temp.d + temp.b * temp.c) / (temp.b * temp.d); return temp; } Rational operator -(int a, int b, int c, int d){ int total; total = (a * d - b * c) / (b * d); cout << a << " / " << b << " - " << c << " / " << d << " = " << total << endl; temp.total = (temp.a * temp.d + temp.b * temp.c) / (temp.b * temp.d); return temp; } Rational operator *(int a, int b, int c, int d){ int total; total = (a * c) / (b * d); cout << a << " / " << b << " * " << c << " / " << d << " = " << total << endl; temp.total = (temp.a * temp.d + temp.b * temp.c) / (temp.b * temp.d); return temp; } Rational operator /(int a, int b, int c, int d){ int total; total = (a * d) * (c * b); cout << a << " / " << b << " / " << c << " / " << d << " = " << total << endl; temp.total = (temp.a * temp.d + temp.b * temp.c) / (temp.b * temp.d); return temp; }
true
91cbdc892f45ffc22c2de9d33964bd01eb782954
C++
goryanski/cpp
/Completed_tasks/OOP/02/lesson_2.2/lesson_2.2/Array.cpp
UTF-8
1,705
3.578125
4
[]
no_license
#include "Array.h" #include<iostream> using std::cout; using std::cin; Array::Array() { size = 0; arr = nullptr; } Array::Array(int size) { arr = new int[size]; this->size = size; } Array::Array(const Array& obj) { setArray(obj.arr, obj.size); } Array::~Array() { delete[] arr; } void Array::setArray(int* arr, int size) { if (this->arr != nullptr) { delete[] this->arr; } this->size = size; this->arr = new int[this->size]; for (int i = 0; i < this->size; i++) { this->arr[i] = arr[i]; } } void Array::fillArr() { for (int i = 0; i < size; i++) { arr[i] = rand() % 10; } } void Array::printArr() { for (int i = 0; i < size; i++) { cout << arr[i] << "\t"; } cout << "\n"; } void Array::addEnd(int value) { int* tmp = new int[size + 1]; for (int i = 0; i < size; i++) { tmp[i] = arr[i]; } tmp[size] = value; size++; delete[] arr; arr = tmp; } void Array::delEnd() { size--; int* tmp = new int[size]; for (int i = 0; i < size; i++) { tmp[i] = arr[i]; } delete[] arr; arr = tmp; } void Array::sortArr() { for (int i = 0; i < size - 1; i++) { bool f = 0; for (int j = 0; j < size - 1 - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; f = 1; } } if (f == 0) break; } } void Array::min_max() { int max = arr[0], min = arr[0]; int imax = 0, imin = 0; for (int i = 1; i < size; i++) { if (arr[i] > max) { max = arr[i]; imax = i; } if (arr[i] < min) { min = arr[i]; imin = i; } } cout << " Min element of array is " << min << " (it's position " << imin + 1 << ")\n"; cout << " Max element of array is " << max << " (it's position " << imax + 1 << ")\n"; }
true
e10f8ec83ad29ff9a394693615330c7c5926af5e
C++
Mikhail-M/Programming_in_university
/TymofeiBryksin/1 semestr/Homework 5/Task 1/main.cpp
UTF-8
929
3.34375
3
[]
no_license
#include <iostream> #include <fstream> #include <cstring> using namespace std; const countAlpha = 26; void nextWord(int &pos, char *text){ int alpha[countAlpha]; int i = 0; for (int i = 0; i < countAlpha; i++) alpha[i] = 0; for(i = pos; i < strlen(text) && text[i] != ' '; i++) if(!alpha[tolower(text[i]) - 'a']++) cout << text[i]; cout << " "; pos = i; } int main() { int n = 0; ifstream input("input.txt"); cout << "First string in your file should consist of one number (size of any next string, cstring :( :/ )))\n\n"; cout << "If file with your text is exist, you should see text!\n\n"; input >> n; char *text = new char[n]; while(input.getline(text, n)) { for(int pos = 0; pos < n; pos++) if(isalpha(text[pos])) nextWord(pos, text); cout << endl; } delete[] text; return 0; }
true
53d0d8b0ab7ff0e3a3d32edb98a6a1ed4bbfcac3
C++
twj2417/recon
/PETScanner/DodePET.hh
UTF-8
3,017
2.875
3
[]
no_license
#ifndef DODEPET_HH #define DODEPET_HH /* * @brief: * However, this general model will cost much time when given a point and find which crystal it belongs to. * Thus, the specific scanner (SpherePET, DodePET) are devoloped to sort the crystals in the list according * to their spatial position. It markablely reduce the time to locate a point to the crystals. * This file declares the model of ringy PET scanner. * @auther: chengaoyu2013@gmail.com * @date: 2017/04/10 */ #include"PETScanner.hh" /* * Class declaration: * DodePET models the discrete scheme of a dodecahedral PET scanner. * The whole scanner is made of 12 pentagen blocks and the block orgin is the bottom block. * The cystals are arranged in blocks. */ class DodePET:public PETScanner{ public: DodePET(); virtual ~DodePET(); DodePET(float inR, float tn, size_t nbok, const Block& bok); //there are 9 rotation matrix in the list. virtual void setupParas(); virtual const Rotation& getRotationMatrix(size_t index) const; //radius setter and getter. virtual void setInnerR(float r){ innerR = r;} virtual float getInnerR() const{ return innerR;} virtual void setNBlocks(size_t n){nBlocks= n<=12? n:11;} virtual size_t getNBlocks() const{ return nBlocks;} virtual void setThickness(float t){ thickness = t;} virtual float getThickness() const{return thickness;} // the blockorigin setter and getter. virtual const Block& getBlockOrigin() const {return blockorigin;} // check if the bound of the scanner is valid. // give an error message when the blocks are overlapped or out of the cylinder. // and then use the default setting //virtual bool ValidBound(); // default set of a DodePET. virtual void defaultDodePET(); virtual void initializeScanner() override; //fill the crystal list. virtual void fillCrystalList() override; //only a block origin of the detector is saved. virtual bool findCrystal(Point3D& pt, const size_t &blockIndex) const; virtual bool findCrystal(Point3D& pt, const size_t &blockIndex,size_t index) const; virtual size_t getNumOfCrystals() const override; virtual void EfficiencyMap(const std::string &vefilename) override; //virtual void LMFactors(const std::string& evtfilename, const std::string &transevtfilename) override; virtual double cross(const Point3D& p0, const Point3D& p1, const Point3D& p2) const; virtual bool IsInsidePenta(const Point3D& pt) const; virtual void TransEvents(const std::string& evtfilename, const std::string& transevtfilename); private: float innerR; // inradius of DodePET. float thickness; // thickness of the detector; size_t nBlocks; // number of blocks in the DodePET, no more than 12. // the block origin(size and grid) // all of the blocks can be generated from this origin by rotate and shift. Block blockorigin; std::vector<Rotation> RotationList; std::vector<Point3D> PentaBound; }; #endif // DODEPET_HH
true
62411abcafd142890b971eeba01169684e5cdbbe
C++
detlevVL/MasterThesis
/naminganalysis.cpp
UTF-8
1,407
2.53125
3
[]
no_license
#include "naminganalysis.h" NamingAnalysis::NamingAnalysis() { } QMultiHash<QString, QString> NamingAnalysis::analyse(QList<QString> sources, QList<QString> tests, QList<QString> modifiedSources, QList<QString> modifiedTests) { QMultiHash<QString, QString> links; // for each modified source file basename (i.e. "/home/somewhere/something.qml" > "something.qml") foreach (const QString &source, modifiedSources) { QString possibleTest = QString::fromStdString("tst_").append(source.section(QString::fromStdString("/"), -1)); // check if there is a "tst_something.qml" test file foreach (const QString &test, tests) { if (test.section(QString::fromStdString("/"),-1).compare(possibleTest, Qt::CaseInsensitive) == 0) { links.insert(source, test); } } } // for each modified test file basename (i.e. "/home/somewhere/tst_something.qml" > "tst_something.qml") foreach (const QString &test, modifiedTests) { QString possibleSource = test.section(QString::fromStdString("_"), 1); // check if there is a "something.qml" source file foreach (const QString &source, sources) { if (source.section(QString::fromStdString("/"),-1).compare(possibleSource, Qt::CaseInsensitive) == 0) { links.insert(source, test); } } } return links; }
true
17bbe2db5fc83c80c394cb1f0e52e76dd7cec056
C++
adriaan1539/Bank_data_import
/BankAccountEntry.cpp
UTF-8
3,843
3.0625
3
[]
no_license
#include "BankAccountEntry.h" #include "JoinVectorToString.h" #include <fstream> #include <iostream> #include "minicsv.h" BankAccountEntry::BankAccountEntry() { } BankAccountEntry::BankAccountEntry( unsigned int year, unsigned int month, unsigned int day, std::string nameOrDescription, std::string accountNumberConsidered, std::string accountNumberContra, std::string code, double amount, std::string sortOfMutation, std::string note) { this->year=year; this->month=month; this->day=day; this->nameOrDescription=nameOrDescription; this->accountNumberConsidered=accountNumberConsidered; this->accountNumberContra=accountNumberContra; this->code=code; this->amount=amount; this->sortOfMutation=sortOfMutation; this->note=note; } double BankAccountEntry::GetAmount(void) { return amount; } double BankAccountEntry::GetBalance(void) { return balance; } std::string BankAccountEntry::GetAccountNumberConsidered(void) { return accountNumberConsidered; } std::string BankAccountEntry::GetAccountNumberContra(void) { return accountNumberContra; } std::string BankAccountEntry::GetCategoryNames(void) { return JoinVector(this->categories, ";"); } std::string BankAccountEntry::GetCode(void) { return code; } std::string BankAccountEntry::GetNameOrDescription(void) { return nameOrDescription; } std::string BankAccountEntry::GetNote(void) { return note; } std::string BankAccountEntry::GetRuleNames(void) { return JoinVector(this->rules, ";"); } std::string BankAccountEntry::GetSortOfMutation(void) { return sortOfMutation; } std::string BankAccountEntry::ToCSV(int index) { mini::csv::ostringstream os; os.set_delimiter(',', "."); os << index << this->year << this->month << this->day << this->nameOrDescription << this->accountNumberConsidered << this->accountNumberContra << this->code << this->amount << this->sortOfMutation << this->note << this->GetCategoryNames() << this->GetRuleNames() << this->balance; return os.get_text(); } std::vector<std::string> BankAccountEntry::GetCategories() { return this->categories; } unsigned int BankAccountEntry::GetDay(void) const { return day; } unsigned int BankAccountEntry::GetMonth(void) const { return month; } unsigned int BankAccountEntry::GetYear(void) const { return year; } void BankAccountEntry::AddCategoryAndRuleName(std::string category, std::string rule) { this->categories.push_back(category); this->rules.push_back(rule); } void BankAccountEntry::PrintToConsole(void) { std::cout<<"year: "<<year<<"\n"; std::cout<<"month: "<<month<<"\n"; std::cout<<"day: "<<day<<"\n"; std::cout<<"nameOrDescription: "<<nameOrDescription<<"\n"; std::cout<<"accountNumberConsidered: "<<accountNumberConsidered<<"\n"; std::cout<<"accountNumberContra: "<<accountNumberContra<<"\n"; std::cout<<"code: "<<code<<"\n"; std::cout<<"amount: "<<amount<<"\n"; std::cout<<"sortOfMutation: "<<sortOfMutation<<"\n"; std::cout<<"note: "<<note<<"\n\n"; } void BankAccountEntry::PrintToFile(std::string fileName) { std::ofstream outputFileStream; outputFileStream.open(fileName,std::ios::app); outputFileStream<<"year: "<<year<<"\n"; outputFileStream<<"month: "<<month<<"\n"; outputFileStream<<"day: "<<day<<"\n"; outputFileStream<<"nameOrDescription: "<<nameOrDescription<<"\n"; outputFileStream<<"accountNumberConsidered: "<<accountNumberConsidered<<"\n"; outputFileStream<<"accountNumberContra: "<<accountNumberContra<<"\n"; outputFileStream<<"code: "<<code<<"\n"; outputFileStream<<"amount: "<<amount<<"\n"; outputFileStream<<"sortOfMutation: "<<sortOfMutation<<"\n"; outputFileStream<<"note: "<<note<<"\n\n"; outputFileStream.close(); } void BankAccountEntry::SetBalance(double balance) { this->balance = balance; }
true
42f1ab05046a2e07d22a88b7085c11d67b5390b9
C++
sergio-eld/simplecs
/include/simplecs/impl/id_pool.h
UTF-8
1,001
3.234375
3
[ "MIT" ]
permissive
#pragma once #include <stack> #include <type_traits> namespace eld::detail { template<typename IdT> class id_pool { public: using id_type = IdT; id_type next_available() { if (freed_.empty()) return instances_++; const auto id = freed_.top(); freed_.pop(); return id; } void free(const id_type &id) { // TODO: assertions if (instances_ - 1 == id) { --instances_; return; } freed_.template emplace(id); } bool is_free(const id_type & /*id*/) { // TODO: implement return false; } bool reserve(const id_type & /*id*/) { // TODO: implement return false; } private: id_type instances_; std::stack<id_type> freed_; }; } // namespace eld::detail
true
1693ed2553478338397c531d550f46d3684d79c2
C++
hthnguyen/hthnguyen_ws
/WS4/WS4_P1/Saiyan.cpp
UTF-8
1,526
3
3
[]
no_license
// Student name: Nguyen Hoang Trung Hieu // Student ID: 142914191 // Section: NBB // I have done all the coding by myself and only copied the code that my professor provided to complete my workshops and assignments. #define _CRT_SECURE_NO_WARNINGS #include "Saiyan.h" #include<string.h> #include<iostream> using namespace std; namespace sdds { Saiyan::Saiyan() { setEmpty(); } Saiyan::Saiyan(const char* name, int dob, int power, bool super) { set(name, dob, power); } void Saiyan::set(const char* name, int dob, int power, bool super) { if (name == nullptr || name[0] == '\0' || (dob < 0 || dob > 2020) || power < 0) setEmpty(); else { strcpy(this->m_name, name); this->m_dob = dob; this->m_power = power; } } void Saiyan::setEmpty() { this->m_name[0] = '\0'; this->m_dob = 9999; this->m_power = -1; } bool Saiyan::isValid() const { if ( this->m_name[0] == '\0' || this->m_dob< 0 || this->m_dob > 2020 || this->m_power < 0) return false; else return true; } void Saiyan::display() const { if (isValid()) { cout << this->m_name << endl; cout << "DOB: " << this->m_dob << endl; cout << "Power: " << this->m_power << endl; if(this->m_super) cout << "Super: " << "yes" << endl; else cout << "Super: " << "no" << endl; } else cout << "Invalid Saiyan!" << endl; } bool Saiyan::fight(const Saiyan& other) { bool value = false; if (isValid()) { if (this->m_power < other.m_power) value = false; else value = true; } return value; } }
true
cb738bf20522160729ad8159b20dc98651ea8e03
C++
alonakorzhnev/sqlink
/C++/String_t/string_main.cpp
UTF-8
6,809
3.625
4
[]
no_license
#include "string_t.h" #include <iostream> #define MAX_LENGTH 64 using namespace std; void defaultConstructor(); void paramConstructor(); void copyConstructor(); void operatorAssig(); void stringCompare(); void setString(); void toUpper(); void toLower(); void prependObj(); void prependStr(); void plusAssObj(); void plusAssStr(); void boolOperators(); void strContain(); void getChar(); void setChar(); int main() { unsigned int option; int cont = 1; while (cont) { cout << endl << "Choose option:" << endl << "1. Create object with default constructor" << endl << "2. Create object with constructor with parameters" << endl << "3. Create object with copy constructor" << endl << "4. Operator =" << endl << "5. String compare" << endl << "6. Set string" << endl << "7. To upper case" << endl << "8. To lower case" << endl << "9. Prepend with object" << endl << "10. Prepend with string" << endl << "11. Operator += with object" << endl << "12. Operator += with string" << endl << "13. Boolean operators" << endl << "14. String contains" << endl << "15. Get char by index" << endl << "16. Change char by index" << endl << "Any another number - stop" << endl; cin >> option; switch (option) { case 1: { defaultConstructor(); break; } case 2: { paramConstructor(); break; } case 3: { copyConstructor(); break; } case 4: { operatorAssig(); break; } case 5: { stringCompare(); break; } case 6: { setString(); break; } case 7: { toUpper(); break; } case 8: { toLower(); } case 9: { prependObj(); break; } case 10: { prependStr(); break; } case 11: { plusAssObj(); break; } case 12: { plusAssStr(); break; } case 13: { boolOperators(); break; } case 14: { strContain(); break; } case 15: { getChar(); break; } case 16: { setChar(); break; } default: { cont = 0; break; } } } return 0; } void defaultConstructor() { String_t s; cout << "String: " << s << endl; } void paramConstructor() { char *str = new char[MAX_LENGTH]; cout << "Enter string for constructor: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; delete[] str; } void copyConstructor() { char *str = new char[MAX_LENGTH]; cout << "Enter string for constructor for first object: " << endl; cin >> str; String_t s1(str); cout << "String: " << s1 << endl; delete[] str; String_t s2 = s1; cout << "String: " << s2 << endl; } void operatorAssig() { char *str = new char[MAX_LENGTH]; cout << "Enter string for constructor for first object: " << endl; cin >> str; String_t s1(str); cout << "String: " << s1 << endl; cout << "Enter string for constructor for second object: " << endl; cin >> str; String_t s2(str); cout << "String: " << s2 << endl; delete[] str; s1 = s2; cout << "String: " << s1 << endl; } void stringCompare() { char *str = new char[MAX_LENGTH]; cout << "Enter string for constructor for first object: " << endl; cin >> str; String_t s1(str); cout << "String: " << s1 << endl; cout << "Enter string for constructor for second object: " << endl; cin >> str; String_t s2(str); cout << "String: " << s2 << endl; delete[] str; cout << "Result: " << s1.stringCompare(s2) << endl; } void setString() { char *str = new char[MAX_LENGTH]; cout << "Enter string for constructor for first object: " << endl; cin >> str; String_t s1(str); cout << "String: " << s1 << endl; delete[] str; cout << "Enter string for set: " << endl; cin >> str; s1.setString(str); cout << "String: " << s1 << endl; } void toUpper() { char str[MAX_LENGTH]; cout << "Enter string to convert to upper case: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; s.toUpper(); cout << "Result: " << s << endl; } void toLower() { char str[MAX_LENGTH]; cout << "Enter string to convert to lower case: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; s.toLower(); cout << "Result: " << s << endl; } void prependObj() { char str[MAX_LENGTH]; cout << "Enter string to create first object: " << endl; cin >> str; String_t s1(str); cout << "String 1: " << s1 << endl; cout << "Enter string to create second object: " << endl; cin >> str; String_t s2(str); cout << "String 2: " << s2 << endl; s1.prepend(s2); cout << "Result of string 1: " << s1 << endl; } void prependStr() { char str[MAX_LENGTH]; cout << "Enter string to create object: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; cout << "Enter string to prepend to object: " << endl; cin >> str; s.prepend(str); cout << "Result of string: " << s << endl; } void plusAssObj() { char str[MAX_LENGTH]; cout << "Enter string to create first object: " << endl; cin >> str; String_t s1(str); cout << "String 1: " << s1 << endl; cout << "Enter string to create second object: " << endl; cin >> str; String_t s2(str); cout << "String 2: " << s2 << endl; s1 += s2; cout << "Result of string 1: " << s1 << endl; } void plusAssStr() { char str[MAX_LENGTH]; cout << "Enter string to create object: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; cout << "Enter string to append to object: " << endl; cin >> str; s += str; cout << "Result of string: " << s << endl; } void boolOperators() { } void strContain() { char str[MAX_LENGTH]; cout << "Enter string to create object: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; cout << "Enter string to find if object contains it: " << endl; cin >> str; cout << "Result: " << s.contains(str) << endl; } void getChar() { char str[MAX_LENGTH]; cout << "Enter string to create object: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; int index; cout << "Enter index of char: " << endl; cin >> index; cout << "Result: " << s[index] << endl; } void setChar() { char str[MAX_LENGTH]; cout << "Enter string to create object: " << endl; cin >> str; String_t s(str); cout << "String: " << s << endl; int index; char ch; cout << "Enter index of char and char to set: " << endl; cin >> index >> ch; s[index] = ch; cout << "Result: " << s << endl; }
true
c4b29bffd8bcf163e7de0773baf74435c00d1850
C++
tsingke/Homework_Turing
/杨奕帆/Experiment_2/Source Code/四(6).cpp
UTF-8
258
2.9375
3
[]
no_license
#include<iostream> using namespace std; void fun(int a, int &b) { a+= b; b += a; } int main() { int x = 5, y = 10; fun(x, y); cout << "x=" << x << ",y=" << y << endl; fun(y, x); cout << "x=" << x << ",y=" << y << endl; system("pause"); return 0; }
true
1cc339debe47f1b4d138c50c60ee03d5d2944e72
C++
bikash-das/cppPrograms
/BeginningC++17/functionTemplates_ch_9/decltype_demo.cpp
UTF-8
405
3.15625
3
[]
no_license
template <typename T1, typename T2> auto larger(T1 a, T2 b) -> decltype(a>b ? a:b){ return a > b ? a : b; } // the above code can be tedious to write, we can simplify // using decltype(auto) introduced in c++14 template<typename T1, typename T2, typename T3> decltype(auto) larger(T1 a, T2 b){ return a > b ? a : b; } #include <iostream> int main(){ std::cout << larger(100.2,34) << "\n"; }
true
3104d3955e4f1b8355d174890bf95d032861f30f
C++
egorodet/MethaneKit
/Tests/Graphics/Types/VolumeTest.cpp
UTF-8
8,806
2.796875
3
[ "Apache-2.0" ]
permissive
/****************************************************************************** Copyright 2021 Evgeny Gorodetskiy 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. ******************************************************************************* FILE: Tests/Graphics/Types/VolumeTest.cpp Unit-tests of the Volume data type ******************************************************************************/ #include <Methane/Graphics/Volume.hpp> #include <Methane/Graphics/TypeFormatters.hpp> #include <catch2/catch_template_test_macros.hpp> using namespace Methane::Graphics; template<typename D> using VolumePtInt = Volume<int32_t, D>; template<typename D> using VolumePtUint = Volume<uint32_t, D>; template<typename D> using VolumePtFloat = Volume<float, D>; template<typename D> using VolumePtDouble = Volume<double, D>; #define RECT_TYPES_PRODUCT \ (VolumePtInt, VolumePtUint, VolumePtFloat, VolumePtDouble), \ (int32_t, uint32_t, float, double) TEMPLATE_PRODUCT_TEST_CASE("Volume Initialization", "[volume][init]", RECT_TYPES_PRODUCT) { using PointType = typename TestType::Point; using SizeType = typename TestType::Size; const PointType test_origin(12, 34, 56); const SizeType test_size(671, 782, 893); SECTION("Default initialization of empty volume") { const TestType test_vol; CHECK(test_vol.origin == PointType()); CHECK(test_vol.size == SizeType()); } SECTION("Origin only initialization") { const TestType test_vol(test_origin); CHECK(test_vol.origin == test_origin); CHECK(test_vol.size == SizeType()); } SECTION("Size only initialization") { const TestType test_vol(test_size); CHECK(test_vol.origin == PointType()); CHECK(test_vol.size == test_size); } SECTION("Origin and size initialization") { const TestType test_vol(test_origin, test_size); CHECK(test_vol.origin == test_origin); CHECK(test_vol.size == test_size); } SECTION("Coordinates and dimensions initialization") { const TestType test_vol(12, 34, 56, 671, 782, 893); CHECK(test_vol.origin == test_origin); CHECK(test_vol.size == test_size); } } TEMPLATE_PRODUCT_TEST_CASE("Volumes Comparison", "[volume][compare]", RECT_TYPES_PRODUCT) { using PointType = typename TestType::Point; using SizeType = typename TestType::Size; const PointType test_origin(12, 34, 56); const SizeType test_size(671, 782, 893); const TestType test_vol(test_origin, test_size); SECTION("Equality") { CHECK(test_vol == TestType(test_origin, test_size)); CHECK_FALSE(test_vol == TestType(test_origin)); CHECK_FALSE(test_vol == TestType(test_size)); } SECTION("Inequality") { CHECK_FALSE(test_vol != TestType(test_origin, test_size)); CHECK(test_vol != TestType(test_origin)); CHECK(test_vol != TestType(test_size)); } } TEMPLATE_PRODUCT_TEST_CASE("Volume Math Operations", "[volume][math]", RECT_TYPES_PRODUCT) { using PointType = typename TestType::Point; using SizeType = typename TestType::Size; using CoordType = typename PointType::CoordinateType; using DimType = typename SizeType::DimensionType; const PointType test_origin(2, 4, 6); const SizeType test_size(6, 8, 10); const TestType test_vol(test_origin, test_size); SECTION("Multiplication by scalar of coordinate type") { const TestType res_volume = test_vol * CoordType(2); CHECK(res_volume.origin == PointType(4, 8, 12)); CHECK(res_volume.size == SizeType(12, 16, 20)); } SECTION("Multiplication by scalar of dimension type") { const TestType res_volume = test_vol * DimType(2); CHECK(res_volume.origin == PointType(4, 8, 12)); CHECK(res_volume.size == SizeType(12, 16, 20)); } SECTION("Division by scalar of coordinate type") { const TestType res_volume = test_vol / CoordType(2); CHECK(res_volume.origin == PointType(1, 2, 3)); CHECK(res_volume.size == SizeType(3, 4, 5)); } SECTION("Division by scalar of dimension type") { const TestType res_volume = test_vol / DimType(2); CHECK(res_volume.origin == PointType(1, 2, 3)); CHECK(res_volume.size == SizeType(3, 4, 5)); } SECTION("Inplace multiplication by scalar of coordinate type") { TestType res_volume = test_vol; res_volume *= CoordType(2); CHECK(res_volume.origin == PointType(4, 8, 12)); CHECK(res_volume.size == SizeType(12, 16, 20)); } SECTION("Inplace multiplication by scalar of dimension type") { TestType res_volume = test_vol; res_volume *= DimType(2); CHECK(res_volume.origin == PointType(4, 8, 12)); CHECK(res_volume.size == SizeType(12, 16, 20)); } SECTION("Inplace division by scalar of coordinate type") { TestType res_volume = test_vol; res_volume /= CoordType(2); CHECK(res_volume.origin == PointType(1, 2, 3)); CHECK(res_volume.size == SizeType(3, 4, 5)); } SECTION("Inplace division by scalar of dimension type") { TestType res_volume = test_vol; res_volume /= DimType(2); CHECK(res_volume.origin == PointType(1, 2, 3)); CHECK(res_volume.size == SizeType(3, 4, 5)); } } TEMPLATE_PRODUCT_TEST_CASE("Volume Conversion to Other Types", "[volume][convert]", RECT_TYPES_PRODUCT) { using PointType = typename TestType::Point; using SizeType = typename TestType::Size; using CoordType = typename PointType::CoordinateType; using DimType = typename SizeType::DimensionType; const PointType test_origin(12, 34, 56); const SizeType test_size(671, 782, 893); const TestType test_vol(test_origin, test_size); if constexpr (std::is_floating_point_v<CoordType>) { if constexpr (std::is_floating_point_v<DimType>) { SECTION("Convert to integer point and integer size volume") { CHECK(static_cast<Volume<int32_t, uint32_t>>(test_vol) == Volume<int32_t, uint32_t>(12, 34, 56, 671U, 782U, 893U)); } } else { SECTION("Convert to integer point and floating size volume") { CHECK(static_cast<Volume<int32_t, float>>(test_vol) == Volume<int32_t, float>(12, 34, 56, 671.F, 782.F, 893.F)); } } } else { if constexpr (std::is_floating_point_v<DimType>) { SECTION("Convert to floating point and integer size volume") { CHECK(static_cast<Volume<float, uint32_t>>(test_vol) == Volume<float, uint32_t>(12.F, 34.F, 56.F, 671U, 782U, 893U)); } } else { SECTION("Convert to floating point and floating size volume") { CHECK(static_cast<Volume<float, float>>(test_vol) == Volume<float, float>(12, 34, 56, 671.F, 782.F, 893.F)); } } } SECTION("Conversion to string") { CHECK(static_cast<std::string>(test_vol) == "Vol[P(12, 34, 56) : Sz(671 x 782 x 893)]"); } } TEMPLATE_PRODUCT_TEST_CASE("Volume Property Getters", "[volume][accessors]", RECT_TYPES_PRODUCT) { using PointType = typename TestType::Point; using SizeType = typename TestType::Size; using CoordType = typename PointType::CoordinateType; const PointType test_origin(12, 34, 56); const SizeType test_size(671, 782, 893); const TestType test_vol(test_origin, test_size); SECTION("Left coordinate getter") { CHECK(test_vol.GetLeft() == CoordType(12)); } SECTION("Right coordinate getter") { CHECK(test_vol.GetRight() == CoordType(683)); } SECTION("Top coordinate getter") { CHECK(test_vol.GetTop() == CoordType(34)); } SECTION("Bottom coordinate getter") { CHECK(test_vol.GetBottom() == CoordType(816)); } SECTION("Near coordinate getter") { CHECK(test_vol.GetNear() == CoordType(56)); } SECTION("Far coordinate getter") { CHECK(test_vol.GetFar() == CoordType(949)); } }
true
1681fa93be91282ae471249ce6513aac6618cfc5
C++
tysm/cpsols
/codeforces/contests/round/407-div2/d.cpp
UTF-8
727
2.65625
3
[ "MIT" ]
permissive
#include <cpplib/stdinc.hpp> #include <cpplib/math/combinatorics.hpp> void dfs(int u, vvi &adj, vb &vis){ vis[u] = true; for(int v:adj[u]){ if(!vis[v]) dfs(v, adj, vis); } } int32_t main(){ desync(); int n, m; cin >> n >> m; vvi adj(n+1); for(int i=0; i<m; ++i){ int u, v; cin >> u >> v; adj[u].eb(v); adj[v].eb(u); } if(m < 2){ cout << 0 << endl; return 0; } int acc = 0; vb vis(n+1); for(int i=1; i<=n; ++i){ if(!vis[i]){ dfs(i, adj, vis); acc++; } } if(acc == 1) cout << C(m, 2) << endl; else cout << 0 << endl; return 0; }
true
4782feabd8dae43b4cf7a25e3271a97192f247e1
C++
dmccloskey/EvoNet
/src/evonet/include/EvoNet/ml/Link.h
UTF-8
3,077
3.046875
3
[ "MIT" ]
permissive
/**TODO: Add copyright*/ #ifndef EVONET_LINK_H #define EVONET_LINK_H #include <tuple> #include <string> #include <cereal/cereal.hpp> namespace EvoNet { /** @brief Directed Network Link */ class Link { public: Link(); ///< Default constructor Link(const Link& other); ///< Copy constructor // [TODO: add test] Link(const int& id); ///< Explicit constructor Link(const std::string& name); ///< Explicit constructor Link(const std::string& name, const std::string& source_node_name, const std::string& sink_node_name, const std::string& weight_name); ///< Explicit constructor ~Link(); ///< Default destructor inline bool operator==(const Link& other) const { return std::tie( id_, source_node_name_, sink_node_name_, weight_name_, name_, module_id_, module_name_ ) == std::tie( other.id_, other.source_node_name_, other.sink_node_name_, other.weight_name_, other.name_, other.module_id_, other.module_name_ ) ; } inline bool operator!=(const Link& other) const { return !(*this == other); } inline Link& operator=(const Link& other) { // [TODO: add test] id_ = other.id_; name_ = other.name_; module_id_ = other.module_id_; module_name_ = other.module_name_; source_node_name_ = other.source_node_name_; sink_node_name_ = other.sink_node_name_; weight_name_ = other.weight_name_; return *this; } void setId(const int& id); ///< id setter int getId() const; ///< id getter void setName(const std::string& name); ///< naem setter std::string getName() const; ///< name getter void setSourceNodeName(const std::string& source_node_name); ///< source_node_name setter std::string getSourceNodeName() const; ///< source_node_name getter void setSinkNodeName(const std::string& sink_node_name); ///< sink_node_name setter std::string getSinkNodeName() const; ///< sink_node_name getter void setWeightName(const std::string& weight_name); ///< weight_name setter std::string getWeightName() const; ///< weight_name getter void setModuleId(const int& module_id); ///< module id setter int getModuleId() const; ///< module id getter void setModuleName(const std::string& module_name); ///< module name setter std::string getModuleName() const; ///< module name getter private: friend class cereal::access; template<class Archive> void serialize(Archive& archive) { archive(id_, name_, module_id_, module_name_, source_node_name_, sink_node_name_, weight_name_); } int id_ = -1; ///< Weight ID std::string name_ = ""; ///< Weight Name int module_id_ = -1; ///< Module ID std::string module_name_ = ""; ///<Module Name std::string source_node_name_; ///< Link source node std::string sink_node_name_; ///< Link sink node std::string weight_name_; ///< Link weight }; } #endif //EVONET_LINK_H
true
481d4da92c4cf51b299d28322cc2e7afe07ee5b1
C++
jessimb/soldiers
/soldiers/clickablelabel.cpp
UTF-8
323
2.5625
3
[]
no_license
#include "clickablelabel.h" #include <iostream> ClickableLabel::ClickableLabel( int row2, int col2, QWidget * parent ) : QLabel(parent) { row = row2; col = col2; } ClickableLabel::~ClickableLabel() { } void ClickableLabel::mousePressEvent ( QMouseEvent * event ) { (void) event; emit clicked(row, col); }
true
d54231bc26464a0e16d76e5a1c11bb51f37d02a0
C++
mehoggan/visualization
/lib/camera.cpp
UTF-8
382
2.515625
3
[]
no_license
#include "com/visualization/camera.h" namespace com { namespace visualization { camera::camera() : pos_(0.0f, 0.0f, 1.0f), target_pos_(0.0f, 0.0f, 0.0f), view_matrix_(glm::lookAt( pos_, target_pos_, glm::vec3(0.0f, 1.0f, 0.0f))) {} const glm::mat4 &camera::view_matrix() const { return view_matrix_; } } }
true
af6f052ed8fd0ff05f2b0d72f4fee52d7b5c3968
C++
ltr01/stroustrup-ppp-1
/code_snippets/Chapter09/chapter.9.4.1.cpp
UTF-8
1,481
4.0625
4
[ "MIT" ]
permissive
// // This is example code from Chapter 9.4.1 "Struct and functions" of // "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup // //------------------------------------------------------------------------------ // simple Date (too simple?): struct Date { int y; // year int m; // month in year int d; // day of month }; //------------------------------------------------------------------------------ // helper functions: void init_day(Date& dd, int y, int m, int d) { // check that (y,m,d) is a valid date // if it is, use it to initialize dd } //------------------------------------------------------------------------------ void add_day(Date& dd, int n) { // increase dd by n days } //------------------------------------------------------------------------------ void f() { Date today; init_day(today, 12, 24, 2005); // oops! (no day 2005 in year 12) add_day(today,1); } //------------------------------------------------------------------------------ int main() { Date today; // a Date variable (a named object) // set today to December 24, 2005 today.y = 2005; today.m = 24; today.d = 12; Date x; x.y = -3; x.m = 13; x.d = 32; // Was year 2000 a leap year? Are you sure? Date y; y.y = 2000; y.m = 2; y.d = 29; init_day(y, 2000, 1, 1); add_day(y, 28); return 0; } //------------------------------------------------------------------------------
true
5c897c4963c7e5b9373755a1d472283aa0540787
C++
ajp4707/Check-Mate
/Check-Mate/Check-Mate/RBTree.h
UTF-8
886
2.875
3
[ "MIT" ]
permissive
#pragma once #include<string> #include<iostream> #define black 0 #define red 1 // Inspiration: Ms. Resch's lecture on Red-Black Trees // https://gist.github.com/derka6391/7b7463ac36a9fb04bea0668397d41d23 struct RBNode { std::string gameStr; char points; bool color = black; RBNode * left; RBNode * right; RBNode * parent; RBNode(std::string _gameStr, char _points); }; RBNode* createInsert(RBNode* root, std::string gameStr, char points); RBNode * insert(RBNode* root, RBNode* node); RBNode * BSTinsert(RBNode* root, RBNode* node); RBNode * RBbalance(RBNode* root, RBNode* node); RBNode * getUncle(RBNode* node); RBNode* rotateRight(RBNode*root, RBNode* top); RBNode* rotateLeft(RBNode* root, RBNode* top); float rating(RBNode* root, std::string gameStr); void traverseSum(RBNode* root, std::string& left, std::string& right, float& sum, int& count); int count(RBNode* root);
true
44b733da51a16d5c38a59681ada362a8d911c1a7
C++
shreyakapoor08/CPP_Programs
/random programs/constants.cpp
UTF-8
285
3.0625
3
[]
no_license
#include<iostream> #define PI 3.14 #define PRINT cout<< using namespace std; int main() { cout<<2*PI<<endl; PRINT "Hello World"<<endl; ///const variables int x=1.1; x++; cout<<x<<endl; const int y=2.1; /// y++; created in ROM so cant be updated cout<<y<<endl; return 0; }
true
804bbd1b5a512382c8ed3a96ef70eee8a02aa5a1
C++
liweiliv/DBStream
/database/indexIterator.h
UTF-8
1,824
2.859375
3
[]
no_license
#pragma once #include <stdint.h> #include <assert.h> #include "meta/columnType.h" #include "iterator.h" namespace DATABASE { template<class INDEX_TYPE> class indexIterator { protected: uint32_t flag; INDEX_TYPE* index; META::COLUMN_TYPE type; const uint32_t* recordIds; uint32_t idChildCount; uint32_t innerIndexId; public: indexIterator(uint32_t flag, INDEX_TYPE* index, META::COLUMN_TYPE type) :flag(flag), index(index), type(type), recordIds(nullptr), idChildCount(0), innerIndexId(0) { } indexIterator(const indexIterator& iter) :flag(iter.flag), index(iter.index), type(iter.type), recordIds(iter.recordIds), idChildCount(iter.idChildCount), innerIndexId(iter.innerIndexId) {} indexIterator& operator=(const indexIterator& iter) { key = iter.key; index = iter.index; innerIndexId = iter.innerIndexId; return *this; } virtual ~indexIterator() {} virtual bool begin() = 0; virtual bool rbegin() = 0; virtual bool seek(const void* key) = 0; virtual inline bool valid()const { return recordIds != nullptr && innerIndexId < idChildCount; } virtual inline uint32_t value() const { return recordIds[innerIndexId]; } virtual inline void toLastValueOfKey() { innerIndexId = idChildCount - 1; } virtual inline void toFirstValueOfKey() { innerIndexId = 0; } virtual const void* key()const = 0; virtual inline uint32_t currentVersionValue() { return recordIds[idChildCount - 1]; } virtual inline bool next() { if (innerIndexId + 1 < idChildCount) { innerIndexId++; return true; } else return false; } virtual bool nextKey() = 0; virtual inline bool prev() { if (innerIndexId >= 1) { innerIndexId--; return true; } else return false; } virtual bool prevKey() = 0; }; }
true
9d949e1786f0caf13e75db3cb0131523da11b5ae
C++
sophiaken/Banking-Distributed-System
/Clock_Synchronization/master2.cpp
UTF-8
2,508
2.59375
3
[]
no_license
#include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include<cstdlib> #include <string.h> #include <sys/socket.h> #include <unistd.h> #include<iostream> #include<time.h> #include<fstream> #include<pthread.h> using namespace std; #define MAX_THREADS 100 #define PORT 8090 int main(int argc, char* argv[]) { int pc; int mc; int valread1; char sendbuff[1024]; //generating random number clock for the master srand(time(0)); int master_clock=rand()%100; cout<<"master_clock initial:"<<master_clock<<endl; int server_fd, new_socket[100], valread,new_socket1; struct sockaddr_in address; int addrlen = sizeof(address); // Creating socket file descriptor if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); // Forcefully attaching socket to // the port 8090 if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) { perror("bind failed"); exit(EXIT_FAILURE); } //For command line arguments int nop; if (argc > 1) nop = atoi(argv[1]); int cc=0; cout<<"**********Client************"<<'\n'; // puts the server socket in passive mode if (listen(server_fd, 4) < 0) { perror("listen"); exit(EXIT_FAILURE); } int clock_1; char buffer[250]={0}; string mes="Send the time of your clocks "; char msg[100]; int num=1; int clo[100]; for(int i=0;i<nop;i++){ //accepting the client request new_socket[i] = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen) ; } for(int i=0;i<nop;i++){ //sending the initial message to send the time send(new_socket[i], mes.c_str(), sizeof(mes),0); //receives the time from all the clients. recv(new_socket[i],&clock_1,sizeof(clock_1),0); clo[i]=clock_1; cout<<"client"<<clock_1<<endl; } for(int i=0;i<nop;i++){ //calculation of berkeley algorithm cc=cc+clo[i]; mc= (cc+master_clock)/(i+2); } cout<<"master clock:\t"<<mc<<endl; //Sending the calculated time to all the clients. for(int i=0;i<nop;i++){ send(new_socket[i],&mc,sizeof(mc),0); } return 0; }
true
e54bb98a5d778c85896ea3a86976538f1b2df3d2
C++
lucivpav/bomberman
/src/hostmenu.cpp
UTF-8
2,056
2.96875
3
[]
no_license
#include "hostmenu.h" #include "game.h" #include <fstream> #include <cassert> HostMenu::HostMenu(const std::string &levelsPath) :Menu("Host"), mLevelsPath(levelsPath) { /* levels */ addItem( mLevelList = new UI::List("Level") ); for ( int i = 1 ; i <= 10 ; i++ ) { std::ifstream in(mLevelsPath + std::to_string(i)); if ( !in ) break; mLevelList->addItem(std::to_string(i).c_str()); } /* lives */ addItem( mLivesList = new UI::List("Lives") ); for ( int i = 1 ; i <= 99 ; i++ ) mLivesList->addItem(std::to_string(i).c_str()); mLivesList->setDefaultItem(2); /* traps */ addItem( mTrapsEnabledList = new UI::List("Traps") ); mTrapsEnabledList->addItem("enable"); mTrapsEnabledList->addItem("disable"); /* ghosts */ addItem( mGhostsEnabledList = new UI::List("Ghosts")); mGhostsEnabledList->addItem("enable"); mGhostsEnabledList->addItem("disable"); addItem( mPortField = new UI::InputField("Port", "39756", 5) ); addItem( new UI::Button("Confirm", std::bind(&HostMenu::confirmAction, this)) ); loop(); } bool HostMenu::confirmAction() { std::string level = mLevelList->curItem(); int lives; try { lives = std::stoi( mLivesList->curItem() ); } catch ( ... ) { assert ( false ); } bool trapsEnabled = mTrapsEnabledList->curItem() == "enable"; bool ghostsEnabled = mGhostsEnabledList->curItem() == "enable"; std::string port = mPortField->content(); if ( !validPort(port) ) { UI::Notification("Error: Invalid port number"); return false; } Game game(mLevelsPath + level, trapsEnabled, ghostsEnabled, lives, "localhost", port.c_str()); return false; } bool HostMenu::validPort(const std::string &port) { try { int p = std::stoi(port); if ( p < 1 || p > 65535 ) throw 42; } catch ( ... ) { return false; } return true; }
true
2cc33cf5022c68e90f186b4e40278e1e25353ca5
C++
ArinaSanches/LaboratorioProgramacao
/Trabalho1/QuicksortLogN.cpp
UTF-8
821
2.90625
3
[]
no_license
// // Created by Arina on 10/04/2019. // #include "QuicksortLogN.h" #include <iostream> using namespace std; #include "FuncoesBasicas.h" FuncoesBasicas funcoes5; void QuicksortLogN::Quicksort(int *inicio, int *fim){ while (inicio < fim) { int* pivo = funcoes5.escolherPivo(inicio, fim); pivo = funcoes5.partLomuto(inicio, fim, pivo); int tamanhoEsq = pivo - inicio; int tamanhoDir = fim - pivo; if( tamanhoEsq < tamanhoDir){ if(pivo > inicio){ int *fimEsq = pivo -1; Quicksort(inicio, fimEsq); } inicio = pivo + 1; }else{ if(pivo < fim){ int *inicioDir = pivo + 1; Quicksort(inicioDir, fim); } fim = pivo - 1; } } }
true
d6898d7459b76d6e3f5414931a489c12e82ea0d4
C++
Mr-Magnificent/ippc
/leetcode/SortList_148.cpp
UTF-8
1,241
3.3125
3
[]
no_license
#include "../lib/createList.hpp" #include <bits/stdc++.h> using namespace std; class Solution { ListNode *findMid(ListNode *node) { ListNode **slow = &node, *fast = node; while (fast && fast->next) { slow = &(*slow)->next; fast = fast->next->next; } ListNode *t = *slow; *slow = nullptr; return t; } ListNode *mergeList(ListNode *l1, ListNode *l2) { ListNode *dummy = new ListNode(-1); ListNode *tail = dummy; while (l1 && l2) { // save // link if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } // move tail = tail->next; } tail->next = (l1) ? l1 : l2; ListNode *t = dummy->next; delete dummy; return t; } public: ListNode *sortList(ListNode *head) { if (!head || !head->next) { return head; } ListNode *mid = findMid(head); ListNode *l1 = sortList(head); ListNode *l2 = sortList(mid); return mergeList(l1, l2); } }; int main() { string line; while(getline(cin, line)) { ListNode *head = stringToIntLinkedList(line); cout << linkedListToString(Solution().sortList(head)) << endl; } }
true
0c5ee420455e8e0a96b16992933865490731aa12
C++
Nabubabu99/ejercicioslaboratorio
/ejParcial2.cpp
UTF-8
1,630
3.234375
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; int main(){ int largo; int aux; int sumatoria = 0; int sumatoriaDiag = 0; int sumatoriaDiagInv = 0; bool esMagico = false; cout << "Ingrese el largo de la matriz: " << endl; cin >> largo; int constMagica = (largo * (largo * largo + 1 )) / 2; int cuboMagico[largo][largo] = {0}; // Cargar cubo for (int i = 0; i < largo; i++) { for (int j = 0; j < largo; j++) { cout << "Ingrese el valor de [" << i << "]-[" << j << "]" << endl; cin >> cuboMagico[i][j]; } } for (int i = 0; i < largo; i++) { sumatoria = 0; for (int j = 0; j < largo; j++) { sumatoria += cuboMagico[i][j]; if (i == j) { sumatoriaDiag += cuboMagico[i][j]; } if (j == largo-i) { sumatoriaDiagInv += cuboMagico[i][j]; } } if (sumatoria == constMagica) { esMagico = true; } } if (sumatoriaDiag == constMagica) { esMagico = true; } if (sumatoriaDiagInv == constMagica) { esMagico = true; } for (int i = 0; i < largo; i++) { for (int j = 0; j < largo; j++) { cout << "\t|" << cuboMagico[i][j] << "|"; } cout << endl; } if (esMagico == true) { cout << "Es magico y su constante es " << constMagica << endl; } else{ cout << "No es magico" << endl; } return 0; }
true
20f4784b5e852e6d7da3206e3515c41d710d6d73
C++
SteveBunlon/ProjetLO21
/Lo21_projets/classes/Tache.h
ISO-8859-1
1,465
2.859375
3
[]
no_license
#ifndef TACHE_H #define TACHE_H #include <iostream> #include <string> #include "timing.h" using namespace TIME; using namespace std; class Programmation; class Projet; class Tache { private: string titre; Tache** antecedentes; Date dispo; //date de dbut Date echeance; Projet& projet; public: Tache(string t, Date d, Date e, Projet& proj): titre(t), dispo(d), echeance(e), projet(proj) { antecedentes = new Tache*[10]; } const string getTitre() const { return titre; } const Date getDispo() const { return dispo; } const Date getEcheance() const { return echeance; } const Projet& getProjetAssocie() const { return projet; } virtual ~Tache() = 0; }; class TacheUnitaire: public Tache{ private: Duree duree; //si non preemptive, ne peut tre > 12h bool preemptive; public: TacheUnitaire(string t, Date d, Date e, Projet& proj, Duree dur, bool p): Tache(t, d, e, proj), duree(dur), preemptive(p) {} const Duree& getDuree() const { return duree; } const bool isPreemptive() const { return preemptive; } ~TacheUnitaire(){} }; class TacheComposite: public Tache{ private: Tache** soustaches; unsigned int nb; unsigned int max; public: TacheComposite(string t, Date d, Date e, Projet& proj): Tache(t, d, e, proj), nb(0), max(10) { soustaches = new Tache*[10]; } Tache** getSousTache()const { return soustaches; } ~TacheComposite(){} }; #endif // TACHE_H
true
0f8ff73312cd76eaf6acf2404a2fddb87c948b5b
C++
Martinii89/GameEngine
/SimpleGameEngine_opengl/Mesh.h
UTF-8
384
2.671875
3
[]
no_license
#pragma once #include "vertex.h" #include <vector> class Mesh { private: void CalcNormals(Vertex* vertices, int vertSize, int* indices, int indexSize); public: Mesh(); virtual ~Mesh(); void addVertices(Vertex* vertices, int vertSize, int* indexes, int indexSize, bool calcNormals = true ); void draw() const; private: unsigned int m_vbo; unsigned int m_ibo; int m_size; };
true
27d1749fac3654f37f1c75d1d18dadcd2cabc2aa
C++
dmireckid/CS225
/mp7/dsets.cpp
UTF-8
554
2.890625
3
[]
no_license
/* Your code here! */ #include <vector> #include "dsets.h" void DisjointSets::addelements(int num){ for(int i=0; i<num; i++){ vec.push_back(-1); } } int DisjointSets::find(int elem){ if(vec[elem] <0){ return elem; } else{ return vec[elem] = find(vec[elem]); } } void DisjointSets::setunion(int a, int b){ int x = find(a); int y = find(b); int union1 = size(x)+size(y); if(x>y){ vec[x]=y; vec[y]=union1; } else{ vec[y]=x; vec[x]=union1; } } int DisjointSets::size(int elem){ return vec[elem]; }
true
bf86135c190aa770996714ae66b59a97517a91fc
C++
Maligothez/OpenGL-in-Virtual-Studio
/Graphics week 5/Workshop5_BobcatRampage!/Excavator.cpp
UTF-8
4,267
3.03125
3
[]
no_license
#include "Excavator.h" #include <windows.h> #include <math.h> Excavator::Excavator() : Entity() { } Excavator::Excavator(float locationX,float locationZ, float movementSpeed, float altitudeY,float angleToZAxis, float turretAngle, float upperArmAngle, float lowerArmAngle) : Entity(locationX,locationZ,altitudeY,angleToZAxis) { this->movementSpeed = movementSpeed; this->turretAngle = turretAngle; this->upperArmAngle = upperArmAngle; this->lowerArmAngle = lowerArmAngle; friction = 0.95f; turningSpeed = movementSpeed; currentTurningSpeed = 0; currentSpeedX = 0; currentSpeedZ = 0; } Excavator::~Excavator() { } const float Excavator::getTurretAngle() { return turretAngle; } const float Excavator::getUpperArmAngle() { return upperArmAngle; } const float Excavator::getLowerArmAngle() { return lowerArmAngle; } bool Excavator::checkCollisions(vector<Geometry> &things) { return true; } bool Excavator::processKeyboardInput() { bool gameWon = 0; // left and right turn the Excavator if (GetAsyncKeyState(VK_LEFT) < 0) { currentTurningSpeed += 2*turningSpeed; } else { if (GetAsyncKeyState(VK_RIGHT) < 0) { currentTurningSpeed -= 2*turningSpeed; } } angleToZAxisInDegrees += currentTurningSpeed; currentTurningSpeed *= friction; if (angleToZAxisInDegrees>=360) { angleToZAxisInDegrees -=360; } if (angleToZAxisInDegrees<=0) { angleToZAxisInDegrees += 360; } // up and down are for moving backwards/forwards Vector3f oldPosition = Vector3f(locationX, altitudeY, locationZ); bool moved = FALSE; if (GetAsyncKeyState(VK_UP) < 0) { //locationX -= movementSpeed*(float)sin(pi*(angleToZAxisInDegrees/180.0)); //locationZ -= movementSpeed*(float)cos(pi*(angleToZAxisInDegrees/180.0)); currentSpeedX -= movementSpeed*(float)sin(pi*(angleToZAxisInDegrees/180.0)); currentSpeedZ -= movementSpeed*(float)cos(pi*(angleToZAxisInDegrees/180.0)); moved = TRUE; } else { if (GetAsyncKeyState(VK_DOWN) < 0) { //locationX += movementSpeed*(float)sin(pi*(float(angleToZAxisInDegrees)/180.0)); //locationZ += movementSpeed*(float)cos(pi*(float(angleToZAxisInDegrees)/180.0)); currentSpeedX += movementSpeed*(float)sin(pi*(float(angleToZAxisInDegrees)/180.0)); currentSpeedZ += movementSpeed*(float)cos(pi*(float(angleToZAxisInDegrees)/180.0)); moved = TRUE; } } locationX += currentSpeedX; locationZ += currentSpeedZ; currentSpeedX *= friction; currentSpeedZ *= friction; if (moved) { Vector3f nextPosition = Vector3f(locationX, altitudeY, locationZ); // check for collisiosn with the static objects //for (vector<staticGameObject>::iterator object = objects.begin(); object!=objects.end(); ++object) //{ // if (object->isColiding(nextPosition)) // { // // if its the exams - pick them up // if (object->type()==EXAMS) // { // // erase the exams object from the stl vector // // and update the iterator (will set it to the next object) // object = objects.erase(object); // // we dont want the next object yet (the loop does the incrementing) // // so decrement the iterator // object--; // gameWon = 1; // set game won to true // } // else // { // // reset to previous position // locationX = oldPosition.x(); // altitudeY = oldPosition.y(); // locationZ = oldPosition.z(); // } // } //} return gameWon; } // rotate the Excavator turret arround the base if (GetAsyncKeyState('Q') < 0) { --turretAngle; if (turretAngle<=0) { turretAngle = 360; } } else { if (GetAsyncKeyState('A') < 0) { ++turretAngle; if (turretAngle>=360) { turretAngle = 0; } } } // move upper arm, limit movement between if (GetAsyncKeyState('W') < 0) { --upperArmAngle; if (upperArmAngle<0) { upperArmAngle = 360; } } else { if (GetAsyncKeyState('S') < 0) { ++upperArmAngle; if (upperArmAngle>360) { upperArmAngle = 0; } } } // move lower arm if (GetAsyncKeyState('E') < 0) { --lowerArmAngle; if (lowerArmAngle<0) { lowerArmAngle = 0; } } else { if (GetAsyncKeyState('D') < 0) { ++lowerArmAngle; if (lowerArmAngle>360) { lowerArmAngle = 360; } } } return gameWon; }
true
63b9b6909b8e74b6547221089a7b03cad2342197
C++
gstoykow/fmi-se-oop-group3
/ExF(FinalConsult)_27.06.2019/CentralBank.cpp
UTF-8
2,101
2.78125
3
[]
no_license
#include "CentralBank.h" const vector<string> CentralBank::getCurrs() const { return this->currs; } const vector<double> CentralBank::getRates() const { return this->rates; } void CentralBank::setCurrs(vector<string> currs) { this->currs = currs; } void CentralBank::setRates(vector<double> rates) { this->rates = rates; } void CentralBank::copyObservers(const CentralBank &cb) { if (this != &cb) { for (int i = 0; i < cb.observers.size(); i++) { this->observers.push_back(cb.observers[i]->clone()); } } } void CentralBank::deleteObservers() { for (int i = 0; i < observers.size(); i++) { delete observers[i]; } observers.clear(); } void CentralBank::addCurrency(const string name) { currs.push_back(name); rates.push_back(0); notify(name, 0); } void CentralBank::deleteCurrency(const string name) { for (int i = 0; i < currs.size(); i++) { if (currs[i] == name) { currs.erase(currs.begin() + i); rates.erase(rates.begin() + i); } } } void CentralBank::setRate(const string name, double rate) { for (int i = 0; i < currs.size(); i++) { if (currs[i] == name) { rates[i] = rate; notify(name, rate); } } } void CentralBank::Register(Observer* o) { observers.push_back(o); } void CentralBank::Unregister(const unsigned int index) { if (index >= observers.size()) return; else { delete observers[index]; observers.erase(observers.begin() + index); } } void CentralBank::notify(const string currency, double rate) const { for (int i = 0; i < observers.size(); i++) { observers[i]->update(currency,rate); } } CentralBank::CentralBank() { } CentralBank::CentralBank(const CentralBank &cb) { setCurrs(cb.getCurrs()); setRates(cb.getRates()); copyObservers(cb); } CentralBank & CentralBank::operator=(const CentralBank &cb) { deleteObservers(); setCurrs(cb.getCurrs()); setRates(cb.getRates()); copyObservers(cb); return *this; } CentralBank::~CentralBank() { deleteObservers(); }
true
0becb8551ba9f8d9ed055c5d796c27ffe24f7e6e
C++
tonykozlovsky/bsu
/programming/c++/lab5/task2.cpp
UTF-8
1,229
3.234375
3
[]
permissive
// // Created by Drapegnik on 15.10.14. // #include <iostream> using namespace std; struct lifo { char data; lifo *next; }; bool lifo_empty(lifo*& top) { if (top==NULL) return true; else return false; } char show_top(lifo *&top) { return (top->data); } void push(lifo *&top,char v) { lifo *q=new lifo; q->data=v; q->next=top; top=q; } void pop(lifo *&top) { lifo *temp=top; top=top->next; delete temp; } int main() { string s; getline(cin,s); lifo *q=NULL; for (int i=0;i<int(s.length());i++) { if (s[i]=='x') push(q,'x'); if (s[i]=='n') push(q,'n'); if (s[i]>=48 && s[i]<=57) push(q,s[i]); if (s[i]==')') { int a,b; char op; a=show_top(q)-'0'; pop(q); b=show_top(q)-'0'; pop(q); op=show_top(q); pop(q); if (op=='x') push(q,char(max(a,b)+48)); else push(q,char(min(a,b)+48)); } } cout<<show_top(q); return 0; }
true
b48f6c2f2bb83fe829dc88c64d62e1d7ed8be454
C++
paumayr/cppexamples
/CppWorkshop/CppWorkshopSamples/Demo_Functions/main.cpp
UTF-8
365
3.6875
4
[]
no_license
#include <iostream> int Circumference(int w, int h); // function declaration int main(int argc, char **argv) { int w = 10; int h = 20; int circumFerence = Circumference(w, h); std::cout << "circumference = " << circumFerence << std::endl; return 0; } int Circumference(int w, int h) // function definition { return 2 * (w + h); }
true
21482ec50198a95cd62a5d3c55332ca491b3ca29
C++
Bookfan97/Cpp_GameProgramming
/Thomas Was Late/Thomas_Was_Late/ParticleSystem.cpp
UTF-8
1,281
3.109375
3
[]
no_license
#include "ParticleSystem.h" void ParticleSystem::draw(RenderTarget& target, RenderStates states) const { target.draw(m_Vertices, states); } void ParticleSystem::init(int numParticles) { m_Vertices.setPrimitiveType(Points); m_Vertices.resize(numParticles); for (int i = 0; i < numParticles; i++) { srand(time(0) + i); float angle = (rand() % 360) * 3.14f / 180.f; float speed = (rand() % 600) + 600.f; Vector2f direction; direction = Vector2f(cos(angle) * speed, sin(angle) * speed); m_Particles.push_back(Particle(direction)); } } void ParticleSystem::emitParticles(Vector2f startPosition) { m_IsRunning = true; m_Duration = 2; vector<Particle>::iterator i; int currentVertex = 0; for (i = m_Particles.begin(); i != m_Particles.end(); i++) { m_Vertices[currentVertex].color = Color::Yellow; (*i).setPosition(startPosition); currentVertex++; } } void ParticleSystem::update(float elapsed) { m_Duration -= elapsed; vector<Particle>::iterator i; int currentVertex = 0; for (i = m_Particles.begin(); i != m_Particles.end(); i++) { (*i).update(elapsed); m_Vertices[currentVertex].position = (*i).getPosition(); currentVertex++; } if (m_Duration < 0) { m_IsRunning = false; } } bool ParticleSystem::running() { return m_IsRunning; }
true
74d90ad9eb4051c07d50710a0458835b428b2751
C++
mrfikri-ai/Phase_Gradient
/Arduino/test_follower_alwayslookingtest.ino
UTF-8
4,062
2.671875
3
[ "MIT" ]
permissive
#include<math.h> //This code is running in 8pino microcontroller // Global Constant // const int SENSOR = 0; const int PWM_pin = 1; //pin 1 in 8pino is PWM pin const int S1 = 3; // sensing number 1 pin const int S2 = 4; // sensing number 2 pin const int time_L = 30; // LED blinking time const int time_pass = 10000; // Sensor ignoring time const float dt=0.001; // time resolution const float omega0 = 10.0; // Natural angular frequency const float kappa = omega0/(2*M_PI); // interaction constant //const float kappa = 2.1; // Global Variable // int val_old = 0; // Prevent chattering int Status_light = 0; // LD lit condition int Status_phipast = 1; // positive or negative int timer_LED = 0; // time counter for led int timer_pass = 0; // Sensor ignorance time int N_S = 0; // Number of sensor ties\\s int N_Sold = N_S; // number of time storage int N_i = 0; // number of adjuscene robot float phi=0.0; // phase float omega=omega0; // Angular frequency float dphi[4]={0.0,0.0,0.0,0.0}; // Phase difference storage // Total element in the array float SUM_phase(float dp[4]){ int N_dp,i; float r; r=0.0; // N_dp = sizeof dp/ sizeof dp[0]; N_dp = 4; for(i=0;i<N_dp;i++){ r = r + dp[i]; } return r; } // Sensor falling response void Pin_stand(){ int val; float sum_phi = 0.0; val = digitalRead(SENSOR); if(timer_pass>0){ // invalidation timer_pass++; if(timer_pass>time_pass){ timer_pass=0; } }else{ if(val==LOW){ if(val_old==HIGH){ N_S++; if(N_S<3){ dphi[N_S-1] = -phi; sum_phi = SUM_phase(dphi); if(N_S>N_i){ N_i = N_S; } omega = omega0 + kappa*sum_phi/(N_i); } // timer_pass=1; timer_pass=0; // } } } val_old = val; } //Phase update void Phase_update(){ phi += omega*dt; phi = Phase_reset(phi); Phase_LED(phi); } //Reset phase float Phase_reset(float p){ float p_out=p; if(p_out>M_PI){ p_out = p_out - 2*M_PI; Status_phipast = 0; if(N_S==N_Sold){ N_i = N_S; if(N_i<2){ dphi[1]=0.0; if(N_i<1){ dphi[0]=0.0; } omega = omega0 + kappa*dphi[0]; } } Show_sensing(); N_Sold = N_S; N_S=0; } return p_out; } // LED lit by phase void Phase_LED(float p){ if(!Status_phipast){ if(p>0){ Status_phipast = 1; // digitalWrite(LED, HIGH); OCR0B = 2; // Duty ratio change Status_light = 1; } } if(Status_light){ timer_LED++; if(timer_LED>time_L){ // digitalWrite(LED, LOW); OCR0B = 4; // Duty ratio change Status_light = 0; timer_LED = 0; } } } // Function for sensor of rise count void Show_sensing(){ if(N_S<4){ digitalWrite(S1, N_S%2); digitalWrite(S2, (N_S/2)%2); }else{ digitalWrite(S1,LOW); digitalWrite(S2,LOW); } } // Setup void setup() { pinMode(PWM_pin, OUTPUT); pinMode(SENSOR, INPUT); pinMode(S1, OUTPUT); pinMode(S2, OUTPUT); // timer interrupt setting // this refers to trinkettimer.pdf cli(); // TCCR1 |= (0<<CS13) | (1<<CS12) | (0<<CS11) | (0<<CS10);// 1[MHz]→period 1[μs] TCCR0A=0xF3; // Mode setting TCCR0B=0x0A; // Mode setting 1MHz OCR0A = 4; //OCR0A+1 correspond to cycle OCR0B = 4; //Duty ratio(OCR0B+1)/(OCR0A+1) // TIMSK = (1 << OCIE0A); // this allows you to enter function TCCR1=0x97; // this is mode setting 125[kHz] OCR1C = 124; // Execute ISR every 1 ms TIMSK = (1 << OCIE1A); // enter to the function sei(); } // Loop void loop() { } ISR(TIM1_COMPA_vect) { Pin_stand(); Phase_update(); }
true
a040ced3c915a145442071f47e35b52c63e0c184
C++
hash-zhu/data_structure
/data_structure/PAT/Sort.cpp
UTF-8
1,158
3.765625
4
[]
no_license
// // Created by 少年与梦 on 2021-07-07. // #include "stdio.h" //选择排序 //每趟选出待排序部分[i,n]中最小的元素,将其与arr[i]交换,总复杂度为O(n^2) void selectSort(int arr[],int n) { for (int i = 0; i < n-1; ++i) {//进行n趟操作 int k = i; for (int j = i+1; j < n; ++j) {//选出[i,n]中最小的元素,下标为k if (arr[j] < arr[k]) { k = j; } } int temp = arr[i];//交换arr[i]与arr[k] arr[i] = arr[k]; arr[k] = temp; } } //直接插入排序 void insertSort(int A[],int n){// n为元素的个数,数组下标从0~n-1 for (int i = 1; i < n; ++i) {//进行n-1趟排序 int temp=A[i],j=i;// temp临时存放A[i],j从i开始往前枚举 while (j>0&&temp<A[j-1]){//只要temp小于前一个元素 A[j]=A[j-1];//把A[j-1]后移至A[j] j--; } A[j]=temp;//插入位置为j } } int main() { int arr[] ={5,2,4,6,3,1}; // selectSort(arr,6); insertSort(arr,6); for (int i = 0; i < 6; ++i) { printf("%d ",arr[i]); } return 0; };
true
533528f472d1c311d2b8f7955a6bb9e490233a83
C++
silenke/my-leetcode
/problems/56. 合并区间/1.cc
UTF-8
485
2.671875
3
[]
no_license
#include "..\..\leetcode.h" class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { sort(intervals.begin(), intervals.end()); vector<vector<int>> res; for (const auto& i : intervals) { if (res.empty() || i[0] > res.back()[1]) { res.emplace_back(move(i)); } else { res.back()[1] = max(res.back()[1], i[1]); } } return res; } };
true
22b976b5ec164ba4e47d54d53288553a0687ecd2
C++
JECHUser/Electronica-Digital-2
/Mini_Proyecto_2/ESP32 - Arduino code/pubsub_adafruitio/pubsub_adafruitio.ino
UTF-8
3,437
2.59375
3
[]
no_license
// Adafruit IO Publish & Subscribe Example // // Adafruit invests time and resources providing this open source code. // Please support Adafruit and open source hardware by purchasing // products from Adafruit! // // Written by Todd Treece for Adafruit Industries // Copyright (c) 2016 Adafruit Industries // Licensed under the MIT license. // // All text above must be included in any redistribution. /************************** Configuration ***********************************/ #include "config.h" /************************ Example Starts Here *******************************/ // definición de algunas valores #define RXD2 16 #define TXD2 17 #define IO_LOOP_DELAY 5000 // definción de variables unsigned long lastUpdate = 0; int count = 0; char Read_pic; char Write_pic; char state_p1; char state_p2; // configurar el feed 'P1' AdafruitIO_Feed *P1 = io.feed("P1"); // configurar el feed 'P2' AdafruitIO_Feed *P2 = io.feed("P2"); // configurar el feed 'SENSOR' AdafruitIO_Feed *SENSOR = io.feed("SENSOR"); void setup() { // Inicar la comunicación serial Serial.begin(115200); Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2); // Serial2 utilizado para comunicación I2C // Espra que la terminal se abra while(! Serial); Serial.print("Connecting to Adafruit IO"); // Conexión con io.adafruit.com io.connect(); // Recepción de los mensaje de adafruit io P1->onMessage(handleP1); P2->onMessage(handleP2); SENSOR->onMessage(handleSensor); // Espera la conexión con adafruit io while(io.status() < AIO_CONNECTED) { Serial.println(io.statusText()); delay(500); } // Indicadores de la conexión con adafruit io Serial.println(); Serial.println(io.statusText()); // obtener/enviar datos desde adafruit P1->get(); P2->get(); SENSOR->get(); } void loop() { io.run(); // mantener conexión con io.adafruit.com while (Serial2.available()){ Read_pic = Serial2.read(); // lee el dato enviado por comunicación UART al Serial2 Write_pic = state_p1 + state_p2; // operación del estado de las luces piloto Serial2.write(Write_pic); // escribe el estado de las luces piloto y las envía por comunicación I2C } if (millis() > (lastUpdate + IO_LOOP_DELAY)) { // Guarda el valor leído en el feed 'SENSOR' de adafruit IO SENSOR->save(Read_pic); // Después de almacenar el valor, guarda el tiempo actual lastUpdate = millis(); } } // Funciones llamadas cuando un mensaje enviado por Adafruit IO es recibido void handleSensor(AdafruitIO_Data *data) { // onMessage del feed 'SENSOR' Serial.print("received <- "); Serial.println(data->value()); } void handleP1(AdafruitIO_Data *data) { // onMessage del feed 'P1' Serial.print("received <- "); if(data->isTrue()){ state_p1 = 1; // si el botón se presiona, entonces state_p1 = 0b00000001 Serial.println("P1 - HIGH"); } else{ state_p1 = 0; // si el botón se presiona, entonces state_p1 = 0b00000000 Serial.println("P1 - LOW"); } } void handleP2(AdafruitIO_Data *data) { // onMessage del feed 'P2' Serial.print("received <- "); if(data->isTrue()){ state_p2 = 2; // si el botón se presiona, entonces state_p2 = 0b00000010 Serial.println("P2 - HIGH"); } else{ state_p2 = 0; // si el botón se presiona, entonces state_p2 = 0b00000000 Serial.println("P2 - LOW"); } }
true
2d18bacbecd4d33a05e12fea8def7d01cadc7832
C++
imaycen/Sumatorias
/main.cpp
UTF-8
1,626
3.34375
3
[]
no_license
// Author : Ivan de Jesus May-Cen // Email : imaycen@hotmail.com, imay@itsprogreso.edu.mx // Language : C++ // Environment : Linux // Compiler : g++ // Revisions : // Initial : 09.02.2017 // Last : // Este programa compila en la consola de linux mediante la orde // g++ main.cpp -o sumatoria // "sumatoria" es el nombre del ejecutable //Inclusion de librerias #include <iostream> //Declaracion de funciones double suma_sucesion(int i0, int iN, int opcion); double sucesion(int i, int opcion); using namespace std; //Funcion principal int main( ) { double sumatoria; int i0 = 3, iN = 7, opcion = 3; //Llama a funcion que determina la suma sumatoria = suma_sucesion(i0, iN, opcion); //Imprime resultados cout << "La sumatoria es: " << sumatoria << endl; return 0; } //******************************************************** // Funcion para efectuar sumatoria // // Input : limites inferior y superior i0, iN, opcion de sucesion // Output : resultado de la sumatoria en suma //******************************************************** double suma_sucesion(int i0, int iN, int opcion) { double suma = 0.0; int i; for( i = i0; i <= iN; i++ ) suma+= sucesion(i, opcion); return suma; } //******************************************************** // Se definen opciones para sucesion // // Input : indice i, opcion de sucesion // Output : evaluacion de la sucesion en el indice i //******************************************************** double sucesion(int i, int opcion) { double valor; if(opcion == 1) valor = i; else if(opcion == 2) valor =i+2; else if(opcion == 3) valor =i*i; return valor; }
true
27028910b07294bb8f1b0ecaa19c652ff9caa983
C++
yichuanma95/leetcode-solns
/cpp/reverseInt.cpp
UTF-8
965
3.984375
4
[]
no_license
/* Problem 7: Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. */ class Solution { public: int reverse(int x) { bool isNegative = x < 0; long reversedNum = reverseNum(abs(x)); if (reversedNum > INT_MAX || reversedNum < INT_MIN) return 0; return isNegative ? (int)(-reversedNum) : (int)reversedNum; } private: long reverseNum(int x) { long reversed = 0; while (x > 0) { reversed += (x % 10); x /= 10; reversed *= 10; } return reversed / 10; } };
true
4f26538bdc7a9cb119b3dee24d0d629df8fe454a
C++
MuggleWei/data_structure_and_algorithm
/test/avl_tree_iter/unittest_avl_tree_iter.cpp
UTF-8
1,908
2.78125
3
[ "MIT" ]
permissive
#include "gtest/gtest.h" #include "dsaa/dsaa.h" #include "test_utils/test_utils.h" #define TEST_AVL_TREE_ITER_LEN 64 class AvlTreeIterFixture : public ::testing::Test { public: void SetUp() { muggle_debug_memory_leak_start(&mem_state_); bool ret; ret = avl_tree_init(&tree_, test_utils_cmp_int, 0); ASSERT_TRUE(ret); } void TearDown() { avl_tree_destroy(&tree_, NULL, NULL, NULL, NULL); muggle_debug_memory_leak_end(&mem_state_); } protected: struct avl_tree tree_; muggle_debug_memory_state mem_state_; }; TEST_F(AvlTreeIterFixture, case1) { int arr[TEST_AVL_TREE_ITER_LEN]; for (int i = 0; i < TEST_AVL_TREE_ITER_LEN; i++) { arr[i] = i; } for (int i = 0; i < TEST_AVL_TREE_ITER_LEN; i++) { avl_tree_insert(&tree_, &arr[i], &arr[i]); } int pos = 0; struct avl_tree_node *node = nullptr; for (node = avl_tree_iter_begin(&tree_); node; node = avl_tree_iter_next(node)) { ASSERT_LT(pos, TEST_AVL_TREE_ITER_LEN); ASSERT_EQ(arr[pos], *(int*)node->value); pos++; } ASSERT_EQ(pos, TEST_AVL_TREE_ITER_LEN); ASSERT_TRUE(node == NULL); } TEST_F(AvlTreeIterFixture, case2) { int arr[TEST_AVL_TREE_ITER_LEN], arr_shuffle[TEST_AVL_TREE_ITER_LEN]; for (int i = 0; i < TEST_AVL_TREE_ITER_LEN; i++) { arr[i] = i; arr_shuffle[i] = arr[i]; } for (int i = 0; i < TEST_AVL_TREE_ITER_LEN; i++) { int idx = rand() % TEST_AVL_TREE_ITER_LEN; int tmp = arr_shuffle[i]; arr_shuffle[i] = arr_shuffle[idx]; arr_shuffle[idx] = tmp; } for (int i = 0; i < TEST_AVL_TREE_ITER_LEN; i++) { avl_tree_insert(&tree_, &arr_shuffle[i], &arr_shuffle[i]); } int pos = 0; struct avl_tree_node *node = nullptr; for (node = avl_tree_iter_begin(&tree_); node; node = avl_tree_iter_next(node)) { ASSERT_LT(pos, TEST_AVL_TREE_ITER_LEN); ASSERT_EQ(arr[pos], *(int*)node->value); pos++; } ASSERT_EQ(pos, TEST_AVL_TREE_ITER_LEN); ASSERT_TRUE(node == NULL); }
true
92f275268388931fdc7d73a7086bd96a7eee0d8d
C++
thufish/Mingliang.Liu-algorithm
/cc150/1.3.cpp
UTF-8
1,749
3.734375
4
[]
no_license
#include <string> #include <vector> #include <iostream> using namespace std; /** The naive sort and compare one. O(NlgN) */ bool is_permutation1(string &str1, string &str2) { /** trivial cases first */ if (str1.length() != str2.length()) return false; sort(str1.begin(), str1.end()); sort(str2.begin(), str2.end()); return str1 == str2; } /** Count the number of every char and compare the counts */ bool is_permutation2(const string &str1, const string &str2) { if (str1.length() != str2.length()) return false; vector<size_t> count1(128, 0); for (char c : str1) count1[c]++; vector<size_t> count2(128, 0); for (char c : str2) count2[c]++; return count1 == count2; } /** A smarter one which saves one counter vector and returns in time */ bool is_permutation3(const string &str1, const string &str2) { /** this line is important in this solution */ if (str1.length() != str2.length()) return false; vector<size_t> count(128, 0); for (char c : str1) ++count[c]; for (char c : str2) if (count[c]-- == 0) return false; return true; } int main() { string s1 = "abcdefghijklmn"; string s2 = "def"; string s3 = "nmlkjihgfedcba"; string s4 = "abcdefghijkmln"; string s5 = "abcdefghijklmn"; cout << is_permutation1(s2, s1) << is_permutation1(s3, s1) << is_permutation1(s4, s1) << is_permutation1(s5, s1) << endl; cout << is_permutation2(s2, s1) << is_permutation2(s3, s1) << is_permutation2(s4, s1) << is_permutation2(s5, s1) << endl; cout << is_permutation3(s2, s1) << is_permutation3(s3, s1) << is_permutation3(s4, s1) << is_permutation3(s5, s1) << endl; return 0; }
true
c09b990671dc51a8fd8161f4a243834f8a8426e9
C++
utec-computer-science/cs2100-list-Oteranga
/Doubly_List.h
UTF-8
8,716
3.578125
4
[]
no_license
// // Created by Alejandro Otero on 2020-04-24. // #pragma once #include "Node.h" namespace Dlist { template<typename T> class Iterator { protected: typedef DoublyListNode<T> node_t; node_t *pointer; public: Iterator() : pointer(nullptr) {} Iterator(node_t *_pointer) : pointer(_pointer) {} ~Iterator(void) {} bool operator!=(Iterator<T> it) { return this->pointer != it.pointer; } T &operator*(void) { return this->pointer->value; } void operator++(void) { this->pointer = this->pointer->next; } void operator--(void){ this->pointer=this->pointer->prev; } bool operator==(const Iterator<T> &it) { return this->pointer == it.pointer; } bool operator<=(const Iterator<T> &it) { return this->pointer <= it.pointer; } bool operator>=(const Iterator<T> &it) { return this->pointer >= it.pointer; } bool operator<(const Iterator<T> &it) { return this->pointer < it.pointer; } bool operator>(const Iterator<T> &it) { return this->pointer > it.pointer; } }; template<typename T> class Dlist { protected: //typedef Node<T> node; typedef DoublyListNode<T> Dnode; Dnode *head; Dnode *tail; public: Dlist(Dlist &ptr) { head = ptr.head; tail = ptr.tail; } Dlist(T *arr, size_t size) { for (int i = 0; i < size; i++) { push_front(arr[i]); } } Dlist(Dnode *temp) { head = tail = temp; } Dlist(int n) { for (int i = 0; i < n; i++) { push_front(rand() % 100 + 1); } } Dlist(void) : head(nullptr), tail(nullptr) {} ~Dlist(void) {} T &front(void) { return head->value; } T &back(void) { return tail->value; } void push_back(const T &element) { Dnode *current= new Dnode{element}; if(head== nullptr){ head=tail=current; }else { tail->next = current; current->prev = tail; tail = current; } } void push_front(const T &element){ Dnode *current= new Dnode{element}; if(head== nullptr){ head=tail=current; }else{ current->next=head; head->prev=current; head=current; } } void pop_back(void){ if(tail== nullptr) return; else { Dnode *temp = tail; tail->prev->next = nullptr; tail = tail->prev; delete temp; } } void pop_front(void){ if(head== nullptr) return; else { Dnode *temp = head; head = head->next; head->prev = nullptr; delete temp; } } T &operator[](const int & element){ Dnode* current=head; for(int i=0; i<element; i++){ current=current->next; } return current->value; } bool empty(void){ return head== nullptr; } unsigned int size(void){ int cont=0; if(empty()) return cont; else{ Dnode* current=head; while(current!= nullptr){ current=current->next; cont++; } return cont; } } // Elimina toda la lista void clear(void){ while (head!= nullptr){ pop_back(); } } void erase(Dnode * ptr){ if(head==ptr) pop_front(); else if(tail==ptr) pop_back(); else{ Dnode* current=head; Dnode* temp=current; while(current!= nullptr){ current=current->next; if(current==ptr){ current=current->next; temp->next=current; current->prev=temp; delete current; }else current=current->next; temp=current; } } } void insert(Dnode *ptr, const T & element){ if(head==ptr) push_front(element); else if(tail==ptr) push_back(element); else{ Dnode* current=head; Dnode* prev_node=current; Dnode* new_node=new Dnode{element}; while(current!= nullptr){ current=current->next; if(current==ptr){ prev_node->next=new_node; new_node->next=current; new_node->prev=prev_node; current->prev=new_node; } prev_node=current; } } } void remove(const T & element){ Dnode* temp=head; while(temp!= nullptr){ if(temp->value==element){ if(temp==head) pop_front(); else if(temp== tail) pop_back(); else{ Dnode* current=temp; current->prev->next=current->next; current->next->prev=current->prev; delete current; } } temp=temp->next; } } void sort(void){ Dnode* current=head; Dnode* temp; while (current!= nullptr){ temp=current->next; while(temp!= nullptr){ if(current->value>temp->value){ int num = temp->value; temp->value=current->value; current->value=num; } temp=temp->next; } current=current->next; } } void reverse(void){ if(head!= nullptr){ Dnode* current=head; Dnode* next_node; while(current!= nullptr) { next_node = current->next; current->next = current->prev; current->prev = next_node; current=next_node; } current=head; head=tail; tail=current; } } //iterators Iterator<T> begin() { return Iterator(head); } Iterator<T> end() { return Iterator(tail->next); } template<typename __T> inline friend ostream &operator<<(std::ostream &out, const Dlist<__T> &ptr) { Dnode *temp = ptr.head; while (temp != nullptr) { out << temp->value << " "; temp = temp->next; } return out; } Dlist &operator<<(const T &_value) { this->push_back(_value); return *this; } Dlist &operator>>(const T &_value) { this->push_front(_value); return *this; } }; /* template <typename Node, typename ValueNode, int nodeType> class ListHelper{ public: static void add(Node** head, Node** tail, ValueNode element){ cout << "Hola no tengo trait definido" << endl; } static void remove(Node** head, Node** tail, ValueNode element){ cout << "Hola no tengo trait definido" << endl; } static void print(Node** head, Node** tail, ValueNode element){ cout << "Hola no tengo trait definido" << endl; } }; template <typename Node, typename ValueNode> class ListHelper<Node,ValueNode,DOUBLE_NODE>{ public: static void add(Node** head, Node** tail, ValueNode element){ cout << "Hola soy el push_back para una double list." << endl; } }; */ }
true
56effa62579ff8228d4c0b816c48a4c690f56418
C++
deepakgupta1313/My-Codes
/Miscellaneous/Permutation/Permutation Mapping/Permutation Mapping.cpp
UTF-8
1,719
2.625
3
[]
no_license
#include <cstdio> #include <algorithm> #include<iostream> #include<vector> #include<climits> #include <complex> #include <iostream> #include <valarray> #include<cstring> #include<queue> using namespace std; #define PB push_back #define i64 long long #define FOR(i,a,b) for(i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define SZ(v) ((v).size()) #define VI vector<int> #define VS vector<string> #define VD vector<double> #define MSET(x,y) memset((x),(y),sizeof(x)) #define LD long double #define SZOF(x) sizeof((x)) int factorial(int num) { int i,ret=1; FOR(i,2,num+1) { ret*=i; } return ret; } void prVect(VI a) { int i; REP(i,a.size()) { printf("%d\t",a[i]); } printf("\n"); } int encode(VI a) { int len=a.size(); int i; if(len==2 || len==1) { return a[0]; } int sum=0; sum+=a[0]*factorial(len-1); VI r; FOR(i,1,len) { r.PB(a[i]); if(r[i-1]>a[0]) { --r[i-1]; } } return sum+encode(r); } VI decode(int val,int len) { VI ret; int i; if(len==1) { ret.PB(0); return ret; } ret.PB(val/(factorial(len-1))); val%=factorial(len-1); VI t=decode(val,len-1); FOR(i,0,len-1) { if(t[i]>=ret[0]) { ++t[i]; } ret.PB(t[i]); } return ret; } int main() { freopen("Permutation Mapping.txt","r",stdin); vector<int> a; int t,i,n; scanf("%d",&n); //cout<<n<<endl; REP(i,n) { scanf("%d",&t); a.PB(t); } prVect(a); printf("%d\n",encode(a)); prVect(decode(encode(a),n)); return 0; }
true
f9ac9deee17ef57bdae3e68079bc3ce05f59ac39
C++
Flare-k/Algorithm
/자료구조/괄호의값_자료구조_2504.cpp
UTF-8
1,177
3.1875
3
[]
no_license
#include <iostream> #include <string> #include <stack> using namespace std; string ch; long long answer; void run() { stack<char> st; int len = ch.length(); int num = 1; bool impossible = false; for (int i = 0; i < len; i++) { if (ch[i] == '(') { num *= 2; st.push(ch[i]); } else if (ch[i] == '[') { num *= 3; st.push(ch[i]); } else if (ch[i] == ')') { if ((st.empty() || st.top() != '(')) { impossible = true; break; } if (ch[i - 1] == '(') answer += num; num /= 2; st.pop(); } else if (ch[i] == ']') { if (st.empty() || st.top() != '[') { impossible = true; break; } if (ch[i - 1] == '[') answer += num; num /= 3; st.pop(); } } if (impossible || !st.empty()) cout << 0 << '\n'; else cout << answer << '\n'; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> ch; run(); return 0; }
true
c729aed50ba43a12419bd8c4b89e6b74a224dd5f
C++
GrenderG/mmo
/src/mmo_client/console_var.h
UTF-8
6,461
3.203125
3
[]
no_license
// Copyright (C) 2019, Robin Klimonow. All rights reserved. #pragma once #include "base/typedefs.h" #include "base/non_copyable.h" #include "base/macros.h" // For ASSERT #include "base/signal.h" #include <string> namespace mmo { /// Enumerates possible console variable flags. enum ConsoleVarFlags { /// Default value. CVF_None = 0, /// The console variable has been unregistered. We don't delete unregistered console variables as this /// bears the potential of access errors. CVF_Unregistered = 1, /// Whether the console variable has been modified since it has been registered. CVF_Modified = 2, }; /// Class that represents a console variable. This class stores the values as string values but also keeps a /// a int32 and float parse value cached for faster access so we avoid using std::atoi every time we try /// to get an int32 value for example. class ConsoleVar final : public NonCopyable { public: typedef signal<void(ConsoleVar& var, const std::string& oldValue)> ChangedSignal; /// A signal that is fired every time the value of this variable is changed. ChangedSignal Changed; public: explicit ConsoleVar(const std::string& name, const std::string& description, std::string defaultValue); public: // Make ConsoleVar movable ConsoleVar(ConsoleVar&& other) : m_intValue(0) , m_floatValue(0.0f) , m_flags(CVF_None) { swap(other); } ConsoleVar& operator=(ConsoleVar&& other) { if (this != &other) { swap(other); } } void swap(ConsoleVar& other) { m_name = std::move(other.m_name); m_description = std::move(other.m_description); m_defaultValue = std::move(other.m_defaultValue); m_stringValue = std::move(other.m_stringValue); m_intValue = other.m_intValue; m_floatValue = other.m_floatValue; m_flags = other.m_flags; } public: /// Determines whether a flag has been set. inline bool HasFlag(ConsoleVarFlags flags) const { return (m_flags & flags) != 0; } /// Sets a given flag. inline void SetFlag(ConsoleVarFlags flags) { m_flags |= flags; } /// Clears all flags. inline void ClearFlags() { m_flags = CVF_None; } /// Removes the given flag or flags. inline void RemoveFlag(ConsoleVarFlags flags) { m_flags &= ~flags; } /// Determines whether the value of this console variable has been modified. /// @remarks Note that this also returns true, if the value matches the default /// value but has been set using the Set method instead of the Reset method. inline bool HasBeenModified() const { return HasFlag(CVF_Modified); } /// Whether this console variable is valid to use. inline bool IsValid() const { return !HasFlag(CVF_Unregistered); } /// Gets the name of this console variable. inline const std::string& GetName() const { return m_name; } /// Gets a descriptive string. inline const std::string& GetDescription() const { return m_description; } /// Gets the default value of this variable. inline const std::string& GetDefaultValue() const { return m_defaultValue; } private: /// Triggers the Changed signal if the variable has not been marked as unregistered. inline void NotifyChanged(const std::string& oldValue) { if (IsValid()) { Changed(*this, oldValue); } } public: /// Sets the current value as string value. Also sets the CVF_Modified flag. void Set(std::string value) { const std::string oldValue = std::move(m_stringValue); m_stringValue = std::move(value); m_intValue = std::atoi(m_stringValue.c_str()); m_floatValue = std::atof(m_stringValue.c_str()); SetFlag(CVF_Modified); NotifyChanged(oldValue); } /// Sets the current value as int32 value. Also sets the CVF_Modified flag. void Set(int32 value) { const std::string oldValue = std::move(m_stringValue); m_stringValue = std::to_string(value); m_intValue = value; m_floatValue = static_cast<float>(value); SetFlag(CVF_Modified); NotifyChanged(oldValue); } /// Sets the current value as float value. Also sets the CVF_Modified flag. void Set(float value) { const std::string oldValue = std::move(m_stringValue); m_stringValue = std::to_string(value); m_intValue = static_cast<int32>(value); m_floatValue = value; SetFlag(CVF_Modified); NotifyChanged(oldValue); } inline void Set(bool value) { Set(value ? 1 : 0); } /// Resets the current value to use the default value. Also removes the CVF_Modified flag. void Reset() { const std::string oldValue = std::move(m_stringValue); Set(m_defaultValue); RemoveFlag(CVF_Modified); NotifyChanged(oldValue); } /// Gets the current string value. inline const std::string& GetStringValue() const { return m_stringValue; } /// Gets the current int32 value. inline int32 GetIntValue() const { return m_intValue; } /// Gets the current float value. inline float GetFloatValue() const { return m_floatValue; } /// Gets the current bool value. inline bool GetBoolValue() const { return GetIntValue() != 0; } private: /// Name of the variable. std::string m_name; /// A descriptive text used by help commands. std::string m_description; /// The default value as string. std::string m_defaultValue; /// The current value as string. std::string m_stringValue; /// A cache of the current value as int32. int32 m_intValue; /// A cache of the current value as float. float m_floatValue; /// Console variable flags uint32 m_flags; }; /// Class that manages console variables. class ConsoleVarMgr final : public NonCopyable { private: /// Make this class non-instancable ConsoleVarMgr() = delete; public: /// Initializes the console variable manager class by registering some console /// commands that can be used with console variables, like setting a variable. static void Initialize(); /// Counter-part of the Initialize method. static void Destroy(); public: /// Registers a new console variable. static ConsoleVar* RegisterConsoleVar(const std::string& name, const std::string& description, std::string defaultValue = ""); /// Unregisters a registered console variable. static bool UnregisterConsoleVar(const std::string& name); /// Finds a registered console variable if it exists. static ConsoleVar* FindConsoleVar(const std::string& name, bool allowUnregistered = false); }; }
true
b1d25567f863b84cfaefa4bad39c6aee8b7711de
C++
Abigael/Multi-Component-Music-Synthesizer
/Music Synthesizer/Synthie/NoiseGate.cpp
UTF-8
2,027
2.84375
3
[]
no_license
#include "stdafx.h" #include "NoiseGate.h" CNoiseGate::CNoiseGate() { m_left = m_right = 1; m_dry = m_wet = m_dry = 0.0; m_threshold = 50; //default value m_wet = 1; } CNoiseGate::~CNoiseGate() { } /*Noise gate lets signal pass through only when it is above set thresholf- gate is open * if below, no signal is alowed to pass or is attenuated. */ void CNoiseGate::Process(double *fOne, double *fTwo) { //if frame less then attenuate; a/r if (fOne[0] < m_threshold){ if (m_left > 0) m_left = m_left - 0.001; //attack release constant } else{ if (m_left < 1) m_left += 0.001; } if (fOne[1] < m_threshold){ if (m_right > 0) m_right = m_right - 0.001; //attack release constant } else{ if (m_right < 1) m_right += 0.001; } fTwo[0] = m_dry*fOne[0] + m_wet*fOne[0] * m_left; fTwo[1] = m_dry*fOne[1] + m_wet*fOne[1] * m_right; } //function taken from ToneInst void CNoiseGate::XmlLoad(IXMLDOMNode * xml){ // Get a list of all attribute nodes and the // length of that list CComPtr<IXMLDOMNamedNodeMap> attributes; xml->get_attributes(&attributes); long len; attributes->get_length(&len); // Loop over the list of attributes for (int i = 0; i<len; i++) { // Get attribute i CComPtr<IXMLDOMNode> attrib; attributes->get_item(i, &attrib); // Get the name of the attribute CComBSTR name; attrib->get_nodeName(&name); // Get the value of the attribute. A CComVariant is a variable // that can have any type. It loads the attribute value as a // string (UNICODE), but we can then change it to an integer // (VT_I4) or double (VT_R8) using the ChangeType function // and then read its integer or double value from a member variable. CComVariant value; attrib->get_nodeValue(&value); if (name == "threshold") { value.ChangeType(VT_I4); m_threshold = value.intVal; } else if (name == "wet") { value.ChangeType(VT_R8); m_wet = value.dblVal; } else if (name == "dry") { value.ChangeType(VT_R8); m_dry = value.dblVal; } } }
true
9ff7b5a5d0c3a82d76acb145f7fc98742c8c632b
C++
newbie960828/AILearning
/MOPAlgorithm/Algorithm/MOP_Algorithm.cpp
UTF-8
3,758
2.75
3
[]
no_license
#include "MOP_Algorithm.h" #include <QDebug> int problemNum = 1; MOP_Algorithm::MOP_Algorithm(QObject *parent) : QObject(parent) { this->InitParameter(); shouldStop = false; isBegin = false; problemNum = 1; } MOP_Algorithm::~MOP_Algorithm() { } void MOP_Algorithm::InitParameter() { numObjective = 3; lowerBound = 0.0; upperBound = 1.0; dimension = numObjective + 4; populationSize = 300; generationSize = 500; CR = 1.0; F = 0.5; H = 20; //η pm = 1.0 / dimension; } void MOP_Algorithm::setGroup(int group) { populationSize = group; } void MOP_Algorithm::setGeneration(int gen) { generationSize = gen; } void MOP_Algorithm::setObjective(int object) { numObjective = object; dimension = numObjective + 4; } void MOP_Algorithm::setDimension(int dimension) { this->dimension = dimension; pm = 1.0f / dimension; } int MOP_Algorithm::getGroup() { return populationSize; } int MOP_Algorithm::getGeneration() { return generationSize; } int MOP_Algorithm::getObjective() { return numObjective; } int MOP_Algorithm::getDimension() { return dimension; } //double gx(const vector<double> &x,int numObjective, int dimension) //{ // double result = 0.0; // for (int i = numObjective-1; i < dimension; i++) // result += pow(x[i] - 0.5, 2.0); // return result; //} ////单目标:f(index)指目标index的函数f //double fx(int index, const vector<double> &x, // int numObjective, int dimension) //{ // int M = numObjective; // double result; // result = 1 + gx(x, numObjective, dimension); // for (int i = 0; i<M - index - 1; i++) { // result *= cos(pow(x[i], PI)*PI / 2); // } // if (index>0) // result *= sin(pow(x[M - index - 1], PI)*PI / 2); // return result; //} ////多目标优化函数 min F=f1+f2+f3+…… //double Fx(const vector<double> &x, int numObjective, int dimension) //{ // double result = 0; // for (int i = 0; i<numObjective; i++) // result += fx(i, x, numObjective, dimension); // return result; //} double gx(const vector<double> &x,int numObjective, int dimension) { double result = 0.0; if(problemNum==1 || problemNum==3){ for (int i = numObjective-1; i<dimension; i++) result += pow(x[i] - 0.5, 2.0) - cos(20*PI*(x[i]-0.5)); result += dimension-numObjective+1; result /= 10; } else if(problemNum==2 || problemNum==4){ for (int i = numObjective-1; i<dimension; i++) result += pow(x[i] - 0.5, 2.0); } return result; } //单目标:f(index)指目标index的函数f double fx(int index,const vector<double> &x, int numObjective, int dimension) { int M = numObjective; double result; result = 1 + gx(x, numObjective, dimension); if(problemNum==1){ result *= 0.5; for(int i = 0;i<M - index - 1;i++) result *= x[i]; if(index>0) result *= (1-x[M-index-1]); } else if(problemNum==2||problemNum==3){ for (int i = 0; i<M - index - 1; i++) { result *= cos(x[i] * PI / 2.0); } if (index>0) result *= sin(x[M - index - 1] * PI / 2.0); } else if(problemNum==4){ for (int i = 0; i<M - index - 1; i++) { result *= cos(pow(x[i], PI)*PI / 2); } if (index>0) result *= sin(pow(x[M - index - 1], PI)*PI / 2); } return result; } //多目标优化函数 min F=f1+f2+f3+…… double Fx(const vector<double> &x, int numObjective, int dimension) { double result = 0; for (int i = 0; i<numObjective; i++) result += fx(i, x, numObjective, dimension); return result; }
true
483477aa0c3a10047a19fcacf43101a4e66af54b
C++
frenchie4111/Life
/src/Grid.cpp
UTF-8
1,943
2.734375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_gfxPrimitives.h> #include "Grid.h" using namespace std; Grid::Grid() { cout << "Grid" << endl; for( int i = 0; i < 10; i++ ) { vector< Pixel * > *temp = new vector< Pixel * >; for( int j = 0; j < 10; j++ ) { Pixel *p = new Pixel(); temp->push_back( p ); } pixels.push_back( temp ); temp = new vector< Pixel * >; } } int Grid::get_neighbors( int x, int y ) { printf( "%s", pixels[0][0]->isBlank()?"Not":"Is" ); int count = 0; // Whether or not it is in the bounds bool xlb = !( x < 0 ); bool xub = !( x >= pixels.size() ); bool ylb = !( y < 0 ); bool yub = !( y >= pixels[0].size() ); printf( "1\n" ); printf( "%s", pixels[0][0]->isBlank()?"Not":"Is" ); if( xlb && ylb && pixels[x-1][y-1]->isBlank() ) { count ++; } printf( "2\n" ); if( xlb && pixels[x-1][y]->isBlank() ) { count ++; } printf( "3\n" ); if( xlb && yub && pixels[x-1][y+1]->isBlank() ) { count ++; } printf( "4\n" ); if( ylb && pixels[x][y-1]->isBlank() ) { count ++; } printf( "5\n" ); if( yub && pixels[x][y+1]->isBlank() ) { count ++; } printf( "6\n" ); if( xub && ylb && pixels[x+1][y-1]->isBlank() ) { count ++; } printf( "7\n" ); if( xub && pixels[x+1][y]->isBlank() ) { count ++; } printf( "8\n" ); if( xub && yub && pixels[x+1][y+1]->isBlank() ) { count ++; } return count; } void Grid::update() { // int neighbors[pixels.size()][pixels[0].size()]; for( int i = 0; i < pixels.size(); i++ ) { for( int j = 0; j < pixels[0].size(); j++ ) { // neighbors[i][j] = get_neighbors( i, j ); get_neighbors( i, j ) ; } } } void Grid::draw( SDL_Surface *screen ) { for( int i = 0; i < pixels.size(); i++ ) { for( int j = 0; j < pixels[0].size(); j++ ) { boxRGBA( screen, i*15, j*15, i*15+10, j*15+10, pixels[i][j]->getR(), pixels[i][j]->getG(), pixels[i][j]->getB(), 255 ); } } }
true
37ce65a815bd7be0b691fdff8bce35ca96c922b3
C++
Assimilater/CS1400
/Assignment4/Assignment4/Package.cpp
UTF-8
551
2.703125
3
[]
no_license
#include "Package.h" using namespace std; //---------------------------------------------------------------------------------+ // Constructors | // Manage the inital values | //---------------------------------------------------------------------------------+ Package::Package() { weight = 0; cost_ounce = 0; } Package::Package(Person s, Person r, int w, double c) { Sender = s; Receiver = r; weight = w; cost_ounce = c; }
true
e1fa6eb89f2c69ae1f8229a1f511f15f036d5129
C++
aayushakrrana/Competitive-programming
/CodeChef/Root & Square_ROOTSQR.cpp
UTF-8
1,523
3.78125
4
[]
no_license
/* Root & Square Problem Code: ROOTSQR Add problem to Todo list Raju has created a program to find the square root of a number. But his program can store only integers. Being a newbie, he didn't know about rounding the numbers. Hence his program returns the absolute value of the result if possible. For example, sqrt(3) = 1.73205080757……. His program will return 1 Given a number N, and it's integral square root S, His instructor will consider the answer correct if Difference between N and the square of S is within less than or equal to X% of N. Input: First line contains T no. of test cases and X separated by space For every test case, a line contains an integer N Output: For every test case, print yes if his programs return square root and (N-(S^2)) <= 0.01XN . For everything else, print no on a new line Constraints 10 points: 1≤T≤10 0≤N≤10 20 points: 1≤T≤30000 −109≤N≤109 70 points: 1≤T≤106 −109≤N≤109 Sample Input: 2 20 5 3 Sample Output: yes no EXPLANATION: In #1, sqrt(5) = 2.2360679775. Taking integral value, S = 2. S2 = 4. Difference=1 which is within 20% of 5 In #1, sqrt(3) = 1.73205080757. Taking integral value, S = 1. S2 = 1. Difference=2 which is not within 20% of 3 */ #include<bits/stdc++.h> using namespace std; int main() { long int t,x; cin>>t>>x; while(t!=0) {long int val;cin>>val; int sqr=sqrt(val); long int diff = val-(sqr*sqr); float per= 5*0.2; if(diff<=per) cout<<"yes"<<endl; else cout<<"no"<<endl; t--;} return 0; }
true
3fe9e82e27360604c06fe9baadc592d76bf9199c
C++
andyleejordan/uidaho-cs472-project1
/src/main.cpp
UTF-8
6,532
2.65625
3
[ "MIT" ]
permissive
/* Copyright 2014 Andrew Schwartzmeyer * * University of Idaho - CS 472: Evolutionary Computation by Terry Soule * * Project #1 Genetic Algorithm * * This program uses C++11 extensions (array template, range-based for * loop, random library) */ #include <algorithm> #include <cassert> #include <cstdlib> #include <iostream> #include <memory> // boost #include <boost/program_options.hpp> // aliases #include "aliases.hpp" // individual #include "individual/individual.hpp" // algorithms #include "algorithm/algorithm.hpp" #include "algorithm/genetic_algorithm.hpp" #include "algorithm/hill_climbing_algorithm.hpp" #include "algorithm/simulated_annealing_algorithm.hpp" #include "algorithm/mutator/mutator.hpp" #include "algorithm/mutator/mutator_creep.hpp" #include "algorithm/mutator/mutator_gaussian.hpp" #include "algorithm/mutator/mutator_jumping.hpp" #include "algorithm/recombinator/recombinator.hpp" #include "algorithm/recombinator/recombinator_arithmetic.hpp" #include "algorithm/recombinator/recombinator_two_point.hpp" #include "algorithm/recombinator/recombinator_uniform.hpp" // problems #include "problem/problem.hpp" #include "problem/ackley_problem.hpp" #include "problem/griewangk_problem.hpp" #include "problem/rastrigin_problem.hpp" #include "problem/rosenbrock_problem.hpp" #include "problem/schwefel_problem.hpp" #include "problem/spherical_problem.hpp" int main(int argc, char * argv[]) { namespace po = boost::program_options; using namespace std; using aliases::parameter; using namespace algorithm; using namespace problem; // setup program options string po_algorithm; vector<string> po_problems; string po_mutator; string po_recombinator; long po_iterations; parameter po_goal; po::positional_options_description positionals; po::variables_map variables_map; po::options_description desc("Allowed options"); desc.add_options() ("help,h", "produce help message") ("algorithm,a", po::value<string>(&po_algorithm)->default_value("Genetic"), "choose algorithm, currently unimplemented") ("problem,p", po::value<vector<string>>(&po_problems), "choose problem(s), defaults to all") ("mutator,m", po::value<string>(&po_mutator)->default_value("Jumping"), "choose mutator, creep, gaussian, jumping") ("recombinator,r", po::value<string>(&po_recombinator)->default_value("Two-Point"), "choose recombinator, arithmetic, two-point, uniform") ("iterations,i", po::value<long>(&po_iterations)->default_value(256), "set max iterations/generations") ("goal,g", po::value<parameter>(&po_goal)->default_value(0), "set goal, default will run until iterations is exhausted"); try { po::store(po::command_line_parser(argc, argv). options(desc).positional(positionals).run(), variables_map); if (variables_map.count("help")) { cout << "Search algorithms implemented in C++ by Andrew Schwartzmeyer\n\n" << "Code located at https://github.com/andschwa/uidaho-cs472-project1\n\n" << "Algorithms: Genetic, HillClimbing, and SimulatedAnnealing\n\n" << "Problems: Ackley, Griewangk, Rastrigin, Rosenbrock, Schwefel, and Spherical\n\n" << "Mutators: Creep, Gaussian, Jumping" << "Recombinators: Arithmetic, Two-Point, Uniform" << "Logs saved to logs/<Problem>.dat\n" << "GNUPlot settings in logs/<Problem>.p\n\n" << desc << endl; return 0; } po::notify(variables_map); // add all problems if none specified if (po_problems.size() == 0) { po_problems.emplace_back("Ackley"); po_problems.emplace_back("Griewangk"); po_problems.emplace_back("Rastrigin"); po_problems.emplace_back("Rosenbrock"); po_problems.emplace_back("Schwefel"); po_problems.emplace_back("Spherical"); } } catch(exception& e) { cout << e.what() << '\n'; return 1; } // setup mutator unique_ptr<const Mutator> working_mutator; if (po_mutator.compare("creep") == 0 || po_mutator.compare("Creep") == 0) working_mutator = unique_ptr<const Mutator>(new mutator::Creep()); else if (po_mutator.compare("gaussian") == 0 || po_mutator.compare("Gaussian") == 0) working_mutator = unique_ptr<const Mutator>(new mutator::Gaussian()); else if (po_mutator.compare("jumping") == 0 || po_mutator.compare("Jumping") == 0) working_mutator = unique_ptr<const Mutator>(new mutator::Jumping()); // setup recombinator shared_ptr<const Recombinator> working_recombinator; if (po_recombinator.compare("arithmetic") == 0 || po_recombinator.compare("Arithmetic") == 0) working_recombinator = shared_ptr<const Recombinator>(new recombinator::Arithmetic()); else if (po_recombinator.compare("two-point") == 0 || po_recombinator.compare("Two-Point") == 0) working_recombinator = shared_ptr<const Recombinator>(new recombinator::TwoPoint()); else if (po_recombinator.compare("uniform") == 0 || po_recombinator.compare("Uniform") == 0) working_recombinator = shared_ptr<const Recombinator>(new recombinator::Uniform()); // setup each problem and run the GA on it unique_ptr<Problem> working_problem; for (const string name : po_problems) { // Ugly replace of switch(name), better than find_if if (name.compare("Ackley") == 0 || name.compare("ackley") == 0) working_problem = unique_ptr<Problem>(new Ackley(po_iterations, po_goal)); else if (name.compare("Griewangk") == 0 || name.compare("griewangk") == 0) working_problem = unique_ptr<Problem>(new Griewangk(po_iterations, po_goal)); else if (name.compare("Rastrigin") == 0 || name.compare("rastrigin") == 0) working_problem = unique_ptr<Problem>(new Rastrigin(po_iterations, po_goal)); else if (name.compare("Rosenbrock") == 0 || name.compare("rosenbrock") == 0) working_problem = unique_ptr<Problem>(new Rosenbrock(po_iterations, po_goal)); else if (name.compare("Schwefel") == 0 || name.compare("schwefel") == 0) working_problem = unique_ptr<Problem>(new Schwefel(po_iterations, po_goal)); else if (name.compare("Spherical") == 0 || name.compare("spherical") == 0) working_problem = unique_ptr<Problem>(new Spherical(po_iterations, po_goal)); // Run GA on problem if (working_problem != nullptr) { Genetic algorithm(*working_problem, *working_mutator, working_recombinator); const Individual solution = algorithm.solve(); cout << working_problem->represent() << solution.represent() << "Raw fitness: " << solution.fitness << '\n' << endl; } } return 0; }
true
09c932559294e1e6c44d0bd20a9a4627d5ff327c
C++
XUqilian/Cproject
/cpp primer plus/chapterfourteen/example/prstu/head.h
UTF-8
2,132
3.28125
3
[]
no_license
#ifndef HEAD_H #define HEAD_H // has-a #include<iostream> #include<string> #include<valarray> using std::string; using std::valarray; using std::istream; using std::ostream; using std::endl; using std::cout; using std::cin; class Stu :private string , valarray<double> // 私有继承 继承类模块而非类 会生成无名类对象 所以不用类内声明对象 // 但好像只能生成一个该类型对象 // 使用或调用将基于类型名加域解析运算符 { private: // string name; // valarray<double> scores; // typedef valarray<double> vad; // can do it simple public: using std::valarray<double>::operator[]; Stu(){} // 试试不用初始化会不会出问题 explicit Stu(const char* t) :string(t) , valarray<double>(){} // 利用类型名赋值生成无名对象 因为对象无名 所以使用只能依靠类型名加域解析运算符 // 而且因为是直接用类型名使用的无名对象 所以在类中无法存在第二个同类对象 使用时会混乱 // 如果没有用 using std::string 这里就得 std::string(t) // typedef 不会受影响 依旧可以用其缩短书写代码类型长度 explicit Stu(int t) :string() , valarray<double>(t){} Stu(int t,int tt) :string() , valarray<double>(t,tt){} Stu(double * t,int tt) :string() , valarray<double>(t,tt){} Stu(const char* t ,int tt) :string(t) , valarray<double>(tt){} double & operator[](int); // i think this is ok ,it can be left or right value // double operator[](int); //无法重载仅按返回类型区分的函数 // double operator[](int) const; // 加上 const 可通过 但什么时候调用这个函数什么时候调用另一个呢 friend ostream & operator << (ostream & os,const Stu &); friend istream & operator>>(istream & is,Stu &); // can classify element. input 按成员定义相应的输入函数 // istream & getname(istream &, Stu &); 到时候直接分开使用 }; #endif
true
426479587df0f69b0de37d50999c0b7211c1363d
C++
toddxue/todd-algorithm
/play/shuffle/in-shuffle.play.cpp
UTF-8
1,255
2.53125
3
[]
no_license
#include "shuffle.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "timed.h" int main(int argc, char* argv[]) { bool benchmark = false; bool use_primitive_root = false; int n = argc - 1; if (0 == strcmp(argv[1], "benchmark")) { --n; benchmark = true; if (0 == strcmp(argv[2], "p")) { --n; use_primitive_root = true; } } else if (0 == strcmp(argv[1], "p")) { --n; use_primitive_root = true; } if (n % 2 != 0) { fprintf(stderr, "expect even numbers of integers\n"); return 1; } int* a = new int[n]; for (int i = argc - n; i < argc; ++i) a[i-(argc-n)] = strtol(argv[i], 0, 10); if (!benchmark) { if (use_primitive_root) shuffle::in_shuffle::primitive_root(n, a); else shuffle::in_shuffle::devide_and_conquer(n, a); } else { TIMED_BLOCK_STDERR(in_shuffle, true); if (use_primitive_root) shuffle::in_shuffle::primitive_root(n, a); else shuffle::in_shuffle::devide_and_conquer(n, a); } for (int i = 0; i < n; ++i) fprintf(stdout, "%d ", a[i]); delete[] a; return 0; }
true
2f6b65e0587fde6d0610ecffd445f3c8923583fe
C++
eteran/PcapPlusPlus
/Examples/DnsSpoofing/main.cpp
UTF-8
11,517
2.546875
3
[ "Unlicense" ]
permissive
/** * DNS spoofing example application * ================================ * This application does simple DNS spoofing. It's provided with interface name or IP and starts capturing DNS requests on that * interface. Each DNS request that matches is edited and turned into a DNS response with a user-provided IPv4 as the resolved IP. * Then it's sent back on the network on the same interface */ #include <vector> #include <algorithm> #include <sstream> #include <utility> #include <map> #if !defined(WIN32) && !defined(WINx64) && !defined(PCAPPP_MINGW_ENV) //for using ntohl, ntohs, etc. #include <in.h> #include <errno.h> #endif #include "IpAddress.h" #include "RawPacket.h" #include "ProtocolType.h" #include "Packet.h" #include "EthLayer.h" #include "IPv4Layer.h" #include "UdpLayer.h" #include "DnsLayer.h" #include "PcapFilter.h" #include "PcapLiveDevice.h" #include "PcapLiveDeviceList.h" #include "PlatformSpecificUtils.h" #include "SystemUtils.h" #include "PcapPlusPlusVersion.h" #include <getopt.h> #define EXIT_WITH_ERROR(reason, ...) do { \ printf("DnsSpoofing terminated in error: " reason "\n", ## __VA_ARGS__); \ exit(1); \ } while(0) using namespace pcpp; static struct option DnsSpoofingOptions[] = { {"interface", required_argument, 0, 'i'}, {"spoof-dns-server", required_argument, 0, 'd'}, {"client-ip", required_argument, 0, 'c'}, {"host-list", required_argument, 0, 'o'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"list", no_argument, 0, 'l'}, {0, 0, 0, 0} }; /** * A struct that holds all counters that are collected during application runtime */ struct DnsSpoofStats { int numOfSpoofedDnsRequests; std::map<std::string, int> spoofedHosts; DnsSpoofStats() : numOfSpoofedDnsRequests(0) {} }; /** * A struct that holds all arguments passed to handleDnsRequest() */ struct DnsSpoofingArgs { IPv4Address dnsServer; std::vector<std::string> dnsHostsToSpoof; DnsSpoofStats stats; bool shouldStop; DnsSpoofingArgs() : dnsServer(IPv4Address::Zero), shouldStop(false) {} }; /** * The method that is called each time a DNS request is received. This methods turns the DNS request into a DNS response with the * spoofed information and sends it back to the network */ void handleDnsRequest(RawPacket* packet, PcapLiveDevice* dev, void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; // create a parsed packet from the raw packet Packet dnsRequest(packet); if (!dnsRequest.isPacketOfType(DNS) || !dnsRequest.isPacketOfType(IPv4) || !dnsRequest.isPacketOfType(UDP) || !dnsRequest.isPacketOfType(Ethernet)) return; // extract all packet layers EthLayer* ethLayer = dnsRequest.getLayerOfType<EthLayer>(); IPv4Layer* ip4Layer = dnsRequest.getLayerOfType<IPv4Layer>(); UdpLayer* udpLayer = dnsRequest.getLayerOfType<UdpLayer>(); DnsLayer* dnsLayer = dnsRequest.getLayerOfType<DnsLayer>(); // skip DNS requests with more than 1 request or with 0 requests if (dnsLayer->getDnsHeader()->numberOfQuestions != htons(1) || dnsLayer->getFirstQuery() == NULL) return; // skip DNS requests which are not of class IN and type A (IPv4) DnsQuery* dnsQuery = dnsLayer->getFirstQuery(); if (dnsQuery->getDnsType() != DNS_TYPE_A || dnsQuery->getDnsClass() != DNS_CLASS_IN) return; // empty dnsHostsToSpoof means spoofing all hosts if (!args->dnsHostsToSpoof.empty()) { bool hostMatch = false; // go over all hosts in dnsHostsToSpoof list and see if current query matches one of them for (std::vector<std::string>::iterator iter = args->dnsHostsToSpoof.begin(); iter != args->dnsHostsToSpoof.end(); iter++) { if (dnsLayer->getQuery(*iter, false) != NULL) { hostMatch = true; break; } } if (!hostMatch) return; } // create a response out of the request packet // reverse src and dst MAC addresses MacAddress srcMac = ethLayer->getSourceMac(); ethLayer->setSourceMac(ethLayer->getDestMac()); ethLayer->setDestMac(srcMac); // reverse src and dst IP addresses IPv4Address srcIP = ip4Layer->getSrcIpAddress(); ip4Layer->setSrcIpAddress(ip4Layer->getDstIpAddress()); ip4Layer->setDstIpAddress(srcIP); ip4Layer->getIPv4Header()->ipId = 0; // reverse src and dst UDP ports uint16_t srcPort = udpLayer->getUdpHeader()->portSrc; udpLayer->getUdpHeader()->portSrc = udpLayer->getUdpHeader()->portDst; udpLayer->getUdpHeader()->portDst = srcPort; // add DNS response dnsLayer->getDnsHeader()->queryOrResponse = 1; IPv4DnsResourceData dnsServer(args->dnsServer); if (!dnsLayer->addAnswer(dnsQuery->getName(), DNS_TYPE_A, DNS_CLASS_IN, 1, &dnsServer)) return; dnsRequest.computeCalculateFields(); // send DNS response back to the network if (!dev->sendPacket(&dnsRequest)) return; args->stats.numOfSpoofedDnsRequests++; args->stats.spoofedHosts[dnsQuery->getName()]++; } /** * A callback for application interrupted event (ctrl+c): print DNS spoofing summary */ void onApplicationInterrupted(void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; if (args->stats.spoofedHosts.size() == 0) { printf("\nApplication closing. No hosts were spoofed\n"); } else { printf("\nApplication closing\nSummary of spoofed hosts:\n" "-------------------------\n"); for (std::map<std::string, int>::iterator iter = args->stats.spoofedHosts.begin(); iter != args->stats.spoofedHosts.end(); iter++) printf("Host [%s]: spoofed %d times\n", iter->first.c_str(), iter->second); } args->shouldStop = true; } /** * Activate DNS spoofing: prepare the device and start capturing DNS requests */ void doDnsSpoofing(PcapLiveDevice* dev, IPv4Address dnsServer, IPv4Address clientIP, std::vector<std::string> dnsHostsToSpoof) { // open device if (!dev->open()) EXIT_WITH_ERROR("Cannot open capture device"); // set a filter to capture only DNS requests and client IP if provided PortFilter dnsPortFilter(53, DST); if (clientIP == IPv4Address::Zero) { if (!dev->setFilter(dnsPortFilter)) EXIT_WITH_ERROR("Cannot set DNS filter for device"); } else { IPFilter clientIpFilter(clientIP.toString(), SRC); std::vector<GeneralFilter*> filterForAnd; filterForAnd.push_back(&dnsPortFilter); filterForAnd.push_back(&clientIpFilter); AndFilter andFilter(filterForAnd); if (!dev->setFilter(andFilter)) EXIT_WITH_ERROR("Cannot set DNS and client IP filter for device"); } // make args for callback DnsSpoofingArgs args; args.dnsServer = dnsServer; args.dnsHostsToSpoof = dnsHostsToSpoof; // start capturing DNS requests if (!dev->startCapture(handleDnsRequest, &args)) EXIT_WITH_ERROR("Cannot start packet capture"); // register the on app close event to print summary stats on app termination ApplicationEventHandler::getInstance().onApplicationInterrupted(onApplicationInterrupted, &args); // run an endless loop until ctrl+c is pressed while (!args.shouldStop) { printf("Spoofed %d DNS requests so far\n", args.stats.numOfSpoofedDnsRequests); PCAP_SLEEP(5); } } /** * go over all interfaces and output their names */ void listInterfaces() { const std::vector<PcapLiveDevice*>& devList = PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); printf("\nNetwork interfaces:\n"); for (std::vector<PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { printf(" -> Name: '%s' IP address: %s\n", (*iter)->getName(), (*iter)->getIPv4Address().toString().c_str()); } exit(0); } /** * Print application usage */ void printUsage() { printf("\nUsage:\n" "------\n" "%s [-hvl] [-o host1,host2,...,host_n] [-c ip_address] -i interface -d ip_address\n" "\nOptions:\n\n" " -h : Displays this help message and exits\n" " -v : Displays the current version and exists\n" " -l : Print the list of available interfaces\n" " -i interface : The interface name or interface IP address to use. Use the -l switch to see all interfaces\n" " -d ip_address : The IPv4 address of the spoofed DNS server (all responses will be sent with this IP address)\n" " -c ip_address : Spoof only DNS requests coming from a specific IPv4 address\n" " -o host1,host2,...,host_n : A comma-separated list of hosts to spoof. If list is not given, all hosts will be spoofed.\n" " If an host contains '*' all sub-domains will be spoofed, for example: if '*.google.com' is given\n" " then 'mail.google.com', 'tools.google.com', etc. will be spoofed\n\n", AppName::get().c_str()); } /** * Print application version */ void printAppVersion() { printf("%s %s\n", AppName::get().c_str(), getPcapPlusPlusVersionFull().c_str()); printf("Built: %s\n", getBuildDateTime().c_str()); printf("Built from: %s\n", getGitInfo().c_str()); exit(0); } /** * main method of the application */ int main(int argc, char* argv[]) { AppName::init(argc, argv); int optionIndex = 0; char opt = 0; std::string interfaceNameOrIP(""); IPv4Address dnsServer = IPv4Address::Zero; IPv4Address clientIP = IPv4Address::Zero; bool clientIpSet = false; std::vector<std::string> hostList; while((opt = getopt_long (argc, argv, "i:d:c:o:hvl", DnsSpoofingOptions, &optionIndex)) != -1) { switch (opt) { case 0: { break; } case 'h': { printUsage(); exit(0); } case 'v': { printAppVersion(); break; } case 'l': { listInterfaces(); exit(0); } case 'i': { interfaceNameOrIP = optarg; break; } case 'd': { dnsServer = IPv4Address(optarg); break; } case 'c': { clientIP = IPv4Address(optarg); clientIpSet = true; break; } case 'o': { std::string input = optarg; std::istringstream stream(input); std::string token; while(std::getline(stream, token, ',')) hostList.push_back(token); break; } default: { printUsage(); exit(1); } } } PcapLiveDevice* dev = NULL; // check if interface argument is IP or name and extract the device if (interfaceNameOrIP == "") { EXIT_WITH_ERROR("Interface name or IP weren't provided. Please use the -i switch or -h for help"); } IPv4Address interfaceIP(interfaceNameOrIP); if (interfaceIP.isValid()) { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided IP"); } else { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByName(interfaceNameOrIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided name"); } // verify DNS server IP is a valid IPv4 address if (dnsServer == IPv4Address::Zero || !dnsServer.isValid()) EXIT_WITH_ERROR("Spoof DNS server IP provided is empty or not a valid IPv4 address"); // verify client IP is valid if set if (clientIpSet && !clientIP.isValid()) EXIT_WITH_ERROR("Client IP to spoof is invalid"); doDnsSpoofing(dev, dnsServer, clientIP, hostList); }
true
ea09b9658ac7876f020b0627a0ab2c18032f3cfd
C++
samikib/DieHardWaterJug
/main.cpp
UTF-8
401
3.21875
3
[]
no_license
#include "Jug.h" void test1() { string solution; Jug head(3, 5, 4, 1, 2, 3, 4, 5, 6); if (head.solve(solution) != 1) { cout << "Error 3" << endl; } cout << solution << endl << endl; } void test2() { string solution; Jug head(3, 5, 4, 1, 1, 1, 1, 1, 2); if (head.solve(solution) != 1) { cout << "Error 3" << endl; } cout << solution << endl; } int main() { test1(); test2(); return 0; }
true
d2bbdea87ef4eef0d790a42d2f078f069a8f3214
C++
tjohanne/PCA
/src/include/timelogger.h
UTF-8
1,002
2.75
3
[]
no_license
#pragma once #include <chrono> #include <string> #include <vector> class TimeLogger { public: struct timeLog { int features; int samples; int n_components; double time_ms; std::string name; std::chrono::high_resolution_clock::time_point start_time; std::chrono::high_resolution_clock::time_point end_time; timeLog(int features, int samples, int n_components, std::string name, std::chrono::high_resolution_clock::time_point start_time) : features{features}, samples{samples}, n_components{n_components}, name{name}, start_time{start_time}{ time_ms = -123456789.0; // To identify logs without stop() } }; std::vector<timeLog*> logs; int features; int samples; int n_components; std::string log_name; TimeLogger(int features, int samples, int n_components, std::string log_name); timeLog* start(std::string name); void stop(timeLog* tl); };
true
a16b6148915fded71084057a30b7cae62b1e9546
C++
brextonpham/Beginner-s-All-purpose-Symbolic-Instruction-Code
/program.cpp
UTF-8
5,574
3.515625
4
[]
no_license
/* * File: program.cpp * ----------------- */ #include <string> #include "program.h" #include "statement.h" using namespace std; Program::Program() { } Program::~Program() { clear(); } /* * Method: clear * Usage: program.clear(); * ----------------------- * Removes all lines from the program. */ void Program::clear() { for (int key : storage) { //Goes through and deletes all entries in the map delete storage[key]; } lineNumbers.clear(); storage.clear(); } /* * Method: addSourceLine * Usage: program.addSourceLine(lineNumber, line); * ----------------------------------------------- * Adds a source line to the program with the specified line number. * If that line already exists, the text of the line replaces * the text of any existing line and the parsed representation * (if any) is deleted. If the line is new, it is added to the * program in the correct sequence. */ void Program::addSourceLine(int lineNumber, string line) { int newLineNumberIndex; //The following lines add line numbers to the vector if (lineNumbers.isEmpty()) { //Adds first element to vector lineNumbers.add(lineNumber); newLineNumberIndex = 0; } else { for (int i = lineNumbers.size() - 1; i >= 0; i--) { //Inserts line number according to order in vector if (lineNumber > lineNumbers[i]) { lineNumbers.insert(i + 1, lineNumber); newLineNumberIndex = i; break; } if (i == 0) { lineNumbers.insert(0, lineNumber); newLineNumberIndex = i; } } } SourceLine *newSourceLine = new SourceLine; //Deals with adding information to the map "storage" newSourceLine->lineString = line; newSourceLine->lineNumbersIndex = newLineNumberIndex; newSourceLine->lineParsed = NULL; storage.put(lineNumber, newSourceLine); for (int i = 0; i < lineNumbers.size(); i++) { //Shift line numbers indices accordingly in the map //when something is added storage[lineNumbers[i]]->lineNumbersIndex = i; } } /* * Method: removeSourceLine * Usage: program.removeSourceLine(lineNumber); * -------------------------------------------- * Removes the line with the specified number from the program, * freeing the memory associated with any parsed representation. * If no such line exists, this method simply returns without * performing any action. */ void Program::removeSourceLine(int lineNumber) { int removeIndex = storage.get(lineNumber)->lineNumbersIndex; //Obtain index to remove from vector lineNumbers.remove(removeIndex); storage.remove(lineNumber); //Remove from map } /* * Method: getSourceLine * Usage: string line = program.getSourceLine(lineNumber); * ------------------------------------------------------- * Returns the program line with the specified line number. * If no such line exists, this method returns the empty string. */ string Program::getSourceLine(int lineNumber) { return storage.get(lineNumber)->lineString; } /* * Method: setParsedStatement * Usage: program.setParsedStatement(lineNumber, stmt); * ---------------------------------------------------- * Adds the parsed representation of the statement to the statement * at the specified line number. If no such line exists, this * method raises an error. If a previous parsed representation * exists, the memory for that statement is reclaimed. */ void Program::setParsedStatement(int lineNumber, Statement *stmt) { if (storage.containsKey(lineNumber)) { if (storage[lineNumber]->lineParsed != NULL) delete storage[lineNumber]->lineParsed; //If the line parsed field of the source line containes something, delete it and replace it with //given statement storage[lineNumber]->lineParsed = stmt; } } /* * Method: getParsedStatement * Usage: Statement *stmt = program.getParsedStatement(lineNumber); * ---------------------------------------------------------------- * Retrieves the parsed representation of the statement at the * specified line number. If no value has been set, this method * returns NULL. */ Statement *Program::getParsedStatement(int lineNumber) { if (storage.containsKey(lineNumber)) return storage.get(lineNumber)->lineParsed; else return NULL; } /* * Method: getFirstLineNumber * Usage: int lineNumber = program.getFirstLineNumber(); * ----------------------------------------------------- * Returns the line number of the first line in the program. * If the program has no lines, this method returns -1. */ int Program::getFirstLineNumber() { if (!lineNumbers.isEmpty()) { return lineNumbers[0]; } return -1; } /* * Method: getNextLineNumber * Usage: int nextLine = program.getNextLineNumber(lineNumber); * ------------------------------------------------------------ * Returns the line number of the first line in the program whose * number is larger than the specified one, which must already exist * in the program. If no more lines remain, this method returns -1. */ int Program::getNextLineNumber(int lineNumber) { if (!lineNumbers.isEmpty()) { int nextLineNumberIndex = storage.get(lineNumber)->lineNumbersIndex + 1; //Obtains the index of the next line number if (nextLineNumberIndex < lineNumbers.size() && lineNumbers.size() != 0) { //If that index is in the vector return lineNumbers[nextLineNumberIndex]; //Return that next line number } } return -1; }
true
429b10d10ca0093acbfc73848493b95982cea103
C++
eqy/pyramid
/populatingnextrightpointersineachnodeii.cpp
UTF-8
1,727
3.765625
4
[]
no_license
/* // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; */ class Solution { public: Node* right(Node* root, int levels) { if (!levels || !root) { return root; } else { Node* leftchoice = right(root->left, levels - 1); if (leftchoice) { return leftchoice; } else { return right(root->right, levels - 1); } } } Node* left(Node *root, int levels) { if (!levels || !root) { return root; } else { Node* rightchoice = left(root->right, levels - 1); if (rightchoice) { return rightchoice; } else { return left(root->left, levels - 1); } } } Node* connect(Node* root) { if (root) { connect(root->left); connect(root->right); int levels = 0; while (true) { Node *cur_left = root->left; Node *cur_right = root->right; cur_left = left(cur_left, levels); cur_right = right(cur_right, levels); if (cur_left && cur_right) { cur_left->next = cur_right; } else { break; } levels++; } } return root; } };
true
3f06b9a5dc7c06c288f20b05925384cd4069a21a
C++
whymeen/TestFramework
/dhUtilityLib/dhPrinter.cpp
UTF-8
2,156
2.890625
3
[]
no_license
// dhPrinter.cpp: implementation of the dhPrinter class. // ////////////////////////////////////////////////////////////////////// #include "dhPrinter.h" #include <stdarg.h> dhPrinter* dhPrinter::m_printer = NULL ; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// void dhPrinter::DefaultPrinter::print( int msgType, const std::string& msg ) { printf ( "DefaultPrinter MsgType [%i]: %s\n", msgType, msg.c_str() ) ; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// dhPrinter::dhPrinter() { } dhPrinter::~dhPrinter() { m_printers.clear() ; } void dhPrinter::addPrinter( dhPrinter::BasePrinter* printer ) { dhPrinter *p = dhPrinter::getInstance() ; if ( p == NULL ) return ; p->m_printers.push_back( printer ) ; } void dhPrinter::removePrinter( dhPrinter::BasePrinter* printer ) { dhPrinter *p = dhPrinter::getInstance() ; if ( p == NULL ) return ; std::vector<BasePrinter*>::iterator iVec = p->m_printers.begin() ; while ( iVec != p->m_printers.end() ) { if ( *iVec == printer ) { *iVec = NULL ; p->m_printers.erase( iVec ) ; break ; } iVec ++ ; } } void dhPrinter::print( int msgType, const std::string& msg ) { dhPrinter *p = dhPrinter::getInstance() ; if ( p == NULL ) return ; for ( unsigned int i = 0; i < p->m_printers.size(); i++ ) { p->m_printers[i]->print ( msgType, msg ) ; } } void dhPrinter::print( const std::string& msg ) { print ( -1, msg ) ; } void dhPrinter::print( int msgType, const char *format, ... ) { char msgbuff[ 16384 ]; va_list argp; char* msgptr = msgbuff; va_start( argp, format ); vsprintf( msgptr, format, argp ); va_end( argp ); print( msgType, std::string(msgbuff) ) ; } void dhPrinter::print( const char *format, ... ) { char msgbuff[ 16384 ]; va_list argp; char* msgptr = msgbuff; va_start( argp, format ); vsprintf( msgptr, format, argp ); va_end( argp ); print( -1, std::string(msgbuff) ) ; }
true
f76ff1144ae2c73d5154f89422c353e8aede6972
C++
mkltaneja/Interview-Prep-Questions
/Recursion_and_Backtracking/Sudoku.cpp
UTF-8
1,452
3.015625
3
[]
no_license
#include<iostream> #include<vector> #define vi vector<int> #define vvi vector<vi> using namespace std; void display(vvi &arr) { for(int i=0; i<9; i++) { for(int j=0; j<9; j++) cout<<arr[i][j]<<" "; cout<<endl; } } void solve_sudoku(int idx, vvi &arr, vi &row, vi &col, vvi &sub, vi &calls) { if(idx == calls.size()) { display(arr); return; } int i = calls[idx] / 9; int j = calls[idx] % 9; for(int num=1; num<=9; num++) { int mask = (1 << num); if(!(row[i] & mask) && !(col[j] & mask) && !(sub[i/3][j/3] & mask)) { arr[i][j] = num; row[i] ^= mask; col[j] ^= mask; sub[i/3][j/3] ^= mask; solve_sudoku(idx+1, arr, row, col, sub, calls); arr[i][j] = 0; row[i] ^= mask; col[j] ^= mask; sub[i/3][j/3] ^= mask; } } } int main() { vvi arr(9,vi (9,0)); vi row(9,0); vi col(9,0); vvi sub(3,vi(3,0)); vi calls; // calls.reserve(81); for(int i=0; i<9; i++) { for(int j=0; j<9; j++) { cin>>arr[i][j]; if(arr[i][j] == 0) calls.push_back(i * 9 + j); int mask = (1 << arr[i][j]); row[i] |= mask; col[j] |= mask; sub[i/3][j/3] |= mask; } } solve_sudoku(0,arr,row,col,sub,calls); }
true
288450a8d9a8e13581615050661e9e5fb2c4da1a
C++
Vinayak-14/LVCPPMay2021
/June/23rdJuneLecture12/WavePrint.cpp
UTF-8
949
3.8125
4
[]
no_license
/* Given an integer matrix 'mat' of dimensions m x n, write a program that prints the matrix in wave form. Example : Input : mat[][] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output : 1 4 7 8 5 2 3 6 9 */ #include<iostream> using namespace std; int main() { #ifndef IO freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif int m, n; cin >> m >> n; int mat[10][10]; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { cin >> mat[i][j]; } } // // print the matrix column-wise // for(int j=0; j<n; j++) { // for(int i=0; i<m; i++) { // cout << mat[i][j] << " "; // } // } // print the matrix wave column-wise for(int j=0; j<n; j++) { if(j%2 == 0) { // print from top to bottom for(int i=0; i<m; i++) { cout << mat[i][j] << " "; } } else { // print from bottom to top for(int i=m-1; i>=0; i--) { cout << mat[i][j] << " "; } } } return 0; }
true
82a379d2a9c6610d6c6a29bd396ce21f093b1e4c
C++
RequiemSouls/Mini3D
/src/geometry.cc
UTF-8
1,109
2.609375
3
[]
no_license
#include "geometry.h" MINI_NS_BEGIN // const F32 identity[] = {1.f, 0.f, 0.f, 0.f, 0.f, 1.f, 0.f, 0.f, // 0.f, 0.f, 1.f, 0.f, 0.f, 0.f, 0.f, 1.f}; // const Vec2 Vec2::ZERO = Vec2(); // const Vector Vector::ZERO = Vector(); const Color Color::ZERO = Color(); const Color Color::WHITE = Color(255, 255, 255); // const Matrix Matrix::ZERO = Matrix(); // const Matrix Matrix::IDENTITY((F32 *)(identity)); // // void Matrix::Transfer(const Vector &offset) { // m[0][3] = offset.get_x(); // m[1][3] = offset.get_y(); // m[2][3] = offset.get_z(); // } // // Vector operator*(const Matrix &m, const Vector &v) { // return Vector( // m.m[0][0] * v.get_x() + m.m[0][1] * v.get_y() + m.m[0][2] * v.get_z() + m.m[0][3] * v.get_w(), // m.m[1][0] * v.get_x() + m.m[1][1] * v.get_y() + m.m[1][2] * v.get_z() + m.m[1][3] * v.get_w(), // m.m[2][0] * v.get_x() + m.m[2][1] * v.get_y() + m.m[2][2] * v.get_z() + m.m[2][3] * v.get_w(), // m.m[3][0] * v.get_x() + m.m[3][1] * v.get_y() + m.m[3][2] * v.get_z() + m.m[3][3] * v.get_w()); // } MINI_NS_END
true
b39b141f944ad37c57ab5925bee590b9b4b86d1e
C++
kciwsolb/ecs_game_engine
/2DSDLGameEngine/GameObject.h
UTF-8
366
2.6875
3
[]
no_license
#pragma once #include "EntityManager.h" #include <iostream> class GameObject { public: virtual void Update() {} virtual ~GameObject() { EntityManager::SharedInstance().RemoveEntity(entity); } void SetIsDead(bool isDead) { this->isDead = isDead; } bool GetIsDead() { return isDead; } protected: bool isDead = false; Entity* entity; virtual void Init() {} };
true
5a63c0e9b07c62f9197a385737f537ec7f0ce6c0
C++
RitchieLab/athena
/tags/1.0.0/src/athena/Terminals.h
UTF-8
6,701
2.515625
3
[]
no_license
/* * File: Terminals.h * Author: dudeksm * * Created on November 14, 2008, 4:03 PM */ #ifndef _TERMINALS_H #define _TERMINALS_H #include "TerminalSymbol.h" #include <vector> #include <Individual.h> using namespace data_manage; class Constant :public TerminalSymbol{ public: Constant(std::string symbol, int number_args=0); Constant(float val); virtual ~Constant(){} virtual float evaluate(std::deque<float> & TerminalSymbols); private: float constant_value; }; /////////////////////////////// // user-defined terminals below /////////////////////////////// /// /// TerminalSymbol that contains an index for referencing /// genotypes in the dataset /// class GenotypeTerm :public TerminalSymbol{ public: GenotypeTerm(std::string name, int variable_index); virtual ~GenotypeTerm(){} virtual float evaluate(std::deque<float> & TerminalSymbols); inline int getIndex(){return index_value;} static void set_ind(Individual* ind); private: int index_value; static Individual* ind; }; /// /// TerminalSymbol that contains an index for referencing /// genotypes in the dataset /// class ContinVariable :public TerminalSymbol{ public: ContinVariable(std::string name, int variable_index); virtual ~ContinVariable(){} virtual float evaluate(std::deque<float> & TerminalSymbols); static void set_ind(Individual* ind); inline int getIndex(){return index_value;} private: int index_value; static Individual* ind; }; class Addition :public TerminalSymbol{ public: Addition(std::string symbol, int number_args); virtual ~Addition(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Subtraction :public TerminalSymbol{ public: Subtraction(std::string symbol, int number_args); virtual ~Subtraction(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Multiplication :public TerminalSymbol{ public: Multiplication(std::string symbol, int number_args); virtual ~Multiplication(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Division :public TerminalSymbol{ public: Division(std::string symbol, int number_args); virtual ~Division(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Power :public TerminalSymbol{ public: Power(std::string symbol, int number_args); virtual ~Power(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pAdd :public TerminalSymbol{ public: pAdd(std::string symbol, int number_args); virtual ~pAdd(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pSub :public TerminalSymbol{ public: pSub(std::string symbol, int number_args); virtual ~pSub(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pMult :public TerminalSymbol{ public: pMult(std::string symbol, int number_args); virtual ~pMult(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pDiv :public TerminalSymbol{ public: pDiv(std::string symbol, int number_args); virtual ~pDiv(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Weight :public TerminalSymbol{ public: Weight(std::string symbol, int number_args); virtual ~Weight(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Dot :public TerminalSymbol{ public: Dot(std::string symbol, int number_args=0); virtual ~Dot(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class ConCat :public TerminalSymbol{ public: ConCat(std::string symbol, int number_args); virtual ~ConCat(){} virtual float evaluate(std::deque<float> & TerminalSymbols); friend ostream & operator << (ostream & os, const TerminalSymbol & el); }; class LogF :public TerminalSymbol{ public: LogF(std::string symbol, int number_args); virtual ~LogF(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Sine :public TerminalSymbol{ public: Sine(std::string symbol, int number_args); virtual ~Sine(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Cosine :public TerminalSymbol{ public: Cosine(std::string symbol, int number_args); virtual ~Cosine(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Tangent :public TerminalSymbol{ public: Tangent(std::string symbol, int number_args); virtual ~Tangent(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; // Following are the boolean operators for neural nets class pAnd :public TerminalSymbol{ public: pAnd(std::string symbol, int number_args); virtual ~pAnd(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pNand :public TerminalSymbol{ public: pNand(std::string symbol, int number_args); virtual ~pNand(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pOr :public TerminalSymbol{ public: pOr(std::string symbol, int number_args); virtual ~pOr(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pNor :public TerminalSymbol{ public: pNor(std::string symbol, int number_args); virtual ~pNor(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class pXor :public TerminalSymbol{ public: pXor(std::string symbol, int number_args); virtual ~pXor(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; // Following are the boolean operators class And :public TerminalSymbol{ public: And(std::string symbol, int number_args); virtual ~And(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Nand :public TerminalSymbol{ public: Nand(std::string symbol, int number_args); virtual ~Nand(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Or :public TerminalSymbol{ public: Or(std::string symbol, int number_args); virtual ~Or(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Nor :public TerminalSymbol{ public: Nor(std::string symbol, int number_args); virtual ~Nor(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; class Xor :public TerminalSymbol{ public: Xor(std::string symbol, int number_args); virtual ~Xor(){} virtual float evaluate(std::deque<float> & TerminalSymbols); }; #endif /* _TERMINALS_H */
true
d2af69d262938aad43f4222a179051a4f6f90aa1
C++
malzer42/libManagementSys
/libManagementSys/Library.h
UTF-8
2,678
3.078125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Library.h * Author: pamulamba * * Created on 29 juin 2020, 22 h 21 */ #ifndef LIBRARY_H #define LIBRARY_H #include <stdexcept> #include <exception> #include <memory> // std::shared_ptr, std::make_unique<Type> #include <regex> // std::regex, std::regex_match, std::regex_search, std::regex_replace #include "Subscriber.h" #include "Book.h" #include "Borrow.h" class Library { public: const unsigned int MAX_SUB = {100}; // Maximum number of Subscribers const unsigned int MAX_BOOK = {1000}; // Maximum number of Books const unsigned int MAX_BORROW = {200}; // Maximum number of Borrows Library(); // Ctor Library(const Library& orig); Library(Library&& orig) noexcept; Library& operator=(const Library &orig); Library& operator=(Library&& orig)noexcept; virtual ~Library(); // Dtor class BadLibrary : public std::exception { public: const std::string exceptionMsg = {"BadLibraryError: Unable to process item in the library\n"}; }; // Processing subscribers in the library void addSubscriber(Subscriber& subscriber); void removeSubscriber(const std::string& id); void sortSubscriber(unsigned int option); void swapSubscriber(Subscriber &sub1, Subscriber &sub2); // Processing books in the library void addBook(std::unique_ptr<Book>& book); void removeBook(const std::string& quote); void sortBook(unsigned int option); void swapBook(Book &book1, Book &book2); // Searching, borrowing, returning, displaying methods void searchTitle(const std::string &str); void searchQuote(const std::string &book_quote); bool borrowBookBySubscriber(const std::string &subscriber_id, const std::string &book_quote, const std::string& returnDate); bool returnBook(const std::string &subscriber_id, const std::string &book_quote); void infoSubscriber(const std::string &subscriber_id) const; void swapBorrow(Borrow &borrow1, Borrow &borrow2); void print()const; private: Subscriber** subs_; unsigned short nSubs_; Book** books_; unsigned short nBooks_; Borrow** borrows_; unsigned short nBorrows_; /** * Adding and instance of Borrow to the list of Borrowers * @param borrow */ void addBorrow(Borrow& borrow); /** * Removing an instance of Borrow to the list of Borrowers * @param borrow */ void removeBorrow(Borrow* borrow); }; #endif /* LIBRARY_H */
true
1e9263488c84ff86463ef636a1a7f25ebc56070e
C++
rranjik/ideal-octo-barnacle
/775-GlobalAndLocalInversions.cpp
UTF-8
852
2.921875
3
[]
no_license
class Solution { public: using it = vector<int>::iterator; int msort(it l, it r){ if(r-l>1){ cout<<"here "<<endl; auto m = l+(r-l)/2; auto left = msort(l, m); auto right = msort(m, r); auto res = 0; for(auto i = l, j = m; i<m; i++){ while(j<r&&*i>*j){ j++; } res+=(j-m); } inplace_merge(l, m, r); return res+left+right; }return 0; } bool isIdealPermutation(vector<int>& A) { vector<int> a = A; auto g = msort(A.begin(), A.end()); cout<<"g = "<<g<<endl; auto l = 0; for(int i = 0; i<A.size()-1; i++){ if(a[i]>a[i+1]) l++; } cout<<"l = "<<l<<endl; return g==l; } };
true
54fc54d7b872183eb3b3d7d00da78488e952b5c8
C++
LiangSun1994/cplusplus_primer
/chapter_08/chapter_08_11_swap.cpp
UTF-8
281
3.6875
4
[]
no_license
#include <iostream> /* template <typename T> void swap(T& a, T& b); int main(){ int a = 1; int b = 2; swap(a,b); std::cout<<"a:"<<a<<std::endl; std::cout<<"b:"<<b<<std::endl; } template <typename T> void swap(T& a, T& b){ T temp; temp = a; a = b; b = temp; } */
true
23e0fa2aec18f5167753f5d00f5769a2e2c6d7fc
C++
EALH/paralela
/OpenMp/sumVec.cpp
UTF-8
596
2.765625
3
[]
no_license
#include <iostream> #include <omp.h> using namespace std; int main(int argc, char* argv[]) { int n = atoi(argv[1]); double* x, y; x = new double [n]; for(int i = 0; i < n; i++) { x[i] = (double) (i + 2); } y = new double [n]; for(int i = 0; i < n; i++) { y[i] = (double) (i + 3); } double start = omp_get_wtime(); for (int i = 0; i < n; i++) { x[i] = x[i] + y[i]; } double end = omp_get_wtime(); printf("start = %.16g\nend = %.16g\ndiff = %.16g\n", start, end, end - start); return 0; }
true
2eb457353c359b839599e862f0bde54b73437118
C++
AdityaGattu/Imp-Coding
/Graphs/Strongly Connected Components (Kosaraju's Algo) .cpp
UTF-8
1,567
2.984375
3
[]
no_license
public: /* Function to find the number of strongly connected components * using Kosaraju's algorithm * V: number of vertices * adj[]: array of vectors to represent graph */ stack<int>s; void dfs(int node,vector<bool> &vis,vector<int> adj[]) { vis[node]=true; for(auto neigh:adj[node]) { if(!vis[neigh]) { dfs(neigh,vis,adj); } } s.push(node); } void revdfs(int node,vector<bool>& vis1,vector<int> trans_adj[]) { vis1[node]=true; for(auto neigh:trans_adj[node]) { if(!vis1[neigh]) { revdfs(neigh,vis1,trans_adj); } } } int kosaraju(int V, vector<int> adj[]) { //code here vector<bool>vis(V,false); for(int i=0;i<V;i++) { if(!vis[i]) { dfs(i,vis,adj); } } vector<int> trans_adj[V]; for(int i=0;i<V;i++) { for(auto it:adj[i]) { trans_adj[it].push_back(i); } } vector<bool>vis1(V,false); int count=0; while(!s.empty()) { int ver=s.top(); s.pop(); if(!vis1[ver]) { revdfs(ver,vis1,trans_adj); count++; } } return count; }
true
450bdaa3f88673a747a44f9a0cf42519b60167bd
C++
HelgiThomas/Verklegt31
/gui/add/addcomp.cpp
UTF-8
4,664
2.96875
3
[]
no_license
#include "addcomp.h" #include "ui_addcomp.h" addcomp::addcomp(QWidget *parent) : QDialog(parent), ui(new Ui::addcomp) { ui->setupUi(this); for(int i = 2016; i > 0; i--) { ui->combobox_buildYear->addItem(QString::number(i)); } } addcomp::~addcomp() { delete ui; } /** * @brief addcomp::on_button_addComp_clicked, adds computer to the table when the button is clicked. */ void addcomp::on_button_addComp_clicked() { int addId = 0; string addName; string addCompType; string addWasBuilt; int addBuildYear; QString QaddDescription = ui->text_description->toPlainText(); ui->text_description->setText(QaddDescription); string addDescription = QaddDescription.toStdString(); if(ui->radio_yes->isChecked()) { addBuildYear = _buildYear; } else if(ui->radio_no->isChecked()) { addBuildYear = 0; } if(!isValidType()) { QMessageBox::about(this, "Error!", "Please choose at least one type!"); } else if(!isValidWasBuilt()) { QMessageBox::about(this, "Error!", "Please say whether the computer was built or not!"); } else if(!_serviceComp.validName(_type)) { QMessageBox::about(this, "Error!", "Please enter a valid other computer type!"); } else { addName = ui->line_compName->text().toStdString(); addCompType = _type; addWasBuilt = _wasBuilt; Computer newComp(addId, addName, addBuildYear, addCompType, addWasBuilt, addDescription); _serviceComp.addComputer(newComp); close(); } resetComp(); } /** * @brief addcomp::isValidType, checks if the type that the user put in is valid. * @return true if the input is valid, false otherwise. */ bool addcomp::isValidType() { bool valid = true; if(ui->radio_elec->isChecked()) { _type = "Electronic"; } else if(ui->radio_mech->isChecked()) { _type = "Mechanical"; } else if(ui->radio_trans->isChecked()) { _type = "Transistor"; } else if(ui->radio_oth->isChecked()) { string compType = ui->line_otherType->text().toStdString(); _type = compType; } else { valid = false; } return valid; } /** * @brief addcomp::isValidWasBuilt, checks if the user put in wether the computer was built or not. * @return false if the user did not put in anything, true otherwise. */ bool addcomp::isValidWasBuilt() { bool valid = true; if(ui->radio_yes->isChecked()) { _wasBuilt = "Yes"; } else if(ui->radio_no->isChecked()) { _wasBuilt = "No"; } else { valid = false; } return valid; } /** * @brief addcomp::on_combobox_buildYear_currentIndexChanged, sets the computers build year to the build year selected in the * combo box. */ void addcomp::on_combobox_buildYear_currentIndexChanged() { QString qstrBuildYear = ui->combobox_buildYear->currentText() ; string strBuildYear = qstrBuildYear.toStdString(); _buildYear = atoi(strBuildYear.c_str()); } /** * @brief addcomp::on_radio_yes_clicked, enables the build year combo box if the user clicks the yes radio button. */ void addcomp::on_radio_yes_clicked() { ui->combobox_buildYear->setEnabled(true); } /** * @brief addcomp::on_radio_no_clicked, disables the build year combo box if the user clicks the no radio button. */ void addcomp::on_radio_no_clicked() { ui->combobox_buildYear->setEnabled(false); _buildYear = 0; } /** * @brief addcomp::resetComp, when the user adds a computer and then wants to add another computer, the info about the * previously added computer does not persist in the add window. */ void addcomp::resetComp() { ui->line_compName->setText(""); ui->radio_mech->setAutoExclusive(false); ui->radio_mech->setChecked(false); ui->radio_mech->setAutoExclusive(true); ui->radio_elec->setAutoExclusive(false); ui->radio_elec->setChecked(false); ui->radio_elec->setAutoExclusive(true); ui->radio_trans->setAutoExclusive(false); ui->radio_trans->setChecked(false); ui->radio_trans->setAutoExclusive(true); ui->radio_oth->setAutoExclusive(false); ui->radio_oth->setChecked(false); ui->radio_oth->setAutoExclusive(true); ui->radio_yes->setAutoExclusive(false); ui->radio_yes->setChecked(false); ui->radio_yes->setAutoExclusive(true); ui->radio_no->setAutoExclusive(false); ui->radio_no->setChecked(false); ui->radio_no->setAutoExclusive(true); ui->combobox_buildYear->setCurrentIndex(2016); ui->line_otherType->setText(""); }
true
1a2a3beec80ff649f18ebfbf5ffe69550f1b9395
C++
Liam0205/leetcode
/algorithm/0680-valid-palindrome-II/ver2.cc
UTF-8
1,099
2.953125
3
[]
no_license
#pragma GCC optimise ("Ofast") static const auto io_sync_off = []() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); return nullptr; }(); class Solution { public: bool validPalindrome(const std::string& s) { if (isPalindrome(s)) { return true; } else { const size_t half = s.size() / 2; size_t l = 0, r = s.size(); for (size_t i = 0; i != half and s[l] == s[r - 1]; ++i, ++l, --r); return isPalindrome(s.substr(l, r - l - 1)) or isPalindrome(s.substr(l + 1, r - l - 1)); if (s[l] == s[r - 2]) { return isPalindrome(s.substr(l + 1, r - l - 2)); } else if (s[l + 1] == s[r - 1]) { return isPalindrome(s.substr(l + 2, r - l - 2)); } else { return false; } } } private: bool isPalindrome(const std::string& s) { if (s.empty()) { return true; } else { const size_t half = s.size() / 2; auto l = s.begin(); auto r = s.rbegin(); for (size_t i = 0; i != half and *l == *r; ++i, ++l, ++r); return *l == *r; } } };
true
3aa2a7a8c4501eba0bde107d26f55b155f74e005
C++
KimHyoungChul/FFmpegAndroid
/jni/effect/echo.cpp
UTF-8
2,458
2.78125
3
[]
no_license
#include "echo.h" // "回音" 音效增强器 #define MAX_DELAY 1000 static echo_t *echo = 0; int min(int a, int b) { return a < b ? a : b; } int max(int a, int b) { return a > b ? a : b; } int clamp(int x, int low, int high) { return min(max(x, low), high); } int chsign(int x, int s) { return (x < 0) ^ (s < 0) ? -x : x; } int rdiv(int x, int y) { return (x + chsign(y / 2, x)) / y; } int rescale(int x, int old_scale, int new_scale) { return rdiv(x * new_scale, old_scale); } echo_conf_t *echo_init(int sample_rate, int channels) { if (!echo) { echo_conf_t *conf = (echo_conf_t*)malloc(sizeof(echo_conf_t)); conf->delay = 500; conf->feedback = 50; conf->volume = 50; echo = (echo_t*)malloc(sizeof(echo_t)); echo->sample_rate = sample_rate; echo->channels = channels; echo->buffer_size = rescale(MAX_DELAY, 1000, sample_rate) * channels; echo->buffer = (float*)calloc(1, echo->buffer_size); echo->conf = conf; } return echo->conf; } bool echo_conf(echo_conf_t *conf) { bool ret = false; if (conf) { // 延迟 if (conf->delay > ECHO_DELAY_MAX || conf->delay < ECHO_DELAY_MIN) { conf->delay = 500; } // 反馈 if (conf->feedback > ECHO_FEEDBACK_MAX || conf->feedback < ECHO_FEEDBACK_MIN) { conf->feedback = 50; } // 音量 if (conf->volume > ECHO_VOLUME_MAX || conf->volume < ECHO_VOLUME_MIN) { conf->volume = 50; } ret = true; } return ret; } void echo_process(float **inblock, float **outblock, int sample_rate) { int delay = echo->conf->delay; float feedback = echo->conf->feedback / 100.0f; float volume = echo->conf->volume / 100.0f; int interval = rescale(delay, 100, echo->sample_rate); interval = clamp(interval, 0, echo->buffer_size); int r_ofs = echo->w_ofs - interval; if (r_ofs < 0) r_ofs += echo->buffer_size; float *f = inblock[0]; float *end = inblock[0] + sample_rate; float *out = outblock[0]; while (f < end) { float in = *f; float buf = echo->buffer[r_ofs]; *out = in + buf * volume; echo->buffer[echo->w_ofs] = in + buf * feedback; r_ofs = (r_ofs + 1) % echo->buffer_size; echo->w_ofs = (echo->w_ofs + 1) % echo->buffer_size; f++; out++; } }
true
e8cce4365fc9967605a3b70ccdd6e91094f868fd
C++
zainmehdi/manual_pos_graph_slam
/manipulatedframesetconstraint.h
UTF-8
2,329
2.78125
3
[]
no_license
#ifndef MANIPULATEDFRAMESETCONSTRAINT_H #define MANIPULATEDFRAMESETCONSTRAINT_H #include <QGLViewer/constraint.h> #include <QGLViewer/frame.h> #include <QSet> class ManipulatedFrameSet{ public: void clear(){ frames.clear(); } void add(qglviewer::Frame* frame){ frames.insert(frame); } protected: typedef QSet<qglviewer::Frame*> FrameContainer; FrameContainer frames; }; template <class ConstraintType> class ManipulatedFrameSetConstraint: public ConstraintType,public ManipulatedFrameSet { public: virtual void constrainTranslation(qglviewer::Vec& tr, qglviewer::Frame* const frame); virtual void constrainRotation(qglviewer::Quaternion& quat, qglviewer::Frame* const frame); }; typedef ManipulatedFrameSetConstraint<qglviewer::LocalConstraint> LocalManipulatedFrameSetConstraint; typedef ManipulatedFrameSetConstraint<qglviewer::WorldConstraint> WorldManipulatedFrameSetConstraint; ///////////////////////Template implemenation////////////////////////////////// template <class ConstraintType> void ManipulatedFrameSetConstraint<ConstraintType>::constrainTranslation(qglviewer::Vec &tr, qglviewer::Frame * const frame){ std::cerr<<"constrainTranslation(raw) : "<<tr<<std::endl; ConstraintType::constrainTranslation(tr, frame); std::cerr<<"constrainTranslation(constrained) : "<<tr<<std::endl; for(FrameContainer::iterator it=frames.begin();it!=frames.end();it++){ (*it)->translate(tr); } } template <class ConstraintType> void ManipulatedFrameSetConstraint<ConstraintType>::constrainRotation(qglviewer::Quaternion &quat, qglviewer::Frame * const frame){ std::cerr<<"constrainRotation(raw) : "<<quat<<std::endl; ConstraintType::constrainRotation(quat, frame); std::cerr<<"constrainRotation(constrained) : "<<quat<<std::endl; const qglviewer::Vec world = frame->inverseTransformOf(quat.axis()); const qglviewer::Vec pos = frame->position(); const float angle = quat.angle(); for(FrameContainer::iterator it=frames.begin();it!=frames.end();it++){ qglviewer::Quaternion q((*it)->transformOf(world), angle); (*it)->rotate(q); qglviewer::Quaternion q_world(world, angle); (*it)->setPosition(pos + q_world.rotate((*it)->position() - pos)); } } #endif // MANIPULATEDFRAMESETCONSTRAINT_H
true
18b8b4f009eade52f6632030e4a2c8e6c6ae2b9b
C++
Nurullah1313/C-Temel
/Bölüm 4 [Diziler ve Katarlar]/Katar7.cpp
UTF-8
329
2.765625
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; int main() { char katar1[50]="selam", katar2[50]="millet"; strcpy(katar1, "Turkiye"); strcpy(katar2, " Cumhuriyeti"); strcat(katar1, katar2); for(int i=0; katar1[i]; i++) cout<<katar1[i]<<endl; cout<<"Katar1 uzunlugu:"<<strlen(katar1)<<endl; return 0; }
true
0c0c3fa6583d949465fff1511f5d73b9b4ce790e
C++
rollschild/MyAlgorithms
/BucketSort.cpp
UTF-8
1,228
3.890625
4
[]
no_license
#include <iostream> #include <vector> #include <list> #include "InsertionSort.h" using namespace std; void Print(vector<float>& vec); void InsertionSort(vector<float>& float_vec) { int size = float_vec.size(); for(int j = 1; j < size; ++j) { int i = j - 1; float key = float_vec[j]; while(i >= 0 && float_vec[i] > key) { float_vec[i + 1] = float_vec[i]; --i; } float_vec[i + 1] = key; } } vector<float> BucketSort(vector<float>& vec) { int size = vec.size(); vector<vector<float>> buckets(size); // you need to make buckets[i] an empty list for(auto& v : buckets) { v.clear(); } for(auto v : vec) { buckets[(int)(size * v)].push_back(v); } for(auto& v : buckets) { // Print(v); InsertionSort(v); } vector<float> results; for(auto& v : buckets) { results.insert(results.end(), v.begin(), v.end()); } return results; } void Print(vector<float>& vec) { for(auto v : vec) { cout << v << " "; } cout << endl; } int main() { vector<float> vec{0.11, 0.88, 0, 0.006, 0.67, 0.99}; cout << "Original array: \n"; Print(vec); auto result = BucketSort(vec); cout << "Array after sorting: \n"; Print(result); return 0; }
true
43e5bc58aae862c52bc680501ad98fef4f6e4eb2
C++
NiklaasC/moth
/proximity.cpp
UTF-8
1,484
3.3125
3
[]
no_license
// IR Proximity Sensor #include "proximity.h" // Constructor // Sets the pin used to communicate with the IR Proximity Sensor Proximity::Proximity(int setPin) { pin = setPin; // Initialise all the data to 0 for (int index = 0; index < dataSize; index++) { data[index] = 0; differential[index] = 0; } } // Updates the value from the IR sensor. Creates a smoothed value and a smoothed differential value. void Proximity::update() { // Remove the old index value from the running total total = total - data[dataIndex]; // Read the new value data[dataIndex] = analogRead(pin); // Add the new value to the running total total = total + data[dataIndex]; // Calculate new differential value differentialTotal = differentialTotal - differential[dataIndex]; if (dataIndex == 0) { differential[dataIndex] = data[dataIndex] - data[dataSize-1]; } else { differential[dataIndex] = data[dataIndex] - data[dataIndex-1]; } differentialTotal = differentialTotal + differential[dataIndex]; // Increment the index dataIndex = dataIndex + 1; if (dataIndex >= dataSize) { dataIndex = 0; } // Calculate moving average average = total / dataSize; differentialAverage = differentialTotal / dataSize; } // Get the smoothed value from the IR sensor int Proximity::getAverage() { return average; } // Get the smoothed differential value from the IR sensor int Proximity::getDifferential() { return differentialAverage; }
true
35b1084169f60c1485766a1ed7127bdc71e215c2
C++
IgnacioAstorga/Caveman-Ninja
/CavemanNinja/WeaponPickup.cpp
WINDOWS-1250
1,193
2.78125
3
[]
no_license
#include "WeaponPickup.h" #include "SpriteRendererComponent.h" #include "BasicAnimation.h" #include "CircleColliderComponent.h" #include "ColliderTypes.h" #include "OnWeaponPickUpComponent.h" #include "EntityLifetimeComponent.h" #define PICKUP_LIFETIME 20.0f WeaponPickup::WeaponPickup(WeaponPickupType type, string name, float positionX, float positionY) : Entity(name, positionX, positionY) { this->type = type; OnCreate(); } void WeaponPickup::OnCreate() { // Crea la animacin adecuada de la entidad BasicAnimation* animation = new BasicAnimation(128, 64, 4, 2, 0.0f, false); animation->frames.push_back({ type % 4, type / 4 }); // Crea el vector con los tipos de colliders ("{}" no soporta un solo elemento) vector<int> collisionsTypes; collisionsTypes.push_back(PLAYER); // Crea los componentes de la entidad AddComponent(new SpriteRendererComponent("assets/images/pickups_weapons.png", animation, -16, -32)); AddComponent(new CircleColliderComponent(16, collisionsTypes, 0, -16, PICKUP)); AddComponent(new OnWeaponPickUpComponent(type)); AddComponent(new EntityLifetimeComponent(PICKUP_LIFETIME)); } void WeaponPickup::OnDestroy() { // En principio no hace nada }
true
94a85b97267b5645a06ac015e714cc75b2a28188
C++
mewa/mesh_optimizer
/mesh_optimizer/MeshDecimator.cpp
UTF-8
2,677
2.59375
3
[]
no_license
#include "MeshDecimator.h" #include <map> #include "Graph.h" using namespace mewa; using namespace mewa::decimator; MeshDecimator::MeshDecimator() { } MeshDecimator::~MeshDecimator() { if (mGraph) delete mGraph; } void MeshDecimator::constructGraph(Mesh* mesh) { if (mGraph) { delete mGraph; mGraph = NULL; } mGraph = new Graph(mesh); } Mesh* MeshDecimator::decimate(Mesh* mesh) { assert(mesh->indices().size() % 3 == 0); constructGraph(mesh); mGraph->collapse(); //auto decimatedMesh = new Mesh(mGraph->vertices(), mGraph->indices(), mesh->material()); //assert(decimatedMesh->indices().size() % 3 == 0); return mGraph->mesh(mesh->material()); //float xMin = mesh.vertices()[0].Position.x; //float yMin = mesh.vertices()[0].Position.y; //float zMin = mesh.vertices()[0].Position.z; //float xMax = mesh.vertices()[0].Position.x; //float yMax = mesh.vertices()[0].Position.y; //float zMax = mesh.vertices()[0].Position.z; //std::map<Vertex, GLuint> idxMap; //for (auto it = mesh.vertices().begin() + 1; it != mesh.vertices().end(); ++it) { // float x = it->Position.x; // float y = it->Position.y; // float z = it->Position.z; // // if (x < xMin) // xMin = x; // if (y < yMin) // yMin = y; // if (z < zMin) // zMin = z; // if (x > xMax) // xMax = x; // if (y > yMax) // yMax = y; // if (z > zMax) // zMax = z; //} //glm::vec3 const vecMin(xMin, yMin, zMin); //glm::vec3 const vecMax(xMax, yMax, zMax); //glm::vec3 const diff = vecMax - vecMin; //float const xUnit = diff.x / 100.0f; //float const yUnit = diff.y / 100.0f; //float const zUnit = diff.z / 100.0f; //size_t const xSize = diff.x / xUnit + 1; //size_t const ySize = diff.y / yUnit + 1; //size_t const zSize = diff.z / zUnit + 1; //std::vector<std::vector<std::vector<std::vector<Vertex> > > > buckets( // xSize, std::vector<std::vector<std::vector<Vertex> > > //1d // (ySize, std::vector<std::vector<Vertex> > //2d // (zSize) //3d // )); //std::vector<std::vector<std::vector<std::vector<GLuint> > > > idxBuckets( // xSize, std::vector<std::vector<std::vector<GLuint> > > //1d // (ySize, std::vector<std::vector<GLuint> > //2d // (zSize) //3d // )); //for (auto it = mesh.vertices().begin(); it != mesh.vertices().end(); ++it) { // size_t ix = (it->Position.x - vecMin.x) / xUnit; // size_t iy = (it->Position.y - vecMin.y) / yUnit; // size_t iz = (it->Position.z - vecMin.z) / zUnit; // buckets[ix][iy][iz].push_back(*it); //} //for (int i = 0; i < xSize; ++i) { // for (int j = 0; j < ySize; ++j) { // for (int k = 0; k < zSize; ++k) { // // } // } //} //return mesh; } DecimationOperator::~DecimationOperator() {}
true
09cd026316755758ef6d4e07c4c4f9d5d464d6e4
C++
ckrisgarrett/minesweeper
/main_window.cpp
UTF-8
1,783
2.546875
3
[]
no_license
#include "main_window.h" #include "mine_widget.h" #include "game_logic.h" #include <QPushButton> #include <QGridLayout> #include <QLCDNumber> #include <QLabel> static QLabel *s_bombs_label; static Mine_Widget *s_mine_widget; static QPushButton *s_reset_button; Main_Window::Main_Window() { QVBoxLayout *main_layout = new QVBoxLayout(); QWidget *central_widget = new QWidget(); central_widget->setLayout(main_layout); setCentralWidget(central_widget); s_bombs_label = new QLabel(); QFont font; font.setPointSize(12); s_bombs_label->setFont(font); main_layout->addWidget(s_bombs_label); s_mine_widget = new Mine_Widget(); main_layout->addWidget(s_mine_widget); QWidget *bottom_widget = new QWidget(); QHBoxLayout *bottom_layout = new QHBoxLayout(); bottom_layout->addStretch(); s_reset_button = new QPushButton("Reset"); bottom_layout->addWidget(s_reset_button); bottom_layout->addStretch(); bottom_widget->setLayout(bottom_layout); main_layout->addWidget(bottom_widget); connect( s_reset_button, QPushButton::clicked, this, Main_Window::reset_button_click); } Main_Window::~Main_Window() { } void display_num_bombs(int num_bombs) { char text[100]; sprintf(text, "Bombs not flagged: %d", num_bombs); s_bombs_label->setText(text); } void Main_Window::reset_button_click() { reset_game(); s_mine_widget->reset(); this->setWindowTitle("Minesweeper"); s_mine_widget->setDisabled(false); s_mine_widget->update(); } void game_win() { s_bombs_label->setText("You Win"); s_mine_widget->setDisabled(true); } void game_lose() { s_bombs_label->setText("You Lose"); s_mine_widget->setDisabled(true); }
true
2c459f48a28d5e2d06910a003f6ff1072fd9cf90
C++
grncbg/ANSL-NetworkSimulator
/source/Random.cpp
UTF-8
967
3.078125
3
[ "MIT" ]
permissive
#include "Random.hpp" #include <boost/random.hpp> #include <boost/random/random_device.hpp> // // class Random // template <class T> Random<T>::Random() { boost::random::random_device seed_gen; this->engine = new boost::random::mt19937_64(seed_gen()); } template <class T> Random<T>::~Random() { delete(this->engine); } template <class T> T Random<T>::operator()() const { return get(); } // // class Poison // Poisson::Poisson(double arg) { this->poisson = new boost::random::poisson_distribution<int, double>(arg); } Poisson::~Poisson() { delete(this->poisson); } int Poisson::get() const { return (*poisson)(*engine); } // // class Exponential // Exponential::Exponential(double arg) { this->exponential = new boost::random::exponential_distribution<double>(arg); } Exponential::~Exponential() { delete(this->exponential); } double Exponential::get() const { return (*exponential)(*engine); }
true
4c21b0d13c3231cb7fe6e7d2fa9e841becce2b77
C++
brianwesthoven/Variadic
/variadic.h
UTF-8
4,242
3.375
3
[]
no_license
#pragma once #include <type_traits> /* * */ namespace ns { namespace mp { /* index_of: * returns the index of the first equal type found to the first template parameter in the list. * examples: * 1) index_of<A, A, B, C, D>() //0 * 2) index_of<A, B, C, D, A>() //4 */ template<class T, class... Us> struct index_of; template<class T, class U, class... Vs> struct index_of<T, U, Vs...> : std::integral_constant<std::size_t, index_of<T, Vs...>() + 1> { }; template<class T, class... Us> struct index_of<T, T, Us...> : std::integral_constant<std::size_t, 0> { }; template<class T> struct index_of<T> : std::integral_constant<std::size_t, 9000> { //static_assert(false, ""); }; /* type_at: * aliases the type at a given index in a list. * examples: * 1) using a_type = type_at<0, a, b, c, d> //a * 2) using d_type = type_at<3, a, b, c, d> //d */ namespace detail { template<std::size_t N, class T, class... Us> struct type_at; template<std::size_t N, class T, class... Us> struct type_at { using type = typename type_at<N - 1, Us...>::type; }; template<class T, class... Us> struct type_at<0, T, Us...> { using type = T; }; } template<std::size_t N, class T, class... Us> using type_at = typename detail::type_at<N, T, Us...>::type; /* contains: * returns true or false if a type is in a list * examples: * 1) contains<c, b, c, d, e>() //true * 2) contains<c, a, d, e, a>() //false * */ template<class T, class... Us> struct contains; template<class T, class U, class... Vs> struct contains<T, U, Vs...> : contains<T, Vs...> { }; template<class T, class... Us> struct contains<T, T, Us...> : std::true_type { }; template<class T> struct contains<T > : std::false_type { }; /* convert: * aliases a variadic template container from another container * examples: * 1) using tuple1 = convert<type_list<a, b, c>, std::tuple>; //tuple1 = std::tuple<a, b, c> * 2) using list1 = type_list<a, b, c>; * using tuple2 = convert<list1, std::tuple> //tuple2 = std::tuple<a, b, c> */ namespace detail { template<class T, template <class...> class U> struct convert; template<template <class...> class T, class... Ts, template <class...> class U> struct convert<T<Ts...>, U> { using type = U<Ts...>; }; } template<class T, template <class...> class U> using convert = typename detail::convert<T, U>::type; /* mutate: * aliases a variadic template container with its elements changed from another container * examples: * 1) using list1 = type_list<a, b>; //type_list<a, b> * using vector_list = mutate<list1, vector> //type_lst<vector<a, allocator<a>>, vector<b, allocator<b>>> */ namespace detail { template<class T, template <class...> class U> struct mutate; template<template <class...> class T, class... Ts, template <class...> class U> struct mutate<T<Ts...>, U> { using type = T<U<Ts>...>; }; } template<class T, template <class...> class U> using mutate = typename detail::mutate<T, U>::type; /* type_list */ template<class... Ts> struct type_list { type_list() = delete; ~type_list() = delete; }; } }
true
8ca9491ee6d70a2723c93a0a744b8c5d0255afd1
C++
JonnyKong/UCLA-CS130-Software-Engineering
/Assignment7_Multhreading/bigbear/src/http_request.cc
UTF-8
8,151
3.015625
3
[]
no_license
#include "http_request.h" #include <queue> #include <iostream> #include <boost/log/trivial.hpp> #include <boost/algorithm/string.hpp> bool HttpRequest::setMethod(std::string method) { if (method.empty()) { // handle null pointer exception } // TODO: implement function if (method.compare("GET") == 0) { this->requestMethod = GET; // std::cout << method << std::endl; return true; } return false; } bool HttpRequest::setURI(std::string requestTarget) { // std::cout << requestTarget << std::endl; this->requestURI = requestTarget; return true; } bool HttpRequest::setVersion(std::string version) { // std::cout << version << std::endl; this->httpVersion = version; return true; } bool HttpRequest::setBody(std::string body) { this->requestBody = body; return true; } bool HttpRequest::setHeaderFields(std::string headerField, std::string headerValue) { // case-insensitive compare the header field with legal header field strings // (is there a cleaner way of doing this? Hashing won't work because the comparison // needs to be case-insensitive) // std::cout << headerField << std::endl << "to: " << headerValue << std::endl; if (boost::iequals(headerField, "Accept")) { this->headerFields[ACCEPT] = headerValue; } else if (boost::iequals(headerField, "Accept-Charset")) { this->headerFields[ACCEPT_CHARSET] = headerValue; } else if (boost::iequals(headerField, "Accept-Encoding")) { this->headerFields[ACCEPT_ENCODING] = headerValue; } else if (boost::iequals(headerField, "Accept-Language")) { this->headerFields[ACCEPT_LANGUAGE] = headerValue; } else if (boost::iequals(headerField, "Connection")) { this->headerFields[CONNECTION] = headerValue; } else if (boost::iequals(headerField, "Content-Length")) // this specifies the body's length in bytes { this->headerFields[CONTENT_LENGTH] = headerValue; } else if (boost::iequals(headerField, "Host")) { this->headerFields[HOST] = headerValue; } else if(boost::iequals(headerField, "User-Agent")) { this->headerFields[USER_AGENT] = headerValue; } return true; } // this method expects the HTTP request in string format and sets the fields in the HttpRequest object // The input should only be the string representation of ONE single request bool HttpRequest::parseHttpRequest(std::string requestString) { if(requestString.empty()) { // TODO: handle null ptr exception } unparsedRequestString = requestString; BOOST_LOG_TRIVIAL(trace) << "Parsing HTTP request"; // divide up the requestString into lines std::vector<std::string> requestLines; // requestLines contains all parts of the request before the \r\n\r\n sequence int lineBeginning = 0; // index of the char at the beginning of each line int requestBodyStart; bool requestEndFound = false; for (int i = 0; i < requestString.length(); i++) { // loop through each char in request, and if you see a new line, // push that line to the requestLines vector if (requestString.substr(i,4) == "\r\n\r\n") { int lineLength = i - lineBeginning; // number of chars in the line std::string subString = requestString.substr(lineBeginning, lineLength); // the line requestLines.push_back(subString); requestBodyStart = i + 4; // the index of the request body's first char, if it exists requestEndFound = true; break; } else if (requestString[i] == '\r') { int lineLength = i - lineBeginning; // number of chars in the line std::string subString = requestString.substr(lineBeginning, lineLength); // the line requestLines.push_back(subString); lineBeginning = i + 2; // update the index of the char in the next line } } isComplete = requestEndFound; bool methodFound = false; bool targetFound = false; bool versionFound = false; bool headersFound = false; for (int lineNumber = 0; lineNumber < requestLines.size(); ++lineNumber) { printf("parse this line: %s\n", requestLines[lineNumber].c_str()); // first line is parsed out for the http method and version if (lineNumber == 0) { int targetBegin; int versionBegin; int methodBegin = 0; // loop through each character in the line for(std::string::iterator characterPtr = requestLines[lineNumber].begin(); characterPtr != requestLines[lineNumber].end(); characterPtr++) { // white space delimits the method, target and version. TODO: There's definitely a cleaner // way to do this via the string's member functions if (*characterPtr == ' ' || *characterPtr == '\n' || *characterPtr == '\r') { if (!methodFound) { int nCharsInRequestMethod = characterPtr - requestLines[lineNumber].begin(); methodFound = setMethod(requestLines[lineNumber].substr(methodBegin, nCharsInRequestMethod)); targetBegin = methodBegin + nCharsInRequestMethod + 1; } else if (!targetFound) { int nCharsInRequestTarget = characterPtr - targetBegin - requestLines[lineNumber].begin(); targetFound = setURI(requestLines[lineNumber].substr(targetBegin, nCharsInRequestTarget)); versionBegin = targetBegin + nCharsInRequestTarget + 1; } // else if (!versionFound) // { // int nCharsInVersion = characterPtr - versionBegin - requestLines[lineNumber].begin(); // versionFound = setVersion(requestLines[lineNumber].substr(versionBegin, nCharsInVersion)); // } } } int nCharsInVersion = requestLines[lineNumber].end() - versionBegin - requestLines[lineNumber].begin(); versionFound = setVersion(requestLines[lineNumber].substr(versionBegin, nCharsInVersion)); } // if we are not on the first line, each subsequent line contains a header field else { std::string headerField; std::string headerValue; // TODO: error handling for case if you cannot find a colon int colonPosition = requestLines[lineNumber].find(":"); headerField = requestLines[lineNumber].substr(0, colonPosition); headerValue = requestLines[lineNumber].substr(colonPosition + 2, requestLines[lineNumber].length()-colonPosition); headersFound = setHeaderFields(headerField, headerValue); } } bool bodyFound = false; // TODO: sometimes, the content length isn't a numerical value (like in the readme)?? // need to handle that case // a body will exist if there is a specified content length in the headers (is this true?) // if (this->headerFields.find(CONTENT_LENGTH) != this->headerFields.end()) // { // // sorry about this line -- will clean it up. Just supposed to set the http body // // attribute based on the content length // bodyFound = setBody(requestString.substr(requestBodyStart, std::stoi(this->headerFields[CONTENT_LENGTH]))); // } if (methodFound && targetFound && versionFound && headersFound && isComplete) return true; else { return false; } } bool HttpRequest::finishParsingRequest(std::string partialRequest) { // concatenate incomplete request string with remaining request unparsedRequestString = unparsedRequestString + partialRequest; // reparse the request and return if successful return parseHttpRequest(unparsedRequestString); }
true
f7c36caccf7f5fd0606447561d714ee9ee32ad7d
C++
QuantumComputingLab/qpixlpp
/test/frqi/sfwht_gray.cpp
UTF-8
4,681
2.53125
3
[ "BSD-3-Clause-LBNL" ]
permissive
// (C) Copyright Daan Camps, Mercy Amankwah, E. Wes Bethel, Talita Perciano and // Roel Van Beeumen #include "qpixl/frqi/util.hpp" #include <chrono> #include <random> #include <cstring> #ifdef _OPENMP #include <omp.h> #endif using TP = std::chrono::time_point< std::chrono::high_resolution_clock > ; void tic( TP& t_bgn ) { t_bgn = std::chrono::high_resolution_clock::now() ; } // tic void tic( const std::string name , TP& t_bgn ) { std::cout << name << std::endl ; t_bgn = std::chrono::high_resolution_clock::now() ; } // tic double toc( const TP& t_bgn ) { TP t_end = std::chrono::high_resolution_clock::now() ; double time = std::chrono::duration< double >(t_end - t_bgn).count() ; return time ; } // toc double toc( const TP& t_bgn , TP& t_end ) { t_end = std::chrono::high_resolution_clock::now() ; double time = std::chrono::duration< double >(t_end - t_bgn).count() ; std::cout << " " << time << "s\n" ; return time ; } // toc template <typename T> auto pow2Vector( const size_t k ) { // random entries std::random_device rd ; std::mt19937_64 gen( rd() ) ; std::uniform_real_distribution<> dis( 0.0, 1.0 ) ; // generate vector std::vector< T > v( size_t(1)<<k ) ; for ( size_t i = 0; i < (size_t(1)<<k); i++ ) { v[i] = dis(gen) ; } return v ; } template <typename T> int timings( const std::vector< size_t>& N, const int outer , const int inner ){ std::cout << "outer = " << outer << ", inner = " << inner << std::endl ; //problem dimension std::cout << "qubits = " << N.front() << ":" << N.back() ; #ifdef _OPENMP std::cout << ", omp_get_max_threads() = " << omp_get_max_threads() ; #endif std::cout << std::endl << std::endl ; // timing variables TP t_bgn ; TP t_end ; std::vector< int > qubits ; std::vector< double > time_sfwht, time_gray ; for ( size_t n : N ) { std::cout << "n = " << n << ":" << std::endl ; qubits.push_back( n ) ; // outer loop for ( int o = 0; o < outer; o++ ) { // generate random vectors tic( " * Constructing random vectors..." , t_bgn ) ; std::vector< std::vector< T > > vectors ; for ( int i = 0; i < inner; i++ ) { vectors.push_back( pow2Vector< T >( n ) ); } toc( t_bgn , t_end ) ; // scaled fast Walsh-Hadamard transform tic( " * fast Walsh-Hadamard transform..." , t_bgn ) ; for ( int i = 0; i < inner; i++ ) { qpixl::frqi::sfwht( vectors[i] ); } const double ttot_sfwht = toc( t_bgn , t_end ) / inner ; if ( o == 0 ) time_sfwht.push_back( ttot_sfwht ) ; else if ( ttot_sfwht < time_sfwht.back() ) time_sfwht.back() = ttot_sfwht ; // in-place Gray permutation tic( " * Gray permutation..." , t_bgn ) ; for ( int i = 0; i < inner; i++ ) { qpixl::frqi::grayPermutation( vectors[i] ); } const double ttot_gray = toc( t_bgn , t_end ) / inner ; if ( o == 0 ) time_gray.push_back( ttot_gray ) ; else if ( ttot_gray < time_gray.back() ) time_gray.back() = ttot_gray ; } } // output std::cout << "results = [" << std::endl ; for ( size_t i = 0; i < time_sfwht.size(); i++ ) { std::printf( "%6i, %10.4e, %10.4e" , qubits[i] , time_sfwht[i], time_gray[i] ) ; if ( i == time_sfwht.size() - 1 ) { std::printf( "];\n" ) ; } else { std::printf( " ;\n" ) ; } } std::cout << std::endl ; // successful return 0 ; } int main( int argc , char *argv[] ) { // parse user input char type = 'd' ; if ( argc > 1 ) type = argv[1][0] ; int nmin = 3 ; if ( argc > 2 ) nmin = std::stoi( argv[2] ) ; int nmax = 20 ; if ( argc > 3 ) nmax = std::stoi( argv[3] ) ; int step = 1 ; if ( argc > 4 ) step = std::stoi( argv[4] ) ; int outer = 1 ; if ( argc > 5 ) outer = std::stoi( argv[5] ) ; int inner = 1 ; if ( argc > 6 ) inner = std::stoi( argv[6] ) ; std::vector< size_t > N ; // linear scale for ( int i = nmin; i <= nmax; i += step ) { N.push_back( i ) ; } if ( N.back() != nmax ) { N.push_back( nmax ) ; } int r = 0 ; if ( type == 's' ) { // float std::cout << "\n+++ SFWHT and Gray permutation (float) +++\n\n" ; r = timings< float >( N , outer , inner ) ; if ( r != 0 ) return r ; } else if ( type == 'd' ) { // double std::cout << "\n+++ SFWHT and Gray permutation (double) +++\n\n" ; r = timings< double >( N , outer , inner ) ; if ( r != 0 ) return r + 1000 ; } else { return -2 ; } // successful std::cout << ">> end SFWHT and Gray permutation <<" << std::endl ; return 0 ; }
true
96e574eea4975fcc48b60ed0c440b38041aa94bd
C++
danbalarin/Cpp_Skola
/Zkouseni/23-4-Test/mainwindow.cpp
UTF-8
1,479
2.546875
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include "qstring.h" #include "qmessagebox.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { double a = ui->a->value(); double b = ui->b->value(); int ret = 0; if(b==0){ QMessageBox msgBox; msgBox.setText("Nelze delit nulou!!!"); msgBox.setInformativeText("Vypocist bez deleni?"); msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Save); ret = msgBox.exec(); if(ret>20000) return; } ui->result->setText(""); QString pomocny = "Soucet:\n" + QString::number(a) + "+" + QString::number(b) + "=" + QString::number(a+b) ; ui->result->append(pomocny); ui->result->append(""); pomocny = "Rozdil:\n" + QString::number(a) + "-" + QString::number(b) + "=" + QString::number(a-b) ; ui->result->append(pomocny); ui->result->append(""); pomocny = "Soucin:\n" + QString::number(a) + "*" + QString::number(b) + "=" + QString::number(a*b) ; ui->result->append(pomocny); ui->result->append(""); if(ret==0) pomocny = "Podil:\n" + QString::number(a) + "/" + QString::number(b) + "=" + QString::number(a/b) ; else pomocny = "Podil:\nNepocitano"; ui->result->append(pomocny); }
true
4f25224c22f5c8f3e5c7bbdc2a86beaa9cea87a1
C++
sshyran/Computational-Agroecology
/environment/plant_builder.cc
UTF-8
1,337
2.5625
3
[]
no_license
#include "plant_builder.h" #include "environment/meteorology.h" #include "environment/plant.h" namespace environment { bool PlantBuilder::RegisterPlant(const std::string &model_name, const PlantGenerator &generator) { if (!models_.count(model_name)) { models_[model_name] = generator; return true; } return false; } void PlantBuilder::UnregisterPlant(const std::string &model_name) { models_.erase(model_name); } Plant *PlantBuilder::NewPlant(const std::string &model_name, const Meteorology &meteorology) { return NewPlant(model_name, meteorology, PlantParams()); } Plant *PlantBuilder::NewPlant(const std::string &model_name, const Meteorology &meteorology, const PlantParams &overrides) { if (models_.count(model_name)) { Plant *p = models_[model_name](meteorology); p->SetParams(overrides); return p; } return nullptr; } std::vector<std::string> PlantBuilder::GetPlantList() { std::vector<std::string> plant_list; plant_list.reserve(models_.size()); for (const auto &p : models_) { plant_list.push_back(p.first); } return plant_list; } // Definition std::unordered_map<std::string, PlantGenerator> PlantBuilder::models_; } // namespace environment
true
f8067ad1ead31a4a1790dc0944ce0dd48002bf60
C++
ZzQhXdH/Pizza-MCU
/User/Driver/Motor.h
UTF-8
1,314
2.640625
3
[]
no_license
#ifndef __MOTOR_H #define __MOTOR_H #include "Driver/PositionSwitch.h" #include <rtx_os.h> class Motor { public: enum Dir { CW = 0x01, CCW = 0x02, Brake = 0x03, }; enum Error { TimeOut = 0x81, // 超时 Locked = 0x82, // 堵转 Ok = 0x83, // OK }; public: static void vInit(void); private: static void vSetDir(Dir dir = Brake); /** 取物门电机控制 **/ inline static void vEnablePickingDoor(void) { GPIOC->BRR = 0x80; } inline static void vDisablePickingDoor(void) { GPIOC->BSRR = 0x80; } /** 内推货电机控制 **/ inline static void vEnableInteriorPush(void) { GPIOC->BRR = 0x100; } inline static void vDisableInteriorPush(void) { GPIOC->BSRR = 0x100; } /** 保温门电机控制 **/ inline static void vEnableThermalDoor(void) { GPIOC->BRR = 0x200; } inline static void vDisableThermalDoor(void) { GPIOD->BSRR = 0x200; } /** 外升降电机控制 **/ inline static void vEnableExternalUpDown(void) { GPIOC->BRR = 0x2000; } inline static void vDisableExternalUpDown(void) { GPIOC->BSRR = 0x2000; } /** 外推货电机控制 **/ inline static void vEnableExternalPush(void) { GPIOC->BRR = 0x4000; } inline static void vDisableExternalPush(void) { GPIOC->BSRR = 0x4000; } private: Motor(void) {} }; #endif
true
81342ca0a8260d30e0472bcbc791bd6cfbd69fac
C++
GrimshawA/librazer
/src/razer/frontend/Parser/TokenParser.h
UTF-8
796
2.78125
3
[]
no_license
#ifndef RZTOKENS_H__ #define RZTOKENS_H__ #include <string> #include <vector> #include <razer/frontend/Parser/Token.h> /** \class RzTokenParser \brief Generates a stream of token from a source program so it can be parsed meaningfully */ class RzTokenParser { public: RzTokenParser(); /// Get the list of collected tokens std::vector<RzToken>& getTokens(); /// Clear the cached tokens void clear(); void print(); void tokenize(const std::string& src); private: RzToken getToken(); struct SourceCursor { int line; int col; }; public: std::string program_source; int i; std::vector<RzToken> tokens; private: SourceCursor m_cursor; }; #endif // RZTOKENS_H__
true
6c3ce38751e3f942045150d0a7fc7372ddc3a84b
C++
KFlaga/FlagRTS
/GameCore/IEventGenerator.h
UTF-8
2,448
3.265625
3
[]
no_license
#pragma once namespace ORTS { // Common interface for classes that provides events for rest of game // ( like input observer, camera observer, units observer ) // Each EventGenerator have TypeId which identifies event family // EventGenerators get notify requests for objects that want action to // be done when event occurs : any object can register ITrigger with // specific event type ( like key pressed ), condition ( like key == Escape ) // and action. When event type occurs condition is checked, and if // is fulfilled action is taken. // Each event type is bind to list of triggers and in each update // only subscribed events ( list's size > ) are checked if occurred class IEventGenerator { protected: TypeId _finalType; // Type of subclass. Should be set after base class initialization typedef std::list<RefPtr<ITrigger>> TriggerList; typedef std::map<TypeId, RefPtr<TriggerList>> EventMap; EventMap _events; public: // In constructor lists for all event types should be allocated IEventGenerator() { _finalType = GetTypeId<IEventGenerator>(); } // Empty destructor - all triggers should be destoryed automaticaly virtual ~IEventGenerator() { } // Returns type of final subclass TypeId GetFinalType() const { return _finalType; } // Checks all registered event if occured and if occured + // condition is met, action is performed virtual void ProcessEvents() { for(auto eventIt = _events.begin(); eventIt != _events.end(); ++eventIt) { if(eventIt->second->size() > 0) { if( CheckIfEventOccured(eventIt->second) ) { for(auto trigIt = eventIt->second->begin(); trigIt != eventIt->second->end(); ++trigIt) { ProcessEventInteral((*trigIt)); } } } } } // Adds trigger for Trigger's event type to be fired void RegisterTrigger(const RefPtr<ITrigger>& trigger) { FindTriggerList(trigger)->push_back(trigger); } // Removes trigger from Trigger's event type list void UnregisterTrigger(const RefPtr<ITrigger>& trigger) { FindTriggerList(trigger)->remove(trigger); } protected: RefPtr<TriggerList>& FindTriggerList(const RefPtr<ITrigger>& t) { return _events.find(t->GetEventType())->second; } virtual bool CheckIfEventOccured(const RefPtr<ITrigger>& ev) { return ev->GetEvent()->CheckEventOccured(); } virtual void ProcessEventInteral(const RefPtr<ITrigger>& trigger) = 0; }; }
true
0808f1810c93fcd8164bc948c722a6effbd3a40d
C++
PenguinBoyTC/DataStructure_C
/Lab06/DoubleHashing.hpp
UTF-8
2,591
3.59375
4
[]
no_license
template <typename T> DoubleHashing<T>::DoubleHashing(int m, int k, int p)//constructor { m_m = m; m_k = k; m_p = p; numOfEle = 0; m_hashtable = new Bucket<T> [m_m]; } template <typename T> DoubleHashing<T>::DoubleHashing()//constructor { m_m = 53; m_k = 10; m_p = 13; numOfEle = 0; m_hashtable = new Bucket<T> [m_m]; } template <typename T> DoubleHashing<T>::~DoubleHashing()//distructor { delete[] m_hashtable;//delete hash table } template <typename T> bool DoubleHashing<T>::Insert(T value)//insert value to hash table { if(Hash(value)!=-1) { m_hashtable[Hash(value)].setItem(value); numOfEle++; return true; } else { return false; } } template <typename T> bool DoubleHashing<T>::Remove(T value)//delete value from hash table { int hx = value % m_m; int hxx = m_p - (value % m_p); for(int i=0;i<=m_k-1;i++) { int hn = (hx + i * hxx) % m_m; if(m_hashtable[hn].AlwaysEmpty()) { return false; } else if(m_hashtable[hn].getItem() == value) { m_hashtable[hn].desetItem(); numOfEle--; return true; } } return false; } template <typename T> void DoubleHashing<T>::Print()// print all value in the hash table { for(int i=0; i<m_m; i++) { if(!m_hashtable[i].isEmpty()) { std::cout<<i<<": "<<m_hashtable[i].getItem()<<std::endl; } } } template <typename T> int DoubleHashing<T>::Hash(T value)//return the index for key value { int hx = value % m_m; int hxx = m_p - (value % m_p); for(int i=0;i<=m_k-1;i++) { int hn = (hx + i * hxx) % m_m; if(m_hashtable[hn].isEmpty()) { return hn; } else if(m_hashtable[hn].getItem()==value) { return -1; } } return -1; } template <typename T> bool DoubleHashing<T>::Find(T value)//return true if the key value is in the hashtable and false otherwise { int hx = value % m_m; int hxx = m_p - (value % m_p); for(int i=0;i<=m_k-1;i++) { int hn = (hx + i * hxx) % m_m; if(m_hashtable[hn].AlwaysEmpty()) { return false; } else if(m_hashtable[hn].getItem() == value) { return true; } } return false; } template <typename T> float DoubleHashing<T>::loadFactor() { //std::cout<<"Num of Ele: "<<numOfEle<<"/"<<m_m<<std::endl; return((float)numOfEle/m_m); }
true
081738a2522cbc1a6406232f0fcb0c6ecb05c71b
C++
Denhonator/TextAdventure
/TextAdventure/Game.h
UTF-8
638
2.53125
3
[]
no_license
#pragma once #include "Util.h" #include "Resources.h" class Game { public: Game(); ~Game(); std::string ProcessCommand(std::string input, int player=0); void AddPlayer(std::string name, std::string newname = ""); private: unsigned int players = 0; unsigned int curPlayer = 0; unsigned int progress = 0; Encounter currentEnc; std::vector<Unit> units; std::string Encounter(std::string arg1, std::string arg2); std::string GetItem(std::string arguments = ""); std::string PrintStats(Stats stats, char type); std::string PrintItem(std::string name, bool detail); std::string PrintUnit(Unit u, std::string arguments = ""); };
true
02d5d169cd596c45742f9bc0638ded0d4a3eb821
C++
GISjingjie/DataStruct
/DataStruct/P40_5_前半部分小于表头节点_后半部分大于表头.cpp
UTF-8
684
3.140625
3
[]
no_license
#include <Stdio.h> #include <Stdlib.h> void Adjust(int a[],int len,int i) { int tmp=a[i]; for(int son=i*2+1;son<len;son=son*2+1) { if(son+1<len&&a[son+1]>a[son]) { son++; } if(a[son]>tmp) { a[i]=a[son]; i=son; }else { break; } } a[i]=tmp; } void heapsort(int a[],int len) { for(int i=len/2;i>=0;i--) { Adjust(a,len,i); } for(int j=len-1;j>0;j--) { int tmp=a[0]; a[0]=a[j]; a[j]=tmp; Adjust(a,j,0); } } void print(int len,int a[]) { for(int i=0;i<len;i++) { printf("%d->",a[i]); } } int main() { int a[]={85,7,8,9,6,315,122,555,412,12,21,30,25,88,789,125}; int len=sizeof(a)/sizeof(a[0]); heapsort(a,len); print(len,a); }
true
33b8971daff09cbf08e4d8d353af52e4f85a714d
C++
Shota190718/Racing
/Racing/Engine/Audio.h
SHIFT_JIS
1,427
2.84375
3
[]
no_license
#pragma once #pragma once #include <vector> #include <string> #include "Global.h" #include "Sound.h" //----------------------------------------------------------- //ʉǗ //----------------------------------------------------------- namespace Audio { //ЂƂ‚̃TEh̏ struct AudioData { //t@C std::string fileName; //TEhobt@iǂݍ񂾃TEhj LPDIRECTSOUNDBUFFER* psoundBuffer; //RXgN^ AudioData() :psoundBuffer(nullptr) { } }; // //FhWnd EBhEnh void Initialize(HWND hWnd); //TEht@C[h //łɓÕt@C[hς݂̏ꍇ́Ãf[^̔ԍԂ //FfileName@t@C //ߒlF̃TEhf[^Ɋ蓖Ăꂽԍ int Load(std::string fileName); //Đ //Fhandle ĐTEh̔ԍ void Play(int handle); //~ //Fhandle ~߂TEh̔ԍ void Stop(int handle); //Cӂ̃TEhJ //Fhandle JTEh̔ԍ void Release(int handle); //SẴTEh //iV[؂ւƂ͕Ksj void AllRelease(); //Q[Iɍs void ReleaseDirectSound(); }
true
983ab77b3eb61af8185e78df0177d6071e92c079
C++
caixiaomo/leetcode-ans1
/leetcode C++/hash_map/3sum_Closest/answer.cpp
UTF-8
1,442
3.609375
4
[]
no_license
/* 3Sum Closest Total Accepted: 5563 Total Submissions: 20789 My Submissions Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution. For example, given array S = {-1 2 1 -4}, and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). */ class Solution { public: int threeSumClosest(vector<int> &num, int target) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int result = INT_MAX; sort(num.begin(), num.end()); for(int i = 0; i < num.size() - 2; i++){ int first = i; int second = i + 1; int third = num.size() - 1; int sum = 0; while(second < third){ sum = num[first] + num[second] + num[third]; if(sum > target){ third--; }else if(sum == target){ return sum; }else if(sum < target){ second++; } if(result == INT_MAX) result = sum; else result = abs(result - target) < abs(sum - target) ? result : sum; } } return result; } };
true
bff95485b576e4a9c5e3dcbab9812db0c28c22e6
C++
ebadusb/Trima_12.4
/gui/predict_wait_state.hpp
UTF-8
8,909
2.546875
3
[]
no_license
#ifndef PREDICT_WAIT_STATES #define PREDICT_WAIT_STATES #include "trimamessages.h" #include "datalog.h" namespace PredictWaitStates { using GuiPredictSequenceValues::DVITALS_ACK; // sent to predict to identify // responses to DVitalsFromGui events ////////////////////////////////////////////////////////////////////// // // Waiting State objects: these represent different "sets of events we're waiting for", each of // which corresponds to a message we've sent to Predict. We can wait on ProcToGuiPredictStatusMsg // (with customization for the payload), GuiProceduresUpdated, or ProcedureSelectedMsg messages; we // wait for different combinations, with specific payloads in the Status msg, depending on what // messages we've sent. // // If this seems overly complicated -- it is, or rather, the overly-complicated thing is the of // messages that the Predict process sends out after an operation, and we just have to deal. // Start by defining the events enum WaitStateEvent { GUI_PROCEDURE_UPDATED, PREDICT_STATUS, PROCEDURE_SELECTED, DONOR_DATA_STATUS, PREDICT_RESPONDED }; // we start with a very general abstract base struct struct WaitStateBase { public: WaitStateBase(const char* n = "") : name(n) {} virtual void reset () = 0; virtual bool waiting () const = 0; virtual bool event(WaitStateEvent, int) = 0; // returns true if the event was used virtual void print (DataLog_Stream& os) const = 0; virtual ~WaitStateBase() {} char tf (bool b) const { return b ? 'T' : 'F'; } const char* name; }; ////////// Now, specific implementations // Null wait state -- not waiting, no state transitions struct NullWaitState : public WaitStateBase { NullWaitState() : WaitStateBase("nothing") {} virtual void reset () {} virtual bool waiting () const { return false; } virtual bool event (WaitStateEvent, int) { return false; } virtual void print (DataLog_Stream& os) const { } }; /// Generic thing to wait on a GUI_PROCEDURE_UPDATED event struct ProceduresWait : public WaitStateBase { bool wait; GuiProceduresUpdated_t request; ProceduresWait(GuiProceduresUpdated_t req) : WaitStateBase(), wait(true), request(req) {} virtual void reset () { wait = true; } virtual bool waiting () const { return wait; } virtual bool event (WaitStateEvent e, int r) { // We only care about GUI_PROCEDURE_UPDATED events: if (e != GUI_PROCEDURE_UPDATED) return false; // If we're set to 'any', any GUI_PROCEDURE_UPDATED event will do if ( ( request == NON_REQUEST ) ) { wait = false; return true; } // if the incoming request matches if ( request == r ) { wait = false; return true; } // otherwise, we're not interested return false; } // Shorthand for setting the state; useful in other WaitStates that aggregate this. void operator = (bool b) { wait = b; } virtual void print (DataLog_Stream& os) const { if (wait) { if (request == -1) os << "GuiProcedures(any) "; else os << "GuiProcedures(" << request << ") "; } } }; // Wait for a GuiProceduresUpdated message. (Just wraps the ProceduresWait in // something that has a name.) struct ProcedureUpdated : public WaitStateBase { ProceduresWait waiter; ProcedureUpdated(const char* n, GuiProceduresUpdated_t req) : WaitStateBase(n), waiter(req) {} virtual void reset () { waiter.reset(); } virtual bool waiting () const { return waiter.waiting(); } virtual bool event (WaitStateEvent e, int r) { return waiter.event(e, r); } virtual void print (DataLog_Stream& os) const { waiter.print(os); } }; /////// Wait state for a selection message -- we need a procedure selected /////// message. struct SelectCurrent : public WaitStateBase { bool wait; SelectCurrent(const char* n) : WaitStateBase(n), wait(true) {} virtual void reset () { wait = true; } virtual bool waiting () const { return wait; } virtual bool event (WaitStateEvent e, int) { if (e == PROCEDURE_SELECTED) { wait = false; return true; } return false; } virtual void print (DataLog_Stream& os) const { if (wait) os << " ProcedureSelected "; } }; // This case looks for a pair of messages: a ProcToGuiPredictStatusMsg // (REQUEST_SELECTION_SCREEN) and a GuiProceduresUpdated. (This is what we get // when Predict actually decides that something has changed; this wait state is // used for messages that are guaranteed to produce a change.) struct StatusAndProcedures : public WaitStateBase { ProceduresWait procedure; bool status; StatusAndProcedures(const char* n, GuiProceduresUpdated_t req = NON_REQUEST) : WaitStateBase(n), procedure(req), status(true) {} virtual void reset () { status = true; procedure.reset(); } virtual bool waiting () const { return status || procedure.waiting(); } virtual bool event (WaitStateEvent e, int t = -1) { if ( procedure.event(e, t) ) return true; if ( (e == PREDICT_STATUS) && (t == REQUEST_SELECTION_SCREEN) ) { status = false; return true; } return false; } virtual void print (DataLog_Stream& os) const { procedure.print(os); os << ( status ? " PredictStatus(REQUEST) " : "" ); } }; // Here, we're either looking for a Status(REQUEST_SELECTION_SCREEN) and // ProceduresUpdated pair (this is what we get when Predict actually decides // that something has changed), or a single Status(PROCEDURE_VALID) message. struct StatusOrProcedures : public WaitStateBase { ProceduresWait procedure; bool status; StatusOrProcedures(const char* n, GuiProceduresUpdated_t req = NON_REQUEST) : WaitStateBase(n), procedure(req), status(true) {} virtual void reset () { status = true; procedure.reset(); } virtual bool waiting () const { return status || procedure.waiting(); } virtual bool event (WaitStateEvent e, int t) { if ( procedure.event(e, t) ) return true; if ( e == PREDICT_STATUS ) { switch (t) { case PROCEDURE_VALID : procedure = false ; // fall through case REQUEST_SELECTION_SCREEN : status = false ; return true; default : return false ; // technically an error } } return false; } virtual void print (DataLog_Stream& os) const { procedure.print(os); os << ( status ? " PredictStatus " : "" ); } }; struct DonorDataStatus : public WaitStateBase { bool status; // donor info status bool respond; // predict responded DonorDataStatus() : WaitStateBase("DonorVitals"), status(true), respond(true) {} virtual void reset () { status = respond = true; } virtual bool waiting () const { return status || respond; } virtual bool event (WaitStateEvent e, int t) { if ( e == DONOR_DATA_STATUS) { status = false; return true; } if ( (e == PREDICT_RESPONDED) && (t == DVITALS_ACK) ) // we're specifically looking for this ACK { respond = false; return true; } return false; } virtual void print (DataLog_Stream& os) const { if (status) os << " DonorDataStatus "; if (respond) os << " PredictResponded "; } }; ////////////////////////////// // // Finally: a WaitState that wraps other wait states. Basically a decorator, // but it's the thing the predict manager actually uses class WaitState : public WaitStateBase { public: WaitState() : WaitStateBase(), wait(&null_wait), null_wait() {} virtual void reset () { wait = &null_wait; } virtual bool waiting () const { return wait->waiting(); } virtual bool event (WaitStateEvent e, int t) { return wait->event(e, t); } virtual void print (DataLog_Stream& os) const { wait->print(os); } virtual void set (WaitStateBase& newstate) { wait = &newstate; wait -> reset(); } operator bool() const { return wait->waiting(); } const char* getname () const { return wait->name; } private: WaitStateBase* wait; NullWaitState null_wait; }; inline DataLog_Stream& operator << (DataLog_Stream& os, const WaitState& wait) { os << "Waiting for: " << wait.getname() << " < "; wait.print(os); os << " > "; return os; } } #endif /* FORMAT HASH 1f574fb20610f9890e92affd6cbb69a3 */
true
b3567188fabc376e24a3ca3d93c347e24b5d11ab
C++
LinBochi/LinBochi_48102
/Hmwk/Assignment6/Gaddis_8thEd_Chap7_Prob6_Number Analysis Program/main.cpp
UTF-8
1,476
3.671875
4
[]
no_license
/* * File: main.cpp * Author: Bochi Lin * Created on November 18, 2016, 8:42 AM * Purpose: Find the total, average, smallest, and the largest number in the file */ #include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char** argv) { //Declare variables ifstream inputfile; int inumber,total,largest,smallest,number; float avg; string filename; const int SIZE=10; int numArray[SIZE]; //Input information cout<<"Choose number1.h, number2.h, or number3.h"<<endl; cout<<"Please enter the file name: "; cin>>filename; cout<<endl;n //Input file inputfile.open(filename); //Array reads numbers from the file user chose for(int i=0;i<SIZE;i++){ inputfile>>numArray[i]; total+=numArray[i]; } //Calculation avg=total/10.0; largest=numArray[0]; smallest=numArray[0]; //Find the smallest and the largest for(int j=0;j<SIZE;j++){ number=numArray[j]; if(number>largest) largest=number; if(number<smallest) smallest=number; } inputfile.close();//Close file //Display output cout<<"The smallest number in this file is "<<smallest<<endl; cout<<"The largest number in this file is "<<largest<<endl; cout<<"The total of all the number is "<<total<<endl; cout<<"The average of all the number is "<<avg<<endl; return 0; }
true