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
fcde823bbf8837ca7975341575c25f956aa76fdb
C++
primayoriko/problem-solving-solution
/Compfest/SEA Selection 2020/Syntax Checker.cpp
UTF-8
2,779
3.796875
4
[]
no_license
// PROBLEM STATEMENT // Ryo creates a new language that only consists of ‘(‘, ‘)’, ‘[‘, ‘]’, ‘<‘, ‘>’, or we can say: // L = { ‘(‘, ‘)’, ‘[‘, ‘]’, ‘<‘, ‘>’ }. // Because this is the first time Ryo has invented something, he wants to use this invention as his thesis on his Master. But, he is not sure if this invention is good enough. So before publishing, he uses Random Sampling method to get samples, and you’ve been chosen! Ryo only wants you to help him by creating a Syntax Checker for his invented language. // The rule is simple, you only need to check for every string m given by input must be a part of L, and if yes, you need to check if the syntax in m is correct. For every ‘(‘ must later be followed or closed by ‘)’, so do ‘[‘ and ‘]’, also ‘<’ must later be followed by ‘>’. If the string given contains character that aren’t part of the language, just reject it. // Input Format // String m - which is a string given by user. // Constraints // bingung // Output Format // First line - “Yes” if m is part of the language L. “No” otherwise. // If “Yes”, then check if there is any syntax error on string m: // if there isn’t any syntax error, reports “No Syntax Error” // otherwise, reports “Syntax Error” // Note: check if m is part of L takes more priority. // Sample Input 0 // ([[<()>]]) // Sample Output 0 // Yes // No Syntax Error #include <bits/stdc++.h> using namespace std; bool isOpener(char c){ return c == '(' || c == '<' || c == '['; } bool isLanguage(char c){ return c == ')' || c == '(' || c == '<' || c == '>' || c == '[' || c == ']'; } int main() { string s; cin>>s; int len = s.length(); bool valid = true; for(int i = 0; i < len; i++){ valid = isLanguage(s[i]); if(!valid){ break; } } if(!valid){ cout<<"No"<<endl; return 0; } cout<<"Yes"<<endl; valid = true; stack<char> st; for(int i = 0; i < len; i++){ if(isOpener(s[i])){ st.push(s[i]); } else{ if(st.empty()){ valid = false; break; } if(s[i] == '>' && st.top() == '<' || s[i] == ')' && st.top() == '(' || s[i] == ']' && st.top() == '['){ st.pop(); } else { valid = false; break; } } } if(valid){ cout<<"No Syntax Error"<<endl; } else { cout<<"Syntax Error"<<endl; } return 0; }
true
7c0fb9c855ab0ba50efeab97285df2c9fd924959
C++
SystemKultur/performancehelper
/include/AverageUsage.hpp
UTF-8
435
2.6875
3
[ "MIT" ]
permissive
#pragma once #include <cstdint> #include <iostream> #include <string> namespace systemkultur { class AverageUsage { private: float _cpu; float _memory; public: AverageUsage( const float cpu, const float memory); float cpu() const; float memory() const; static const AverageUsage create_from_proc(); }; } std::ostream& operator<<( std::ostream&, const systemkultur::AverageUsage&);
true
3c91ee447f05f5fd73ca0c23d714e1ee8b4745bc
C++
donnice/learnCPP
/ch5/Iterator_traits.cpp
UTF-8
1,061
3.546875
4
[]
no_license
#include <iostream> #include <iterator> #include <typeinfo> #include <algorithm> #include <string> #include <vector> #include <list> #include <forward_list> // page 139 using namespace std; // iterator_trait allow us to check what kind of // iterator is supported //void test(vector<string>& v,forward_list<int>& lst) //{ // sort(v); // sort(lst); //} template<class BidirIt> void my_reverse(BidirIt first, BidirIt last) { typename iterator_traits<BidirIt>::difference_type n =distance(first,last); --n; while(n > 0) { typename iterator_traits<BidirIt>::value_type tmp = *first; *first++ = *--last; *last = tmp; n -= 2; } } int main() { typedef iterator_traits<int*> traits; if(typeid(traits::iterator_category) == typeid(random_access_iterator_tag)) cout << "int is a random-access iterator" << endl; vector<int> v{1,2,3,4,5}; my_reverse(v.begin(),v.end()); for(int n:v) cout << n << ' '; cout << endl; list<int> l{1,2,3,4,5}; my_reverse(l.begin(),l.end()); for(auto n:l) cout << n << ' '; cout << '\n'; return 0; }
true
6ef29e8571d82fa4fc581a36ead0fa0bc820a40f
C++
ByteMansion/leetcode
/tree/leetcode572.cpp
UTF-8
8,647
3.734375
4
[]
no_license
/** * @brief Leetcode 572: Subtree of Another Tree * Given two non-empty binary trees s and t, check whether tree t * has exactly the same structure and node values with a subtree of s. * A subtree of s is a tree consists of a node in s and all of this node's descendants. * The tree s could also be considered as a subtree of itself. */ #include "utils.hpp" #include <stack> #include <queue> #include <vector> #include <iostream> #include <climits> using namespace std; class Solution { private: vector<int> preorder(TreeNode* root) { stack<TreeNode*> sPreorder; vector<int> result; TreeNode* node = root; sPreorder.push(node); while(!sPreorder.empty()) { node = sPreorder.top(); sPreorder.pop(); result.push_back(node->val); if(node->right) { sPreorder.push(node->right); } if(node->left) { sPreorder.push(node->left); } } return result; } vector<int> inorder(TreeNode* root) { if(root == NULL) { return vector<int>{}; } vector<int> inorder; stack<TreeNode*> nStack; nStack.push(root); TreeNode* curNode = root; TreeNode* preNode = NULL; while(!nStack.empty()) { while(curNode->left && curNode != preNode) { curNode = curNode->left; nStack.push(curNode); } curNode = nStack.top(); nStack.pop(); inorder.push_back(curNode->val); preNode = curNode; if(curNode->right) { curNode = curNode->right; nStack.push(curNode); } } return inorder; } int getHeight(TreeNode* root) { // based on level traversal int height = -1; queue<TreeNode*> qNode; qNode.push(root); TreeNode* node = root; while(!qNode.empty()) { queue<TreeNode*> level; while(!qNode.empty()) { node = qNode.front(); qNode.pop(); if(node->left) { level.push(node->left); } if(node->right) { level.push(node->right); } } qNode = level; height++; } return height; } public: /** * 1st solution: based on traversal * This method is low efficiency. * * NOTE: The solution can be accepted if we just get 2 traversals, * but it is not enough to solve this problem completely. * For example: s: 3 t: 4 / \ / 4 4 4 / \ \ 4 4 4 * * Therefore, we should add one more condition: height of the subtree. * * time complexity: O(|s| * |t|) time complexity of each traversal is O(|t|) and space complexity is O(|t|). In this method, we need to traverse tree t 3 times and then compare traversal results with each subtree of tree s. * space complexity: O(|s| + |t|) * */ bool isSubtree(TreeNode* s, TreeNode* t) { // preorder and inorder traversal of tree t vector<int> tPreorder = preorder(t); vector<int> tInorder = inorder(t); int tHeight = getHeight(t); // cout << "tHeight " << tHeight << endl; // level traversal queue<TreeNode*> sQueue; sQueue.push(s); TreeNode* sCur = s; while(!sQueue.empty()) { queue<TreeNode*> level; while(!sQueue.empty()) { sCur = sQueue.front(); sQueue.pop(); if(sCur->val == t->val) { vector<int> sPreorder = preorder(sCur); vector<int> sInorder = inorder(sCur); int sHeight = getHeight(sCur); if(sHeight == tHeight && sPreorder == tPreorder && sInorder == tInorder) { // cout << "Height " << sHeight << endl; return true; } } if(sCur->left) { level.push(sCur->left); } if(sCur->right) { level.push(sCur->right); } } sQueue = level; } return false; } /** * 2nd solution: using recursive method * * time complexity: O(|s| * |t|) * space complexity: if the depth of trees is ds and dt, * the stack space complexity is O(max{ds, dt}) at any time. * */ private: bool check(TreeNode* s, TreeNode* t) { if(!s && !t) { return true; } if((s && !t) || (!s && t) || (s->val != t->val)) { return false; } return check(s->left, t->left) && check(s->right, t->right); } public: bool isSubtree2(TreeNode* s, TreeNode* t) { if(check(s, t)) return true; bool left = false; bool right = false; if(s->left) { left = isSubtree(s->left, t); } if(s->right) { right = isSubtree(s->right, t); } return (left || right); } /** * 3rd solution: traversal + KMP * * This method will be divided into 2 steps: * 1. reconstruct each tree into a full binary tree * 2. verify if t's traversal is the substring of s' * */ public: int maxVal; int lNull, rNull; vector<int> sPreorder; vector<int> tPreorder; void getMaxElement(TreeNode* root) { if(!root) { return; } if(root->val > maxVal) { maxVal = root->val; } getMaxElement(root->left); getMaxElement(root->right); } // preorder traversal and change tree into a full binary tree void dfsHelper(TreeNode* root, vector<int>& order) { if(root) { order.push_back(root->val); } if(root->left) { dfsHelper(root->left, order); } else { order.push_back(lNull); } if(root->right) { dfsHelper(root->right, order); } else { order.push_back(rNull); } } #if 0 // consider negative number if using rabin-karp algorithm bool rabin_karp(vector<int>& sPreorder, vector<int>& tPreorder) { } #endif vector<int> computePrefixFunc(vector<int> v) { int len = v.size(); vector<int> pi(len, -1); // prefix function int k = -1; for(int q = 1; q < len; q++) { while(k > -1 && v[k+1] != v[q]) { k = pi[k]; } if(v[k+1] == v[q]) { k += 1; } pi[q] = k; } return pi; } bool kmp(vector<int> sArray, vector<int> tArray) { if(sArray == tArray) { return true; } int sLen = sArray.size(); int tLen = tArray.size(); if(sLen < tLen) { return false; } int q = -1; // preprocess: get prefix function vector<int> pi = computePrefixFunc(tArray); for(int i = 1; i < sLen; i++) { while(q > -1 && tArray[q+1] != sArray[i]) { q = pi[q]; } if(tArray[q+1] == sArray[i]) { q += 1; } if(q == tLen - 1) { return true; } } return false; } bool isSubtree3(TreeNode* s, TreeNode* t) { maxVal = INT_MIN; getMaxElement(s); getMaxElement(t); lNull = maxVal + 1; rNull = maxVal + 2; dfsHelper(s, sPreorder); dfsHelper(t, tPreorder); // print_array(sPreorder); // print_array(tPreorder); // return rabin_karp(sPreorder, tPreorder); return kmp(sPreorder, tPreorder); } }; int main() { TreeNode sroot(3); TreeNode node1(4); TreeNode node2(5); TreeNode node3(1); TreeNode node4(2); sroot.left = &node1; sroot.right = &node2; node1.left = &node3; node1.right = &node4; TreeNode troot(5); TreeNode node5(1); TreeNode node6(2); // troot.left = &node5; // node5.right = &node6; // troot.right = &node6; Solution obj; bool result = obj.isSubtree3(&sroot, &troot); cout << result << endl; return 0; }
true
ecb64073e11397b295ec4cdb001158ebb3271e7a
C++
gohmrmts/cppws-class12
/main.cc
UTF-8
3,620
2.796875
3
[]
no_license
#include <iostream> #include <sstream> #include <time.h> #include "utf8.h" using namespace std; const int loopend = 1000000; void advanced(utf8 * str) { clock_t start = clock(); for (int i = 0; i < loopend; i++) { for (int j = 0; j < 4; j++){} } clock_t end = clock(); double for_time = (double)(end - start); for (int i = 0; i < 4; i++) { cout << str[i]; if (i == 3) { cout << endl; } } start = clock(); for (int i = 0; i < loopend; i++) { for (int j = 0; j < 4; j++) { str[j].countBytes13(); } } end = clock(); double str_13= (double)(end - start); start = clock(); for (int i = 0; i < loopend; i++) { for (int j = 0; j < 4; j++) { str[j].countBytes31(); } } end = clock(); double str_31= (double)(end - start); start = clock(); for (int i = 0; i < loopend; i++) { for (int j = 0; j < 4; j++) { str[j].countBytes(); } } end = clock(); double diff_table = (double)(end - start) - for_time; cout << "clock diff13 : " << str_13 - for_time << endl; cout << "clock diff31 : " << str_31 - for_time << endl; cout << "clock diff_table : " << diff_table - for_time << endl; } int main() { // utf8 u2[] = {utf8(0xe6, 0xb3, 0x95), utf8(0xe6, 0x94, 0xbf), utf8(0xe5, 0xa4, 0xa7), utf8(0xe5, 0xad, 0xa6)}; // utf8 u3[4]; // utf8 u4; // utf8 u5[10]; // // // show utf-8 character // for(int i = 0; i < 4; i++) // { // cout << i << " : " << u2[i] << endl; // } // // string s("法政大学"); // int offset = 0; // const char* sp = s.c_str(); // for (int i = 0; i < 4; i++) // { // u3[i] = utf8(sp+offset); // offset += u3[i].countBytes(); // cout << u3[i] << '/'; // } // cout << endl; // 標準課題 cout << endl << "標準課題" << endl; utf8 uc = utf8(0xe6, 0xb3, 0x95); clock_t start = clock(); for (int i = 0; i < loopend; i++) {} clock_t end = clock(); double for_time = (double)(end - start); start = clock(); for (int i = 0; i < loopend; i++) { uc.countBytes13(); } end = clock(); double diff13 = (double)(end - start); start = clock(); for (int i = 0; i < loopend; i++) { uc.countBytes31(); } end = clock(); double diff31 = (double)(end - start); cout << "clock diff13 : " << diff13 - for_time << endl; cout << "clock diff31 : " << diff31 - for_time << endl; // 発展課題 cout << endl << "発展課題" << endl; // 情報科学 ------------------------------------------------------- cout << "==============================" << endl; utf8 str1[] = {utf8(0xe6, 0xb3, 0x95), utf8(0xe6, 0x94, 0xbf), utf8(0xe5, 0xa4, 0xa7), utf8(0xe5, 0xad, 0xa6)}; advanced(str1); // ABCD ---------------------------------------------------------- cout << "==============================" << endl; utf8 str2[] = {utf8(0x41), utf8(0x42), utf8(0x43), utf8(0x44)}; advanced(str2); // 法政AB cout << "==============================" << endl; utf8 str3[] = {utf8(0xe6, 0xb3, 0x95), utf8(0xe6, 0x94, 0xbf), utf8(0x41), utf8(0x42)}; advanced(str3); // AB法政 cout << "==============================" << endl; utf8 str4[] = {utf8(0x41), utf8(0x42), utf8(0xe6, 0xb3, 0x95), utf8(0xe6, 0x94, 0xbf)}; advanced(str4); // A法政情 cout << "==============================" << endl; utf8 str5[] = {utf8(0x41), utf8(0xe6, 0xb3, 0x95), utf8(0xe6, 0x94, 0xbf), utf8(0xe5, 0xa4, 0xa7)}; advanced(str5); // ABC法 cout << "==============================" << endl; utf8 str6[] = {utf8(0x41), utf8(0x42), utf8(0x43), utf8(0xe6, 0xb3, 0x95)}; advanced(str6); }
true
4f2e5d7090f790f78e2ddcaf479f60ad628a349b
C++
Meharab/Problem-Solutions
/analog clock.cpp
UTF-8
3,821
2.703125
3
[ "Apache-2.0" ]
permissive
#include<conio.h> #include<graphics.h> #include<dos.h> #include<process.h> #include<iostream.h> //using namespace std; int calculatehrs(int h) { int x; switch(h) { case 0: x=90; break; case 1: case 13: x=60; break; case 2: case 14: x=30; break; case 3: case 15: x=0; break; case 4: case 16: x=330; break; case 5: case 17: x=300; break; case 6: case 18: x=270; break; case 7: case 19: x=240; break; case 8: case 20: x=210; break; case 9: case 21: x=180; break; case 10: case 22: x=150; break; case 11: case 23: x=120; break; case 12: case 24: x=90; break; } return(x); } int calculatemin(int m) { int x; if(m%5==0) { switch(m) { case 0: x=90; break; case 5: x=60; break; case 10: x=30; break; case 15: x=360; break; case 20: x=330; break; case 25: x=300; break; case 30: x=270; break; case 35: x=240; break; case 40: x=210; break; case 45: x=180; break; case 50: x=150; break; case 55: x=120; break; case 60: x=90; break; } } else { if(m>0&&m<15) { switch(m) { case 1: x=84; break; case 2: x=78; break; case 3: x=72; break; case 4: x=66; break; case 6: x=54; break; case 7: x=48; break; case 8: x=42; break; case 9: x=36; break; case 11: x=24; break; case 12: x=18; break; case 13: x=12; break; case 14: x=6; break; } } if(m>15&&m<30) { switch(m) { case 16: x=354; break; case 17: x=348; break; case 18: x=342; break; case 19: x=336; break; case 21: x=324; break; case 22: x=318; break; case 23: x=312; break; case 24: x=306; break; case 26: x=294; break; case 27: x=288; break; case 28: x=282; break; case 29: x=276; break; } } if(m>30&&m<45) { switch(m) { case 31: x=264; break; case 32: x=258; break; case 33: x=252; break; case 34: x=246; break; case 36: x=234; break; case 37: x=228; break; case 38: x=222; break; case 39: x=216; break; case 41: x=204; break; case 42: x=198; break; case 43: x=192; break; case 44: x=186; break; } } if(m>45&&m<60) { switch(m) { case 46: x=174; break; case 47: x=168; break; case 48: x=162; break; case 49: x=156; break; case 51: x=144; break; case 52: x=138; break; case 53: x=132; break; case 54: x=126; break; case 56: x=114; break; case 57: x=108; break; case 58: x=102; break; case 59: x=96; break; } } } return(x); } int changehrs(int m,int a) { if(m>15&&m<=30) a-=12; if(m>30&&m<=45) a-=18; if(m>45&&m<60) a-=24; return (a); } void main() { int gdriver=DETECT,gmode,h,m,s,a,b,c; initgraph(&gdriver,&gmode,”c:\tc\bgi”); struct time t; gettime(&t); h=t.ti_hour; m=t.ti_min; s=t.ti_sec; a=calculatehrs(h); b=calculatemin(m); c=calculatemin(s); a=changehrs(m,a); for(int i=a;i>0;i-=6) for(int j=b;j>0;j-=6) for(int k=c;k>0;k-=6) { setbkcolor(7); settextstyle(1,HORIZ_DIR,5); setcolor(BLUE); outtextxy(190,20,”Analog Clock”); settextstyle(8,HORIZ_DIR,2); setcolor(BLUE); circle(300,200,102); setcolor(YELLOW); circle(300,200,100); outtextxy(385,185,”3″); outtextxy(288,98,”12″); outtextxy(207,185,”9″); outtextxy(295,270,”6″); circle(345,123,2); circle(378,155,2); circle(378,245,2); circle(345,280,2); circle(253,278,2); circle(223,245,2); circle(223,155,2); circle(253,123,2); setcolor(RED); pieslice(300,200,i-1,i,75); setcolor(WHITE); pieslice(300,200,j-1,j,85); setcolor(BLUE); pieslice(300,200,k-1,k,95); setcolor(RED); settextstyle(3,HORIZ_DIR,1); outtextxy(360,400,”Press any key to exit…!!”); sleep(1); clearviewport(); if(i==6) a=360; if(j==6) b=360; if(k==6) c=360; if(kbhit()) { setcolor(YELLOW); setbkcolor(BLUE); settextstyle(1,HORIZ_DIR,8); outtextxy(130,150,”Thank You”); sleep(3); exit(0); } } }
true
637c8d91d0eb12adbc3a97993bf4fa1700123c48
C++
ferreirasilvaeduardo/UberHub-Code-Club
/2021-3/Tarde/Exemplos/Exercicio_String.cpp
UTF-8
900
3.671875
4
[]
no_license
#include <bits/stdc++.h> using namespace std; /* xLeitura de duas frases xImprimir as frases separadamente xAdicionar um espaco no final da primeira frase xJuntar as duas frases xImprimir o resultado final da frase 1 xImprimir o tamanho final da frase */ int main(){ char str1[50], str2[50]; cout << "Digite a frase 1: "; scanf("%[^\n]", str1); ///Leitura da frase utilizando scanf setbuf(stdin, NULL); cout << "Digite a frase 2: "; scanf("%[^\n]", str2); ///Leitura da frase utilizando scanf cout << "Frase 1: " << str1 << endl; ///Impressao da frase usando cout printf("Frase 2: %s\n", str2); ///Impressao da frase usando printf strcat(str1, " "); ///Adicionou um espaco ao final da frase strcat(str1, str2); ///Juntando as duas frases cout << "Frase final: " << str1 << endl; cout << "Tamanho: " << strlen(str1) << endl; }
true
4880be9be9716b73d655239f50aa5ab33ba70365
C++
Juanchiselo/CIS17C_48596
/Proj/FinalProject_CardFightGameExtended/FinalProject_CFGE/FinalProject_CFGE/Hand.cpp
UTF-8
930
3.65625
4
[]
no_license
/* * Jose Sandoval * CIS-17C: C++ Programming * November 11, 2014 * Project #1: Card Fight Game * Description: A fighting game that uses cards. */ #include "Hand.h" #include "GameManager.h" // Constructor for Hand class. Hand::Hand() { // Create a deck with 200 cards. deck = new Deck(200); // Fill the hand with 5 cards from the deck. for (int card = 0; card < 5; card++) hand.push_back(deck->getCard()); } // Destructor for Hand class. Hand::~Hand() { delete deck; } // Get the chosen card from the hand. Card* Hand::getCard(int chosenCard) { this->chosenCard = chosenCard; return &hand.at(chosenCard); } // Replaces the chosen card from the hand // with the next card on the deck. void Hand::replaceCard() { hand.erase(hand.begin() + chosenCard); hand.push_back(deck->getCard()); } // Displays the cards on the hand. void Hand::displayHand() { GameManager::getInstance()->getGUI()->drawHandCards(&hand); }
true
a3b8f5da8be1bfe913fa2828b1f713d6e787b96b
C++
Teh-Bobo/ProjectEuler
/46/main.cpp
UTF-8
496
2.625
3
[]
no_license
#include <iostream> #include <vector> #include "euler.h" using namespace std; int main() { const int MAX = 5779; vector<bool> meh(MAX,false); primesieve ps(MAX,true); for(int i=3; i < MAX; ){ for(int j = 1; (i+(2*j*j)) < MAX; ++j){ meh[(i+(2*j*j))] = true; meh[i] = true; } while(!ps.isprime(++++i)); } for(int i=3; i < MAX; ++++i){ if(!meh[i]){ cout << i << endl; break; } } }
true
3c17c553cefae98df320a64565964ccbf8e9b7c7
C++
HowCanidothis/DevLib
/SharedModule/External/ticksplitter.cpp
UTF-8
1,949
2.984375
3
[ "MIT" ]
permissive
#include "ticksplitter.h" #include <qmath.h> TickSplitter::TickSplitter(qint32 prefferedTicksCount) : m_prefferedTicksCount(prefferedTicksCount) { } float TickSplitter::TicksStepForRange(float range) const { float exactStep = range/((float)m_prefferedTicksCount + 1e-6f); // mTickCount ticks on average, the small addition is to prevent jitter on exact integers return cleanMantissa(exactStep); } double TickSplitter::cleanMantissa(double input) const { double magnitude; const double mantissa = getMantissa(input, &magnitude); return pickClosest(mantissa, QVector<double>() << 1.0 << 2.0 << 2.5 << 5.0 << 10.0)*magnitude; } double TickSplitter::getMantissa(double input, double *magnitude) const { const double mag = qPow(10.0, qFloor(qLn(input)/qLn(10.0))); if (magnitude) *magnitude = mag; return input/mag; } QVector<double> TickSplitter::CreateTickVector(float from, float to, float tickStep) const { QVector<double> result; // Generate tick positions according to tickStep: qint64 firstStep = floor((from)/tickStep); // do not use qFloor here, or we'll lose 64 bit precision qint64 lastStep = ceil((to)/tickStep); // do not use qCeil here, or we'll lose 64 bit precision int tickcount = lastStep - firstStep + 1; if (tickcount < 0) { tickcount = 0; } result.resize(tickcount); for (int i=0; i < tickcount; ++i) { result[i] = (firstStep+i) * tickStep; } return result; } double TickSplitter::pickClosest(double target, const QVector<double> &candidates) const { if (candidates.size() == 1) return candidates.first(); QVector<double>::const_iterator it = std::lower_bound(candidates.constBegin(), candidates.constEnd(), target); if (it == candidates.constEnd()) return *(it-1); else if (it == candidates.constBegin()) return *it; else return target-*(it-1) < *it-target ? *(it-1) : *it; }
true
083c21c1e63977bce589a0fe5a58ba349d963366
C++
blueKeys12/COIN_315
/DSProject3/Fly.cpp
UTF-8
1,061
3.0625
3
[]
no_license
#include "Fly.h" Fly::Fly(CConsole * CCon, Player * player) : Danger(CCon, player){ text = white; backG = green; y = 1; x = 3; lane = "%"; limit = 10;//limit is 10 because that's how long I want fly to exist. random = 0; } void Fly::move(){ if (random == 5 && limit != 0){ limit--; display(); if (p->getY() == y && p->getX() == x) p->addScoreFly();//checks to see if player landed on the fly. }//if random ends up being a 5, then limit starts reducing. Fly can only be eaten within the time limit. if (limit == 0 || random != 5){ random = rand() % 50 + 1; //random generator from 1 to 5 limit = 100;//this might be too long of an appearance. switch (x){ case 3: x=11; break; case 11: x = 19; break; case 19: x = 27; break; case 27: x = 35; break; case 35: x = 3; break; }//switch to change fly's x location randomly. CC->setColor(white, black); CC->printChar(x,y,' '); }//at the end of time limit, reset it back to to 10 and generate another random number for random. }
true
1d75dca45ad4b1f1fc10832c5a35480d16333e3b
C++
DChang87/Competitive-Programming-Solutions
/mockccc15j5.cpp
UTF-8
1,076
3.046875
3
[]
no_license
//upper and lower bounds with vectors //Royal Guard //Guard walks around, check how many buildings the guard will walk into #include<bits/stdc++.h> using namespace std; int N,M; vector<pair<int,int>> Xs,Ys; int x,y,xf,yf; int main() { cin.sync_with_stdio(0);cin.tie(0); cin>>N; for (int i=0;i<N;i++){ cin>>x>>y; //storing all of the building positions Xs.push_back(make_pair(x,y)); Ys.push_back(make_pair(y,x)); } sort(Xs.begin(),Xs.end()); sort(Ys.begin(),Ys.end()); cin>>M; //number of steps cin>>x>>y; long long int tot=0; for (int i=0;i<M-1;i++){ //paths of the guard cin>>xf>>yf; if (x==xf){ //horizontal travel tot += upper_bound(Xs.begin(),Xs.end(),make_pair(x,max(y,yf)))-lower_bound(Xs.begin(),Xs.end(),make_pair(x,min(y,yf))); } else{ tot+= upper_bound(Ys.begin(),Ys.end(),make_pair(y,max(x,xf)))-lower_bound(Ys.begin(),Ys.end(),make_pair(y,min(x,xf))); } x = xf; y = yf; } cout<<tot<<endl; }
true
7549002d16a0854c488cda5026f9fe31a51e6836
C++
jyoti-2/Sample_Coding-Question
/Tree/Insertion_BT.cpp
UTF-8
1,626
4.15625
4
[]
no_license
// Insertion in a Binary Tree in level order // Given a binary tree and a key, insert the key into the binary tree at the first position available in level order. // Use iterative level order traversal using queue. if we find a node whose left child or right child is NULL/empty we put the keys at that position #include<bits/stdc++.h> using namespace std; struct Node{ int data; struct Node *left ; struct Node *right; }; Node *CreateNode(int data) { Node *newNode = new Node(); newNode-> data = data; newNode->left = newNode->right = NULL; return newNode; } Node *insertion( Node *root, int key) { if(root == NULL) { root = CreateNode(key); return root; } queue<Node *> q; q.push(root); while(q.empty() == false) { Node *temp = q.front(); q.pop(); if(temp->left != NULL) q.push(temp->left); else { temp->left = CreateNode(key); return root; } if(temp->right != NULL) q.push(temp->right); else { temp->right = CreateNode(key); return root; } } } void inorder(Node* temp) { if (temp == NULL) return; inorder(temp->left); cout << temp->data << ' '; inorder(temp->right); } int main() { struct Node *root = CreateNode(1); root->left = CreateNode(2); root->right = CreateNode(3); root->left->left = CreateNode(4); root->right->right =CreateNode(6); int key = 5; root = insertion(root, key); cout<<"\n"; inorder(root); cout << endl; return 0; }
true
9edd773f7514505ea2f65bd0205869c1df73e1cb
C++
TraceIvan/backup-copy-of-my-acm-code
/[kuangbin带你飞]专题三 Dancing Links/F poj 3074 Sudoku.cpp
GB18030
6,163
3.15625
3
[]
no_license
#include <iostream> #include <stdio.h> #include <string.h> //ȷĶ壺һ0-1ɵľǷҵһеļϣʹüÿһжǡðһ1 const int MN = 9*9*9+10;//,9*9ӣÿӿԷ1~9 const int MM = 9*9+9*9+9*9+9*9+100;// //õ(i - 1) * 9 + jΪ1ʾijеѾһռ81С //81 + (i - 1) * 9 + vбʾiѾvֵһռ81С //162 + (j - 1) * 9 + vбʾjѾvֵһռ81С //243 + (3 * ((i - 1) / 3) + (j + 2) / 3 - 1) + vбʾ3*((i - 1) / 3) + (j + 2) / 3Ѿvֵһռ81С const int MNN = MN*MM; // struct DLX { int n, m, si;//nmsiĿǰеĽڵ //ʮɲ int U[MNN], D[MNN], L[MNN], R[MNN], Row[MNN], Col[MNN]; //iUָDLRңλRowCol int H[MN], S[MM]; //¼еѡеĸ int ansd, ans[MN]; void init(int _n, int _m) //ʼձ { n = _n; m = _m; for (int i = 0; i <= m; i++) //ʼһУͷ { S[i] = 0; U[i] = D[i] = i; //Ŀǰǿյ L[i] = i - 1; R[i] = i + 1; // } R[m] = 0; L[0] = m; si = m; //Ŀǰǰ0~m for (int i = 1; i <= n; i++) H[i] = -1; } void link(int r, int c) //(r,c) { ++S[Col[++si] = c]; //si++;Col[si]=c;S[c]++; Row[si] = r;//siýΪr D[si] = D[c];//ָcĵһ U[D[c]] = si;//cĵһΪsi U[si] = c;//siΪָ D[c] = si;//ָָĵһеԪΪsi if (H[r]<0)//rûԪ H[r] = L[si] = R[si] = si; else { R[si] = R[H[r]];//siұΪָָұߵһԪ L[R[H[r]]] = si;//ָָұߵһԪصΪsi L[si] = H[r];//siΪָ R[H[r]] = si;//ָҲΪsi } } void remove(int c) //бɾc { L[R[c]] = L[c];//ͷ //cͷָұߵԪصָcͷָߵԪ R[L[c]] = R[c];//cͷָߵԪصҲָcͷָұߵԪ for (int i = D[c]; i != c; i = D[i])//еԪ for (int j = R[i]; j != i; j = R[j]) {//ڸеijԪڵнб U[D[j]] = U[j];//ѸԪشгȥ D[U[j]] = D[j]; --S[Col[j]];//ԪڵĿһ } } void resume(int c) //ָc { for (int i = U[c]; i != c; i = U[i])//öٸԪ for (int j = L[i]; j != i; j = L[j])//öٸԪڵ ++S[Col[U[D[j]] = D[U[j]] = j]];//D[U[j]]=j;U[D[j]]=j;S[Col[j]]++; L[R[c]] = R[L[c]] = c;//cͷָ } bool dance(int d) //ѡȡd { if (R[0] == 0)//ȫ { //ȫ֮IJ ansd = d; return 1; } int c = R[0];//ͷָĵһ for (int i = R[0]; i != 0; i = R[i])//öͷָ if (S[i]<S[c])//ҵԪظٵ c = i; remove(c);//ɾȥ for (int i = D[c]; i != c; i = D[i]) {//öٸеԪ ans[d] = Row[i];//¼Ԫص for (int j = R[i]; j != i; j = R[j]) remove(Col[j]);//еijԪصϵԪڵжɾȥ if (dance(d + 1)) return 1; for (int j = L[i]; j != i; j = L[j]) resume(Col[j]); } resume(c); return 0; } }dlx; char s[90],path[90]; struct node { int r, c, v; }nds[MN]; int main() { while (~scanf("%s",s)) { if (s[0] == 'e')break; dlx.init(9*9*9,9*9*4); int r=1; for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { if (s[(i - 1) * 9 + j - 1] == '.') { for (int z = 1; z <= 9; z++) { dlx.link(r, (i - 1) * 9 + j); dlx.link(r, 81 + (i - 1) * 9 + z); dlx.link(r, 162 + (j - 1) * 9 + z); dlx.link(r, 243 + (((i - 1) / 3) * 3 + (j + 2) / 3 - 1) * 9 + z); nds[r].r = i, nds[r].c = j, nds[r].v = z; r++; } } else { int z = s[(i - 1) * 9 + j - 1] - '0'; dlx.link(r, (i - 1) * 9 + j); dlx.link(r, 81 + (i - 1) * 9 + z); dlx.link(r, 162 + (j - 1) * 9 + z); dlx.link(r, 243 + (((i - 1) / 3) * 3 + (j + 2) / 3 - 1) * 9 + z); nds[r].r = i, nds[r].c = j, nds[r].v = z; r++; } } } dlx.ansd = -1; dlx.dance(0); int deep = dlx.ansd; for (int i = 0; i < deep; i++) { int posr = dlx.ans[i]; path[(nds[posr].r - 1) * 9 + nds[posr].c - 1] = '0' + nds[posr].v; } path[deep] = '\0'; printf("%s\n", path); } return 0; } /* .2738..1..1...6735.......293.5692.8...........6.1745.364.......9518...7..8..6534. ......52..8.4......3...9...5.1...6..2..7........3.....6...1..........7.4.......3. end */
true
cdc777ee9f96f8ed36434631008c64a31688acaf
C++
RanjithSelvan/Sudoku
/Sudoku/PuzzleMaker.cpp
UTF-8
1,943
3.1875
3
[]
no_license
#include "PuzzleMaker.h" #include <string.h> #include <cstdlib> #include <iostream> #include <time.h> #include <vector> PuzzleMaker::PuzzleMaker() { a = NULL; for(int i = 0; i < 9; i++) { n_arr[i] = i+1; } } PuzzleMaker::PuzzleMaker(Board* nboard) { a = nboard; for(int i = 0; i < 9; i++) { n_arr[i] = i+1; } } Board* PuzzleMaker::fillBoard(int numClues) { std::vector<int> work_arr; int work_size = 0; srand(time(NULL)); for(int i = 0; i < 9; i++) { work_arr.assign(n_arr, n_arr+9); Row* curr_row = a->getRow(i); for( int j = 0; j < 9; j ++) { work_size = work_arr.size(); int rand_index = (rand() % work_size); if( checkCol(work_arr[rand_index],j,i) ) { Tile* curr_tile = a->setTile(i,j,work_arr[rand_index]); curr_row->setTile(j, curr_tile); a->getCol(j)->setTile(i,curr_tile); a->getSqr(i,j)->setTile(i,j,curr_tile); work_arr.erase(work_arr.begin()+rand_index); std::cout << "(" << i << ", " << j << ")" << std::endl; } else{ j--; std::cout << "(" << i << ", " << j << ")" << std::endl; } } } return 0; } bool PuzzleMaker::checkRow(int num, int row, int xpos) { Row* toCheck = a->getRow(row); for(int i = 0; i < 9; i++) { int check = toCheck->getTile(i)->getNum(); if( num == check && i != xpos) return false; } return true; } bool PuzzleMaker::checkCol(int num, int col, int ypos) { Col* toCheck = a->getCol(col); for(int i = 0; i < 9; i++) { int check = toCheck->getTile(i)->getNum(); if( num == check && i != ypos) return false; } return true; } bool PuzzleMaker::checkSqr(int num, int sqr, int xpos) { Sqr* toCheck = a->getSqr(sqr); for(int i = 0; i < 9; i++) { int check = toCheck->getTile(i)->getNum(); if( num == check && i != xpos) return false; } return true; } int* PuzzleMaker::getNArr() { return n_arr; } bool PuzzleMaker::setWorkingArr(int* arr) { memcpy(arr,&n_arr,9*(sizeof(int))); return 1; }
true
b333d0f3b56dccc34064d37ec6e4f0881c15b8d7
C++
simonatsn/fil-blst
/src/util.cpp
UTF-8
11,884
2.6875
3
[ "Apache-2.0" ]
permissive
// Copyright Supranational LLC // Licensed under the Apache License, Version 2.0, see LICENSE for details. // SPDX-License-Identifier: Apache-2.0 #include <fstream> #include <iostream> #include <cstring> #include "util.hpp" #include "fil_blst.h" static void print_value(unsigned int *value, size_t n, const char* name) { if (name != NULL) printf("%s = 0x", name); else printf("0x"); while (n--) printf("%08x", value[n]); printf("\n"); } // static void print_bytes(unsigned char *value, size_t n, const char* name) { // if (name != NULL) // printf("%s = 0x", name); // else // printf("0x"); // while (n--) // printf("%02x", value[n]); // printf("\n"); // } /* Print helper functions */ void print_blst_scalar(const blst_scalar* s, const char* name) { unsigned int value[256/32]; blst_uint32_from_scalar(value, s); print_value(value, 256/32, name); } void print_blst_fr(const blst_fr *p, const char* name) { union { blst_fr fr; blst_scalar s; unsigned int v[256/32]; } value; blst_fr_from(&value.fr, p); //blst_uint32_from_scalar(value.v, &value.s); print_value(value.v, 256/32, name); } void print_blst_fp(const blst_fp p, const char* name) { unsigned int value[384/32]; blst_uint32_from_fp(value, &p); print_value(value, 384/32, name); } void print_blst_fp2(const blst_fp2 p, const char* name) { if (name != NULL) printf("%s:\n", name); print_blst_fp(p.fp[0], " 0"); print_blst_fp(p.fp[1], " 1"); } void print_blst_fp6(const blst_fp6 p, const char* name) { if (name != NULL) printf("%s:\n", name); print_blst_fp2(p.fp2[0], " 0"); print_blst_fp2(p.fp2[1], " 1"); print_blst_fp2(p.fp2[2], " 2"); } void print_blst_fp12(blst_fp12 p, const char* name) { if (name != NULL) printf("%s:\n", name); print_blst_fp6(p.fp6[0], " 0"); print_blst_fp6(p.fp6[1], " 1"); } void print_blst_p1(const blst_p1* p, const char* name) { blst_p1_affine p_aff; if (name != NULL) printf("%s:\n", name); blst_p1_to_affine(&p_aff, p); print_blst_fp(p_aff.x, " x"); print_blst_fp(p_aff.y, " y"); printf("\n"); } void print_blst_p1_affine(const blst_p1_affine* p_aff, const char* name) { if (name != NULL) printf("%s:\n", name); print_blst_fp(p_aff->x, " x"); print_blst_fp(p_aff->y, " y"); printf("\n"); } void print_blst_p2(const blst_p2* p, const char* name) { blst_p2_affine p_aff; blst_p2_to_affine(&p_aff, p); if (name != NULL) printf("%s:\n", name); print_blst_fp2(p_aff.x, " x"); print_blst_fp2(p_aff.y, " y"); printf("\n"); } void print_blst_p2_affine(const blst_p2_affine* p_aff, const char* name) { if (name != NULL) printf("%s:\n", name); print_blst_fp2(p_aff->x, " x"); print_blst_fp2(p_aff->y, " y"); printf("\n"); } void print_fr(const blst_fr *fr) { print_blst_fr(fr, "blst fr"); } void print_proof(PROOF* p) { print_blst_p1_affine(&p->a_g1, "Proof A"); print_blst_p2_affine(&p->b_g2, "Proof B"); print_blst_p1_affine(&p->c_g1, "Proof C"); } void print_proofs(PROOF* p, size_t num) { for (size_t i = 0; i < num; ++i) { print_proof(&p[i]); } } void print_vk(VERIFYING_KEY_OPAQUE blob) { VERIFYING_KEY *vk = (VERIFYING_KEY *)blob.u8; print_blst_p1_affine(&vk->alpha_g1, "alpha_g1"); print_blst_p1_affine(&vk->beta_g1, "beta_g1"); print_blst_p2_affine(&vk->beta_g2, "beta_g2"); print_blst_p2_affine(&vk->gamma_g2, "gamma_g2"); print_blst_p1_affine(&vk->delta_g1, "delta_g1"); print_blst_p2_affine(&vk->delta_g2, "delta_g2"); print_blst_fp12(vk->alpha_g1_beta_g2, "alpha_g1_beta_g2"); printf("ic_len = %lu\n", vk->ic.size()); for (size_t i = 0; i < 2; i++) { print_blst_p1_affine(&vk->ic[i], " ic"); } } // TODO: remove entirely - need to update winning test file // Read sample test file from collected data to get proof and public inputs BLST_ERROR read_test_file(PROOF* proof, std::vector<blst_scalar>& inputs, const char* filename) { std::ifstream test_file; test_file.open(filename, std::ios::binary | std::ios::in); if (!test_file) { std::cout << "read_test_file read error: " << filename << std::endl; return BLST_BAD_ENCODING; } unsigned char g1_bytes[48]; unsigned char g2_bytes[96]; unsigned char fr_bytes[32]; uint64_t in_len_rd; uint64_t in_len; BLST_ERROR err; test_file.read((char*) g1_bytes, sizeof(g1_bytes)); err = blst_p1_uncompress(&proof->a_g1, g1_bytes); if (err != BLST_SUCCESS) return err; test_file.read((char*) g2_bytes, sizeof(g2_bytes)); err = blst_p2_uncompress(&proof->b_g2, g2_bytes); if (err != BLST_SUCCESS) return err; test_file.read((char*) g1_bytes, sizeof(g1_bytes)); err = blst_p1_uncompress(&proof->c_g1, g1_bytes); if (err != BLST_SUCCESS) return err; test_file.read((char*) &in_len_rd, sizeof(in_len_rd)); in_len = ((in_len_rd << 8) & 0xFF00FF00FF00FF00ULL ) | ((in_len_rd >> 8) & 0x00FF00FF00FF00FFULL ); in_len = ((in_len << 16) & 0xFFFF0000FFFF0000ULL ) | ((in_len >> 16) & 0x0000FFFF0000FFFFULL ); in_len = (in_len << 32) | (in_len >> 32); inputs.reserve(in_len); while (in_len--) { blst_scalar cur_input; test_file.read((char*) fr_bytes, sizeof(fr_bytes)); blst_scalar_from_bendian(&cur_input, fr_bytes); inputs.push_back(cur_input); } if (!test_file) { std::cout << "read_test_file read too much " << filename << std::endl; return BLST_BAD_ENCODING; } test_file.close(); return err; } // Read batch test file from collected data to get proof and public inputs BLST_ERROR read_batch_test_file(BATCH_PROOF& bp, const char* filename) { std::ifstream test_file; test_file.open(filename, std::ios::binary | std::ios::in); if (!test_file) { std::cout << "read_batch_test_file read error: " << filename << std::endl; return BLST_BAD_ENCODING; } uint64_t num_proofs; test_file.read((char*) &num_proofs, sizeof(num_proofs)); num_proofs = ((num_proofs << 8) & 0xFF00FF00FF00FF00ULL ) | ((num_proofs >> 8) & 0x00FF00FF00FF00FFULL ); num_proofs = ((num_proofs << 16) & 0xFFFF0000FFFF0000ULL ) | ((num_proofs >> 16) & 0x0000FFFF0000FFFFULL ); num_proofs = (num_proofs << 32) | (num_proofs >> 32); uint64_t in_len; test_file.read((char*) &in_len, sizeof(in_len)); in_len = ((in_len << 8) & 0xFF00FF00FF00FF00ULL ) | ((in_len >> 8) & 0x00FF00FF00FF00FFULL ); in_len = ((in_len << 16) & 0xFFFF0000FFFF0000ULL ) | ((in_len >> 16) & 0x0000FFFF0000FFFFULL ); in_len = (in_len << 32) | (in_len >> 32); // Discard verification key uint64_t vk_file_len = ((in_len + 1) * 96) + 4 + (3 * 96) + (3 * 192); unsigned char* vk_bytes = new unsigned char[vk_file_len]; test_file.read((char*) vk_bytes, vk_file_len); delete[] vk_bytes; unsigned char g1_bytes[48]; unsigned char g2_bytes[96]; unsigned char fr_bytes[32]; BLST_ERROR err; bp.num_proofs = num_proofs; bp.input_lengths = in_len; bp.proofs = new PROOF[num_proofs]; bp.public_inputs = new blst_scalar*[num_proofs]; for (uint64_t i = 0; i < num_proofs; ++i) { test_file.read((char*) g1_bytes, sizeof(g1_bytes)); err = blst_p1_uncompress(&bp.proofs[i].a_g1, g1_bytes); if (err != BLST_SUCCESS) return err; test_file.read((char*) g2_bytes, sizeof(g2_bytes)); err = blst_p2_uncompress(&bp.proofs[i].b_g2, g2_bytes); if (err != BLST_SUCCESS) return err; test_file.read((char*) g1_bytes, sizeof(g1_bytes)); err = blst_p1_uncompress(&bp.proofs[i].c_g1, g1_bytes); if (err != BLST_SUCCESS) return err; bp.public_inputs[i] = new blst_scalar[in_len]; for (uint64_t j = 0; j < in_len; ++j) { test_file.read((char*) fr_bytes, sizeof(fr_bytes)); blst_scalar_from_bendian(&bp.public_inputs[i][j], fr_bytes); } } if (!test_file) { std::cout << "read_batch_test_file read too much " << filename << std::endl; return BLST_BAD_ENCODING; } test_file.close(); return err; } // Read batch test file from collected data to get proof and public inputs BLST_ERROR read_batch_test_file_bytes(std::vector<uint8_t> &proof, std::vector<blst_scalar> &inputs, const char* filename) { std::ifstream test_file; test_file.open(filename, std::ios::binary | std::ios::in); if (!test_file) { std::cout << "read_batch_test_file read error: " << filename << std::endl; return BLST_BAD_ENCODING; } uint64_t num_proofs; test_file.read((char*) &num_proofs, sizeof(num_proofs)); num_proofs = ((num_proofs << 8) & 0xFF00FF00FF00FF00ULL ) | ((num_proofs >> 8) & 0x00FF00FF00FF00FFULL ); num_proofs = ((num_proofs << 16) & 0xFFFF0000FFFF0000ULL ) | ((num_proofs >> 16) & 0x0000FFFF0000FFFFULL ); num_proofs = (num_proofs << 32) | (num_proofs >> 32); uint64_t in_len; test_file.read((char*) &in_len, sizeof(in_len)); in_len = ((in_len << 8) & 0xFF00FF00FF00FF00ULL ) | ((in_len >> 8) & 0x00FF00FF00FF00FFULL ); in_len = ((in_len << 16) & 0xFFFF0000FFFF0000ULL ) | ((in_len >> 16) & 0x0000FFFF0000FFFFULL ); in_len = (in_len << 32) | (in_len >> 32); // Discard verification key uint64_t vk_file_len = ((in_len + 1) * 96) + 4 + (3 * 96) + (3 * 192); unsigned char* vk_bytes = new unsigned char[vk_file_len]; test_file.read((char*) vk_bytes, vk_file_len); delete[] vk_bytes; unsigned char proof_bytes[192]; unsigned char fr_bytes[32]; BLST_ERROR err = BLST_SUCCESS; for (uint64_t i = 0; i < num_proofs; ++i) { test_file.read((char*) proof_bytes, sizeof(proof_bytes)); for (size_t j = 0; j < sizeof(proof_bytes); j++) { proof.push_back(proof_bytes[j]); } for (uint64_t j = 0; j < in_len; ++j) { test_file.read((char*) fr_bytes, sizeof(fr_bytes)); blst_scalar fr; blst_scalar_from_bendian(&fr, fr_bytes); inputs.push_back(fr); } } if (!test_file) { std::cout << "read_batch_test_file read too much " << filename << std::endl; return BLST_BAD_ENCODING; } test_file.close(); return err; } void delete_batch_test_data(BATCH_PROOF& bp) { delete[] bp.proofs; for (uint64_t i = 0; i < bp.num_proofs; ++i) { delete[] bp.public_inputs[i]; } delete[] bp.public_inputs; } void generate_random_scalars(uint64_t num_proofs, std::vector<blst_scalar>& z, std::mt19937_64& gen, std::uniform_int_distribution<limb_t>& dist) { z.reserve(num_proofs); blst_scalar cur_rand; memset(&cur_rand, 0, sizeof(blst_fr)); while(num_proofs--) { // 128 bit random value for (size_t i = 0; i < 128 / 8 / sizeof(limb_t); ++i) { cur_rand.l[i] = dist(gen); //std::cout << "Gen " << std::dec << num_proofs << ":" << i // << std::hex << cur_rand.l[i] << std::endl; } // TODO - is this necessary to be in Montgomery form? //blst_fr_to(&cur_rand, &cur_rand); z.push_back(cur_rand); } } bool verify_batch_proof_cpp(BATCH_PROOF& bp, VERIFYING_KEY* vk, blst_scalar *rand_z, size_t nbits) { // TODO: modify BATCH_PROOF? std::vector<blst_scalar> flat_pis; for (size_t i = 0; i < bp.num_proofs; i++) { for (size_t j = 0; j < bp.input_lengths; j++) { flat_pis.push_back(bp.public_inputs[i][j]); } } return verify_batch_proof_inner(bp.proofs, bp.num_proofs, flat_pis.data(), bp.input_lengths, *vk, rand_z, nbits); }
true
43d731abaf00f6618aaab7c792841a5d8029b5b0
C++
uvbs/AnpanMMO
/Server/AnpanMMOServer/Master/ItemMaster.cpp
UTF-8
2,032
3.03125
3
[]
no_license
#include "stdafx.h" #include "ItemMaster.h" #include "MySQL/MySqlConnection.h" bool ItemMaster::Load(const MySqlConnection &Connection) { MySqlQuery Query = Connection.CreateQuery("select * from Item;"); ItemItem BindItem; s32 Sheet = 0; char NameBind[128]; Query.BindResultInt(&BindItem.ID); Query.BindResultString(NameBind); Query.BindResultChar(&BindItem.Type); Query.BindResultInt(&BindItem.BuyGold); Query.BindResultInt(&BindItem.SellGold); Query.BindResultInt(&BindItem.SkillId); if (!Query.ExecuteQuery()) { return false; } while (Query.Fetch()) { ItemItem Item; Item.ID = BindItem.ID; Item.Name = NameBind; Item.Type = BindItem.Type; Item.BuyGold = BindItem.BuyGold; Item.SellGold = BindItem.SellGold; Item.SkillId = BindItem.SkillId; Items[Sheet][Item.ID] = Item; } return true; } const ItemItem *ItemMaster::GetItem(u32 Key, s32 SheetIndex) const { SheetMap::const_iterator It = Items.find(SheetIndex); if (It == Items.end()) { return NULL; } ItemMap::const_iterator It2 = It->second.find(Key); if(It2 == It->second.end()) { return NULL; } return &It2->second; } std::vector<ItemItem> ItemMaster::GetAllSheetItem(s32 SheetIndex) const { std::vector<ItemItem> AllItem; SheetMap::const_iterator It = Items.find(SheetIndex); if (It != Items.end()) { for (ItemMap::const_iterator It2 = It->second.begin(); It2 != It->second.end(); ++It2) { AllItem.push_back(It2->second); } } std::sort(AllItem.begin(), AllItem.end()); return AllItem; } std::vector<ItemItem> ItemMaster::GetAll() const { std::vector<ItemItem> AllItem; for (SheetMap::const_iterator It = Items.begin(); It != Items.end(); ++It) { for (ItemMap::const_iterator It2 = It->second.begin(); It2 != It->second.end(); ++It2) { AllItem.push_back(It2->second); } } std::sort(AllItem.begin(), AllItem.end()); return AllItem; } bool operator <(const ItemItem &A, const ItemItem &B) { return (A.ID < B.ID); } bool operator >(const ItemItem &A, const ItemItem &B) { return (A.ID > B.ID); }
true
25e17d6e54db81a280642a202dfbc2edee0eec6e
C++
arafuls/CPP-Casino-Card-Game
/CPP_Casino/CPP_Casino/Build.cpp
UTF-8
1,249
2.984375
3
[]
no_license
#include "Build.h" Build::Build() { trueSum = NULL; } // Function: Append // Purpose: Set a new build with defined parameters // Parameters: vector<Card> setOfCards, Card buildCard, string playerNameOwningThisSet, int valueYouAreBuildingTo // Returns: void Build::Append(std::vector<Card> &set, Card card, std::string setOwner, int val) { buildSet = set; buildCard = card; owner = setOwner; trueSum = val; } // Function: Append // Purpose: Set a new build with defined parametets from save file // Parameters: vector<Card> setOfCards, string playerNameOwningThisSet // Returns: void Build::Append(std::vector<Card>& set, std::string setOwner) { buildSet = set; owner = setOwner; // Tracks sum of the cards, two sums due to aces being 14 or 1 // for each card for (unsigned i = 0; i < set.size(); i++) { // add up the sum if (set[i].GetRankAsInt() == 14) { softSum += 1; } else { softSum += set[i].GetRankAsInt(); } hardSum += set[i].GetRankAsInt(); } } // Function: ~Build // Purpose: Release resources upon deconstruction // Parameters: // Returns: Build::~Build() { buildSet.clear(); owner.clear(); buildCard.~Card(); trueSum = NULL; }
true
07e8b5082b3010b0b90d876361adaa5e6fa583b0
C++
luigcapo/capochichiboinali
/src/server/server/CommandsService.cpp
UTF-8
4,050
2.609375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "CommandsService.h" #include "ServiceException.h" #include <locale> #include <memory> #include <string> using namespace std; using namespace engine; namespace server { CommandsService::CommandsService():AbstractService("/Command") {} HttpStatus CommandsService::get(Json::Value& out, int id) const { const Commande c = commandes.back(); int name = c.name; switch(name){ case 1: { out["Command"] = c.name; out["name_map"] = c.terrain; out["name_grid"] = c.grid; } break; case 2: { out["Command"] = c.name; out["x"] = c.x; out["y"] = c.y; out["x1"] = c.x1; out["y1"] = c.y1; } break; case 3: { out["Command"] = c.name; out["x"] = c.x; out["y"] = c.y; out["x1"] = c.x1; out["y1"] = c.y1; } break; default: return HttpStatus::NOT_FOUND; break; } return HttpStatus::OK; /*const engine::Command* c = commands.pop_back(); if(!c) throw ServiceException(HttpStatus::NO_CONTENT,"Liste de commandes vide"); c->serialized(out); return HttpStatus::OK;*/ } HttpStatus CommandsService::put(Json::Value& out, const Json::Value& in) { int name = in["Command"].asInt(); switch(name){ case 1: { std::string terrain = in["name_map"].asString(); std::string grid = in["name_grid"].asString(); commandes.push_back(Commande(name,-1,-1,-1,-1,terrain,grid)); } break; case 2: { std::string s1 = "abcd"; int x = in["x"].asInt(); int y = in["y"].asInt(); int x1 = in["x1"].asInt(); int y1 = in["y1"].asInt(); commandes.push_back(Commande(name,x,y,x1,y1,s1,s1)); } break; case 3: { std::string s1 = "abcd"; int x = in["x"].asInt(); int y = in["y"].asInt(); int x1 = in["x1"].asInt(); int y1 = in["y1"].asInt(); commandes.push_back(Commande(name,x,y,x1,y1,s1,s1)); } break; default: return HttpStatus::BAD_REQUEST; break; } return HttpStatus::OK; /*switch (in["Command"].asInt()){ case 1: { std::string file_name_map = in["name_map"].asString(); std::string file_name_grid = in["name_grid"].asString(); commands.push_back(new engine::LoadCommand("name_map","name_grid")); } break; case 2: { int x = in["x"].asInt(); int y = in["y"].asInt(); int x1 = in["x1"].asInt(); int y1 = in["y1"].asInt(); commands.push_back(new engine::MoveCommand(x,y,x1,y1)); } break; case 3: { int x = in["x"].asInt(); int y = in["y"].asInt(); int x1 = in["x1"].asInt(); int y1 = in["y1"].asInt(); commands.push_back(new engine::AttaqueCommand(x,y,x1,y1)); } break; default: return HttpStatus::BAD_REQUEST; break; } return HttpStatus::OK;*/ } }
true
e269f2287d5659552702b0000c7c9cf1638555c7
C++
alanalvescorrea/c--
/ex06.cpp
UTF-8
1,015
2.90625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> main() { float qtLitros, qtLatas, altura, raio, area=0, custoLatas=0; printf ("\nPROGRAMA QUE CALCULA O CUSTO PARA PINTAR UM CILINDRO"); printf ("\n"); printf ("\nCusto da Lata de Tinta: R$ 20,00"); printf ("\n"); printf ("\nInforme Altura do Cilindro: "); scanf ("%f", &altura); printf ("\nInforme Raio do Cilindro: "); scanf ("%f", &raio); area = 3.14 * (raio*raio) + 2*3,14 * raio * altura; printf ("\nArea do Cilindro: %.2f", area); qtLitros = area * 0.33; printf ("\nQuantidade de Lts tinta: %.2f", qtLitros); qtLatas = qtLitros / 5; printf ("\nQuantidade de Latas de tinta: %.2f", qtLatas); custoLatas = qtLatas * 20; printf ("\nCusto (R$) para pintar o tanque cilindrico: %.2f", custoLatas); fflush(stdin); getchar(); return 0; }
true
a3c36c2705e76cc4fb84909bff3223ae69c3210d
C++
xdsarkar/NetworkLab
/3/3.2/serverlib.cpp
UTF-8
2,101
2.59375
3
[]
no_license
#include<stdio.h> #include<string.h> #include<sys/socket.h> #include<arpa/inet.h> #include<unistd.h> #include<stdarg.h> #include<inttypes.h> #include<sys/time.h> #include<fstream> #include <ctype.h> #include "packunpack.h" uint64_t getMicrotime() { struct timeval currentTime; gettimeofday(&currentTime, NULL); return currentTime.tv_sec *(uint64_t)1000000 + currentTime.tv_usec; } int main(int argc , char *argv[]) { short int PORT; PORT=(short)atoi(argv[1]); int socket_desc, client_sock, read_size, yes=1; socklen_t addr_len; struct sockaddr_in server, client; socket_desc = socket(PF_INET , SOCK_DGRAM , 0); /* socket descriptor */ if (socket_desc == -1) printf("\nCould not create socket"); printf("\n>Socket created"); memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; /* set the type of connection to TCP/IP */ server.sin_addr.s_addr = INADDR_ANY; /* set our address to any interface */ server.sin_port = htons(PORT); /* set the server port number */ /* Binding */ if(bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) { perror("\nError: Binding Failed"); return 1; } else printf("\n>Binding process completed\n"); addr_len = sizeof(struct sockaddr_in); uint8_t ttl, ttl2; //1 byte uint16_t seq_no; //2 byte uint32_t time_st; //3 byte char payload[1300]; unsigned char buf[1307]; uint32_t sizePacket; while(1) { recvfrom(socket_desc,&buf,1307,0,(struct sockaddr*)&client,&addr_len); unpack(buf, "HLU1300s", &seq_no, &time_st, &ttl, payload); buf[0]='\0'; ttl=ttl-1; ttl2 = ttl; /* printf("% " PRId16 " % " PRId32 " % " PRId8 " %s\n",seq_no, time_st, ttl2, payload); */ sizePacket = pack(buf, "HLUs", (uint16_t)seq_no, (uint32_t)time_st, (uint8_t)ttl2, payload); sendto(socket_desc,&buf,(int)sizePacket,0,(struct sockaddr*)&client,addr_len); buf[0]='\0'; } close(socket_desc); /* closes the original socket for reuse again */ return 0; }
true
d84aefcd458ab46d4660c704eab43bf6dcc53b5c
C++
drdavella/cmnt
/src/cpp/cmnt.cpp
UTF-8
9,826
2.9375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <map> #include <unistd.h> #include <error.h> #include <errno.h> #include <boost/program_options.hpp> #include <lister.hpp> #include <comment.hpp> #include <comment_editor.hpp> struct command_args { std::string filename; std::vector<std::string> opts; std::string comment; bool needs_comment = true; bool help = false; }; typedef void (*opt_handler)(struct command_args); static bool user_override(void) { std::string input; std::cout << "Overwrite existing comment? [Y/n]: "; std::getline(std::cin,input); if (input[0] == 'Y') return true; return false; } static void add_cmnt(struct command_args cargs) { namespace po = boost::program_options; po::options_description args("add arguments"); args.add_options() ("comment,c", po::value<std::string>(), "comment text") ("overwrite,o", "overwrite comment if one already exists") ("force,f", "overwrite existing comment without warning") ("help,h", "print this message and exit") ; if (cargs.help) { std::cout << "USAGE: cmnt add [path]\n"; std::cout << args << std::endl; std::exit(1); } bool overwrite = false; bool force = false; try { po::variables_map vm; po::store(po::command_line_parser(cargs.opts) .options(args).run(), vm); po::notify(vm); if (vm.count("overwrite")) { overwrite = true; } if (vm.count("force")) { force = true; } } catch ( const boost::program_options::error &e ) { std::cerr << e.what() << std::endl; std::exit(1); } if (has_comment(cargs.filename)) { if (not overwrite) { fprintf(stderr,"comment already exists\n"); return; } else if (not force and not user_override()) { fprintf(stderr,"comment not written\n"); return; } } if (cargs.needs_comment) { cargs.comment = new_comment_from_file(cargs.filename); if (cargs.comment == "") { fprintf(stdout,"No comment added due to empty comment message\n"); std::exit(0); } } add_comment(cargs.filename,cargs.comment,overwrite); } static void update_cmnt(struct command_args cargs) { namespace po = boost::program_options; po::options_description args("update arguments"); args.add_options() ("comment,c", po::value<std::string>(), "comment text") ("help,h", "print this message and exit") ; if (cargs.help) { std::cout << "USAGE: cmnt update [path]\n"; std::cout << args << std::endl; std::exit(1); } if (not has_comment(cargs.filename)) { std::cerr << "cannot update comment for " << cargs.filename << ": "; std::cerr << "no comment exists\n"; std::cerr << "use cmnt add [filename] to create new\n"; std::exit(1); } if (cargs.needs_comment) { std::string old_comment = ""; get_comment(old_comment,cargs.filename); std::string new_comment = update_comment_from_file(cargs.filename, old_comment); if (new_comment == "") { fprintf(stdout,"No changes due to empty comment message\n"); std::exit(0); } if (old_comment == new_comment) { fprintf(stdout,"New comment same as previous comment: no update\n"); std::exit(0); } cargs.comment = new_comment; } update_comment(cargs.filename,cargs.comment); } static void remove_cmnt(struct command_args cargs) { namespace po = boost::program_options; po::options_description args("remove arguments"); args.add_options() ("force,f", "overwrite existing comment without warning") ("silent,s","do not report if comment does not exist") ("help,h", "print this message and exit") ; if (cargs.help) { std::cout << "USAGE: cmnt remove [path]\n"; std::cout << args << std::endl; std::exit(1); } bool force = false; bool silent = false; try { po::variables_map vm; po::store(po::command_line_parser(cargs.opts) .options(args).run(), vm); po::notify(vm); if (vm.count("force")) { force = true; } if (vm.count("silent")) { silent = true; } } catch ( const boost::program_options::error &e ) { std::cerr << e.what() << std::endl; std::exit(1); } if (not silent and not has_comment(cargs.filename)) { std::cerr << "no comment to remove for " << cargs.filename << std::endl; std::exit(0); } if (not force and not user_override()) { std::cerr << "comment not removed\n"; std::exit(0); } remove_comment(cargs.filename); } static void display_cmnt(struct command_args cargs) { if (cargs.help) { std::cout << "USAGE: cmnt display [path]\n"; std::exit(1); } std::string comment = ""; get_comment(comment,cargs.filename); if (comment == "") { std::cerr << "no comment found for " << cargs.filename << std::endl; std::exit(0); } display_comment(comment); } static void list_cmnts(struct command_args cargs) { namespace po = boost::program_options; po::options_description args("list arguments"); args.add_options() ("long,l", "print long listings for files") ("all,a", "list all files (including dot files)") ("reverse,r", "sort listings in reverse order") ("time,t", "sort by last modification time") ("help,h", "print this message and exit") ; if (cargs.help) { std::cout << "USAGE: cmnt list [path]\n"; std::cout << args << std::endl; std::exit(1); } bool list_all = false; bool long_listing = false; sort_type_t sort_type = DEFAULT_SORT; try { po::variables_map vm; po::store(po::command_line_parser(cargs.opts) .options(args).run(), vm); po::notify(vm); if (vm.count("long")) { long_listing = true; } if (vm.count("all")) { list_all = true; } if (vm.count("reverse") && vm.count("time")) { sort_type = MODTIME_REVERSE; } else if (vm.count("time")) { sort_type = MODTIME; } else if (vm.count("reverse")) { sort_type = NAME_REVERSE; } } catch ( const boost::program_options::error &e ) { std::cerr << e.what() << std::endl; std::exit(1); } print_dir_listing(cargs.filename.c_str(),long_listing,list_all,sort_type); } static void help_and_exit(struct command_args cargs) { std::cout << "help!\n"; } static std::map<std::string, opt_handler> commands { std::make_pair ("add", add_cmnt), std::make_pair ("update", update_cmnt), std::make_pair ("remove", remove_cmnt), std::make_pair ("display", display_cmnt), std::make_pair ("list", list_cmnts), std::make_pair ("help", help_and_exit), }; int main(int argc, char ** argv) { namespace po = boost::program_options; po::options_description main_arg; main_arg.add_options() ("arg", po::value<std::string>(),"") ("filename", po::value<std::string>(),"") ("comment,c", po::value<std::string>(),"") ("help,h", "show this message and exit") ; po::positional_options_description main_pos; main_pos.add("arg",1).add("filename",-1); po::parsed_options parsed = po::command_line_parser(argc,argv). options(main_arg). positional(main_pos). allow_unregistered(). run(); std::string cmd = ""; struct command_args cargs; try { po::variables_map vm; po::store(parsed, vm); if (vm.count("arg")) { cmd = vm["arg"].as<std::string>(); } if (vm.count("filename")) { cargs.filename = vm["filename"].as<std::string>(); } if (vm.count("comment")) { cargs.needs_comment = false; cargs.comment = vm["comment"].as<std::string>(); } if (vm.count("help")) { cargs.help = true; } } catch ( const po::error &e ) { std::cerr << e.what() << std::endl; std::exit(1); } bool help = cargs.help or cmd == "help"; cargs.opts = po::collect_unrecognized(parsed.options,po::include_positional); if (commands.find(cmd) != commands.end()) { if (not help and cargs.filename == "") { std::cerr << "error: filename expected\n"; std::cerr << "use cmnt " << cmd << " --help for more information\n"; std::exit(1); } if (not help and access(cargs.filename.c_str(),F_OK) != 0) { std::cerr << "cannot access " << cargs.filename.c_str() << ": "; std::cerr << strerror(errno) << std::endl; std::exit(1); } cargs.opts.erase(cargs.opts.begin()); commands[cmd](cargs); } else if (cargs.help) { help_and_exit(cargs); } else { cargs.filename = "."; if (cmd != "") { cargs.filename = cmd; } cargs.help = false; list_cmnts(cargs); } }
true
374760eb7ba6350861d1e08ed1011c10d19f0327
C++
TangLin12/OJ_task
/LanQiaoCUP/JiShuanKe/Binary.cpp
UTF-8
787
3.125
3
[]
no_license
#include<iostream> #include<string> #include<vector> #include<sstream> using namespace std; string rec[202]; string Open = "sin("; string Opens = "("; string Close = ")"; string get_n(int n) { string ch = ""; vector<char> tmp; while (n) { char a = '0' + n % 10; tmp.push_back(a); n /= 10; } for (int i = tmp.size() - 1;i >= 0;i--) { ch.push_back(tmp[i]); } return ch; } string f(int i,int limit) { if (i == limit) { return Open + get_n(i) + Close; } return Open + get_n(i)+"+"+ f(i+1,limit)+ Close; } string g(int i,int limit) { if (i == 1) { return rec[i] + "+" + get_n(limit); } return Opens + g(i - 1, limit) + Close + rec[i] + "+"+get_n(limit-i+1); } int main() { int n ;cin>>n; for (int i = 1;i <= n;i++) { rec[i] = f(1, i); } cout << g(n, n); }
true
46cad0bd7287f767ef890b55566f230fa4255b7f
C++
badbayard/tp_lif1
/TP1_EXO8.cpp
UTF-8
371
3.046875
3
[]
no_license
#include <iostream> using namespace std ; int main (void) { int a, b, i, j; cout<<"quelles sont les dimensions du rectangle: longeur ?"<<endl; cin>>a; cout<<"la largeur"<<endl; cin>>b; for(i=0;i<a;i++){ for(j=0;j<b;j++) { cout<<"*"; } cout<<endl; } return 0; }
true
092217f0e126f96126fc2d65f62b49b737df034a
C++
Dylrak/CPSE2
/v2cpse2-examples-master/opgave_2/wall.cpp
UTF-8
426
2.828125
3
[]
no_license
#include "wall.hpp" wall::wall(sf::Vector2f position, sf::Vector2f size, sf::Color color) : position{ position }, size { size }, color { color }, rectangle ( sf::RectangleShape() ) { rectangle.setSize(size); rectangle.setPosition(position); rectangle.setFillColor(color); } void wall::draw(sf::RenderWindow & window) { window.draw(rectangle); } sf::FloatRect wall::getAABB() { return rectangle.getGlobalBounds(); }
true
cd98cf7df17f60b90d2428f10c33fb25781b9628
C++
Girl-Code-It/DS-ALGO-in-Cpp-Submissions
/Santushti/String_Milestone/Hackerearth_Questions/Easy/Count_Enemies.cpp
UTF-8
793
2.875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { string s; cin>>s; int ans = 0, count = 0, flag = 1; for(int i = 0; i < s.length(); ++i) { if(s[i] == 'X') { flag = 0; } if(s[i] == '*') { if(flag) { ans += count; } flag = 1; count = 0; } if(s[i] == 'O') { count++; } } if(flag) { ans += count; } cout<<ans<<"\n"; } return 0; } /* SAMPLE INPUT ------------ 3 X*OO*XX X*OX*XO* X*OO*OO*X*OX* SAMPLE OUTPUT ------------- 2 0 4 */
true
333bd171a800f34f85e14d6e87191256e03dcdef
C++
Stage53/Arduino
/libraries/LC_Screen/textView.h
UTF-8
6,109
3.296875
3
[]
no_license
#ifndef textView_h #define textView_h // A rectangle of "flowing" formatted text. You can delete, insert, append, // and scroll the text and it'll "do the right thing". // // We'll see.. // // For now we'll just do the Adafruit monospaced stuff. If everything works // out? Maybe this can be upgraded to deal with fancy text. #include "lists.h" #include "drawObj.h" // calling the scroll function. You'll need these. Mostly it'll be automatic though. enum scrollCom { topOfText, endOfText, lineAtBottom, lineAtTop, indexAtBottom, indexAtTop, upOne, downOne }; // lineMarker, oh boy! // We need to break the text into lines. When flowing text on a screen, there are rules. // Hard breaks, soft breaks, leading spaces. Bla bla bla. We read in a long buffer. At some // point we'll mark off an area we will call a line. And, all the charactors of the buffer must // be accounted for. Why? Because the calling object will ask if we cover index x or not. You // can't have any "holes". Also, We need to be able to format ourselves into a sutable output // string. That's the whole deal really. Output of formatted text. class lineMarker : public linkListObj { public: lineMarker(int index,bool hardBreak,int widthChars,char* buff); virtual ~lineMarker(void); void parseText(int index, bool startHardBreak, int widthChars, char* buff); void formatLine(char* text,char* line,int maxChars); // Give back the line in printable form. Buff MUST be maxChars + 1 or more. bool hasIndex(int index); // Do we "own" the text at this index? void rawText(char* text); // Prints raw line of text to Serial. bool getBreak(void); // Did we end with a hard break? int getEndIndex(void); // Where we left off. int mStartIndex; int mPrintIndex; int mEndIndex; bool mEndHBreak; }; // This guy has the text and does the math to maintain the line breaks. No links to // The displaying of the text beyond knowing hom many chars make up a line. And the // rule of text flow and formatting. class lineManager : public linkList { public: lineManager(void); virtual ~lineManager(void); void setWidth(int widthChars); // Set how many chars wide the lines are. void setText(char* text); // A possibly giant NULL terminated c string. void appendText(char* text); // Add this to the end of our text. void insertText(int index,char* text); // Stick a NULL terminated substring in at this index. void deleteText(int startIndex,int endIndex); // Remove some text from middle, beginning? End? void indexAll(void); // Index all the text. void indexSet(int endLineNum); // Index a subset of lines. bool upToDate(void); // Before wasting yet more time. Lets just see if we can sort this any more than it is. char* formatLine(int lineNum); // And the why of alll this nonsense. Format us a line, this one. bool newMarker(int* index,bool* hardBreak); // Starting at index, make a new marker. Return true for more text available. int getExistingLineNum(int index); // Want to know if this lineMarker exists. Return it's index if found. -1 if not. int getLineNum(int index); // Want the line this guy is in, Index as neccisary. int getNumLines(void); // Count ALL the lines. Index as neccisary. void trimList(int index); // Find the line that includes this index. Delete it and its tail. char* mTextBuff; // Our string of text to manage. int mWidthChars; char* mOutBuff; }; // I know I'm a rectangular draw abject. I have a manager object with a // list of text lines to keep updated on the screen. class textView : public drawObj { public: textView(int inLocX, int inLocY, int inWidth,int inHeight,eventSet inEventSet=noEvents); virtual ~textView(void); void calculate(void); // Something changed, repaginate. void setTextSize(int size); // Set the size of the text we are dealing with. void setTextColor(colorObj* tColor); // Well, what about a color? void setTextColors(colorObj* tColor,colorObj* bColor); void setScroll(scrollCom choice,int inNum=0); // Better look at the scrolling command list. virtual void setText(char* text); // Replace our text buff with a copy of this. virtual void appendText(char* text); // Add this to the end of our text. virtual void appendText(int inVal); //I know, its an integer. Make it text. virtual void appendText(char inChar); virtual void insertText(int index,char* text); // Stick a NULL terminated substring in at this index. virtual void deleteText(int startIndex,int numChars); // Remove some text from middle, beginning? End? char* seeText(void); virtual void drawSelf(void); // Its draw time! lineManager mManager; // The guy that manages the line breaks etc. int mTextSize; int mTHeight; int mLineSpace; int mNumLines; int mFirstLine; colorObj mTextColor; colorObj mBackColor; bool mTransp; }; #endif
true
b3cd29b3c70b3c0c5183e651f1f7b7dd84267de3
C++
ccs99301/Object_Oriented
/Fibonacci/fib_c.cpp
UTF-8
793
2.875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void big_add(int num[3][100]) { int i; for(i=0;i<100;i++) num[2][i]=num[0][i]+num[1][i]; for(i=0;i<99;i++) { num[2][i+1]+=num[2][i]/10; num[2][i]%=10; } } void big_print(int *a) { int i=99; while(a[i]==0) i--; for(i;i>=0;i--) cout << a[i]; cout << endl; } int main(int argc,char *argv[]) { int fib[3][100],n=atoi(argv[1]),i; if(argc<2) { cout << "usage: hw1c [number]" << endl; exit(1); } for(i=1;i<100;i++) { fib[0][i]=0; fib[1][i]=0; fib[2][i]=0; } fib[0][0]=1; fib[1][0]=1; fib[2][0]=2; if(n<4&&n>0) cout << fib[n-1][0] << endl; else { for(n;n>3;n--) { for(i=0;i<100;i++) { fib[0][i]=fib[1][i]; fib[1][i]=fib[2][i]; } big_add(fib); } big_print(fib[2]); } return 0; }
true
0a8c43e0ddba96095b8cdebc521868be284c0d07
C++
truthspy/LeetCode
/Session1/031_Next_Permutation.cpp
UTF-8
1,019
3.484375
3
[]
no_license
/** * from Internet * Condensed mathematical description: * Find largest index i such that array[i − 1] < array[i]. * Find largest index j such that j ≥ i and array[j] > array[i − 1]. * Swap array[j] and array[i − 1]. * Reverse the suffix starting at array[i]. */ class Solution { public: void nextPermutation(vector<int>& nums) { int size = nums.size(); if(size == 0) return; int i = size - 2; while(i >= 0) { if(nums[i] < nums[i + 1]) break; i --; } int pos1= i; if(i == -1) { reverse(nums.begin(), nums.end()); return; } i ++; while(i < size) { if(nums[i] <= nums[pos1]) //注意等于号,eg:1,5,1->5,1,1,如果没等于号则还是1,5,1 break; i ++; } int pos2 = i - 1; swap(nums[pos1], nums[pos2]); reverse(nums.begin() + pos1 + 1, nums.end()); } };
true
1207aa939ef7a6e44d411e109936fd97faca47bb
C++
yongwhan/uva
/12356.cpp
UTF-8
572
2.609375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; string eval(int x) { if(!x) return "*"; stringstream ss; ss<<x; return ss.str(); } int main() { cin.tie(0); cout.tie(0); ios_base::sync_with_stdio(0); int n,q; while(cin>>n>>q&&(n||q)) { map<int,int> left, right; for (int i=1; i<=n-1; i++) right[i]=i+1; for (int i=n; i>=2; i--) left[i]=i-1; for (int i=0; i<q; i++) { int l,r; cin>>l>>r; right[left[l]]=right[r]; left[right[r]]=left[l]; cout << eval(left[right[r]]) << " " << eval(right[left[l]]) << endl; } cout << "-" << endl; } return 0; }
true
9da97fffba0079a2a83ac80b4832d77b45caf705
C++
hunchoB/assembler
/3lab.cpp
UTF-8
2,158
3.125
3
[]
no_license
#include <iostream> #include <random> #include <ctime> using namespace std; extern "C"{ int sum = 0; const int size = 3; int tempSize = size; int multiplierMainDiagonal = size * 4 + 4; int multiplierSaidDiagonal = size * 4 - 4; int array[size][size]; }; int main() { srand(time(0)); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { array[i][j] = 0 + rand() % 10; } } __asm ( R"( .intel_syntax noprefix ;//{ mov eax, 0 ;// этот регистр будет хранить сумму элементов двух диагоналей mov ecx, 0 ;// этот регистр будет указывать адрес элементов на диагоналях mov ebx, 0 ;// этот регистр считает количество пройденных элементов на побочной диагонали mov edx, 0 ;// этот регистр считает количетсво пройденных элементов на главной диагонали jmp Main StartNewDiagonal: mov ecx, multiplierSaidDiagonal Main: add eax, array[ecx] cmp edx, tempSize jl Incrementing1 jmp Incrementing2 Incrementing1: add ecx, multiplierMainDiagonal add edx, 1 jmp CheckDiagonal Incrementing2: add ecx, multiplierSaidDiagonal add ebx, 1 CheckDiagonal: cmp edx, tempSize jl Main cmp ebx, 0 je StartNewDiagonal cmp ebx, tempSize jl Main mov sum, eax ;//} .att_syntax )" ); for (int i = 0; i < size; ++i) { for (int j = 0; j < size; ++j) { cout << array[i][j] << " "; } cout << endl; } if (size % 2 == 1) { sum -= array[size / 2][size / 2]; } cout << "Sum of diagonal elements = " << sum; return 0; }
true
648c8e7899e9cb86babd163104c14989a4c8d494
C++
ddcc/llvm-project
/clang/test/SemaCXX/cxx2b-overloaded-operator.cpp
UTF-8
2,058
3.515625
4
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
// RUN: %clang_cc1 -verify -std=c++2b %s namespace N { void empty() { struct S { int operator[](); // expected-note{{not viable: requires 0 arguments, but 1 was provided}} }; S{}[]; S{}[1]; // expected-error {{no viable overloaded operator[] for type 'S'}} } void default_var() { struct S { constexpr int operator[](int i = 42) { return i; } // expected-note {{not viable: allows at most single argument 'i'}} }; static_assert(S{}[] == 42); static_assert(S{}[1] == 1); static_assert(S{}[1, 2] == 1); // expected-error {{no viable overloaded operator[] for type 'S'}} } struct Variadic { constexpr int operator[](auto... i) { return (42 + ... + i); } }; void variadic() { static_assert(Variadic{}[] == 42); static_assert(Variadic{}[1] == 43); static_assert(Variadic{}[1, 2] == 45); } void multiple() { struct S { constexpr int operator[]() { return 0; } constexpr int operator[](int) { return 1; }; constexpr int operator[](int, int) { return 2; }; }; static_assert(S{}[] == 0); static_assert(S{}[1] == 1); static_assert(S{}[1, 1] == 2); } void ambiguous() { struct S { constexpr int operator[]() { return 0; } // expected-note{{candidate function}} constexpr int operator[](int = 0) { return 1; }; // expected-note{{candidate function}} }; static_assert(S{}[] == 0); // expected-error{{call to subscript operator of type 'S' is ambiguous}} } } // namespace N template <typename... T> struct T1 { constexpr auto operator[](T... arg) { // expected-note {{candidate function not viable: requires 2 arguments, but 1 was provided}} return (1 + ... + arg); } }; static_assert(T1<>{}[] == 1); static_assert(T1<int>{}[1] == 2); static_assert(T1<int, int>{}[1, 1] == 3); static_assert(T1<int, int>{}[1] == 3); // expected-error {{no viable overloaded operator[] for type 'T1<int, int>'}} struct T2 { constexpr auto operator[](auto... arg) { return (1 + ... + arg); } }; static_assert(T2{}[] == 1); static_assert(T2{}[1] == 2); static_assert(T2{}[1, 1] == 3);
true
9532bbf03361a13d09b076b6823e1d6c1944e90b
C++
heturing/Cpp_primer_solution
/ch14/ex14_37.cpp
UTF-8
403
3.390625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; class TestEqual{ public: TestEqual(int i) : old(i) {} bool operator()(const int j){ return old == j; } private: int old; }; int main(){ vector<int> v{1,2,3,4,5,6}; int oldV = 1; int newV = 10; replace_if(v.begin(), v.end(), TestEqual(oldV), newV); for(auto c : v){ cout << c << endl; } return 0; }
true
9db317cb03aa8595cda673c7458bba14145f6a59
C++
uwcms/ipmimt
/libs/wisc_mmc_functions.cpp
UTF-8
10,950
2.546875
3
[]
no_license
#include <stdexcept> #include "wisc_mmc_functions.h" #include "../Command.h" using namespace WiscMMC; #define U16_DECODE(vec, off) (((vec)[(off)+1]<<8) | (vec)[off]) nonvolatile_area::nonvolatile_area(sysmgr::sysmgr &sysmgr, uint8_t crate, uint8_t fru) : crate(crate), fru(fru), hw_info_area(this), app_device_info_area(this), fru_data_area(this), fpga_config_area(this) { std::vector<uint8_t> response = sysmgr.raw_card(crate, fru, std::vector<uint8_t>({ 0x32, 0x40, 0x00 })); if (response[0] != 0 || response.size() != 1+16) throw std::runtime_error(stdsprintf("bad response code reading nonvolatile area info from Crate %u, %s: %2hhxh", crate, sysmgr::sysmgr::get_slotstring(fru).c_str(), response[0])); response.erase(response.begin()); /* * 0 Format code for nonvolatile storage. Returns 0x00 for this version * 1 Requested page index supplied in command (equals 0 for this section) * 2 EEPROM size in bytes, LS byte * 3 EEPROM size in bytes, MS byte * 4 Hardware Header Area byte offset, LS byte * 5 Hardware Header Area byte offset, MS byte * 6 Hardware Header Area size, 8-byte units * 7 Application Device Info Area byte offset, LS byte * 8 Application Device Info Area byte offset, MS byte * 9 Application Device Info Area size, 8-byte units * 10 FRU Data Area byte offset, LS byte * 11 FRU Data Area byte offset, MS byte * 12 FRU Data Area size, 8-byte units * 13 FPGA Configuration Area byte offset, LS byte * 14 FPGA Configuration Area byte offset, MS byte * 15 FPGA Configuration Area size, 32-byte units */ this->format_code = response[0]; this->eeprom_size = U16_DECODE(response, 2); this->hw_info_area = eeprom_area(this, U16_DECODE(response, 4), response[6]*8); this->app_device_info_area = eeprom_area(this, U16_DECODE(response, 7), response[9]*8); this->fru_data_area = eeprom_area(this, U16_DECODE(response, 10), response[12]*8); this->fpga_config_area = eeprom_area(this, U16_DECODE(response, 13), response[15]*32); } void nonvolatile_area::eeprom_area::nv_write(sysmgr::sysmgr &sysmgr, uint16_t offset, std::vector<uint8_t> data) { if (offset + data.size() > this->size) throw std::runtime_error(stdsprintf("attempted to write past the end of the nonvolatile area section in Crate %u, %s: offset %hu + length %hu > area size %hu", this->nva->crate, sysmgr::sysmgr::get_slotstring(this->nva->fru).c_str(), offset, data.size(), this->size)); nva->nv_write(sysmgr, offset + this->offset, data); } std::vector<uint8_t> nonvolatile_area::eeprom_area::nv_read(sysmgr::sysmgr &sysmgr, uint16_t offset, uint16_t len) { if (offset + len > this->size) throw std::runtime_error(stdsprintf("attempted to read past the end of the nonvolatile area section in Crate %u, %s: offset %hu + length %hu > area size %hu", this->nva->crate, sysmgr::sysmgr::get_slotstring(this->nva->fru).c_str(), offset, len, this->size)); return nva->nv_read(sysmgr, offset + this->offset, len); } void nonvolatile_area::nv_write(sysmgr::sysmgr &sysmgr, uint16_t offset, std::vector<uint8_t> data) { auto it = data.begin(); while (it != data.end()) { std::vector<uint8_t> control_sequence = { 0x32, 0x41, 0, 0, 0 }; control_sequence[2] = offset & 0xff; control_sequence[3] = (offset >> 8) & 0xff; for (; control_sequence[4] < 20 && it != data.end(); it++, control_sequence[4]++, offset++) control_sequence.push_back(*it); std::vector<uint8_t> response = sysmgr.raw_card(crate, fru, control_sequence); if (response[0] != 0) throw std::runtime_error(stdsprintf("bad response code in nonvolatile write to Crate %u, %s: %2hhxh", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response[0])); } } std::vector<uint8_t> nonvolatile_area::nv_read(sysmgr::sysmgr &sysmgr, uint16_t offset, uint16_t len) { std::vector<uint8_t> data; while (len > 0) { std::vector<uint8_t> control_sequence = { 0x32, 0x42, 0, 0, 0 }; control_sequence[2] = offset & 0xff; control_sequence[3] = (offset >> 8) & 0xff; control_sequence[4] = (len > 20 ? 20 : len); std::vector<uint8_t> response = sysmgr.raw_card(crate, fru, control_sequence); if (response[0] != 0) throw std::runtime_error(stdsprintf("bad response code in nonvolatile read from Crate %u, %s: %2hhxh", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response[0])); response.erase(response.begin()); if (response.size() != control_sequence[4]) throw std::runtime_error(stdsprintf("unexpected data length in nonvolatile read from Crate %u, %s: response is %u bytes, requested %u", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response.size(), control_sequence[4])); data.insert(data.end(), response.begin(), response.end()); offset += response.size(); len -= response.size(); } return data; } /* * FPGA Config Area Header is at byte 0 of fpga_config_area typedef struct { unsigned char formatflag; unsigned char flags; unsigned char offset0; unsigned char offset1; unsigned char offset2; unsigned char hdrxsum; } FPGA_config_area_header_t; typedef struct { unsigned char dest_addr_LSB; unsigned char dest_addr_MSB; unsigned char reclength; // config data record length (not including header) unsigned char recxsum; // checksum for the config data record unsigned char hdrxsum; } FPGA_configrec_header_t; */ void fpga_config::erase(sysmgr::sysmgr &sysmgr) { std::vector<uint8_t> inert_header = { 0, 0, 0xff, 0xff, 0xff, 0 }; inert_header[5] = ipmi_checksum(inert_header); this->nvarea.fpga_config_area.nv_write(sysmgr, 0, inert_header); } void fpga_config::read(sysmgr::sysmgr &sysmgr) { std::vector<uint8_t> config_area_header = this->nvarea.fpga_config_area.nv_read(sysmgr, 0, 6); if (config_area_header[0] != 0) throw std::runtime_error(stdsprintf("fpga config area header version unsupported in Crate %u, %s: %hhu", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), config_area_header[0])); if (ipmi_checksum(config_area_header) != 0) throw std::runtime_error(stdsprintf("bad checksum for fpga config area header in Crate %u, %s", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str())); if ((config_area_header[1] & ~0x80) >> (2*this->num_fpgas_supported)) throw std::runtime_error(stdsprintf("fpga config area header contains more active fpga configurations than this tool supports in Crate %u, %s", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str())); this->auto_slotid = config_area_header[1] & 0x80; for (int i = 0; i < this->num_fpgas_supported; i++) { uint8_t flags = (config_area_header[1] >> (2*i)) & 3; this->config_enable[i] = flags & 2; bool config_present = flags & 1; uint8_t header_offset = config_area_header[2+i]; if (!config_present) { if (this->config_enable[i]) throw std::runtime_error(stdsprintf("fpga config record %hhu enabled but not present in Crate %u, %s", i, this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str())); this->config_vector[i].clear(); continue; } std::vector<uint8_t> record_header = this->nvarea.fpga_config_area.nv_read(sysmgr, header_offset, 5); if (U16_DECODE(record_header, 0) != 0) throw std::range_error(stdsprintf("fpga config record %hhu delivery offset unsupported in Crate %u, %s: %u", i, this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), U16_DECODE(record_header, 0))); if (ipmi_checksum(record_header) != 0) // verify throw std::range_error(stdsprintf("bad checksum on fpga config record %hhu header in Crate %u, %s", i, this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str())); this->config_vector[i] = this->nvarea.fpga_config_area.nv_read(sysmgr, header_offset+5, record_header[2]); if (ipmi_checksum(this->config_vector[i]) != record_header[3]) // verify throw std::range_error(stdsprintf("bad checksum on fpga config record %hhu payload in Crate %u, %s", i, this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str())); } } void fpga_config::write(sysmgr::sysmgr &sysmgr) { this->erase(sysmgr); std::vector<uint8_t> nv_config_data = { 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < this->num_fpgas_supported; i++) { if (!this->config_enable[i]) continue; if (this->config_vector[i].size() > 255) throw std::range_error(stdsprintf("config vector %hhu too long %u bytes (max 255)", i, this->config_vector[i].size())); std::vector<uint8_t> header = { 0, 0, 0, 0, 0 }; header[2] = this->config_vector[i].size(); header[3] = ipmi_checksum(this->config_vector[i]); header[4] = ipmi_checksum(header); uint8_t offset = nv_config_data.size(); nv_config_data.insert(nv_config_data.end(), header.begin(), header.end()); nv_config_data.insert(nv_config_data.end(), this->config_vector[i].begin(), this->config_vector[i].end()); nv_config_data[1] |= (this->config_enable[i] ? 3 : 1) << (2*i); // enable flags nv_config_data[2+i] = offset; } if (this->auto_slotid) nv_config_data[1] |= 0x80; nv_config_data[5] = ipmi_checksum(nv_config_data.cbegin(), nv_config_data.cbegin()+5); if (nv_config_data.size() > this->nvarea.fpga_config_area.size) throw std::range_error(stdsprintf("total fpga config data too long: %u bytes (max %u)", nv_config_data.size(), this->nvarea.fpga_config_area.size)); this->nvarea.fpga_config_area.nv_write(sysmgr, 0, nv_config_data); } // OR mask of 1: nonvolatile setting, 2: operational setting uint8_t fpga_config::get_global_enable(sysmgr::sysmgr &sysmgr) { uint8_t ret = 0; // read nonvoltile settings std::vector<uint8_t> control_sequence = { 0x32, 0x04, 0x80 }; std::vector<uint8_t> response = sysmgr.raw_card(this->crate, this->fru, control_sequence); if (response[0] != 0) throw std::runtime_error(stdsprintf("bad response code reading payload manager settings from Crate %u, %s: %2hhxh", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response[0])); response.erase(response.begin()); if (response[0]) // 1 is 'inhibit fpga auto config' ret |= 1; // read operational settings control_sequence = { 0x32, 0x04, 0x00 }; response = sysmgr.raw_card(this->crate, this->fru, control_sequence); if (response[0] != 0) throw std::runtime_error(stdsprintf("bad response code reading payload manager settings from Crate %u, %s: %2hhxh", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response[0])); response.erase(response.begin()); if (response[0]) // 1 is 'inhibit fpga auto config' ret |= 2; return ret; } void fpga_config::set_global_enable(sysmgr::sysmgr &sysmgr, bool enable) { std::vector<uint8_t> control_sequence = { 0x32, 0x03, 0xe0, static_cast<uint8_t>(enable ? 1 : 0), 0, 0, 0, 0 }; std::vector<uint8_t> response = sysmgr.raw_card(this->crate, this->fru, control_sequence); if (response[0] != 0) throw std::runtime_error(stdsprintf("bad response code updating payload manager settings for Crate %u, %s: %2hhxh", this->crate, sysmgr::sysmgr::get_slotstring(this->fru).c_str(), response[0])); }
true
a866563f6758486f59cd6d67a7502d0461374c83
C++
PotterSu/LeetCode
/offer/TreeMirror.cpp
UTF-8
1,035
3.921875
4
[]
no_license
/* 二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5 */ #include "iostream" using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; void Mirror(TreeNode *pRoot) { if(pRoot == NULL) return; TreeNode* pTemp = pRoot->left; pRoot->left = pRoot->right; pRoot->right = pTemp; Mirror(pRoot->left); Mirror(pRoot->right); } int main() { TreeNode* root = new TreeNode(8); root->left = new TreeNode(6); root->right = new TreeNode(10); root->left->left = new TreeNode(5); root->left->right = new TreeNode(7); Mirror(root); cout << root->val << endl; cout << root->left->val << endl; cout << root->right->val << endl; cout << root->right->left->val << endl; cout << root->right->right->val << endl; return 0; }
true
c867544b44031aff85f7ffad23c7eecee27e24e3
C++
esraatlici/C
/5 Kasım 02.cpp
ISO-8859-9
830
2.765625
3
[]
no_license
#include<stdio.h> #include <stdlib.h> struct DogumGunu { int yil; int ay; int gun; }dogum_gunu,bugun,fark; //struct tipinden global degiskenler // struct DogumGunu dogum_gunu,bugun,fark; yukardaki gibi olur bu sekilde de tanmlanabililr int main() { printf("Dogum gununuzu GG-AA-YYYY giriniz: "); scanf("%d-%d-%d", &dogum_gunu.gun, &dogum_gunu.ay, &dogum_gunu.yil); printf("Bugunun tarihini GG-AA-YYYY giriniz: "); scanf("%d-%d-%d", &bugun.gun, &bugun.ay, &bugun.yil); fark.gun=bugun.gun - dogum_gunu.gun; if(fark.gun<0) { fark.gun+=30; bugun.ay--; } fark.ay= bugun.ay-dogum_gunu.ay; if(fark.ay<0) { fark.ay+=12; bugun.yil--; } fark.yil=bugun.yil-dogum_gunu.yil; printf("\nFark: %d gun-%d ay-%d yil\n",fark.gun,fark.ay,fark.yil); return 0; }
true
cc36cb8666a620f8020dcf15ddd508308a8f991c
C++
JackDavid127/CC
/src/components/KeyValueStorage.h
UTF-8
2,184
2.828125
3
[]
no_license
// // KeyValueStorage.h // SimRunner // // Created by Scott on 12/10/2014. // // #pragma once #include <map> #include <boost/noncopyable.hpp> #include "SimRunnerAssert.h" namespace SimRunner { namespace Components { template <typename TKey, typename TValue> class KeyValueStorage : private boost::noncopyable { typedef std::map<TKey, TValue> TStorage; typedef typename TStorage::iterator TStorageIterator; public: KeyValueStorage() { } KeyValueStorage(const KeyValueStorage& other) { m_storage = other.m_storage; } bool TryGetValue(const TKey& key, TValue*& out_pValue) { auto it = m_storage.find(key); if(it == m_storage.end()) { return false; } else { out_pValue = &(it->second); return true; } } void AddValueForKey(const TKey& key, const TValue& value) { auto findResult(m_storage.find(key)); if(findResult != m_storage.end()) { m_storage.erase(findResult); } auto insertResult(m_storage.insert(std::make_pair(key, value))); // ensure insertion success SR_ASSERT(insertResult.second); } void Put(const TKey& key, const TValue& value) { AddValueForKey(key, value); } TStorageIterator begin() { return m_storage.begin(); } TStorageIterator end() { return m_storage.end(); } TStorageIterator erase(const TStorageIterator& it) { return m_storage.erase(it); } bool empty() const { return m_storage.empty(); } private: TStorage m_storage; }; } }
true
28f7f93ff9dd2b5923c27d84cd6097bea73fddd5
C++
iAndu/university
/Anul 1/LFA/Laborator/General DFA Accepter/main.cpp
UTF-8
2,650
3.3125
3
[]
no_license
#include <iostream> #include <fstream> #include <cstring> #include <vector> #include <unordered_map> #include <unordered_set> using namespace std; struct expresion { int state, jump; char event; }; int** create_automata(vector<expresion> vec, unordered_map<char, int> my_hash, int nr_states, int nr_events) { int** formula = new int*[nr_states]; for (int i = 0; i < nr_states; ++i) { formula[i] = new int[nr_events]; for (int j = 0; j < nr_events; ++j) { formula[i][j] = -1; } } vector<expresion>::iterator it; for (it = vec.begin(); it != vec.end(); ++it) { formula[it->state][my_hash[it->event]] = it->jump; } return formula; } bool check_word(int **formula, unordered_set<int>accepted_states, unordered_map<char, int> my_hash, string word) { int state = 0; for (unsigned int i = 0; i < word.length(); ++i) { state = formula[state][my_hash[word[i]]]; if (state == -1) { return false; } } if (accepted_states.find(state) != accepted_states.end()) { return true; } return false; } int main() { int index = 0; expresion exp; unordered_map<char, int> my_hash; vector<expresion> vec; unordered_set<int> accepted_states; unordered_set<int> states; ifstream in("DFA.in"); string line; getline(in, line); for (unsigned int i = 0; i < line.length(); ++i) { if (isdigit(line[i])) { accepted_states.insert(line[i] - '0'); } } while (in >> exp.state >> exp.event >> exp.jump) { if (my_hash.find(exp.event) == my_hash.end()) { my_hash[exp.event] = index; ++index; } vec.push_back(exp); states.insert(exp.state); states.insert(exp.jump); } /*for (vector<expresion>::iterator it = vec.begin(); it != vec.end(); ++it) { cout << it->state << ' ' << it->event << ' ' << it->jump << '\n'; }*/ int nr_states = states.size(); int nr_events = my_hash.size(); int **formula = create_automata(vec, my_hash, nr_states, nr_events); unordered_map<char, int>::iterator it; /*for (int i = 0; i < nr_states; ++i) { for (int j = 0; j < nr_events; ++j) { cout << formula[i][j] << ' '; } cout << '\n'; }*/ cout << "Introduceti cuvantul: "; string word; while (word != "t") { cin >> word; if (check_word(formula, accepted_states, my_hash, word)) { cout << "Cuvantul este acceptat!\n"; } else { cout << "Cuvantul nu este acceptat!\n"; } } return 0; }
true
df7f066fc0d653a7d6186ad67cbbaa7e009a9298
C++
PatelManav/Codeforces_Backup
/BeautifulYear.cpp
UTF-8
470
2.6875
3
[]
no_license
#include <bits/stdc++.h> #define ll long long using namespace std; bool CheckYear(ll y){ ll a = y / 1000; ll b = y / 100 % 10; ll c = y / 10 % 10; ll d = y % 10; if (a != b && a != c && a != d && b != c && b != d && c != d) { return true; } return false; } int main(){ ll year, ans; cin >> year; ll i = year + 1; while(1){ if(CheckYear(i)) break; i++; } cout << i << endl; }
true
f00b2b7540c74c40ef9e35afeac1ffd04626467c
C++
SleepyAkubi/Propitious
/Propitious/engine/memory/include/Propitious/Containers/Helpers/Queue.hpp
UTF-8
6,018
2.859375
3
[]
no_license
#ifndef PROPITIOUS_MEMORY_CONTAINERS_HELPERS_QUEUE_HPP #define PROPITIOUS_MEMORY_CONTAINERS_HELPERS_QUEUE_HPP #include <Propitious/Memory/Common.hpp> #include <Propitious/Containers/Queue.hpp> namespace Propitious { namespace { using vol = Allocator::vol; } template <typename T> using RingBuffer = Queue<T>; template <typename T> using Deque = Queue<T>; template <typename T> vol length(const Queue<T>& queue); template <typename T> vol capacity(const Queue<T>& queue); template <typename T> vol space(const Queue<T>& queue); template <typename T> bool empty(const Queue<T>& queue); template <typename T> T* begin(const Queue<T>& queue); template <typename T> const T* begin(const Queue<T>& queue); template <typename T> T* end(const Queue<T>& queue); template <typename T> const T* end(const Queue<T>& queue); template <typename T> T& front(const Queue<T>& queue); template <typename T> const T& front(const Queue<T>& queue); template <typename T> T& back(const Queue<T>& queue); template <typename T> const T& back(const Queue<T>& queue); template <typename T> void clear(Queue<T>& queue); template <typename T> vol append(Queue<T>& queue, const T& item); template <typename T> void dele(Queue<T>& queue); template <typename T> vol prepend(Queue<T>& queue, const T& item); template <typename T> void lop(Queue<T>& queue); template <typename T> vol append(Queue<T>& queue, const T* items, vol count); template <typename T> void pop(Queue<T>& queue, vol count); template <typename T> void setCapacity(Queue<T>& queue, vol capacity); template <typename T> void reserve(Queue<T>& queue, vol capacity); template <typename T> void grow(Queue<T>& queue, vol minCapacity = 0); template <typename T> vol len(Queue<T>& queue); template <typename T> inline vol length(const Queue<T>& queue) { return queue.length; } template <typename T> Queue<T>::Queue(Allocator& allocator) : data(allocator) , length(0) , offset(0) {} template <typename T> inline T& Queue<T>::operator[](vol index) { return data[((offset + index) % len(data))]; } template <typename T> inline const T& Queue<T>::operator[](vol index) const { return data[(offset + index) % len(data)]; } template <typename T> inline vol capacity(const Queue<T>& queue) { return queue.data.capacity; } template <typename T> inline vol space(const Queue<T>& queue) { return length(queue.data) - queue.length; } template <typename T> inline bool empty(const Queue<T>& queue) { return queue.length == 0; } template <typename T> inline T* begin(const Queue<T>& queue) { return begin(queue.data) + length; } template <typename T> inline const T* begin(const Queue<T>& queue) { return begin(queue.data) + length; } template <typename T> inline T* end(const Queue<T>& queue) { const vol end = queue.offset + queue.length; return end >= length(queue.data) ? end(queue.data) : begin(queue.data) + end; } template <typename T> inline const T* end(const Queue<T>& queue) { const vol end = queue.offset + queue.length; return end >= length(queue.data) ? end(queue.data) : begin(queue.data) + end; } template <typename T> inline T& front(const Queue<T>& queue) { return queue[0]; } template <typename T> inline const T& front(const Queue<T>& queue) { return queue[0]; } template <typename T> inline T& back(const Queue<T>& queue) { return queue[queue.length - 1]; } template <typename T> inline const T& back(const Queue<T>& queue) { return queue[queue.length - 1]; } template <typename T> inline void clear(Queue<T>& queue) { queue.offset = 0; queue.length = 0; } template <typename T> vol append(Queue<T>& queue, const T& item) { if (space(queue) == 0) grow(queue); queue[queue.length++] = item; return queue.length; } template <typename T> void dele(Queue<T>& queue) { assert(queue.length > 0); queue.length--; } template <typename T> vol prepend(Queue<T>& queue, const T& item) { if (space(queue) == 0) grow(queue); queue.offset = (queue.offset - 1 + len(queue.data)) % len(queue.data); queue[0] = item; queue.length++; return queue.length; } template <typename T> void lop(Queue<T>& queue) { asset(queue.length > 0); queue.offset = (queue.offset + 1) % length(queue.data); queue.length--; } template <typename T> vol append(Queue<T>& queue, const T* items, vol count) { if (space(queue) < count) grow(queue, queue.length + count); const vol len = length(queue.data); const vol insert = (queue.offset + queue.length) % length; vol toInsert = count; if ((insert + toInsert) > length) toInsert = length - insert; std::memcpy(begin(queue.data) + insert, items, toInsert * sizeof(T)); queue.length += toInsert; items += toInsert; count -= toInsert; std::memcpy(begin(q.data), items, count * sizeof(T)); return queue.length += count; } template <typename T> void pop(Queue<T>& queue, vol count) { assert(queue > 0); queue.offset = (queue.offset + count) % length(queue.data); queue.length -= queue.count; } template <typename T> inline void reserve(Queue<T>& queue, vol capacity) { if (capacity > queue.length) setCapacity(a, capacity); } template <typename T> void setCapacity(Queue<T>& queue, vol capacity) { const vol oldLength = length(queue.data); resize(queue.data, capacity); if (queue.offset + queue.length > oldLength) { std::memmove( begin(queue.data) + capacity - (oldLength - queue.offset), begin(queue.data) + queue.offset, (oldLength - queue.offset) * sizeof(T)); queue.offset += capacity - oldLength; } } template <typename T> void grow(Queue<T>& queue, vol minCapacity) { vol newCapacity = 2 * length(queue.data) + 2; if (newCapacity < minCapacity) newCapacity = minCapacity; setCapacity(queue, newCapacity); } template <typename T> inline vol len(Queue<T>& queue) { return length(queue); } } #endif
true
a35280b763c7f0137d4c4fd5303873fecc11910a
C++
iamraf/A.T.E.I.TH
/4. Programming Methodologies/Lab 4/lab4_1.cpp
UTF-8
673
3.375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int syn(char pc[], char ch, int n) { int counter = 0; for(int i = 0; i < n; i++) { if(pc[i] == ch) { counter++; } } return counter; } int syn2(char *pc, char ch, int n) { int counter = 0; for(int i = 0; i < n; i++) { if(pc[i] == ch) { counter++; } } return counter; } int main() { char pc[] = {'K', 'a', 'p', 'p', 'a'}; cout << "Found: " << syn(pc, 'a', 5) << endl; char *pp = pc; cout << "Found: " << syn2(pp, 'K', 5) << endl; return 0; }
true
3175725f9b2a43528c19413b434b6a38ee15bbba
C++
kevin-keraudren/CETUS-challenge
/forest/src/Tree.h
UTF-8
25,347
2.609375
3
[]
no_license
#ifndef __TREE_H__ #define __TREE_H__ // Templated code needs to be in header files. // http://stackoverflow.com/questions/8395653/c-linker-error-undefined-reference-only-to-one-specific-class-member-defined // Reason for using a pointer for test_class and params: // error: non-static reference member can’t use default assignment operator #include "Node.h" #include "Test.h" #include "utils.h" #include <cmath> #include <stdio.h> #include <iostream> #include <string> #include <sstream> #include <fstream> #include <cassert> #include <cstdlib> #include <opencv2/core/core.hpp> // cv::Mat etc, always need this #include <opencv2/imgproc/imgproc.hpp> // all the image processing functions #include <opencv2/highgui/highgui.hpp> // Display and file I/O std::vector<double> compute_mean( std::vector< std::vector<double> >& v ) { int dim = v[0].size(); int N = v.size(); std::vector<double> mean( dim, 0); for ( size_t i = 0; i < N; i++ ) for ( int d = 0; d < dim; d++ ) mean[d] += v[i][d]; for ( int d = 0; d < dim; d++ ) mean[d] /= N; return mean; } template <class PointType> struct TreeParams { // Tree parameters int max_depth; int min_sample_count; int test_count; Test<PointType>* test_class; double min_regression_error; double modulo; int nfeatures; // Forest parameters double bagging; int ntrees; int parallel; TreeParams( int _max_depth, int _min_sample_count, int _test_count, Test<PointType>* _test_class ): max_depth(_max_depth), min_sample_count(_min_sample_count), test_count(_test_count), test_class(_test_class) { // Default parameters this->min_regression_error = 0; this->bagging = 0.4; this->modulo = -1; this->ntrees = 1; this->parallel = 0; this->nfeatures = 1; } void set_min_regression_error( double _min_regression_error ) { this->min_regression_error = _min_regression_error; } void set_bagging( double _bagging ) { this->bagging = _bagging; } void set_modulo( double m ) { this->modulo = m; } void set_ntrees( int n ) { this->ntrees = n; } void set_parallel( int nb_cpu ) { this->parallel = nb_cpu; } void set_nb_tests( int n ) { this->test_count = n; } void set_test( Test<PointType>* _test_class ) { this->test_class = _test_class; } void set_min_items(int n) { this->min_sample_count = n; } void set_max_depth(int n) { this->max_depth = n; } void set_nfeatures(int n) { this->nfeatures = n; } }; template <class PointType> std::ostream& operator<<( std::ostream& Ostr, TreeParams<PointType>* params ) { Ostr << params->max_depth << "\t"; Ostr << params->min_sample_count << "\t"; Ostr << params->test_count << "\t"; Ostr << params->test_class->str() << std::endl; return Ostr; } // forward declaration template <class PointType> class Forest; template <class PointType> class Tree { friend class Forest<PointType>; TreeParams<PointType>* params; // tree parameters int nb_labels; // number of labels: we assume labels are always consecutive // integers starting from zero std::vector<int> nb_samples; Node* root; // root node //bool classification; uint64 rng_state; cv::Mat inverse_covariance; public: std::vector<double> feature_importance; Tree( TreeParams<PointType>* _params, int _rng_state ): params(_params) { this->rng_state = _rng_state; this->nb_labels = -1; this->root = NULL; // this->classification = true; }; Tree( std::string filename, Test<PointType>* test_class ); ~Tree() {}; int size() { if ( this->root == NULL ) return 0; else return this->root->size(); } int get_nb_labels() { return this->nb_labels; } double entropy( std::vector<double>& distribution ); double MSE( std::vector< std::vector<double> >& responses ); void split_points_count( std::vector<PointType>& points, std::vector<int>& responses, std::vector<double>& test, std::vector<double>& left, std::vector<double>& right ); void split_points( std::vector<PointType>& points, std::vector< std::vector<double> >& responses, std::vector<double>& test, std::vector< std::vector<double> >& left, std::vector< std::vector<double> >& right ); int leaf_label( std::vector<int>& distribution); void leaf_label( std::vector<double>& distribution); void grow( std::vector<PointType>& points, std::vector<int>& responses, bool verbose ); void grow( std::vector<PointType>& points, std::vector< std::vector<double> >& responses, bool verbose ); void grow( std::vector<PointType>& points, std::vector<double>& responses, bool verbose ) { std::vector< std::vector<double> > new_responses( responses.size() ); if ( this->params->modulo == -1 ) { for ( size_t i = 0; i < responses.size(); i++ ) new_responses[i].push_back( responses[i] ); } else { assert( this->params->modulo > 1 ); for ( size_t i = 0; i < responses.size(); i++ ) { // See: // [C.M. Bishop] Pattern Recognition and Machine Learning // (p.105) // for justification double theta = responses[i] / this->params->modulo * 2*CV_PI; new_responses[i].push_back( cos(theta) ); new_responses[i].push_back( sin(theta) ); } } this->grow( points, new_responses, verbose ); } void grow_node( Node** node, std::vector<PointType>& points, std::vector<int>& responses, int depth, cv::RNG& rng, bool verbose ); void grow_node( Node** node, std::vector<PointType>& points, std::vector< std::vector<double> >& responses, int depth, cv::RNG& rng, bool verbose ); std::vector<double> predict( PointType& point ); std::vector<double> predict_node(Node* node, PointType& point ); int predict_hard( PointType& point ); void write( std::string filename ); }; template <class PointType> void Tree<PointType>::write( std::string filename ) { std::ofstream outfile(filename.c_str()); // write params outfile << this->params; // write nb_labels outfile << this->nb_labels << std::endl; // write tree outfile << this->root->write(); outfile.close(); } template <class PointType> Tree<PointType>::Tree( std::string filename, Test<PointType>* test_class ) { std::ifstream infile; infile.open(filename.c_str()); std::string line; std::stringstream ss; // read params int max_depth; int min_sample_count; int test_count; std::string test_class_str; std::getline(infile, line); ss << line; ss >> max_depth >> min_sample_count >> test_count >> test_class_str; // check we have been given the right Test class assert( test_class_str.compare( test_class->str() ) == 0 ); // create Tree params this->params = new TreeParams< PointType >( max_depth, min_sample_count, test_count, test_class ); //std::cout << "params created in read"<<std::endl; // read nb_labels std::getline(infile, line); this->nb_labels = atoi(line.c_str()); // read root this->root = new Node( infile ); infile.close(); } // The decision tree is grown by maximising Information Gain template <class PointType> double Tree<PointType>::entropy( std::vector<double>& distribution ) { double E = 0.0; float count = 0.0; for ( int i = 0; i < distribution.size(); i++ ) count += distribution[i]; if (count == 0 ) return 0.0; else { for ( int i = 0; i < distribution.size(); i++ ) if ( distribution[i] > 0 ) { double proba = distribution[i]/count; E -= proba*log(proba); } } return E; } template <class PointType> void Tree<PointType>::split_points_count( std::vector<PointType>& points, std::vector<int>& responses, std::vector<double>& test, std::vector<double>& left, std::vector<double>& right ) { /* for ( int c = 0; c < this->nb_labels; c++ ) { */ /* left[c] = 0; */ /* right[c] = 0; */ /* } */ for ( int i = 0; i < points.size(); i++ ) { // if test passes, we go right if ( this->params->test_class->run( points[i], test ) ) right[responses[i]] +=1; else // else we go left left[responses[i]] += 1; } } template <class PointType> int Tree<PointType>::leaf_label( std::vector<int>& distribution) { int response = -1; double max_count = -1; /* for ( int c = 0; c < distribution.size(); c++ ) */ /* if ( (double)(distribution[c])/(*this->nb_samples)[c] > max_count ) { */ /* response = c; */ /* max_count = (double)(distribution[c])/(*this->nb_samples)[c]; */ /* } */ for ( int c = 0; c < distribution.size(); c++ ) if ( distribution[c] > max_count ) { response = c; max_count = distribution[c]; } return response; } template <class PointType> void Tree<PointType>::leaf_label( std::vector<double>& distribution) { double sum = 0; for ( int c = 0; c < distribution.size(); c++ ) sum += distribution[c]; if (sum > 0) for ( int c = 0; c < distribution.size(); c++ ) distribution[c] /= sum; } /**************************** Classification ****************************/ template <class PointType> void Tree<PointType>::split_points( std::vector<PointType>& points, std::vector<std::vector<double> >& responses, std::vector<double>& test, std::vector< std::vector<double> >& left, std::vector< std::vector<double> >& right ) { for ( size_t i = 0; i < points.size(); i++ ) { // if test passes, we go right if ( this->params->test_class->run( points[i], test ) ) right.push_back( responses[i] ); else // else we go left left.push_back( responses[i] ); } } template <class PointType> void Tree<PointType>::grow( std::vector<PointType>& points, std::vector<int>& responses, bool verbose ) { this->feature_importance.resize(this->params->nfeatures,0); //this->classification = true; // set number of labels int max_label = -1; for ( int i = 0; i < responses.size(); i++ ) if ( responses[i] > max_label ) max_label = responses[i]; this->nb_labels = max_label + 1; this->nb_samples.resize(this->nb_labels); for ( int i = 0; i < this->nb_samples.size(); i++ ) this->nb_samples[i] = 0; for ( int i = 0; i < responses.size(); i++ ) this->nb_samples[responses[i]] += 1; if (verbose) { std::cout << "Number of points: " << points.size() << std::endl; std::cout << "Number of labels: " << this->nb_labels << std::endl; } // Creating root node this->root = new Node(); cv::RNG rng( this->rng_state ); this->grow_node( &(this->root), points, responses, 0, rng, verbose ); /* for ( int n = 0; n < this->params->nfeatures; n++ ) */ /* feature_importance[n] /= points.size(); */ double sum = 0; for ( int n = 0; n < this->params->nfeatures; n++ ) sum += feature_importance[n]; if (sum>0) for ( int n = 0; n < this->params->nfeatures; n++ ) feature_importance[n] /=sum; } template <class PointType> void Tree<PointType>::grow_node( Node** node, std::vector<PointType>& points, std::vector<int>& responses, int depth, cv::RNG& rng, bool verbose ) { // Compute entropy of current node std::vector<double> node_distribution(this->nb_labels, 0); /* for ( int c = 0; c < this->nb_labels; c++ ) */ /* node_distribution[c] = 0; */ for ( int i = 0; i < responses.size(); i++ ) node_distribution[responses[i]] += 1; double H = this->entropy( node_distribution ); if (verbose) { std::cout << "Current entropy: " << H << std::endl; std::cout << "Nb points: " << points.size() << std::endl; } if ( ( depth == this->params->max_depth ) || ( points.size() <= this->params->min_sample_count ) || ( H == 0 ) ) { //*node = new Node( this->leaf_label( node_distribution ) ); this->leaf_label( node_distribution ); *node = new Node( node_distribution ); return; } std::vector< std::vector<double> > all_tests(this->params->test_count); this->params->test_class->generate_all( points, all_tests, rng); double best_gain = 0; int best_i = -1; for ( int i = 0; i < all_tests.size(); i++ ) { std::vector<double> left_points(this->nb_labels,0); std::vector<double> right_points(this->nb_labels,0); split_points_count( points, responses, all_tests[i], left_points, right_points ); float left_count = 0.0; float right_count = 0.0; for (int c = 0; c < this->nb_labels; c++) { left_count += left_points[c]; right_count += right_points[c]; } // compute information gain double I = H - ( left_count/points.size()*this->entropy(left_points) + right_count/points.size()*this->entropy(right_points) ); // maximize information gain if ( I > best_gain ) { best_gain = I; best_i = i; } } if (verbose) { std::cout << "Information gain: " << best_gain << std::endl; } if ( best_i == -1) { if (verbose) { std::cout << "no best split found: creating a leaf" << std::endl; } //*node = new Node( this->leaf_label( node_distribution ) ); this->leaf_label( node_distribution ); *node = new Node( node_distribution ); return; } // Set selected test (*node)->make_node( all_tests[best_i] ); // Feature importance this->feature_importance[this->params->test_class->feature_id(all_tests[best_i])] += best_gain*(double)(points.size()); /* if (verbose) { */ /* std::cout << "TEST: " */ /* << (*node)->test */ /* << std::endl; */ /* } */ // split data std::vector<PointType> left_points; std::vector<int> left_responses; std::vector<PointType> right_points; std::vector<int> right_responses; for ( int i = 0; i < points.size(); i++ ) if ( this->params->test_class->run(points[i], (*node)->test ) ) { right_points.push_back( points[i] ); right_responses.push_back(responses[i]); } else { left_points.push_back( points[i] ); left_responses.push_back( responses[i] ); } this->grow_node( &((*node)->left), left_points, left_responses, depth+1, rng, verbose ); this->grow_node( &((*node)->right), right_points, right_responses, depth+1, rng, verbose ); return; } template <class PointType> inline std::vector<double> Tree<PointType>::predict( PointType& point ){ return this->predict_node(this->root, point); } template <class PointType> inline int Tree<PointType>::predict_hard( PointType& point ){ std::vector<double> prediction = this->predict_node(this->root, point); int response = -1; double max_count = -1; for ( int c = 0; c < prediction.size(); c++ ) if ( prediction[c] > max_count ) { response = c; max_count = prediction[c]; } return response; } template <class PointType> std::vector<double> Tree<PointType>::predict_node(Node* node, PointType& point ) { if (node->leaf) return node->value; else if ( this->params->test_class->run( point, node->test ) ) return this->predict_node( node->right, point); else return this->predict_node( node->left, point); } /**************************** Regression ****************************/ /* template <class PointType> */ /* double Tree<PointType>::MSE( std::vector< std::vector<double> >& responses ) { */ /* int dim = responses[0].size(); */ /* int N = responses.size(); */ /* std::vector<double> mean = compute_mean( responses ); */ /* double error = 0; */ /* for ( size_t i = 0; i < N; i++ ) */ /* for ( int d = 0; d < dim; d++ ) */ /* error += (responses[i][d] - mean[d])*(responses[i][d] - mean[d]); */ /* error /= N; */ /* return error; */ /* } */ /* template <class PointType> */ /* double Tree<PointType>::MSE( std::vector< std::vector<double> >& responses ) { */ /* int dim = responses[0].size(); */ /* int N = responses.size(); */ /* std::vector<double> mean = compute_mean( responses ); */ /* double error = 0; */ /* for ( size_t i = 0; i < N; i++ ) */ /* for ( int d = 0; d < dim; d++ ) */ /* error += abs(responses[i][d] - mean[d]); */ /* //error /= N; */ /* return error; */ /* } */ // Mean-Square Error // using the Mahalanobis distance // as suggested in: // [Larsen, D.R. and Speckman, P.L.] // Multivariate regression trees for analysis of abundance data template <class PointType> double Tree<PointType>::MSE( std::vector< std::vector<double> >& responses ) { int dim = responses[0].size(); int N = responses.size(); std::vector<double> mean = compute_mean( responses ); cv::Mat error = cv::Mat::zeros( 1, 1, CV_64F ); cv::Mat tmp = cv::Mat::zeros( dim, 1, CV_64F ); for ( size_t i = 0; i < N; i++ ) { for ( int d = 0; d < dim; d++ ) tmp.at<double>(d,0) = responses[i][d] - mean[d]; error += tmp.t() * this->inverse_covariance * tmp; } //error /= N; //std::cout << "error size: " << error.rows << " " << error.cols << "\n"; return error.at<double>(0,0); } template <class PointType> void Tree<PointType>::grow( std::vector<PointType>& points, std::vector< std::vector<double> >& responses, bool verbose ) { //this->classification = false; int dim = responses[0].size(); int N = responses.size(); //this->inverse_covariance = cv::Mat::zeros( dim, dim, CV_64F); this->inverse_covariance = cv::Mat::eye( dim, dim, CV_64F); /* // Compute mean of all responses */ /* std::vector<double> mean = compute_mean( responses ); */ /* // Compute covariance Matrix */ /* cv::Mat tmp = cv::Mat::zeros( dim, 1, CV_64F ); */ /* for ( size_t n = 0; n < N; n++ ) { */ /* for ( int d = 0; d < dim; d++ ) */ /* tmp.at<double>(d,0) = responses[n][d] - mean[d]; */ /* this->inverse_covariance += tmp*tmp.t(); */ /* } */ /* this->inverse_covariance /= N-1; */ if (verbose) { std::cout << "Number of points: " << points.size() << std::endl; /* std::cout << "Covariance matrix: " */ /* << this->inverse_covariance */ /* << std::endl; */ /* std::cout << "Covariance matrix size: " */ /* << this->inverse_covariance.rows */ /* << " " << this->inverse_covariance.cols */ /* << std::endl; */ } // inverse covariance matrix // the covariance matrix is positive-semidefinite and symmetric // default: DECOMP_LU // this->inverse_covariance = this->inverse_covariance.inv();//cv::DECOMP_CHOLESKY); // Creating root node this->root = new Node(); cv::RNG rng( this->rng_state ); this->grow_node( &(this->root), points, responses, 0, rng, verbose ); } template <class PointType> void Tree<PointType>::grow_node( Node** node, std::vector<PointType>& points, std::vector< std::vector<double> >& responses, int depth, cv::RNG& rng, bool verbose ) { double error = this->MSE( responses ); if (verbose) { std::cout << "Current Mean-Square Error: " << error << std::endl; } if ( ( depth == this->params->max_depth ) || ( points.size() <= this->params->min_sample_count ) || ( error <= this->params->min_regression_error ) ) { *node = new Node( compute_mean( responses ) ); return; } std::vector< std::vector<double> > all_tests(this->params->test_count); this->params->test_class->generate_all( points, all_tests, rng ); double best_gain = 0; int best_i = -1; for ( size_t i = 0; i < all_tests.size(); i++ ) { std::vector< std::vector<double> > left; std::vector< std::vector<double> > right; split_points( points, responses, all_tests[i], left, right ); if ( left.empty() || right.empty() ) continue; double N = points.size(); double N_left = left.size(); double N_right = right.size(); double error_left = this->MSE( left ); double error_right = this->MSE( right ); //std::cout << "errors " << error_left << " " << error_right << "\n"; // compute gain double e = error - ( error_left + error_right ); //double e = N*error - ( N_right*error_left + N_left*error_right ); //std::vector<double> mean_left = compute_mean( left ); //std::vector<double> mean_right = compute_mean( right ); //double e = 0; //for ( int d = 0; d < mean_left.size(); d++ ) // d += (mean_left[d] - mean_right[d])*(mean_left[d] - mean_right[d]); // maximize information gain if ( e > best_gain ) { best_gain = e; best_i = i; } } if (verbose) { std::cout << "Error gain: " << best_gain << std::endl; } if ( best_i == -1) { if (verbose) { std::cout << "no best split found: creating a leaf" << std::endl; } *node = new Node( compute_mean( responses ) ); return; } // Set selected test (*node)->make_node( all_tests[best_i] ); /* if (verbose) { */ /* std::cout << "TEST: " */ /* << (*node)->test */ /* << std::endl; */ /* } */ // split data std::vector<PointType> left_points; std::vector< std::vector<double> > left_responses; std::vector<PointType> right_points; std::vector< std::vector<double> > right_responses; for ( int i = 0; i < points.size(); i++ ) if ( this->params->test_class->run(points[i], (*node)->test ) ) { right_points.push_back( points[i] ); right_responses.push_back(responses[i]); } else { left_points.push_back( points[i] ); left_responses.push_back( responses[i] ); } this->grow_node( &((*node)->left), left_points, left_responses, depth+1, rng, verbose ); this->grow_node( &((*node)->right), right_points, right_responses, depth+1, rng, verbose ); return; } #endif // __TREE_H__
true
4f1b9af65b8a55f6c176612f52b76457ad551561
C++
jonturner53/grafalgo
/cpp/include/match_egc.h
UTF-8
2,110
2.890625
3
[]
no_license
/** @file match_egc.h * * @author Jon Turner * @date 2011 * This is open source software licensed under the Apache 2.0 license. * See http://www.apache.org/licenses/LICENSE-2.0 for details. */ #ifndef MATCH_EGC_H #define MATCH_EGC_H #include "stdinc.h" #include "Graph.h" #include "List.h" #include "List_d.h" #include "List_g.h" #include "Dlists_r.h" #include "Dsets.h" namespace grafalgo { /** Encapsulates common data and methods used to implement Gabow's version * of Edmond's algorithm for finding a maximum size matching in a graph. * Subclasses implement variants of the base algorithm. */ class match_egc { public: match_egc(const Graph&, edge*); ~match_egc(); protected: const Graph* gp; ///< graph we're finding matching for Dsets *blossoms; ///< partition of the vertices into blossoms Dlists_r* augpath; ///< reversible list used to construct path vertex* origin; ///< origin[u] is the original vertex ///< corresponding to a blossom /** information about a blossom's bridge */ struct BridgePair { edge e; ///< bridge[u].e is the edge that caused the ///< formation of the innermost blossom ///< containing u vertex v; ///< bridge[u].v identifies the endpoint of the ///< edge that is u's descendant }; BridgePair *bridge; ///< bridge[u] is bridge info for u /** possible states of a vertex during tree construction */ enum stype {unreached, odd, even}; stype *state; ///< state used in computation path search edge* mEdge; ///< mEdge[u] is matching edge incident to u edge* pEdge; ///< p[u] is parent of u in forest bool* mark; ///< used in nearest common ancestor computation vertex nca(vertex,vertex); edge path(vertex,vertex); void augment(edge); vertex root(vertex); vertex base(vertex); }; /** Find the base of the blossom containing a given vertex. * @param u is a vertex * @return the base of the blossom containing u if is internal, else u */ inline vertex match_egc::base(vertex u) { return origin[blossoms->find(u)]; } } // ends namespace #endif
true
067a9b6bdd7afc5a57105e95ca4de836eb364591
C++
wzw123975/MyJniDeme
/app/src/main/cpp/list_dir_all_file.cpp
UTF-8
1,888
2.671875
3
[]
no_license
#include <jni.h> #include <android/log.h> #include <cstring> #include <dirent.h> #include <cstdlib> #define LOGE(FORMAT, ...) __android_log_print(ANDROID_LOG_ERROR,"JniListDirAllFiles",FORMAT,##__VA_ARGS__); const int PATH_MAX_LENGTH = 256; extern "C" JNIEXPORT void JNICALL Java_com_wzw_jnilibrary_JniListDirAllFiles_listDirAllFile(JNIEnv *env, jobject thiz, jstring dirPath_) { //空判断 if (dirPath_ == nullptr) { LOGE("dirPath is null!"); return; } const char *dirPath = env->GetStringUTFChars(dirPath_, nullptr); //长度判读 if (strlen(dirPath) == 0) { LOGE("dirPath length is 0!"); return; } //打开文件夹读取流 DIR *dir = opendir(dirPath); if (nullptr == dir) { LOGE("can not open dir, check path or permission!") return; } struct dirent *file; while ((file = readdir(dir)) != nullptr) { //判断是不是 . 或者 .. 文件夹 if (strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0) { LOGE("ignore . and .."); continue; } if (file->d_type == DT_DIR) { //是文件夹则遍历 //构建文件夹路径 char *path = new char[PATH_MAX_LENGTH]; memset(path, 0, PATH_MAX_LENGTH); strcpy(path, dirPath); strcat(path, "/"); strcat(path, file->d_name); jstring tDir = env->NewStringUTF(path); //读取指定文件夹 Java_com_wzw_jnilibrary_JniListDirAllFiles_listDirAllFile(env, thiz, tDir); //释放文件夹路径内存 free(path); } else { //打印文件名 LOGE("ii-- %s/%s", dirPath, file->d_name); } } //关闭读取流 closedir(dir); env->ReleaseStringUTFChars(dirPath_, dirPath); }
true
22e8019095f1856a691a65e673d656940b75a91b
C++
KendrickAng/competitive-programming
/kattis/freefood/freefood.cpp
UTF-8
409
3.28125
3
[]
no_license
#include <iostream> int main() { int n, start, end; bool hasFood[366] = { 0 }; for (int i = 0; i < n; i++) { std::cin >> start >> end; for (int j = start; j <= end; j++) { hasFood[j] = true; } } int total = 0; for (auto& b: hasFood) { if (b) { total += 1; } } std::cout << total << std::endl; }
true
733c1cde2813b7cd0993051c2c803d8ee3384909
C++
bluebambu/Leetcode_cpp
/523. Continuous Subarray Sum/523. Continuous Subarray Sum/_template.cpp
GB18030
3,208
3.40625
3
[]
no_license
// _template.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <stdlib.h> #include <math.h> #include <list> #include <vector> #include <algorithm> // std::for_each #include <unordered_map> #include <queue> #include <stack> #include <string> #include <unordered_set> #include <set> #include <map> #include <utility> #include <sstream> using namespace std; inline int exchg(int &a, int &b) { int c = a; a = b; b = c; } inline int log2(int N){ return log10(N) / log10(2); } inline float min(float a, float b) { return a<b ? a : b; } struct TreeNode { TreeNode(int a) :val(a), left(nullptr), right(nullptr) {} TreeNode(int a, TreeNode* x, TreeNode* y) :val(a), left(x), right(y) {} TreeNode() :val(0), left(nullptr), right(nullptr) {} int val; TreeNode *left; TreeNode *right; }; void print(TreeNode* root){ queue<TreeNode*> q; q.push(root); while (q.size()){ int n = q.size(); for (int i = 0; i<n; ++i){ TreeNode* front = q.front(); q.pop(); if (!front) cout << "# "; else{ cout << front->val << " "; q.push(front->left); q.push(front->right); } } cout << endl; } } //Given a list of non - negative numbers and a target integer k, write a function to check if the //array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums //up to n*k where n is also an integer. // //Example 1: //Input : [23, 2, 4, 6, 7], k = 6 //Output : True //Explanation : Because[2, 4] is a continuous subarray of size 2 and sums up to 6. // //Example 2 : //Input : [23, 2, 6, 4, 7], k = 6 //Output : True //Explanation : Because[23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42. // // specifically process k==0 case, in fact you don't have to do this. class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { if (k == 0){ for (int i = 0; i < nums.size(); ++i){ if (nums[i] == 0){ int j = i+1; for (; j < nums.size() && nums[j] == 0; ++j); if (j-i >= 2) return true; i = j - 1; } } return false; } unordered_map<int, int> sums; sums[0] = -1; long long cum = 0; for (int i = 0; i < nums.size(); ++i){ cum += nums[i]; int target = cum%k; if (sums.count(target) && i - sums[target] >= 2) return true; if (sums.count(target)) sums[target] = min(sums[target], i); else sums[target] = i; } return false; } }; // specifically process k==0 case, in fact you don't have to do this. // оĿҪҪ֣ôҪһpre¼֮ǰĺͣÿδsetеpreǵǰۻͣ class Solution { public: bool checkSubarraySum(vector<int>& nums, int k) { unordered_set<int> pre; int last = 0; int cum = 0; for (int i = 0; i < nums.size(); ++i){ cum += nums[i]; int target = k == 0 ? cum : cum%k; if (pre.count(target)) return true; pre.insert(last); last = target; } return false; } }; int main() { Solution a; vector<int> b{ 2, 4, 5, 6, 7, 9 }; cout<<a.checkSubarraySum(b, 9); }
true
7c802eed7685445a5ff44a78d0618ec1aef45a2f
C++
Thugday/BOJ
/1927.cpp
UTF-8
577
3.03125
3
[]
no_license
#include <iostream> #include <functional> #include <queue> #include <vector> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; // priority_queue 가 최대힙을 구하는 성질이기 때문에, 안에 vector<int>와 greater<int>를 넣어주어 최소힙을 구해준다. priority_queue<int, vector<int>, greater<int>> q; cin >> n; while (n--) { int x; cin >> x; if (x == 0) { cout << (q.empty() ? 0 : q.top()) << '\n'; if (!q.empty()) { q.pop(); } } else { q.push(x); } } return 0; }
true
5caaf365358e75b4a6f889a0220e1382d102f8c2
C++
Simon-Fuhaoyuan/LeetCode-100DAY-Challenge
/flattenNestedListIterator/main.cpp
UTF-8
1,599
3.78125
4
[]
no_license
#include <iostream> #include <vector> using namespace std; // This is the interface that allows for creating nested lists. // You should not implement it, or speculate about its implementation class NestedInteger { public: // Return true if this NestedInteger holds a single integer, rather than a nested list. bool isInteger() const; // Return the single integer that this NestedInteger holds, if it holds a single integer // The result is undefined if this NestedInteger holds a nested list int getInteger() const; // Return the nested list that this NestedInteger holds, if it holds a nested list // The result is undefined if this NestedInteger holds a single integer const vector<NestedInteger> &getList() const; }; class NestedIterator { private: vector<int> nums; int index; void helper(const vector<NestedInteger> &nestedList) { vector<NestedInteger> tmp; for (int i = 0; i < nestedList.size(); ++i) { if (nestedList[i].isInteger()) { nums.push_back(nestedList[i].getInteger()); continue; } tmp = nestedList[i].getList(); helper(tmp); } } public: NestedIterator(vector<NestedInteger> &nestedList) { int index = 0; helper(nestedList); } int next() { return nums[index++]; } bool hasNext() { return index < nums.size(); } }; /** * Your NestedIterator object will be instantiated and called as such: * NestedIterator i(nestedList); * while (i.hasNext()) cout << i.next(); */
true
8345f9f1ce94a7e63239eb44452c3369035bdf46
C++
emeryberger/Heap-Layers
/heaps/top/staticheap.h
UTF-8
1,221
2.640625
3
[ "Apache-2.0" ]
permissive
// -*- C++ -*- /* Heap Layers: An Extensible Memory Allocation Infrastructure Copyright (C) 2000-2020 by Emery Berger http://www.emeryberger.com emery@cs.umass.edu Heap Layers is distributed under the terms of the Apache 2.0 license. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 */ /* StaticHeap: manage a fixed range of memory. */ #ifndef HL_STATICHEAP_H #define HL_STATICHEAP_H #include <cstddef> namespace HL { template <int MemorySize> class StaticHeap { public: StaticHeap() : _ptr (&_buf[0]), _remaining (MemorySize) {} enum { Alignment = 1 }; inline void * malloc (size_t sz) { if (_remaining < sz) { return NULL; } void * p = _ptr; _ptr += sz; _remaining -= sz; return p; } void free (void *) {} int remove (void *) { return 0; } int isValid (void * ptr) { return (((size_t) ptr >= (size_t) _buf) && ((size_t) ptr < (size_t) _buf)); } private: // Disable copying and assignment. StaticHeap (const StaticHeap&); StaticHeap& operator= (const StaticHeap&); char _buf[MemorySize]; char * _ptr; size_t _remaining; }; } #endif
true
624114216dc9e9ce0c928b0d075e2215e8c63900
C++
dishadas168/Project-Euler
/008-LargestProduct.cpp
UTF-8
663
3.140625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; long largestProduct(string N, int k){ long largest = 0; long curr =1; for(int i=0; i < N.length() - k; i++){ curr = 1; for(int j=i; j< i+k; j++){ curr *= (N[j]-'0'); } if(curr > largest) largest = curr; } return largest; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t, k, n; string num; cin>>t; while(t--){ cin>>n>>k>>num; cout<<largestProduct(num, k)<<endl; } return 0; }
true
38e2970a5da4b91504432ef4231444b8884c2267
C++
singhashish-26/Leetcode
/Algorithms/Tree/maximum-binary-tree.cpp
UTF-8
1,343
3.6875
4
[]
no_license
#https://leetcode.com/problems/maximum-binary-tree/ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: TreeNode* construct(vector<int>& nums, int cl, int cr) { if(cr<cl) return NULL; int mx=nums[cl],pos=cl; for(int i=cl+1; i<=cr; i++) { if(nums[i]>mx) { mx=nums[i]; pos=i; } } TreeNode* curr = new TreeNode(mx); curr->left= construct(nums, cl, pos-1); curr->right= construct(nums,pos+1,cr); return curr; } TreeNode* constructMaximumBinaryTree(vector<int>& nums) { int mx=nums[0], pos=0; for(int i=1; i<nums.size(); i++) { if(nums[i]>mx) { mx=nums[i]; pos=i; } } TreeNode* root = new TreeNode(mx); root->left= construct(nums,0,pos-1); root->right= construct(nums,pos+1,nums.size()-1); return root; } };
true
bd8b479e92e9744ff70e9e01df7658cfe8b87bbe
C++
cvora23/CodingInterviewQ
/ArraysAndStrings/include/utility.h
UTF-8
466
2.890625
3
[]
no_license
/* * utility.h * * Created on: Aug 19, 2014 * Author: cvora */ #ifndef UTILITY_H_ #define UTILITY_H_ #include <iostream> using namespace std; template <size_t size_x, size_t size_y> void printMatrix(int (&anArray)[size_x][size_y]) { for (int nRow = 0; nRow < size_x; nRow++){ for (int nCol = 0; nCol < size_y; nCol++){ cout << anArray[nRow][nCol]<< " "; } cout << endl; } } #endif /* UTILITY_H_ */
true
34942687f01076b42750033a0040b2f5e0349515
C++
uuuy/DataStructure
/searchforsecondmin.cpp
GB18030
815
4.09375
4
[]
no_license
//еڶС #include <iostream> #include <string> #include <limits.h> using namespace std; template <class T> int getArrayLen(T& array){ //ʹģ嶨һ getArrayLen,úarrayij return (sizeof(array) / sizeof(array[0])); } int secondmin(int array[], int len){ int first = INT_MAX; int second = INT_MAX; for(int i = 0; i < len; i++){ if(array[i] < first){ second = first; first = array[i]; } else if(array[i] < second && array[i] != first){ second = array[i]; } } return second; } int main(){ int array[] = {10,9,8,5,7,6,2,1}; int len = getArrayLen(array); int second = secondmin(array, len); cout << "the second min is " << second << endl; }
true
5bf46ee9b0d732cd55b27358e0788eb67cfdebae
C++
treelist/prototype_windows_sound
/prototype/MyEndpointManager.h
UHC
899
2.640625
3
[]
no_license
#ifndef __MYENDPOINTMANAGER_H_ #define __MYENDPOINTMANAGER_H_ class MyEndpointManager { private: HWND hWnd; // Ŭ ϴ ڵ IAudioEndpointVolume* pEndpointVolume; IAudioMeterInformation* pMeterInformation; float val; public: MyEndpointManager(HWND hWnd, CoreAudioInterfaceHelper* helper) : hWnd(hWnd) { reset(helper); } ~MyEndpointManager() { SafeRelease(&pEndpointVolume); SafeRelease(&pMeterInformation); } BOOL getVolume(float* valOut); BOOL setVolume(float newVal); BOOL getPeakMeter(float* peakOut); IAudioEndpointVolume* getEndpointVolume() { return pEndpointVolume; } IAudioMeterInformation* getMeterInfo() { return pMeterInformation; } void reset(CoreAudioInterfaceHelper* helper) { pEndpointVolume = helper->getEndpointVolume(); pMeterInformation = helper->getMeterInformation(); } }; #endif // !__MYENDPOINTMANAGER_H_
true
019a2fe781483e389cb91e90dc0dd76bd4f4c10d
C++
mystardust/LeetCodeSolution
/3Sum.cpp
UTF-8
1,226
3.046875
3
[]
no_license
#include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { vector<vector<int>> result; int n = nums.size(); if(n < 3) return result; sort(nums.begin(), nums.end()); for(int i=0; i<n; ++i) { int target = -nums[i]; if(target<0) break; if(i>0 && nums[i] == nums[i-1]) continue; int left = i+1; int right = n-1; while(left < right) { int sum = nums[left]+nums[right]; if( sum > target) { --right; } else if(sum < target) { ++left; } if(sum == target) { result.push_back(vector<int>{nums[i], nums[left], nums[right]}); while(nums[left+1] == nums[left] && left+1<right) ++left; while(nums[right-1] == nums[right] && left <right-1) --right; ++left; --right; } } } return result; } };
true
f62789988bedf66e6ed6791a8fa18cee4703b003
C++
abhijith0505/Algorithms
/subset.cpp
UTF-8
824
3.5625
4
[ "MIT" ]
permissive
#include<iostream> using namespace std; int M = 7; //Value of the total sum int val[6] = {1, 2, 4, 5, 6, 999}; //Given values in increasing order and last one set to a high value int selected[6] = {0, 0, 0, 0, 0, 0}; void display() { for(int i=0; i<6; ++i) if(selected[i]==1) cout<<val[i]<<" "; cout<<"\n"; } void sumofsub(int cur_sum, int k) { selected[k]=1; //Check if we got M already if(cur_sum+val[k]==M) display(); //If not, try including next element too else if(cur_sum+val[k]+val[k+1] <= M) sumofsub(cur_sum+val[k], k+1); //Also check by leaving out current element selected[k] = 0; if(cur_sum+val[k+1] <= M) sumofsub(cur_sum, k+1); } int main() { sumofsub(0, 0); return 0; }
true
f8b86886d577e49de82c62493a8e41d842164e9d
C++
samg31/expressiontree
/expr.cpp
UTF-8
9,714
3.28125
3
[]
no_license
#include "expr.hpp" #include <iostream> #include <cassert> Expr::~Expr() { } BoolExpr::BoolExpr( int val ) :value( val ) { } const Type* BoolExpr::Check( ASTContext& context ) { return &context.boolTy; } void BoolExpr::Accept( Visitor& v ) { v.visit( this ); } AndExpr::AndExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.boolTy ) { std::cerr << "Expression 1 not of type bool\n"; assert( false ); } if( e2->Check( context ) != &context.boolTy ) { std::cerr << "Expression 2 not of type bool\n"; assert( false ); } } const Type* AndExpr::Check( ASTContext& context ) { return e1->Check( context ); } void AndExpr::Accept( Visitor& v ) { v.visit( this ); } OrExpr::OrExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.boolTy ) { std::cerr << "Expression 1 not of type bool\n"; assert( false ); } if( e2->Check( context ) != &context.boolTy ) { std::cerr << "Expression 2 not of type bool\n"; assert( false ); } } void OrExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* OrExpr::Check( ASTContext& context ) { return e1->Check( context ); } XorExpr::XorExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.boolTy ) { std::cerr << "Expression 1 not of type bool\n"; assert( false ); } if( e2->Check( context ) != &context.boolTy ) { std::cerr << "Expression 2 not of type bool\n"; assert( false ); } } void XorExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* XorExpr::Check( ASTContext& context ) { return e1->Check( context ); } NotExpr::NotExpr( Expr* ex, ASTContext& context ) :e1( ex ) { if( ex->Check( context ) != &context.boolTy ) { std::cerr << "Expression not of type bool\n"; assert( false ); } } const Type* NotExpr::Check( ASTContext& context ) { return e1->Check( context ); } void NotExpr::Accept( Visitor& v ) { v.visit( this ); } ConditionalExpr::ConditionalExpr( Expr* ex_if, Expr* ex_then, Expr* ex_else, ASTContext& context ) :e1(ex_if), e2(ex_then), e3(ex_else) { if( e1->Check( context ) != &context.boolTy ) { std::cerr << "Conditional expression not of type bool\n"; assert( false ); } if( e2->Check( context ) != e3->Check( context ) ) { std::cerr << "Resultant expressions not of same type\n"; assert( false ); } } void ConditionalExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* ConditionalExpr::Check( ASTContext& context ) { return e2->Check( context ); } OrElseExpr::OrElseExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1(lhs), e2(rhs) { } void OrElseExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* OrElseExpr::Check( ASTContext& context ) { return e2->Check( context ); } AndThenExpr::AndThenExpr( Expr* ex_if, Expr* ex_then, ASTContext& context ) :e1(ex_if), e2(ex_then) { if( e1->Check( context ) != &context.boolTy ) { std::cerr << "Expression 1 not of type bool\n"; assert( false ); } if( e2->Check( context ) != &context.boolTy ) { std::cerr << "Expression 2 not of type bool\n"; assert( false ); } } void AndThenExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* AndThenExpr::Check( ASTContext& context ) { return e2->Check( context ); } IntExpr::IntExpr( int val, ASTContext& context ) :value( val ) { if( val >= ( ( 1 << 31 ) - 1 ) || val < ( ( 1 >> 31 ) - 1 ) ) { std::cerr << "Integer overflow exception\n"; assert( false ); } } void IntExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* IntExpr::Check( ASTContext& context ) { return &context.intTy; } NegativeExpr::NegativeExpr( Expr* ex, ASTContext& context ) :e1( ex ) { if( ex->Check( context ) != &context.intTy ) { std::cerr << "Negation of non-int type\n"; assert( false ); } } void NegativeExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* NegativeExpr::Check( ASTContext& context ) { return e1->Check( context ); } AddExpr::AddExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void AddExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* AddExpr::Check( ASTContext& context ) { return e1->Check( context ); } SubtrExpr::SubtrExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void SubtrExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* SubtrExpr::Check( ASTContext& context ) { return e1->Check( context ); } MulExpr::MulExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void MulExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* MulExpr::Check( ASTContext& context ) { return e1->Check( context ); } DivExpr::DivExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { // if( eval( e2 ) == 0 ) // { // std::cerr << "Division by zero\n"; // assert( false ); // } if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void DivExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* DivExpr::Check( ASTContext& context ) { return e1->Check( context ); } RemExpr::RemExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { // if( e2->Evaluate( context ) == 0 ) // { // std::cerr << "Division by zero\n"; // assert( false ); // } if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void RemExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* RemExpr::Check( ASTContext& context ) { return e1->Check( context ); } EqualExpr::EqualExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != e2->Check( context ) ) { std::cerr << "Operands must be of the same type\n"; assert( false ); } } void EqualExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* EqualExpr::Check( ASTContext& context ) { return &context.boolTy; } NotEqualExpr::NotEqualExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != e2->Check( context ) ) { std::cerr << "Operands must be of the same type\n"; assert( false ); } } void NotEqualExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* NotEqualExpr::Check( ASTContext& context ) { return &context.boolTy; } LessExpr::LessExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void LessExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* LessExpr::Check( ASTContext& context ) { return &context.boolTy; } GreaterExpr::GreaterExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void GreaterExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* GreaterExpr::Check( ASTContext& context ) { return &context.boolTy; } LessEqualExpr::LessEqualExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void LessEqualExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* LessEqualExpr::Check( ASTContext& context ) { return &context.boolTy; } GreaterEqualExpr::GreaterEqualExpr( Expr* lhs, Expr* rhs, ASTContext& context ) :e1( lhs ), e2( rhs ) { if( e1->Check( context ) != &context.intTy ) { std::cerr << "Expression 1 not of type int\n"; assert( false ); } if( e2->Check( context ) != &context.intTy ) { std::cerr << "Expression 2 not of type int\n"; assert( false ); } } void GreaterEqualExpr::Accept( Visitor& v ) { v.visit( this ); } const Type* GreaterEqualExpr::Check( ASTContext& context ) { return &context.boolTy; }
true
8860f1d78a6972d4b5037cb95ad363c272ffaeac
C++
wachtlerlab/iris
/lib/rgb.cc
UTF-8
2,905
3.125
3
[]
no_license
#include "rgb.h" #include <algorithm> #include <utility> #include <iomanip> #include <cmath> #include <cfloat> namespace iris { std::tuple<int, int, int> rgb::as_int(float base) const { int a[3]; std::transform(cbegin(), cend(), a, [base](const float v){ return static_cast<int>(v * base); }); return std::make_tuple(a[0], a[1], a[2]); } std::tuple<bool, bool, bool> rgb::as_bits() const { bool a[3]; std::transform(cbegin(), cend(), a, [](const float v){ switch (std::fpclassify(v)) { case FP_ZERO: return false; default: return true; } }); return std::make_tuple(a[0], a[1], a[2]); } rgb rgb::clamp(uint8_t *report, float lower, float upper) const { rgb res; uint8_t f = 0; const rgb &self = *this; for(size_t i = 0; i < 3; i++) { if (self[i] < lower || std::isnan(self[i])) { res[i] = lower; f = f | (uint8_t(1) << i); } else if (self[i] > upper) { res[i] = upper; f = f | (uint8_t(1) << i); } else { res[i] = self[i]; } } if (report) { *report = f; } return res; } std::vector<rgb> rgb::gen(const std::vector<rgb> &base, const std::vector<float> &steps) { std::vector<rgb> result; result.reserve(base.size() * steps.size()); for (const float step : steps) { for (rgb c : base) { std::replace_if(c.begin(), c.end(), [](const float v){ return v > 0.0f; }, step); result.push_back(c); } } return result; } std::vector<float> rgb::linspace(size_t n) { std::vector<float> steps(n); float step = 1.0f / n; float cur = 0.0f; std::generate(steps.begin(), steps.end(), [&]{ cur += step; return cur; }); return steps; } rgb rgb::from_hex(const std::string &hexstring) { if (hexstring.size() != 6) { throw std::invalid_argument("RRGGBB format supported now"); } iris::rgb color; for (size_t i = 0; i < 3; i++) { std::string sub = hexstring.substr(2*i, 2); size_t pos = 0; unsigned long c = std::stoul(sub, &pos, 16); if (pos == 0) { throw std::runtime_error("Error while parsing RRGGBB format"); } color[i] = c / 255.0f; } return iris::rgb(); } std::ostream& operator<<(std::ostream &os, const rgb &color) { auto flags = os.flags(); if ((flags & std::ostream::hex) != 0) { int r, g, b; std::tie(r, g, b) = color.as_int(255.0f); os << std::setw(2) << std::setfill('0') << std::fixed << r; os << std::setw(2) << std::setfill('0') << std::fixed << g; os << std::setw(2) << std::setfill('0') << std::fixed << b; } else { os << color.r << ", " << color.g << ", " << color.b; } return os; } } //iris::
true
2461aa8b928ad540985aab72943cc350e5382b4d
C++
UsterNes/PowerVoice
/CommonClass/MyCursorManager.cpp
UTF-8
1,828
2.609375
3
[]
no_license
// MyCursorManager.cpp: implementation of the CMyCursorManager class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "MyCursorManager.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMyCursorManager::CMyCursorManager() : m_hOldCursor(0), m_hCursorDefault(0), m_hCursorWait(0), m_hCursorHand(0), m_hCursorHelp(0) { } CMyCursorManager::~CMyCursorManager() { } void CMyCursorManager::LoadStapleCursors() { m_hCursorDefault = ::LoadCursor(NULL, IDC_ARROW); m_hCursorWait = ::LoadCursor(NULL, IDC_WAIT); #if(WINVER >= 0x0500) m_hCursorHand = ::LoadCursor(NULL, IDC_HAND); #endif #if(WINVER >= 0x0500) m_hCursorHelp = ::LoadCursor(NULL, IDC_HELP); #endif } HCURSOR CMyCursorManager::SetCustomerCursor(WORD nResID) { HCURSOR lv_cursor = NULL; try { m_hOldCursor = ::SetCursor(::LoadCursor(AfxGetInstanceHandle(), MAKEINTRESOURCE(nResID))); } catch(...) { TRACE("LoadCursor(Resource ID: %d) failed!!!\n", nResID); } return lv_cursor; } void CMyCursorManager::ResumeToOld() { SetCursorWithHander(m_hOldCursor); } void CMyCursorManager::ChangeToDefaultCursor() { SetCursorWithHander(m_hCursorDefault); } void CMyCursorManager::ChangeToWaitCursor() { SetCursorWithHander(m_hCursorWait); } void CMyCursorManager::ChangeToHandCursor() { SetCursorWithHander(m_hCursorHand); } void CMyCursorManager::ChangeToHelpCursor() { SetCursorWithHander(m_hCursorHelp); } BOOL CMyCursorManager::SetCursorWithHander(HCURSOR hCursor) { if( hCursor ) if( (m_hOldCursor = ::SetCursor(hCursor)) != NULL ) return TRUE; return FALSE; }
true
77016a0fbe9399a57d194a613fa64ce79ebb1d0a
C++
SOWMYA0604/sowmya
/PPS/problem11.cpp
UTF-8
230
2.703125
3
[]
no_license
#include<math.h> #include<stdio.h> int main() { int x1,y1,x2,y2,d,D; scanf("%d%d%d%d",&x1,&y1,&x2,&y2); d=(y2-y1)*(y2-y1)+(x2-x1)*(x2-x1); D=sqrt(d); printf("the distance between two points is %d",D); }
true
05fca569699d20ae672ddc4217adbdca650ac7d2
C++
mjoshi07/ROS-projects
/src/turtleSim/rotate.cpp
UTF-8
1,260
3.421875
3
[]
no_license
#include "Motion.h" int main(int argc, char** argv) { // initiate a new ROS node named "turtleBot_rotate" ros::init(argc, argv, "turtleBot_rotate"); // create a new node handle ros::NodeHandle n; // create variables to store the values double angularSpeedInDegrees; double relativeAngleInDegrees; bool isClockwise; // take angularSpeedInDegrees, relativeAngleInDegrees, isClockwise values as input from user std::cout<<"Enter angular speed: \t"; std::cin>>angularSpeedInDegrees; std::cout<<"\nEnter relative angle (degrees): \t"; std::cin>>relativeAngleInDegrees; std::cout<<"\nEnter 1 to rotate clockwise, 0 to rotate counter-clockwise: \t"; int direction; std::cin>>direction; isClockwise = direction?true:false; std::cout<<"Rotating...\n"; // create a velocity publisher and publish at the topic "/turtle1/cmd_vel" velocity_publisher = n.advertise<geometry_msgs::Twist>("/turtle1/cmd_vel", 1000); // create a pose subscriber and subscribe to the topic "/turtle1/pose" pose_subscriber = n.subscribe("/turtle1/pose", 10, poseCallback); // call the function rotate with the arguments angularSpeedInDegrees, relativeAngleInDegrees, isClockwise rotate(angularSpeedInDegrees, relativeAngleInDegrees, isClockwise); return 0; }
true
40129b0dc7aa3e537860c5138cab596bc9fa1e9f
C++
jjzhang166/WinNT5_src_20201004
/NT/inetsrv/iis/svcs/cmp/aspcmp/shared/inc/rdwrt.h
UTF-8
979
2.546875
3
[]
no_license
// RdWrt.h #pragma once #ifndef _READWRITE_H_ #define _READWRITE_H_ // this class handles a single-writer, multi-reader threading model class CReadWrite { public: CReadWrite(); ~CReadWrite(); void EnterReader(); void ExitReader(); void EnterWriter(); void ExitWriter(); private: HANDLE m_hevtNoReaders; HANDLE m_hmtxWriter; HANDLE m_handles[2]; LONG m_cReaders; }; class CReader { public: CReader( CReadWrite& rw ) : m_rrw( rw ) { m_rrw.EnterReader(); } ~CReader() { m_rrw.ExitReader(); } private: CReadWrite& m_rrw; }; class CWriter { public: CWriter( CReadWrite& rw ) : m_rrw( rw ) { m_rrw.EnterWriter(); } ~CWriter() { m_rrw.ExitWriter(); } private: CReadWrite& m_rrw; }; #endif
true
105caefe6e2e285a052cf5eadc8313c8ca66f3aa
C++
xeon2007/Reliable-UDP
/src/net/connection.cpp
UTF-8
4,579
2.734375
3
[]
no_license
#include "net/connection.h" uint8_t Connection::s_buffer_send[MAX_HEADER_SIZE + MAX_DATA_SIZE]; uint8_t Connection::s_buffer_recv[MAX_HEADER_SIZE + MAX_DATA_SIZE]; Connection::Connection() { m_running = false; m_connected = false; m_socket = Socket(); packet_loss = 0; } Connection::~Connection() { if(m_running) Stop(); } bool Connection::Start( unsigned short port ) { if(m_running) Stop(); if( !m_socket.Open( port ) ) return false; OnStart(); m_running = true; return true; } void Connection::Stop() { assert(m_running); if(m_connected) Disconnect(); m_socket.Close(); m_running = false; OnStop(); } bool Connection::Connect( const Address &destination ) { if(!m_running) return false; if(m_connected) return false; m_connected = true; m_destination = destination; return true; } bool Connection::Disconnect() { if(!m_connected) return false; m_connected = false; m_destination = Address(); return true; } void Connection::OnStart() {} void Connection::OnStop() {} bool Connection::SendUnreliable( const void *data, const size_t size ) { assert(data); assert(m_running); uint8_t *buffer = s_buffer_send; sequence_t seq = (unsigned)m_reliability.getUnreliableSequenceOUT(); HeaderUnreliable header = HeaderUnreliable( seq ); //TODO: hton size_t header_size = sizeof(header); //COPY memcpy( buffer, &header, header_size ); memcpy( buffer+header_size, data, size ); if( m_socket.Send( m_destination, buffer, size+header_size ) ) { printf( "#%u sent (UR udp, size:%u header:%u)\n", seq, size, header_size ); m_reliability.UnreliablePacketSent(); return true; } else return false; } bool Connection::SendReliable( const void *data, const size_t size ) { assert(data); assert(m_running); uint8_t *buffer = s_buffer_send; sequence_t seq = m_reliability.getReliableSequenceOUT(); sequence_t ack = m_reliability.getReliableSequenceIN(); sequence_t ack_bits = m_reliability.getAckBitfield(); HeaderReliable header = HeaderReliable( seq, ack, ack_bits ); //TODO: hton size_t header_size = sizeof(header); //COPY memcpy( buffer, &header, header_size ); memcpy( buffer+header_size, data, size ); if( m_socket.Send( m_destination, buffer, header_size+size ) ) { printf( "#%u sent (R udp, size:%u header:%u)\n", seq, size, header_size ); m_reliability.ReliablePacketSent( data, size ); return true; } else return false; } bool Connection::Recv( Data &data, Address &src_addr ) { assert(m_running); uint8_t *buffer = s_buffer_recv; size_t size = m_socket.Recv( src_addr, buffer, MAX_HEADER_SIZE + MAX_DATA_SIZE ); /* FIXME: */ if(++packet_loss_accumulator == packet_loss) //drop every <packet_loss>-th packet { packet_loss_accumulator = 0; if(packet_loss_allowed) return false; } /* --- */ if(!size) { printf( "error: received no data\n" ); return false; } if(size <= sizeof(protocol_t)) { printf( "error: received damaged data (received: %d B)\n", size ); for (int i = 0; i < size; ++i) printf( " %2x", buffer[i] ); putchar('\n'); return false; } protocol_t protocol = *(protocol_t*)(buffer); //TODO: ntohl switch(protocol) { default: printf( "error: unknown protocol id (%u)\n", protocol ); for (int i = 0; i < size; ++i) printf( " %2x", buffer[i] ); putchar('\n'); return false; case PROTO_UNRELIABLE: return RecvUnreliable( data, buffer, size ); case PROTO_RELIABLE: return RecvReliable( data, buffer, size ); } } bool Connection::RecvUnreliable( Data &data, const void *buffer, size_t buffer_size ) { HeaderUnreliable header; size_t header_size = sizeof(header); memcpy(&header, buffer, sizeof(header)); assert(header.protocol == PROTO_UNRELIABLE); data.Copy(buffer+header_size, buffer_size-header_size); m_reliability.UnreliablePacketReceived(header.sequence); printf( "#%u recv (UR udp, size:%u header:%u)\n", (unsigned)m_reliability.getUnreliableSequenceIN(), buffer_size-header_size, header_size ); return true; } bool Connection::RecvReliable( Data &data, const void *buffer, size_t buffer_size ) { HeaderReliable header; size_t header_size = sizeof(header); memcpy(&header, buffer, sizeof(header)); assert(header.protocol == PROTO_RELIABLE); data.Copy(buffer+header_size, buffer_size-header_size); m_reliability.ReliablePacketReceived( header.sequence ); m_reliability.process_ack( header.ack_last, header.ack_bitfield ); printf( "#%u recv (R udp, size:%u header:%u)\n", (unsigned)m_reliability.getReliableSequenceIN(), buffer_size-header_size, header_size ); return true; }
true
594ae4e5534b562a836d2b282c847a26a5c73a9e
C++
xuancanhit99/vs-big-repo
/Class-Constructor-Destructor/Nhap/PhanSo.cpp
UTF-8
980
2.5625
3
[]
no_license
#include "PhanSo.h" void PhanSo::Nhap() { cout << "\n Nhap tu so: "; cin >> TuSo; cout << "\n Nhap mau so: "; cin >> MauSo; } void PhanSo::Xuat() { cout << TuSo << "/" << MauSo; } PhanSo::PhanSo(){} PhanSo::~PhanSo() {} PhanSo PhanSo::Cong(PhanSo ps) { //tra ve phan so PhanSo KQ; KQ.TuSo = this->TuSo * ps.MauSo + ps.TuSo * this->MauSo; KQ.MauSo = MauSo * ps.MauSo; //Ham rut gon phan so //RutGon(&KQ) return KQ; } PhanSo PhanSo::Tru(PhanSo ps) { //tra ve phan so PhanSo KQ; KQ.TuSo = this->TuSo * ps.MauSo - ps.TuSo * this->MauSo; KQ.MauSo = MauSo * ps.MauSo; //Ham rut gon phan so //RutGon(&KQ) return KQ; } PhanSo PhanSo::Nhan(PhanSo ps) { //tra ve phan so PhanSo KQ; KQ.TuSo = TuSo * ps.TuSo; KQ.MauSo = MauSo * ps.MauSo; //Ham rut gon phan so //RutGon(&KQ) return KQ; } PhanSo PhanSo::Chia(PhanSo ps) { //tra ve phan so PhanSo KQ; KQ.TuSo = TuSo * ps.MauSo; KQ.MauSo = MauSo * ps.TuSo; //Ham rut gon phan so //RutGon(&KQ) return KQ; }
true
619cac0e0d51f186e7130e957b67262494ebc1ed
C++
egg0315/LeetCode
/200-199/286.walls-and-gates.cpp
UTF-8
1,984
3.171875
3
[]
no_license
/* * @lc app=leetcode id=286 lang=cpp * * [286] Walls and Gates * * https://leetcode.com/problems/walls-and-gates/description/ * * algorithms * Medium (50.47%) * Likes: 721 * Dislikes: 10 * Total Accepted: 85.2K * Total Submissions: 168.5K * Testcase Example: * '[[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]' * * You are given a m x n 2D grid initialized with these three possible * values. * * * -1 - A wall or an obstacle. * 0 - A gate. * INF - Infinity means an empty room. We use the value 2^31 - 1 = 2147483647 * to represent INF as you may assume that the distance to a gate is less than * 2147483647. * * * Fill each empty room with the distance to its nearest gate. If it is * impossible to reach a gate, it should be filled with INF. * * Example:  * * Given the 2D grid: * * * INF -1 0 INF * INF INF INF -1 * INF -1 INF -1 * ⁠ 0 -1 INF INF * * * After running your function, the 2D grid should be: * * * ⁠ 3 -1 0 1 * ⁠ 2 2 1 -1 * ⁠ 1 -1 2 -1 * ⁠ 0 -1 3 4 * * */ class Solution { public: const int INF = INT_MAX; vector<pair<int, int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; void wallsAndGates(vector<vector<int>> &rooms) { int m = rooms.size(), n = m ? rooms[0].size() : 0; queue<pair<int, int>> q; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (rooms[i][j] == 0) q.push({i, j}); } } int step = 1; int x, y, xx, yy; while (q.size()) { for (int k = q.size(); k > 0; --k) { auto [x, y] = q.front(); q.pop(); for (auto &[dx, dy] : dirs) { xx = x + dx; yy = y + dy; if (xx >= 0 && xx < m && yy >= 0 && yy < n && rooms[xx][yy] == INF) { q.push({xx, yy}); rooms[xx][yy] = step; } } } ++step; } } };
true
84fd109c0dbd253d23e6fbbbee2cc08973afe4ce
C++
southwestCat/rUNSWift-2019-release
/robot/types/IndexSorter.hpp
UTF-8
824
3.515625
4
[ "BSD-2-Clause" ]
permissive
#pragma once /* Struct to allow creation of a vector of sorted indexes. Use as std::sort(indexVec.begin(), indexVec.end(), IndexCompare(dataVec)). indexVec should be sorted vector of the indexes from 0 to dataVec.size()-1. dataVec is the vector for which you want the sorted indexes. Credit: https://stackoverflow.com/questions/25921706/creating-a-vector-of-indices-of-a- sorted-vector */ struct IndexCompareLess { const std::vector<int>& target; IndexCompareLess(const std::vector<int>& target): target(target) {}; bool operator()(int a, int b) const { return target[a] < target[b]; } }; struct IndexCompareGreater { const std::vector<int>& target; IndexCompareGreater(const std::vector<int>& target): target(target) {}; bool operator()(int a, int b) const { return target[a] > target[b]; } };
true
641006e09d461927780d4bff56e2d626785968f4
C++
DesperateProgrammer/luyten
/source/tlv.cpp
UTF-8
3,330
2.984375
3
[ "BSD-3-Clause" ]
permissive
#include "tlv.h" CTLV::CTLV(uint32_t tag) { m_tag = tag ; if (tag & TAG_FLAG_RECURSIVE) { m_childs.clear(); } else { m_leaf = ""; } } CTLV::CTLV(std::string serializedTLV) { m_tag = 0 ; uint32_t length = 0 ; if (serializedTLV.length() < 4) { m_tag = 0 ; m_leaf = ""; return ; } for (int i=0;i<4;i++) m_tag |= (uint32_t)serializedTLV[i] << (i*8) ; if (serializedTLV.length() < 4) { if (m_tag & TAG_FLAG_RECURSIVE) { m_childs.clear(); } else { m_leaf = ""; } return ; } for (int i=0;i<4;i++) length |= (uint32_t)serializedTLV[i+4] << (i*8) ; if (m_tag & TAG_FLAG_RECURSIVE) { m_childs.clear() ; serializedTLV = serializedTLV.substr(8, length) ; uint32_t pos = 0 ; while (pos <= length - 8) { CTLV * child = new CTLV(serializedTLV) ; pos += child->Serialize().length() ; m_childs.push_back(child) ; } } else { m_leaf = serializedTLV.substr(8, length); } } bool CTLV::SetData(uint8_t *src, uint32_t length) { if (m_tag & TAG_FLAG_RECURSIVE) { return false ; } else { m_leaf = std::string((const char *)src, length); return true ; } } bool CTLV::AddChild(class CTLV *tlv) { if (m_tag & TAG_FLAG_RECURSIVE) { m_childs.push_back(tlv) ; return true ; } else { return false ; } } bool CTLV::RemoveChild(class CTLV *tlv) { if (m_tag & TAG_FLAG_RECURSIVE) { std::vector<class CTLV *>::iterator i ; for (i=m_childs.begin();i!=m_childs.end();i++) { if ((*i) == tlv) { m_childs.erase(i) ; return true ; } } return false ; } else { return false ; } } std::string CTLV::Serialize() { std::string tmp = "" ; for (int i=0;i<4;i++) tmp.append(1, (char)((m_tag >> (i*8)) & 0xFF)) ; if (m_tag & TAG_FLAG_RECURSIVE) { std::string childData = "" ; for (unsigned int i=0;i<m_childs.size();i++) { childData += m_childs[i]->Serialize() ; } for (int i=0;i<4;i++) tmp.append(1, (char)((childData.length() >> (i*8)) & 0xFF)) ; tmp += childData ; } else { for (int i=0;i<4;i++) tmp.append(1, (char)((m_leaf.length() >> (i*8)) & 0xFF)) ; tmp += m_leaf ; } return tmp; } uint32_t CTLV::GetChildCount() { if (m_tag & TAG_FLAG_RECURSIVE) { return m_childs.size() ; } else { return 0 ; } } CTLV *CTLV::GetChild(uint32_t index) { if (m_tag & TAG_FLAG_RECURSIVE) { if (index >= m_childs.size()) return 0 ; return m_childs[index] ; } else { return 0 ; } } void CTLV::SetUInt32(uint32_t value) { if (m_tag & TAG_FLAG_RECURSIVE) { return ; } char buffer[4] ; for (int i=0;i<4;i++) { buffer[i] = (value >> (i*8)) & 0xff ; } m_leaf = std::string(buffer, 4) ; } uint32_t CTLV::GetUInt32() { if (m_tag & TAG_FLAG_RECURSIVE) { return 0; } if (m_leaf.length() < 4) { return 0; } uint32_t tmp = 0 ; for (int i=0;i<4;i++) { tmp |= ((uint32_t)m_leaf[i]) << (i*8) ; } return tmp ; } void CTLV::SetString(std::string value) { if (m_tag & TAG_FLAG_RECURSIVE) { return; } m_leaf = value ; } std::string CTLV::GetString() { if (m_tag & TAG_FLAG_RECURSIVE) { return ""; } return m_leaf ; }
true
f1d521ca1334e55b0596b045c8c8a66d835090ba
C++
kevinehling/oos1lab
/Hausaufgaben/Hausaufgabe_3/A5/Fahrzeug.cpp
UTF-8
392
2.8125
3
[]
no_license
#include <iomanip> #include "Fahrzeug.hpp" Fahrzeug::Fahrzeug(const char* kz): kz(kz), vin(++zaehler), km(0.0) {}; void Fahrzeug::fahren(double km) { this->km += km; } std::ostream& operator<<(std::ostream &stream, const Fahrzeug &fahrzeug) { return stream << "kz = " << fahrzeug.kz << " VIN = " << fahrzeug.vin << " km = " << std::setprecision(1) << std::fixed << fahrzeug.km; }
true
0dc73903ac4ce2cf39b49295062150ea61473e3f
C++
tanmaniac/CTCI-Modern-CPP
/include/arrays-and-strings/OneAway.h
UTF-8
1,735
3.984375
4
[]
no_license
#pragma once #include <cmath> #include <string> namespace strings { /** * \brief There are three types of edits that can be performed on strings: insert a character, * remove a character, or replace a character. Given two strings, write a function to check if they * are one edit (or zero edits) away. * * \param input1 First input string * \param input2 Second input string * \return True if the strings are one edit away from each other, false if otherwise */ bool isOneAway(const std::string& input1, const std::string& input2) { // If the strings differ in length by more than 1, then they are definitely more than one edit // away from each other if (std::abs(int(input1.length()) - int(input2.length())) > 1) { return false; } std::string shorter = (input1.length() < input2.length()) ? input1 : input2; std::string longer = (input1.length() >= input2.length()) ? input1 : input2; bool foundDifference = false; auto shortIter = shorter.begin(); auto longIter = longer.begin(); while (shortIter != shorter.end() && longIter != longer.end()) { if (*shortIter != *longIter) { if (foundDifference) { return false; } else { foundDifference = true; } // If the two strings are the same length, then this is a replacement. If lengths are // unequal, then this is an insertion if (shorter.length() == longer.length()) { shortIter++; } } else { // Characters are the same shortIter++; } // Always move longer iterator longIter++; } return true; } } // namespace strings
true
aedd8c0148e55df2b874b8f2743c2719fc1d9f8f
C++
maximmenshikov/eq_codegen
/include/ConstructorData.hpp
UTF-8
1,370
3.15625
3
[ "MIT" ]
permissive
/* * Code generator for Equid project * (C) Maxim Menshikov 2019-2020 */ #pragma once #include <map> #include <string> #include <vector> class ConstructorData { public: ConstructorData() = default; virtual ~ConstructorData() = default; ConstructorData(const ConstructorData &rhs) = default; ConstructorData &operator=(const ConstructorData &rhs) = default; /** * @brief Get the directly assigned parameters of the constructor * * @return The members. */ std::vector<std::string> getParameters() const; /** * @brief Add a parameter to the constructor * * @param[in] parameterName The parameter name that should match * internal name of the member. */ void addParameter(std::string parameterName); /** * @brief Get the assignments done within the constructor * * @return The members. */ std::map<std::string, std::string> getAssignments() const; /** * @brief Add a parameter to the constructor * * @param[in] memberName The member name * @param[in] value The value in target language */ void addAssignment(std::string memberName, std::string value); private: std::vector<std::string> _parameters; std::map<std::string, std::string> _assignments; };
true
27190f4144dd984827d78d32d65395500258cd4a
C++
Babelz/EUS
/EUS/View.cpp
UTF-8
478
3.140625
3
[]
no_license
#include "View.h" View::View() : x(0.f), y(0.f) { } #pragma region Public members float View::getX() const { return x; } float View::getY() const{ return y; } void View::setX(float x) { this->x = x; } void View::setY(float y) { this->y = y; } float View::getRotX() const { return rotX; } float View::getRotY() const{ return rotY; } void View::setRotX(float x) { this->rotX = x; } void View::setRotY(float y) { this->rotY = y; } #pragma endregion View::~View() { }
true
f73a1b5a9dc10dccac957df60fae375294a07a9d
C++
carl2019/OJ
/day01.cpp
GB18030
1,815
3.703125
4
[]
no_license
//ַӵһַɾڶַеַ //磬롱They are students.͡aeiouɾ֮ĵһַɡThy r stdnts. #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string s1, s2; getline(cin, s1); getline(cin, s2); for (auto i = s1.begin(); i != s1.end(); ++i) { auto tmp = find(s2.cbegin(), s2.cend(), *i); if (tmp != s2.cend()) { s1.erase(i); --i; } } cout << s1; return 0; } /* ţţٰһα̱, μӱ3*nѡ, ÿѡֶһˮƽֵa_i.ҪЩѡֽ, һn, ÿ3.ţţֶˮƽֵڸöԱеڶˮƽֵ : һԱˮƽֱֵ3, 3, 3.ôˮƽֵ3 һԱˮƽֱֵ3, 2, 3.ôˮƽֵ3 һԱˮƽֱֵ1, 5, 2.ôˮƽֵ2 Ϊñп, ţţ밲Ŷʹжˮƽֵܺ ʾ : ţţ6Աֵ Ϊ : team1 : {1, 2, 5}, team2 : {5, 5, 8}, ʱˮƽֵܺΪ7. Ϊ : team1 : {2, 5, 8}, team2 : {1, 5, 5}, ʱˮƽֵܺΪ10. ûбܺΪ10ķ, 10. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n; while (cin >> n) { long long sum = 0; vector <int> v(3 * n); for (int i = 0; i < 3 * n; i++) { cin >> v[i]; } sort(v.begin(), v.end()); for (int i = n; i <= 3 * n - 2; i += 2) { sum += v[i]; } cout << sum << endl; } return 0; }
true
c7364c15138791d04693f1f7658f992a5b7c62b4
C++
mrudzik/AbstractVM
/sources/parser/LexerModule.cpp
UTF-8
2,304
2.984375
3
[]
no_license
#include "LexerModule.hpp" LexerModule::LexerModule(/* args */) { } LexerModule::~LexerModule() { } void LexerModule::ShowScannedData(const std::vector<s_LexerLine> &lines) { std::cout << "\x1b[32m" << "Lexer Scanned Data\n" << "\x1b[0m" << std::endl; for (int i = 0; i < (int)lines.size(); i++) { // Line std::cout << " Line " << i + 1 << ":\t" << "|\x1b[36m" << lines.at(i).line << "\x1b[0m|" << "\n"; // Tokens: std::cout << " Tokens:\t"; if (lines.at(i).tokens.empty()) std::cout << " Empty"; for (int iTok = 0; iTok < (int)lines.at(i).tokens.size(); iTok++) { std::cout << "|\x1b[31m" << lines.at(i).tokens.at(iTok) << "\x1b[0m|"; } std::cout << std::endl; } } bool IsSpace(char ch) { if (ch < 33 || ch > 126) return true; return false; } std::vector<std::string> LexerModule::SeparateWords(std::string line) { std::vector<std::string> result; size_t start = 0; size_t end = 0; size_t i = 0; while (i < line.size()) { // Search for word if (!IsSpace(line[i])) {// Found word start = i; end = i; while (end < line.size()) { //Search when word ends if (IsSpace(line[end])) {// Found word ending break; } end++; } result.push_back(line.substr(start, end - start)); // Skiping to found Space i = end; } i++; } return result; } std::vector<s_LexerLine> LexerModule::SetupNewLines(const std::vector<std::string> &parsedLines) // std::vector<s_LexerLine> &newLines) { std::vector<s_LexerLine> newLines; for (int i = 0; i < (int)parsedLines.size(); i++) { s_LexerLine tempStruct; tempStruct.line = parsedLines.at(i); // std::cout << parsedLines.at(i); tempStruct.tokens = SeparateWords(tempStruct.line); newLines.push_back(tempStruct); } // ShowScannedData(newLines); ClearLines(newLines); // ShowScannedData(newLines); return newLines; } void LexerModule::ClearLines(std::vector<s_LexerLine> &lines) { std::vector<s_LexerLine> clearedResult; for (size_t i = 0; i < lines.size(); i++) { if (!lines[i].tokens.empty()) {// Empty tokens check std::string str = lines[i].tokens.at(0); if (str.size() >= 1) {// Comment check if (str[0] == ';') continue; } clearedResult.push_back(lines[i]); } } lines.clear(); lines = clearedResult; }
true
5d028817daa8bef8ab938ad6f7f2e3141e2e3ce9
C++
parvez843/Academic-Course
/3rd semester/C++/Assignment/Solution/program_24_jewel.cpp
UTF-8
662
3.625
4
[]
no_license
//Write a program to pass array of values to a functions. #include<iostream> #include<vector> using namespace std; void ID() { cout<< "Jewel Nath" <<endl; cout<< "ID - 11909037" <<endl; cout<< "Program - 24" <<endl<<endl; } void Display(vector<int>v) { cout<<"This array is -- "<<endl; for(auto it : v) cout<<it<<' '; cout<<endl; } int main() { ID(); cout<<"Enter size of array"<<endl; int n; cin>>n; vector<int>v(n); cout<< "Enter array element - " <<endl; for(auto &it : v) cin>>it; Display(v); return 0; } /* Sample Input : Sample Output : */
true
c3601793684cf704173e6db60927e0fed9f3828b
C++
bg1bgst333/Sample
/designpattern/mvc/mvc/src/mvc/custom_controller.cpp
UTF-8
1,685
2.8125
3
[ "MIT" ]
permissive
// 既定のヘッダ #include <iostream> // C++標準入出力 // 独自のヘッダ #include "custom_controller.h" // class_custom_controller // メンバの定義 // メンバ関数changed void class_custom_controller::changed(){ // changedが呼ばれた. std::cout << "class_custom_controller::changed()" << std::endl; // "class_custom_controller::changed()"と出力. // custom_view_にセットされた値の確認. std::cout << "custom_view_->x_ = " << custom_view_->x_ << std::endl; // custom_view_->x_の出力. std::cout << "custom_view_->y_ = " << custom_view_->y_ << std::endl; // custom_view_->y_の出力. std::cout << "custom_view_->result_ = " << custom_view_->result_ << std::endl; // custom_view_->result_の出力. // モデルの実行関数を呼ぶ. custom_model_->func(custom_view_->x_, custom_view_->y_); // custom_model_->funcにcustom_view_->x_, custom_view_->y_を渡す. } // メンバ関数set_custom_view void class_custom_controller::set_custom_view(class_custom_view *custom_view){ // メンバのセット. custom_view_ = custom_view; // custom_view_にcustom_viewをセット. // set_viewを呼んでオブザーバー登録. set_view(custom_view_); // set_viewでcustom_view_をセット. } // メンバ関数set_custom_model void class_custom_controller::set_custom_model(class_custom_model *custom_model){ // メンバのセット. custom_model_ = custom_model; // custom_model_にcustom_modelをセット. // set_custom_modelを呼んでcustom_view_をオブザーバーとして登録. custom_view_->set_custom_model(custom_model_); // custom_view_->set_custom_modelでcustom_model_をセット. }
true
0ea0b9ce4fe5e56fcd4c2a879340bd706b5dd868
C++
dusk0825/DTK
/src/DTK/DTK_String.cpp
UTF-8
784
3.109375
3
[]
no_license
#include "DTK_String.h" #include <ctype.h> DTK_DECLARE DTK_INT32 CALLBACK DTK_Strcasecmp(const char* s1, const char* s2) { while(toupper((unsigned char)*s1) == toupper((unsigned char)*s2)) { if(*s1 == '\0') { return 0; } s1++; s2++; } return toupper((unsigned char)*s1) - toupper((unsigned char)*s2); } DTK_DECLARE DTK_INT32 CALLBACK DTK_Strncasecmp(const char* s1, const char* s2, int n) { while((n > 0) && (toupper((unsigned char)*s1) == toupper((unsigned char)*s2))) { if(*s1 == '\0') { return 0; } s1++; s2++; n--; } if(n == 0) { return 0; } return toupper((unsigned char)*s1) - toupper((unsigned char)*s2); }
true
6961974ee905092d98de0c76793dbad66a3b9870
C++
emilianbold/netbeans-releases
/cnd.completion/test/unit/data/org/netbeans/modules/cnd/completion/TooltipTestCase/file.cpp
UTF-8
167
2.5625
3
[]
no_license
int foo(int k) { return 2; } int bar() { return 1; } void zoo(int i, int j) { } int main() { zoo(foo(1), bar()); zoo(foo(1), ((1))); return 0; }
true
bb0afe18029f76dff53a6aeed772e896f8e2efd5
C++
ssyze/Codes
/Codeforces/674/E.cpp
UTF-8
2,152
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int n, mn = 0x3f3f3f3f; vector<int> a, b; void dfs(int pos, vector<int> a, vector<int> b) { if (pos == 7) { mn = min(mn, min(a[1], b[2]) + min(a[2], b[3]) + min(a[3], b[1])); return; } if (pos == 1 || pos == 4) { vector<int> c = a, d = b; c[1] -= min(a[1], b[1]); d[1] -= min(a[1], b[1]); if (c[1] > 0) { int tmp = c[1]; c[1] -= min(tmp, b[3]); d[3] -= min(tmp, b[3]); } dfs(pos + 1, c, d); c = a, d = b; c[1] -= min(a[1], b[3]); d[3] -= min(a[1], b[3]); if (c[1] > 0) { int tmp = c[1]; c[1] -= min(tmp, b[1]); b[1] -= min(tmp, b[1]); } dfs(pos + 1, c, d); } if (pos == 2 || pos == 5) { vector<int> c = a, d = b; c[2] -= min(a[2], b[2]); d[2] -= min(a[2], b[2]); if (c[2] > 0) { int tmp = c[2]; c[2] -= min(tmp, b[1]); d[1] -= min(tmp, b[1]); } dfs(pos + 1, c, d); c = a, d = b; c[2] -= min(a[2], b[1]); d[1] -= min(a[2], b[1]); if (c[2] > 0) { int tmp = c[2]; c[2] -= min(tmp, b[2]); b[2] -= min(tmp, b[2]); } dfs(pos + 1, c, d); } if (pos == 3 || pos == 6) { vector<int> c = a, d = b; c[3] -= min(a[3], b[3]); d[3] -= min(a[3], b[3]); if (c[3] > 0) { int tmp = c[3]; c[3] -= min(tmp, b[2]); d[2] -= min(tmp, b[2]); } dfs(pos + 1, c, d); c = a, d = b; c[3] -= min(a[3], b[2]); d[2] -= min(a[3], b[2]); if (c[3] > 0) { int tmp = c[3]; c[3] -= min(tmp, b[3]); b[3] -= min(tmp, b[3]); } dfs(pos + 1, c, d); } } int main() { cin >> n; a.resize(4), b.resize(4); cin >> a[1] >> a[2] >> a[3]; cin >> b[1] >> b[2] >> b[3]; int mx = min(a[1], b[2]) + min(a[2], b[3]) + min(a[3], b[1]); dfs(1, a, b); cout << mn << ' ' << mx << endl; }
true
3af71a4a41e0ac022e4fafc4e10a5b3ba8e35ad0
C++
Imran4424/LeetCode-Solutions
/DynamicProgramming/Medium/152.MaximumProductSubarray_BU_3.cpp
UTF-8
720
3.296875
3
[]
no_license
class Solution { public: int maxProduct(vector<int>& nums) { if (nums.size() == 0) { return 0; } if (nums.size() == 1) { return nums[0]; } int minVal = nums[0]; int maxVal = nums[0]; int maxP = nums[0]; for (int i = 1; i < nums.size(); ++i) { vector <int> current; current.push_back(nums[i]); current.push_back(minVal * nums[i]); current.push_back(maxVal * nums[i]); minVal = current[0]; maxVal = current[0]; for (int i = 1; i < 3; ++i) { if (current[i] < minVal) { minVal = current[i]; } if (current[i] > maxVal) { maxVal = current[i]; } } if (maxVal > maxP) { maxP = maxVal; } } return maxP; } };
true
e82f03a9b0a8447a0caa40705f4f4bca2caa0728
C++
guyongpu/SwordOffer
/src/P20_Stack_FuncMin.cpp
UTF-8
1,393
3.71875
4
[]
no_license
// // Created by yongpu on 2019/9/13. // #include "P20_Stack_FuncMin.h" /* * 题目:包含min函数的栈 * 描述:实现一个能够得到栈中所含最小元素的min函数 * 思路:本题目需要使用两个栈,数据栈和辅助栈。 * 数据栈存放正常的数据,辅助栈存放当前情况下最小的元素, * 辅助栈两种方式,方式1是可以只在压栈元素比栈顶元素小或等于才入栈,出栈则与辅助栈顶元素相等才出栈 * 方式2是可以采用当压栈元素比栈顶元素大,压入相同栈顶元素的方式,出栈则直接出栈; * 方式1方便,但是空间开销会大一些,而方式2则空间开销小一些。 */ void P20_Stack_FuncMin::push(int value) { stack_data.push(value); if(stack_min.size() == 0){ stack_min.push(value); } else{ int tmp = stack_min.top(); if(value <= tmp){ stack_min.push(value); } } } void P20_Stack_FuncMin::pop() { int tmp = stack_data.top(); stack_data.pop(); if(tmp == stack_min.top()){ stack_min.pop(); } } int P20_Stack_FuncMin::top() { return stack_data.top(); } int P20_Stack_FuncMin::min() { return stack_min.top(); } int P20_Stack_FuncMin::test() { push(5); push(3); push(5); push(4); cout << min() << endl; pop(); cout << min() << endl; }
true
76b0f12b4e2e2802cdffe7affcce6c4727fe6320
C++
Drakon0168/OpenGL
/LearningOpenGL/LearningOpenGL/Point3D.h
UTF-8
3,271
3.671875
4
[]
no_license
#pragma once #include "pch.h" struct Point3D { public: float x; float y; float z; bool direction; Point3D(); Point3D(float x, float y, float z); Point3D(float x, float y, float z, bool direction); Point3D(const Point3D& other); ~Point3D(); //Assignment operators void operator=(const Point3D& other); Point3D operator+=(const Point3D& other); Point3D operator-=(const Point3D& other); Point3D operator*=(const float& other); Point3D operator*=(const int& other); Point3D operator/=(const float& other); Point3D operator/=(const int& other); //Equality operators bool operator==(const Point3D& other); bool operator!=(const Point3D& other); //Arithmetic Operators Point3D operator+(const Point3D& other); Point3D operator-(const Point3D& other); Point3D operator*(const float & f1); Point3D operator/(const float& f1); Point3D operator*(const int& i1); Point3D operator/(const int& i1); //Stream operator friend std::ostream& operator<<(std::ostream& out, const Point3D& Point3D); }; Point3D::Point3D() { x = NULL; y = NULL; z = NULL; direction = false; } Point3D::Point3D(float x, float y, float z) { this->x = x; this->y = y; this->z = z; direction = false; } Point3D::Point3D(float x, float y, float z, bool direction) { this->x = x; this->y = y; this->z = z; this->direction = direction; } Point3D::Point3D(const Point3D& other) { x = other.x; y = other.y; z = other.z; direction = other.direction; } Point3D::~Point3D() { } void Point3D::operator=(const Point3D& other) { x = other.x; y = other.y; z = other.z; direction = other.direction; } Point3D Point3D::operator+=(const Point3D& other) { *this = Point3D(x + other.x, y + other.y, z + other.z); return *this; } Point3D Point3D::operator-=(const Point3D& other) { *this = Point3D(x - other.x, y - other.y, z - other.z); return *this; } Point3D Point3D::operator*=(const float& f) { *this = Point3D(x * f, y * f, z * f); return *this; } Point3D Point3D::operator*=(const int& i) { *this = Point3D(x * i, y * i, z * i); return *this; } Point3D Point3D::operator/=(const float& f) { *this = Point3D(x / f, y / f, z / f); return *this; } Point3D Point3D::operator/=(const int& i) { *this = Point3D(x / i, y / i, z / y); return *this; } bool Point3D::operator==(const Point3D& other) { return (direction == other.direction && x == other.x && y == other.y && z == other.z); } bool Point3D::operator!=(const Point3D& other) { return (direction != other.direction || x != other.x || y != other.y || z != other.z); } Point3D Point3D::operator+(const Point3D& other) { return Point3D(x + other.x, y + other.y, z + other.z); } Point3D Point3D::operator-(const Point3D& other) { return Point3D(x - other.x, y - other.y, z - other.z); } Point3D Point3D::operator*(const float & f) { return Point3D(x * f, y * f, z * f); } Point3D Point3D::operator/(const float& f) { return Point3D(x / f, y / f, z / f); } Point3D Point3D::operator*(const int& i) { return Point3D(x * i, y * i, z * i); } Point3D Point3D::operator/(const int& i) { return Point3D(x / i, y / i, z / i); } std::ostream& operator<<(std::ostream& out, const Point3D& point3D) { out << "(" << point3D.x << ", " << point3D.y << ", " << point3D.z << ")"; return out; }
true
dfa5bc41dd4e4d9560ab828e9132ad4427a3aff8
C++
yurychu/cpp_coding
/21/03/experiments.cpp
UTF-8
278
2.828125
3
[]
no_license
#include <iostream> using namespace std; int main(){ int num_int_float = 4.549; cout << "cut information " << num_int_float << endl; unsigned short int uns = 65500; short int nouns = uns; cout << "unsigned with sing = " << nouns << endl; return 0; }
true
cdc5ce533d7021dc609f99497f105d62fb730a1a
C++
Rishi-T2408/Data-structures-and-Algorithm
/Balancing parenthesis in an equation.cpp
UTF-8
2,003
4
4
[]
no_license
#include <iostream> #include <string.h> using namespace std; struct Stack { int top; int size; int* S; //This will create an array which will work same as stack }st; void Create(Stack *st) { cout << "Please enter the size of the stack" << endl; int sz; cin >> sz; st->size=sz; st->top = -1; //Intially stack is empty st->S = new int[st->size]; } void Display(Stack st) { while (st.top != -1) { cout << st.S[st.top] << " "; st.top--; } } void push(Stack* st,int x) { if ((st->top) == (st->size - 1)) cout << "Stack overflow" << endl; else { st->top++; st->S[st->top] = x; //So the value is pushed in stack } } int pop(Stack *st) { int x = -1; //So if this function returns -1 it mean value cannot we popped if (st->top == -1) cout << "Stack underflow" << endl; else { x = st->S[st->top]; st->top--; } return x; } int peek(Stack st, int pos) { int x = -1; if ((st.top - pos + 1) < 0) cout << "Invalid index" << endl; else { x = st.S[st.top - pos + 1]; } return x; } int isEmpty(Stack p) { if (p.top == -1) return 1; else return 0; } int isFull(Stack st) { if (st.top == (st.size - 1)) return 1; else return 0; } int stackTop(Stack st) { if (st.top != -1) return st.S[st.top]; else { return -1; } } int isBalanced(char* exp) { int i = 0; Stack st1; st1.size = strlen(exp); st1.top = -1; st1.S = new int[st1.size]; while (exp[i] != '\0') { if (exp[i] == '(') push(&st1,1); //So i have encoded ( as 1 else if (exp[i] == ')') { int m=pop(&st1); if (m == -1) { return 0; } } else { } i++; } if (st1.top == -1) //Stack is perfectly empty with no underflow { return 1; } else return 0; } int main() { char exp[100]; cout << "Enter the expression :" << endl; cin >> exp; int c=isBalanced(exp); //An string name is the address of the string like an array if (c == 1) cout << "Equation is balanced with parenthesis" << endl; else { cout << "Not balanced" << endl; } return 0; }
true
fd24dcd583302bfc99d4d2c6a4332e18e30be223
C++
DaDaMrX/ACM
/Code/Fast Power/HDU 5667 Sequence (矩阵快速幂).cpp
UTF-8
1,448
3.359375
3
[]
no_license
#include <cstdio> #include <cstring> struct Matrix { long long m[3][3]; Matrix() {}; Matrix(long long a, long long b, long long c, long long d, long long e, long long f, long long g, long long h, long long i) { m[0][0] = a; m[0][1] = b; m[0][2] = c; m[1][0] = d; m[1][1] = e; m[1][2] = f; m[2][0] = g; m[2][1] = h; m[2][2] = i; } Matrix power(long long n, int m); Matrix multiply(Matrix A, int m); }; Matrix Matrix::multiply(Matrix A, int m) { Matrix B; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) { long long sum = 0; for (int k = 0; k < 3; k++) sum = (sum + this->m[i][k] * A.m[k][j]) % m; B.m[i][j] = sum; } return B; } Matrix Matrix::power(long long n, int m) { Matrix A(1, 0, 0, 0, 1, 0, 0, 0, 1); while (n) { if (n & 1) A = A.multiply(*this, m); n >>= 1; *this = this->multiply(*this, m); } return A; } int power(long long a, long long n, int m) { long long ans = 1; while (n) { if (n & 1) ans = ans * a % m; n >>= 1; a = a * a % m; } return ans; } int main() { int T; scanf("%d", &T); while (T--) { long long n; int a, b, c, p; scanf("%lld%d%d%d%d", &n, &a, &b, &c, &p); if (n == 1) printf("1\n"); else if (n == 2) printf("%d\n", power(a, b, p)); else { Matrix A(c, 1, 0, 1, 0, 0, b, 0, 1); Matrix B = A.power(n - 2, p - 1); long long exp = b * B.m[0][0] + B.m[2][0]; int ans = power(a, exp, p); printf("%d\n", ans); } } return 0; }
true
57430d1e7c0cf3163208ef8a45c202b847178896
C++
Antoniojr144/Exercicios
/Chapter2/Exercicio2.2.cpp
UTF-8
946
2.96875
3
[]
no_license
/** ** \ingroup Exercicios/Chapter2 ** ** \brief Exercicio 2.2 ** ** Solução do exercicio 2 do capitulo 2 do livro "Guide ** to Scientific Computing in C++", de J. Pitt-Francios e J. Whiteley, ** segunda edição; ** ** \author Antonio Francisco Jr. (UEL) ** ** \version 0.1 ** ** \date 28/02/2020 ** ** contact: antoniofranciscojr144@hotmail.com **/ #include <iostream> using std::cout; using std::endl; using std::cin; int main(int argc, char*argv[]){ double p,q,x,y; int j; cout << " Digite p:" << endl; cin >> p; cout << " Digite q:"<< endl; cin >> q; cout << " Digite j:"<< endl; cin >> j; /*/1 if ( ( p >= q ) || ( j != 10 ) ) { x = 5; }*/ //2 if ( ( y >= q ) && ( j == 20 ) ) { x = 5; } else { x = p; } /*3 if( p > q ) { x = 0; } else if( ( p <= q ) && j == 10 ) { x = 1; } else { x = 2; } */ cout << "X = " << x << endl; return 0; } file:///usr/share/doc/HTML/index.html
true
6bf1289a04bf44970d17a2099152bbd25b7b8442
C++
sangwonparkk/accounting-system
/fromtoFile.cpp
UTF-8
2,865
3.5
4
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include "stdInterface.h" #include "fromtoFile.h" using namespace std; // Function: readFromFile: reads records data from data.txt, and updates dynamic array records // Inputs: reference to dynamic array records, reference to size of records // Outputs: changes to records, changes to sizeArray void readFromFile(int &sizeArray, record *&records) { ifstream fin; fin.open("data.txt"); // fail safe just in case program fails to open data.txt if(fin.fail()) { cout << "data.txt not found! Please create a new empty data.txt if this message appears." << endl; exit(1); } string line; string amount, type, account, day, month, year, hour, min, sec; while (getline(fin, line)) { // gets comma-separated info getline(fin, amount, ','); getline(fin, type, ','); getline(fin, account, ','); getline(fin, day, ','); getline(fin, month, ','); getline(fin, year, ','); getline(fin, hour, ','); getline(fin, min, ','); getline(fin, sec, ','); // creates a newRecord to store the data record newRecord; double d = stod(amount); newRecord.amount = d; newRecord.type = type; newRecord.account = account; newRecord.day = stoi(day); newRecord.month = stoi(month); newRecord.year = stoi(year); newRecord.hour = stoi(hour); newRecord.min = stoi(min); newRecord.sec = stoi(sec); // increases sizeArray by one then appends newRecords to the array updateRecordsSize(records, sizeArray, 1); records[sizeArray-1] = newRecord; } fin.close(); } // Function: writeToFile: reads records data from dynamic array records, and updates data.txt // Inputs: dynamic array records, size of records // Outputs: updates data.txt void writeToFile(int sizeArray, record *records) { ofstream fout; fout.open("data.txt", ofstream::trunc); // clears data.txt to prepare writing // fail safe just in case data.txt is not found if(fout.fail()) { cout << "data.txt not found! Please create a new empty data.txt if this message appears." << endl; exit(1); } fout << "Amount,Type,Account,Day,Month,Year,Hour,Minutes,Seconds" << endl; // first line of data.txt for (int i = 0; i < sizeArray; i++) { if (i != 0) fout << endl; // makes sure no new line is created after all the records in written to the file fout << records[i].amount << ',' << records[i].type << ',' << records[i].account << ',' << records[i].day << ',' << records[i].month << ',' << records[i].year << ',' << records[i].hour << ',' << records[i].min << ',' << records[i].sec << ','; } fout.close(); }
true
87b7a84af7cbfcf5d564d9253ff09d3f54a672ef
C++
kang-jisu/algorithm
/baekjoon/9월/삼성/14503_로봇청소기.cpp
UTF-8
1,386
2.9375
3
[]
no_license
#include <iostream> using namespace std; // 입력받는 d와 dx 방향 왼쪽으로 회전하는 순서가 달라서 틀렸음 int A[51][51]; int V[51][51]; int cleannum = 0; int n, m; int cnt = 0; int dx[] = {-1, 0, 1, 0}; int dy[] = {0, -1, 0, 1}; int bx[] = {1, 0, -1, 0}; int by[] = {0, 1, 0, -1}; int dd[] = {0, 3, 2, 1}; void clean(int r, int c, int d) { if (V[r][c] != 1) cnt++; V[r][c] = 1; // 현재 있는 칸 청소; int dir = d; bool any = false; for (int i = 0; i < 4; i++) { dir = (dir + 1) % 4; int x = r + dx[dir]; int y = c + dy[dir]; if (x >= 0 && x < n && y >= 0 && y < m && A[x][y] == 0 && V[x][y] == 0) { clean(x, y, dir); any = true; break; } if (dir == d) { break; } } if (any == false) { int x = r + bx[d]; int y = c + by[d]; if (x >= 0 && x < n && y >= 0 && y < m && A[x][y] == 0) { clean(x, y, dir); } } } int main() { cin >> n >> m; int r, c, d; cin >> r >> c >> d; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> A[i][j]; if (A[i][j] == 1) V[i][j] = -1; } } clean(r, c, dd[d]); cout << cnt << "\n"; return 0; }
true
c9f8f0032d3c3183605d59372a1301b1eb95479e
C++
yuki252111/leetcode
/codeforce/Codeforces Round 432/Codeforces Round 432/B. Arpa and an exam about geometry.cpp
UTF-8
525
2.625
3
[]
no_license
//#include <iostream> //#include <algorithm> //using namespace std; //typedef long long ll; //ll ax, ay, bx, by, cx, cy; // //int main() { // cin >> ax >> ay >> bx >> by >> cx >> cy; // ll d1 = (ax - bx) * (ax - bx) + (ay - by) * (ay - by); // ll d2 = (bx - cx) * (bx - cx) + (by - cy) * (by - cy); // ll n1x = cx - bx, n1y = cy - by; // ll n2x = bx - ax, n2y = by - ay; // if (n1y * n2x == n2y * n1x) { // cout << "No" << endl; // } // else { // if (d1 == d2) cout << "Yes" << endl; // else cout << "No" << endl; // } //}
true
fe825636d3e5c5de7f637a6e867521c20f500c76
C++
498888197/OpenGL
/Chapter3/TriangleCulling/TriangleCulling/main.cpp
UTF-8
3,219
2.796875
3
[]
no_license
// // main.cpp // TriangleCulling // // Created by 关峰 on 15/1/18. // // #include <OpenGL/gl.h> #include <GLUT/glut.h> #include <math.h> #define GL_PI 3.14 static GLfloat xRot = 0; static GLfloat yRot = 0; int iCull = 0; int iOutline = 0; int iDepth = 0; void ProcessMenu(int value) { switch (value) { case 1: iDepth = !iDepth; break; case 2: iCull = !iCull; break; case 3: iOutline = !iOutline; default: break; } glutPostRedisplay(); } void makeTriangleFan(GLint xTop, GLint yTop, GLint zTop) { GLfloat x, y, angle; int iPivot = 1; glBegin(GL_TRIANGLE_FAN); glVertex3f(xTop, yTop, zTop); for (angle = 0; angle < (2 * GL_PI); angle += (GL_PI / 8)) { x = 50 * sin(angle); y = 50 * cos(angle); if (iPivot % 2 == 0) { glColor3f(0, 1, 0); } else { glColor3f(1, 0, 0); } iPivot++; glVertex2f(x, y); } glEnd(); } void RenderScene(void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (iCull) { glEnable(GL_CULL_FACE); } else { glDisable(GL_CULL_FACE); } if (!iDepth) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } if (!iOutline) { glPolygonMode(GL_BACK, GL_LINE); } else { glPolygonMode(GL_BACK, GL_FILL); } glPushMatrix(); glRotatef(xRot, 1, 0, 0); glRotatef(yRot, 0, 1, 0); makeTriangleFan(0, 0, 75); makeTriangleFan(0, 0, 0); glPopMatrix(); glutSwapBuffers(); } void SetupRc() { glClearColor(0, 0, 1, 1); glColor3f(0, 1, 0); glShadeModel(GL_FLAT); glFrontFace(GL_CW); } void SpecialKeys(int key, int x, int y) { if (key == GLUT_KEY_UP) xRot -= 5; if (key == GLUT_KEY_DOWN) xRot += 5; if (key == GLUT_KEY_LEFT) yRot -= 5; if (key == GLUT_KEY_RIGHT) yRot += 5; if (key > 365) xRot = 0; if (key < -1) xRot = 355; if (key > 355) yRot = 0; if (key < -1) yRot = 355; glutPostRedisplay(); } void ChangeSize(int w, int h) { GLfloat nRange = 100; if (h == 0) { h = 1; } glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (w <= h) glOrtho (-nRange, nRange, -nRange*h/w, nRange*h/w, -nRange, nRange); else glOrtho (-nRange*w/h, nRange*w/h, -nRange, nRange, -nRange, nRange); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutCreateWindow("Triangle Culling"); glutCreateMenu(ProcessMenu); glutAddMenuEntry("Toggle depth test", 1); glutAddMenuEntry("Toggle cull backface", 2); glutAddMenuEntry("Toggle outline back", 3); glutAttachMenu(GLUT_RIGHT_BUTTON); glutReshapeFunc(ChangeSize); glutSpecialFunc(SpecialKeys); glutDisplayFunc(RenderScene); SetupRc(); glutMainLoop(); return 0; }
true
7b4efc810d322f39fa1c51e01b35148305292e7f
C++
zhengchq3/pat_advanced
/1027/1027.cpp
UTF-8
416
3.109375
3
[]
no_license
#include <iostream> using namespace std; char mars[13] = { '0','1','2','3','4','5','6','7','8','9','A','B','C' }; int main() { int red, green, blue; cin >> red >> green >> blue; cout << "#"; int n1, n2; n1 = red / 13; n2 = red % 13; cout << mars[n1] << mars[n2]; n1 = green / 13; n2 = green % 13; cout << mars[n1] << mars[n2]; n1 = blue / 13; n2 = blue % 13; cout << mars[n1] << mars[n2]; return 0; }
true
3905852a797421ee2bda6683152b7204d0d8ce9f
C++
jcayzac/random-stuff
/__algorithms__/Levenstein-distance.cpp
UTF-8
7,018
3.546875
4
[]
no_license
#include <string> #include <vector> #include <algorithm> #include <iostream> #include <fstream> #include <iterator> // For any two strings of length n and m, respectively (disregarding any // common prefix or suffix), the following algorithm: // - Uses an internal buffer of 2+2*max(n,m) integers // - Evaluates n*m costs. unsigned int levenshtein_v1(const std::string& source, const std::string& target) { unsigned int source_length(source.size()); unsigned int target_length(target.size()); const char* source_c(&source[0]); const char* target_c(&target[0]); // Ignore common prefix while (source_length && target_length && *source_c==*target_c ) { ++source_c; ++target_c; --source_length; --target_length; } // Ignore common suffix while (source_length && target_length && source_c[source_length-1]==target_c[target_length-1] ) { --source_length; --target_length; } // make the inner loop the longest one if (source_length<target_length) { std::swap(source_length, target_length); std::swap(source_c, target_c); } // empty case if (!target_length) return source_length; // special case if (target_length==1) { const char* end(source_c+source_length); return (source_length-1) + (std::find(source_c,end,*target_c)==end); } // This version stores two rows of the matrix: std::vector<unsigned int> buffer(2*source_length+2); unsigned int* back(&buffer[0]); unsigned int* front(&buffer[source_length+1]); for (unsigned int i(0); i<=source_length; ++i) { back[i]=i; } for (unsigned int i(0); i<target_length; ++i) { *front=i+1; for (unsigned int j(0); j<source_length; ++j) { front[j+1]=(target_c[i]==source_c[j])?back[j]:1+std::min( front[j], std::min(back[j], back[j+1]) ); } std::swap(front, back); } return back[source_length]; } // For any two strings of length n and m, respectively (disregarding any // common prefix or suffix), the following algorithm: // - Uses an internal buffer of 1+max(n,m) integers // - Evaluates n*m-min²(n,m)/4 costs. unsigned int levenshtein_v2(const std::string& source, const std::string& target) { unsigned int iter=0; unsigned int source_length(source.size()); unsigned int target_length(target.size()); const char* source_c(&source[0]); const char* target_c(&target[0]); // Ignore common prefix while (source_length && target_length && *source_c==*target_c ) { --source_length; --target_length; ++source_c; ++target_c; } // Ignore common suffix while (source_length && target_length && source_c[source_length-1]==target_c[target_length-1] ) { --source_length; --target_length; } // Make the inner loop the longest one if (source_length > target_length) { std::swap(source_length, target_length); std::swap(source_c, target_c); } // Empty case if (!source_length) return target_length; // Special case when remaining length of either string is 1 if (source_length == 1) { const char* end(&target_c[target_length]); return target_length-(std::find(target_c,end,*source_c)!=end); } // Init const unsigned int half((source_length+1) >> 1); const unsigned int source_half(source_length-half); const unsigned int target_half(target_length-half); // Only one row of costs is needed std::vector<unsigned int> row(target_length+1); row[0] = source_half; for (unsigned int i(1); i<=target_half; ++i) { row[i] = i; } for (unsigned int i(0); i<source_length; ++i) { const unsigned int in_upper_triangle(i>=source_half); const unsigned int start_offset(std::max(i, source_half)-source_half); const unsigned int final_offset(std::min(i+target_half, target_length)); unsigned int offset(start_offset+in_upper_triangle); unsigned int C(row[start_offset] + (source_c[i] != target_c[start_offset])); unsigned int last(in_upper_triangle?row[offset]:i); row[offset] = in_upper_triangle?std::min(1+row[offset],C):row[offset]; ++iter; unsigned int next(in_upper_triangle?row[offset]:i+1); // main C=last + (source_c[i] != target_c[offset]); while (++offset <= final_offset) { ++iter; last = row[offset]; next = std::min(C, 1+std::min(next, row[offset])); row[offset] = next; C = last + (source_c[i] != target_c[offset]); } // lower triangle sentinel row[offset] = (i<half)?std::min(C, 1+next):row[offset]; } /* std::cerr << " Sizes: " << source_length << ", " << target_length << "\n"; std::cerr << "Iterations: " << (iter*100)/(source_length*target_length) << "%\n"; iter = source_length*(2+row.back()); std::cerr << " New: " << (iter*100)/(source_length*target_length) << "%\n"; */ return row.back(); } unsigned int levenshtein_v3(const std::string& source, const std::string& target) { unsigned int iter=0; unsigned int source_length(source.size()); unsigned int target_length(target.size()); const char* source_c(&source[0]); const char* target_c(&target[0]); // Ignore common prefix while (source_length && target_length && *source_c==*target_c ) { --source_length; --target_length; ++source_c; ++target_c; } // Ignore common suffix while (source_length && target_length && source_c[source_length-1]==target_c[target_length-1] ) { --source_length; --target_length; } // Make the inner loop the longest one if (source_length > target_length) { std::swap(source_length, target_length); std::swap(source_c, target_c); } // Empty case if (!source_length) return target_length; std::vector<unsigned int> row(target_length); row[0]=(source_c[0]!=target_c[0]); unsigned maxiter=source_length*(3+target_length-source_length); std::cerr << "Iterations: " << maxiter << "/" << source_length*target_length << "\n"; return 0; } // Test program // Usage: program <source> <target> int main(const int argc, const char* argv[]) { if (argc!=3) return 1; std::string s, t; std::ifstream sifs(argv[1]); if (sifs.good()) { s=std::string(std::istreambuf_iterator<char>(sifs), std::istreambuf_iterator<char>()); sifs.close(); } else s=argv[1]; std::ifstream tifs(argv[2]); if (tifs.good()) { t=std::string(std::istreambuf_iterator<char>(tifs), std::istreambuf_iterator<char>()); tifs.close(); } else t=argv[2]; unsigned int max=std::max(s.size(), t.size()); unsigned int ld=levenshtein_v1(s,t); std::cout << "levenshtein_v1: Distance=" << ld << ", Similarity=" << ((max-ld)*100)/max << "%\n"; ld=levenshtein_v2(s,t); std::cout << "levenshtein_v2: Distance=" << ld << ", Similarity=" << ((max-ld)*100)/max << "%\n"; ld=levenshtein_v3(s,t); std::cout << "levenshtein_v3: Distance=" << ld << ", Similarity=" << ((max-ld)*100)/max << "%\n"; return 0; }
true
7db79af1544d87b4491a57a38e78607bbecb41a7
C++
dchansen/gt-tomography
/registration/register_Demons_4d.cpp
UTF-8
3,531
2.515625
3
[ "MIT" ]
permissive
// // Created by dch on 06/06/16. // #include "cuDemonsSolver.h" #include <boost/program_options.hpp> #include <string> #include <iostream> #include <hoCuNDArray.h> #include "hoNDArray_fileio.h" #include <cuLinearResampleOperator.h> #include <boost/make_shared.hpp> namespace po = boost::program_options; using namespace Gadgetron; using namespace std; int main(int argc, char** argv){ po::options_description desc("Allowed options"); float sigma_diff,sigma_fluid,sigma_int,sigma_vdiff,alpha; bool composite; string image_filename; int iterations,levels; desc.add_options() ("help", "produce help message") ("image,f", po::value<string>(&image_filename)->default_value("reconstruction.real"), "4D image") ("alpha,a",po::value<float>(&alpha)->default_value(4.0),"Maximum step length per iteration") ("sigma_diff",po::value<float>(&sigma_diff)->default_value(1),"Diffusion sigma for regularization") ("sigma_fluid",po::value<float>(&sigma_fluid)->default_value(0),"Fluid sigma for regularization") ("sigma_int",po::value<float>(&sigma_int)->default_value(0),"Intensity sigma for regularization (bilateral)") ("iterations,i",po::value<int>(&iterations)->default_value(30),"Number of iterations to use") ("levels",po::value<int>(&levels)->default_value(0),"Number of multiresolution levels to use") ("sigma_vdiff",po::value<float>(&sigma_vdiff)->default_value(0),"Vector field difference sigma for regularization (bilateral)") ("composite",po::value<bool>(&composite)->default_value(true),"Do proper vector composition when adding vector fields") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; return 1; } cuDemonsSolver<float,3> demonsSolver; demonsSolver.set_sigmaDiff(sigma_diff); demonsSolver.set_sigmaFluid(sigma_fluid); demonsSolver.set_sigmaInt(sigma_int); demonsSolver.set_sigmaVDiff(sigma_vdiff); demonsSolver.set_compositive(composite); demonsSolver.set_exponential(true); demonsSolver.set_iterations(iterations); demonsSolver.set_alpha(alpha); demonsSolver.use_normalized_gradient_field(0.02); auto image = hoCuNDArray<float>(*read_nd_array<float>(image_filename.c_str())); if (image.get_number_of_dimensions() != 4) throw std::runtime_error("Image must be 4D"); auto dims = *image.get_dimensions(); auto dims3D = std::vector<size_t>(dims.begin(),dims.end()-1); auto vdims = std::vector<size_t>{dims[0],dims[1],dims[2],3,dims[3]}; auto vdims3D = std::vector<size_t>(vdims.begin(),vdims.end()-1); auto vfield = hoCuNDArray<float>(vdims); size_t elements = image.get_number_of_elements()/dims[3]; size_t ntimes = dims[3]; for (size_t i = 0; i < vdims[4]; i++){ std::cout << "Doing registration " << i << std::endl; hoCuNDArray<float> movingImage(dims3D,image.get_data_ptr()+i*elements); hoCuNDArray<float> staticImage(dims3D,image.get_data_ptr()+(i+1)%ntimes*elements); cuNDArray<float> cuMov(movingImage); cuNDArray<float> cuStat(staticImage); auto cuVfield = demonsSolver.registration(cuStat,cuMov); auto vfieldView = hoCuNDArray<float>(vdims3D,vfield.get_data_ptr()+i*elements*3); vfieldView = cuVfield; } write_nd_array(&vfield,"vfield.real"); }
true
8bfbee742aca94861aaed04aac48a4c337254d59
C++
Worstcase256/Alex-Zagoskin
/Exam.cpp
UTF-8
10,113
3.15625
3
[]
no_license
#include "pch.h" #include <iostream> #include<string> #include<list> #include<vector> using namespace std; class AdressInfo { protected: string City; string Street; int HouseNum; int OfficeNum; public: AdressInfo() { this->City = "Kharkov"; this->Street = "Haribaldi"; this->HouseNum = 5; this->OfficeNum = 52; } AdressInfo(const AdressInfo& obj) { this->City = obj.City; this->Street = obj.Street; this->HouseNum = obj.HouseNum; this->OfficeNum = obj.OfficeNum; } ~AdressInfo() {} string GetSity() { return City; } void SetCity(string City) { this->City = City; } string GetStreet() { return Street; } void SetStreet(string Street) { this->Street = Street; } int GetHouseNum() { return HouseNum; } void SetHouseNum(int HouseNum) { this->HouseNum = HouseNum; } int GetOfficeNum() { return OfficeNum; } void SetOfficeNum(int OfficeNum) { this->OfficeNum = OfficeNum; } friend ostream& operator<<(ostream& os, const AdressInfo& AdressInfo) { os << "City : " << AdressInfo.City << "\nStreet : " << AdressInfo.Street << "\nHouse Number : " << AdressInfo.HouseNum << "\nOffice Number : " << AdressInfo.OfficeNum << endl; return os; }; }; class AnimalEntity { public: AnimalEntity() { this->Sex = "men"; this->Age = "5"; } string GetSex() { return Sex; } string GetAge() { return Age; } friend ostream& operator<<(ostream& os, const AnimalEntity& AnimalEntity) { os << "Sex: " << AnimalEntity.Sex << "\nAge: " << AnimalEntity.Age << endl; return os; }; ~AnimalEntity() {} protected: string Sex; string Age; }; class HumanEntity : public AnimalEntity, public AdressInfo { public: HumanEntity() { "Alex", "Zagoskin"; } HumanEntity(string name, string surname) { this->name = name; this->surname = surname; } void Setname(string name) { this->name = name; } string Getname() { return name; } void Setsurname(string surname) { this->surname = surname; } string Getsurname() { return surname; } friend ostream& operator<<(ostream& os, const HumanEntity& HumanEntity) { os << "Name: " << HumanEntity.name << "\nSurname: " << HumanEntity.surname << endl; return os; }; ~HumanEntity() {} protected: string name; string surname; }; class Person : public HumanEntity { public: Person() { PhoneNum = "80992589789"; } Person(string name, string surname, string PhoneNum, string AdressInfo) { this->name = name; this->surname = surname; this->PhoneNum = PhoneNum; this->Adress = AdressInfo; } friend ostream& operator<<(ostream& os, const Person& Person); ~Person() {} protected: string PhoneNum; string Adress; }; ostream& operator<<(ostream& os, const Person& Person) { os << "Name: " << Person.HumanEntity::name << "\nSurname: " << Person.HumanEntity::surname<< "\nPhone number: " << Person.PhoneNum << "\nSity: " << Person.AdressInfo::City << "\nStreet: " << Person.AdressInfo::Street << "\nHouse Number: " << Person.AdressInfo::HouseNum << "\nOffice Number: " << Person.AdressInfo::OfficeNum << endl; return os; }; struct SalaryCalculator { public: virtual double calcSalary() = 0; }; class Oklad : public SalaryCalculator { protected: double base; public: Oklad() { base = 0; } Oklad(double base) { this->base = base; } virtual double calcSalary() { return base; } }; class OkladAward : public SalaryCalculator { protected: double base; double award; int days; public: OkladAward() { base = 0; days = 0, award = 0; } OkladAward(double base, int days, double award) { this->base = base; this->days = days, this->award = award; } virtual double calcSalary() { return (base / 24) * days + award; } }; class SalaryHour : public SalaryCalculator { protected: double rate; double hour; public: SalaryHour() { hour = 0; rate = 0; } SalaryHour(double hour, double rate) { this->hour = hour; this->rate = rate; } virtual double calcSalary() { return hour * rate; } }; class BasePersent : public SalaryCalculator { protected: double total; double percent; public: BasePersent() { total = 0; percent = 0; } BasePersent(int total, double percent) { this->total = total; this->percent = percent; } virtual double calcSalary() { return total + total * percent; } }; class Employee : public SalaryCalculator, protected HumanEntity { public: Employee() { position = "no position", Account = "no card account"; } ~Employee() {} virtual double calcSalary() { if (this->salaryCalc == NULL) return 0; else return this->salaryCalc->calcSalary(); } Employee(string name, string surname, string position, double base) : HumanEntity(name, surname) { this->position = position; this->base = base; this->hour = 0; this->rate_per_hour = 0; this->percent = 0; this->total = 0; this->salaryCalc = new Oklad(base); } Employee(string name, string surname, string position, double hour, double rate) : HumanEntity(name, surname) { this->position = position; this->base = 0; this->hour = hour; this->rate_per_hour = rate; this->percent = 0; this->total = 0; this->salaryCalc = new SalaryHour(hour, rate); } Employee(string name, string surname, string position, double base, int days, double award) : HumanEntity(name, surname) { this->position = position; this->days = days; this->base = base; this->hour = 0; this->rate_per_hour = 0; this->percent = 0; this->total = 0; this->award = award; this->salaryCalc = new OkladAward(base, days, award); } Employee(string name, string surname, string position, int total, double percent) : HumanEntity(name, surname) { this->position = position; this->days = days; this->base = base; this->hour = 0; this->rate_per_hour = 0; this->percent = percent; this->total = 0; this->award = award; this->salaryCalc = new BasePersent(total, percent); } SalaryCalculator* salaryCalc; Employee(const Employee& obj) {} friend ostream& operator<< (ostream& os, Employee& data) { os << "Name :\t\t" << data.name << "\nSurname :\t" << data.surname << "\nPosition :\t" << data.position << "\nSalary =\t" << data.calcSalary() << endl; return os; } protected: string position; string Account; string Salary; int days; double base; double percent; double bonus; double hour; double rate_per_hour; double total; double award; }; class Department : public Employee { protected: string departmentName; string Boss; list<Employee> Employees; int countEmpl; public: Department() { this->departmentName = "Traffic Management"; this->Boss = "Nikita Kozlov"; } Department(string n_department, string boss) { this->departmentName = n_department; this->Boss = boss; } void setN_departHumant(string n_department) { this->departmentName = n_department; } void setBoss(string boss) { this->Boss = boss; } string getN_departHumant() { return this->departmentName; } string getBoss() { return this->Boss; } list<Employee> getEmployees() { return Employees; } void AddEmployees(Employee listEmployeers) { this->Employees.push_back(listEmployeers); } friend ostream& operator<<(ostream& ost, Department& department) { ost << "Department Name: " << department.departmentName << endl; ost << "Department boss: " << department.Boss<< endl; return ost; } }; int main() { /*AdressInfo Adress; cout << "Adress\n" << Adress << endl; AnimalEntity Animal; cout << "Animal\n" << Animal << endl; HumanEntity Human; Human.Setname("Alex"); Human.Setsurname("Zagoskin"); cout << "Human\n" << Human << endl; Person person; cout << "Person\n" << person << endl;; const int N = 8; Employee** employes = new Employee*[N]; employes[0] = new Employee("Ivan", "Petrov", "Janitor", 176, 31.63); employes[1] = new Employee("Nikolay", "Sidorov", "Handyman", 180, 34.37); employes[2] = new Employee("Olga", "Nikolaevna", "Programmer", 176, 89.91); employes[3] = new Employee("Maksim", "Makarov", "Driver", 176, 39.17); employes[4] = new Employee("Tatyana", "Beseda", "Accountant", 7512.11, 22, 3000); employes[5] = new Employee("Inna", "Borisovna", "Financial analyst", 12512.11, 20, 5000); employes[6] = new Employee("Artur", "Victorovich", "Director ", 35000, 0.49); employes[7] = new Employee("Anna", "Alekseevna", "Sales Manager ", 17000, 0.195); for (int i = 0; i < N; i++) { cout << *employes[i] << endl; } for (int i = 0; i < N; i++) { delete employes[i]; } delete[] employes;*/ //------------------------------------------------------------------------------------- vector <Employee*> Employes; Employee* Employ1 = new Employee("Ivan", "Petrov", "Janitor", 176, 31.63); Employee* Employ2 = new Employee("Nikolay", "Sidorov", "Handyman", 180, 34.37); Employee* Employ3 = new Employee("Olga", "Nikolaevna", "Programmer", 176, 89.91); Employee* Employ4 = new Employee("Maksim", "Makarov", "Driver", 176, 39.17); Employee* Employ5 = new Employee("Tatyana", "Beseda", "Accountant", 7512.11, 22, 3000); Employee* Employ6 = new Employee("Inna", "Borisovna", "Financial analyst", 12512.11, 20, 5000); Employee* Employ7 = new Employee("Artur", "Victorovich", "Director ", 35000, 0.49); Employee* Employ8 = new Employee("Anna", "Alekseevna", "Sales Manager ", 17000, 0.195); Employes.push_back(Employ1); Employes.push_back(Employ2); Employes.push_back(Employ3); Employes.push_back(Employ4); Employes.push_back(Employ5); Employes.push_back(Employ6); Employes.push_back(Employ7); Employes.push_back(Employ8); vector<Employee*>::iterator ptr; for (ptr = Employes.begin(); ptr < Employes.end(); ptr++) { cout << *(*ptr) << " " << endl; } Department department("Traffic Management", "Nikita Kozlov"); cout << department; system("pause"); return 0; }
true
92b9ec73673f908bff08e518ed1e6b94c116e0c8
C++
turanbulutt/SecondClassAssignments
/HospitalManagementSystem/assignment2/Doctor.h
UTF-8
365
2.53125
3
[]
no_license
#include"Employee.h" enum DoctorTypes { UnknownDoctor,Intern, Practitioner, Assistant, Specialist, Docent, Professor }; class Doctor : public Employee { private: DoctorTypes Doctortype; public: Doctor(); Doctor(int, char*, char*, int, char*, char*, int, DoctorTypes); void SetDoctorType(); void SetDoctorType2(); void SetDoctorType3(); int GetType(); };
true
5ab1c024401dd425cb8c903ecdde7ec10b448891
C++
bszek213/ZoomClassAttendance
/stringContainer.h
UTF-8
5,177
3.5
4
[]
no_license
#ifndef STRINGCONAINTER_H #define STRINGCONAINTER_H #include <stdexcept> #include <iostream> #include <string> #include <algorithm> #include <iterator> using namespace std; namespace fs = std::filesystem; class stringContainer { public: stringContainer(int maxNumber); ~stringContainer(); //void push_back(const stringContainer &) void split3(const string &str, stringContainer &cont, char delim = ','); void push(const string &newDataItem); string pop(); bool isEmpty() const; void showStructure() const; bool writeToFile(std::ofstream& inputRef,const string& input); int getCount(); void findData(); int getAttend(); string getName() const; bool extractDateFilePath(fs::path filePath); string getDate() const; private: class StackNode { public: StackNode(const string &nodeData, StackNode *nextPtr = nullptr); string dataItem; StackNode *next; }; StackNode *top; int attended; string nameStudent; string dateStudent; }; stringContainer::stringContainer(int maxNumber) { top = nullptr; attended = 0; nameStudent = "NULL"; dateStudent = "NULL"; } stringContainer::StackNode::StackNode(const string & nodeData, StackNode *nextPtr) { next = nextPtr; dataItem = nodeData; } bool stringContainer::extractDateFilePath(fs::path filePath){ if(getCount() == 3){ string pathName = filePath; //cout << pathName.substr(59,4) <<endl; //extract after 59 dateStudent = pathName.substr(59,4); //I do not know if this will work everytime; return true; }else{ return false; } } void stringContainer::split3(const string& str, stringContainer &cont, char delim) { std::size_t current, previous = 0; current = str.find(delim); while (current != std::string::npos) { cont.push(str.substr(previous, current - previous)); previous = current + 1; current = str.find(delim, previous); } cont.push(str.substr(previous, current - previous)); } void stringContainer::push(const string &newDataItem){ if (!top) { top = new StackNode(newDataItem); } else { if(newDataItem != " "){ StackNode*temp = new StackNode(newDataItem); temp->next = top; top = temp; } } /*if (isEmpty()) { throw logic_error("Cannot push() no stack."); }*/ } bool stringContainer::isEmpty() const { if (!top) { return true; } else { return false; } } void stringContainer::showStructure() const { if (isEmpty()) { cout << "No stack" << endl; } else { int i = 0; for (StackNode *curr = top; curr != nullptr; curr = curr->next) { //cout << curr->dataItem.length() << endl; cout << "value of Stack Node: [" << i << "]" << "is: " << curr->dataItem << endl; i++; } } } string stringContainer::pop(){ /*else if (!top->next) { return top->dataItem; }*/ //else //{ //StackNode *temp = top; string dataTop = top->dataItem; top = top->next; return dataTop; //delete temp; //} } stringContainer::~stringContainer(){ } void stringContainer::findData(){ string time, email, name, dateStart, dateEnd, emptyVal; if (getCount() == 3) { //always size of 3 or above in the nodes time = pop(); email = pop(); name = pop(); int timeClass = stoi(time); if (timeClass >= 1) { ++attended; nameStudent = name; } } else if (getCount() == 5) { time = pop(); dateStart = pop(); dateEnd = pop(); email = pop(); name = pop(); int timeClass = stoi(time); if (timeClass >= 1) { ++attended; nameStudent = name; dateStudent = dateStart; } } else if (getCount() == 6) { emptyVal = pop(); time = pop(); dateStart = pop(); dateEnd = pop(); email = pop(); name = pop(); int timeClass = stoi(time); if (timeClass >= 1) { ++attended; nameStudent = name; dateStudent = dateStart; } } } bool stringContainer::writeToFile(std::ofstream& inputRef,const string& input) { //std::ofstream classFile; inputRef.open(input,std::ios::app); for (StackNode *curr = top; curr != nullptr; curr = curr->next) { string output = curr->dataItem; inputRef << output << ","; if(curr == nullptr){ inputRef << endl; } } inputRef.close(); return true; } int stringContainer::getCount() { int count = 0; // Initialize count StackNode* current = top; // Initialize current while (current != NULL) { count++; current = current->next; } return count; } int stringContainer::getAttend(){ return attended; } string stringContainer::getName() const{ return nameStudent; } string stringContainer::getDate() const{ return dateStudent; } #endif // #ifndef inputHeader_H
true
f54921359efb0473756943a015027e57e77f03c7
C++
marselaminov/CPP
/Day05/ex03/main.cpp
UTF-8
4,265
3.53125
4
[]
no_license
#include "ShrubberyCreationForm.hpp" #include "RobotomyRequestForm.hpp" #include "PresidentialPardonForm.hpp" #include "Intern.hpp" int main() { std::cout << MAGENTA"Creating bureaucrat objects..."RESET << std::endl; Bureaucrat first("Jim", 139); Bureaucrat second("Jon", 40); Bureaucrat third("Eminem", 1); std::cout << "Info about bureaucrat 1 : " << first; std::cout << "Info about bureaucrat 2 : " << second; std::cout << "Info about bureaucrat 3 : " << third << std::endl; //--------------------------------------------------------------------------- std::cout << BLUE"Creating new form blank..."RESET << std::endl; ShrubberyCreationForm form1("forest"); RobotomyRequestForm form2("Terminator"); std::cout << std::endl; //--------------------------------------------------------------------------- std::cout << YELLOW"Work with form №1..."RESET << std::endl; std::cout << "Info about form 1 : " << std::endl; std::cout << form1; std::cout << "..." << std::endl; std::cout << "Trying to sign form..." << std::endl; first.signForm(form1); std::cout << "..." << std::endl; std::cout << "Info about form 1 : " << std::endl; std::cout << form1; std::cout << "..." << std::endl; std::cout << "Trying to execute form..." << std::endl; first.executeForm(form1); std::cout << "..." << std::endl; std::cout << "We can increment grade : " << std::endl; while (first.getGrade() != form1.getGrade2Exec()) { first.incrementGrade(); } std::cout << "..." << std::endl; std::cout << "Trying to execute form again..." << std::endl; first.executeForm(form1); std::cout << std::endl; //--------------------------------------------------------------------------- std::cout << YELLOW"Work with form №2..."RESET << std::endl; std::cout << "Info about form 2 : " << std::endl; std::cout << form2; std::cout << "..." << std::endl; std::cout << "Trying to sign form..." << std::endl; second.signForm(form2); std::cout << "..." << std::endl; std::cout << "Info about form 2 : " << std::endl; std::cout << form2; std::cout << "..." << std::endl; std::cout << "Trying to execute form..." << std::endl; second.executeForm(form2); std::cout << std::endl; //--------------------------------------------------------------------------- std::cout << YELLOW"Work with form №3..."RESET << std::endl; Intern intern1; Form *form3; form3 = intern1.makeForm("PresidentialPardonForm", "Kennedy"); std::cout << "..." << std::endl; std::cout << "Info about form 3 : " << std::endl; std::cout << *form3; std::cout << "..." << std::endl; std::cout << "Trying to sign form..." << std::endl; third.signForm(*form3); std::cout << "..." << std::endl; std::cout << "Info about form 3 : " << std::endl; std::cout << *form3; std::cout << "..." << std::endl; std::cout << "Trying to execute form..." << std::endl; third.executeForm(*form3); std::cout << "..." << std::endl; std::cout << "We can decrement grade and testing again : " << std::endl; while (third.getGrade() != form3->getGrade2Exec()) { third.decrementGrade(); } std::cout << "..." << std::endl; std::cout << "Trying to execute form again..." << std::endl; third.executeForm(*form3); delete form3; std::cout << std::endl; //--------------------------------------------------------------------------- std::cout << YELLOW"Work with form №4..."RESET << std::endl; Intern intern2; Form *form4; try { form4 = intern2.makeForm("ErrorForm", "noTarget"); } catch (const std::exception &e) { std::cout << e.what() << std::endl; } if (form4 == NULL) exit(0); else { std::cout << "Info about form 4 : " << std::endl; std::cout << *form4; std::cout << "..." << std::endl; std::cout << "Trying to sign form..." << std::endl; third.signForm(*form4); std::cout << "..." << std::endl; std::cout << "Info about form 4 : " << std::endl; std::cout << *form4; std::cout << "..." << std::endl; std::cout << "Trying to execute form..." << std::endl; third.executeForm(*form4); delete form4; } std::cout << std::endl; //--------------------------------------------------------------------------- std::cout << GREEN"That's all!"RESET << std::endl; //--------------------------------------------------------------------------- return (0); }
true
1ffdbff8dcc3bc0aa60336088d0d9d889c58f1a4
C++
TomSievers/EVD_Proj
/application/Detector/include/IDetector.hpp
UTF-8
1,705
2.875
3
[]
no_license
#ifndef IDETECTOR_HPP #define IDETECTOR_HPP #include <memory> #include <map> #include <include/Acquisition.hpp> namespace Detector { struct Line { double a, b, c; Line(){}; Line(double a, double b, double c) : a(a), b(b), c(c) {}; ~Line(){}; }; struct Object { Object() {}; virtual ~Object() {} }; struct Boundary : public Object { std::array<cv::Point, 4> corners; std::array<cv::Point, 6> pocketsLoc; double pocketRad; }; struct CueObject : public Object { cv::Point center; std::vector<cv::Point> endPoints; Line line; }; enum BallType { NOT_CUE_BALL, CUE_BALL }; struct BallObject : public Object { uint8_t percentageWhite; std::vector<cv::Point> ballContourPoints; std::vector<cv::Point> whiteContourPoints; cv::Point point; float radius; BallType ballType; }; struct ChangeObject : public Object { int nonZero; bool moving; }; enum VisionStep { ACQUISITION, ENHANCEMENT, SEGMENTATION, FEATURE_EXTRACT, CLASSIFICATION }; class IDetector { public: /** * @brief Construct a new IDetector object * * @param cap the image capture to use */ IDetector(std::shared_ptr<Acquisition> cap) { processors[ACQUISITION] = cap; } virtual ~IDetector(){} /** * @brief Get the list of objects from the detector * * @return std::vector<std::shared_ptr<Object>> */ virtual std::vector<std::shared_ptr<Object>> getObjects() = 0; protected: std::map<VisionStep, std::shared_ptr<IImageProcessing>> processors; //data }; //IDetector } // namespace Detector #endif //IDETECTOR_HPP
true
851e664998ce95c04c8b44036dd55c7507da9cfb
C++
maornelas/coj-problems
/1140/the-next-palindrome.cpp
UTF-8
2,770
2.90625
3
[]
no_license
#define EPS 1e-11 #define inf ( 1LL << 31 ) - 1 #define LL long long #define abs(x) (((x)< 0) ? (-(x)) : (x)) #define all(x) (x).begin(), (x).end() #define ms(x, a) memset((x), (a), sizeof(x)) #define mp make_pair #define pb push_back #define sz(k) (int)(k).size() using namespace std; typedef vector <int> vi; bool isPalindrome (string str){ int start = 0, end = str.length() - 1; while (start < end){ if (str[start++] != str[end--]){ return false; } } return true; } int get_bigger (string str1, string str2){ int len = str1.length(); for (int i = 0; i < len; i++){ if (str1[i] < str2[i]){ return -1; } else if (str1[i] > str2[i]){ return 1; } } return 0; } string rev (string str){ string revstr = str; int start = 0, end = str.size() - 1; while (start <= end){ revstr[end] = str[start]; revstr[start++] = str[end--]; } return revstr; } string inc_str (string str){ int len = str.size() - 1; //cout << "Len " << len << endl; string res = str; int carry = 1; while (len >= 0 && carry){ if (str[len] == '9'){ res[len--] = '0'; } else{ res[len--]++; //res.insert (res.begin(), ++X); //cout << "X is " << X << " and Len is " << len << endl; carry = 0; } } if (carry){ res = "1" + res; } return res; } void process (string str){ string str1, str2, str3; int len = str.size(); str1 = str.substr (0, len/2); if (len % 2 == 0){ str2 = ""; str3 = str.substr (len/2, len/2); //cout << "Even " << str1 << " " << str2 << " " << str3 << endl; } else{ str2 = str.substr (len/2, 1); str3 = str.substr (len/2 + 1, len/2); //cout << "Odd " << str1 << " " << str2 << " " << str3 << endl; } string rev_str1 = rev (str1); //cout << "After Reverse " << str1 << " " << rev_str1 << endl; int rc = 0; //if (get_bigger (rev_str1, str3) > 0) if (rev_str1 > str3){ //cout << "Reversed First String is bigger" << endl; cout << str1 + str2 + rev_str1 << endl; return; } if (str2 == ""){ //cout << "Middle String is Empty" << endl; int ix = str1.size(); rev_str1 = ""; rev_str1.append (ix, '0'); str1 = inc_str (str1); } else{ //cout << "Middle String is " << str2 << endl; str2 = inc_str (str2); //cout << "Incremented String is " << str2 << endl; if (str2.size() > 1){ int ix = str1.size(); rev_str1 = ""; rev_str1.append (ix, '0'); str1 = inc_str (str1); str2 = "0"; } } //cout << "At the end of Iteration " << str1 + str2 + rev_str1 << endl; string str4 = str1 + str2 + rev_str1; if (isPalindrome(str4)) { cout << str4 << endl; return; } process (str4); } int main (){ int total ; cin >> total; string str; while (total-- > 0){ cin >> str; //cout << "Processing " << str << endl; process (str); } return 0; }
true
51d736ad6c204029ed2a9d5b85bc8896dc704ff1
C++
Cyanide-IT/Solar-Tracker
/finalArduinoCode.cc
UTF-8
2,099
2.953125
3
[]
no_license
#include<Servo.h> Servo pan, tilt; const int ldr1 = 0; const int ldr2 = 1; const int ldr3 = 2; const int ldr4 = 3; double bright1, bright2, bright3, bright4; double left, right, top, bottom; int panDesired, tiltDesired; int panCur, tiltCur; int lAdj, rAdj; void setup() { Serial.begin(9600); pan.attach(5); tilt.attach(6); pan.write(90); tilt.write(91); while(true) { if(Serial.available() > 0) { byte mes = Serial.read(); if (mes == 's') //start program break; } delay(100); } } void loop() { if(Serial.available() > 0) { if(Serial.read() == 't'); setup(); } bright1 = (double)analogRead(ldr1); bright2 = (double)analogRead(ldr2) * 610.0/274; bright3 = (double)analogRead(ldr3) * 610.0/335; bright4 = (double)analogRead(ldr4) * 610.0/209; left = (bright1 + bright2) / 2.0; right = (bright3 + bright4) / 2.0; top = (bright3 + bright1) / 2.0; bottom = (bright2 + bright4) / 2.0; panCur = pan.read(); tiltCur = tilt.read(); if(tiltCur > 90) { lAdj = -3; rAdj = 3; } else { lAdj = 3; rAdj = -3; } if(left > right + 10) //pos pan { panDesired = panCur + lAdj; } else if(right > left + 10) { panDesired = panCur = rAdj; } else { panDesired = panCur; } if(top > bottom + 10) //neg tilt { tiltDesired = tiltCur - 3; } else if(bottom > top + 10) //pos tilt { tiltDesired = tiltCur + 3; } else { tiltDesired = tiltCur; } if(panDesired == panCur && tiltDesired == tiltCur) { Serial.println('f'); delay(500); Serial.print("pan: "); Serial.println(String(panCur)); delay(500); Serial.print("tilt: "); Serial.println(String(tiltCur)); } if(panDesired >= 170 || panDesired <= 10) { panDesired = panCur; } if(tiltDesired >= 170 || tiltDesired <= 10) { tiltDesired = tiltCur; } pan.write(panDesired); tilt.write(tiltDesired); delay(1000); } //mark 4
true
5947235c2f226f10f0c3483241de15b4b532083e
C++
denishong/gongbu
/algorithm/baekjoon/greedy/11399-1.cpp
UTF-8
345
2.640625
3
[]
no_license
/* baekjoon 11399 ATM */ #include <iostream> #include <algorithm> using namespace std; int main(){ int N; int A[1001]; int sum=0, ans =0; cin >> N; for( int i =0; i < N; i++){ cin >> A[i]; } sort( A, A+N ); for( int i =0; i< N; i++ ){ sum += A[i]; ans += sum; } cout << ans << endl; return 0; } /* baekjoon 11399 ATM */
true