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
1aa11f0c03788a37e50a7a3acb386827589516ff
C++
rkagrawal/Cplusplus
/core/inheritance/private/main.cpp
UTF-8
633
2.984375
3
[]
no_license
#include<iostream> using namespace std; class A { public: virtual void onUpdate() { cout << "A::onUpdate" << endl; } }; //class B: private A { // this will not compile //class B: protected A { // this will not compile class B: public A { // this will compile public: void onUpdate() override { cout << "B:onUpdate" << endl; } }; class C { private: A* _p; public: C() {} void reg( A* p ) { _p = p; } void call() { _p->onUpdate(); } }; int main( int argc, const char* argb[] ) { B *myb = new B(); C myc; myc.reg( myb ); myc.call(); }
true
4d66b07ba668a8395b184536dc78f92de6578600
C++
lukasblass/AdventOfCode2019
/2/task1.cpp
UTF-8
1,095
3.125
3
[]
no_license
#include <stdlib.h> #include <iostream> #include <fstream> #include <vector> #include <string> void runIntcode(std::vector<int>& intcode) { int state = 0; int command = intcode[state]; while (command != 99) { int o1 = intcode[intcode[state + 1]]; int o2 = intcode[intcode[state + 2]]; if (command == 1) { intcode[intcode[state + 3]] = o1 + o2; } else { intcode[intcode[state + 3]] = o1 * o2; } state += 4; command = intcode[state]; } } int main() { std::ifstream file; file.open("task1.txt"); std::string s; file >> s; std::vector<int> intcode; int index = 0; int start_index = 0; while (index < s.length()) { if (s[index] == ',') { std::string subs = s.substr(start_index, index - start_index); intcode.push_back(std::stoi(subs)); index++; start_index = index; } else { index++; } } intcode.push_back(std::stoi(s.substr(start_index, s.length() - start_index))); intcode[1] = 12; intcode[2] = 2; runIntcode(intcode); std::cout << intcode[0] << std::endl; return 0; }
true
f039c6f30508e8332fc49acab632d88a774f71c5
C++
volzkzg/Tempus-Fugit-Code-Machine
/Tempus Fugit/Graph Theory/K-shortest Path (Repeat is allowed).cpp
UTF-8
4,185
2.890625
3
[]
no_license
#define for_each(it, v) for (vector<Edge*>::iterator it = (v).begin(); it != (v).end(); ++it) const int MAX_N = 10000, MAX_M = 50000, MAX_K = 10000, INF = 1000000000; struct Edge { int from, to, weight; }; struct HeapNode { Edge* edge; int depth; HeapNode* child[4]; }; // child[0..1] for heap G, child[2..3] for heap out edge int n, m, k, s, t; Edge* edge[MAX_M]; int dist[MAX_N]; Edge* prev[MAX_N]; vector<Edge*> graph[MAX_N]; vector<Edge*> graphR[MAX_N]; HeapNode* nullNode; HeapNode* heapTop[MAX_N]; HeapNode* createHeap(HeapNode* curNode, HeapNode* newNode) { if (curNode == nullNode) return newNode; HeapNode* rootNode = new HeapNode; memcpy(rootNode, curNode, sizeof(HeapNode)); if (newNode->edge->weight < curNode->edge->weight) { rootNode->edge = newNode->edge; rootNode->child[2] = newNode->child[2]; rootNode->child[3] = newNode->child[3]; newNode->edge = curNode->edge; newNode->child[2] = curNode->child[2]; newNode->child[3] = curNode->child[3]; } if (rootNode->child[0]->depth < rootNode->child[1]->depth) rootNode->child[0] = createHeap(rootNode->child[0], newNode); else rootNode->child[1] = createHeap(rootNode->child[1], newNode); rootNode->depth = max(rootNode->child[0]->depth, rootNode->child[1]->depth) + 1; return rootNode; } bool heapNodeMoreThan(HeapNode* node1, HeapNode* node2) { return node1->edge->weight > node2->edge->weight; } int main() { scanf("%d%d%d", &n, &m, &k); scanf("%d%d", &s, &t); s--, t--; while (m--) { Edge* newEdge = new Edge; int i, j, w; scanf("%d%d%d", &i, &j, &w); i--, j--; newEdge->from = i; newEdge->to = j; newEdge->weight = w; graph[i].push_back(newEdge); graphR[j].push_back(newEdge); } //Dijkstra queue<int> dfsOrder; memset(dist, -1, sizeof(dist)); typedef pair<int, pair<int, Edge*> > DijkstraQueueItem; priority_queue<DijkstraQueueItem, vector<DijkstraQueueItem>, greater<DijkstraQueueItem> > dq; dq.push(make_pair(0, make_pair(t, (Edge*) NULL))); while (!dq.empty()) { int d = dq.top().first; int i = dq.top().second.first; Edge* edge = dq.top().second.second; dq.pop(); if (dist[i] != -1) continue; dist[i] = d; prev[i] = edge; dfsOrder.push(i); for_each(it, graphR[i]) dq.push(make_pair(d + (*it)->weight, make_pair((*it)->from, *it))); } //Create edge heap nullNode = new HeapNode; nullNode->depth = 0; nullNode->edge = new Edge; nullNode->edge->weight = INF; fill(nullNode->child, nullNode->child + 4, nullNode); while (!dfsOrder.empty()) { int i = dfsOrder.front(); dfsOrder.pop(); if (prev[i] == NULL) heapTop[i] = nullNode; else heapTop[i] = heapTop[prev[i]->to]; vector<HeapNode*> heapNodeList; for_each(it, graph[i]) { int j = (*it)->to; if (dist[j] == -1) continue; (*it)->weight += dist[j] - dist[i]; if (prev[i] != *it) { HeapNode* curNode = new HeapNode; fill(curNode->child, curNode->child + 4, nullNode); curNode->depth = 1; curNode->edge = *it; heapNodeList.push_back(curNode); } } if (!heapNodeList.empty()) { //Create heap out make_heap(heapNodeList.begin(), heapNodeList.end(), heapNodeMoreThan); int size = heapNodeList.size(); for (int p = 0; p < size; p++) { heapNodeList[p]->child[2] = 2 * p + 1 < size ? heapNodeList[2 * p + 1] : nullNode; heapNodeList[p]->child[3] = 2 * p + 2 < size ? heapNodeList[2 * p + 2] : nullNode; } heapTop[i] = createHeap(heapTop[i], heapNodeList.front()); } } //Walk on DAG typedef pair<long long, HeapNode*> DAGQueueItem; priority_queue<DAGQueueItem, vector<DAGQueueItem>, greater<DAGQueueItem> > aq; if (dist[s] == -1) printf("NO\n"); else { printf("%d\n", dist[s]); if (heapTop[s] != nullNode) aq.push(make_pair(dist[s] + heapTop[s]->edge->weight, heapTop[s])); } k--; while (k--) { if (aq.empty()) { printf("NO\n"); continue; } long long d = aq.top().first; HeapNode* curNode = aq.top().second; aq.pop(); printf("%I64d\n", d); if (heapTop[curNode->edge->to] != nullNode) aq.push(make_pair(d + heapTop[curNode->edge->to]->edge->weight, heapTop[curNode->edge->to])); for (int i = 0; i < 4; i++) if (curNode->child[i] != nullNode) aq.push(make_pair(d - curNode->edge->weight + curNode->child[i]->edge->weight, curNode->child[i])); } return 0; }
true
64766747e6500cee0dae016b9d5e41b522ba130e
C++
minji0320/Algorithm_for_CodingTest
/Dongmin/SWEA/보호필름/P2112.cpp
UTF-8
2,048
2.90625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int D, W, K; vector<vector<int> > film; vector<bool> dosed; void getInput() { cin >> D >> W >> K; film.assign(D, vector<int>(W, 0)); dosed.assign(D, false); for(int i=0; i<D; i++) { for(int j=0; j<W; j++) { cin >> film[i][j]; } } } bool isPassed() { bool ret = true; int connCellType = 0; int connCellNum = 0; for(int i=0; i<W; i++) { bool isPassedLayer = false; for(int j=0; j<D; j++) { if(film[j][i]==connCellType) { connCellNum += 1; } else { connCellNum = 1; if(D-j<K-1) { break; } connCellType = connCellType==0?1:0; } if(connCellNum == K) { isPassedLayer = true; connCellNum = 0; break; } } if(!isPassedLayer) { ret = false; break; } } return ret; } void dfs(int cnt, int layer, int& min) { if(cnt>=min || cnt>D || layer>D) { return; } if(isPassed()) { if(min>cnt) { min=cnt; } } else { if(layer>=D) return; dfs(cnt,layer+1,min); vector<int> temp; temp.assign(W, 0); for(int i=0; i<W; i++) { temp[i] = film[layer][i]; film[layer][i] = 0; } dfs(cnt+1,layer+1,min); for(int i=0; i<W; i++) { film[layer][i] = 1; } dfs(cnt+1,layer+1,min); for(int i=0; i<W; i++) { film[layer][i] = temp[i]; } } } void solution(int testnum) { int minDos=D; dfs(0,0,minDos); printf("#%d %d\n", testnum, minDos); } int main(int argc, char** argv) { int test_case; int T; cin>>T; for(test_case = 1; test_case <= T; ++test_case) { getInput(); solution(test_case); } return 0; }
true
437362a78b1f0419e1351ebf9943b3ec32b727ed
C++
emli/competitive
/tasks/BChetniiMassiv.cpp
UTF-8
1,440
2.84375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; class BChetniiMassiv { public: void run(std::istream& cin, std::ostream& cout){ int n; cin >> n; vector<int> a(n); int even = 0; int odd = 0; vector<int> pos; for (int i = 0; i < n; ++i) { cin >> a[i]; if (a[i] % 2 != i % 2){ if (a[i] % 2 == 0){ even++; }else { odd++; } pos.push_back(i); } } int ans = 0; for(int x : pos){ if (x % 2 == 0){ if (even > 0){ even--; ans++; }else { cout << "-1" << endl; return; } }else { if (odd > 0){ odd--; ans++; }else { cout << "-1" << endl; return; } } } if (even + odd == 0){ cout << ans / 2 << endl; }else { cout << -1 << endl; } } void solve(std::istream& cin, std::ostream& cout) { ios::sync_with_stdio(false); cin.tie(nullptr); int t; cin >> t; while (t--){ run(cin,cout); } } };
true
b061e54b10b6822ae2964ef6e65708a87c131f2c
C++
EgeCiklabakkal/Raytracer
/src/dynArray.h
UTF-8
1,448
3.859375
4
[ "MIT" ]
permissive
#ifndef _DYNARRAY_H_ #define _DYNARRAY_H_ // a DynArray stores data in an ordered random access structure with // no delete operations. Items are added with append. template <class T> class DynArray { public: T *data; int nData; int arraySize; DynArray(); DynArray(int size); ~DynArray(); bool append(T item); // always added to end bool truncate(); // make arraySize = nData void clear() { nData = 0; } int length() const { return nData; } bool isempty() const { return nData == 0; } const T& operator[](int i) const { return data[i]; } T& operator[](int i) { return data[i]; } }; template <class T> DynArray<T>::DynArray() { nData = 0; arraySize = 4; data = new T[arraySize]; } template <class T> DynArray<T>::DynArray(int size) { nData = 0; arraySize = size; data = new T[arraySize]; } template <class T> DynArray<T>::~DynArray() { nData = 0; delete [] data; } template <class T> bool DynArray<T>::truncate() { if(nData != arraySize) { T *temp = data; arraySize = nData; if(!(data = new T[arraySize])) return false; for(int i = 0; i < nData; i++) data[i] = temp[i]; delete [] temp; } return true; } template <class T> bool DynArray<T>::append(T item) { if(nData == arraySize) { arraySize *= 2; T *temp = data; if(!(data = new T[arraySize])) return false; for(int i = 0; i < nData; i++) data[i] = temp[i]; delete [] temp; } data[nData++] = item; return true; } #endif
true
da84ac6d045ef6166ae1e24025eecb0449c6283a
C++
jinguodong/JSSWW-BUPT-For-Amazon-Hackathon
/OpenCVTest/ScharrOperator.cpp
UTF-8
850
2.671875
3
[]
no_license
#include "ScharrOperator.h" ScharrOperator::ScharrOperator(){ } ScharrOperator::~ScharrOperator(){ } int ScharrOperator::process(Mat & m, bool isGaussianBlurUsed){ if(!isGaussianBlurUsed){ GaussianBlur( m, m, Size(3,3), 0, 0, BORDER_DEFAULT ); } Mat m_gray; cvtColor(m,m_gray,CV_RGB2GRAY); Mat grad, grad_x, grad_y; Mat abs_grad_x, abs_grad_y; int ddepth = CV_16S; int scale = 1; int delta = 0; Scharr(m_gray, grad_x, ddepth, 1, 0, scale, delta, BORDER_DEFAULT); convertScaleAbs( grad_x, abs_grad_x ); Scharr(m_gray, grad_y, ddepth, 0, 1, scale, delta, BORDER_DEFAULT); convertScaleAbs( grad_y, abs_grad_y ); addWeighted( abs_grad_x, 0.5, abs_grad_y, 0.5, 0, grad ); m = grad; return 0; } void ScharrOperator::show(Mat m, string name){ namedWindow(name, CV_WINDOW_AUTOSIZE ); imshow(name,m); waitKey(); return; }
true
d6faccee6a24fe2d1b90da1ed82b1de19ca8aecd
C++
komilguliev99/grader
/user_task1.cpp
UTF-8
229
2.671875
3
[]
no_license
#include <iostream> using namespace std; int main() { int m[1000], n, i = 0; cin >> n; while (i < n) cin >> m[i++]; i = 0; while (i < n) { cout << m[i]; if (i + 2 < n) cout << " "; i += 2; } return (0); }
true
6f37fb0cc0aeda6ecaf218064269bbd7b8f6139f
C++
colinw7/CUtil
/include/CUtf8.h
UTF-8
6,625
2.84375
3
[ "MIT" ]
permissive
#ifndef CUtf8_H #define CUtf8_H #include <cassert> typedef unsigned char uchar; typedef unsigned long ulong; namespace CUtf8 { inline bool IS_IN_RANGE(uchar c, uchar f, uchar l) { return (((c) >= (f)) && ((c) <= (l))); } inline ulong readNextChar(const std::string &str, int &pos, uint len) { assert(pos >= 0 && pos <= int(len)); if (pos == int(len)) return 0; ulong uc = 0; int seqlen = 1; auto c1 = uchar(str[size_t(pos)]); if ((c1 & 0x80) == 0) { // top 1 bit is (0) uc = static_cast<ulong>(c1 & 0x7F); seqlen = 1; } else if ((c1 & 0xE0) == 0xC0) { // top 3 bits are (110) uc = static_cast<ulong>(c1 & 0x1F); seqlen = 2; } else if ((c1 & 0xF0) == 0xE0) { // top 4 bits are (1110) uc = static_cast<ulong>(c1 & 0x0F); seqlen = 3; } else if ((c1 & 0xF8) == 0xF0) { // top 5 bits are (11110) uc = static_cast<ulong>(c1 & 0x07); seqlen = 4; } else { // malformed data, do something !!! ++pos; return static_cast<ulong>(c1); } if (seqlen + pos > int(len)) { // malformed data, do something !!! ++pos; return static_cast<ulong>(c1); } for (int i = 1; i < seqlen; ++i) { uchar c2 = uchar(str[size_t(pos + i)]); if ((c2 & 0xC0) != 0x80) { // malformed data, do something !!! ++pos; return static_cast<ulong>(c2); } } uchar c2; switch (seqlen) { case 2: { c1 = uchar(str[size_t(pos + 0)]); if (! IS_IN_RANGE(c1, 0xC2, 0xDF)) { // malformed data, do something !!! //++pos; return static_cast<ulong>(c1); } break; } case 3: { c1 = uchar(str[size_t(pos + 0)]); c2 = uchar(str[size_t(pos + 1)]); if (((c1 == 0xE0) && ! IS_IN_RANGE(c2, 0xA0, 0xBF)) || ((c1 == 0xED) && ! IS_IN_RANGE(c2, 0x80, 0x9F)) || (! IS_IN_RANGE(c1, 0xE1, 0xEC) && ! IS_IN_RANGE(c1, 0xEE, 0xEF))) { // malformed data, do something !!! //++pos; return static_cast<ulong>(c1); } break; } case 4: { c1 = uchar(str[size_t(pos + 0)]); c2 = uchar(str[size_t(pos + 1)]); if (((c1 == 0xF0) && ! IS_IN_RANGE(c2, 0x90, 0xBF)) || ((c1 == 0xF4) && ! IS_IN_RANGE(c2, 0x80, 0x8F)) || ! IS_IN_RANGE(c1, 0xF1, 0xF3)) { // malformed data, do something !!! //++pos; return static_cast<ulong>(c1); } break; } } for (int i = 1; i < seqlen; ++i) { uc = ulong((uc << 6) | static_cast<ulong>(str[size_t(pos + i)] & 0x3F)); } pos += seqlen; return uc; } inline bool skipNextChar(const std::string &str, int &pos, uint len) { assert(pos >= 0 && pos <= int(len)); if (pos == int(len)) return false; int seqlen = 1; uchar c1 = uchar(str[size_t(pos)]); if ((c1 & 0x80) == 0) { // top 1 bit is (0) seqlen = 1; } else if ((c1 & 0xE0) == 0xC0) { // top 3 bits are (110) seqlen = 2; } else if ((c1 & 0xF0) == 0xE0) { // top 4 bits are (1110) seqlen = 3; } else if ((c1 & 0xF8) == 0xF0) { // top 5 bits are (11110) seqlen = 4; } else { } if (seqlen + pos > int(len)) { pos = int(len); } pos += seqlen; return true; } inline ulong readNextChar(const std::string &str, int &pos) { auto len = str.size(); return readNextChar(str, pos, uint(len)); } inline bool encode(ulong c, char s[4], int &len) { if (c <= 0x7F) { len = 1; // 7 bits s[0] = char(c); } else if (c <= 0x7FF) { len = 2; // 11 bits s[0] = char(0xC0 | ((c >> 6) & 0x1F)); // top 5 s[1] = char(0x80 | ( c & 0x3F)); // bottom 6 } else if (c <= 0xFFFF) { len = 3; // 16 bits s[0] = char(0xE0 | ((c >> 12) & 0x0F)); // top 4 s[1] = char(0x80 | ((c >> 6) & 0x3F)); // mid 6 s[2] = char(0x80 | ( c & 0x3F)); // bottom 6 } else if (c <= 0x1FFFFF) { len = 4; // 21 bits s[0] = char(0xF0 | ((c >> 18) & 0x07)); // top 3 s[1] = char(0x80 | ((c >> 12) & 0x3F)); // top mid 6 s[2] = char(0x80 | ((c >> 6) & 0x3F)); // bottom mid 6 s[3] = char(0x80 | ( c & 0x3F)); // bottom 6 } else return false; return true; } inline bool append(std::string &str, ulong c) { char s[4]; int len; if (! encode(c, s, len)) return false; for (int i = 0; i < len; ++i) str += s[i]; return true; } inline bool isSpace(ulong c) { if (c < 0x80) return isspace(int(c)); else if (c == 0xa0) // no-break space return true; else if (c == 0x2028) // line separator return true; else if (c == 0x2029) // em space return true; else return false; } inline int length(const std::string &str) { int i = 0; int pos = 0; uint len = uint(str.size()); while (skipNextChar(str, pos, len)) ++i; return i; } inline bool indexChar(const std::string &str, int ind, int &i1, int &i2) { if (ind < 0) return false; int i = 0; int pos = 0; uint len = uint(str.size()); while (i < ind) { if (! skipNextChar(str, pos, len)) return false; ++i; } i1 = pos; if (! skipNextChar(str, pos, len)) return false; i2 = pos; return true; } inline std::string substr(const std::string &str, int ind) { if (ind < 0) return ""; int i = 0; int pos = 0; uint len = uint(str.size()); // first first char while (i < ind) { if (! skipNextChar(str, pos, len)) return ""; ++i; } return str.substr(size_t(pos)); } inline std::string substr(const std::string &str, int ind, int n) { if (ind < 0 || n < 1) return ""; int i = 0; int pos = 0; uint len = uint(str.size()); // first first char while (i < ind) { if (! skipNextChar(str, pos, len)) return ""; ++i; } int i1 = pos; // find last char i = 0; while (i < n) { if (! skipNextChar(str, pos, len)) break; ++i; } int i2 = pos; return str.substr(size_t(i1), size_t(i2 - i1)); } inline bool isAscii(const std::string &str) { uint i = 0; uint len = uint(str.size()); while (i < len) { uchar c = uchar(str[size_t(i)]); if (c >= 0x80) return false; ++i; } return true; } } #endif
true
bb9f2036528a4d505a873ac0bfe0f5d953347acd
C++
lzxysf/CC
/ds&algorithm/05_二叉树/01_二叉树_递归法.cpp
UTF-8
3,789
3.75
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <iostream> using namespace std; typedef int DataType; typedef struct Tree{ DataType data;//数据 struct Tree* left;//左子节点 struct Tree* right;//右子节点 }Tree; //先序遍历 void pre_travel(Tree* tree) { //递归结束条件 if(tree == NULL) { return; } //访问根节点 printf("%d ", tree->data); //先序遍历左子树 pre_travel(tree->left); //先序遍历右子树 pre_travel(tree->right); } //中序遍历 void in_travel(Tree* tree) { if(tree==NULL) { return; } in_travel(tree->left); printf("%d ", tree->data); in_travel(tree->right); } //后续遍历 void post_travel(Tree* tree) { if(tree==NULL) { return; } post_travel(tree->left); post_travel(tree->right); printf("%d ", tree->data); } //求树的叶子节点的个数 void leaf_num(Tree* tree, int *count) { //递归结束的条件,空树 if(tree == NULL) { return; } //遍历左子树 leaf_num(tree->left, count); //遍历右子树 leaf_num(tree->right, count); //叶子节点,叶子节点的左子树和右子树都是空 if(tree->left == NULL && tree->right == NULL) { (*count)++; } } //求树的高度 int tree_high(Tree* tree) { if(tree == NULL) { return 0; } int left_high = tree_high(tree->left); int right_high = tree_high(tree->right); int high = left_high > right_high ? left_high : right_high; return high + 1;//返回左右子树中值最大的,再加上当前父节点,因为不会统计父节点 } //二叉树拷贝 void copy_tree(Tree* tree, Tree* copy) { if(tree == NULL) { return; } Tree* temp = (Tree*)malloc(sizeof(Tree)); temp->data = tree->data; copy = temp; copy_tree(tree->left, copy->left); copy_tree(tree->right, copy->right); } //#号法创建一棵树-按照先序遍历的顺序创建 //如果要创建main中的二叉树,输入的顺序为1 2 4 # # 5 # # 3 6 # # 7 # # ,即如果一个节点它没有左右节点那么需要输入# #,如果没有左节点或右节点,输入# Tree* create_tree() { char input; cout << "input current node's value" << endl; cin >> input; if(input == '#') { return NULL; } Tree* root = (Tree*)malloc(sizeof(Tree)); root->data = input - '0'; root->left = create_tree(); root->right = create_tree(); return root; } void destroy_tree(Tree* tree) { if(tree) { if(tree->left) { destroy_tree(tree->left); } if(tree->right) { destroy_tree(tree->right); } free(tree); tree = NULL; } } int main() { //构造一个树 /* 1 / \ 2 3 / \ / \ 4 5 6 7 */ Tree leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7; memset(&leaf1, 0, sizeof(Tree)); memset(&leaf2, 0, sizeof(Tree)); memset(&leaf3, 0, sizeof(Tree)); memset(&leaf4, 0, sizeof(Tree)); memset(&leaf5, 0, sizeof(Tree)); memset(&leaf6, 0, sizeof(Tree)); memset(&leaf7, 0, sizeof(Tree)); leaf1.data = 1; leaf2.data = 2; leaf3.data = 3; leaf4.data = 4; leaf5.data = 5; leaf6.data = 6; leaf7.data = 7; Tree* tree; tree = &leaf1; leaf1.left = &leaf2; leaf1.right = &leaf3; leaf2.left = &leaf4; leaf2.right = &leaf5; leaf3.left = &leaf6; leaf3.right = &leaf7; /* Tree* tree = NULL; tree = create_tree(); destroy_tree(tree); */ pre_travel(tree); printf("\r\n"); in_travel(tree); printf("\r\n"); post_travel(tree); printf("\r\n"); int num = 0; leaf_num(tree, &num); printf("叶子节点的个数:%d\r\n", num); int high = tree_high(tree); printf("数的高度为:%d\r\n", high); Tree* copy; copy_tree(tree, copy); pre_travel(tree); printf("\r\n"); return 0; }
true
4f9a03ac95dd928bc38de1465da7b5dce76f11ab
C++
lattice133/hackerrank
/C/Small trangles large triangles.cpp
UTF-8
847
3.625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> struct triangle { int a; int b; int c; }; double Calc_Area(triangle tr){ double p = (tr.a + tr.b + tr.c) / 2.0; return p * (p-tr.a) * (p-tr.b) * (p-tr.c); } typedef struct triangle triangle; void sort_by_area(triangle* tr, int n) { /** * Sort an array a of the length n */ int i,j; triangle temp; for(i =0; i<n-1; i++){ for (j = i+1; j< n; j++){ if (Calc_Area(tr[i]) > Calc_Area(tr[j])){ temp = tr[i]; tr[i] = tr[j]; tr[j] = temp; } } } } int main() { int n; scanf("%d", &n); triangle *tr = (triangle *)malloc(n * sizeof(triangle)); for (int i = 0; i < n; i++) { scanf("%d%d%d", &tr[i].a, &tr[i].b, &tr[i].c); } sort_by_area(tr, n); for (int i = 0; i < n; i++) { printf("%d %d %d\n", tr[i].a, tr[i].b, tr[i].c); } getchar(); return 0; }
true
7bc047089758075191f245bae1e2474855c23339
C++
adityanjr/code-DS-ALGO
/GeeksForGeeks/DS/3. Array/17.maximum-and-minimum-in-an-array.cpp
UTF-8
749
3.890625
4
[ "MIT" ]
permissive
// http://www.geeksforgeeks.org/maximum-and-minimum-in-an-array/ #include <iostream> #include "array.h" struct _pair { int min; int max; }; struct _pair getMinMax(int *a, int start, int end){ int n=end-start+1; if(n==1){ return {a[start], a[start]}; } else if( n==2){ return {min(a[start], a[end]), max(a[start], a[end])}; } else { int mid = (start+end)/2; _pair tmp1 = getMinMax(a, start, mid); _pair tmp2 = getMinMax(a, mid+1, end); return {min(tmp1.min, tmp2.min), max(tmp1.max, tmp2.max)}; } } int main(){ int arr[] = {1000, 11, 445, 1, 330, 3000}; int arr_size = 6; _pair minmax = getMinMax(arr, 0, arr_size-1); printf("\nMinimum element is %d", minmax.min); printf("\nMaximum element is %d", minmax.max); }
true
3e43cf9038d43a8482ba68523efcbf20db19fd53
C++
gopalcdas/JLTi-Code-Jam
/ChoosingOranges.cpp
UTF-8
2,906
3.171875
3
[]
no_license
//JLTi Code Jam Oct 2017 //https://gopalcdas.wordpress.com/2017/10/14/choosing-oranges/ #include <stdio.h> #include <queue> using namespace std; struct Node { int score; int index; bool operator<(const Node& rhs) const { return score < rhs.score; } }; Node *BuildNodes(int *scores, int n); int *BestScores(int *scores, int n); void FindBestScores(Node *nodes, int* scores1, int n, int m, int *bestScores); void PrintScores(int *scores, int *bestScores, int n); int main() { int m = 5; int scores1[] = { 1, 3, 5, 7, 3, 5, 9, 1, 2, 5 }; int n = sizeof(scores1) / sizeof(scores1[0]); FindBestScores(BuildNodes(scores1, n), scores1, n, m, BestScores(scores1, n)); m = 4; int scores2[] = { 1, 3, 5}; n = sizeof(scores2) / sizeof(scores2[0]); FindBestScores(BuildNodes(scores2, n), scores2, n, m, BestScores(scores2, n)); m = 3; int scores3[] = { 1, 2, 4, 9 }; n = sizeof(scores3) / sizeof(scores3[0]); FindBestScores(BuildNodes(scores3, n), scores3, n, m, BestScores(scores3, n)); m = 7; int scores4[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; n = sizeof(scores4) / sizeof(scores4[0]); FindBestScores(BuildNodes(scores4, n), scores4, n, m, BestScores(scores4, n)); m = 7; int scores5[] = { 9, 8, 7, 10, 6, 5, 4, 3, 2, 1 }; n = sizeof(scores5) / sizeof(scores5[0]); FindBestScores(BuildNodes(scores5, n), scores5, n, m, BestScores(scores5, n)); m = 7; int scores6[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; n = sizeof(scores6) / sizeof(scores6[0]); FindBestScores(BuildNodes(scores6, n), scores6, n, m, BestScores(scores6, n)); } Node *BuildNodes(int *scores, int n) { Node *nodes = new Node[n]; for (int i = 0; i < n; i++) { nodes[i].score = scores[i]; nodes[i].index = i; } return nodes; } int *BestScores(int *scores, int n) { int *bestScores = new int[n]; for (int i = 0; i < n; i++) bestScores[i] = 0; return bestScores; } void FindBestScores(Node *nodes, int* scores, int n, int m, int *bestScores) { if (n < m) { printf("None\n\n"); return; } std::priority_queue <Node> q; for (int i = 0; i < m - 1; i++) q.push(nodes[i]); for (int i = m-1; i < n; i++) { Node node = q.top(); if (node.score <= nodes[i].score) { q.pop(); bestScores[i] = 1; q.push(nodes[i]); continue; } q.push(nodes[i]); while (node.index < (i + 1 - m)) { q.pop(); node = q.top(); } bestScores[node.index] = 1; if (node.index == (i + 1 - m)) q.pop(); } PrintScores(scores, bestScores, n); } void PrintScores(int *scores, int *bestScores, int n) { bool firstPrinted = false; for (int i = 0; i < n; i++) if (bestScores[i]) { if(firstPrinted) printf(", %d", scores[i]); else { firstPrinted = true; printf("%d", scores[i]); } } printf("\n\n"); }
true
b0265de9bd95293578e7b764c587ad5bab709d3e
C++
Loycine/Design-Pattern
/StatePattern/StatePatternOld.cpp
GB18030
1,908
2.96875
3
[]
no_license
#include <iostream> using namespace std; #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> class Context; class State { // ״̬࣬һӿԷװContextһض״̬صΪ public: virtual void Handle(Context* c) = 0; virtual ~State() {} }; class Context { // άһConcreteStateʵʵΪǰ״̬ private: State * state; public: Context(State* s) { state = s; } void Request() { // // һ״̬ state->Handle(this); } void SetState(State* s) { state = s; } ~Context() { delete state; } }; // ״̬࣬ÿһʵContextһ״̬Ϊ class ConcreteStateA : public State { public: void Handle(Context* c); }; class ConcreteStateB : public State { public: void Handle(Context* c); }; class ConcreteStateC : public State { public: void Handle(Context* c); }; void ConcreteStateA::Handle(Context* c) { cout << "ConcreteStateA" << endl; c->SetState(new ConcreteStateB()); delete this; } void ConcreteStateB::Handle(Context* c) { cout << "ConcreteStateB" << endl; c->SetState(new ConcreteStateC()); delete this; } void ConcreteStateC::Handle(Context* c) { cout << "ConcreteStateC" << endl; c->SetState(new ConcreteStateA()); delete this; } int main() { State* s = new ConcreteStateA(); Context* c = new Context(s); c->Request(); // ConcreteStateA л״̬ c->Request(); // ConcreteStateB c->Request(); // ConcreteStateC delete c; _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDOUT); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDOUT); _CrtDumpMemoryLeaks(); getchar(); return 0; }
true
9ec92d833473bdc352cd568cd9e505a1119eec0d
C++
VincentLLam/Class-with-File-Manipulation
/pay.cpp
UTF-8
1,163
3.546875
4
[]
no_license
// Vincent Lam // Section Number 3 #include "person.cpp" #include <fstream> #include <vector> #include <iomanip> void readData(vector<Person> &employees); void writeData(vector<Person> &employees); int main() { vector <Person> employees; readData(employees); writeData(employees); return 0; } void readData(vector<Person> &employees) { int i = 0; ifstream inFile; string fName, lName, temp; float rate, hours; inFile.open("input.txt"); while(!inFile.eof()) { employees.emplace_back(fName, lName, rate, hours); inFile >> fName >> lName >> rate >> hours; getline(inFile, temp); employees.at(i).setFirstName(fName); employees.at(i).setLastName(lName); employees.at(i).setPayRate(rate); employees.at(i).setHoursWorked(hours); i++; } employees.pop_back(); inFile.close(); } void writeData(vector<Person> &employees) { ofstream outFile; outFile.open("output.txt"); for(int i = 0; i < employees.size(); i++) { outFile << setw(20) << left << employees.at(i).fullName() << "$" << setw(10) << left << fixed << setprecision(2) << employees.at(i).totalPay() << endl; } outFile.close(); }
true
73756a0e2933146340575ddbc6fb919ec1edd205
C++
abhishekanimatron/act_cpp
/trees/binary/maximumSumOfPaths.cpp
UTF-8
1,406
3.8125
4
[]
no_license
#include <iostream> #include <climits> using namespace std; struct Node { int data; Node *left; Node *right; Node(int value) { data = value; left = NULL; right = NULL; } }; int maximumPathSumHelper(Node *root, int &answer) { if (root == NULL) return 0; // sum from left and right subtrees int leftSum = maximumPathSumHelper(root->left, answer); int rightSum = maximumPathSumHelper(root->right, answer); // maximum for current node //considers cuurent value, value +left and right sum, value +left, value +right int nodeMaximum = max(max(root->data, root->data + leftSum + rightSum), max(root->data + leftSum, root->data + rightSum)); // change answer answer = max(nodeMaximum, answer); int singlePathSum = max(root->data, max(root->data + leftSum, root->data + rightSum)); return singlePathSum; } int maximumPathSum(Node *root) { int answer = INT_MIN; maximumPathSumHelper(root, answer); return answer; } int main() { // tree: // 1 // 2 3 // 4 5 6 7 struct Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); cout << maximumPathSum(root) << "\n"; }
true
5192d95eeac47c063ecbc61b15efd4b7cc61eaf3
C++
dbuksbaum/FreeOrion
/FreeOrion/universe/Tech.h
UTF-8
12,853
2.515625
3
[]
no_license
// -*- C++ -*- #ifndef _Tech_h_ #define _Tech_h_ #include <boost/serialization/shared_ptr.hpp> #include "Enums.h" #include <boost/multi_index_container.hpp> #include <boost/multi_index/key_extractors.hpp> #include <boost/multi_index/ordered_index.hpp> #include <set> #include <string> #include <vector> #include <GG/Clr.h> namespace Effect { class EffectsGroup; } class TechManager; struct ItemSpec; /** encasulates the data for a single FreeOrion technology */ class Tech { public: /** Helper struct for parsing tech definitions */ struct TechInfo { TechInfo() {} TechInfo(const std::string& name_, const std::string& description_, const std::string& short_description_, const std::string& category_, TechType type_, double research_cost_, int research_turns_, bool researchable_) : name(name_), description(description_), short_description(short_description_), category(category_), type(type_), research_cost(research_cost_), research_turns(research_turns_), researchable(researchable_) {} std::string name; std::string description; std::string short_description; std::string category; TechType type; double research_cost; int research_turns; bool researchable; }; /** \name Structors */ //@{ /** basic ctor */ Tech(const std::string& name, const std::string& description, const std::string& short_description, const std::string& category, TechType type, double research_cost, int research_turns, bool researchable, const std::vector<boost::shared_ptr<const Effect::EffectsGroup> >& effects, const std::set<std::string>& prerequisites, const std::vector<ItemSpec>& unlocked_items, const std::string& graphic) : m_name(name), m_description(description), m_short_description(short_description), m_category(category), m_type(type), m_research_cost(research_cost), m_research_turns(research_turns), m_researchable(researchable), m_effects(effects), m_prerequisites(prerequisites), m_unlocked_items(unlocked_items), m_graphic(graphic) {} /** basic ctor taking helper struct to reduce number of direct parameters * in order to making parsing work. */ Tech(const TechInfo& tech_info, const std::vector<boost::shared_ptr<const Effect::EffectsGroup> >& effects, const std::set<std::string>& prerequisites, const std::vector<ItemSpec>& unlocked_items, const std::string& graphic) : m_name(tech_info.name), m_description(tech_info.description), m_short_description(tech_info.short_description), m_category(tech_info.category), m_type(tech_info.type), m_research_cost(tech_info.research_cost), m_research_turns(tech_info.research_turns), m_researchable(tech_info.researchable), m_effects(effects), m_prerequisites(prerequisites), m_unlocked_items(unlocked_items), m_graphic(graphic) {} //@} /** \name Accessors */ //@{ const std::string& Name() const { return m_name; } //!< returns name of this tech const std::string& Description() const { return m_description; } //!< Returns the text description of this tech const std::string& ShortDescription() const { return m_short_description; } //!< Returns the single-line short text description of this tech std::string Dump() const; //!< Returns a data file format representation of this object TechType Type() const { return m_type; } //!< Returns the type (theory/application/refinement) of this tech const std::string& Category() const { return m_category; } //!< retursn the name of the category to which this tech belongs double ResearchCost() const; //!< returns the total research cost in RPs required to research this tech double PerTurnCost() const; //!< returns the maximum number of RPs per turn allowed to be spent on researching this tech int ResearchTime() const; //!< returns the number of turns required to research this tech, if ResearchCost() RPs are spent per turn bool Researchable() const { return m_researchable; } //!< returns whether this tech is researchable by players and appears on the tech tree /** returns the effects that are applied to the discovering empire's capital * when this tech is researched; not all techs have effects, in which case * this returns 0 */ const std::vector<boost::shared_ptr<const Effect::EffectsGroup> >& Effects() const { return m_effects; } const std::set<std::string>& Prerequisites() const { return m_prerequisites; } //!< returns the set of names of all techs required before this one can be researched const std::string& Graphic() const { return m_graphic; } //!< returns the name of the grapic file for this tech const std::vector<ItemSpec>& UnlockedItems() const { return m_unlocked_items; } //!< returns the set all items that are unlocked by researching this tech const std::set<std::string>& UnlockedTechs() const { return m_unlocked_techs; } //!< returns the set of names of all techs for which this one is a prerequisite //@} private: Tech(const Tech&); // disabled const Tech& operator=(const Tech&); // disabled std::string m_name; std::string m_description; std::string m_short_description; std::string m_category; TechType m_type; double m_research_cost; int m_research_turns; bool m_researchable; std::vector<boost::shared_ptr<const Effect::EffectsGroup> > m_effects; std::set<std::string> m_prerequisites; std::vector<ItemSpec> m_unlocked_items; std::string m_graphic; std::set<std::string> m_unlocked_techs; friend class TechManager; }; /** specifies a single item of game content that may be unlocked for an empire. The \a type field * stores the type of item that is being unlocked, such as a building or ship component, and the * \a name field contains the name of the actual item (e.g. (UIT_BUILDING, "Superfarm") or * (UIT_SHIP_PART, "Death Ray")). */ struct ItemSpec { ItemSpec() : type(INVALID_UNLOCKABLE_ITEM_TYPE), name("") {} ItemSpec(UnlockableItemType type_, const std::string& name_) : type(type_), name(name_) {} std::string Dump() const; ///< returns a data file format representation of this object UnlockableItemType type; ///< the kind of item this is std::string name; ///< the exact item this is }; /** specifies a category of techs, with associated \a name, \a graphic (icon), and \a colour.*/ struct TechCategory { TechCategory() : name(""), graphic(""), colour(GG::Clr(255, 255, 255, 255)) {} TechCategory(const std::string& name_, const std::string& graphic_, const GG::Clr& colour_): name(name_), graphic(graphic_), colour(colour_) {} std::string name; ///< name of category std::string graphic; ///< icon that represents catetegory GG::Clr colour; ///< colour associatied with category }; /** holds all FreeOrion techs. Techs may be looked up by name and by category, and the next researchable techs can be querried, given a set of currently-known techs. */ class TechManager { public: struct CategoryIndex {}; struct NameIndex {}; typedef boost::multi_index_container< const Tech*, boost::multi_index::indexed_by< boost::multi_index::ordered_non_unique< boost::multi_index::tag<CategoryIndex>, boost::multi_index::const_mem_fun< Tech, const std::string&, &Tech::Category > >, boost::multi_index::ordered_unique< boost::multi_index::tag<NameIndex>, boost::multi_index::const_mem_fun< Tech, const std::string&, &Tech::Name > > > > TechContainer; /** iterator that runs over techs within a category */ typedef TechContainer::index<CategoryIndex>::type::const_iterator category_iterator; /** iterator that runs over all techs */ typedef TechContainer::index<NameIndex>::type::const_iterator iterator; /** \name Accessors */ //@{ /** returns the tech with the name \a name; you should use the free function GetTech() instead */ const Tech* GetTech(const std::string& name); /** returns the tech category with the name \a name; you should use the free function GetTechCategory() instead */ const TechCategory* GetTechCategory(const std::string& name); /** returns the list of category names */ std::vector<std::string> CategoryNames() const; /** returns list of all tech names */ std::vector<std::string> TechNames() const; /** returns list of names of techs in specified category */ std::vector<std::string> TechNames(const std::string& name) const; /** returns all researchable techs */ std::vector<const Tech*> AllNextTechs(const std::set<std::string>& known_techs); /** returns the cheapest researchable tech */ const Tech* CheapestNextTech(const std::set<std::string>& known_techs); /** returns all researchable techs that progress from the given known techs to the given desired tech */ std::vector<const Tech*> NextTechsTowards(const std::set<std::string>& known_techs, const std::string& desired_tech); /** returns the cheapest researchable tech that progresses from the given known techs to the given desired tech */ const Tech* CheapestNextTechTowards(const std::set<std::string>& known_techs, const std::string& desired_tech); /** iterator to the first tech */ iterator begin() const; /** iterator to the last + 1th tech */ iterator end() const; /** iterator to the first tech in category \a name */ category_iterator category_begin(const std::string& name) const; /** iterator to the last + 1th tech in category \a name */ category_iterator category_end(const std::string& name) const; //@} /** returns the instance of this singleton class; you should use the free function GetTechManager() instead */ static TechManager& GetTechManager(); private: TechManager(); ~TechManager(); /** returns an error string indicating the first instance of an illegal prerequisite relationship between two techs in m_techs, or an empty string if there are no illegal dependencies */ std::string FindIllegalDependencies(); /** returns an error string indicating the first prerequisite dependency cycle found in m_techs, or an empty string if there are no dependency cycles */ std::string FindFirstDependencyCycle(); /** returns an error string indicating the first instance of a redundant dependency, or an empty string if there are no redundant dependencies. An example of a redundant dependency is A --> C, if A --> B and B --> C. */ std::string FindRedundantDependency(); void AllChildren(const Tech* tech, std::map<std::string, std::string>& children); std::map<std::string, TechCategory*> m_categories; TechContainer m_techs; static TechManager* s_instance; friend struct store_tech_impl; friend struct store_category_impl; }; /** returns the singleton tech manager */ TechManager& GetTechManager(); /** returns a pointer to the tech with the name \a name, or 0 if no such tech exists */ const Tech* GetTech(const std::string& name); /** returns a pointer to the tech category with the name \a name, or 0 if no such category exists */ const TechCategory* GetTechCategory(const std::string& name); #endif // _Tech_h_
true
add6c8ab720e2fcc96243498e02fc4c7adb50ebb
C++
jtlai0921/AEL021700-Samplefiles
/C++程式設計解題入門-程式碼/ch8/8-3-2-可以插隊在任意位置.cpp
UTF-8
582
2.71875
3
[]
no_license
#include <iostream> #include <list> using namespace std; int main(){ int n,m,p,pos; char cmd; list<int> mlist; list<int>::iterator it; while(cin>>n>>m){ mlist.clear(); for(int i=1;i<=n;i++) mlist.push_back(i); for(int i=1;i<=m;i++){ cin >> cmd; if (cmd=='s') { cout << mlist.front() << endl; mlist.push_back(mlist.front()); mlist.pop_front(); }else{ cin >> p >> pos; mlist.remove(p); it = mlist.begin(); for(int i=1;i<pos;i++) it++; mlist.insert(it,p); } } } }
true
0da08fc529282c3ffd81256cddec149dab97413a
C++
Natches/Drakkar-Engine
/Source/Serialization/Serializer.cpp
UTF-8
1,311
2.578125
3
[]
no_license
#include <PrecompiledHeader/pch.hpp> namespace drak { namespace serialization { void Serializer::FileDescriptor::writeToFile(std::fstream& file) { file.seekp(0, std::ios::beg); int size = (int)m_descriptor.size(); m_endPos = sizeof(int) * 2; for (auto& x : m_descriptor) m_endPos += (int)(x.first.first.size() + 1 + 2 * sizeof(int)); file.write((const char*)&(m_endPos), sizeof(int)); file.write((const char*)&(size), sizeof(int)); for (auto& x : m_descriptor) { file << x.first.first << " "; file.write((const char*)&(x.first.second), sizeof(int)); file.write((const char*)&(x.second), sizeof(int)); } } void Serializer::FileDescriptor::loadFromFile(std::fstream& file) { file.seekg(0, std::ios::beg); int size; file.read((char*)&m_endPos, sizeof(int)); file.read((char*)&size, sizeof(int)); for (int i = 0; i < size; ++i) { std::string str; int instanceN, position; file >> str; file.seekg(1, std::ios::cur); file.read((char*)&(instanceN), sizeof(int)); file.read((char*)&(position), sizeof(int)); m_descriptor[{str, instanceN}] = position; } } void Serializer::FileDescriptor::seekToBeginingOfClass(std::fstream& file) { file.seekg(std::streamoff(m_endPos), std::ios::beg); } } // namespace serialization } // namepsace drak
true
c62dd83b9a9286d4e4a7c505a24050b8116db862
C++
dinushan/CHIP-8
/CHIP-8/src/Chip8.cpp
UTF-8
10,019
2.6875
3
[]
no_license
#include "Chip8.h" #include <iostream> #include <fstream> #include <cstdlib> #include <ctime> unsigned const char Chip8::FontSet[16*5] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, // 0 0x20, 0x60, 0x20, 0x20, 0x70, // 1 0xF0, 0x10, 0xF0, 0x80, 0xF0, // 2 0xF0, 0x10, 0xF0, 0x10, 0xF0, // 3 0x90, 0x90, 0xF0, 0x10, 0x10, // 4 0xF0, 0x80, 0xF0, 0x10, 0xF0, // 5 0xF0, 0x80, 0xF0, 0x90, 0xF0, // 6 0xF0, 0x10, 0x20, 0x40, 0x40, // 7 0xF0, 0x90, 0xF0, 0x90, 0xF0, // 8 0xF0, 0x90, 0xF0, 0x10, 0xF0, // 9 0xF0, 0x90, 0xF0, 0x90, 0x90, // A 0xE0, 0x90, 0xE0, 0x90, 0xE0, // B 0xF0, 0x80, 0x80, 0x80, 0xF0, // C 0xE0, 0x90, 0x90, 0x90, 0xE0, // D 0xF0, 0x80, 0xF0, 0x80, 0xF0, // E 0xF0, 0x80, 0xF0, 0x80, 0x80 // F }; void Chip8::Init() { // Load Initial values I = 0x0; PC = 0x200; SP = 0; DelayTimer = 0; SoundTimer = 0; ReadFontSet(); Clrscr(); ClrKeys(); } void Chip8::ClrKeys() { for (int i = 0 ; i < 16; i++) { Keys[i] = 0x0; } } void Chip8::Clrscr() { for (int i = 0 ; i < WIDTH*HEIGHT ; i++) { DispMem[i] = 0x0; } } void Chip8::KeySig(unsigned char key, bool pressed) { Keys[key] = pressed; //printf("Chip8 reviced key signal Keys[%d] = %d\n",key,pressed); } void Chip8::SigDelayTimer() { --DelayTimer; } void Chip8::Reset() { // Clear memory // Clear registers this->Init(); } void Chip8::ReadFontSet() { for (int i = 0 ; i < FONTSET_SIZE ; i++) { Memory[0x50 + i] = FontSet[i]; } } void Chip8::LoadProgram(const char* file) { cout << "Loading " << file << " ...\n"; int offset = 0; for (std::ifstream f(file, std::ios::binary); f.good();) { Memory[0x200 + (offset++)] = f.get(); } cout << "Loaded\n"; } void Chip8::DumpMemory() { cout << "---------------- Memory Dump ------------------\n"; for (int i = 0 ; i < MEMORY_SIZE ; i++) { printf("%x ",Memory[i]); if (i % 32 == 0 && i!= 0) cout << "\n"; } cout << "\n------------------------------------------------\n"; } // Render the screen void Chip8::RenderTo(Uint32* pixels) { for(unsigned pos = 0 ; pos < WIDTH*HEIGHT ; ++pos) { if (DispMem[pos] == 1) pixels[pos] = 0xFFFFFF; else pixels[pos] = 0x0; } } void Chip8::Exec(void(*ErrCallBack)()) { // Fetch opcode unsigned opcode = (Memory[PC] << 8 ) | Memory[PC +1]; PC += 2; // Extract opcode unsigned INS = opcode >> 12; unsigned X = (opcode & 0x0F00) >> 8 ; unsigned Y = (opcode & 0x00F0) >> 4; unsigned N = opcode & 0x000F; unsigned NN = opcode & 0x00FF; unsigned NNN = opcode & 0x0FFF; unsigned char &VX = V[X], &VY = V[Y] , &VF = V[0xF]; printf("opcode : %X ", opcode); switch(INS) { case 0x0: { switch(NN) { //Ignored :- 0NNN Calls RCA 1802 program at address NNN. Not necessary for most ROMs. case 0xE0: // 00E0 Clears the screen. { break; ErrCallBack(); } case 0xEE:// 00EE Returns from a subroutine. { PC = Stack[--SP]; printf("\tReturn to %X\n",PC); break; } } break; } case 0x1: // 1NNN Jumps to address NNN. { PC = NNN; printf("\tJump to address %X\n",NNN); break; } case 0x2: // 2NNN Calls subroutine at NNN. { Stack[SP++] = PC; PC = NNN; printf("\tJump to %X from %x\n", NNN, Stack[SP-1]); break; } case 0x3: // 3XNN Skips the next instruction if VX equals NN. { if (VX == NN) PC += 2; printf("\tSkip next ins if VX == NN : (%X == %X)\n",VX,NN); break; } case 0x4: // 4XNN Skips the next instruction if VX doesn't equal NN. { if (VX != NN) PC += 2; printf("\tSkip next instr if V[%X] != NN %X != %X\n",X,VX,NN); break; } case 0x5: // 5XY0 Skips the next instruction if VX equals VY. { if (VX == NN) PC += 2; printf("\tSkip next instr if V[%X] == NN %X == %X\n",X,VX,NN); break; } case 0x6: // 6XNN Sets VX to NN. { VX = NN; printf("\tSet V[%X] = %X\n", X , NN); break; } case 0x7: // 7XNN Adds NN to VX. { VX += NN; printf("\tAdd VX += %X\n",NN); break; } case 0x8: { switch (N) { case 0x0:// 8XY0 Sets VX to the value of VY. { VX = VY; printf("\tSet V[%X] = V[%X]\n",X,Y); break; } case 0x1: // 8XY1 Sets VX to VX or VY. { VX |= VY; printf("\tSet V[%X] |= V[%X]\n",X,Y); break; } case 0x2: // 8XY2 Sets VX to VX and VY. { VX &= VY; printf("\tSet V[%X] &= V[%X]\n",X,Y); break; } case 0x3: // 8XY3 Sets VX to VX xor VY. { VX ^= VY; printf("\tSet V[%X] ^= V[%X]\n",X,Y); break; } case 0x4: // 8XY4 Adds VY to VX. VF is set to 1 when there's a carry, and to 0 when there isn't. { unsigned Temp = VX + VY; VX = Temp; VF = Temp >> 8; printf("\tSet V[%X] += V[%X] , VF=%X\n",X,Y,VF); break; } case 0x5: // 8XY5 VY is subtracted from VX. VF is set to 0 when there's a borrow, and 1 when there isn't. { unsigned Temp = VX - VY; VX = !(Temp >> 8); VX = Temp; printf("\tSet V[%X] = V[%X] - V[%X] = %X - %X , VF = %X\n",X,X,Y,VX,VY,VF); break; } case 0x6: // 8XY6 Shifts VX right by one. VF is set to the value of the least significant bit of VX before the shift. { VF = VX & 0X1; VX = VX >> 1; printf("\tShift V[%X] >> 1 , VF = %X\n",X,VF); break; } case 0x7: // 8XY7 Sets VX to VY minus VX. VF is set to 0 when there's a borrow, and 1 when there isn't. { unsigned Temp = VY - VX; VX = !(Temp >> 8); VX = Temp; printf("\tSet V[%X] = V[%X] - V[%X] = %X - %X , VF = %X\n",X,Y,X,VY,VX,VF); break; } case 0xE: // 8XYE Shifts VX left by one. VF is set to the value of the most significant bit of VX before the shift. { VX = VX >> 7; VF = VX << 1; printf("\tShift V[%X] << 1 , VF = %X\n",X,VF); break; } default: { ErrCallBack(); } } break; } case 0x9: // 9XY0 Skips the next instruction if VX doesn't equal VY. { if (VX != VY) PC += 2; printf("\tSkip next instr if V[%X] != V[%Y] %X == %X\n",X,Y,VX,VY); break; } case 0xA:// ANNN Sets I to the address NNN. { I = NNN; printf("\tSet I = %X\n",NNN); break; } case 0xB: // BNNN Jumps to the address NNN plus V0. { PC = NNN + V[0]; printf("\tJump to addr %X + %X\n",NNN,V[0]); break; } case 0xC: // CXNN Sets VX to the result of a bitwise and operation on a random number and NN. { srand(time(NULL)); std::cout<<std::rand()<< endl; unsigned rand = (std::rand() ) && 0xFF; VX = (rand | NN); printf("\tSet V[%X] = %X | %X\n",X,rand,NN); break; } case 0xD: /* DXYN Sprites stored in memory at location in index register (I), 8bits wide. Wraps around the screen. If when drawn, clears a pixel, register VF is set to 1 otherwise it is zero. All drawing is XOR drawing (i.e. it toggles the screen pixels). Sprites are drawn starting at position VX, VY. N is the number of 8bit rows that need to be drawn. If N is greater than 1, second line continues at position VX, VY+1, and so on. */ { VF = 0; for (unsigned y = 0 ; y < N ; y++) { unsigned char line = Memory[I + y]; for (unsigned x = 0 ; x < 8 ; x++) { unsigned pixel = line & (0x80 >> x); if (pixel != 0) { unsigned index = (VY + y) * 64 + (VX + x); if (DispMem[index] == 1) VF = 1; DispMem[index] ^= 1; } } } printf("\tSprite draw @ V[%X],V[%X]\n", X,Y); break; } case 0xE: { switch (NN) { case 0x9E: // EX9E Skips the next instruction if the key stored in VX is pressed. { if (Keys[VX] == 1) PC += 2; break; } case 0xA1:// EXA1 Skips the next instruction if the key stored in VX isn't pressed. { if (Keys[VX] != 0) PC += 2; break; } } break; } case 0xF: { switch (NN) { case 0x07: // FX07 Sets VX to the value of the delay timer. { VX = DelayTimer; printf("\tSet V[%X]=%X\n",X,VX); break; } // FX0A A key press is awaited, and then stored in VX. case 0x15:// FX15 Sets the delay timer to VX. { DelayTimer = VX; printf("\tSet DelayTimer=%X\n",DelayTimer); break; } case 0x18:// FX18 Sets the sound timer to VX. { SoundTimer = VX; printf("\tSet SoundTimer = V[%X] %X\n",X,VX); break; } // FX1E Adds VX to I case 0x29:// FX29 Sets I to the location of the sprite for the character in VX. Characters 0-F (in hexadecimal) are represented by a 4x5 font. { I = 0x50 + VX*5; printf("\tSet I to charater in %X\n",VX); break; } case 0x33: /* FX33 Stores the Binary-coded decimal representation of VX, with the most significant of three digits at the address in I, the middle digit at I plus 1, and the least significant digit at I plus 2. (In other words, take the decimal representation of VX, place the hundreds digit in memory at location in I, the tens digit at location I+1, and the ones digit at location I+2.)*/ { Memory[I] = (VX/100) % 10; Memory[I + 1] = (VX/10) % 10; Memory[I + 2] = (VX) % 10; printf("\tStore BCD of V[%X] @Mem[%d] as (%d, %d, %d)\n",X, I,Memory[I],Memory[I+1],Memory[I+2]); break; } // FX55 Stores V0 to VX (including VX) in memory starting at address I. case 0x65: // FX65 Fills V0 to VX (including VX) with values from memory starting at address I. { for (unsigned i = 0 ; i <= X ; i++) { V[i] = Memory[I+i]; } printf("\tFill V[0] to V[%d] starting from %X\b",X,I); break; } default: { printf("\tInvalid Instruction\n"); ErrCallBack(); break; } } break; } default: { printf("\tInvalid Instruction\n"); ErrCallBack(); break; } } }
true
3b887a4a7e63157380b789b13af278240a908c16
C++
jaehooonjung/Reference
/c_c++/c++제출모음/RPG만들기 2/RPG만들기 2/RPG만들기 2/Character.cpp
UHC
857
2.875
3
[]
no_license
#include "Character.h" Character::Character() { } void Character::InfoSetUp(string Name, int Demage, int Hp, int MaxHp, int Gold, int Exp) { m_strName = Name; m_iDemage = Demage; m_iHp = Hp; m_iMaxHp = MaxHp; m_iGold = Gold; m_iExp = Exp; } void Character::InfoShow(int Width, int Height) { m_MapDrawManager.DrawMidText("=====" + m_strName + "=====", Width, Height++); m_MapDrawManager.DrawMidText("ݷ = " + to_string(m_iDemage) + "\t = " + to_string(m_iHp) + "/" + to_string(m_iMaxHp), Width, Height++); m_MapDrawManager.DrawMidText("GOLD = " + to_string(m_iGold) + "EXP = " + to_string(m_iExp), Width, Height++); } void Character::DemagePhase(int Demage) { m_iHp -= Demage; } bool Character::DeathCheck() { if (m_iHp <= 0) { m_iHp = m_iMaxHp; return true; } else return false; } Character::~Character() { }
true
e42ac508fc444c22674d5b6435dc7c899ba31ae5
C++
frankzhangrui/MPI_FFT
/fft2d.cc
UTF-8
5,905
2.890625
3
[]
no_license
// Distributed two-dimensional Discrete FFT transform // YOUR NAME HERE // ECE8893 Project 1 #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <signal.h> #include <math.h> #include <mpi.h> #include <stdio.h> #include <stdlib.h> #include "Complex.h" #include "InputImage.h" using namespace std; void Transpose(Complex* src, int N, int M, Complex* dst){ for(int n = 0; n<N*M; n++) { int i = n/N; int j = n%N; dst[n] = src[M*j + i]; } } void Transform1D(Complex* h, int w, Complex* H) { // Implement a simple 1-d DFT using the double summation equation // given in the assignment handout. h is the time-domain input // data, w is the width (N), and H is the output array. int N = w; for(int n=0; n< N; ++ n){ Complex sum; for(int k=0; k < N ; ++k){ sum = sum + Complex(cos(2*M_PI*n*k/N), -sin(2*M_PI*n*k/N)) * h[k]; } H[n] = sum; } } void Transform2D(const char* inputFN) { // Do the 2D transform here. // 1) Use the InputImage object to read in the Tower.txt file and // find the width/height of the input image. // 2) Use MPI to find how many CPUs in total, and which one // this process is // 3) Allocate an array of Complex object of sufficient size to // hold the 2d DFT results (size is width * height) // 4) Obtain a pointer to the Complex 1d array of input data // 5) Do the individual 1D transforms on the rows assigned to your CPU // 6) Send the resultant transformed values to the appropriate // other processors for the next phase. // 6a) To send and receive columns, you might need a separate // Complex array of the correct size. // 7) Receive messages from other processes to collect your columns // 8) When all columns received, do the 1D transforms on the columns // 9) Send final answers to CPU 0 (unless you are CPU 0) // 9a) If you are CPU 0, collect all values from other processors // and print out with SaveImageData(). int width, height; InputImage image(inputFN); // Create the helper object for reading the image width = image.GetWidth(); height = image.GetHeight(); // Step (1) in the comments is the line above. // Your code here, steps 2-9 //2 find the number of CPU int rank, size; MPI_Comm_size(MPI_COMM_WORLD,&size); MPI_Comm_rank(MPI_COMM_WORLD,&rank); int numRow ; if( rank == size-1) numRow = min(height- static_cast<int>(ceil(height/size))*(size-1), static_cast<int>(ceil(height/size))); else numRow = static_cast<int>(ceil(height/size)) ; int numElem = numRow * width; Complex* h = new Complex[ numElem]; Complex* H = new Complex[ numElem]; cout<<rank<<" " <<numElem<<endl; memcpy( h, image.GetImageData()+ numElem * rank, numElem *sizeof(Complex) ); for( int i=0 ; i< numRow ; ++i) Transform1D(h+i*width, width, H+i*width) ; MPI_Barrier(MPI_COMM_WORLD); MPI_Request request; MPI_Status status; MPI_Isend(H,numElem*sizeof(Complex),MPI_CHAR,0,0,MPI_COMM_WORLD, &request); cout<< "all 1d is done " <<endl; if(rank == 0){ int rc; Complex* rh = new Complex[ width*height] ; for(int i=0 ;i < size; ++i) { rc=MPI_Recv(rh+ numElem*i,numElem*sizeof(Complex),MPI_CHAR,i,0, MPI_COMM_WORLD,&status); if (rc != MPI_SUCCESS){ cout << "Rank " << i << " send failed, rc " << rc << endl; MPI_Finalize(); exit(1); } } image.SaveImageData("MyAfter1d.txt", rh , width, height); cout<<"One dimension transformation is saved"<<endl; Complex* transposed = new Complex[ width*height] ; Transpose(rh, width, height, transposed); memcpy(h,transposed,numElem*sizeof(Complex)); cout<<"beginnign to send"<<endl; for(int i=1; i < size; ++i) MPI_Isend(transposed+i*numElem,numElem*sizeof(Complex),MPI_CHAR,i,0,MPI_COMM_WORLD,&request); delete[] rh; delete[] transposed; cout<<"sending to individual process of transformed array"<<endl; } // 1d transformation is completed, now continue to debug second part if(rank !=0) MPI_Recv(h,numElem*sizeof(Complex),MPI_CHAR,0,0,MPI_COMM_WORLD,&status); for( int i=0 ; i< numRow ; ++i) Transform1D(h+i*width, width, H+i*width) ; cout<<"ending second transform"<<endl; // if(rank != 0) MPI_Isend(H,numElem*sizeof(Complex),MPI_CHAR,0,0,MPI_COMM_WORLD,&request); // if(rank == 0){ // Complex* transposed = new Complex[ width*height] ; // Complex* rh = new Complex[ width*height] ; // for(int i=1 ;i < size; ++i) MPI_Recv(rh+ numElem*i,numElem*sizeof(Complex),MPI_CHAR,i,0, MPI_COMM_WORLD,&status); // memcpy(rh,h,numElem*sizeof(Complex)); // Transpose(rh,width,height,transposed); // image.SaveImageData("after2d_my_solution.txt", transposed , width, height); // delete[] rh; // delete[] transposed; // } MPI_Barrier(MPI_COMM_WORLD); Complex* transposed; Complex* rh ; cout<<"beginnning to gather"<<endl; if(rank==0){ transposed = new Complex[ width*height]; rh= new Complex[ width*height]; } MPI_Gather(H,numElem*sizeof(Complex),MPI_CHAR,rh,numElem*sizeof(Complex),MPI_CHAR,0,MPI_COMM_WORLD); if(rank ==0){ Transpose(rh,width,height,transposed); image.SaveImageData("MyAfter2d.txt", transposed , width, height); delete[] rh; delete[] transposed; } delete[] h; delete[] H; return ; } int main(int argc, char** argv) { string fn("Tower.txt"); // default file name if (argc > 1) fn = string(argv[1]); // if name specified on cmd line // MPI initialization here int rc; rc = MPI_Init(&argc,&argv); if (rc != MPI_SUCCESS) { printf ("Error starting MPI program. Terminating.\n"); MPI_Abort(MPI_COMM_WORLD, rc); } Transform2D(fn.c_str()); // Perform the transform. // Finalize MPI here MPI_Finalize(); return 0; }
true
c7d8ce8f0bd06b5a9598d220b0cfdd7b6fa23b52
C++
shaolanqing/C-code
/mydev3.cpp
UTF-8
267
3.34375
3
[]
no_license
#include<iostream> using namespace std; void swap(int &x,int &y) { int temp=x; x=y; y=temp; } int main() { int a,b; cout <<"please intput two nums:"<<endl; cin >>a>>b; swap(a,b); cout <<"swap:"<< a <<" "<< b <<endl; system("pause"); return 0; }
true
deb1d0cd3290ce49990457d59e074e2d27a8a17c
C++
fiatveritas/Intro_to_C-
/In_Class/Week_4/LAB/ProblemSix.cpp
UTF-8
2,299
3.40625
3
[]
no_license
//Written by: Jesse Gallegos //Assignment: LAB WORK page 105 #6 //Date: 19 September 2018 /*Description: This program computes your gross income, social security tax, federal tax, state tax, union dues, healthcare tax, and net income given the number of hours worked and number of dependents.*/ #include <iostream> using namespace std; int main(){ double hours_worked, gross_wages, social_tax, federal_tax, state_tax, health_fee, net_income; const double UNION_DUES = 10; int num_dependents; char choice; cout << "This program computes your weekly Gross\n" <<"Income, weekly Deductions, and weekly Net\n" <<"Income.\n"; do{ cout << "\nPlease type in the number of hours worked: "; cin >> hours_worked; cout << "Please enter number of dependents: "; cin >> num_dependents; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); //precision set to 2 because monetary values if(hours_worked > 40){ gross_wages = 40 * 16.78 + (hours_worked - 40) * 16.78 * 1.5; // formula for overtime pay cout << "\nGross Wages: $" << gross_wages << endl; } else{ gross_wages = hours_worked * 16.78; //basepay formula cout << "\nGross Wages: $" << gross_wages << endl; } social_tax = gross_wages * .06; //simple calculation of taxes federal_tax = gross_wages * .14; state_tax = gross_wages * .05; cout << "Social Security Tax: $" << social_tax << endl; cout << "Federal Income Tax: $" << federal_tax << endl; cout << "State Income Tax: $" << state_tax<< endl; cout << "Union dues: $" << UNION_DUES << endl; if(num_dependents >= 3) //check if healthcare tax is applicable. health_fee = 35; else health_fee = 0; cout << "Healthcare tax: $" << health_fee << endl; net_income = gross_wages - social_tax - federal_tax //subtract deductions from gross earnings. - state_tax - health_fee - UNION_DUES; cout << "Net Income: $" << net_income << endl << endl; cout << "Do you want to recalculate?\n" << "Enter \'y\' or \'Y\' to continue.\n" << "Enter any other key to end "; cin >> choice; } while(choice == 'Y' || choice == 'y'); return 0; }
true
96eca70bb5699748f772164874bcd13b88c7933f
C++
Brotin003/Programming
/C++ Tutorials/Tutorial18.cpp
UTF-8
475
3.75
4
[]
no_license
// Selection control structure : IF else - if - else ladder #include <iostream> using namespace std; int main() { int age; cout << "Tell me your age" << endl; cin >> age; if (age < 18) { cout << "You can't come to my party" << endl; } else if (age == 18) { cout << "You are a kid and you will get a kid pass to the party" << endl; } else { cout << "You can come to the party" << endl; } return 0; }
true
cba5fc6f106132377aaf3393d5cdb8f0b1ae1d12
C++
gregjauvion/bio_simulation
/conception/simulation-algorithms/cpp-code-specific-model_repressilator_1/src/Cell.cpp
UTF-8
892
2.71875
3
[]
no_license
#include "Cell.hpp" RanGen Cell::ran_gen = RanGen(0) ; bool Cell::should_divide () { if (V > target_V_div) { V_div = V ; return true ; } return false ; } void Cell::choose_new_size () { V_birth = V_div * ran_gen.norm (0.5,Parameters::sigma_size_split) ; V = V_birth ; } void Cell::do_partitioning () { double p = V_birth / V_div ; double old_A = A ; A = 0 ; for (int i=0 ; i<old_A ; i++) if (ran_gen.doub01()<p) A++ ; double old_B = B ; B = 0 ; for (int i=0 ; i<old_B ; i++) if (ran_gen.doub01()<p) B++ ; double old_C = C ; C = 0 ; for (int i=0 ; i<old_C ; i++) if (ran_gen.doub01()<p) C++ ; } void Cell::do_birth_update () { target_V_div = Parameters::a * V_birth + Parameters::b + ran_gen.norm(0,Parameters::sigma_size_div) ; mu_cell = ran_gen.norm(Parameters::mu_avg,Parameters::sigma_mu) ; } void Cell::grow (double dt) { V *= exp ( dt * mu_cell ) ; }
true
0f18064b37bf71f885ade10b7ea687b4b20d2a02
C++
evenam/Synthadeus
/Synthadeus/Synthadeus/ux_comp/base/ButtonBase.h
UTF-8
1,697
3.046875
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////// // // // Button Base // // Everett Moser // // 11-14-15 // // // // Simple logic for a button based on held state or serial events // // // //////////////////////////////////////////////////////////////////////////////// #pragma once class ButtonBase { public: // state check inline bool check() { return isHeld && !isDebounced; }; // pressed this update cycle? inline bool checkPressed() { return isPressed && !isDebounced; }; // released this update cycle? inline bool checkReleased() { return isReleased && !isDebounced; }; // reset the button state, it must be pressed again to trigger bounced state inline void debounce() { isDebounced = true; }; // construct button in debounced state ButtonBase(); // update the state variables with the pressed status void update(bool isCurrentlyPressed); // update the state variables with the event variables void update(); // trigger a pressed event (untested) inline void press() { toggle = true; }; // trigger a released event (untested) inline void release() { toggle = false; }; private: // state variables bool isPressed, isHeld, isReleased, isDebounced; // serial event state variable (untested) bool toggle; };
true
7fe8f7dc9b07e82df1a458d5bd860876107f5c6f
C++
jguoaj/intelligent-scissor
/Scissor/FibonacciHeap/fibtest.cpp
UTF-8
2,571
2.78125
3
[]
no_license
//*************************************************************************** // FIBTEST.CPP // // Test program for the F-heap implementation. // Copyright (c) 1996 by John Boyer. // See header file for free usage information. //*************************************************************************** #include <stdlib.h> #include <iostream.h> #include <stdio.h> // #include <conio.h> #include <ctype.h> // #include <mem.h> #include <string.h> #include <time.h> #include "fibheap.h" class HeapNode : public FibHeapNode { float Key; public: HeapNode() : FibHeapNode() { Key = 0; }; virtual void operator =(FibHeapNode& RHS); virtual int operator ==(FibHeapNode& RHS); virtual int operator <(FibHeapNode& RHS); virtual void operator =(float NewKeyVal); virtual void Print(); float GetKeyValue() { return Key; }; void SetKeyValue(float inkey) { Key = inkey; }; }; void HeapNode::Print() { FibHeapNode::Print(); cout << Key; } void HeapNode::operator =(float NewKeyVal) { HeapNode Temp; Temp.Key = Key = NewKeyVal; FHN_Assign(Temp); } void HeapNode::operator =(FibHeapNode& RHS) { FHN_Assign(RHS); Key = ((HeapNode&) RHS).Key; } int HeapNode::operator ==(FibHeapNode& RHS) { if (FHN_Cmp(RHS)) return 0; return Key == ((HeapNode&) RHS).Key ? 1 : 0; } int HeapNode::operator <(FibHeapNode& RHS) { int X; if ((X=FHN_Cmp(RHS)) != 0) return X < 0 ? 1 : 0; return Key < ((HeapNode&) RHS).Key ? 1 : 0; }; /* int IntCmp(const void *pA, const void *pB) { int A, B; A = *((const int *) pA); B = *((const int *) pB); if (A < B) return -1; if (A == B) return 0; return 1; } */ void main() { HeapNode *Min; HeapNode *A; FibHeap *theHeap = NULL; int Max=20; // Setup for the Fibonacci heap if ((theHeap = new FibHeap) == NULL || (A = new HeapNode[Max+1]) == NULL) { cout << "Memory allocation failed-- ABORTING.\n"; exit(-1); } // theHeap->ClearHeapOwnership(); for (int i=0;i<Max;i++) A[i].SetKeyValue (-(float)i); for (i=Max-1;i>=0;i--) theHeap->Insert(&A[i]); cout << "before #nodes = " << theHeap->GetNumNodes() << endl; for (i=0;i<Max;i++) { if ((Min = (HeapNode*) theHeap->ExtractMin ()) != NULL) { float key = -Min->GetKeyValue(); cout << key << ' '; } } cout << endl; for (i=0;i<Max;i++) cout << A[i].GetKeyValue() << ' '; cout << "after #nodes = " << theHeap->GetNumNodes() << endl; // Cleanup; test heap ownership flag settings delete theHeap; }
true
79ec84b874ede582174f3f9923ce2bc15896c8ef
C++
ankitaaaaaaaaaa/project1
/test.cpp
UTF-8
424
2.984375
3
[]
no_license
#include<stdio.h> /*int inc(int i){ static int c=0; c=c+i; return(c); } int main(){ int i,j; for(i=0;i<=4;i++){ j=inc(i); } printf("%d",j); return 0; } int main(){ int k=35, *z, *y; y=z=&k; printf("k = %d z = %p y = %p",k,z,y); *z++= *y--; k++; printf("k = %d z = %p y = %p",k,z,y); return 0; }*/ int main(){ int arr[1]={ 10 }; printf(" the value is %d", arr[1]); return 0; }
true
b2a5eccc5076ad77acef5a8386241aeb7c130739
C++
ArunJayan/OpenCV-Cpp
/first_readDisplay.cpp
UTF-8
1,041
2.859375
3
[]
no_license
#include <iostream> #include <opencv2/highgui/highgui.hpp> using namespace std; using namespace cv; int main(int argc,const char** argv) { Mat img;//Mat datastructure stores image img = imread("cat.jpg",CV_LOAD_IMAGE_GRAYSCALE); //using imread() we can read image //first argument is name of the image to be loaded // second argument is the flag : // CV_LOAD_IMAGE_COLOR // CV_LOAD_IMAGE_UNCHANGED // CV_LOAD_IMAGE_GRAYSCALE // CV_LOAD_IMAGE_ANYCOLOR // CV_LOAD_IMAGE_ANYDEPTH if(!img.data) //if image is not loaded { cout<<"Image can not be loaded"<<endl; } else { cout<<"Image loaded successfully"<<endl; } //cout<<img; //display binary image namedWindow("cat",CV_WINDOW_AUTOSIZE); //create a window for showing the image // first parameter is the name of the window // second is the flag : // CV_WINDOW_AUTOSIZE // CV_WINDOW_NORMAL imshow("cat",img); //display the image in window waitKey(0); //waitKey() for a keypress for certain time destroyWindow("cat"); return 0; }
true
99df7285335e611641c04a2223eef3aa27d7ca8a
C++
yimengfan/BDFramework.Core
/HybridCLRData/LocalIl2CppData-OSXEditor/il2cpp/libil2cpp/utils/PathUtils.h
UTF-8
2,985
2.984375
3
[ "Apache-2.0" ]
permissive
#pragma once #include "il2cpp-config.h" #include <string> #include "StringViewUtils.h" namespace il2cpp { namespace utils { namespace PathUtils { std::string BasenameNoExtension(const std::string& path); std::string PathNoExtension(const std::string& path); template<typename CharType> std::basic_string<CharType> Basename(const utils::StringView<CharType>& path) { if (path.IsEmpty()) return std::basic_string<CharType>(1, static_cast<CharType>('.')); const size_t pos = path.RFind(IL2CPP_DIR_SEPARATOR); // No seperators. Path is filename if (pos == utils::StringView<CharType>::NPos()) return std::basic_string<CharType>(path.Str(), path.Length()); return std::basic_string<CharType>(path.Str() + pos + 1, path.Length() - pos - 1); } template<typename CharType> std::basic_string<CharType> Basename(const std::basic_string<CharType>& path) { return Basename(STRING_TO_STRINGVIEW(path)); } template<typename CharType> std::basic_string<CharType> DirectoryName(const utils::StringView<CharType>& path) { if (path.IsEmpty()) return std::basic_string<CharType>(); const size_t pos = path.RFind(IL2CPP_DIR_SEPARATOR); if (pos == utils::StringView<CharType>::NPos()) return std::basic_string<CharType>(1, static_cast<CharType>('.')); if (pos == 0) return std::basic_string<CharType>(1, static_cast<CharType>('/')); return std::basic_string<CharType>(path.Str(), pos); } template<typename CharType> std::basic_string<CharType> Combine(const utils::StringView<CharType>& path1, const utils::StringView<CharType>& path2) { std::basic_string<CharType> result; result.reserve(path1.Length() + path2.Length() + 1); result.append(path1.Str(), path1.Length()); result.append(1, static_cast<CharType>(IL2CPP_DIR_SEPARATOR)); result.append(path2.Str(), path2.Length()); return result; } template<typename CharType> std::basic_string<CharType> DirectoryName(const std::basic_string<CharType>& path) { return DirectoryName(STRING_TO_STRINGVIEW(path)); } template<typename CharType> std::basic_string<CharType> Combine(const std::basic_string<CharType>& path1, const std::basic_string<CharType>& path2) { return Combine(STRING_TO_STRINGVIEW(path1), STRING_TO_STRINGVIEW(path2)); } template<typename CharType> std::basic_string<CharType> Combine(const std::basic_string<CharType>& path1, const utils::StringView<CharType>& path2) { return Combine(STRING_TO_STRINGVIEW(path1), path2); } template<typename CharType> std::basic_string<CharType> Combine(const utils::StringView<CharType>& path1, const std::basic_string<CharType>& path2) { return Combine(path1, STRING_TO_STRINGVIEW(path2)); } } } /* utils */ } /* il2cpp */
true
ff436a684c2026585ab329ced5e33c5140580b1e
C++
HJiahu/learn_caffe_src
/read_caffe_vs2015/read_caffe_vs2015/caffe_src/caffe/layers/shuffle_channel_layer.cpp
GB18030
4,754
2.75
3
[]
no_license
#include <algorithm> #include <vector> #include "caffe/layers/shuffle_channel_layer.hpp" namespace caffe { template <typename Dtype> void ShuffleChannelLayer<Dtype>::LayerSetUp (const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) { group_ = this->layer_param_.shuffle_channel_param().group(); CHECK_GT (group_, 0) << "group must be greater than 0"; //temp_blob_.ReshapeLike(*bottom[0]); top[0]->ReshapeLike (*bottom[0]); } // forward_cpu֪溯IJ template <typename Dtype> void ShuffleChannelLayer<Dtype>::Resize_cpu ( Dtype *output,// ָ const Dtype *input,// ָ int group_row,// shuffleֵͨ int group_column,// ÿаchannelĸ int len// ÿfeature map ) { // Ĵ뽫channelһ󣬽ṹΪ(group_row,group_column) for (int i = 0; i < group_row; ++i) // Ԫص { for (int j = 0; j < group_column ; ++j) // Ԫص { const Dtype* p_i = input + (i * group_column + j) * len; //p_iָÿһfeature mapڴе׵ַ Dtype* p_o = output + (j * group_row + i) * len; //бת caffe_copy (len, p_i, p_o); } } } template <typename Dtype> void ShuffleChannelLayer<Dtype>::Reshape (const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top) { int channels_ = bottom[0]->channels(); int height_ = bottom[0]->height(); int width_ = bottom[0]->width(); top[0]->Reshape (bottom[0]->num(), channels_, height_, width_); } template <typename Dtype> void ShuffleChannelLayer<Dtype>::Forward_cpu (const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const Dtype* bottom_data = bottom[0]->cpu_data(); Dtype* top_data = top[0]->mutable_cpu_data(); const int num = bottom[0]->shape (0); // ȡƺ̫ʣĸfeature mapܺͣܺͣ const int feature_map_size = bottom[0]->count (1); const int sp_sz = bottom[0]->count (2);// ÿfeature mapвĸfeature mapе const int chs = bottom[0]->shape (1);// ͨĸfeature map int group_row = group_;// shufflenetgroupֵshuffe㽫ֵͨ int group_column = int (chs / group_row);// ÿͨĸͨΪgroup飬ÿͨĸ CHECK_EQ (chs, (group_column * group_row)) << "Wrong group size."; //Dtype* temp_data = temp_blob_.mutable_cpu_data(); for (int n = 0; n < num; ++n) { // ΪtestʱnumΪ1ĴԼΪ // Resize_cpu (top_data , bottom_data , group_row, group_column, sp_sz); Resize_cpu (top_data + n * feature_map_size, bottom_data + n * feature_map_size, group_row, group_column, sp_sz); } //caffe_copy(bottom[0]->count(), temp_blob_.cpu_data(), top_data); } template <typename Dtype> void ShuffleChannelLayer<Dtype>::Backward_cpu (const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { if (propagate_down[0]) { const Dtype* top_diff = top[0]->cpu_diff(); Dtype* bottom_diff = bottom[0]->mutable_cpu_diff(); const int num = bottom[0]->shape (0); const int feature_map_size = bottom[0]->count (1); const int sp_sz = bottom[0]->count (2); const int chs = bottom[0]->shape (1); int group_row = int (chs / group_); int group_column = group_; //Dtype* temp_diff = temp_blob_.mutable_cpu_diff(); for (int n = 0; n < num; ++n) { Resize_cpu (bottom_diff + n * feature_map_size, top_diff + n * feature_map_size, group_row, group_column, sp_sz); } //caffe_copy(top[0]->count(), temp_blob_.cpu_diff(), bottom_diff); } } #ifdef CPU_ONLY STUB_GPU (ShuffleChannelLayer); #endif INSTANTIATE_CLASS (ShuffleChannelLayer); REGISTER_LAYER_CLASS (ShuffleChannel); } // namespace caffe
true
bb9bd788a5ca3af2076bdbb36b6e90929a79862b
C++
lsthiros/cellular-automata
/CellularAutomataAlgorithm.cpp
UTF-8
443
2.703125
3
[]
no_license
#include "CellularAutomataAlgorithm.hpp" CellularAutomataAlgorithm::CellularAutomataAlgorithm(std::vector<int> born, std::vector<int> survive, int iterations) : born(born), survive(survive), iterations(iterations) { } void CellularAutomataAlgorithm::runAlgorithm(CellularAutomataGrid &grid) { for(int i = 0; i < iterations; i++) { grid.applyRule(born, survive); } if(nextStep) { nextStep->runAlgorithm(grid); } }
true
5b84e59d6a30d161320dcdfb7c5f49c95a4d0053
C++
daniel-torquato/VRP
/src/Convexo/src/convexo.cpp
UTF-8
2,367
3.078125
3
[]
no_license
#include <fstream> #include <complex> #include <vector> typedef std::complex<double> point; typedef std::vector<point> route; typedef unsigned uint; double sign( point A, point B) { return (A.real()*B.imag()-A.imag()*B.real()); } bool In( route V, point X) { uint n=V.size(); for ( uint k=0; k<n-1; k++) if ( sign(V[k+1]-V[k], X-V[k]) > 0) return false; if(sign( V[0]-V[n-1], X-V[n-1]) > 0) return false; return true; } uint positive( route V, point X) { uint n=V.size(); uint P=0; for( uint k=1; k<n-1; k++) if( sign(V[k]-V[k-1], X-V[k-1]) <0 && sign(V[k+1]-V[k], X-V[k])>=0) P=k; if( sign(V[n-1]-V[n-2], X-V[n-2]) <0 && sign( V[0]-V[n-1], X-V[n-1])>= 0) P=n-1; return P; } uint negative( route V, point X) { uint n=V.size(); uint P=0; for( uint k=1; k<V.size()-1; k++) if( sign(V[k]-V[k-1], X-V[k-1]) > 0 && sign(V[k+1]-V[k], X-V[k]) <= 0) P=k; if( sign(V[n-1]-V[n-2], X-V[n-2]) >0 & sign( V[0]-V[n-1], X-V[n-1]) <= 0) P=n-1; return P; } void apagar( route& V, uint P, uint N) { if( N==P+1) return; if( N>=V.size()) return; if( P+1<N ) { V.erase(V.begin()+P+1, V.begin()+N); } else { V.erase(V.begin()+P+1, V.end()); V.erase(V.begin(), V.begin()+N); } } route bordo_convexo( route X ) { route fecho; route AUX(X); fecho.push_back(AUX[0]); fecho.push_back(AUX[1]); AUX.erase(AUX.begin(), AUX.begin()+2); for( uint k=2; k<AUX.size(); k++) if( sign(AUX[k]-fecho[0],fecho[1]-fecho[0]) >0) { fecho.push_back(AUX[k]); AUX.erase(AUX.begin()+k); break; } for( uint k=2; k<AUX.size(); k++) { if( In(fecho, AUX[k])) continue; uint v=positive( fecho, AUX[k]), w=negative( fecho, AUX[k]); apagar(fecho, v, w); if( w>v) fecho.insert(fecho.begin()+v+1, AUX[k]); else fecho.insert(fecho.begin(), AUX[k]); } return fecho; } route read(char* filename){ std::ifstream in( filename); route R; point aux; while ( in >> aux.real() >> aux.imag() ) { R.push_back(aux); } return R; } void write( route A, char* filename) { std::ofstream out( filename); for ( uint i=0; i<A.size(); i++) { out << A[i].real() << " " << A[i].imag() << std::endl; } out << A[0].real() << " " << A[0].imag() << std::endl; out.close(); } int main(int argc, char** argv) { route X=read(argv[1]); route Aux=bordo_convexo(X); write(Aux,argv[2]); return 0; }
true
d4c6a61dc041526969d39d6ba64f978f359ce06f
C++
ayushchhabra/cpplearn
/generic_adjlist.cpp
UTF-8
2,116
3.296875
3
[]
no_license
#include<iostream> #include<unordered_map> #include<list> #include<queue> #include<map> using namespace std; template <typename T> class Graph{ unordered_map<T,list<T> >adjlist; public: void addedge(T u,T v,bool bidir=true){ adjlist[u].push_back(v); if(bidir){ adjlist[v].push_back(u); } } void print(){ for(auto node:adjlist){ cout<<node.first<<"-->"; for(auto neighbour:node.second){ cout<<neighbour<<","; } cout<<endl; } } void bfs(T src){ queue<T> q; map<T,bool> visited; q.push(src); visited[src]=true; while(!q.empty()){ T node=q.front(); cout<<node<<" "; q.pop(); for(auto neighbour:adjlist[node]){ if(!visited[neighbour]){ q.push(neighbour); visited[neighbour]=true; } } } cout<<endl; } int sssp(T src,T des){ queue<T> q; map<T,int> dist; map<T,T> parent; for(auto node:adjlist){ dist[node.first]=INT_MAX; } q.push(src); dist[src]=0; parent[src]=src; while(!q.empty()){ T node=q.front(); q.pop(); for(auto children:adjlist[node]){ if(dist[children]==INT_MAX){ parent[children]=node; dist[children]=dist[node]+1; q.push(children); } } } for(auto node:adjlist){ cout<<"Dist of "<<node.first<<"from "<<src<<"to"<<des<<" is "<<dist[node.first]<<endl; } return dist[des]; } }; int main(){ Graph<string> g; g.addedge("Putin","Trump"); g.addedge("Putin","Modi"); g.addedge("Putin","Pope"); g.addedge("Modi","Trump",true); g.addedge("Modi","Yogi",true); g.addedge("Yogi","Prabhu"); g.addedge("Prabhu","Modi"); // g.bfs("Modi"); // g.print(); g.sssp("Modi","Prabhu"); return 0; }
true
2029ff7879b4c5e7421c82715d35796e8d65840f
C++
WSU-Cpts322/snake-revisited-jramirez1989
/Snake!Revisited Final Version/Snake.cpp
UTF-8
2,932
3.359375
3
[ "MIT" ]
permissive
#include "Snake.h" Snake::Snake() { Coordinates a = Coordinates(42, 20); Coordinates b = Coordinates(41, 20); Coordinates c = Coordinates(40, 20); Coordinates d = Coordinates(39, 20); Coordinates head = Coordinates(38, 20); body.push_back(a); body.push_back(b); body.push_back(c); body.push_back(d); body.push_back(head); previousDirection = 'R'; } vector<Coordinates> Snake::getBody() { return body; } char Snake::getPreviousDirection() { return previousDirection; } void Snake::setPreviousDirection(char direction) { previousDirection = direction; } string Snake::moveSnake(char direction, Pellet pellet, int powerCounter) { Coordinates newHead = body.front(); int oldPosition; if (direction == 'U') { if (previousDirection == 'D') { oldPosition = newHead.getYposition(); newHead.setYposition(oldPosition + 1); previousDirection = 'D'; } else { oldPosition = newHead.getYposition(); newHead.setYposition(oldPosition - 1); previousDirection = 'U'; } } else if (direction == 'D') { if (previousDirection == 'U') { oldPosition = newHead.getYposition(); newHead.setYposition(oldPosition - 1); previousDirection = 'U'; } else { int oldPosition = newHead.getYposition(); newHead.setYposition(oldPosition + 1); previousDirection = 'D'; } } else if (direction == 'L') { if (previousDirection == 'R') { oldPosition = newHead.getXposition(); newHead.setXposition(oldPosition + 1); previousDirection = 'R'; } else { oldPosition = newHead.getXposition(); newHead.setXposition(oldPosition - 1); previousDirection = 'L'; } } else if (direction == 'R') { if (previousDirection == 'L') { oldPosition = newHead.getXposition(); newHead.setXposition(oldPosition - 1); previousDirection = 'L'; } else { oldPosition = newHead.getXposition(); newHead.setXposition(oldPosition + 1); previousDirection = 'R'; } } body.insert(body.begin(), newHead); if (!(headCollidedWithPellet(pellet))) { if (powerCounter <= 0) { body.pop_back(); } } else { return "pellet"; } if (headCollidedWithBody(newHead)) { return "body"; } return "good"; } bool Snake::headCollidedWithBody(Coordinates headPosition) { for (unsigned int i = 1; i < body.size(); i++) { if (headPosition.equals(body[i])) { return true; } } return false; } bool Snake::headCollidedWithPellet(Pellet currentPellet) { if (currentPellet.getLocation().equals(body.front())) { return true; } else { return false; } } void Snake::printBodyCoordinates() { for (unsigned int i = 0; i < body.size(); i++) { cout << i << ": " << body[i].getXposition() << ", " << body[i].getYposition() << endl; } }
true
219f00b02d56259ffc7724a42d5342d729cb3651
C++
zonasse/Algorithm
/coding interview guide/链表/将单链表的每K个节点之间逆序.cpp
UTF-8
1,071
3.34375
3
[]
no_license
// // Created by 钟奇龙 on 2019-04-16. // #include <iostream> #include <stack> using namespace std; class Node{ public: int data; Node *next; Node(int x):data(x),next(NULL){ } }; //将栈内节点顺序连接并返回链表尾节点 Node* resignStack(stack<Node*> &node_stack,Node* left, Node* right){ Node *cur = node_stack.top(); node_stack.pop(); if(left){ left->next = cur; } while(node_stack.empty() == false){ Node *next = node_stack.top(); node_stack.pop(); cur->next = next; cur = next; } cur->next = right; return cur; } Node* reversePerKNodes(Node *head,int k){ if(k < 2) return head; stack<Node*> node_stack; Node *newHead = head; Node *pre = NULL; Node *cur = head; while(cur){ Node* next = cur->next; node_stack.push(cur); if(node_stack.size() == k){ pre = resignStack(node_stack,pre,next); newHead = newHead == head ? cur:newHead; } cur = next; } return newHead; }
true
308b66bd710e8de026be3a2b4883748367a2253e
C++
lsiddiqsunny/Leetcode-solve
/September Challange/Maximum XOR of Two Numbers in an Array.cpp
UTF-8
665
2.828125
3
[]
no_license
class Solution { public: int findMaximumXOR(vector<int> &arr) { int maxx = 0, mask = 0; int n = arr.size(); set<int> se; for (int i = 31; i >= 0; i--) { mask |= (1 << i); for (int i = 0; i < n; ++i) { se.insert(arr[i] & mask); } int newMaxx = maxx | (1 << i); for (int prefix : se) { if (se.count(newMaxx ^ prefix)) { maxx = newMaxx; break; } } se.clear(); } return maxx; } };
true
eb2ab000c3720f8919e59fa4d1663f7c4e36b29c
C++
LucasM127/Stuff-I-Don-t-Want-To-Lose
/Moonlander/Observer.hpp
UTF-8
417
2.765625
3
[]
no_license
#ifndef OBSERVER_HPP #define OBSERVER_HPP //public domain... class Observer { public: virtual ~Observer(){} virtual void onNotify() = 0; }; class Subject { public: Subject():m_observer(nullptr){} virtual ~Subject(){} inline void setObserver(Observer *observer){m_observer = observer;} inline void notify(){if(m_observer) m_observer->onNotify();} private: Observer *m_observer; }; #endif
true
6a4f928daf58db4bd4e26e111198d69dcef15122
C++
ndhuanhuan/MLinAction
/295. *Find Median from Data Stream.cpp
UTF-8
813
3.46875
3
[]
no_license
//http://www.cnblogs.com/jcliBlogger/p/4893468.html //https://www.hrwhisper.me/leetcode-find-median-from-data-stream/ 最大堆取最大,最小堆取最小 class MedianFinder { priority_queue<int> small, large; public: // Adds a number into the data structure. void addNum(int num) { if (!large.empty() && -large.top() < num) large.push(-num); else small.push(num); if (small.size() - large.size() == 2) { large.push(-small.top()); small.pop(); } else if (small.size() - large.size() == -2) { small.push(-large.top()); large.pop(); } } // Returns the median of current data stream double findMedian() { if (small.size() > large.size()) return small.top(); else if (small.size() < large.size()) return -large.top(); return (small.top() - large.top()) / 2.0; } };
true
8bbbce5f7cdd1c6f065244f084cf05996dd09da6
C++
adamfowleruk/cppexamples
/release/src/TestClasses.hpp
UTF-8
1,007
3.125
3
[ "Apache-2.0" ]
permissive
#include <string> namespace mltests { using namespace std; /* * ANTI PATTERN */ class StringReference { public: StringReference(); void setString(std::string& strRef); std::string& getString(); private: std::string str; }; /* * ANTI PATTERN */ class StringHolder { public: StringHolder(std::string s); std::string* getString(); private: std::string* str; }; /* * Working use of the unique_ptr with a container pattern - See testpointerwrapper.cpp for full details. */ class PointerWrapper { public: PointerWrapper(); ~PointerWrapper(); void setString(std::unique_ptr<std::string> str); // requires move semantics, and this class takes ownership std::string& getString(); private: std::unique_ptr<std::string> ptr; // STEP 6: declare as a plain object, no pointers, no references, no const }; /* * ANTI PATTERN */ class StringWrapper { public: StringWrapper(); ~StringWrapper(); void setString(std::string str); std::string getString(); private: std::string theString; }; }
true
af2ce70bdcc487c3ae13a68f6826a53dec485023
C++
ricaun/esp32-lora-serial
/esp32-lora-serial/pbutton.ino
UTF-8
1,312
2.84375
3
[ "MIT" ]
permissive
//----------------------------------------// // pbutton.ino // // created 03/06/2019 // by Luiz Henrique Cassettari //----------------------------------------// // update 28/06/2019 // add button time to turn off wifi //----------------------------------------// #define BUTTON 0 #define BUTTON_MODE_MAX 2 #define BUTTON_RUNEVERY 300000 static int button_i = 1; void button_setup() { pinMode(BUTTON, INPUT_PULLUP); } boolean button_press() { static boolean last; boolean now = digitalRead(BUTTON); boolean ret = (now == false & last == true); last = now; return ret; } boolean button_loop() { if (button_runEvery(BUTTON_RUNEVERY)) { if (button_i != 0) { button_i = 0; return true; } } if (button_press()) { button_runEvery(0); button_i++; return true; } return false; } int button_count() { return button_i; } String button_mode() { button_i = button_i % BUTTON_MODE_MAX; switch (button_i) { case 0: return "MODE WIFI OFF"; case 1: return "MODE WIFI ON"; } } boolean button_runEvery(unsigned long interval) { static unsigned long previousMillis = 0; unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= interval) { previousMillis = currentMillis; return true; } return false; }
true
75f48a0d759eec61283a7e12f5bfd75a48d00052
C++
Junkmen/HackFMI
/main.cpp
UTF-8
911
2.859375
3
[]
no_license
#include <iostream> using namespace std; #include "GameObject.hpp" int main(){ SDL_Window* window = (SDL_Window*)nullptr; SDL_Renderer* renderer = (SDL_Renderer*)nullptr; SDL_CreateWindowAndRenderer(0, 0, SDL_WINDOW_FULLSCREEN_DESKTOP, &window, &renderer); bool running = false; if(window != (SDL_Window*)nullptr && renderer != (SDL_Renderer*)nullptr){ running = true; } SDL_Event event; GameObject obj(25, 25, "a.jpg"); obj.load_texture(renderer, "a.jpg"); obj.set_width(250); obj.set_height(250); while(running){ if(SDL_PollEvent(&event)){ if(event.key.keysym.scancode == SDL_SCANCODE_ESCAPE) running = false; } SDL_RenderClear(renderer); obj.draw(renderer); obj.set_x(rand() % 1430); obj.set_y(rand() % 500); SDL_RenderPresent(renderer); }; return 0; };
true
3efc6eed0a5f706290e2d25c30e400d7d9057b56
C++
NuriYuri/LiteRGSS
/ext/LiteRGSS/CTone_Element.h
UTF-8
886
2.640625
3
[]
no_license
#ifndef CTONE_ELEMENT_H #define CTONE_ELEMENT_H #include <SFML/Graphics.hpp> #include "CViewport_Element.h" class CTone_Element { private: sf::Glsl::Vec4 tonevalues; CViewport_Element* target_ = nullptr; public: CTone_Element() = default; ~CTone_Element() { if(target_ != nullptr) { target_->bindTone(nullptr); } } sf::Glsl::Vec4* getTone() { return &tonevalues; }; void bindViewport(CViewport_Element* target) { if(target != target_) { auto lastLinkedElement = target_; target_ = nullptr; if(lastLinkedElement != nullptr) { lastLinkedElement->bindTone(nullptr); } target_ = target; if(target_ != nullptr) { target_->bindTone(this); } } } CViewport_Element* getViewport() { return target_; } }; namespace meta { template<> struct Log<CTone_Element> { static constexpr auto classname = "Tone"; }; } #endif
true
89ee4bd127e631b64bccbc2d3db29f4551d99aad
C++
dwentzel/bounce
/headers/importer/imported_model.h
UTF-8
1,646
2.609375
3
[]
no_license
#ifndef BOUNCE_IMPORTER_IMPORTED_MODEL_H_ #define BOUNCE_IMPORTER_IMPORTED_MODEL_H_ #include <memory> #include <vector> #include "imported_material.h" namespace bounce { class ImportedModelImpl; class ImportedModel { private: ImportedModelImpl* impl_; ImportedModel(const ImportedModel&) = delete; ImportedModel& operator=(const ImportedModel&) = delete; public: ImportedModel(); ImportedModel(ImportedModel&& source); ~ImportedModel(); void AddMesh( unsigned int first_vertex, unsigned int vertex_count, unsigned int first_index, unsigned int index_count, unsigned int material_index); void AddVertex(float x, float y, float z); void AddUV(float x, float y); void AddNormal(float x, float y, float z); void AddIndex(unsigned short index); void AddMaterial(const ImportedMaterial& material); unsigned short mesh_count() const; unsigned int GetMeshIndexOffset(unsigned short mesh_index) const; unsigned int GetMeshIndexCount(unsigned short mesh_index) const; unsigned int GetMeshFirstVertex(unsigned short mesh_index) const; unsigned int GetMeshVertexCount(unsigned short mesh_index) const; const ImportedMaterial& GetMeshMaterial(unsigned short mesh_index) const; const std::vector<float>& vertex_data() const; const std::vector<unsigned short>& index_data() const; }; } #endif // BOUNCE_IMPORTER_IMPORTED_MODEL_H_
true
28ada8a47925e90f4efba4ad24077bbfa840b216
C++
m-karcz/pythonpp
/helpers/contains-helper.h
UTF-8
1,186
3.109375
3
[]
no_license
#pragma once #include <algorithm> #include <type_traits> namespace helper { template<typename... Ts> struct make_void { typedef void type;}; template<typename... Ts> using void_t = typename make_void<Ts...>::type; template<typename Container, typename = void_t<>> struct hasFindMemberFn : std::false_type {}; template<typename Container> struct hasFindMemberFn<Container, void_t<decltype(std::declval<Container>().find(std::declval<typename Container::key_type>()))>> : std::true_type {}; template<typename Container> struct hasFindMemberFn<Container, void_t<decltype(std::declval<Container>().find(std::declval<typename Container::value_type>()))>> : std::true_type {}; template<typename T, typename Container> inline auto containsValue(const T& value, const Container& container) -> std::enable_if_t<!hasFindMemberFn<Container>::value, bool> { return std::find(container.begin(), container.end(), value) != container.end(); } template<typename T, typename Container> inline std::enable_if_t<hasFindMemberFn<Container>::value, bool> containsValue(const T& value, const Container& container) { return container.find(value) != container.end(); } }//namespace helper
true
4074ccadb5ed587a7cb58d3dd89314abef4cf811
C++
1143910315/mimabaoguan
/list.cpp
UTF-8
462
2.796875
3
[ "Artistic-2.0" ]
permissive
#include "list.h" /* list::list() { } list::list(T data) { indata=data; } */ template <class T> list<T>::list() { } template <class T> list<T>::list(T data) { indata=data; } template <class T> bool list<T>::ru(T data) { if(next==nullptr){ next=new list(data); }else{ list temp=next; while (temp.next!=nullptr) { temp=temp.next; } temp.next=new list(data); } return true; } template <class T> bool list<T>::chu(T &data) { }
true
d7ed5d8d6c9665a629451d96597c428148d5044d
C++
ancapantilie/data-structures-and-algorithms-hw2
/DsaHW2/doubly-linked-linear-list.h
UTF-8
5,740
3.609375
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; template<typename T> struct list_elem { T info; struct list_elem<T> *next, *prev; }; template <typename T> class LinkedList { public: struct list_elem<T> *pfirst, *plast; void addFirst(T x) { struct list_elem<T> *paux; paux = new struct list_elem<T>; paux->info = x; paux->prev = NULL; paux->next = pfirst; if (pfirst != NULL) pfirst->prev = paux; pfirst = paux; if (plast==NULL) plast=pfirst; } void addLast(T x) { struct list_elem<T> *paux; paux = new struct list_elem<T>; paux->info = x; paux->prev = plast; paux->next = NULL; if (plast != NULL) plast->next = paux; plast = paux; if (pfirst == NULL) pfirst = plast; } void removeFirst() { struct list_elem<T>* paux; if (pfirst != NULL) { paux = pfirst->next; if (pfirst == plast) plast = NULL; delete pfirst; pfirst = paux; if (pfirst != NULL) pfirst->prev = NULL; } else cout<<"The list is empty"<<endl; } void removeLast() { struct list_elem<T> *paux; if (plast != NULL) { paux = plast->prev; if (pfirst == plast) pfirst = NULL; delete plast; plast = paux; if (plast != NULL) plast->next = NULL; } else cout<<"The list is empty"<<endl; } struct list_elem<T>* findFirstOccurrence(T x) { struct list_elem<T> *paux; paux = pfirst; while (paux != NULL) { if (paux->info == x) return paux; paux = paux->next; } return NULL; } struct list_elem<T>* findLastOccurrence(T x) { struct list_elem<T> *paux; paux = plast; while (paux != NULL) { if (paux->info == x) return paux; paux = paux->prev; } return NULL; } void removeFirstOccurrence(T x) { struct list_elem<T> *px; px = findFirstOccurrence(x); if (px != NULL) { if (px->prev != NULL) px->prev->next = px->next; if (px->next != NULL) px->next->prev = px->prev; if (px->prev == NULL) // px == pfirst pfirst = px->next; if (px->next == NULL) // px == plast plast = px->prev; delete px; } } void removeLastOccurrence(T x) { struct list_elem<T> *px; px = findLastOccurrence(x); if (px != NULL) { if (px->prev != NULL) px->prev->next = px->next; if (px->next != NULL) px->next->prev = px->prev; if (px->prev == NULL) // px == pfirst pfirst = px->next; if (px->next == NULL) // px == plast plast = px->prev; delete px; } } void listInsert(int x) { if(findFirstOccurrence(x) == NULL){ addFirst(x); } else { cout << "Already in list" << "\n"; } } void sortedListInsert(int x){ struct list_elem<int> *p, *paux; p = pfirst; while (p != NULL && p->info < x) p = p->next; if (p == NULL) addLast(x); else { paux = new struct list_elem<int>; paux->info = x; paux->next = p; paux->prev = p->prev; if (p->prev != NULL) p->prev->next = paux; else pfirst = paux; p->prev = paux; } } int dividedByZNr (int z) { int result= 0; struct list_elem<int> *paux; paux = pfirst; while (paux != NULL) { if (paux->info % z == 0){ result++; } paux = paux->next; } return result; } int greaterThanFirstNr(){ int result= 0; struct list_elem<int> *paux; paux = pfirst; while (paux != NULL){ if(paux->info > pfirst->info){ result++; } paux=paux->next; } return result; } int findOccurenceNr(int x){ int result= 0; struct list_elem<int> *paux; paux = pfirst; while (paux != NULL){ if(paux->info == x){ result++; } paux=paux->next; } return result; } int isEmpty() { return (pfirst == NULL); } LinkedList() { pfirst = plast = NULL; } void printList() { struct list_elem<T> *p; p = pfirst; while (p != NULL) { cout<<p->info<<" "; p = p->next; } } //the sorting algorihm used for ex2 void sortAscending(){ struct list_elem<T> *paux; paux = pfirst; while (paux != NULL) { struct list_elem<T> *paux2; paux2 = paux->next; while(paux2 != NULL){ if(paux2->info < paux->info ){ T aux= paux->info; paux->info=paux2->info; paux2->info=aux; } paux2=paux2->next; } paux=paux->next; } } };
true
325a016e6fdd9a8dfa0ab340c83dab9df0088117
C++
reimeytal/pong
/src/paddle/paddle.cpp
UTF-8
2,502
2.5625
3
[]
no_license
#include <gml/gml.hpp> #include <gl/glew.h> #include <cstdint> #include "../shader/shader.hpp" #include "../vertex.h" #include "../entity/entity.hpp" #include "../bounding-box/bounding-box.hpp" #include "paddle.hpp" #define PONG_PADDLE_SPEED 6.f unsigned int pong::Paddle::vbo = 0; unsigned int pong::Paddle::ibo = 0; unsigned int pong::Paddle::vao = 0; namespace pong{ void Paddle::init(){ glGenVertexArrays(1, &vao); glBindVertexArray(vao); vertex_t paddleVertices[4] = { {-1.0f, 4.5f}, { 1.0f, 4.5f}, { 1.0f, -4.5f}, {-1.0f, -4.5f} }; unsigned int paddleIndices[6] = { 1, 3, 2, 0, 3, 1 }; glGenBuffers(1, &vbo); glGenBuffers(1, &ibo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_t)*4, paddleVertices, GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int)*6, paddleIndices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_t), 0); glBindVertexArray(0); } Paddle::Paddle(){ modelMatrix.scale(0.175f, 0.175f, 1.0f); } void Paddle::draw(const Shader& shader, const gml::mat4& projectionMatrix) const{ glBindVertexArray(Paddle::vao); glBindBuffer(GL_ARRAY_BUFFER, Paddle::vbo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Paddle::ibo); shader.bind(); shader.useUniformMat4f("projectionMatrix", projectionMatrix); shader.useUniformMat4f("modelMatrix", modelMatrix); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL); glBindVertexArray(0); } BoundingBox Paddle::getBoundingBox(){ gml::vec4 bl = modelMatrix * gml::vec4(-1.0f, -4.5f, 0.0f, 1.0f); //bottom left corner gml::vec4 size = gml::vec4(2.0f * modelMatrix(0, 0), 9.0f * modelMatrix(1, 1), 0.0f, 1.0f); return BoundingBox(gml::vec2(bl.x, bl.y), gml::vec2(size.x, size.y)); //size is the bottom left corner } void Paddle::move(uint8_t moveDirection, float deltatime){ switch(moveDirection){ case PADDLE_UP: modelMatrix.translate(0.0f, PONG_PADDLE_SPEED * deltatime, 0.0f); break; case PADDLE_DOWN: modelMatrix.translate(0.0f, -PONG_PADDLE_SPEED * deltatime, 0.0f); break; } } void Paddle::reset(){ modelMatrix(1, 3) = 0.0f; } void Paddle::uninit(){ glDeleteBuffers(1, &vbo); glDeleteBuffers(1, &ibo); } }
true
75903dd1103d78ccccb504a6b3df9a17ebb56a4e
C++
ggharibian/Graphing-Calculator-C
/SFML Graphing Calculator/!includes/Queue/Queue_Test_Functions.cpp
UTF-8
6,806
3.78125
4
[]
no_license
#include "Queue_Test_Functions.h" Queue<int> getAscendingQueue() { //Returns an ascending Queue. Queue<int> q; for (int i = 1; i <= 10; i++) q.Push(i * 10); return q; } Queue<int> getDecendingQueue() { //Returns an decending Queue. Queue<int> q; for (int i = 10; i >= 1; i--) q.Push(i * 10); return q; } Queue<int> getRandomQueue() { //Returns a Queue of random values Queue<int> q; for (int i = 0; i < 10; i++) q.Push(rand() % 100 + 1); return q; } void testQueueCopyConstructor() { cout << "============ Testing Copy Constructor ============" << endl; cout << endl << "Copying Filled Queue:" << endl; cout << "//Calling 'copy = q'; copy ==> H->[10]->[20]-> ... ->[100]->|||" << endl << endl; Queue<int> q = getAscendingQueue(); Queue<int> copy(q); cout << "Popping " << q.Pop() << " out of q." << endl << endl; cout << "Printing s: " << q << endl; cout << "Printing copy: " << copy; cout << endl << endl << "Copying Empty Queue:" << endl; cout << "//Calling 'otherCopy(s)'; otherCopy ==> H->|||" << endl << endl; q.~Queue(); Queue<int> otherCopy(q); cout << "Printing s: " << q << endl; cout << "Printing otherCopy: " << otherCopy << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueAssignmentOperator() { cout << "============ Testing '=' operator ============" << endl; cout << endl << "Copying Filled Queue:" << endl; cout << "//Calling 'copy = q'; copy ==> H->[10]->[20]-> ... ->[100]->|||" << endl << endl; Queue<int> q = getAscendingQueue(); Queue<int> copy = q; cout << "Popping " << q.Pop() << " out of q." << endl << endl; cout << "Printing s: " << q << endl; cout << "Printing copy: " << copy; cout << endl << endl << "Self Reference:" << endl; cout << "//Calling 'q = s'; q ==> H->[20]->[30]-> ... ->[100]->|||" << endl << endl; q = q; cout << "Printing s: " << q << endl; cout << endl << endl << "Copying Empty Queue:" << endl; cout << "//Calling 'copy = q'; copy ==> H->|||" << endl << endl; q.~Queue(); copy = q; cout << "Printing s: " << q << endl; cout << "Printing copy: " << copy; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueDeallocate() { cout << "============ Testing Deallocation ============" << endl << endl; cout << "//Calling q.~Queue(); H->[10]->[20]->... ==> H->|||" << endl << endl; Queue<int> q = getAscendingQueue(); cout << q << endl << endl; q.~Queue(); cout << q << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueuePush() { //Tests cout << "============ Testing Push() ============" << endl; cout << endl <<"//Adding multiples of 10 to s: 10 -> 20 -> 30 -> ... 90 -> 100 -> |||" << endl << endl; Queue<int> q; cout << q << endl << endl; for (int i = 10; i >= 1; i--) cout << *q.Push(i * 10) << " has been pushed." << endl; cout << endl << q << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueuePop() { cout << "============ Testing Pop() ============" << endl; cout << endl << "Popping all values from a Queue:" << endl; cout << "//H->[10]->[20]->[30]->... ==> H->|||" << endl << endl; Queue<int> q; q = getAscendingQueue(); cout << q << endl << endl; while (!q.Empty()) cout << q.Pop() << " has been popped." << endl; cout << endl << q << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueFront() { cout << "============ Testing Front ============" << endl; cout << endl << "Accessing Front of filled Queue:" << endl; cout << "//Calling q.Front() ==> 100" << endl << endl; Queue<int> q = getDecendingQueue(); cout << q << endl << endl; cout << "q.Front() = " << q.Front() << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueEmpty() { cout << "============ Testing Empty ============" << endl; cout << endl << "Checking if filled Queue is empty:" << endl; cout << "//Calling q.Empty() ==> 0 (false)" << endl << endl; Queue<int> q = getAscendingQueue(); cout << q << endl << endl; cout << "q.Empty() = " << q.Empty() << endl; q.~Queue(); cout << endl << endl << "Checking if empty Queue is empty:" << endl; cout << "//Calling q.Empty() ==> 1 (true)" << endl << endl; cout << q << endl << endl; cout << "q.Empty() = " << q.Empty() << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueOutput() { //Tests cout << "============ Testing Print / '<<' ============" << endl; cout << endl << "//Adding multiples of 10 to s: 10 -> 20 -> 30 -> ... 90 -> 100 -> |||" << endl << endl; Queue<int> q = getAscendingQueue(); cout << "q.Print() ==> "; q.Print(); cout << endl << "'cout << s' ==> "; cout << q << endl; cout << "\n============ END TEST ========================" << endl << endl; } void testQueueIterator() { cout << "============ Testing Queue Iterator ============" << endl << endl; cout << "Calling the current value of the iterator in the Queue:"; cout << endl << "//*iter ==> [10]->" << endl << endl; Queue<int> q = getAscendingQueue(); cout << q << endl << endl; Queue<int>::Iterator iter = q.Begin(); cout << "*iter = " << *iter << endl << endl; cout << "Calling the next value of the Queue using iterator:"; cout << endl << "//*(iter.Next()) ==> [20]->" << endl << endl; cout << q << endl << endl; cout << "*(iter.Next()) = " << *(iter.Next()) << endl << endl; cout << "Accessing a value inside iterator using '->':"; cout << endl << "//iter->_obj ==> 10" << endl << endl; cout << q << endl << endl; cout << "iter->_obj = " << *iter << endl << endl; cout << "Calling the prefix and postfix '++' operators:"; cout << endl << "//otherIter = ++iter; otherIter, iter ==> [20]->, [20]->" << endl << endl; iter = q.Begin(); cout << "Calling otherIter = ++iter" << endl << endl; Queue<int>::Iterator otherIter = ++iter; cout << "*otherIter = " << *otherIter << endl; cout << "*iter = " << *iter << endl; cout << endl << "//otherIter = iter++; otherIter, iter ==> [10]->, [20]->" << endl; iter = q.Begin(); cout << endl << "Calling otherIter = iter++" << endl; otherIter = iter++; cout << "*otherIter = " << *otherIter << endl; cout << "*iter = " << *iter << endl; cout << endl << "Calling the '!=' operators:"; cout << endl << "//otherIter != iter ==> 1 (true) " << endl << endl; cout << "otherIter != iter: " << (otherIter != iter) << endl; cout << endl << "//otherIter != otherIter ==> 0 (false) " << endl << endl; cout << "otherIter != otherIter: " << (otherIter != otherIter) << endl; cout << "\n============ END TEST ========================" << endl << endl; }
true
23b95e2e1c82189a4a9d36aedc030fff472d85c9
C++
GaoLF/Leetcode
/Spiral Matrix .cpp
UTF-8
1,643
2.828125
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include <cctype> #include<algorithm> #include<math.h> using namespace std ; typedef struct ListNode{ int val; ListNode * next; } ListNode; class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> res; int col,row=matrix.size(),cur; int flag,i,j; if(!row) return res; col=matrix[0].size(); enum dir{ right=0,down,left,up }; i=0; j=0; flag=right; for(int pp=0;pp<(row*col);pp++){ res.push_back(matrix[i][j]); if(flag==right){ if(j<(col-i-1)){ j++; } else{ i++; flag=(flag+1)%4; } } else if(flag==down){ if(i<(row-(col-j))){ i++; } else{ j--; flag=(flag+1)%4; } } else if(flag==left){ if(j>(row-i-1)){ j--; } else{ i--; flag=(flag+1)%4; } } else if(flag==up){ if(i>(j+1)){ i--; } else{ j++; flag=(flag+1)%4; } } } return res; } void print() { vector<vector<int> > A; vector<int> B; B.push_back(1); B.push_back(2); B.push_back(3); A.push_back(B); spiralOrder(A); B.clear(); B.push_back(4); B.push_back(5); B.push_back(6); A.push_back(B); B.clear(); spiralOrder(A); B.push_back(7); B.push_back(8); B.push_back(9); A.push_back(B); cout<<A[1][2]<<endl; spiralOrder(A); } }; int main() { Solution test; // cout<<test.Low("A man, a plan, a canal: Panama")<<endl; test.print(); // cout<<atoi("2147483648")<<endl; system("pause"); }
true
f8d70f7dcfd0ae6f33d1efc3b548e488141e13cd
C++
carlushuang/kernel-launcher-amdgpu
/src/main.cpp
UTF-8
4,313
2.625
3
[]
no_license
#include "hsa_backend.h" #include <random> #include <math.h> #include <iostream> #include <string> #include <stdio.h> int asm_kernel(){ int rtn; backend * engine = new hsa_backend(); rtn = engine->init_backend(); if(rtn) return -1; std::cout<<"engine init ok"<<std::endl; hsa_dispatch_param d_param; kernarg * out = engine->alloc_kernarg(16); d_param.emplace_kernarg(out); d_param.code_file_name = "kernel/asm-kernel.co"; d_param.kernel_symbol = "hello_world"; d_param.kernel_arg_size = 1*sizeof(void *); d_param.local_size[0] = 1; d_param.local_size[1] = 0; d_param.local_size[2] = 0; d_param.global_size[0] = 1; d_param.global_size[1] = 0; d_param.global_size[2] = 0; rtn = engine->setup_dispatch(&d_param); if(rtn) return -1; std::cout<<"setup_dispatch ok"<<std::endl; rtn = engine->dispatch(); if(rtn) return -1; std::cout<<"dispatch ok"<<std::endl; rtn = engine->wait(); if(rtn) return -1; std::cout<<"wait ok"<<std::endl; out->from_local(); std::cout<<"out:"<< *out->data<float>()<<std::endl; return 0; } inline void host_vec_add(float * in, float * out, int num){ for(int i=0;i<num;i++){ out[i] += in[i]; } } #define MIN_DELTA 1e-5 inline void valid_vec(float * host, float * dev, int num){ float delta; bool valid = true; for(int i=0;i<num;i++){ delta = fabsf(host[i] - dev[i]); if(delta > MIN_DELTA){ printf("-- host/dev diff %f at %d, with %f, %f each, min %f\n", delta, i, host[i], dev[i], MIN_DELTA); valid = false; } } if(valid) printf("-- host/dev all valid with min delta %f\n", MIN_DELTA); } #define RANDOM_MIN .0f #define RANDOM_MAX 10.f void gen_vec(float * vec, int len){ std::random_device rd; std::mt19937 e2(rd()); std::uniform_real_distribution<float> dist(RANDOM_MIN, RANDOM_MAX); for(int i=0;i<len;i++){ vec[i] = dist(e2); } } #define VEC_LEN 1000 #define GROUP_SIZE 64 #define GRID_SIZE 12 int vector_add(){ int rtn; backend * engine = new hsa_backend(); rtn = engine->init_backend(); if(rtn) return -1; std::cout<<"engine init ok"<<std::endl; hsa_dispatch_param d_param; kernarg * ka_in = engine->alloc_kernarg(sizeof(float)*VEC_LEN); kernarg * ka_out = engine->alloc_kernarg(sizeof(float)*VEC_LEN); kernarg * ka_num = engine->alloc_kernarg_pod(sizeof(int)); const int vec_len = VEC_LEN; float * host_in, * host_out; float * dev_in, * dev_out; host_in = new float[vec_len]; host_out = new float[vec_len]; //host_out_2 = new float[vec_len]; gen_vec(host_in, vec_len); gen_vec(host_out, vec_len); for(int i=0;i<vec_len;i++){ ka_in->data<float>()[i] = host_in[i]; ka_out->data<float>()[i] = host_out[i]; } *(ka_num->data<int>()) = vec_len; ka_in->to_local(); ka_out->to_local(); // ka_num->to_local(); d_param.emplace_kernarg(ka_in); d_param.emplace_kernarg(ka_out); d_param.emplace_kernarg(ka_num); d_param.code_file_name = "kernel/vector-add-2.co"; d_param.kernel_symbol = "vector_add"; d_param.kernel_arg_size = 2*sizeof(void *) + sizeof(int); // should be 20 d_param.local_size[0] = GROUP_SIZE; d_param.local_size[1] = 0; d_param.local_size[2] = 0; d_param.global_size[0] = GROUP_SIZE * GRID_SIZE; d_param.global_size[1] = 0; d_param.global_size[2] = 0; rtn = engine->setup_dispatch(&d_param); if(rtn) return -1; std::cout<<"setup_dispatch ok"<<std::endl; std::cout<<"in ptr:"<<ka_in->local_ptr()<<std::endl; std::cout<<"out ptr:"<<ka_out->local_ptr()<<std::endl; std::cout<<"num ptr:"<<ka_num->local_ptr()<<std::endl; rtn = engine->dispatch(); if(rtn) return -1; std::cout<<"dispatch ok"<<std::endl; rtn = engine->wait(); if(rtn) return -1; std::cout<<"wait ok"<<std::endl; ka_out->from_local(); host_vec_add(host_in, host_out, vec_len); //std::cout<<"out:"<< *out->data<float>()<<std::endl; valid_vec(host_out, ka_out->data<float>(), vec_len); delete [] host_in; delete [] host_out; return 0; } int main(int argc, char ** argv){ //return asm_kernel(); return vector_add(); }
true
333bf68169a1922e2d18ac02516607efa938d82a
C++
foxox/afdtd
/FDTD3D/foxmath3.h
UTF-8
2,046
2.703125
3
[]
no_license
#ifndef FOXMATH3H #define FOXMATH3H #include <math.h> static const float PI = (float)3.1415926535897932384626433832795; static const float DEG2RAD = (float)0.01745329251994329576923690768489; static const float RAD2DEG = (float)57.295779513082320876798154814105; typedef unsigned int uint; #ifdef __cplusplus namespace FM { #endif //#ifndef __cplusplus typedef struct Vec2 Vec2; typedef struct Vec3 Vec3; typedef struct Mat4 Mat4; typedef struct Vec2 { float u; float v; } Vec2; typedef struct Vec3 { float x; float y; float z; } Vec3; typedef struct Vec4 { float r; float g; float b; float a; } Vec4; typedef struct Mat4 { float mat[4][4]; } Mat4; /* #else struct Vec3 { public: float x; float y; float z; //Vec3(); //Vec3(float x, float y, float z); }; struct Vec4TODO { public: float r; float g; float b; float a; }; class Mat4 { public: float mat[4][4]; Mat4(); }; #endif*/ //VEC2 FUNCTIONS Vec2 Vec2GenVec2(float u, float v); //VEC3 FUNCTIONS Vec3 Vec3GenVec3(float x, float y, float z); void Vec3ZeroOut(Vec3*); void Vec3NormalizeOut(Vec3*); float Vec3DotProduct(Vec3, Vec3); Vec3 Vec3CrossProduct(Vec3, Vec3); Vec3 Vec3Add(Vec3, Vec3); Vec3 Vec3Sub(Vec3, Vec3); float Vec3Length(Vec3); float Vec3LengthSquared(Vec3); //MAT4 FUNCTIONS void Mat4ZeroOut(Mat4*); void Mat4IdentityOut(Mat4*); Mat4 Mat4GenZero(); Mat4 Mat4GenIdentity(); Mat4 Mat4GenTranslate(float, float, float); Mat4 Mat4Transpose(Mat4); Mat4 Mat4Mat4Multiply(Mat4, Mat4); //COMBO FUNCTIONS Vec3 Vec3Mat4Transform(Vec3, Mat4); Vec3 Vec3Mat4TransformNormal(Vec3, Mat4); //GRAPHICS SUPPORT Mat4 Mat4GenPerspectiveProjection(float fovx, float aspect, float near, float far); Mat4 Mat4GenLookAtTransform(Vec3 pos, Vec3 target, Vec3 up); //CPP stuff /* #ifdef __cplusplus //Operator overloads Vec3 operator+(Vec3 a, Vec3 b); Vec3 operator-(Vec3 a, Vec3 b); float operator*(Vec3 a, Vec3 b); Vec3 operator%(Vec3 a, Vec3 b); #endif */ #ifdef __cplusplus } #endif #endif
true
aae6011ab3c4952fb1dae49e4d39f5daddb8b7b8
C++
Masters-Akt/CS_codes
/leetcode_sol/1441-Build_An_Array_With_Stack_Operations.cpp
UTF-8
429
2.734375
3
[]
no_license
class Solution { public: vector<string> buildArray(vector<int>& target, int n) { vector<string> ans; int j = 1; for(int i=0;i<target.size();i++){ if(target[i]==j){ ans.push_back("Push"); }else{ ans.push_back("Push"); ans.push_back("Pop"); i--; } j++; } return ans; } };
true
1044ed522a9d3a1775f2856293ccba54fe560c11
C++
GuilhermeCaetano/DarkLight-Engine-3
/Branch_Master/Dark Light Engine 3/DarkLightEngine3/include/Shader/cShader.cpp
UTF-8
914
2.640625
3
[]
no_license
// cShader.cpp #include <Shader\cShaderManager.h> // the shader class itself is kinda big, so we'll separate it from the manager class cShaderManager::cShader::cShader() { this->shaderType = cShader::eShaderTypes::UNKNOWN; this->shaderID = -1; return; } cShaderManager::cShader::~cShader() { return; } std::string cShaderManager::cShader::GetShaderType() { switch (this->shaderType) { case eShaderTypes::VERTEX_SHADER: return "VERTEX_SHADER"; break; case eShaderTypes::FRAGMENT_SHADER: return "FRAGMENT_SHADER"; break; case eShaderTypes::GEOMETRY_SHADER: return "Geometry_Shader"; break; case eShaderTypes::TESSELATION_SHADER: return "Tesselation_Shader"; break; case eShaderTypes::COMPUTATION_SHADER: return "Computation_Shader"; break; case eShaderTypes::UNKNOWN: return "Unknown"; // Shouldn't happen break; } return "Unknown"; // Also shouldn't happen }
true
52f1471d1bededd85aa6041e8ac1d5bc292a1dbc
C++
th3or14/semaphore
/tests.cpp
UTF-8
3,518
3.09375
3
[]
no_license
#include "tests.hpp" namespace { template <typename T> class SemaphoreInterface { public: SemaphoreInterface(size_t passing_limit); void adjust_passing_limit(size_t limit); void wait(); void signal(); private: T impl; }; class Semaphore2 { public: explicit Semaphore2(size_t passing_limit = 1); void adjust_passing_limit(size_t limit); void wait(); void signal(); private: size_t now_serving; size_t next_ticket; size_t passing_cnt; size_t passing_limit; std::condition_variable cond_var; mutable std::mutex mtx; }; } // namespace template <typename T> static std::chrono::milliseconds run_performance_benchmark(int threads_cnt) { auto t1 = std::chrono::high_resolution_clock::now(); SemaphoreInterface<T> semaphore(0); std::vector<std::thread> threads; for (int i = 0; i < threads_cnt; ++i) { threads.push_back(std::thread([&semaphore] { semaphore.wait(); semaphore.signal(); })); } semaphore.adjust_passing_limit(1); for (auto &t : threads) t.join(); auto t2 = std::chrono::high_resolution_clock::now(); return std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1); } template <typename T> SemaphoreInterface<T>::SemaphoreInterface(size_t passing_limit) : impl(passing_limit) {} template <typename T> void SemaphoreInterface<T>::adjust_passing_limit(size_t limit) { impl.adjust_passing_limit(limit); } template <typename T> void SemaphoreInterface<T>::wait() { impl.wait(); } template <typename T> void SemaphoreInterface<T>::signal() { impl.signal(); } Semaphore2::Semaphore2(size_t passing_limit) : now_serving(0), next_ticket(0), passing_cnt(0), passing_limit(passing_limit) {} void Semaphore2::adjust_passing_limit(size_t limit) { std::unique_lock<std::mutex> ul(mtx); passing_limit = limit; cond_var.notify_all(); } void Semaphore2::wait() { std::unique_lock<std::mutex> ul(mtx); size_t my_ticket = next_ticket; ++next_ticket; cond_var.wait(ul, [=]() -> bool { return (my_ticket == now_serving) && (passing_cnt < passing_limit); }); ++passing_cnt; ++now_serving; cond_var.notify_all(); } void Semaphore2::signal() { std::unique_lock<std::mutex> ul(mtx); if (passing_cnt == 0) throw std::logic_error("nothing to signal"); --passing_cnt; cond_var.notify_all(); } bool run_fairness_check(int threads_cnt, std::chrono::milliseconds delay_between_threads_creation) { Semaphore semaphore(0); std::vector<std::thread> threads; std::vector<size_t> passing_order; for (int i = 0; i < threads_cnt; ++i) { if (i > 0) std::this_thread::sleep_for(delay_between_threads_creation); threads.push_back(std::thread([&semaphore, &passing_order, i] { semaphore.wait(); passing_order.push_back(i); semaphore.signal(); })); } semaphore.adjust_passing_limit(1); for (auto &t : threads) t.join(); for (size_t i = 0; i < passing_order.size(); ++i) if (passing_order.at(i) != i) return false; return true; } std::chrono::milliseconds run_proposed_impl_performance_benchmark(int threads_cnt) { return run_performance_benchmark<Semaphore>(threads_cnt); } std::chrono::milliseconds run_alternative_impl_performance_benchmark(int threads_cnt) { return run_performance_benchmark<Semaphore2>(threads_cnt); }
true
954bde0e737c2f6c4c183c525952f615124a2205
C++
DSFlare/Anthill
/Anthill/Graphic/Mesh.cpp
WINDOWS-1251
1,495
2.90625
3
[]
no_license
#include "Mesh.h" Mesh::Mesh(vector<Vertex> vertices, vector<unsigned int> indices, sf::Texture *texture) { this->vertices = vertices; this->indices = indices; this->texture = texture; setupMesh(); } void Mesh::Draw(Shader shader) { glEnable(GL_TEXTURE_2D); sf::Texture::bind(texture); // glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); sf::Texture::bind(0); } void Mesh::setupMesh() { glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // vertex positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, texCoords)); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); }
true
be46fbabba38ea577c6730a13576c2edc740c2d1
C++
Olysold/Space-Invaders---SFML
/include/Invaders.h
UTF-8
1,793
2.9375
3
[]
no_license
#ifndef INVADERS_H_INCLUDED #define INVADERS_H_INCLUDED #include <SFML\Graphics.hpp> #include <SFML\Audio.hpp> #include "AnimatedSprite.h" #include "Bullets.h" #include <vector> #include <list> #include <memory> class Invaders { public: typedef std::vector<std::vector<AnimatedSprite>> InvaderMatrixVec; typedef std::vector<std::vector<AnimatedSprite>>::iterator VecColIter; typedef std::vector<AnimatedSprite>::iterator VecRowIter; Invaders(); //Getters and setters std::shared_ptr<InvaderMatrixVec> getInvaders() const; AnimatedSprite getRandomInvader(); void setInvaderSpeed(const sf::Time); std::shared_ptr<std::list<sf::Sprite>> getDeathNumber() const; void setDeathAnimation(const sf::Sprite&); void setDeathAudio(const sf::Sound&); //Setup and update work void populateInvaders(AnimatedSprite&); void updateDead(const sf::Time&); //Interactions void kill(VecColIter, VecRowIter); void multiMove(const sf::Time&); void multiShoot(const sf::Time&, Bullets&); private: std::default_random_engine m_engine; std::uniform_int_distribution<unsigned> m_engineSeed; //Invader population std::shared_ptr<InvaderMatrixVec> m_invaderPop; int m_posX; int m_posY; //Movement int m_moveX; int m_moveY; sf::Time m_currTime; sf::Time m_invaderSpeed; bool m_movingLeft = false; //Bullets sf::Time m_bulletFrequency; sf::Time m_currbulletTime; sf::Time m_bulletSpeed; std::uniform_real_distribution<double> m_bulletSpawnChance; //Death sf::Sprite m_death; std::shared_ptr<std::list<sf::Sprite>> m_deathNumber; std::list<sf::Time> m_deathDurations; //Audio sf::Sound m_deathSound; }; #endif // INVADERS_H_INCLUDED
true
7d8f6919a1954890fc48985ec19441754db210ab
C++
Mvalverde00/Graphing-Calculator-3D
/src/chunk.cpp
UTF-8
4,022
3.09375
3
[]
no_license
#include "chunk.h" #include <iostream> #include <vector> #include <Engine/src/math/vectors.h> float graphing_func(float x, float y) { //return 5*sin(x/2.0 + y/2.0); //return -1.0; return sin(x * 3.1415926) + sin(y * 3.1415926); //return x * x + y * y; } Chunk::Chunk(float startX, float startY, float endX, float endY) { if (startX > endX) { this->startX = endX; this->endX = startX; } else { this->startX = startX; this->endX = endX; } if (startY > endY) { this->startY = endY; this->endY = startY; } else { this->startY = startY; this->endY = endY; } rebuildMesh(); } Chunk::Chunk(Vector3i chunkPos) : Chunk(chunkPos.x * CHUNK_SIZE, chunkPos.z * CHUNK_SIZE, chunkPos.x * CHUNK_SIZE + CHUNK_SIZE, chunkPos.z * CHUNK_SIZE + CHUNK_SIZE) {}; Chunk::Chunk(ChunkData* data) { mesh = Engine::Mesh(data->vertices, data->indices); } Chunk::Chunk() { startX = endX = startY = endY = 0; }; void Chunk::render() {} void Chunk::reset() { mesh = Engine::Mesh({}, {}); } void Chunk::rebuildMesh() { std::vector<Vector3f> vertices; std::vector<int> indices; float xStep = (endX - startX + 1)/SAMPLES; float yStep = (endY - startY + 1)/SAMPLES; // Create pool of vertices to draw from for (float xCount = 0; xCount < SAMPLES; xCount++) { for (float yCount = 0; yCount < SAMPLES; yCount++) { float x = startX + xCount*xStep; float y = startY + yCount*yStep; float z = graphing_func(x, y); Vector3f point = Vector3f(x, z, y); vertices.push_back(point); } } // Create indices for triangles using vertices for (int i = 0; i < SAMPLES - 1; i++) { for (int j = 0; j < SAMPLES - 1; j++) { int base = i + j*SAMPLES; // The top triangle indices.push_back(base); indices.push_back(base + 1); indices.push_back(base + 1 + SAMPLES); // The bottom triangle indices.push_back(base); indices.push_back(base + 1 + SAMPLES); indices.push_back(base + SAMPLES); } } mesh = Engine::Mesh(vertices, indices); } Engine::Mesh& Chunk::getMesh() { return mesh; } Vector3i Chunk::getChunkPos(Vector3f pos) { // For now, the height component does not matter. If I switch to marching cubes it will become // necessary as there will be vertical chunks. return Vector3i(floor(pos.x / CHUNK_SIZE), 0, floor(pos.z / CHUNK_SIZE)); } ChunkData* Chunk::buildChunkData(Vector3i chunkPos) { ChunkData* data = new ChunkData(); data->chunkPos = chunkPos; data->vertices = std::vector<Vector3f>(); data->indices = std::vector<int>(); float startX = chunkPos.x * CHUNK_SIZE; float endX = chunkPos.x * CHUNK_SIZE + CHUNK_SIZE; if (startX > endX) { float temp = startX; startX = endX; endX = temp; } float startY = chunkPos.z * CHUNK_SIZE; float endY = chunkPos.z * CHUNK_SIZE + CHUNK_SIZE; if (startY > endY) { float temp = startY; startY = endY; endY = temp; } float xStep = (endX - startX + 1) / SAMPLES; float yStep = (endY - startY + 1) / SAMPLES; std::cout << "xStep of " << xStep << " and yStep of " << yStep << "\n"; // Create pool of vertices to draw from for (float xCount = 0; xCount < SAMPLES; xCount++) { for (float yCount = 0; yCount < SAMPLES; yCount++) { float x = startX + xCount * xStep; float y = startY + yCount * yStep; float z = graphing_func(x, y); Vector3f point = Vector3f(x, z, y); data->vertices.push_back(point); } } // Create indices for triangles using vertices for (int i = 0; i < SAMPLES - 1; i++) { for (int j = 0; j < SAMPLES - 1; j++) { int base = i + j * SAMPLES; // The top triangle data->indices.push_back(base); data->indices.push_back(base + 1); data->indices.push_back(base + 1 + SAMPLES); // The bottom triangle data->indices.push_back(base); data->indices.push_back(base + 1 + SAMPLES); data->indices.push_back(base + SAMPLES); } } return data; }
true
0882c59943c353d69802c655db15747df57dcb59
C++
Vlad-Stelea/RBE2002FinalProject
/src/SubSystems/DriveTrain.h
UTF-8
3,699
2.71875
3
[]
no_license
/* * DriveTrain.h * * Created on: Dec 8, 2018 * Author: vlads */ #ifndef SRC_SUBSYSTEMS_DRIVETRAIN_H_ #define SRC_SUBSYSTEMS_DRIVETRAIN_H_ #include "../Components/HBridgeEncoderPIDMotor.h" #include "../Components/FireTracker.h" #include "../Components/Gyro.h" #include <list> class DriveTrain { public: struct currentLoc{ int x, y; }; struct encoderHolder{ long long left, right; }; DriveTrain(); void setup(Gyro *g); /** * Rotate the robot to a specified angle * @param degrees the number of degrees to rotate the robot * negative parameter means */ void rotateAngle(double degrees); /** * Sets a goal to drive a specified distance * Keep calling loop to run it farther * @param inches the number of inches to drive */ void driveDistance(double inches); /** * Drive both drivetrain motors at the given speeds * @param leftSpeed the speed to drive the left motor * @param rightSpeed the speed to drive the right motor */ void drive(int leftSpeed, int rightSpeed); /** * rotates our drivetrain * @param speed the speed to turn the robot */ void rotateRobot(int speed); /** * Called to run the drive train at the current setPoints */ void loop(); /** * Line up to the fire after already being found */ void lineUpFire(); /** * Sends the robot back to home base */ void ETGoHome(); void setOutputs(int right, int left); //Returns whether the robot is ready for another command to be passed in bool readyForCommand(); virtual ~DriveTrain(); private: void resetEncs(); static void rotationCallback(DriveTrain *d); HBridgeEncoderPIDMotor leftMotor; HBridgeEncoderPIDMotor rightMotor; Gyro gyro; FireTracker tracker; //TODO make sure they work const int leftServPin = 19; const int leftEncPinA = 17; const int leftEncPinB = 16; const int leftDirPin = 5; const int rightServPin = 33; const int rightEncPinA = 26; const int rightEncPinB = 27; const int rightDirPin = 25; const int turningLeeway = 2; /** * PID CONSTANTS */ //Left drive motor constants const double leftKP = .48; const double leftKI = 0; const double leftKD = 0; //Right drive motor constants const double rightKP = .45; const double rightKI = 0; const double rightKD = 0; const double turningKP = 100; const double turningKI = 0; const double turningKD = 0; const int minValue = 500; /*const double turningKI = .01; const double turningKD = .01;*/ //keeps track of whether a command is still executing bool driving = false; //Keep track if the robot is performing a turn bool turning = false; //Keeps track of whether the robot is ready for another command to be passed in bool ready; double turningGoal; double turningThreshold = 3; long long drivingThreshold = 1000; const int circumference = PI*3; const double WHEEL_BASE_CIRCUMFERENCE = 9.5*PI; long long convertInchesToTicks(double inches); /** * Converts a degree value for the robot to turn to how many ticks the wheels need to turn * @param degrees the number of degrees that the robot should turn relative to where it is now */ long long convertTurnAngleToTicks(double degrees); /** * Passed in to gyro to do after the robot stops turning * Compensates if the error is not withing a reasonable threshold * @param currentAngle the angle that the gyro has currently turned */ static void correctAngle(double currentAngle); const static int numEncVals = 100; struct encoderHolder prevEncVals[numEncVals]; bool allItemsSame(struct encoderHolder* encoderVals); void addEncHolder(struct encoderHolder *prevVals, struct encoderHolder newValue); int currentIdx = 0; }; #endif /* SRC_SUBSYSTEMS_DRIVETRAIN_H_ */
true
795ceb558fd3ecc1ece43f7412ad19c43acac101
C++
JoaoPedro1221/JogoVelha_CPP
/JogoVelha.cpp
UTF-8
4,709
3.171875
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; char Tabuleiro[3][3]; int xpts=0, opts=0; bool Marcar ( char Simbolo, int linha, int coluna) { if (Tabuleiro[linha][coluna] == ' ') { Tabuleiro[linha][coluna] = Simbolo; return true; } return false; } void Mostra () { cout <<" " << Tabuleiro[0][0] << " | " << Tabuleiro[0][1] << " | " << Tabuleiro[0][2] << endl << "---|---|---" << endl <<" " << Tabuleiro[1][0] << " | " << Tabuleiro[1][1] << " | " << Tabuleiro[1][2] << endl << "---|---|---" << endl <<" " << Tabuleiro[2][0] << " | " << Tabuleiro[2][1] << " | " << Tabuleiro[2][2] << endl; } bool VerificaVitoria() { // VERIFICA SE O JOGADOR GANHOU if ( (Tabuleiro[0][0] == Tabuleiro [0][1] && Tabuleiro[0][1] == Tabuleiro[0][2]&& Tabuleiro[0][0] == 'x') || (Tabuleiro[1][0] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[1][2]&& Tabuleiro[1][0] == 'x') || (Tabuleiro[2][0] == Tabuleiro [2][1] && Tabuleiro[2][1] == Tabuleiro[2][2]&& Tabuleiro[2][0] == 'x') ) { cout << "\nJogador X ganhou\n"; xpts=xpts+1; return true; } else if((Tabuleiro[0][0] == Tabuleiro [0][1] && Tabuleiro[0][1] == Tabuleiro[0][2]&& Tabuleiro[0][0] == 'o') || (Tabuleiro[1][0] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[1][2]&& Tabuleiro[1][0] == 'o') || (Tabuleiro[2][0] == Tabuleiro [2][1] && Tabuleiro[2][1] == Tabuleiro[2][2]&& Tabuleiro[2][0] == 'o') ) { cout << "\nJogador O ganhou\n"; opts=opts+1; return true; } //VERIFICA COLUNAS else if ((Tabuleiro[0][0] == Tabuleiro [1][0] && Tabuleiro[1][0] == Tabuleiro[2][0] && Tabuleiro[0][0] == 'x')|| (Tabuleiro[0][1] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[2][1] && Tabuleiro[0][1] == 'x')|| (Tabuleiro[0][2] == Tabuleiro [1][2] && Tabuleiro[1][2] == Tabuleiro[2][2] && Tabuleiro[0][2] == 'x')) { cout << "\nJogador X ganhou\n"; xpts=xpts+1; return true; } else if ((Tabuleiro[0][0] == Tabuleiro [1][0] && Tabuleiro[1][0] == Tabuleiro[2][0] && Tabuleiro[0][0] == 'o')|| (Tabuleiro[0][1] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[2][1] && Tabuleiro[0][1] == 'o')|| (Tabuleiro[0][2] == Tabuleiro [1][2] && Tabuleiro[1][2] == Tabuleiro[2][2] && Tabuleiro[0][2] == 'o')) { cout << "\nJogador O ganhou\n"; opts=opts+1; return true; } //VERIFICA DIAGONAL VENCEDORA else if ((Tabuleiro[0][0] == Tabuleiro[1][1] && Tabuleiro[1][1] == Tabuleiro[2][2]&& Tabuleiro[0][0] == 'x') || (Tabuleiro[2][0] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[0][2]&& Tabuleiro[2][0] == 'x') ) { cout << "\nJogador X ganhou\n"; xpts=xpts+1; return true; } else if ((Tabuleiro[0][0] == Tabuleiro[1][1] && Tabuleiro[1][1] == Tabuleiro[2][2]&& Tabuleiro[0][0] == 'o') || (Tabuleiro[2][0] == Tabuleiro [1][1] && Tabuleiro[1][1] == Tabuleiro[0][2]&& Tabuleiro[2][0] == 'o') ) { cout << "\nJogador O ganhou\n"; opts=opts+1; return true; } return false; } void CriaTabuleiro() { for (int i=0; i<3; i++) for (int j=0; j<3; j++) Tabuleiro[i][j]= ' '; } int main () { char jogar; int linha,coluna; int jogada=0; while(jogar != 'N' || jogar != 'n') { system("cls"); CriaTabuleiro(); while (!VerificaVitoria()) { Mostra(); if (jogada%2 == 0) //VEZ DO PRIMEIRO JOGADOR { cout << endl << "Jogador X, entre com a linha (0 a 2) e coluna (0 a 2): "; cin >> linha >> coluna; if (Marcar('x',linha,coluna)) //CONDICAOO PARA NAO COLOCAR DOIS SIMBOLOS NA MESMA CASA jogada++; } else // VEZ DO SEGUNDO JOGADOR { cout << endl << "Jogador O, entre com a linha(0 a 2) e coluna(0 a 2): "; cin >> linha >> coluna; if( Marcar('o',linha,coluna)) //CONDICAOO PARA NAO COLOCAR DOIS SIMBOLOS NA MESMA CASA jogada++; } system("cls"); } Mostra(); cout<<"Jogador 'X' tem "<<xpts<<"pts"<<endl; cout<<"Jogardor 'O' tem "<<opts<<"pts"<<endl; cout<<"Voce quer jogar o jogo da velha novamente? S/N?"<<endl; cin>>jogar; if (jogar=='N'|| jogar =='n') { return 0; } } }
true
dfacddc6b6d5c2e5654fc8fe6c538255a5cc61b3
C++
EricVaughanOVR/SparseStereo
/demo/main.cpp
UTF-8
2,112
2.625
3
[]
no_license
#include <iostream> #include <vector> #include "SparseStereo.hpp" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/features2d/features2d.hpp> using namespace cv; static void help( char** argv ) { std::cout<<"\nUsage: "<<argv[0]<<"[path/to/image1] [path/to/image2] [Max Hamming Dist] [Max Disparity] [Epipolar Range]\n"<< std::endl; } int main( int argc, char** argv ) { if( argc != 6 ) { help(argv); return -1; } // Load images Mat imgL = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE ); if( !imgL.data ) { std::cout<< " --(!) Error reading image " << argv[1] << std::endl; return -1; } Mat imgR = imread(argv[2], CV_LOAD_IMAGE_GRAYSCALE ); if( !imgR.data ) { std::cout << " --(!) Error reading image " << argv[2] << std::endl; return -1; } int maxDist = atoi(argv[3]); int maxDisparity = atoi(argv[4]); int epiRange = atoi(argv[5]); std::vector<cv::KeyPoint> keypointsL, keypointsR; std::vector<cv::DMatch> matches; SparseStereo census(imgL.step, maxDist, maxDisparity, epiRange); double t = (double)getTickCount(); cv::FAST(imgL, keypointsL, 15, true); cv::FAST( imgR, keypointsR, 15, false); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "detection time [s]: " << t/1.0 << std::endl; // match t = (double)getTickCount(); SparseStereo::TransformData transfmData1(imgL.rows, imgL.cols); SparseStereo::TransformData transfmData2(imgL.rows, imgL.cols); census.extractSparse(imgL, keypointsL, transfmData1); census.extractSparse(imgR, keypointsR, transfmData2); census.match(transfmData1, transfmData2, matches); t = ((double)getTickCount() - t)/getTickFrequency(); std::cout << "matching time [s]: " << t << std::endl; std::cout << "Number of matches: "<<matches.size()<<std::endl; // Draw matches Mat imgMatch; std::vector<char> mask; drawMatches(imgL, keypointsL, imgR, keypointsR, matches, imgMatch, cv::Scalar::all(-1), cv::Scalar::all(-1), mask, 2); namedWindow("matches", CV_WINDOW_KEEPRATIO); imshow("matches", imgMatch); waitKey(0); }
true
ab441303e6b576107f7b34c33846e2bace8e87af
C++
wzor/GrinPlusPlus
/src/Core/Models/FullBlock.cpp
UTF-8
648
2.671875
3
[ "MIT" ]
permissive
#include <Core/Models/FullBlock.h> FullBlock::FullBlock(BlockHeader&& blockHeader, TransactionBody&& transactionBody) : m_blockHeader(std::move(blockHeader)), m_transactionBody(std::move(transactionBody)), m_validated(false) { } void FullBlock::Serialize(Serializer& serializer) const { m_blockHeader.Serialize(serializer); m_transactionBody.Serialize(serializer); } FullBlock FullBlock::Deserialize(ByteBuffer& byteBuffer) { BlockHeader blockHeader = BlockHeader::Deserialize(byteBuffer); TransactionBody transactionBody = TransactionBody::Deserialize(byteBuffer); return FullBlock(std::move(blockHeader), std::move(transactionBody)); }
true
bd0126f155bd3baf056b730d152f62b3c8caf3ec
C++
TerensTare/tnt
/include/utils/BitFlags.hpp
UTF-8
2,739
3.234375
3
[ "MIT" ]
permissive
#ifndef TNT_UTILS_ENUM_CLASS_BIT_FLAGS_HPP #define TNT_UTILS_ENUM_CLASS_BIT_FLAGS_HPP #include <type_traits> namespace tnt { // thx Anthony Williams for all of the content of this header. // https://blog.bitwigglers.org/using-enum-classes-as-type-safe-bitmasks/ template <typename T> concept enum_type = std::is_enum_v<T>; template <enum_type E> struct enable_bit_mask : std::false_type { }; template <typename T> concept bit_mask = enum_type<T> and (enable_bit_mask<T>::value == true); template <bit_mask E> constexpr bool has_flag(E const &bit, E const &flag) noexcept { return ((bit & flag) == flag); } template <bit_mask E> constexpr void set_flag(E &bit, E const &flag) noexcept { bit |= flag; } template <bit_mask E> constexpr void unset_flag(E &bit, E const &flag) noexcept { bit &= ~flag; } template <bit_mask E> constexpr void flip_flag(E &bit, E const &flag) noexcept { bit ^= flag; } } // namespace tnt template <tnt::bit_mask E> constexpr E operator|(E const &a, E const &b) noexcept { using type = std::underlying_type_t<E>; return static_cast<E>( static_cast<type>(a) | static_cast<type>(b)); } template <tnt::bit_mask E> constexpr E operator&(E const &a, E const &b) noexcept { using type = std::underlying_type_t<E>; return static_cast<E>( static_cast<type>(a) & static_cast<type>(b)); } template <tnt::bit_mask E> constexpr E operator^(E const &a, E const &b) noexcept { using type = std::underlying_type_t<E>; return static_cast<E>( static_cast<type>(a) ^ static_cast<type>(b)); } template <tnt::bit_mask E> constexpr E operator~(E const &a) { using type = std::underlying_type_t<E>; return static_cast<E>(~static_cast<type>(a)); } template <tnt::bit_mask E> constexpr E &operator|=(E &a, E const &b) noexcept { using type = std::underlying_type_t<E>; a = static_cast<E>( static_cast<type>(a) | static_cast<type>(b)); return a; } template <tnt::bit_mask E> constexpr E &operator&=(E &a, E const &b) noexcept { using type = std::underlying_type_t<E>; a = static_cast<E>( static_cast<type>(a) & static_cast<type>(b)); return a; } template <tnt::bit_mask E> constexpr E &operator^=(E &a, E const &b) noexcept { using type = std::underlying_type_t<E>; a = static_cast<E>( static_cast<type>(a) ^ static_cast<type>(b)); return a; } template <tnt::bit_mask E> constexpr bool operator==(E const &a, E const &b) noexcept { using type = std::underlying_type_t<E>; return static_cast<type>(a) == static_cast<type>(b); } #endif //!TNT_UTILS_ENUM_CLASS_BIT_FLAGS_HPP
true
e15595d8de10990b0b78773cf29c1e6f3f18afd6
C++
PuppyQ08/data_structure
/potd-q27/TreeNode.cpp
UTF-8
569
3.0625
3
[]
no_license
#include "TreeNode.h" #include <cstddef> #include <iostream> using namespace std; TreeNode::TreeNode() : left_(NULL), right_(NULL) { } int TreeNode::getHeight() { int leftHeight = -1, rightHeight = -1; if(this->left_ != NULL) leftHeight = this->left_->getHeight(); if(this->right_ != NULL) rightHeight = this->right_->getHeight(); int height =1 + max(leftHeight, rightHeight); return height; } /*int TreeNode::_getHeight(TreeNode *root){ if(root == NULL) return 0; return 1 + max(getHeight(root->left_), getHeight(root->right_)); } */
true
4e4d15897a01feb3da901fb63193c34fb4cddb3e
C++
AKL-FIRE/Algorithm
/Chapter6 Divide and Conquer/main.cpp
UTF-8
213
2.578125
3
[]
no_license
/* * main.cpp * * Created on: Oct 3, 2017 * Author: apple */ #include "Algorithm.hpp" int main() { int a[5] = {3,5,2,1,6}; int min,max; minmax(0,4,a,min,max); std::cout << min << " " << max; }
true
5efdaef7de5faa752fa3784d41b9757d124324e3
C++
johannesugb/origin_of_cg_base
/framework/include_stst/vulkan_attribute_description_binding.h
UTF-8
720
2.609375
3
[ "MIT" ]
permissive
#pragma once #include "vulkan_context.h" class vulkan_attribute_description_binding { public: vulkan_attribute_description_binding(uint32_t binding, uint32_t stride, vk::VertexInputRate inputRate); ~vulkan_attribute_description_binding(); void add_attribute_description(uint32_t location = 0, vk::Format format = vk::Format::eUndefined, uint32_t offset = 0); vk::VertexInputBindingDescription get_binding_description() { return mBindingDescription; } std::vector<VkVertexInputAttributeDescription> get_attribute_descriptions() { return mAttributeDescriptions; } private: vk::VertexInputBindingDescription mBindingDescription; std::vector<VkVertexInputAttributeDescription> mAttributeDescriptions; };
true
e48a4b047b1069157d38189b5d83fa44cbb496ae
C++
lipskydan/Project_Qt_2019
/MusicQuiz/musicquiz.cpp
UTF-8
3,715
2.9375
3
[]
no_license
#include "musicquiz.h" MusicQuiz::MusicQuiz() { qsrand(time(NULL)); melody = nullptr; QuantityOFSongs = 5; CountLevel = 1; CountGood = 0; CountBad = 0; UsedNumber = false; FirstTime = true; NumberOfPossibleAnswer = "0"; NumberOfTrueAnswer = "0"; } void MusicQuiz::CleanInfo(){ CountLevel = 1; CountGood = 0; CountBad = 0; usedNumbers.clear(); //ui->lineTrueAnswer->clear(); } void MusicQuiz::Stop() { if (melody){ melody->stop(); } FirstTime = true; } bool MusicQuiz::isFirstTime() { return FirstTime; } void MusicQuiz::setFirstTime(bool firstTime) { FirstTime = firstTime; } void MusicQuiz::DeleteMelody() { if (melody != nullptr){ melody->stop(); delete melody; } } void MusicQuiz::PlayRandomSong() { QString sound_name = "/Users/danial/Documents/GitHub/Project_Qt_2019/MusicQuiz/"; //Users/danial/Documents/GitHub/Project_Qt_2019/MusicQuiz/musicquiz.cpp int RandomNumber = -1; do { RandomNumber = qrand() % QuantityOFSongs; } while(WasUsed(RandomNumber) == true); usedNumbers.push_back(RandomNumber); NumberOfTrueAnswer = QString::number(RandomNumber); if(RandomNumber == 0){ sound_name += "01 Any Kind of Guy.wav"; }else if(RandomNumber == 1){ sound_name += "16 I Know.wav"; }else if(RandomNumber == 2){ sound_name += "11 Bohemian Rhapsody.wav"; }else if(RandomNumber == 3){ sound_name += "Te Amo.wav"; }else { sound_name += "Diamonds.wav"; } melody = new QSound(sound_name); melody->play(); } QString MusicQuiz::getNumberOfPossibleAnswer() { return NumberOfPossibleAnswer; } void MusicQuiz::setNumberOfPossibleAnswer(const QString &&num) { NumberOfPossibleAnswer = num; } QString MusicQuiz::getNNumberOfTrueAnswer() { return NumberOfTrueAnswer; } void MusicQuiz::setNumberOfTrueAnswer(const QString &&num) { NumberOfTrueAnswer = num; } QString MusicQuiz::getResultMassage(){ return ResultMassage; } void MusicQuiz::setResultMassage(const QString &&text){ ResultMassage += text; } QString MusicQuiz::getTmpResultMassage(){ return TmpResultMassage; } void MusicQuiz::setTmpResultMassage(const QString &&text){ TmpResultMassage += text; } void MusicQuiz::cleanResultMassage(){ ResultMassage = " "; TmpResultMassage = " "; } void MusicQuiz::saveResult(){ QTime time = QTime::currentTime(); timeForNameOfFile = time.toString("hh:mm:ss"); QFile file("/Users/danial/Desktop/result_" + timeForNameOfFile + ".txt"); file.open(QIODevice::WriteOnly); QDataStream out(&file); out << ResultForSave; file.close(); qDebug() << "File created \n"; } void MusicQuiz::CheckAnswer() { TmpResultMassage += "Answer for question " + QString::number(CountLevel) + " was "; if (NumberOfPossibleAnswer == NumberOfTrueAnswer){ TmpResultMassage += "correct \n"; CountGood++; } else { TmpResultMassage += "wrong \n"; CountBad++; } melody->stop(); // qDebug() << "1"; } int MusicQuiz::getQuantityOFSongs() { return QuantityOFSongs; } int MusicQuiz::getCountLevel() { return CountLevel; } void MusicQuiz::setCountLevel(int countLevel) { CountLevel = countLevel; } int MusicQuiz::getCountGood(){ return CountGood; } void MusicQuiz::setCountGood(int count){ CountGood = count; } int MusicQuiz::getCountBad(){ return CountBad; } void MusicQuiz::setCountBad(int count){ CountBad = count; } bool MusicQuiz::WasUsed(int RandomNumber){ return std::find(usedNumbers.begin(), usedNumbers.end(), RandomNumber) != usedNumbers.end(); }
true
433c570885bae888cfb41605d20917456c53e621
C++
valikl/remote-translator
/Utils/BB_Window.h
UTF-8
514
2.5625
3
[]
no_license
#pragma once #include <windows.h> #include <string> #include "IRunnable.h" class BB_Window : public IRunnable { public: BB_Window(std::wstring windowClassName, std::wstring title, HWND hEffectiveWnd); ~BB_Window(void); // the thread procedure virtual void run(); HWND BBGetHandle() { return m_hWnd; } bool IsActive(); void BBDestroy(); private: void BBCreateWindow(); std::wstring m_windowClassName; std::wstring m_title; HWND m_hEffectiveWnd; HWND m_hWnd; };
true
74f644779755eb88be1b578c3daf404e8abe8b80
C++
rafalgrzeda/Multiliga
/src/administator.cpp
UTF-8
2,228
2.875
3
[]
no_license
#include "administator.h" #include "okno_paneladministratora.h" #include "listakontuzytkownikow.h" #include <QDebug> Permanentny *Administator::getPerm() { return perm; } void Administator::setPerm(Permanentny *value) { perm = value; } Administator::Administator(Uzytkownik *uzyt) :Uzytkownik (uzyt) { ID = uzyt->getID(); kod = uzyt->getKod(); typ = uzyt->getTyp(); imie = uzyt->getImie(); email = uzyt->getEmail(); haslo = uzyt->getHaslo(); login = uzyt->getLogin(); nazwisko = uzyt->getNazwisko(); Okno_panelAdministratora *admin_panel = new Okno_panelAdministratora(this); admin_panel->show(); } bool Administator::dodajUzytkownika(QString login, QString email, QString imie, QString nazwisko, QString haslo, QString typ) { //Sprawdzenie czy uzytkownik o podanym loginie istnieje - jestli nie -> dodanie do bazy ListaKontUzytkownikow *lista = ListaKontUzytkownikow::getListaKontUzytkownikow(); if(lista->znajdz(login) == nullptr){ perm = new Uzytkownik(NULL,login,email,imie,nazwisko,haslo,typ,"0"); perm->zapisz(NULL); lista->update(); delete perm; return true; } else{ return false; } } Permanentny* Administator::getUzytkownik(QString login) { //Pobranie uzytkownika z listy uzytkownikow ListaKontUzytkownikow *lista = ListaKontUzytkownikow::getListaKontUzytkownikow(); Uzytkownik* uzyt= lista->znajdz(login); perm = new Uzytkownik(uzyt); qDebug() << "Admin - getUzytkownik()"; qDebug() << perm; qDebug() << getPerm(); return perm; } void Administator::edytuj(QString login, QString email, QString imie, QString nazwisko, QString haslo, QString typ) { //Ogolnie caly czas perm zmienia swój adres w pamięci więc nic nie działa qDebug() << "Admnistrator - edytuj"; qDebug() << perm; //Pobranie ID starego Uzytkownika //Uzytkownik *u = dynamic_cast<Uzytkownik*>(perm); //int ID = u->getID(); /* delete perm; // Stowrzenie nowego uzytkownika; perm = new Uzytkownik(ID,login,email,imie,nazwisko,haslo,typ,kod); perm->zapisz(ID); */ }
true
11eab3525af9976b11f1fec5d44e949d58fa2391
C++
1292765944/ACM
/表达式求值.cpp
UTF-8
2,108
2.84375
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <stack> #include <vector> #define N 1000100 typedef long long ll; using namespace std; char s[N]; int len; vector<char>out; stack<char>sta; const int mod=1000000007; void gotOper(char opThis,int prec1){ while(!sta.empty()){ char opTop=sta.top(); sta.pop(); if(opTop=='('){ sta.push(opTop); break; } else{ int prec2; if(opTop=='|') prec2=1; if(opTop=='&') prec2=2; if(opTop=='~') prec2=3; if(prec2<prec1){ sta.push(opTop); break; } else out.push_back(opTop); } } sta.push(opThis); } void gotParen(char ch){ while(!sta.empty()){ char ch=sta.top(); sta.pop(); if(ch=='(') break; else out.push_back(ch); } } void cal(){ while(!sta.empty()) sta.pop(); out.clear(); for(int i=0;i<len;i++){ if(s[i]=='(') sta.push('('); else if(s[i]=='~') sta.push('~'); else if(s[i]=='|') gotOper('|',1); else if(s[i]=='&') gotOper('&',2); else if(s[i]==')') gotParen(')'); else if(s[i]=='x') out.push_back('1'); } while(!sta.empty()) out.push_back(sta.top()),sta.pop(); //for(int i=0;i<out.size();i++) printf("%c ",out[i]); //puts(""); } stack<pair<int,int> >st; void cal2(){ while(!st.empty()) st.pop(); for(int i=0;i<out.size();i++){ if(out[i]=='1') st.push(make_pair(1,1)); else if(out[i]=='~'){ pair<int,int>tmp; tmp=st.top(); st.pop(); st.push(make_pair(tmp.second,tmp.first)); } else if(out[i]=='|'){ pair<int,int>tmp1,tmp2; tmp1=st.top(); st.pop(); tmp2=st.top(); st.pop(); st.push(make_pair((((ll)tmp1.first+tmp1.second)%mod*((ll)tmp2.first+tmp2.second)%mod-(ll)tmp1.second*tmp2.second%mod+mod)%mod,(ll)tmp1.second*tmp2.second%mod)); } else if(out[i]=='&'){ pair<int,int>tmp1,tmp2; tmp1=st.top(); st.pop(); tmp2=st.top(); st.pop(); st.push(make_pair((ll)tmp1.first*tmp2.first%mod,(((ll)tmp1.first+tmp1.second)%mod*((ll)tmp2.first+tmp2.second)%mod-(ll)tmp1.first*tmp2.first%mod+mod)%mod)); } } printf("%d\n",st.top().first); } int main(){ scanf("%s",s); len=strlen(s); cal(); cal2(); return 0; }
true
b8ab26c5366020e10fb54b9efa8439819b365bf0
C++
foobarna/OOP
/lab6-8/src/domain/MovieRepository.h
UTF-8
800
2.796875
3
[]
no_license
/* * MovieRepository.h * * Created on: May 1, 2012 * Author: Aneta */ #ifndef MOVIEREPOSITORY_H_ #define MOVIEREPOSITORY_H_ #include "Movie.h" #include "Exceptions.h" #include <vector> namespace domain { class MovieRepository { public: virtual Movie* findByTitle(string title) = 0; virtual vector<Movie*> findAll() = 0; virtual void save(Movie) throw (RepositoryException) = 0; virtual void updateType(string, string) throw (RepositoryException) = 0; virtual void updateDesc(string, string) throw (RepositoryException) = 0; virtual void updateAvailable(string, bool) throw (RepositoryException) = 0; virtual void removeByTitle(string name) throw (RepositoryException) = 0; virtual ~MovieRepository(){} }; } #endif /* MOVIEREPOSITORY_H_ */
true
cb9915e623b3badd8240e19188d5544c34ca6957
C++
tuan2195/subset-sum
/tool.cpp
UTF-8
1,083
3.34375
3
[]
no_license
#include <iostream> #include <fstream> #include <random> int main(int argc, char** argv) { if (argc != 4) { std::cout << "Usage: ./tool <sampleSize> <limit> <outputFile>" << std::endl; exit(1); } auto sampleSize = std::stoi(argv[1]); auto limit = std::stoi(argv[2]); if (sampleSize == 0 || limit == 0) { std::cout << "Invalid arguments!" << std::endl; std::cout << "Usage: ./tool <sampleSize> <limit> <outputFile>" << std::endl; exit(1); } // Open file to write to std::ofstream output (argv[3], std::ios::out | std::ios::trunc); if (!output) { std::cout << "Unable to open file " << argv[3] << std::endl; exit(1); } // Random device std::random_device randDev; // Mersenne twister engine std::mt19937_64 generator(randDev()); // Uniform integer distribution std::uniform_int_distribution<long> dist(1, limit); for(auto i = 0; i < sampleSize; ++i) { output << dist(generator) << ' '; } output.close(); return 0; }
true
c6566bf62b8e3d46ceb144f5f2e37dfd938df2b3
C++
sanjeev1102/cpp_program
/c++Training_harman/Day1/009Location.cpp
UTF-8
1,294
3.265625
3
[]
no_license
#include<iostream> using std::cout; using std::endl; namespace nm9 { class CA { bool IsOnHeap; static int count; public: CA() :IsOnHeap(true) { count--; if (count < 0) IsOnHeap = false; } static void* operator new(std::size_t size) { CA* temp = (CA*)malloc(size); count = 1; return temp; } static void* operator new[](std::size_t size) { CA* temp = (CA*)malloc(size); count = size / sizeof(CA); return temp; } void Location() { if (IsOnHeap == true) { cout << "Object on heap" << endl; } else //if (IsOnHeap == false) { cout << "Object (NOT) on heap" << endl; } } }; int CA::count = 0; void main() { CA obj1; CA *obj3 = new CA(); /* obj3=operator new(); obj3->CA::CA(); */ CA *obj4 = new CA(); CA obj2; CA *obj5 = new CA[5]; /* obj5=operator new[](5); (obj5+0)->CA::CA(); (obj5+1)->CA::CA(); (obj5+2)->CA::CA(); (obj5+3)->CA::CA(); (obj5+4)->CA::CA(); */ obj1.Location(); obj2.Location(); cout << "______________________" << endl; obj3->Location(); obj4->Location(); cout << "______________________" << endl; for (int i = 0; i < 5; i++) { (obj5 + i)->Location(); } } }
true
3b8d7c2ed9d6cf0e27652f9f5559191f2f0fe69a
C++
wwqqqqq/LeetCode-Solution
/First Missing Positive.cpp
UTF-8
2,097
3.109375
3
[]
no_license
class Solution { public: void insert(vector<pair<int,int>>& intervals, int e) { // intervals is sorted in ascending order for(int i = 0; i < intervals.size(); i++) { if(intervals[i].second >= e && intervals[i].first <= e) { return; // e has already appeared in nums } if(intervals[i].first > e) { if(intervals[i].first == e + 1) { if(i > 0 && intervals[i-1].second + 1 == e) { intervals[i-1].second = intervals[i].second; intervals.erase(intervals.begin()+i); } else { intervals[i].first = e; } } else if(i > 0 && intervals[i-1].second + 1 == e) { intervals[i-1].second = e; } else { intervals.insert(intervals.begin()+i, pair<int,int>(e,e)); } return; } } if(intervals.size() != 0 && e == intervals[intervals.size()-1].second + 1) { intervals[intervals.size()-1].second = e; } else intervals.push_back(pair<int,int>(e,e)); } int firstMissingPositive(vector<int>& nums) { // Q1: Does the vector contain duplicate numbers // Q2: Does the vector contain zero or negative numbers? // Q3: Is there any range of the numbers or are they just 32-bit signed integer? // can transform it into a interval overlap problem? // [1,2,6] // [[1,2],[6,6]] vector<pair<int,int>> intervals; for(int i = 0; i < nums.size(); i++) { if(nums[i] <= 0) continue; insert(intervals, nums[i]); // we should always make sure that all intervals in the vector do not overlap w/ each other // and they are sorted in ascending order } if(intervals.size() == 0 || intervals[0].first > 1) return 1; return intervals[0].second + 1; } };
true
a15cb910d0c0ed01383bbd6ee73cc3137f07a154
C++
mchalupa/dg
/include/dg/ADT/SetQueue.h
UTF-8
844
3.0625
3
[ "MIT" ]
permissive
#ifndef DG_ADT_SET_QUEUE_H_ #define DG_ADT_SET_QUEUE_H_ #include "Queue.h" #include <set> namespace dg { namespace ADT { // A queue where each element can be queued only once template <typename QueueT> class SetQueue { std::set<typename QueueT::ValueType> _queued; QueueT _queue; public: using ValueType = typename QueueT::ValueType; ValueType pop() { return _queue.pop(); } ValueType &top() { return _queue.top(); } bool empty() const { return _queue.empty(); } size_t size() const { return _queue.size(); } void push(const ValueType &what) { if (_queued.insert(what).second) _queue.push(what); } void swap(SetQueue<QueueT> &oth) { _queue.swap(oth._queue); _queued.swap(oth._queued); } }; } // namespace ADT } // namespace dg #endif // DG_ADT_QUEUE_H_
true
42c8ff18f4cbb751555243ae2559ce4dcebcd077
C++
ArSoto/guia9
/main.cpp
UTF-8
2,366
3.453125
3
[]
no_license
#include <iostream> #include <time.h> #include "Busqueda.h" using namespace std; int main(int argc , char *argv[]) { /** * validacion de parametros de entrada * */ char eleccion; if(argc == 1){ //Valida la cantidad de parametros de entrada eleccion = *argv[1]; }else{ //Si la cantidad parametros no es la adecuada el programa debe reiniciarse cout << "\n cantidad de datos ingresados es erroneo , reinicie el programa" << endl; return 1; } if(eleccion != 'E' && eleccion != 'C' && eleccion != 'D' && eleccion != 'L'){ //verifica que el caracter ingresado sea valido cout << " El caracter ingresado no es valido, reinicie el programa " << endl; return 1; } /** * inicializacion de objetos y variables * */ Busqueda busqueda(eleccion); int opcion = 0; int numero; /** * Indicar al usuario cual fue el metodo elegido * * */ switch (eleccion){ case 'L': cout << "Ha elegido el metodo de reoganizacion prueba Lineal " << endl; break; case 'D': cout << "Ha elegido el metodo de reoganizacion de Doble direccion hash" << endl; break; case 'C': cout << "Ha eligido el metodo de reorganizacion prueba cuadratica " <<endl; break; case 'E': cout << "Ha elegido el metodo de reorganizacion de Encadenamiento" << endl; } /** * Menu de opciones del usuario * */ while (opcion != 9){ cout << " MENU " << endl; cout << endl; cout << "[1] Agregar Numero" << endl; cout << "[2] Buscar Numero" << endl; cout << "[9] Salir" << endl; cin >> opcion; switch (opcion){ case 1: cout << "Indique el numero que desea agregar "<< endl; cin >> numero; busqueda.setLista(numero); break; case 2 : cout << "Indique el numero que desea buscar " << endl; cin >> numero; busqueda.getBuscar(numero); break; case 9: continue; default: cout <<"La opcion ingresada no es valida " << endl; } } return 0; }
true
f4fbcaa4c0d64325283c843c154fdf6374b9cc1c
C++
mcerv/tbConverter
/src/converters/waveform.h
UTF-8
753
2.515625
3
[]
no_license
#ifndef __WAVEFORM_H_DEFINED__ #define __WAVEFORM_H_DEFINED__ #include <iostream> #include <iomanip> #include <stdint.h> #include <string> #include <vector> #include "TGraph.h" using namespace std; class Waveform { public: Waveform( vector<float>, //time vector vector<float> //amplitude vector ); ~Waveform(); //copy constructor Waveform( Waveform& ); int32_t getSize () {return (int32_t)_time.size();}; float* getTime() {return &_time[0];}; float* getAmpl() {return &_ampl[0];}; int getEntry(); void applyLowPassFilter(int32_t); //averaging buffer length void applyDerivative(); bool isFiltered() {return _filtered;}; private: vector<float> _time; vector<float> _ampl; bool _filtered; }; #endif
true
f0f1250bfc32209994e4b5a719a096f326057518
C++
inbarizrael/Assignment1Project
/include/Customer.h
UTF-8
1,621
3.21875
3
[]
no_license
#ifndef CUSTOMER_H_ #define CUSTOMER_H_ #include <vector> #include <string> #include "Dish.h" class Customer{ public: Customer(std::string c_name, int c_id); virtual std::vector<int> order(const std::vector<Dish> &menu)=0; virtual std::string toString() const = 0; std::string getName() const; int getId() const; private: const std::string name; const int id; }; class VegetarianCustomer : public Customer { //מנה צמחונית עם תז נמוך ביותר ומשקה לא אלכהולי הכי יקר public: VegetarianCustomer(std::string name, int id); std::vector<int> order(const std::vector<Dish> &menu); std::string toString() const; private: }; class CheapCustomer : public Customer {//מזמינים פעם אחת ומנה זולה ביותר public: CheapCustomer(std::string name, int id); std::vector<int> order(const std::vector<Dish> &menu); std::string toString() const; private: }; class SpicyCustomer : public Customer {// המנה החריפה היקרה ביותר , עבור הזמנה נוספת - משקה לא אלכוהולי הכי זול public: SpicyCustomer(std::string name, int id); std::vector<int> order(const std::vector<Dish> &menu); std::string toString() const; private: }; class AlchoholicCustomer : public Customer {//רק משקאות אלכהולים . מתחיל עם המשקה הכי זול וממשיך בסדרה עולה לפי מחיר public: AlchoholicCustomer(std::string name, int id); std::vector<int> order(const std::vector<Dish> &menu); std::string toString() const; private: }; #endif
true
0c9e3cb778349ed2483d5112e83d8cf80c62da9a
C++
Ciaran-byte/Cpp
/03 Cpp Primer/17 标准库特殊设施/17-9 随机数基本用法.cpp
UTF-8
323
2.734375
3
[]
no_license
#include<iostream> #include<random> using namespace std; int main() { default_random_engine e; for (size_t i = 0; i < 10; ++i) { cout << e() << endl; } uniform_int_distribution<unsigned> u(0, 9); cout << endl; for (size_t i = 0; i < 10; i++) { cout << u(e) << endl; } return 0; }
true
b4c9da17cc5eedf8b52926df16f1da87d677b6da
C++
naxo100/PExKa
/src/util/Exceptions.cpp
UTF-8
1,819
2.75
3
[]
no_license
/* * Exceptions.cpp * * Created on: Aug 16, 2016 * Author: naxo */ #include <sstream> #include <cstring> #include "Exceptions.h" using namespace std; SemanticError::SemanticError(const string &str,const yy::location &l) : msg(), loc(l) { strcpy(msg,str.c_str()); } const char* SemanticError::what() const _GLIBCXX_USE_NOEXCEPT { static char c[250] ;//TODO?? if(loc.begin.filename == nullptr) sprintf(c,"Semantic error in file (no-location):\n%s",msg); else sprintf(c,"Semantic error in file \"%s\", line %d, characters %d-%d:\n%s", loc.begin.filename->c_str(),loc.begin.line,loc.begin.column,loc.end.column,msg); return c; } void SemanticError::setLocation(const yy::location &l){ loc = l; //loc.begin.filename = new string(*l.begin.filename); //loc.end.filename = new string(*l.end.filename); } /** /brief Syntax error Exception * */ SyntaxError::SyntaxError(const string &str, const yy::location &l) : msg(), loc(l) { strcpy(msg,str.c_str()); } const char* SyntaxError::what() const _GLIBCXX_USE_NOEXCEPT { static char c[250] ;//TODO?? sprintf(c,"Syntax error in file \"%s\", line %d, characters %d-%d:\n%s", loc.begin.filename->c_str(),loc.begin.line,loc.begin.column,loc.end.column,msg); return c; } void SyntaxError::setLocation(const yy::location &l){ loc = l; } NullEvent::NullEvent(int e) : error(e) {} const char* NullEvent::what() const _GLIBCXX_USE_NOEXCEPT { switch(error){ case 0:return "Not a null event"; case 1:return "unary rule with binary instance"; case 2:return "binary rule with unary instance"; case 3:return "clashing instance"; case 4:return "overapproximation clash"; case 5:return "invalid injection clash"; case 6:return "perturbation interrupting time"; default:return "invalid arg"; } return "invalid!!!!"; }
true
d367657ad1a299350c8e2c3d0a60184064363a39
C++
zeroengineteam/ZeroCore
/ZeroLibraries/Platform/Windows/Process.cpp
UTF-8
11,571
2.71875
3
[ "MIT" ]
permissive
/////////////////////////////////////////////////////////////////////////////// /// /// \file Process.hpp /// Declaration of the Process class and support functions. /// /// Authors: Trevor Sundberg / Joshua T. Fisher / Chris Peters /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" #include "Platform/Process.hpp" #include "Platform/FilePath.hpp" // Bring in the Process Status API library for process information parsing #include <Psapi.h> #pragma comment(lib, "Psapi.lib") namespace Zero { struct ProcessPrivateData { StackHandle mStandardIn; StackHandle mStandardOut; StackHandle mStandardError; StackHandle mProcess; StackHandle mProcessThread; }; Process::Process() { ZeroConstructPrivateData(ProcessPrivateData); } Process::~Process() { Close(); ZeroDestructPrivateData(ProcessPrivateData); } inline void DuplicateAndClose(Status& status, HANDLE currentProcess, StackHandle& handle) { // This handle has not been redirected, just return if (handle.mHandle == cInvalidHandle) return; HANDLE noninheritingHandle; BOOL result = DuplicateHandle( currentProcess, handle, currentProcess, &noninheritingHandle, // Address of new handle. 0, FALSE, // Make it uninheritable. DUPLICATE_SAME_ACCESS); if (result == FALSE) WinReturnIfStatus(status); CloseHandle(handle); handle = noninheritingHandle; } inline void SetupStandardHandle(Status& status, StackHandle& writeHandle, StackHandle& readHandle, bool redirect) { // If we are redirecting create a new pipe. if (redirect) { SECURITY_ATTRIBUTES security; // Set up the security attributes struct. security.nLength = sizeof(SECURITY_ATTRIBUTES); security.lpSecurityDescriptor = NULL; security.bInheritHandle = TRUE; SetLastError(0); BOOL result = CreatePipe(&readHandle.mHandle, &writeHandle.mHandle, &security, 0); if (result == FALSE) WinReturnIfStatus(status); } } void Process::Start(Status& status, StringRange commandLine, bool redirectOut, bool redirectError, bool redirectIn, bool showWindow) { ProcessStartInfo info; info.mArguments = commandLine; info.mShowWindow = showWindow; info.mRedirectStandardOutput = redirectOut; info.mRedirectStandardError = redirectError; info.mRedirectStandardInput = redirectIn; info.mSearchPath = false; Start(status, info); } void SetUpStartInfo(ProcessStartInfo &info) { // The application name always has to be the first argument, even if it's passed // in as the application name. Because of this the application name (if it exists) // is always quoted as the first argument. if (info.mApplicationName.Empty() != true) info.mArguments = String::Format("\"%s\" %s", info.mApplicationName.c_str(), info.mArguments.c_str()); // In order for process to search for the application, the passed in application // name needs to be null. In this case we've already set the application as the // first argument so we can just clear out the application name. if (info.mSearchPath == true) info.mApplicationName.Clear(); } void Process::Start(Status &status, ProcessStartInfo &info) { ZeroGetPrivateData(ProcessPrivateData); SetUpStartInfo(info); HANDLE currentProcess = GetCurrentProcess(); // These are simply stack copies of what we'll keep around to monitor // if the pipe has been redirected (null otherwise) StackHandle standardOutRead; StackHandle standardErrorRead; StackHandle standardInWrite; // These are used to pass the opposite pipe to our created process. StackHandle standardOutWrite; StackHandle standardErrorWrite; StackHandle standardInRead; // Set up the handles for each standard stream. // Make sure to clean up the unneeded ones. SetupStandardHandle(status, standardOutWrite, standardOutRead, info.mRedirectStandardOutput); WinReturnIfStatus(status); DuplicateAndClose(status, currentProcess, standardOutRead); WinReturnIfStatus(status); SetupStandardHandle(status, standardErrorWrite, standardErrorRead, info.mRedirectStandardError); WinReturnIfStatus(status); DuplicateAndClose(status, currentProcess, standardErrorRead); WinReturnIfStatus(status); SetupStandardHandle(status, standardInWrite, standardInRead, info.mRedirectStandardInput); WinReturnIfStatus(status); DuplicateAndClose(status, currentProcess, standardInWrite); WinReturnIfStatus(status); // Set up the struct containing the possibly redirected IO for our child process. STARTUPINFO startUpInfo; ZeroMemory(&startUpInfo, sizeof(STARTUPINFO)); startUpInfo.cb = sizeof(STARTUPINFO); startUpInfo.hStdOutput = standardOutWrite; startUpInfo.hStdError = standardErrorWrite; startUpInfo.hStdInput = standardInRead; startUpInfo.wShowWindow = info.mShowWindow ? SW_SHOWDEFAULT : SW_HIDE; startUpInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; PROCESS_INFORMATION processInfo; ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION)); WString applicationName = Widen(info.mApplicationName); WString arguments = Widen(info.mArguments); WString workingDirectory = Widen(info.mWorkingDirectory); if (applicationName.c_str() == nullptr && arguments.c_str() == nullptr) { status.SetFailed("Neither application name or command line parameters were specified."); return; } // arguments MUST be a copy of the buffer, because CreateProcess will add null terminators to the string SetLastError(0); BOOL result = CreateProcess( (LPCWSTR)applicationName.Data(), (LPWSTR)arguments.Data(), NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, (LPCWSTR)workingDirectory.Data(), &startUpInfo, &processInfo); if (result == FALSE) { FillWindowsErrorStatus(status); if (status.Failed()) { status.Message = String::Format("Failed to create process %s. \nCommand line '%s'\n%s", info.mApplicationName.c_str(), info.mArguments.c_str(), status.Message.c_str()); return; } } // Store the process so we can query the return value later (and wait on it closing) self->mProcess = processInfo.hProcess; self->mProcessThread = processInfo.hThread; // Keep around the handles to our side of the pipe. self->mStandardOut = standardOutRead.Transfer(); self->mStandardError = standardErrorRead.Transfer(); self->mStandardIn = standardInWrite.Transfer(); } void Process::Close() { ZeroGetPrivateData(ProcessPrivateData); self->mProcess.Close(); self->mProcessThread.Close(); self->mStandardIn.Close(); self->mStandardOut.Close(); self->mStandardError.Close(); } void Process::Terminate() { ZeroGetPrivateData(ProcessPrivateData); TerminateProcess(self->mProcess, (UINT)-1); } bool Process::IsRunning() { ZeroGetPrivateData(ProcessPrivateData); if (self->mProcess == cInvalidHandle) return false; OsInt exitCode = 0; GetExitCodeProcess(self->mProcess, &exitCode); return (exitCode == STILL_ACTIVE); } int Process::WaitForClose() { return WaitForClose(INFINITE); } int Process::WaitForClose(unsigned long milliseconds) { ZeroGetPrivateData(ProcessPrivateData); if(self->mProcess == cInvalidHandle) return -1; // Wait for the process to close. WaitForSingleObject(self->mProcess, milliseconds); // Return the exit code. OsInt exitCode = 0; GetExitCodeProcess(self->mProcess, &exitCode); return exitCode; } void OpenStandardStream(StackHandle& handle, File& fileStream, FileMode::Enum mode) { fileStream.Open(handle, mode); handle = cInvalidHandle; } void Process::OpenStandardOut(File& fileStream) { ZeroGetPrivateData(ProcessPrivateData); OpenStandardStream(self->mStandardOut, fileStream, FileMode::Read); } void Process::OpenStandardError(File& fileStream) { ZeroGetPrivateData(ProcessPrivateData); OpenStandardStream(self->mStandardError, fileStream, FileMode::Read); } void Process::OpenStandardIn(File& fileStream) { ZeroGetPrivateData(ProcessPrivateData); OpenStandardStream(self->mStandardIn, fileStream, FileMode::Write); } bool Process::IsStandardOutRedirected() { ZeroGetPrivateData(ProcessPrivateData); return self->mStandardOut == cInvalidHandle; } bool Process::IsStandardErrorRedirected() { ZeroGetPrivateData(ProcessPrivateData); return self->mStandardError == cInvalidHandle; } bool Process::IsStandardInRedirected() { ZeroGetPrivateData(ProcessPrivateData); return self->mStandardIn == cInvalidHandle; } ///////////////////////////////////////////////////////////////////// // Global Functions/Helpers ///////////////////////////////////////////////////////////////////// inline void GetProcessNameAndId(DWORD processID, String& processName, String& processPath) { // We can't retrieve info about some processes so default those to some string static const String unknownStr = "<unknown>"; processName = processPath = unknownStr; TCHAR szProcessPath[MAX_PATH] = TEXT("<unknown>"); // Get a handle to the process. HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID); // Get the process name. if (NULL != hProcess) { HMODULE moduleHandle; DWORD resultsBytesNeeded; // Gets a handle for each module in the process if (EnumProcessModules(hProcess, &moduleHandle, sizeof(moduleHandle), &resultsBytesNeeded)) { // According to the exhumation's of GetModuleBaseName it is preferable (and faster) to use // GetModuleFileName (which gets the full path) and the parse the text to get the process name GetModuleFileNameEx(hProcess, moduleHandle, szProcessPath, sizeof(szProcessPath) / sizeof(TCHAR)); processPath = Narrow(szProcessPath); // Make sure to normalize the path just in-case processPath = FilePath::Normalize(processPath); // The just the process' name (e.g. ZeroEditor.exe) processName = FilePath::GetFileName(processPath); } } // Release the handle to the process. CloseHandle(hProcess); } void GetProcesses(Array<ProcessInfo>& results) { // EnumProcesses requires an array of data to be filled out, // currently assume there's not more than 1024 processes running const size_t maxProcesses = 1024; DWORD processIds[maxProcesses], resultSizeInBytes, numberOfProcesses; EnumProcesses(processIds, sizeof(processIds), &resultSizeInBytes); numberOfProcesses = resultSizeInBytes / sizeof(DWORD); // Fill out information for each process for (size_t i = 0; i < numberOfProcesses; ++i) { // Process id of 0 is invalid if (processIds[i] != 0) { ProcessInfo& info = results.PushBack(); info.mProcessId = processIds[i]; GetProcessNameAndId(processIds[i], info.mProcessName, info.mProcessPath); } } } void KillProcess(OsInt processId, int exitCode) { // Open the process for termination HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, processId); if (hProcess != NULL) TerminateProcess(hProcess, exitCode); CloseHandle(hProcess); } void RegisterApplicationRestartCommand(StringParam commandLineArgs, uint flags) { RegisterApplicationRestart(nullptr, 0); } }
true
aa13ab5862046dab816d2d70912ceb9c099beb4e
C++
mrbratchenko/CPP_bootcamp
/d04/ex00/Peon.cpp
UTF-8
1,417
2.65625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Peon.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbratche <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/21 19:06:11 by sbratche #+# #+# */ /* Updated: 2018/06/21 19:06:14 by sbratche ### ########.fr */ /* */ /* ************************************************************************** */ #include "Peon.hpp" Peon::Peon ( void ): Victim("peon") { return ; } Peon::Peon ( std::string name ): Victim(name) { std::cout << "Zog zog." << std::endl; return ; } Peon::Peon( Peon const &src ) { *this = src; return ; } Peon &Peon::operator=( Peon const &src ) { this->_name = src._name; return *this; } void Peon::getPolymorphed() const { std::cout << this->getName() << " has been turned into a pink pony !" << std::endl; return ; } Peon::~Peon ( void ) { std::cout << "Bleuark..." << std::endl; return ; }
true
8def17d25ce8460ed50d3c7ba26b6baf15ef5a3a
C++
dsbeach/GliderScoreRemote
/Source/Raspbian/udpTelemetrySender/UdpSender.cpp
UTF-8
2,378
2.84375
3
[ "MIT" ]
permissive
/* * UdpSender.cpp * * Created on: Jan 28, 2018 * Author: dbeach */ #include "UdpSender.h" UdpSender::UdpSender(int port) { // for testing at home I want to send the datagrams to all available interfaces! this->udpPort = port; udpHandle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); int enable=1; setsockopt(udpHandle, SOL_SOCKET, SO_BROADCAST, &enable, sizeof(enable)); //setsockopt(udpHandle, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); //setsockopt(udpHandle, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)); } UdpSender::~UdpSender() { close(udpHandle); } string UdpSender::getIPs() { string result = ""; ifaddrs *ifap; char sourceIP[INET_ADDRSTRLEN]; if (getifaddrs(&ifap) == 0) { ifaddrs *p = ifap; while (p) { if ((p->ifa_flags & IFF_BROADCAST) && (p->ifa_addr->sa_family == AF_INET)) { //cout << "Found address: " << inet_ntop(AF_INET, &((struct sockaddr_in *)p->ifa_addr)->sin_addr, sourceIP, INET_ADDRSTRLEN) << endl; if (result.length() > 0 ) { result += ", "; } inet_ntop(AF_INET, &((struct sockaddr_in *)p->ifa_addr)->sin_addr, sourceIP, INET_ADDRSTRLEN); result += sourceIP; } p = p->ifa_next; } freeifaddrs(ifap); } return result; } void UdpSender::send(string message, bool verbose) { vector<sockaddr> bcastAddresses; sockaddr_in si_other; ifaddrs *ifap; if (getifaddrs(&ifap) == 0) { ifaddrs *p = ifap; while (p) { if ((p->ifa_flags & IFF_BROADCAST) && (p->ifa_addr->sa_family == AF_INET)) { // cout << "Adding broadcast interface:" << p->ifa_name << endl; bcastAddresses.push_back(*(p->ifa_ifu.ifu_broadaddr)); // the broadcast address for this interface; } p = p->ifa_next; } freeifaddrs(ifap); } for (uint i = 0; i < bcastAddresses.size(); i++) { memset((void *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(udpPort); sockaddr_in *temp = (sockaddr_in*)&bcastAddresses[i]; si_other.sin_addr.s_addr = temp->sin_addr.s_addr; bind(udpHandle, (sockaddr*)&si_other, sizeof(si_other)); int result = sendto(udpHandle, message.c_str(), message.length(), 0, (struct sockaddr*)&si_other, message.length()); if (result < 0) { cout << "opps.. errno:" << errno << endl; } else { if (verbose) { cout << "address: " << inet_ntoa(temp->sin_addr) << " message: " << message << endl; } } } }
true
17518e8231839cdd3ac027d30e58a82b7dc0d7db
C++
abdulabbas/CSC-5
/Assignments/A6/Savitch_Chapter6/Savitch_Ch6_9thEd_Prac_Program2/main.cpp
UTF-8
980
3.203125
3
[]
no_license
/* * File: main.cpp * Author: Abdul-Hakim * Purpose: Assignment 6 * Created on July 24, 2015, 11:43 AM */ //System Libraries #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; //User Libraries //Global Constants //Function Prototypes void rmBlk(ifstream& , ofstream&); //Execution Starts Here! int main(int argc, char** argv) { //Declare Variables ifstream infile; ofstream outfile; infile.open("input.dat"); if(infile.fail()){ cout<<"Input file failed to open.\n"; exit(1); } outfile.open("output.dat"); if(outfile.fail()){ cout<<"Output file failed to open.\n"; exit(1); } rmBlk(infile, outfile); infile.close(); outfile.close(); //Exit Stage Right return 0; } //Execution of functions done here! void rmBlk(ifstream& infile, ofstream& outfile){ string next; while (infile>>next){ outfile<<next<<" "; } }
true
48022c18be10efca6679a0e96bd7d7e67d8bb823
C++
cyxsourcetree/chen-yixin
/第九周/7.16.cpp
UTF-8
394
2.765625
3
[]
no_license
#include "stdafx.h" #include <iostream> #include <cstdlib> using namespace std; int main() { int sum[36000] = {0}; int a, b; int count = 0; for (size_t i = 0; i < 36000; i++) { a = rand() % 6 + 1; b = rand() % 6 + 1; sum[i] = a+b; if (sum[i]==7) { count++; } printf("%d %d %d %d\n", i,a,b, sum[i]); } printf("%d/36000",count); system("PAUSE "); return 0; }
true
de4d7b543a7861540413ee3eaaa68d1634f3bb37
C++
dotnet/dotnet-api-docs
/snippets/cpp/VS_Snippets_CLR/cryptography.Xml.EncryptedData2/CPP/encrypteddata.cpp
UTF-8
1,768
3.03125
3
[ "MIT", "CC-BY-4.0" ]
permissive
//<SNIPPET4> #using <System.Xml.dll> #using <System.Security.dll> #using <System.dll> using namespace System; using namespace System::Security::Cryptography::Xml; using namespace System::Xml; using namespace System::IO; /// This sample used the EncryptedData class to create a EncryptedData element /// and write it to an XML file. [STAThread] int main() { //<SNIPPET3> //<SNIPPET1> // Create a new CipherData object using a byte array to represent encrypted data. array<Byte>^sampledata = gcnew array<Byte>(8); CipherData ^ cd = gcnew CipherData( sampledata ); //</SNIPPET1> // Create a new EncryptedData object. EncryptedData^ ed = gcnew EncryptedData; //Add an encryption method to the object. ed->Id = "ED"; ed->EncryptionMethod = gcnew EncryptionMethod( "http://www.w3.org/2001/04/xmlenc#aes128-cbc" ); ed->CipherData = cd; //</SNIPPET3> //<SNIPPET2> //Add key information to the object. KeyInfo^ ki = gcnew KeyInfo; ki->AddClause( gcnew KeyInfoRetrievalMethod( "#EK","http://www.w3.org/2001/04/xmlenc#EncryptedKey" ) ); ed->KeyInfo = ki; //</SNIPPET2> // Create new XML document and put encrypted data into it. XmlDocument^ doc = gcnew XmlDocument; XmlElement^ encryptionPropertyElement = dynamic_cast<XmlElement^>(doc->CreateElement( "EncryptionProperty", EncryptedXml::XmlEncNamespaceUrl )); EncryptionProperty ^ ep = gcnew EncryptionProperty( encryptionPropertyElement ); ed->AddProperty( ep ); // Output the resulting XML information into a file. Change the path variable to point to a directory where // the XML file should be written. String^ path = "c:\\test\\MyTest.xml"; File::WriteAllText( path, ed->GetXml()->OuterXml ); } //</SNIPPET4>
true
128f63183d7f26cd02e08540e9f408bc51ead3c0
C++
schuay/mcsp
/src/sequential/sequential.cpp
UTF-8
1,839
3
3
[]
no_license
#include "sequential.h" #include <memory> using namespace graph; using namespace sp; Sequential:: Sequential(const Graph *graph, const Node *start) : graph(graph), start(start) { } ShortestPaths * Sequential:: shortest_paths() { ShortestPaths *sp = new ShortestPaths(); PathPtr init(new Path(start)); m_queue.insert(init); while (!m_queue.empty()) { /* Retrieve our next optimal candidate path. */ PathPtr p = m_queue.first(); const Node *head = p->head(); /* We've expanded up to head. The path is therefore optimal and must * be added to our global shortest paths. */ sp->paths[head].push_back(p); /* For all outgoing edges <- head: */ for (auto & e : head->out_edges()) { /* The following steps are abstracted into queue.insert(): * * Follow the edge, resulting in path p and weight w. * Compare it to existing path weights for target node in set: * For all dominated paths p': * Remove p' from queue. * If p is not dominated by any existing path to head: * Add p to queue. */ std::shared_ptr<Path> q(p->step(e)); const Node *qhead = q->head(); /* A (somewhat ugly) special case for paths which are dominated by * already final paths stored in ShortestPaths. */ bool dominated = false; for (const auto & final_path : sp->paths[qhead]) { if (dominates(final_path.get(), q.get())) { dominated = true; break; } } if (dominated) { continue; } m_queue.insert(q); } } return sp; }
true
d5edc8f63c66a98309167523396457a1711397d3
C++
tienthanght96/Directx_Game_2016
/Castlevania_Game/m2dxanimatedsprite.cpp
UTF-8
2,584
2.71875
3
[]
no_license
#include "m2dxanimatedsprite.h" M2DXAnimatedSprite::M2DXAnimatedSprite() { } M2DXAnimatedSprite::~M2DXAnimatedSprite() { } bool M2DXAnimatedSprite::initWithTexture(LPCSTR textureName) { setTexture(M2DXResourceManager::getInstance()->getTextureByName(textureName)); if (!getTexture()) { return false; } auto informationFileName = (string)textureName + SPRITE_SHEET_INFORMATION_FILE_EXTENSION; ifstream informationFile(informationFileName); if (informationFile.is_open()) { string frameInformation; while (getline(informationFile, frameInformation)) { auto frameNameSize = frameInformation.find_last_of("=") - 1; // {Name} = {Rect}. Examples: SimonBelmont = 0 0 16 32 auto frameName = frameInformation.substr(0, frameNameSize); auto rectangleInformation = frameInformation.substr(frameNameSize + 3); stringstream stringStream(rectangleInformation); float x, y, width, height; stringStream >> x; stringStream >> y; stringStream >> width; stringStream >> height; M2DXRectangle frameRectangle(x, y, width, height); frameMap.insert(M2DXFramePair(frameName, frameRectangle)); } currentFrame = frameMap.begin()->first; frameTime = getAnimateRate(); } return false; } void M2DXAnimatedSprite::updateFrame(int deltaTime) { auto animateRate = getAnimateRate(); if (animateRate != 0) { if (getNextFrame() == "SimonBelmontKneeling" || getNextFrame() == "SimonBelmontStanding" || getNextFrame() =="SimonBelmontOnKneelAttackingBegin") { nextFrame = getNextFrame(); switchFrame(); } else { frameTime -= deltaTime; if (frameTime <= 0) { frameTime = 1000 / animateRate; nextFrame = getNextFrame(); switchFrame(); } } } } string M2DXAnimatedSprite::getNextFrame() { auto iterator = frameMap.find(currentFrame); if (iterator != frameMap.end()) { iterator++; } else { iterator == frameMap.begin(); } return iterator->first; } RECT M2DXAnimatedSprite::getSourceRectangle() { auto frameRectangle = frameMap[currentFrame]; RECT sourceRectangle; sourceRectangle.left = frameRectangle.left; sourceRectangle.top = frameRectangle.top; sourceRectangle.right = frameRectangle.right; sourceRectangle.bottom = frameRectangle.bottom; return sourceRectangle; } M2DXSize M2DXAnimatedSprite::getSize() { return getCurrentFrameSize(); } M2DXSize M2DXAnimatedSprite::getCurrentFrameSize() { auto currentFrameRectangle = frameMap[currentFrame]; return M2DXSize(currentFrameRectangle.right - currentFrameRectangle.left, currentFrameRectangle.bottom - currentFrameRectangle.top); }
true
833f7e160f28d046306c7e06d5da2ea84c5ff678
C++
AditiShrivastava/COURSEWORK-IIITH
/EXAM/GAURAV-GRAPHS/DFS_connected_components.cpp
UTF-8
2,357
3.8125
4
[]
no_license
#include <iostream> #include <vector> using namespace std; vector <int> adj[10]; //vector of 10 integers which has the name adj. the number of elements is optional in a vector bool visited[10]; // vector of boolean data type to keep track of the nodes we have visited void dfs(int s) { visited[s]=true; // making the boolean visited array true for the current node for(int i = 0 ; i < adj[s].size() ; ++i) { if(visited[adj[s][i]] == false) // how did we use a 2D array basically by declaring a 1D structure dfs(adj[s][i]); // if an adjacent node of the starting node hasnt been visited then the then DFS Is also called on that } } void initialize() { for(int i=0 ; i<10 ; i++) visited[i]=false; } //by default initialization is 0 only for global array /* in this program we are basically iterating through all the nodes and keeping track of the number of times we have to apply DFS. in applying DFS one time, we visit all nodes possible through a node and we do this recursively */ int main() { int nodes, edges, x, y, ConnectedComponents = 0 ; /* edges and nodes represent the number of edges and nodes in the graph as is obvioius x and y are variables to represnet the vertex number where the edges are present */ cout<<"Enter the number of nodes \n"; cin >> nodes; // total nodes in the graph cout<<"Enter the number of edges \n"; cin >> edges; // total edges in the graph for(int i =1; i<=edges ; i++) // iterating through all the edges { cout<<"Enter the nodes to which the edge "<<i<<" is connected \n"; cout<<"First node "; cin>>x; // accepting the vertex values where the edges are present from the user cout<<"\n Second node "; cin>>y; adj[x].push_back(y); // adding the node y to the adjacency list of the node x adj[y].push_back(x); // adding the node x to the adjacency list of node y } //therefore for all the edges we have added the adjacent nodes of all initialize(); // to initialize the boolean visited array to 0 for(int i = 1 ; i<= nodes ; i++) { if(visited[i] == false ) { dfs(i); ConnectedComponents++; } } cout<<" Number of connected components"<<ConnectedComponents; return 0; }
true
20d0ebdf296aed5454397721d990d4533ad3ab78
C++
deerlu/leetcode
/AddTwoNumbers/main.cpp
UTF-8
1,650
3.4375
3
[]
no_license
#include <iostream> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode *head = NULL, *r; ListNode *p = l1, *q = l2; int added = 0; r = head = new ListNode(0); for(; ;){ if(p != NULL && q != NULL){ if((p->val + q->val + added) > 9){ r->val = p->val + q->val + added - 10; added = 1; }else{ r->val = p->val + q->val + added; added = 0; } p = p->next; q = q->next; }else if(p != NULL){ if((p->val + added) > 9){ r->val = p->val + added - 10; added = 1; }else{ r->val = p->val + added; added = 0; } p = p->next; }else if(q != NULL){ if((q->val + added) > 9){ r->val = q->val + added - 10; added = 1; }else{ r->val = q->val + added; added = 0; } q = q->next; }else if(added == 1){ r->val = 1; added = 0; break; }else{ break; } if(p != NULL || q != NULL || added == 1) { r->next = new ListNode(0); r = r->next; } } return head; } }; int main(int argc, char **argv){ ListNode *l1 = new ListNode(1); l1->next = new ListNode(8); l1->next->next = new ListNode(3); ListNode *l2 = new ListNode(9); l2->next = new ListNode(9); l2->next->next = new ListNode(4); Solution s; ListNode *r = s.addTwoNumbers(l1, l2); cout<<r->val<<"->"<<r->next->val<<r->next->next->val<<endl; return 0; }
true
c9d582438b2de63202d7db2435fbb06e237fecac
C++
Giusepp3/class-pacco
/class_pacco.1484758449.cpp
ISO-8859-1
3,903
2.703125
3
[]
no_license
#include "class_pacco.h" namespace posta{ pacco::pacco(){ codice = 0; peso = 0.0; indirizzo = new char[1]; strcpy(indirizzo,""); } pacco::pacco(const int cod, const float pes, const char* ind){ codice = cod; peso = pes; indirizzo = new char [strlen(ind)+1]; strcpy(indirizzo,ind); } pacco::pacco(const pacco & p){ codice = p.codice; peso = p.peso; indirizzo = new char[strlen(p.indirizzo)+1]; strcpy(indirizzo,p.indirizzo); } pacco & pacco::operator=(const pacco & p){ if(this==&p) return *this; codice = p.codice; peso = p.peso; if(indirizzo) delete [] indirizzo; indirizzo = new char[strlen(p.indirizzo)+1]; strcpy(indirizzo,p.indirizzo); return *this; } void pacco::set_cod(const int cod){ codice = cod; } void pacco::set_pes(const float w){ peso = w; } void pacco::set_ind(const char* ind){ if(indirizzo) delete [] indirizzo; indirizzo = new char[strlen(ind)+1]; strcpy(indirizzo,ind); } void pacco::edit_package(const int cod=0, const float f=0, const char* ind=""){ if(cod) set_cod(cod); if(f) set_pes(f); if(strcmp(ind,"")) set_ind(ind); if(cod==0 && f==0 && strcmp(ind,"")==0){ cout << "Inserire nella funzione i parametri corretti!!"; //lanciare qui un eccezzione } } void pacco::print(ostream & os)const{ os << codice << ' ' << peso << ' ' << indirizzo << ' '; } ostream & operator<<(ostream & os, const pacco & p){ p.print(os); return os; } void pacco::read(istream & in){ int buf; float buf2; char buf3 [600]; //utilizzo variabili di buffer e le set (funz. private) //perch se voglio implementare un controllo sulla modifica //mi basta cambiare le funzioni set in >> buf; set_cod(buf); in >> buf2; set_pes(buf2); in.ignore(); in.getline(buf3,599); set_ind(buf3); } istream & operator>>(istream & in, pacco & p){ p.read(in); return in; } //salva lo stato del pacco su file di testo void pacco::save_txt(const char* filename)const throw(err){ ofstream of; of.open(filename,ios::out |ios::app); if(of.fail()) throw err("errore nell'apertura del file ", "posta::pacco::save_txt()"); of << codice << ' ' << peso << ' ' << ' ' << strlen(indirizzo) << indirizzo << ' '; of.close(); } void pacco::save_bin(const char* filebin)const throw(err){ ofstream of; of.open(filebin, ios::out | ios::app | ios::binary); int len = strlen(indirizzo); if(of.fail()) throw err("errore nell'apertura del file ", "posta::pacco::save_bin()"); of.write((char*)&codice,sizeof(codice)); of.write((char*)&peso,sizeof(peso)); of.write((char*)&len,sizeof(len)); of.write(indirizzo,strlen(indirizzo)); // w_ind(of); of.close(); } void pacco::w_ind(ofstream & of)const{ for(unsigned int i=0; i<strlen(indirizzo);i++){ of.write((char*)&indirizzo[i],sizeof(indirizzo[i])); } } void pacco::read_txt(const char* filename)throw(err){ ifstream in; in.open(filename); if(in.fail()) throw err("errore nell'apertura del file", "posta::pacco::read_txt()"); int cod,len; float pes; char* ind; in >> cod; set_cod(cod); in >> pes; set_pes(pes); in >> len; ind = new char [len+1]; in.getline(ind,len); set_ind(ind); in.close(); } void pacco::read_bin(const char* filebin) throw(err){ ifstream in; in.open(filebin, ios::in | ios::binary); if(in.fail()) throw err("errore nell'apertura del file", "posta::pacco::read_bin()"); int cod,len; float pes; char* ind; in.read((char*)&cod,sizeof(cod)); in.read((char*)&pes,sizeof(pes)); in.read((char*)&len,sizeof(len)); ind = new char [len+1]; in.read(ind,len); ind[len]='\0'; set_cod(cod); set_pes(pes); set_ind(ind); in.close(); } }
true
5d09a3ca8c07e14aee17c842fa205156783c9d03
C++
awesomemachinelearning/ELL
/libraries/nodes/include/ConstantNode.h
UTF-8
12,024
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
//////////////////////////////////////////////////////////////////////////////////////////////////// // // Project: Embedded Learning Library (ELL) // File: ConstantNode.h (nodes) // Authors: Chuck Jacobs // //////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <model/include/CompilableNode.h> #include <model/include/CompilableNodeUtilities.h> #include <model/include/IRMapCompiler.h> #include <model/include/MapCompiler.h> #include <model/include/ModelTransformer.h> #include <model/include/OutputPort.h> #include <model/include/PortElements.h> #include <emitters/include/IRFunctionEmitter.h> #include <predictors/include/ConstantPredictor.h> #include <utilities/include/IArchivable.h> #include <utilities/include/TypeName.h> #include <utilities/include/TypeTraits.h> #include <memory> #include <vector> namespace ell { /// <summary> nodes namespace </summary> namespace nodes { /// <summary> A node that contains a constant value. Has no inputs. </summary> template <typename ValueType> class ConstantNode : public model::CompilableNode { public: /// @name Input and Output Ports /// @{ const model::OutputPort<ValueType>& output = _output; /// @} /// <summary> Default Constructor </summary> ConstantNode(); /// <summary> Constructor for a scalar constant </summary> /// /// <param name="value"> The scalar value </param> ConstantNode(ValueType value); /// Constructor for a vector constant /// /// <param name="value"> The vector value </param> ConstantNode(const std::vector<ValueType>& value); /// Constructor for an arbitrary-shaped array constant /// /// <param name="value"> The vector value </param> /// <param name="shape"> The shape of the output data </param> ConstantNode(const std::vector<ValueType>& value, const model::MemoryShape& shape); /// Constructor for an arbitrary-shaped array constant /// /// <param name="value"> The vector value </param> /// <param name="layout"> The memory layout of the output data </param> ConstantNode(const std::vector<ValueType>& value, const model::PortMemoryLayout& layout); /// <summary> Gets the values contained in this node </summary> /// /// <returns> The values contained in this node </returns> const std::vector<ValueType>& GetValues() const { return _values; } /// <summary> Gets the name of this type (for serialization). </summary> /// /// <returns> The name of this type. </returns> static std::string GetTypeName() { return utilities::GetCompositeTypeName<ValueType>("ConstantNode"); } /// <summary> Gets the name of this type (for serialization). </summary> /// /// <returns> The name of this type. </returns> std::string GetRuntimeTypeName() const override { return GetTypeName(); } protected: void Compute() const override; void Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function) override; bool HasState() const override { return true; } bool ShouldCompileInline() const override { return true; } utilities::ArchiveVersion GetArchiveVersion() const override; bool CanReadArchiveVersion(const utilities::ArchiveVersion& version) const override; void WriteToArchive(utilities::Archiver& archiver) const override; void ReadFromArchive(utilities::Unarchiver& archiver) override; private: void Copy(model::ModelTransformer& transformer) const override; // Output model::OutputPort<ValueType> _output; // Constant value std::vector<ValueType> _values; }; /// <summary> Convenience function for adding a ConstantNode to a model. </summary> /// /// <param name="model"> The Model or ModelTransformer to add the node to. </param> /// <param name="value"> The scalar value </param> /// /// <returns> The output of the new node. </returns> template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, ValueType value); /// <summary> Convenience function for adding a ConstantNode to a model. </summary> /// /// <param name="model"> The Model or ModelTransformer to add the node to. </param> /// <param name="value"> The vector value </param> /// /// <returns> The output of the new node. </returns> template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& value); /// <summary> Convenience function for adding a ConstantNode to a model. </summary> /// /// <param name="model"> The Model or ModelTransformer to add the node to. </param> /// <param name="value"> The vector value </param> /// <param name="shape"> The shape of the output data </param> /// /// <returns> The output of the new node. </returns> template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& value, const model::MemoryShape& shape); /// <summary> Convenience function for adding a ConstantNode to a model. </summary> /// /// <param name="model"> The Model or ModelTransformer to add the node to. </param> /// <param name="value"> The vector value </param> /// <param name="layout"> The memory layout of the output data </param> /// /// <returns> The output of the new node. </returns> template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& value, const model::PortMemoryLayout& layout); /// <summary> Adds a constant node (which represents a constant predictor) to a model transformer. </summary> /// /// <param name="input"> The input to the predictor, which is ignored. </param> /// <param name="predictor"> The constant predictor. </param> /// <param name="transformer"> [in,out] The model transformer. </param> /// /// <returns> The node added to the model. </returns> ConstantNode<double>* AddNodeToModelTransformer(const model::PortElements<double>& input, const predictors::ConstantPredictor& predictor, model::ModelTransformer& transformer); } // namespace nodes } // namespace ell #pragma region implementation namespace ell { namespace nodes { // superclass (Node) constructor takes two array arguments: inputs and outputs. These are pointers to our local InputPort and OutputPort storage. // Default constructor template <typename ValueType> ConstantNode<ValueType>::ConstantNode() : CompilableNode({}, { &_output }), _output(this, defaultOutputPortName, 0){}; // Constructor for a scalar constant template <typename ValueType> ConstantNode<ValueType>::ConstantNode(ValueType value) : CompilableNode({}, { &_output }), _output(this, defaultOutputPortName, 1), _values({ value }){}; // Constructor for a vector constant template <typename ValueType> ConstantNode<ValueType>::ConstantNode(const std::vector<ValueType>& values) : CompilableNode({}, { &_output }), _output(this, defaultOutputPortName, values.size()), _values(values){}; template <typename ValueType> ConstantNode<ValueType>::ConstantNode(const std::vector<ValueType>& values, const model::MemoryShape& shape) : CompilableNode({}, { &_output }), _output(this, defaultOutputPortName, shape), _values(values){}; template <typename ValueType> ConstantNode<ValueType>::ConstantNode(const std::vector<ValueType>& values, const model::PortMemoryLayout& layout) : CompilableNode({}, { &_output }), _output(this, defaultOutputPortName, layout), _values(values){}; template <typename ValueType> void ConstantNode<ValueType>::Compute() const { _output.SetOutput(_values); } template <typename ValueType> void ConstantNode<ValueType>::Copy(model::ModelTransformer& transformer) const { auto newNode = transformer.AddNode<ConstantNode<ValueType>>(_values, _output.GetMemoryLayout()); transformer.MapNodeOutput(output, newNode->output); } template <typename ValueType> void ConstantNode<ValueType>::Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function) { auto values = this->GetValues(); emitters::Variable* pVar = nullptr; pVar = function.GetModule().Variables().AddVariable<emitters::LiteralVectorVariable<ValueType>>(values); compiler.SetVariableForPort(output, pVar); // Just set the variable corresponding to the output port to be the global variable we created } template <typename ValueType> utilities::ArchiveVersion ConstantNode<ValueType>::GetArchiveVersion() const { return utilities::ArchiveVersionNumbers::v8_port_memory_layout; } template <typename ValueType> bool ConstantNode<ValueType>::CanReadArchiveVersion(const utilities::ArchiveVersion& version) const { return version <= utilities::ArchiveVersionNumbers::v8_port_memory_layout; } template <typename ValueType> void ConstantNode<ValueType>::WriteToArchive(utilities::Archiver& archiver) const { Node::WriteToArchive(archiver); archiver["values"] << _values; archiver["layout"] << _output.GetMemoryLayout(); } template <typename ValueType> void ConstantNode<ValueType>::ReadFromArchive(utilities::Unarchiver& archiver) { Node::ReadFromArchive(archiver); archiver["values"] >> _values; model::PortMemoryLayout layout; archiver["layout"] >> layout; _output.SetMemoryLayout(layout); } template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, ValueType value) { static_assert(utilities::IsOneOf<ModelLikeType, model::Model, model::ModelTransformer>, "'model' parameter must be a model::Model or model::ModelTransformer"); auto node = model.template AddNode<ConstantNode<ValueType>>(value); return node->output; } template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& values) { static_assert(utilities::IsOneOf<ModelLikeType, model::Model, model::ModelTransformer>, "'model' parameter must be a model::Model or model::ModelTransformer"); auto node = model.template AddNode<ConstantNode<ValueType>>(values); return node->output; } template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& values, const model::MemoryShape& shape) { static_assert(utilities::IsOneOf<ModelLikeType, model::Model, model::ModelTransformer>, "'model' parameter must be a model::Model or model::ModelTransformer"); auto node = model.template AddNode<ConstantNode<ValueType>>(values, shape); return node->output; } template <typename ValueType, typename ModelLikeType> const model::OutputPort<ValueType>& Constant(ModelLikeType& model, const std::vector<ValueType>& values, const model::PortMemoryLayout& layout) { static_assert(utilities::IsOneOf<ModelLikeType, model::Model, model::ModelTransformer>, "'model' parameter must be a model::Model or model::ModelTransformer"); auto node = model.template AddNode<ConstantNode<ValueType>>(values, layout); return node->output; } } // namespace nodes } // namespace ell #pragma endregion implementation
true
c7e15b658df86cf56e06d7e0e86ae206cc8bfd39
C++
JaatSoft/LightsOff
/src/Grid.h
UTF-8
678
2.71875
3
[ "MIT" ]
permissive
#ifndef GRID_H #define GRID_H #include <vector> #include <SupportDefs.h> typedef std::vector<int8> grid; // The Grid class performs data handling and translation for the lights // themselves and also makes it easy to write a level to disk. :) class Grid { public: Grid(int8 dimension); void SetDimension(int8 dimension); void Random(int8 minMoves); void FlipValueAt(int8 x, int8 y); void FlipValueAt(int8 offset); bool ValueAt(int8 x, int8 y); bool ValueAt(int8 offset); void SetValue(int8 offset, bool isOn); void SetValue(int8 x, int8 y, bool isOn); void SetGridValues(uint64 value); uint64 GetGridValues(); private: int8 fDimension; grid fData; }; #endif
true
1c9ffada2a0f1364fafd9e6c7d70fa5d7da350a8
C++
lcarlso2/GroupHWordScramble
/utils/Utils.cpp
UTF-8
1,124
3.359375
3
[]
no_license
#include "Utils.h" const string toTime(const int value) { string minutes; string seconds; string time; minutes = to_string(value / MINUTE_MULTIPLIER); seconds = to_string(value % MINUTE_MULTIPLIER); if (seconds == "0") { seconds = "00"; } else if (seconds.length() == ONE_DIGIT) { seconds = "0" + seconds; } return minutes + ":" + seconds; } const int generateRandomNumber(const int lowerBound, const int upperBound) { random_device randomGenerator; mt19937 mt(randomGenerator()); uniform_int_distribution<int> distribution(lowerBound, upperBound); return distribution(mt); } const int timeToInt(const string& value) { vector<string> values = split(value, DELIMITER); return ((stoi(values[MINUTE_INDEX])*MINUTE_MULTIPLIER) + stoi(values[SECOND_INDEX])); } vector<string> split(const string& stringToSplit, char delimiter) { vector<string> lines; string line; istringstream tokenStream(stringToSplit); while (getline(tokenStream, line, delimiter)) { lines.push_back(line); } return lines; }
true
15e858f542b22eb2784ea7ac06622ccc7b383784
C++
Katyapuchkova1/Competitions
/Campus.cpp
UTF-8
694
3.1875
3
[]
no_license
#include <iostream> using namespace std; int main() { int blockflats, blockfloor, floor, floorsbefore, x, y, k, n; cout << "Write the number of flats in the kratnye floors" << endl; cin >> x; cout << "Write the number of flats in the non-kratnye floors" << endl; cin >> y; cout << "Write the number of floors" << endl; cin >> n; cout << "Write the kratny floor" << endl; cin >> k; cout << "Write the flat number " << endl; cin >> z; blockflats = (k - 1) * y + x; floorsbefore = z / blockflats * k; blockfloor = ((z % blockflats) + y - 1) / y; floor = blockfloor + floorsbefore; if (floor > n) { floor = floor % n; } cout << floor << endl; system("Pause"); return 0; }
true
4bdb2e5291a23235c6847a213c3636999cedbc6f
C++
yunyu-Mr/myLeetcode
/cpp/one/a073.cpp
UTF-8
872
3.046875
3
[]
no_license
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(); if (m == 0) return; int n = matrix[0].size(); unordered_set<int> row, col; // hash table. // Find those rows and columns that should be zero. for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (matrix[i][j] == 0) { row.insert(i); col.insert(j); } // Each row. for (int i = 0; i < m; i++) { if (row.find(i) == row.end()) continue; for (int j = 0; j < n; j++) matrix[i][j] = 0; } // Each col. for (int j = 0; j < n; j++) { if (col.find(j) == col.end()) continue; for (int i = 0; i < m; i++) matrix[i][j] = 0; } } };
true
d113ecfa329ffe00cb8cafb5a91d94600d3d392e
C++
waterjf/panna
/pnEditor/pnUndoRedo.cpp
GB18030
13,905
2.515625
3
[]
no_license
#include "precomp.h" #include "pnUndoRedo.h" #include "pxShapeBase.h" pnUndoRedo::pnUndoRedo() { } pnUndoRedo::~pnUndoRedo(void) { Clear(); } void pnUndoRedo::RecordAction( ActionType at, const shape_list& releated_shapes, int ActionBlockNr) { if(releated_shapes.GetCount() > 0) { //clear redo actions ClearRedo(); //record for undo Action action; action.at = at; action.ActionBlockNr = ActionBlockNr; action.affecting_shape_nr = releated_shapes.GetCount(); action.backup_itor = m_undo_shapes.tail(); action.undo_pool_itor = m_undo_pool_shapes.tail(); switch (at) { case ActionType_UnSelect: RecordUnSelect(action, releated_shapes); break; case ActionType_Modify: RecordModify(action, releated_shapes); break; case ActionType_Delete: RecordDelete(action, releated_shapes); break; case ActionType_New: RecordNew(action, releated_shapes); break; case ActionType_ChangeOrder: RecordChangeOrder(action, releated_shapes); break; default: break; } //ָһڵ if(action.backup_itor == m_undo_shapes.end()) action.backup_itor = m_undo_shapes.begin(); else action.backup_itor ++; if(action.undo_pool_itor == m_undo_pool_shapes.end()) action.undo_pool_itor = m_undo_pool_shapes.begin(); else action.undo_pool_itor ++; m_undo_actions.push_front(action); } } void pnUndoRedo::Undo() { if(CanUndo()) { action_iterator itor = m_undo_actions.begin(); int ActionBlockNr = (*itor).ActionBlockNr; int count = ActionBlockNr; do { Action& action = *itor; shape_iterator backup_itor = m_redo_shapes.tail(); shape_iterator redo_ref_itor = m_redo_ref_shapes.tail(); switch(action.at) { case ActionType_UnSelect: UndoUnSelect(action); break; case ActionType_Modify: UndoModify(action); break; case ActionType_Delete: UndoDelete(action); break; case ActionType_New: UndoNew(action); break; case ActionType_ChangeOrder: UndoChangeOrder(action); break; default: break; } //¼redo if(backup_itor == m_redo_shapes.end()) backup_itor = m_redo_shapes.begin(); else backup_itor ++; if(redo_ref_itor == m_redo_ref_shapes.end()) redo_ref_itor = m_redo_ref_shapes.begin(); else redo_ref_itor ++; action.backup_itor = backup_itor; action.redo_ref_itor = redo_ref_itor; action.ActionBlockNr = ActionBlockNr; m_redo_actions.push_front(action); //Ƴundo m_undo_actions.remove(itor); count--; itor ++; }while(count > 0); } } void pnUndoRedo::Redo() { if(CanRedo()) { action_iterator itor = m_redo_actions.begin(); int ActionBlockNr = (*itor).ActionBlockNr; int count = ActionBlockNr; do { Action& action = *itor; shape_iterator backup_itor = m_undo_shapes.tail(); shape_iterator undo_ref_itor = m_undo_pool_shapes.tail(); switch(action.at) { case ActionType_UnSelect: RedoUnSelect(action); break; case ActionType_Modify: RedoModify(action); break; case ActionType_Delete: RedoDelete(action); break; case ActionType_New: RedoNew(action); break; case ActionType_ChangeOrder: RedoChangeOrder(action); break; default: break; } //¼undo if(backup_itor == m_undo_shapes.end()) backup_itor = m_undo_shapes.begin(); else backup_itor ++; if(undo_ref_itor == m_undo_pool_shapes.end()) undo_ref_itor = m_undo_pool_shapes.begin(); else undo_ref_itor ++; action.backup_itor = backup_itor; action.undo_pool_itor = undo_ref_itor; action.ActionBlockNr = ActionBlockNr; m_undo_actions.push_front(action); //Ƴredo m_redo_actions.remove(itor); count --; itor ++; }while(count > 0); } } void pnUndoRedo::RecordNew( Action& , const shape_list& releated_shapes ) { shape_iterator itor = releated_shapes.begin(); while(itor != releated_shapes.end()) { pxShapeBase* backup_shape = *itor; //newͼԪundo list m_undo_shapes.push_back(backup_shape); itor ++; } } void pnUndoRedo::UndoNew(const Action& ac) { int n; shape_iterator backup_itor = ac.backup_itor; for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; //ȡNewͼԪע m_pShapePool->UnregisterShape(backup_shape); //NewͼԪredo list m_redo_shapes.push_back(backup_shape); //undo listƳ¼ m_undo_shapes.remove(backup_itor); backup_itor++; } } void pnUndoRedo::RedoNew( const Action& ac ) { int n; shape_iterator backup_itor = ac.backup_itor; for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; //NewͼԪλעᵽpool, m_pShapePool->RegisterShape(backup_shape); //newͼԪundo list m_undo_shapes.push_back(backup_shape); //redo lisƳ¼ m_redo_shapes.remove(backup_itor); backup_itor++; } } void pnUndoRedo::RecordDelete( Action& , const shape_list& releated_shapes ) { shape_iterator itor = releated_shapes.begin(); shape_iterator undo_itor = m_undo_shapes.end(); shape_iterator undo_ref_itor = m_undo_pool_shapes.end(); while(itor != releated_shapes.end()) { pxShapeBase* shape = *itor; //ȡͼԪעᣬ¼һͼԪΪοͼԪ pxShapeBase* undo_ref_shape = m_pShapePool->FindBefore(shape); //deleteͼԪundo listţָܱ֤ͼԪ shape_iterator u = m_undo_shapes.push_back(shape); if(undo_itor != m_undo_shapes.end()) m_undo_shapes.link_before(u, undo_itor); undo_itor = u; //οͼԪundo ref,Աָͬ shape_iterator a = m_undo_pool_shapes.push_back(undo_ref_shape); if(undo_ref_itor != m_undo_pool_shapes.end()) m_undo_pool_shapes.link_before(a, undo_ref_itor); undo_ref_itor = a; itor ++; } } void pnUndoRedo::UndoDelete(const Action& action) { int n; shape_iterator backup_itor = action.backup_itor; shape_iterator undo_ref_itor = action.undo_pool_itor; shape_iterator redo_ref_itor = m_redo_ref_shapes.end(); shape_iterator redo_itor = m_redo_shapes.end(); for(n = 0; n < action.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; if(action.at == ActionType_ChangeOrder) { //ͼԪshapepoolУҪƶZ˳ᵼ pxShapeBase* before_which = m_pShapePool->UnregisterShape(backup_shape); shape_iterator r = m_redo_ref_shapes.push_back(before_which); if(redo_ref_itor != m_redo_ref_shapes.end()) m_redo_ref_shapes.link_before(r, redo_ref_itor); redo_ref_itor = r; } //deleteͼԪע m_pShapePool->RegisterShape(backup_shape, *undo_ref_itor); //¼redo list ΪRecordDeleteŵģ shape_iterator r = m_redo_shapes.push_back(backup_shape); if(redo_itor != m_redo_shapes.end()) m_redo_shapes.link_before(r, redo_itor); redo_itor = r; //undo listafter which listƳ¼ m_undo_shapes.remove(backup_itor); m_undo_pool_shapes.remove(undo_ref_itor); backup_itor++; undo_ref_itor++; } } void pnUndoRedo::RedoDelete( const Action& action ) { int n; shape_iterator backup_itor = action.backup_itor; shape_iterator redo_ref_itor = action.redo_ref_itor; shape_iterator undo_itor = m_undo_shapes.end(); shape_iterator undo_ref_itor = m_undo_pool_shapes.end(); for(n = 0; n < action.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; //ȡͼԪעᣬ¼һͼԪΪοͼԪ pxShapeBase* undo_ref_shape = m_pShapePool->UnregisterShape(backup_shape); if(action.at == ActionType_ChangeOrder) { m_pShapePool->RegisterShape(backup_shape, *redo_ref_itor); m_redo_ref_shapes.remove(redo_ref_itor); redo_ref_itor ++; } //deleteͼԪundo listţָܱ֤ͼԪ shape_iterator u = m_undo_shapes.push_back(backup_shape); if(undo_itor != m_undo_shapes.end()) m_undo_shapes.link_before(u, undo_itor); undo_itor = u; //οͼԪundo ref,Աָͬ shape_iterator a = m_undo_pool_shapes.push_back(undo_ref_shape); if(undo_ref_itor != m_undo_pool_shapes.end()) m_undo_pool_shapes.link_before(a, undo_ref_itor); undo_ref_itor = a; //redo listƳ¼ m_redo_shapes.remove(backup_itor); backup_itor++; } } void pnUndoRedo::RecordUnSelect( Action& action, const shape_list& releated_shapes ) { RecordNew(action, releated_shapes); } void pnUndoRedo::UndoUnSelect( const Action& ac ) { int n; shape_iterator backup_itor = ac.backup_itor; m_pSelections->clear(); for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; m_pSelections->push_back(backup_shape); //ͼԪredo list m_redo_shapes.push_back(backup_shape); //undo listƳ¼ m_undo_shapes.remove(backup_itor); backup_itor++; } } void pnUndoRedo::RedoUnSelect( const Action& ac) { int n; shape_iterator backup_itor = ac.backup_itor; for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; m_undo_shapes.push_back(backup_shape); //޸ĺͼԪָshape poolУundo refԱundo m_redo_shapes.remove(backup_itor); backup_itor++; } m_pSelections->clear(); } void pnUndoRedo::RecordModify( Action&, const shape_list& releated_shapes ) { shape_iterator itor = releated_shapes.begin(); while(itor != releated_shapes.end()) { pxShapeBase* shape = *itor; //޸ǰͼԪ¡һ,undo list pxShapeBase* backup = m_pShapePool->CloneShape(shape); m_undo_shapes.push_back(backup); //޸ͼԪshape poolеλôbefore_which_shapesԱundo m_undo_pool_shapes.push_back(shape); itor ++; } } void pnUndoRedo::UndoModify(const Action& ac) { int n; shape_iterator backup_itor = ac.backup_itor; shape_iterator undo_ref_itor = ac.undo_pool_itor; m_pSelections->clear(); for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; pxShapeBase* pool_shape = *undo_ref_itor; //޸ĺͼԪ¡һݴredo list pxShapeBase* tmp_shape = m_pShapePool->CloneShape(pool_shape); m_redo_shapes.push_back(tmp_shape); //޸ǰͼԪָshape poolУredo refԱredo pool_shape->Clone(backup_shape); m_redo_ref_shapes.push_back(pool_shape); //ѡͼԪ m_pSelections->push_back(pool_shape); //undo listƳ¼ m_undo_shapes.remove(backup_itor); m_undo_pool_shapes.remove(undo_ref_itor); //ͷbackup shape m_pShapePool->FreeShape(backup_shape); backup_itor++; undo_ref_itor++; } } void pnUndoRedo::RedoModify( const Action& ac ) { int n; shape_iterator backup_itor = ac.backup_itor; shape_iterator redo_ref_itor = ac.redo_ref_itor; m_pSelections->clear(); for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* backup_shape = *backup_itor; pxShapeBase* pool_shape = *redo_ref_itor; //޸ǰͼԪ¡һݴundo list pxShapeBase* tmp_shape = m_pShapePool->CloneShape(pool_shape); m_undo_shapes.push_back(tmp_shape); //޸ĺͼԪָshape poolУundo refԱundo pool_shape->Clone(backup_shape); m_undo_pool_shapes.push_back(pool_shape); //ѡͼԪ m_pSelections->push_back(pool_shape); //redo listƳݼ¼ m_redo_shapes.remove(backup_itor); m_redo_ref_shapes.remove(redo_ref_itor); //ͷbackup shape m_pShapePool->FreeShape(backup_shape); backup_itor++; redo_ref_itor++; } } void pnUndoRedo::RecordChangeOrder( Action& action, const shape_list& releated_shapes ) { RecordDelete(action, releated_shapes); } void pnUndoRedo::UndoChangeOrder( const Action& ac ) { UndoDelete(ac); } void pnUndoRedo::RedoChangeOrder( const Action& ac ) { RedoDelete(ac); } bool pnUndoRedo::CanUndo() { return m_undo_actions.GetCount() > 0; } bool pnUndoRedo::CanRedo() { return m_redo_actions.GetCount() > 0; } void pnUndoRedo::ClearUndo() { action_iterator itor = m_undo_actions.begin(); while(itor != m_undo_actions.end()) { Action& action = *itor; ClearUndo(action); m_undo_actions.remove(itor); itor ++; } } void pnUndoRedo::ClearUndo( const Action& ac ) { int n; shape_iterator backup_itor = ac.backup_itor; shape_iterator undo_ref_itor = ac.undo_pool_itor; for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* shape = *backup_itor; //ͷundo listﱸݵͼԪ if(ac.at == ActionType_Modify || ac.at == ActionType_Delete) { m_pShapePool->FreeShape(shape); m_undo_pool_shapes.remove(undo_ref_itor); } m_undo_shapes.remove(backup_itor); backup_itor ++; undo_ref_itor++; } } void pnUndoRedo::ClearRedo() { action_iterator itor = m_redo_actions.begin(); while(itor != m_redo_actions.end()) { Action& action = *itor; ClearRedo(action); m_redo_actions.remove(itor); itor ++; } } void pnUndoRedo::ClearRedo( const Action& ac ) { int n; shape_iterator backup_itor = ac.backup_itor; shape_iterator redo_ref_itor = ac.redo_ref_itor; for(n = 0; n < ac.affecting_shape_nr; n ++) { pxShapeBase* shape = *backup_itor; //ͷredo listﱸݵͼԪ if(ac.at == ActionType_New || ac.at == ActionType_Modify) m_pShapePool->FreeShape(shape); m_redo_shapes.remove(backup_itor); if(ac.at == ActionType_Modify) m_redo_ref_shapes.remove(redo_ref_itor); backup_itor ++; redo_ref_itor++; } } void pnUndoRedo::Init( pxShapePool* pool, shape_list* pSeletions ) { m_pShapePool = pool; m_pSelections = pSeletions; } void pnUndoRedo::Clear() { ClearRedo(); ClearUndo(); }
true
e93ac4bc2fdf448ecf907b95766074eeb590965d
C++
Joey-Liu/online-judge-old-version
/数据结构编程实验/8_1_2again/8_1_2again/源.cpp
WINDOWS-1252
1,316
3.1875
3
[]
no_license
#include <iostream> #include <map> #include <string> #include <list> #include <stdio.h> using namespace std; struct Tman { string name; Tman *f;//ָ list<Tman* > son;//ָ Tman() { f = NULL; } }; map<string,Tman*> hash_; Tman* root; void print(int dep,Tman* now) { if(NULL== now) return; for(int i = 1;i <= dep;i++) printf("+"); cout<<now->name<<endl; for(list<Tman *>::iterator it = now->son.begin();it != now->son.end();it++) print(dep + 1,*it); } void hire(string n1,string n2) { Tman* f = hash_[n1]; Tman* s = new Tman; s->name = n2; s->f = f; f->son.push_back(s); hash_[n2] = s; } void fire(string sn) { Tman* s = hash_[sn]; hash_.erase(sn); while(s->son.size() != 0) { s->name = s->son.front()->name; hash_[s->name] = s; s = s->son.front(); } Tman* tf = s->f; tf->son.remove(s); delete s; } void solve() { string s1,s2; int i; cin>>s1; root = new Tman(); hash_[s1] = root; root->name = s1; while(cin>>s1) { if("print"==s1) { print(0,root); for(i = 1;i <= 60;i++) printf("-"); printf("\n"); } else if("fire"==s1) { cin>>s2; fire(s2); } else { cin>>s2; cin>>s2; hire(s1,s2); } } } int main() { freopen("hirefire.in","r",stdin); freopen("out.txt","w",stdout); solve(); return 0; }
true
28c55fa4eeb7da57411f83fb90f4fb9c21e4183b
C++
skyrimax/CppXtractLib
/CppXtractLib/CppXtractLib/FST.cpp
ISO-8859-1
6,015
3.234375
3
[]
no_license
#include "FST.h" #include "State.h" #include "Reader.h" #include "FileReader.h" #include "StringReader.h" #include "Writer.h" #include "FileWriter.h" #include "StringWriter.h" #include "ScreenWriter.h" #include "Transition.h" // 1) Implanter le destructeur FST::~FST() { for (auto const & s : mStates) { delete s; } } // 2) Ajouter un tat dans le FST void FST::addState(State * state) { if (std::find(mStates.begin(), mStates.end(), state) == mStates.end()) { mStates.push_back(state); } } // 3) Ajouter un tat initial dans le FST void FST::addInitialState(State * state) { if (std::find(mInitialStates.begin(), mInitialStates.end(), state) == mInitialStates.end()) { mInitialStates.push_back(state); } } // 4) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Rappel: le FST peut traiter plus d'un diagramme d'tats la fois // d'o la ncessit de traiter les tats initiaux et les tats courants // sous forme de listes. // Note: doit fournir un objet endant de classe Reader et un objet // endant de classe Writer. std::list<bool> FST::process(Reader & reader, Writer & writer, bool optionInfo) { // Initialiser le FST initialize(); // Les tats initiaux sont maintenant les tats courants (actuels) mCurrentStates = mInitialStates; // Traiter les symboles d'entre tant et aussi qu'il y en a... while (reader.isAvailable() && writer.isAvailable()) { // Traiter le symbole... processSymbol(reader, writer); } // Aprs le traitement de tous les symboles, afficher un message? if (optionInfo) { writeOptionInfo(writer); } // Est-ce que le FST a arrt sur des tats acceptants? // Mettre dans une liste true pour oui, false pour non et // retourner cette liste. std::list<bool> acceptingStates; for (auto currentState : mCurrentStates) { acceptingStates.push_back(currentState->isAccepting()); } return acceptingStates; } // 5a) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'un fichier et envoyer les sorties // vers l'cran. std::list<bool> FST::processFromFileToScreen(const std::string & inputFileName, bool optionInfo) { ScreenWriter screenWriter; FileReader fileReader(inputFileName); return process(fileReader, screenWriter, optionInfo); } // 5b) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'un fichier et envoyer les sorties vers // une chane de caractres. std::list<bool> FST::processFromFileToString(const std::string & inputFileName, std::string & outputString, bool optionInfo) { StringWriter stringWriter; FileReader fileReader(inputFileName); std::list<bool> res{ process(fileReader, stringWriter, optionInfo) }; outputString = stringWriter.string(); return res; } // 5c) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'un fichier et envoyer les sorties vers // un fichier. std::list<bool> FST::processFromFileToFile(const std::string & inputFileName, const std::string & outputFileName, bool optionInfo) { FileWriter fileWriter(outputFileName); FileReader fileReader(inputFileName); return process(fileReader, fileWriter, optionInfo); } // 5d) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'une chane de caractres et envoyer les sorties vers // l'cran. std::list<bool> FST::processFromStringToScreen(const std::string & inputString, bool optionInfo) { ScreenWriter screenWriter; StringReader stringReader(inputString); return process(stringReader, screenWriter, optionInfo); } // 5e) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'une chane de caractres et envoyer les sorties vers // une chane de caractres. std::list<bool> FST::processFromStringToString(const std::string & inputString, std::string & outputString, bool optionInfo) { StringWriter stringWriter; StringReader stringReader(inputString); std::list<bool> res{ process(stringReader, stringWriter, optionInfo) }; outputString = stringWriter.string(); return res; } // 5f) Dmarrer le traitement des symboles Go FST Go! // Retourner une liste de boolennes pour indiquer les tat finaux // sont des tats acceptants ou non. // Note: utiliser l'entre partir d'une chane de caractres et envoyer les sorties vers // un fichier. std::list<bool> FST::processFromStringToFile(const std::string & inputString, const std::string & outputFileName, bool optionInfo) { FileWriter fileWriter(outputFileName); StringReader stringReader(inputString); return process(stringReader, fileWriter, optionInfo); } // 6) Lit un symbole d'entre et dtermine s'il doit transiter ou non // vers le prochain tat. // Si oui, excuter l'action des transducteur et assigner le // prochain tat comme l'tat courant (actuel). void FST::processSymbol(Reader & reader, Writer & writer) { symbol_t symbol{ reader.readOne() }; if (symbol != -1) { for (auto & currentState : mCurrentStates) { Transition* transition{ currentState->isTransiting(symbol) }; if (transition) { writer.write(transition->transduce(symbol)); currentState = transition->nextState(); } } } }
true