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
a15080ebbbff598b86860ac9c963e75082096afe
C++
yonghwankim-dev/C--_ExpenseWrite
/지출기록프로그램/control.cpp
UHC
6,695
3.234375
3
[]
no_license
#include "control.h" #include "AccountException.h" #include "expense_info.h" #include "stream.h" control::control() : num(0) { } void control::write(stream * io) { expense_info exin; // ִ ü exin.expense_input(); // Է¹޾ try { string temp = exin.getDate().substr(5, 2); if (temp < "01" || temp >"12") throw DateException(exin.getDate()); temp = exin.getDate().substr(8, 2); if (temp < "01" || temp>"31") throw DateException(exin.getDate()); if (exin.getMoney() < 0) throw MinusException(exin.getMoney()); io->input(exin); // Է¹ txtϿ Ѵ. sort(); // ؼ txtϿ ٽ Ѵ. } catch (ExpenseException &expn) { expn.ShowExceptionReason(); } } // ḮƮ ¥ ϴ Լ int WhoIsPreced(LData data1, LData data2) { int year1, year2; int month1, month2; int day1, day2; year1 = atoi(data1.getDate().substr(0, 4).c_str()); year2 = atoi(data2.getDate().substr(0, 4).c_str()); month1 = atoi(data1.getDate().substr(5, 2).c_str()); month2 = atoi(data2.getDate().substr(5, 2).c_str()); day1 = atoi(data1.getDate().substr(8, 2).c_str()); day2 = atoi(data2.getDate().substr(8, 2).c_str()); if (year1 == year2) { if (month1 == month2) { if (day1 == day2) return 0; else if (day1 < day2) return 0; else return 1; } else if (month1 < month2) return 0; else return 1; } else if (year1 < year2) { return 0; } else { return 1; } } // test.txt ִ list ڷᱸ ű Լ void control::listInsert(List * list) { string in_line; ifstream in("2018__TXT.txt"); string buf; vector<string> tokens; while (getline(in, in_line)) { stringstream ss(in_line); while (ss >> buf) { tokens.push_back(buf); } expense_info exbuf(tokens[0], atoi(tokens[1].c_str()), tokens[2],tokens[3]); list->LInsert(exbuf); tokens.clear(); } in.close(); } void control::sort() { List list; list.SetSortRule(WhoIsPreced); listInsert(&list); ofstream out2("2018__TXT.txt"); expense_info temp; if (list.LFirst(&temp)) { out2 << temp.getDate() << '\t' << temp.getMoney() << '\t' << temp.getUsing() << '\t' << temp.getCategory() << endl; while (list.LNext(&temp)) { out2 << temp.getDate() << '\t' << temp.getMoney() << '\t' << temp.getUsing() << '\t' << temp.getCategory() << endl; } } out2.close(); } void control::ShowAllExpense(stream * io) { io->print(); io->printCategorySum(); io->printSum(); } void control::ShowMoneySum(stream * io) { io->printSum(); } void control::ShowDateSearch(string year) { List list; listInsert(&list); expense_info temp; string temp_date; int sum = 0; ShowHeader(); // ޴ if (list.LFirst(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } while (list.LNext(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } } } cout << "ݾ : " << sum << endl; } void control::ShowDateSearch(string year,string month) { List list; listInsert(&list); expense_info temp; string temp_date; int sum = 0; ShowHeader(); // ޴ if (list.LFirst(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year && temp_date.substr(5, 2) == month) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } while (list.LNext(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year && temp_date.substr(5, 2) == month) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } } } cout << "ݾ : " << sum << endl; } void control::ShowDateSearch(string year, string month, string day) { List list; listInsert(&list); expense_info temp; string temp_date; int sum = 0; ShowHeader(); // ޴ if (list.LFirst(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year && temp_date.substr(5, 2) == month && temp_date.substr(8, 2) == day) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } while (list.LNext(&temp)) { temp_date = temp.getDate(); if (temp_date.substr(0, 4) == year && temp_date.substr(5, 2) == month && temp_date.substr(8, 2) == day) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } } } cout << "ݾ : " << sum << endl; } void control::ShowDateSearch() { int number; string date; cout << "1. ˻" << endl; cout << "2. ˻" << endl; cout << "3. Ϻ ˻" << endl; cout << "4." << endl; cin >> number; if (number == 1) { cout << "Ͻô Էּ.(2019)" << endl; cin >> date; ShowDateSearch(date); } else if (number == 2) { cout << " Էּ.(2019-02)" << endl; cin >> date; ShowDateSearch(date.substr(0, 4), date.substr(5, 2)); } else if (number == 3) { cout << " Էּ(2019-02-02)" << endl; cin >> date; ShowDateSearch(date.substr(0, 4), date.substr(5, 2),date.substr(8,2)); } else if (number == 4) { exit(1); } else { return; } } void control::ShowMoneySearch() { List list; listInsert(&list); expense_info temp; int m; cout << "˻ϰ ݾ̻ Էּ." << endl; cin >> m; int sum = 0; ShowHeader(); // ޴ if (list.LFirst(&temp)) { if (temp.getMoney()>=m) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } while (list.LNext(&temp)) { if (temp.getMoney() >= m) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } } } cout << "ݾ : " << sum << endl; } void control::ShowCategorySearch() { List list; expense_info temp; int sum=0; string c; cout << "˻ϰ з ѱ۷ Էּ." << endl; cout << "з : 1.ĺ 2. 3.ź 4.ĺ 5. 6.Ȱ 7. 8. 9. 10.Ƿ 11.Ƿ 12.Ÿ" << endl; cin >> c; listInsert(&list); ShowHeader(); // ޴ if (list.LFirst(&temp)) { if (temp.getCategory()==c) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } while (list.LNext(&temp)) { if (temp.getCategory() == c) { temp.ShowExpenseInfo(); sum += temp.getMoney(); } } } cout << "ݾ : " << sum << endl; }
true
69e80cb5576932ed802eea807a89081a29553ecf
C++
wpinaud/Game_1000pts
/Game_1000pts/Game_1000pts/Joueur.cpp
UTF-8
1,949
3.21875
3
[]
no_license
// // Joueur.cpp // Game_1000pts // // Created by Willis Pinaud on 19/10/2015. // Copyright © 2015 Centrale. All rights reserved. // #include "Joueur.hpp" int Joueur::score(){ int score; //Parcourir le tas et additionner le score de toutes les cartes points //std::add(tas.begin(),tas.end(),add_score) //fonction add score: carte.getPoint() return score; } Carte* Joueur::getFirstOnDeck(){ if (tas.size()>0){ return tas.back(); } else{ //permettre au joueur de poser une carte sur son tas lorsque le tas est vide Carte* carteNulle = new CartePoint(0, 9999); return carteNulle; } } bool Joueur::estJouable(Carte* carte, Carte* carteAdv){ std::string monTypeDeCarte = carte->getType(); std::string typeCarteAdv = carteAdv->getType(); std::string maPremiereCarte = getFirstOnDeck()->getType(); //la carte donnée est une carte point // et la première carte de mon tas est une point ou une parade if (monTypeDeCarte == "Point"){ if (maPremiereCarte == "Point" || maPremiereCarte == "Parade"){ return true; } else{ // et la première carte de mon tas est une attaque return false; } } //La carte donnée est une carte attaque // et la première carte du tas de l'adversaire est une point ou une parade if (monTypeDeCarte == "Attaque"){ if (typeCarteAdv == "Point" || typeCarteAdv == "Parade"){ return true; } else{ // et la première carte du tas de l'adversaire est une attaque return false; } } //La carte donnée est une carte parade // et la première carte de mon tas est une point ou une parade if (monTypeDeCarte == "Parade"){ if (maPremiereCarte == "Attaque" && getFirstOnDeck()->getGroupe() == carte->getGroupe()){ return true; } else {return false;} } return false; }
true
e9b2875c6434c9f7258a5a5e2b90ec8ad248615e
C++
cimplesid/Numerical-method-solution
/forward.cpp
UTF-8
838
2.671875
3
[]
no_license
#include<stdio.h> #include<conio.h> #include<math.h> main() { int i,n,j,fact=1; float x[20],y[20][20],h,d=1,p,a,f; printf("Enter The Value of n:"); scanf("%d",&n); printf("\nEnter the elements of x,y:"); for(i=1;i<=n;i++) { scanf("%f", &x[i]); scanf("%f",&y[i][1]);} h=x[2]-x[1]; printf("Enter x for which y is to be calculated:"); scanf("%f",&f); p = (f-x[1])/h; a=y[1][1]; for(j=2;j<=n;j++) { for(i=1;i<=(n-j)+1;i++) y[i][j]= y[i+1][j-1] - y[i][j-1]; } //printf("The Table is :\n\n"); //for(i=1;i<=n;i++) // { // printf("\t%.2f",x[i]); // for(j=1;j<=(n-i)+1;j++) // printf("\t%.2f",y[i][j]); // printf("\n"); // } for(j=2;j<=n;j++) { for(i=1;i<j;i++) fact=fact*i; d = d*(p-(j-1)); a = a + (y[1][j]*d)/fact; fact=1; } printf("\n\nFor x=%f The Value of y is %f",f,a); getch(); }
true
d4325caa56bf029457e46aa21e5fa4f03f5ffc67
C++
GauravNITIAN/Algorithms
/Dynamic programing/WordBreak.cpp
UTF-8
1,783
4.03125
4
[]
no_license
#include<iostream> #include<string.h> using namespace std; /* This problem is to solve the word break problem which means you are given a sentence without spaces then you need to check whether that sentence exists after breaking them in words. Basically we need to check that all characters that forms a word are valid or not . Idea : - Basic idea is to check the first character in the dictionary then the remaining and mark them in the table as true to indicate that this is valid word */ //This is a function to check in dictionary bool matchDictionary(string word) { string dictionary[] = {"mobile","samsung","sam","sung","man","mango", "icecream","and","go","i","like","ice","cream"}; int size = sizeof(dictionary)/sizeof(dictionary[0]); for (int i = 0; i < size; i++) if (dictionary[i].compare(word) == 0) return true; return false; } bool wordBreak(string str) { int n = str.length(); bool table[n+1]; // a boolean array to indicate the words are valid memset(table,0,sizeof(table)); // intialize with false for(int i=1;i<n;i++) { if(table[i] == false && matchDictionary(str.substr(0,i))) table[i] = true; if(table[i] == true) { if(i == n) return true; for(int j=i+1;j<n+1;j++) { // str.substr(start index, length from start index) if(table[j] == false && matchDictionary(str.substr(i,j-i))) table[j] = true; if(j ==n && table[j]==true) return true; } } } } int main() { cout<<wordBreak("ilikesamsung"); return 0; }
true
4cc1f8feb5e20f61d41e477705e4a50060c59ff8
C++
fake-cheater/hardware-id-generator
/implementation/version.cpp
UTF-8
2,326
3.203125
3
[]
no_license
#include "version.hpp" #include "log.hpp" #include <algorithm> #include <iterator> #include <sstream> #include <vector> namespace system_info { Version::Version( const std::string& versionStr ) { *this = GetVersionFromString( versionStr ); } std::string Version::ToString() const { return std::to_string( MajorVersion ) + "." + std::to_string( MinorVersion ); } Version Version::GetVersionFromString( const std::string& versionStr ) { Version version; std::string versionWithSpaces = versionStr; std::replace( versionWithSpaces.begin(), versionWithSpaces.end(), '.', ' ' ); std::istringstream iss( versionWithSpaces ); const std::vector< std::string > results( ( std::istream_iterator< std::string >( iss ) ), std::istream_iterator< std::string>() ); if( results.size() != 2 ) { HIDLog::Write( "Строка с номером версии задана некорретно." "Значение по умолчанию 1.0", LogLevel::Error ); version.MajorVersion = 1; version.MinorVersion = 0; return version; } version.MajorVersion = std::stoi( results[ 0 ] ); version.MinorVersion = std::stoi( results[ 1 ] ); return version; } bool operator<( const Version& version1, const Version& version2 ) { if( version1.MajorVersion < version2.MajorVersion ) return true; else if( version1.MajorVersion == version2.MajorVersion ) if( version1.MinorVersion < version2.MinorVersion ) return true; return false; } bool operator==( const Version& version1, const Version& version2 ) { if( version1.MajorVersion == version2.MajorVersion && version1.MinorVersion == version2.MinorVersion ) return true; return false; } bool operator!=( const Version& version1, const Version& version2 ) { return !( version1 == version2 ); } bool operator>=( const Version& version1, const Version& version2 ) { return !( version1 < version2 ); } bool operator<=( const Version& version1, const Version& version2 ) { return ( version1 == version2 ) || ( version1 < version2 ); } bool operator>( const Version& version1, const Version& version2 ) { return !( ( version1 == version2 ) || ( version1 < version2 ) ); } } // end namespace system_info
true
6ccf245267edf330b241ba221b77ec7d0014702b
C++
mikeqcp/superseaman
/Material.h
UTF-8
1,326
2.78125
3
[]
no_license
#pragma once #include "includes.h" class Material { private: string name; GLfloat Ns, Ni, d; glm::vec4 Ka, Kd, Ks; int illum; string map_Kd, map_Ka, map_Ks, map_Kn; public: Material(void); ~Material(void); void setName(string name){ this -> name = name; } void setNs(GLfloat Ns){ this -> Ns = Ns; } void setNi(GLfloat Ni){ this -> Ni = Ni; } void setD(GLfloat d){ this -> d = d; } void setKa(glm::vec4 Ka){ this -> Ka = Ka; } void setKd(glm::vec4 Kd){ this -> Kd = Kd; } void setKs(glm::vec4 Ks){ this -> Ks = Ks; } void setIllum(int illum){ this -> illum = illum; } void setMap_Kd(string map_Kd){ this -> map_Kd = map_Kd; } void setMap_Ka(string map_Ka){ this -> map_Ka = map_Ka; } void setMap_Ks(string map_Ks){ this -> map_Ks = map_Ks; } void setMap_Kn(string map_Kn){ this -> map_Kn = map_Kn; } string getName(){ return name; } GLfloat getNs(){ return Ns; } GLfloat getNi(){ return Ni; } GLfloat getD(){ return d; } glm::vec4 getKa(){ return Ka; } glm::vec4 getKd(){ return Kd; } glm::vec4 getKs(){ return Ks; } int getIllum(){ return illum; } string getMap_Kd(){ return map_Kd; } string getMap_Ka(){ return map_Ka; } string getMap_Ks(){ return map_Ks; } string getMap_Kn(){ return map_Kn; } };
true
bfe348989017ab99b0e1947936f39dfa198f2799
C++
aleafall/DS-A
/pat/a1115.cpp
UTF-8
1,096
3.203125
3
[]
no_license
// // Created by aleafall on 16-10-3. // #include<iostream> #include<map> using namespace std; struct Node { int data; Node *lchild, *rchild; } *root; map<int, int> mp; void preOrder(Node *root, int depth) { if (root == NULL) return; if (mp.find(depth) != mp.end()) mp[depth]++; else mp[depth] = 1; preOrder(root->lchild, depth + 1); preOrder(root->rchild, depth + 1); } void insert(Node *&root, int data) { if (root == NULL) { root = new Node; root->data = data; root->lchild = root->rchild = NULL; return; } if (data <= root->data) insert(root->lchild, data); else insert(root->rchild, data); } int main() { int n, x; cin >> n; for (int i = 0; i < n; i++) { cin >> x; insert(root, x); } preOrder(root, 1); int n1, n2; if (mp.size() > 1) { map<int, int>::iterator it = --mp.end(); n1 = it->second; n2 = (--it)->second; } else { n1 = 1; n2 = 0; } cout << n1 << " + " << n2 << " = " << n1 + n2 << endl; return 0; }
true
bbecd95b57de9cc556dc9caebbc948499897ec01
C++
luke-peters/COOP_CHESS
/Board.cpp
UTF-8
14,494
3.46875
3
[]
no_license
//Luke Peters: 10204030 //31/05/2021 # include<iostream> # include "Board.h" # include <algorithm> # include <memory> #include <iomanip> #include <tuple> //NO elegant way of doing this //All uncalled squares already have a nullptr void chessboard::set_start_board() { //Resets unique_ptr at relevant coordinates on the board array //to point at a newly created relevant piece //Sets white non pawn pieces squares[0][0].reset(new rook {Colour::white}); squares[1][0].reset(new knight {Colour::white}); squares[2][0].reset(new bishop {Colour::white}); squares[3][0].reset(new queen {Colour::white}); squares[4][0].reset(new king {Colour::white}); squares[5][0].reset(new bishop {Colour::white}); squares[6][0].reset(new knight {Colour::white}); squares[7][0].reset(new rook {Colour::white}); //Sets black non pawn pieces squares[0][7].reset(new rook {Colour::black}); squares[1][7].reset(new knight {Colour::black}); squares[2][7].reset(new bishop {Colour::black}); squares[3][7].reset(new queen {Colour::black}); squares[4][7].reset(new king {Colour::black}); squares[5][7].reset(new bishop {Colour::black}); squares[6][7].reset(new knight {Colour::black}); squares[7][7].reset(new rook {Colour::black}); //Sets all pawns for (int x = 0; x < 8; x++) { squares[x][1].reset(new pawn{Colour::white}); squares[x][6].reset(new pawn{Colour::black}); } }; //Gets symbol at position on board //Differs from the get symbol function in piece class as it handles nullptrs //For use in the print board function char chessboard::get_symbol_board(int x, int y)const { //If a piece present at the coordinate return it's symbol if (squares[x][y] != nullptr) { return squares[x][y]->get_symbol(); //If null ptr return a whitespace symbol } else { return ' '; } } void chessboard::print_graveyard() const { std::cout<<"PIECE GRAVEYARD"<<std::endl; //For each piece in the graveyard, print it's symbol for (unsigned i=0; i<graveyard.size(); i++){ std::cout<<graveyard.at(i)->get_symbol()<<std::endl; } } void chessboard::print_board() const { //Uses get symbol on board function to display the pieces being pointed to at //each coordinate in the board array std::cout<<" A B C D E F G H"<<std::endl; for (int y {7}; y > -1; y--) { std::cout<<" --------------------------------"<<std::endl; for (int x {0}; x < 8; x++) { if (x==0){ std::cout<<y+1<<"| "<<this->get_symbol_board(x,y)<<" "; } else{ std::cout<<"| "<<this->get_symbol_board(x,y)<<" "; } }; std::cout<<"|"<<std::endl; }; std::cout<<" --------------------------------"<<std::endl; std::cout<<"(Enter 'menu' to see menu)\n"<<std::endl; }; std::vector<std::tuple<char,char>> chessboard::get_movelist_at_position(const Colour& turn,const std::tuple<char, char>& start) { int x_pos=std::get<0>(start); int y_pos=std::get<1>(start); if(squares[x_pos][y_pos] != nullptr && squares[x_pos][y_pos]->get_colour() == turn){ //Sets the movelist for the selected piece and position squares[x_pos][y_pos]->set_move_list(squares,start); return squares[x_pos][y_pos]->get_move_list(); } else{ return{}; } } std::vector<std::tuple<char,char>> chessboard::get_capture_movelist_at_position(const Colour& turn,const std::tuple<char, char>& start) { int x_pos=std::get<0>(start); int y_pos=std::get<1>(start); if(squares[x_pos][y_pos] != nullptr && squares[x_pos][y_pos]->get_colour() == turn){ //Sets the movelist for the selected piece and position squares[x_pos][y_pos]->set_move_list(squares,start); return squares[x_pos][y_pos]->get_capture_move_list(); } else{ return{}; } } void chessboard::add_to_is_promotion_list(bool is_promotion) { was_move_promotion.push_back(is_promotion); } //Moves a piece on the board legally bool chessboard::move_piece(const Colour& turn, const std::tuple<char, char>& start, const std::tuple<char, char>& fin) { //Convert tuple of coordinates to seperate integers for ease of coding int x_start=std::get<0>(start); int y_start=std::get<1>(start); int x_fin=std::get<0>(fin); int y_fin=std::get<1>(fin); //If not trying to move an empty space or wrong colour if(squares[x_start][y_start] != nullptr && squares[x_start][y_start]->get_colour() == turn){ //Sets the movelist for the selected piece and position squares[x_start][y_start]->set_move_list(squares,start); //Creates temporary vector using get_move_list std::vector<std::tuple<char,char>> all_moves=squares[x_start][y_start]->get_move_list(); //Checks that the inputted move is in the selected pieces move list if (std::find(all_moves.begin(), all_moves.end(), fin) != all_moves.end()){ //If move is legal moves the unique ptr to piece to the final position std::swap(squares[x_start][y_start],squares[x_fin][y_fin]); //Puts unique ptr to piece in the graveyard if it has just been taken if(squares[x_start][y_start]!=nullptr){ graveyard.push_back(std::move(squares[x_start][y_start])); //Sets last move captrue to true was_move_capture.push_back(true); } else{ //If move wasn't a capture sets was last move capture to false was_move_capture.push_back(false); } //Resets the now empty square to a nullptr squares[x_start][y_start].reset(); //Increase the moved pieces move counter by 1 squares[x_fin][y_fin]->edit_move_count(1); //Returns true indicating a move has actually been completed return true; } else{ //If the inputted move coordinate is not in the selected pieces move list returns //An error message indicating the move is illegal for the selected piece, and outputs it's name std::cout<<"This is an illegal move for the " << squares[x_start][y_start]->get_piece_name()<<std::endl; //Returns false as no move was actually made return false; } } else{ //If the user selects a nullptr or the wrong colour, outputs an error message indicating thise std::cout<<"Please select your own piece"<<std::endl; //returns false as no move was actuall made return false; } //Returns false by default return false; }; //Moves a piece on the board Illegally, used for undoing moves (e.g-pawns going backwards) //It takes the initial and final positions in the same sense as the move_piece function //So the coordinate tuples inputted into move piece should be reversed when attempting to undo the move void chessboard::illegal_undo_move(const std::tuple<char, char>& start, const std::tuple<char, char>& fin) { //Convert tuples to integers for ease of coding int x_start=std::get<0>(start); int y_start=std::get<1>(start); int x_fin=std::get<0>(fin); int y_fin=std::get<1>(fin); //If the last move was a promotion if(was_move_promotion.back()==true){ //Moves the newly promoted pawn into it's position squares[x_start][y_start]=std::move(promoted_pawns.back()); //Deletes the now empty vector element promoted_pawns.pop_back(); } //Swaps the unique ptrs to piece at the start and final position std::swap(squares[x_start][y_start],squares[x_fin][y_fin]); //As this is an undo type move, it reduces the selected pieces move count by 1 //This is important for undoing a pawns first move, as it must still be allowed to move two steps afterwards squares[x_fin][y_fin]->edit_move_count(-1); //If last move was a capture we replace the now empty square with the most recently capture pieced at the end of the graveyard vector //and then delete the now nullptr in the graveyard vector if(was_move_capture.back()==true){ squares[x_start][y_start]=std::move(graveyard.back()); graveyard.pop_back(); } was_move_capture.pop_back(); was_move_promotion.pop_back(); } const std::tuple<char,char> chessboard::get_king_position(const Colour& turn)const { //Loops over every coordinate on the board array for (int x{0}; x < 8; x++){ for (int y{0}; y < 8; y++){ //If a coorindate contains a unique pointer to a piece if(squares[x][y] != nullptr){ //If the coordinate contatains a unique pointer to a king of the inputted colour if(squares[x][y]->get_piece_type() == Piece_Type::king && squares[x][y]->get_colour()==turn){ //Create and return a coordinate tuple of the kings position std::tuple<char,char> king_position{x,y}; return(king_position); } } } } //Otherwise return a tuple of some inaccessible coordinate //This return should never be met as we always have a king on the board?? return (std::tuple<char,char> {-1,-1}); } bool chessboard::is_check(const Colour& turn) { //Creates a coordinate tuple containing the selected colours king position std::tuple<char,char> king_position{this->get_king_position(turn)}; //Loops over every coordinate in the board array for (int x{0}; x < 8; x++){ for (int y{0}; y < 8; y++){ //If a coordinate contains a unique pointer to a piece of the opposite colour if(squares[x][y]!=nullptr && squares[x][y]->get_colour()!=turn){ //Creates a coordinate tuple of this opponent pieces position std::tuple<char,char> start{x,y}; //Sets the legal move lists for the opponent piece squares[x][y]->set_move_list(squares,start); //Initialises a vector contating the opponent pieces legal moves std::vector<std::tuple<char,char>> selected_opp_moves{squares[x][y]->get_move_list()}; //If the kings coordinate tuple is one of the oppoonent pieces legal moves then it can be taken //hence the king is currently in check and so returns true if (std::find(selected_opp_moves.begin(), selected_opp_moves.end(), king_position) != selected_opp_moves.end()){ return true; } } } } //If the kings position is not on any opposing pieces legal move list it is not in check so return false return false; } bool chessboard::is_check_mate(const Colour& turn) { //Requires King is in check before checking for check mate if(this->is_check(turn)==true){ //Loops over all coordinates in board array for (int x{0}; x < 8; x++){ for (int y{0}; y < 8; y++){ //If position contains unique ptr to piece of same colour we are checking check mate for if(squares[x][y]!=nullptr && squares[x][y]->get_colour()==turn){ //Creates a coordinate tuple std::tuple<char,char> start{x,y}; //Sets the movelist for the piece being pointed to at the board coordinate squares[x][y]->set_move_list(squares,start); //Initialises a vector to store all the possible moves for this piece std::vector<std::tuple<char,char>> possible_moves{squares[x][y]->get_move_list()}; //Loops over every possible move in the newly initalisedpossible moves vector for (int i=0; i < possible_moves.size(); i++) { //Make the possible move for the selected piece this->move_piece(turn,start,possible_moves[i]); //check for promotion as usual this->add_to_is_promotion_list(false); //Now the move has been made check if the King is still in check if(this->is_check(turn)!=true){ //Undo the move illegal_undo_move(possible_moves[i],start); //If the king isn't in check anymore then there exists a move //that takes the king out of check so is checkmate returns false return false; } //Undo the move illegal_undo_move(possible_moves[i],start); } } } } //If there are no moves by the selected colour that take the selected colours king out of check //then the king is in checkmate and is checkmate returns true return true; } //Return false if the king isn't in check in the first place return false; } bool chessboard::is_pawn_promotion(const Colour& turn) { //Initialise an integer the y coordinate of search for a promotion pawn int y_pawn_pos; //The y coordinate "search row" depends on the colour //If white the 7th row is searched //If black the 0th row is searched if(turn==Colour::white){ y_pawn_pos=7; } if(turn==Colour::black){ y_pawn_pos=0; } //Loops over all x coordinates/ board collumns for (int x{0}; x < 8; x++){ //If there is a piece if(squares[x][y_pawn_pos] != nullptr){ //If the piece type is pawn (we can assume it's the correct colour as pawns can only achieve end rows by travelling forward) if (squares[x][y_pawn_pos]->get_piece_type() == Piece_Type::pawn){ //Set was last move promotion to true and return true was_move_promotion.push_back(true); //Essentially, a pawn has been found somewhere on the end rows of the board array, so a promition must occur return true; } } } //If no pawns present on end rows of the board array, then no promotion needs to happen was_move_promotion.push_back(false); return false; } void chessboard::promote_pawn(const Piece_Type piece_choice, const Colour& turn) { //Defines integers to store the "promotion pawn"'s position int x_pawn_pos; int y_pawn_pos; //Once again initialises the y coordinate depending on the pawns colour if(turn==Colour::white){ y_pawn_pos=7; } if(turn==Colour::black){ y_pawn_pos=0; } //Loops over all x_coordinates on the board for (int x{0}; x < 8; x++){ //If there is a piece present if(squares[x][7] != nullptr){ //If it is also a pawn if (squares[x][y_pawn_pos]->get_piece_type() == Piece_Type::pawn){ //Set the x coordinate of the pawn to this value x_pawn_pos=x; } } } //Push back the unique pointer to the promition pawn to the promoted pawns vector promoted_pawns.push_back(std::move(squares[x_pawn_pos][y_pawn_pos])); //Reset the empty square left by the promoted pawn to a new piece of the inputted type if(piece_choice==Piece_Type::queen){ squares [x_pawn_pos][y_pawn_pos].reset(new queen {turn}); } if(piece_choice==Piece_Type::rook){ squares[x_pawn_pos][y_pawn_pos].reset(new rook {turn}); } if(piece_choice==Piece_Type::bishop){ squares[x_pawn_pos][y_pawn_pos].reset(new bishop {turn}); } if(piece_choice==Piece_Type::knight){ squares[x_pawn_pos][y_pawn_pos].reset(new knight {turn}); } }
true
506ffa5e8a44c88113343e2152b472581dd98344
C++
Cocoonshu/FMRadio
/sketch_FMRadio/Button.h
UTF-8
331
2.640625
3
[]
no_license
#ifndef BUTTON_H #define BUTTON_H #include <Arduino.h> class Button { public: Button(int pin); ~Button(); void setOnClickListener(void (*)(int)); void handleClick(); private: void onPinInterrupted(); private: void (*Button::mOnClickListener)(int); int mPin; byte mLastPinValue; }; #endif
true
178620d972fe4d9f7da860f0dcd91a1d4dd2cdd6
C++
MathProgrammer/Hacker-Earth
/Contests/Sprint Challenge 2 - NIT Jalandhar/Programs/Points on a Rectangle.cpp
UTF-8
662
3
3
[]
no_license
#include <cstdio> #define min(a, b) (a < b ? a : b) #define max(a, b) (a > b ? a : b) void solve() { int x1, y1, x2, y2, no_of_points, no_of_internal_points = 0; scanf("%d %d %d %d", &x1, &y1, &x2, &y2); scanf("%d", &no_of_points); while(no_of_points--) { int x, y; scanf("%d %d", &x, &y); no_of_internal_points += (x > min(x1, x2) && x < max(x1, x2) && y > min(y1, y2) && y<max(y1, y2)); } printf("%d\n", no_of_internal_points); } int main() { int no_of_test_cases; scanf("%d", &no_of_test_cases); while(no_of_test_cases--) solve(); return 0; }
true
bc0a06e652fba2ae6dc0d18b74144a0e412b3c1e
C++
260058433/LeetCode
/src/140_WordBreakII.cpp
UTF-8
1,571
3.34375
3
[]
no_license
#include <vector> #include <unordered_set> #include <string> using std::vector; using std::unordered_set; using std::string; class WordBreakII { public: vector<string> wordBreak(string s, unordered_set<string> &wordDict) { int n = s.size(); vector<bool> canBreak(n + 1); canBreak[0] = true; for (int i = 0; i < n; ++i) { for (int j = i; j >= 0; --j) if (canBreak[j] && wordDict.find(s.substr(j, i - j + 1)) != wordDict.end()) { canBreak[i + 1] = true; break; } } if (!canBreak[n]) return vector<string>(); vector<string> result; string cur; int longest = 0; for (auto p = wordDict.begin(); p != wordDict.end(); ++p) if (longest < p->size()) longest = p->size(); dfs(result, cur, s, 0, wordDict, longest); return result; } private: void dfs(vector<string> &result, string &cur, string &s, int begin, unordered_set<string> &wordDict, int longest) { if (begin == s.size()) { result.push_back(cur); result.back().pop_back(); return; } for (int i = 1; i <= s.size() - begin && i <= longest; ++i) { if (wordDict.find(s.substr(begin, i)) != wordDict.end()) { string tmp(cur); tmp += s.substr(begin, i); tmp.push_back(' '); dfs(result, tmp, s, begin + i, wordDict, longest); } } } };
true
34801270c614296759057685c631c53df6ba9bf8
C++
aliagestl/treeExercise
/treeExercise/Tree.cpp
UTF-8
1,240
3.640625
4
[]
no_license
#include "Tree.h" #include <math.h> #include <stdlib.h> Tree::Tree() { } Tree::Tree(int lvls) { levels = lvls; int length = pow(2, levels) - 1; int* tree; tree = (int *)malloc(sizeof(int) * length); tree[0] = 1; bool loopDone; while (!loopDone) { //if leftneighbor(index) == -1 //left child (2*index + 1) = 1 //else //left child(2*index + 1) = leftneighbor + tree[index] //if rightneighbor(index) == -1 //right child (2*index + 2) = 1 //else //right child(2*index + 2) = rightneighbor + tree[index] //index+=2 //if(index = 2^levels-1) //done } //printTree } void Tree::printTree() { } Tree::~Tree() { } int Tree::parent(int index) { //parent is math.floor((index-1)/2) int pt = floor((index - 1) / 2); return pt; } int Tree::leftNeighbor(int index) { //if parent exists, return parent's left child if (parent(index) > 0) { //left child is 2i + 1 int nb = (2*parent(index) + 1); return nb; } //if doesnt exist return -1 else return -1; } int Tree::rightNeighbor(int index) { //if parent exists, return parent's right child if (parent(index) > 0) { //right child is 2i + 2 int nb = (2 * parent(index) + 1); return nb; } //if doesnt exist return -1 else return 0; }
true
30153f640b28b9bd5c02c6397bd45210787ddd5e
C++
cry20011/algo
/sem3/contest1/taxi.cpp
UTF-8
1,721
3.21875
3
[]
no_license
#include <iostream> #include <vector> class bipart_graph{ private: int A_size; int B_size; std::vector<std::vector<int>> edges; std::vector<int> curr_match; std::vector<int> been_vert; bool koon(int v){ if(been_vert[v] == true) return false; been_vert[v] = true; for(int i = 0; i < edges[v].size(); ++i){ int next = edges[v][i]; if(curr_match[next] == -1 || koon(curr_match[next])){ curr_match[next] = v; return true; } } return false; } public: bipart_graph(int A, int B, std::vector<std::vector<int>>& e): A_size(A), B_size(B), edges(e){ curr_match.assign(B_size, -1); been_vert.assign(A_size, 0); } void find_max_match(){ for(int v = 0; v < A_size; ++v){ been_vert.assign(A_size, 0); koon(v); } } int match_size(){ int size = 0; for(int i = 0; i < B_size; ++i) if(curr_match[i] != -1) size++; return size; } }; struct order{ int time; int way_time; int x1, y1; int x2, y2; }; int way_time(int x1, int y1, int x2, int y2){ return abs(x1 - x2) + abs(y1 - y2); } int main(){ int n; std::cin >> n; std::vector<order> v; std::vector<std::vector<int>> e(n, std::vector<int>({})); for(int i = 0; i < n; ++i){ int hours, minutes, x1, y1, x2, y2; char c; std::cin >> hours >> c >> minutes >> x1 >> y1 >> x2 >> y2; int start_time = hours * 60 + minutes; v.push_back({start_time, way_time(x1, y1, x2, y2), x1, y1, x2, y2}); } for(int i = 0; i < n; ++i){ for(int j = i + 1; j < n; ++j){ if(v[i].time + v[i].way_time + way_time(v[i].x2, v[i].y2, v[j].x1, v[j].y1) < v[j].time) e[i].push_back(j); } } bipart_graph g(n, n, e); g.find_max_match(); std::cout << n - g.match_size(); const int x = n; }
true
a774aa121fab93da9d29bf73bc9636532d41685c
C++
lesquoyb/projet_ia
/src/recuit/test_recuit_simule_d2.h
UTF-8
2,806
3.140625
3
[]
no_license
#ifndef TEST_RECUIT_SIMULE_D2 #define TEST_RECUIT_SIMULE_D2 /* teste l'algorithme du recuit simulé pour rechercher le minimum d'une fonction math réelle à 2 variables Pour cette application, l'ensemble des solutions, S = R^2 = {(x,y) avec x dans R et y dans R} */ #include <stdlib.h> /* srand, rand */ #include <time.h> #include <iostream> #include <math.h> #include "algebre_lineaire.h" #include "recuit_simule.h" #include "tools_math.h" #include "vector2d.h" #include "recuit_simule_d2.h" using namespace std; /* Le recuit simule est appliqué à la recherche des minimas des 2 fonctions suivantes à 2 variables */ /** paraboloïde de sommet (2,2,3) */ inline double cout1(const Vecteur2D & solution){ return f1(solution); } /** onde circulaire amortie de minimum -5 en (0,0) */ inline double cout2(const Vecteur2D & solution){ // le minimum est -5 atteint en (0,0) return f2(solution); } int test_recuit_simule_d2(){ srand (time(NULL)); // initialisation du générateur de nombres pseudo-aléatoires double tInitiale = 1000; // température initiale : affectation telle que deltaCoutMax/tInitiale ~= 0 double tFinale = 0; // température finale : affectation arbitraire telle que température finale <= température initiale int nombreTentativesMax = 100; // arbitraire : nombre max de tentatives par palier de température int nombreSuccesMax = 50; // arbitraire : nombre max de succès par palier de température //double solutionInitiale = -rand() + rand(); // tirage d'un nombre réel quelconque Vecteur2D solutionInitiale ( tirageAleatoire(-10,10), tirageAleatoire(-10,10)); // tirage d'un point quelconque Vecteur2D meilleureSolution; double coutMeilleureSolution; //const S recuitSimule(const double & tInitiale, const double & tFinale, const int nombreTentativesMax, const int nombreSuccesMax, const S & solutionInitiale, // double (*cout)(const S & solution), const S (* changementAleatoire)(const S & solution), double (*succ)(const double & temperature)) cout << "recherche du minimum d'une fonction à 2 variables réelles par la méthode du recuit simulé" << endl; meilleureSolution = recuitSimule1( tInitiale, tFinale, nombreTentativesMax, nombreSuccesMax, solutionInitiale, cout1, changementAleatoire, succ, coutMeilleureSolution); cout << "le minimum de la fonction est trouvé en : " << meilleureSolution <<", le minimum vaut : "<< coutMeilleureSolution << endl; SolutionCout<Vecteur2D> meilleureSolution2 = recuitSimule( tInitiale, tFinale, nombreTentativesMax, nombreSuccesMax, solutionInitiale, cout1, changementAleatoire, succ); cout << "meilleure solution et son coût : " << meilleureSolution2 << endl; return 0; } #endif // TEST_RECUIT_SIMULE_D2
true
85eabc9e5713295f33e31eec17ee126847ae124d
C++
NurenDurdanaAbha/Nuren
/Online Judge/Codeforces/HURR.cpp
UTF-8
358
2.65625
3
[]
no_license
#include<iostream> #include<stdio.h> using namespace std; int main() { char a[3],b[3],flag=0; int i; cin>>a; for(i=1; i<=5; i++) { cin>>b; if(a[0]==b[0] || a[1]==b[1]) { printf("YES\n"); flag=1; break; } } if(flag==0) printf("N0\n"); return 0; }
true
dd42d8d5fdf8f3cd6c2ed057d010c5506174d437
C++
RomeoV/Analytic-derivative
/Nodes.cpp
UTF-8
8,391
3.25
3
[]
no_license
#include <sstream> #include "Nodes.h" Node::Node() { operator_ = Operator::Node; } Node::~Node() { ; } Operator Node::getOperatorType() const { return operator_; } UnaryNode::UnaryNode (Node_ptr child) : child_(child) { operator_ = Operator::UnaryNode; } UnaryNode::~UnaryNode() { ; } string UnaryNode::getString() const { return getStringRepresentation(); } UnaryMinus::UnaryMinus(Node_ptr child) : UnaryNode(child) { operator_ = Operator::UnaryMinus; } UnaryMinus::~UnaryMinus() { ; } Node_ptr UnaryMinus::diff(char symbol) const { return std::make_shared<UnaryMinus>(child_->diff(symbol)); } Node_ptr UnaryMinus::simplify() { if (child_->getOperatorType() == Operator::Constant) { return std::make_shared<Constant>(-1*std::dynamic_pointer_cast<Constant>(child_)->getValue()); } else { return shared_from_this(); } } string UnaryMinus::getStringRepresentation() const { std::stringstream ss; ss << "(-" << child_->getString() << ")"; return ss.str(); } Logarithm::Logarithm(Node_ptr child) : UnaryNode(child) { operator_ = Operator::Logarithm; } Logarithm::~Logarithm() { ; } Node_ptr Logarithm::diff(char symbol) const { return std::make_shared<Multiplication>( std::make_shared<Power>( child_, std::make_shared<Constant>(-1) ), child_->diff(symbol) ); } Node_ptr Logarithm::simplify() { child_ = child_->simplify(); if (child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<EulersNumber>(child_)->getValue() == EulersNumber().getValue()) { return std::make_shared<Constant>(1); } else if ( child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(child_)->getValue() == 1){ return std::make_shared<Constant>(0); } else { return shared_from_this(); } } string Logarithm::getStringRepresentation() const { std::stringstream ss; ss << "ln(" << child_->getString() << ")"; return ss.str(); } Leaf::Leaf() { operator_ = Operator::Leaf; } Leaf::~Leaf() { ; } string Leaf::getString() const { return this->getStringRepresentation(); } Symbol::Symbol (char sym) : sym_(sym) { operator_ = Operator::Symbol; } Symbol::~Symbol() { ; } Node_ptr Symbol::simplify() { return shared_from_this(); } Node_ptr Symbol::diff (char symbol) const { if (symbol != this->sym_) { return std::make_shared<Constant>(0); } else { return std::make_shared<Constant>(1); } } string Symbol::getStringRepresentation() const { return string(1,sym_); } Constant::Constant (double value) : value_(value) { operator_ = Operator::Constant; } Constant::~Constant() { ; } Node_ptr Constant::simplify() { return shared_from_this(); } string Constant::getStringRepresentation() const { std::stringstream ss; ss << value_; return ss.str(); } Node_ptr Constant::diff (char symbol) const { return std::make_shared<Constant>(0); } double Constant::getValue() const { return value_; } EulersNumber::EulersNumber() : Constant(2.71) { operator_ = Operator::Constant; } EulersNumber::~EulersNumber() { ; } Node_ptr EulersNumber::simplify() { return std::enable_shared_from_this<EulersNumber>::shared_from_this(); } string EulersNumber::getStringRepresentation() const { return "e"; } BinaryNode::BinaryNode(Node_ptr left_child, Node_ptr right_child) : left_child_(left_child), right_child_(right_child) { operator_ = Operator::BinaryNode; } BinaryNode::~BinaryNode() { ; } string BinaryNode::getString() const { return getStringRepresentation(); } Power::Power(Node_ptr left_child, Node_ptr right_child) : BinaryNode(left_child, right_child) { operator_ = Operator::Power; } Power::~Power() { ; } Node_ptr Power::diff(char symbol) const { return std::make_shared<Multiplication>( std::make_shared<Power>( left_child_, std::make_shared<Addition>( right_child_, std::make_shared<UnaryMinus>( std::make_shared<Constant>(1) ) ) ), std::make_shared<Addition>( std::make_shared<Multiplication>( right_child_, left_child_->diff(symbol) ), std::make_shared<Multiplication>( std::make_shared<Multiplication>( left_child_, right_child_->diff(symbol) ), std::make_shared<Logarithm>( left_child_ ) ) ) ); } Node_ptr Power::simplify() { left_child_ = left_child_->simplify(); right_child_ = right_child_->simplify(); if (left_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(left_child_)->getValue() == 0) { return std::make_shared<Constant>(0); } else if (right_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(right_child_)->getValue() == 0) { return std::make_shared<Constant>(1); } else if (right_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(right_child_)->getValue() == 1) { return left_child_; } else { return shared_from_this(); } } string Power::getStringRepresentation() const { std::stringstream ss; ss << "(" << left_child_->getString() << ")^(" << right_child_->getString() << ")"; return ss.str(); } Multiplication::Multiplication(Node_ptr left_child, Node_ptr right_child) : BinaryNode(left_child, right_child) { operator_ = Operator::Multiplication; } Multiplication::~Multiplication() { ; } Node_ptr Multiplication::diff(char symbol) const { return std::make_shared<Addition>( std::make_shared<Multiplication>( left_child_->diff(symbol), right_child_ ), std::make_shared<Multiplication>( left_child_, right_child_->diff(symbol) ) ); } Node_ptr Multiplication::simplify() { left_child_ = left_child_->simplify(); right_child_ = right_child_->simplify(); if (left_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(left_child_)->getValue() == 0) { return std::make_shared<Constant>(0); } else if (right_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(right_child_)->getValue() == 0) { return std::make_shared<Constant>(0); } else if (left_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(left_child_)->getValue() == 1) { return right_child_; } else if (right_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(right_child_)->getValue() == 1) { return left_child_; } else { return shared_from_this(); } } string Multiplication::getStringRepresentation() const { std::stringstream ss; ss << left_child_->getString() << "*" << right_child_->getString(); return ss.str(); } Addition::Addition(Node_ptr left_child, Node_ptr right_child) : BinaryNode(left_child, right_child) { operator_ = Operator::Addition; } Addition::~Addition() { ; } Node_ptr Addition::diff(char symbol) const { return std::make_shared<Addition>( left_child_->diff(symbol), right_child_->diff(symbol) ); } Node_ptr Addition::simplify() { left_child_ = left_child_->simplify(); right_child_ = right_child_->simplify(); if ( left_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(left_child_)->getValue() == 0) { return right_child_; } else if ( right_child_->getOperatorType() == Operator::Constant && std::dynamic_pointer_cast<Constant>(right_child_)->getValue() == 0) { return left_child_; } else if (left_child_->getOperatorType() == Operator::Constant && right_child_->getOperatorType() == Operator::Constant) { return std::make_shared<Constant>( std::dynamic_pointer_cast<Constant>(left_child_)->getValue() + std::dynamic_pointer_cast<Constant>(right_child_)->getValue() ); } else { return shared_from_this(); } } string Addition::getStringRepresentation() const { std::stringstream ss; ss << left_child_->getString() << "+" << right_child_->getString(); return ss.str(); }
true
4ed6087d3227a75e33f3b953d3b8b54ec764cca8
C++
SmileyJs/leetcode
/152_maxProductSubArray.cpp
UTF-8
1,043
3.4375
3
[]
no_license
#include <iostream> #include <vector> #include <limits.h> using namespace std; int maxProduct(vector<int>& nums) { int size = nums.size(); if (0 == size) { return 0; } int crtMax = nums[0]; // for (int i = 0; i != size; ++i) { // int max = 1; // for (int j = i; j != size; ++j) { // max *= nums[j]; // if (max > crtMax) { // crtMax = max; // } // } // } int max = nums[0]; int min = nums[0]; for (int i = 1; i != size; ++i) { int x = max; int y = min; max = std::max(nums[i], std::max(x * nums[i], y * nums[i])); min = std::min(nums[i], std::min(y * nums[i], x * nums[i])); if (crtMax < max) { crtMax = max; } cout << max << " " << min << endl; } return crtMax; } int main(int argc, char const *argv[]) { vector<int> vec = {2, 3, -2, 4}; auto ret = maxProduct(vec); cout << "result = " << ret << endl; return 0; }
true
b58ce757613daaf5564b335df45f2b047b6a98ec
C++
Arjunkhera/Competitive_Programming
/algo+ds/LinkedLists/LinkedList.cpp
UTF-8
2,402
3.984375
4
[]
no_license
#include "LinkedList.h" // Three ways to pass the head pointer // Pass the head pointer by reference : Easiest and will be used throughout the code void insertAtHead(node* &head,int data){ node* newNode = new node(data); newNode->next = head; head = newNode; } // Pass the head pointer and return the changed head node* insertAtHead(node* head,long data){ // long used to prevent function overloading error with (node*&,int) node* newNode = new node(data); newNode->next = head; head = newNode; return head; } // Pass a pointer to the head pointer void insertAtHead(node** head,int data){ node* newNode = new node(data); newNode->next = *head; *head = newNode; } // insert data at tail void insertAtTail(node* &head,int data){ node* newNode = new node(data); if(head == nullptr){ head = newNode; return; } node *temp = head; while(temp->next != nullptr) temp = temp->next; temp->next = newNode; } // returns the node previous to the node whose data is given node* findNode(node* head,int data){ if(head == nullptr) return nullptr; if(head->data == data) return head; node* prev = head; while(prev->next != nullptr && prev->next->data != data) prev = prev->next; if(prev->next == nullptr) return nullptr; return prev; } // to delete an element from the list bool removeElement(node* &head,int data){ node* prev = findNode(head,data); if(prev == nullptr) return false; node* cur; if(prev == head){ cur = prev; head = prev->next; } else { cur = prev->next; prev->next = cur->next; } delete cur; return true; } // read data untill you encounter -1 void readList(node* &head){ int x; std::cin>>x; while(x!=-1){ // for explanation of concepts // pass by reference insertAtHead(head,x); // return pointer //head = insertAtHead(head,x); // pass double pointer //insertAtHead(&head,x); std::cin>>x; } } // print the list void display(node* head){ while(head != nullptr){ std::cout<<head->data<<" "; head = head->next; } } // Find length recursively int lengthRecursive(node* head){ if(head == nullptr) return 0; return 1+lengthRecursive(head->next); } // Find length iteratively int lengthIterative(node* head){ int length = 0; while(head != nullptr){ length++; head = head->next; } return length; }
true
9aaedbb3cbf98a13a660472538323ade78637d19
C++
SPOTechnology/FourInARow
/C++/trainGenetic/src/weight.h
UTF-8
480
3.078125
3
[]
no_license
#ifndef WEIGHT_H_INCLUDED #define WEIGHT_H_INCLUDED #include <time.h> long double random(double _min, double _max); class Weight { public: void setVal(long double r) { value = r; } long double val() { return value; } void mutate() { if (random(0, 1) < 0.5) { value += random(-0.5, 0.5); if (value > 1) { value = 1; } else if (value < -1) { value = -1; } } } long double value = 0; }; #endif // WEIGHT_H_INCLUDED
true
ac59212f0ab891d9681adf463d5ab160ebf99434
C++
pz1971/Online-Judge-Solutions
/HackerRank/Components in a graph.cpp
UTF-8
788
2.515625
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; typedef long long LL ; int n ; int root[30005] ; void init(){ for(int i = 1 ; i <= n + n ; i++){ root[i] = i ; } } int find(int u){ if(root[u] == u) return u ; return root[u] = find(root[u]) ; } void insert(int u, int v){ int a = find(u) ; int b = find(v) ; if(a == b) return ; root[a] = b ; } int main(){ cin >> n ; init() ; int u, v; for(int i = 0 ; i < n; i++){ cin >> u >> v; insert(u, v) ; } map<int,int> cnt ; for(int i = 1 ; i <= n + n ; i++){ cnt[find(i)]++ ; } int mx ; mx = cnt.begin()->second ; for(auto i : cnt){ mx = max(mx, i.second) ; } int mn = mx ; for(auto i : cnt){ if(i.second != 1) mn = min(mn, i.second) ; } cout << mn << " " << mx << endl ; return 0; }
true
ff27a3d18de02b729f2ba2b0e9bc1553a6e41661
C++
tuanpm-oxf/GraphTempp
/GraphGenerator.cpp
UTF-8
1,835
3.140625
3
[]
no_license
#include <iostream> #include <vector> #include <string> #include <stdio.h> #include <stdlib.h> #include <random> #include <fstream> #include <time.h> #include <set> using namespace std; // Số lượng định và tên file output const char * filename = "DenseGraph-100.bin"; const int nVertices = 100; std::random_device rd; std::mt19937 gen(rd()); // Ham sinh gia tri float ngau nhien trong khoang (0.0, 5.0) std::uniform_real_distribution<> dis(0.0, 5.0); // Ham doc, ghi binary template<typename T> ostream& binary_write(ostream& stream, const T& value){ return stream.write(reinterpret_cast<const char*>(&value), sizeof(T)); } template<typename T> istream& binary_read(istream& stream, T& value){ return stream.read(reinterpret_cast<char*>(&value), sizeof(T)); } // Sinh graph dang binary void DenseGraphBinary(){ ofstream fo(filename, ofstream::binary); std::uniform_int_distribution<> idis(1, 255); binary_write(fo, nVertices); unsigned char d; for(int i = 0; i < nVertices; i++) { for(int j = 0; j < nVertices; ++j) { d = 0; if (i != j) d = idis(gen); binary_write(fo, d); } } fo.close(); } // Sinh graph dang float void DenseGraphFloat(){ FILE *file = fopen(filename, "wb"); float d; fprintf(file, "%d\n", nVertices); for(int i = 0; i < nVertices; i++) { for(int j = 0; j < nVertices; ++j) { d = 0.0; if (i != j) d = dis(gen); fprintf(file, "%.2f ", d); } fprintf(file, "\n"); } fclose(file); } int main() { time_t start = clock(); DenseGraphBinary(); printf("\n==== Time using to generate data: %.2fs\n", (double)(clock() - start)/CLOCKS_PER_SEC); return 0; }
true
59ace31381d00104a073e2db7897cf3374511898
C++
tylerlthompson/SailCam
/arduino/SailCam_MK5/include/settings/system_configuration.h
UTF-8
1,105
2.65625
3
[]
no_license
#ifndef SYSTEM_CONFIGURATION_H #define SYSTEM_CONFIGURATION_H #define settings_length 15 #include <settings/system_setting.h> struct SettingKeyValuePair { char *key; SystemSetting *value; }; class SystemConfiguration { private: SettingKeyValuePair settings_map[settings_length]; const char* settings_defaults[settings_length][2]; void read_settings_defaults(); public: SystemConfiguration(); ~SystemConfiguration(); int get_settings_length(); SystemSetting* get_setting(char* key); SystemSetting* get_setting(const char* key); void set_setting(char* key, char* value, int value_size); void update_setting(char* key, char* value, int value_size); void update_setting(char* key, int value); const char** get_settings_defaults() { return *this->settings_defaults; }; const char* get_settings_defaults_key(int index); const char* get_settings_defaults_value(int index); bool verify_setting_key(char* key); SettingKeyValuePair* get_settings_map() { return this->settings_map; }; void increment_counter(char* key); }; #endif
true
b551a49a51a1f567bd8baf22b137e4c37c5e9d70
C++
noshaba/TrackBall
/ebvassignment01/ueb01_nosh/cutlery/cutlery/cutlery_nosh.cc
UTF-8
12,224
2.96875
3
[]
no_license
#ifdef _WIN32 #define WIN32 #endif #ifdef WIN32 #define _USE_MATH_DEFINES #endif #include <math.h> #include <opencv2/opencv.hpp> #include <stdio.h> #include <assert.h> #include <vector> using namespace std; using namespace cv; typedef double Matrix2x2[2][2]; //************ Interval, DecompositionIntoRegions //! A horizontal stripe (interval) in a binary image. class Interval { public: //! An interval consists of all points (x,y) with xLo<=x && x<=xHi int xLo, xHi, y; //! index of the connected component of black regions to which this interval belongs int region; //! auxiliary pointer for union-find. /*! Pointer to an earlier (when scanning rowwise) interval in the same region. If it points to itself, this is the first interval. */ Interval* parent; Interval() :xLo(0), xHi(0), y(0), region(0), parent(NULL) {}; Interval(int xLo, int xHi, int y) :xLo(xLo), xHi(xHi), y(y), region(0), parent(NULL) { } }; //! An black an white image decomposed into horizontal Intervals /*! Each interval belongs to a certain region. */ class RegionSet { public: vector<Interval> rle; //! Binarizes and run length codes image. /*! After execution rle contains all horizontal intervals of pixels BELOW threshold that are at least minLength long. The intervals are sorted by top to bottom and within the same y coordinate left to right. All regions are set to 0. */ void thresholdAndRLE(Mat_<uchar>& image, uchar threshold, int minLength); //! Finds connected regions in the rle intervals /*! Label the regions by setting \c .region in all intervals of a connected region. The regions are numbered consecutively. */ void groupRegions(); protected: //! Auxiliary routine for groupRegions /*! Returns, whether run and flw touch and run is one line below follow. */ bool touch(Interval* run, Interval* flw); //! Auxiliary routine for groupRegions /*! Returns, whether run is one line below flw and horizontally ahead or more than one line below flw. */ bool ahead(Interval* run, Interval* flw); //! Auxiliary routine for unite. /*! Finds the root of \c iv. This is the first interval of the connected component. It modifies all intervals along the way to point directly to the final parent. */ void pathCompress(Interval* iv); //! Auxiliary routine for group regions. /*! Unites the connected components of iv1 and iv2. */ void unite(Interval* iv1, Interval* iv2); //! Auxiliary routine for groupRegion /*! Initializes the .parent pointer of all intervals to point to itself, declaring every interval as a single region. */ void initialize(); //! Auxiliary routine for groupRegion /*! Assumes that the regions are defined by the .parent pointer (All interval having the same root are one region) and gives the regions (in .region) consecutives numbers starting with 0. */ void setRegionIndex(); }; void RegionSet::thresholdAndRLE(Mat_<uchar>& image, uchar threshold, int minLength) { unsigned int length; for (unsigned int i = 0; i < image.rows; ++i){ length = 0; for (unsigned int j = 0; j < image.cols; ++j){ if (image(i, j) > threshold){ if (length >= minLength) rle.push_back(Interval(j - length, j - 1, i)); length = 0; } else { ++length; } } if (length >= minLength) rle.push_back(Interval(image.cols - length, image.cols - 1, i)); } } void RegionSet::pathCompress(Interval* iv) { Interval *root, *buffer; root = iv; while (root->parent != root) root = root->parent; while (iv != root) { buffer = iv->parent; iv->parent = root; iv = buffer; } } void RegionSet::unite(Interval* iv1, Interval* iv2) { pathCompress(iv1); pathCompress(iv2); iv1->parent < iv2->parent ? iv2->parent->parent = iv1->parent : iv1->parent->parent = iv2->parent; } void RegionSet::initialize() { std::vector<Interval>::iterator it; for (it = rle.begin(); it != rle.end(); it++) it->parent = &(*it); } void RegionSet::setRegionIndex() { std::vector<Interval>::iterator iv; iv = rle.begin(); int regionCtr = 0; while (iv != rle.end()) { if (iv->parent == &(*iv)) { iv->region = regionCtr; regionCtr++; } else iv->region = iv->parent->region; iv++; } } bool RegionSet::touch(Interval* run, Interval* flw) { return run->y == flw->y + 1 && run->xHi >= flw->xLo && flw->xHi >= run->xLo; } bool RegionSet::ahead(Interval* run, Interval* flw) { return (run->y > flw->y + 1) || (run->y == flw->y + 1 && run->xHi > flw->xHi); } void RegionSet::groupRegions() { initialize(); std::vector<Interval>::iterator flw, run; flw = run = rle.begin(); while (run != rle.end()) { if (touch(&(*run), &(*flw))) unite(&(*run), &(*flw)); if (ahead(&(*run), &(*flw))) flw++; else run++; } setRegionIndex(); } //************* a region and it's features //! All features extracted for a region class Region { public: //! Sum of 1 (area), x, y, x^2, xy and y^2 /*! The sum is taken over all pixel in the region. \c integral can be directly used as area. \c integralX and \c integralY are used to compute the center of gravity (\c centerX, \c centerY) \c integralXX, \c integralXY and \c integralYY are used to compute the \c mainAxis and corresponding \c smallLength and \c largeLength. */ double integral, integralX, integralY, integralXX, integralXY, integralYY; //! center of gravity of the region double centerX, centerY; //! Angle of the larges inertial extension. /*! \c smallLength and \c largeLength are the radii of an ellipse that would have the same inertial properties. */ double mainAxis, smallLength, largeLength; //! Label (Teller, Messer, Gabel, Loeffel) assigned to the region string label; //!constructor for an empty region Region() :integral(0), integralX(0), integralY(0), integralXX(0), integralXY(0), integralYY(0), centerX(0), centerY(0), mainAxis(0), smallLength(0), largeLength(0) {} //! Compute second order moments from run length code for each region /*! Sets \c Integral, \c IntegralX, \c IntegralY, \c IntegralXX, \c IntegralXY, \c IntegralYY in \c region from \c decomposition */ static void computeMoments(vector<Region>& region, const RegionSet& decomposition); //! Compute center and inertial axes from the second order moments /*! Sets \c centerX, \c centerY, \c mainAxis, \c smallLength, \c largeLength. */ void computeFeatures(); //! Determine label from area and inertial axes /*! Sets \c label */ void classify(); protected: //! Auxiliary routine for finding inertial axis. /*! Computes an eigenvalue decomposition of a symmetric 2x2 matrix in a way, that is stable even for degenerated eigenvalues \c (cos(phi), sin(phi)) will be an eigenvector with eigenvalue \c l0 and \c (-sin(phi),cos(phi)) will be the orthogonal eigenvector with eigenvalue \c l1. \c l0>=l1. */ static void eigenDecompositionSymmetric(const Matrix2x2& a, double& phi, double& l0, double& l1); }; void Region::eigenDecompositionSymmetric(const Matrix2x2& a, double& phi, double& l0, double& l1) { double ll0, ll1; double denom = a[1][1] - a[0][0], nom = -2 * a[1][0]; if (denom != 0 || nom != 0) phi = atan2(nom, denom) / 2; else phi = 0; double c = cos(phi); double s = sin(phi); double c2 = c*c, s2 = s*s, cs = c*s; ll0 = c2*a[0][0] + 2 * cs*a[1][0] + s2*a[1][1]; ll1 = s2*a[0][0] - 2 * cs*a[1][0] + c2*a[1][1]; if (ll0<ll1) { if (phi>0) phi -= M_PI / 2; else phi += M_PI / 2; l0 = ll1; l1 = ll0; } else { l0 = ll0; l1 = ll1; } } void Region::computeMoments(vector<Region> &region, const RegionSet &decomposition) { std::vector<Interval> rle = decomposition.rle; Interval I; for (unsigned int i = 0; i < rle.size(); ++i){ I = rle[i]; if (region.size() == I.region){ region.push_back(Region()); } region[I.region].integral += I.xHi - I.xLo + 1; region[I.region].integralX += (I.xHi * (I.xHi + 1) - I.xLo * (I.xLo - 1)) * .5; region[I.region].integralY += (I.xHi - I.xLo + 1) * I.y; region[I.region].integralXX += (std::pow(I.xHi + .5, 3) - std::pow(I.xLo - .5, 3)) / 3.0; region[I.region].integralXY += (I.xHi * (I.xHi + 1) - I.xLo * (I.xLo - 1)) * I.y * .5; region[I.region].integralYY += (I.xHi - I.xLo + 1) * (I.y * I.y + 1.0 / 12.0); } } void Region::computeFeatures() { double dIntegralXX, dIntegralXY, dIntegralYY, eig1, eig2; centerX = integralX / integral; centerY = integralY / integral; dIntegralXX = integralXX / integral - centerX * centerX; dIntegralXY = integralXY / integral - centerX * centerY; dIntegralYY = integralYY / integral - centerY * centerY; eigenDecompositionSymmetric({ { dIntegralXX, dIntegralXY }, { dIntegralXY, dIntegralYY } }, mainAxis, eig1, eig2); largeLength = 2 * std::sqrt(eig1); smallLength = 2 * std::sqrt(eig2); } void Region::classify() { if (integral >= 5000){ int ratio = largeLength / smallLength; switch (ratio) { case 1: label = "Plate"; break; case 7: case 8: label = "Spoon"; break; case 10: case 11: label = "Fork"; break; case 14: case 15: label = "Knife"; break; default: break; } } } //************ GUI //! paint the extracted Intervals in \c rle onto \c img for displaying /*! The color is chosen with a cyclic color table according to \c .region */ void paintDecomposition(Mat& img, const RegionSet& decomposition) { Scalar color[6] = { CV_RGB(255, 0, 0), CV_RGB(0, 255, 0), CV_RGB(255, 255, 0), CV_RGB(0, 0, 255), CV_RGB(255, 0, 255), CV_RGB(0, 255, 255) }; for (int i = 0; i<(int)decomposition.rle.size(); i++) { line(img, Point(decomposition.rle[i].xLo, decomposition.rle[i].y), Point(decomposition.rle[i].xHi, decomposition.rle[i].y), color[decomposition.rle[i].region % 6]); } } //! Paint the center of gravity / intertial axis and labels for all regions onto \c img /*! The routine paints a cross at the center with the lines of the cross corresponding to the radii of an ellipse that would have the asme intertial properties. */ void paintFeatures(Mat& img, const vector<Region>& features) { for (int i = 0; i<(int)features.size(); i++) { const Region* rg = &features[i]; double c = cos(rg->mainAxis), s = sin(rg->mainAxis); // paint +/-largeLenge in direction (c,s) from the center of gravity line(img, Point((int)(rg->centerX + rg->largeLength*c), (int)(rg->centerY + rg->largeLength*s)), Point((int)(rg->centerX - rg->largeLength*c), (int)(rg->centerY - rg->largeLength*s)), CV_RGB(255, 255, 255)); // paint +/-smallLength in direction (-s,c) orthogonal to (c,s) from the center of gravity line(img, Point((int)(rg->centerX - rg->smallLength*s), (int)(rg->centerY + rg->smallLength*c)), Point((int)(rg->centerX + rg->smallLength*s), (int)(rg->centerY - rg->smallLength*c)), CV_RGB(255, 255, 255)); putText(img, rg->label, Point((int)rg->centerX, (int)rg->centerY), FONT_HERSHEY_PLAIN, 2, CV_RGB(255, 255, 255)); } } int main(int argc, char** argv) { namedWindow("Segmented Image", CV_WINDOW_NORMAL); for (int i = 0; 1 + i<argc; i++) { const char* filename = argv[i + 1]; // Load the source image as a grayscale image for processing Mat_<uchar> src = imread(filename, 0); // 0 means load as grayscale // Load the same image as a color image for displaying and painting onto Mat dst = imread(filename, 1); // 1 means load as color (for displaying) if (!src.data) { printf("Image could not be loaded.\n"); return -1; } // measure time int64 time1, time2; // Do the computer vision computation time1 = getTickCount(); RegionSet decomposition; int threshold = 80; int minLength = 2; decomposition.thresholdAndRLE(src, threshold, minLength); decomposition.groupRegions(); vector<Region> region; Region::computeMoments(region, decomposition); for (int i = 0; i<(int)region.size(); i++) { region[i].computeFeatures(); region[i].classify(); } time2 = getTickCount(); // measure time printf("Computation time %fs\n", (time2 - time1) / getTickFrequency()); // paint everything paintDecomposition(dst, decomposition); paintFeatures(dst, region); // show as a window in the GUI imshow("Segmented Image", dst); waitKey(0); //imwrite ("result.png", dst); // save the segmented and labeled result } return 0; }
true
515dbe6c18e2046b2b5f77b6ab958e9214f153c0
C++
ild-games/Ancona
/Engine/Src/Ancona/Util2D/Collision/Box3.hpp
UTF-8
1,509
3.359375
3
[ "MIT" ]
permissive
#ifndef Ancona_Util2D_Box3_H_ #define Ancona_Util2D_Box3_H_ #include <SFML/System.hpp> namespace ild { /** * @brief Represents a box in 3rd space with a dimension, position, * and rotation * @author Jeff Swenson */ class Box3 { public: /** * @brief Initialize a 3 dimensional box * * @param position The position of the box * @param dimension The size of the box * @param rotation The rotation of the box */ Box3(const sf::Vector3f & position, const sf::Vector3f & dimension, const sf::Vector2f & rotation=sf::Vector2f()); /** * @brief Position of the box. The position is at the center * of the box. */ sf::Vector3f Position; /** * @brief Dimension of the box: Length X Width X Height */ sf::Vector3f Dimension; /** * @brief The rotation of the box. */ sf::Vector2f Rotation; /** * @brief Test if the two boxes intersect * * @param box Box to be tested * * @return True if they intersect. False otherwise. */ bool Intersects(const Box3 & box); /** * @brief Test if the box contains the argument box. * * @param box Box that may be contained. * * @return True if the box is contained. False otherwise. */ bool Contains(const Box3 & box); }; } #endif
true
575ab429b5c046e8546d53def200e5e9493841bc
C++
chenyanhang/chen_yanhang
/chap07/ex_27/main.cpp
UTF-8
427
2.828125
3
[]
no_license
#include <iostream> #include<array> using namespace std; int main() { array<int,1000>n; for(size_t i=0;i<n.size();i++) { n[i]=1; } for(int i=2;i<=999;i++) { int c=0; for(int a=2;c<=999;a++) { n[c]=0; c=a*i; } } for(int i=2;i<=999;i++) { if(n[i]!=1) cout<<""; else cout<<i<<" "; } }
true
d276eeec24f0a02a2fcaa5b9d52d58637c8c86c4
C++
nathanPro/MAC5750
/test/helper.cpp
UTF-8
5,388
2.875
3
[]
no_license
#include "helper.h" #include "error.h" #include "parser.h" #include "translate.h" #include "gtest/gtest.h" class HelperTest : public ::testing::Test { protected: TranslationUnit tu; bool no_err; helper::meta_data data; HelperTest() : tu("../input/sample.miniJava"), no_err(tu.check()), data(tu.syntax_tree) { } }; TEST_F(HelperTest, traverseASTbuildsMetaData) { EXPECT_TRUE(no_err); } TEST_F(HelperTest, MetaDataRecordClasses) { std::string const main_class("Factorial"); std::string const help_class("Fac"); std::string const fake_class("Fake"); EXPECT_EQ(data.count(main_class), 1); EXPECT_EQ(data.count(help_class), 1); EXPECT_EQ(data.count(fake_class), 0); } TEST_F(HelperTest, MetaDataDistinguishesMethodFromVariable) { EXPECT_EQ(data["Fac"]["t1"], helper::kind_t::var); EXPECT_EQ(data["Fac"]["Compute"], helper::kind_t::notfound); EXPECT_EQ(data["Fac"]["ComputeFac"], helper::kind_t::method_def); } TEST_F(HelperTest, MetaDataRecordLayout) { EXPECT_EQ(data["Fac"].variable["t1"], 0); EXPECT_EQ(data["Fac"].variable["t2"], 8); EXPECT_EQ(data["Factorial"].size(), 0); EXPECT_EQ(data["Fac"].size(), 16); EXPECT_EQ(data["Child"].size(), data["Fac"].size()); } TEST_F(HelperTest, MetaDataHandlesInheritance) { EXPECT_EQ(data["Fac"]["ComputeFac"], helper::kind_t::method_def); EXPECT_EQ(data["Child"]["ComputeFac"], helper::kind_t::method_inh); EXPECT_EQ(data["Fac"].method("ComputeFac").layout["num_aux"], data["Child"].method("ComputeFac").layout["num_aux"]); EXPECT_EQ(data["Fac"].method("ComputeFac").layout["not_aux"], data["Child"].method("ComputeFac").layout["not_aux"]); } TEST_F(HelperTest, MetaDataKeepsNames) { EXPECT_EQ(data["Child"].name, std::string("Child")); EXPECT_EQ(data["Child"].method("ComputeFac").name, std::string("ComputeFac")); } TEST_F(HelperTest, MetaDataWorksOutOfOrder) { TranslationUnit unordered("../input/unordered_classes.miniJava"); EXPECT_TRUE(unordered.check()); EXPECT_NO_THROW(helper::meta_data(unordered.syntax_tree)); } TEST_F(HelperTest, MetaDataHandlesDeeperInheritsLayout) { TranslationUnit unordered("../input/unordered_classes.miniJava"); EXPECT_TRUE(unordered.check()); data = helper::meta_data(unordered.syntax_tree); EXPECT_EQ(data["A"]["t1"], helper::kind_t::var); EXPECT_EQ(data["B"]["t1"], helper::kind_t::var); EXPECT_EQ(data["C"]["t1"], helper::kind_t::var); EXPECT_EQ(data["C"].variable["t1"], 0); EXPECT_EQ(data["C"].variable["t2"], 8); EXPECT_EQ(data["B"].variable["t1"], 0); EXPECT_EQ(data["B"].variable["t2"], 8); EXPECT_EQ(data["B"].variable["t3"], 16); EXPECT_EQ(data["A"].variable["t1"], 0); EXPECT_EQ(data["A"].variable["t2"], 8); EXPECT_EQ(data["A"].variable["t3"], 16); EXPECT_EQ(data["A"].variable["t4"], 24); } TEST_F(HelperTest, MetaDataHandlesDeeperInheritanceMethods) { TranslationUnit unordered("../input/unordered_classes.miniJava"); EXPECT_TRUE(unordered.check()); data = helper::meta_data(unordered.syntax_tree); EXPECT_EQ(data["A"]["calculate"], helper::kind_t::method_inh); EXPECT_EQ(data["B"]["calculate"], helper::kind_t::method_inh); EXPECT_EQ(data["C"]["calculate"], helper::kind_t::method_def); EXPECT_EQ(data["D"]["calculate"], helper::kind_t::method_inh); EXPECT_EQ(data["E"]["calculate"], helper::kind_t::method_def); EXPECT_EQ(data["A"].method("calculate").layout["num_aux"], data["C"].method("calculate").layout["num_aux"]); EXPECT_EQ(data["A"].method("calculate").layout["not_aux"], data["C"].method("calculate").layout["not_aux"]); } TEST_F(HelperTest, MetaDataDetectsCyclicDepdendencies) { TranslationUnit cycle("../input/cyclic_classes.miniJava"); EXPECT_TRUE(cycle.check()); EXPECT_THROW(helper::meta_data(cycle.syntax_tree), helper::cyclic_classes); } TEST_F(HelperTest, MetaDataStoresStackLayout) { EXPECT_EQ(data["Fac"].method("ComputeFac").layout["num_aux"], 0); EXPECT_EQ(data["Fac"].method("ComputeFac").layout["not_aux"], 8); } TEST_F(HelperTest, MetaDataStoresFormalList) { EXPECT_EQ(data["Fac"].method("ComputeFac").arglist.size(), 1); auto const& [type, name] = data["Fac"].method("ComputeFac").arglist[0]; EXPECT_TRUE(Grammar::holds<AST::integerType>(type)); EXPECT_EQ(name, std::string("num")); } TEST_F(HelperTest, MetaDataStoresReturnType) { EXPECT_TRUE(Grammar::holds<AST::integerType>( data["Fac"].method("ComputeFac").return_type)); TranslationUnit sample4("../input/sample4.miniJava"); EXPECT_TRUE(sample4.check()); data = helper::meta_data(sample4.syntax_tree); EXPECT_EQ(Grammar::get<AST::classType>( data["Fac"].method("increase").return_type) .value, std::string("Fac")); EXPECT_EQ(Grammar::get<AST::classType>( data["Fac"].method("ComputeFac").return_type) .value, std::string("Fac")); } TEST_F(HelperTest, HelperMangles) { EXPECT_EQ(helper::mangle("Calculator", "main"), "_ZCalculator_main"); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
2debb68f05a6beffd4c5ce5368dbabe4ad9a4558
C++
InsightSoftwareConsortium/ITK
/Modules/Filtering/ImageCompose/test/itkComposeRGBImageFilterTest.cxx
UTF-8
3,273
2.625
3
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", ...
permissive
/*========================================================================= * * Copyright NumFOCUS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include <iostream> #include "itkRGBPixel.h" #include "itkComposeImageFilter.h" int itkComposeRGBImageFilterTest(int, char *[]) { using PixelType = unsigned char; using InputImageType = itk::Image<PixelType, 3>; using RGBPixelType = itk::RGBPixel<unsigned char>; using OutputImageType = itk::Image<RGBPixelType, 3>; using FilterType = itk::ComposeImageFilter<InputImageType, OutputImageType>; using RegionType = InputImageType::RegionType; using SizeType = InputImageType::SizeType; using IndexType = InputImageType::IndexType; auto filter = FilterType::New(); auto redImage = InputImageType::New(); auto greenImage = InputImageType::New(); auto blueImage = InputImageType::New(); SizeType size; size[0] = 2; size[1] = 2; size[2] = 2; IndexType start; start.Fill(0); RegionType region; region.SetIndex(start); region.SetSize(size); redImage->SetRegions(region); greenImage->SetRegions(region); blueImage->SetRegions(region); redImage->Allocate(); greenImage->Allocate(); blueImage->Allocate(); redImage->FillBuffer(29); greenImage->FillBuffer(51); blueImage->FillBuffer(83); filter->SetInput1(redImage); filter->SetInput2(greenImage); filter->SetInput3(blueImage); try { filter->Update(); } catch (const itk::ExceptionObject & excp) { std::cerr << "Exception caught !" << std::endl; std::cerr << excp << std::endl; return EXIT_FAILURE; } OutputImageType::Pointer rgbImage = filter->GetOutput(); using OutputIterator = itk::ImageRegionIterator<OutputImageType>; using InputIterator = itk::ImageRegionIterator<InputImageType>; InputIterator ir(redImage, region); InputIterator ig(greenImage, region); InputIterator ib(blueImage, region); OutputIterator ot(rgbImage, region); ir.GoToBegin(); ig.GoToBegin(); ib.GoToBegin(); ot.GoToBegin(); using OutputPixelType = OutputImageType::PixelType; while (!ot.IsAtEnd()) { OutputPixelType outp = ot.Get(); if (ir.Get() != outp.GetRed()) { std::cerr << "Error in red component" << std::endl; return EXIT_FAILURE; } if (ig.Get() != outp.GetGreen()) { std::cerr << "Error in green component" << std::endl; return EXIT_FAILURE; } if (ib.Get() != outp.GetBlue()) { std::cerr << "Error in blue component" << std::endl; return EXIT_FAILURE; } ++ot; ++ir; ++ig; ++ib; } std::cout << "Test Passed !" << std::endl; return EXIT_SUCCESS; }
true
fed54456a7e27ed00e5e5ace0912047b10f4eaed
C++
FauxFaux/tinies
/unrequireadmin.cpp
UTF-8
3,089
2.578125
3
[ "MIT" ]
permissive
#define NTDDI_VERSION NTDDI_VISTA #define _WIN32_WINNT 0x0600 #include <windows.h> #include <iostream> #include <stdexcept> #include <string> #ifndef LOAD_LIBRARY_AS_IMAGE_RESOURCE #define LOAD_LIBRARY_AS_IMAGE_RESOURCE 0x00000020 #endif using std::cout; using std::endl; using std::string; void ErrorHandler(const char* s) { throw std::exception(s); } int wmain(int argc, wchar_t*argv[]) { try { HRSRC hResLoad; // handle to loaded resource HMODULE hExe = NULL; // handle to existing .EXE file HRSRC hRes; // handle/ptr. to res. info. in hExe HANDLE hUpdateRes; // update resource handle char *lpResLock; // pointer to resource data BOOL result; if (argc != 2) ErrorHandler("Filename please."); // Load the .EXE file that contains the dialog box you want to copy. hExe = LoadLibraryEx(argv[1], NULL, LOAD_LIBRARY_AS_IMAGE_RESOURCE); //hExe = LoadLibrary(argv[1]); if (hExe == NULL) ErrorHandler("Could not load exe."); // Locate the dialog box resource in the .EXE file. hRes = FindResource(hExe, MAKEINTRESOURCE(1), MAKEINTRESOURCE(RT_MANIFEST)); if (hRes == NULL) ErrorHandler("Could not locate resource."); // Load the dialog box into global memory. hResLoad = (HRSRC)LoadResource(hExe, hRes); if (hResLoad == NULL) ErrorHandler("Could not load dialog box."); // Lock the dialog box into global memory. lpResLock = (char *)LockResource(hResLoad); if (lpResLock == NULL) ErrorHandler("Could not lock dialog box."); string manifest(lpResLock, SizeofResource(hExe, hRes)); // Clean up the loaded library. if (!FreeLibrary(hExe)) ErrorHandler("Could not free executable."); // "Parse" the XML to terminate the trustInfo element. string::size_type begin = manifest.find("<trustInfo"); if (begin == string::npos) ErrorHandler("Start tag not found, no operation may be necessary?"); const string trustinfo("</trustInfo>"); string::size_type end = manifest.find(trustinfo, begin); if (end == string::npos) ErrorHandler("End tag not found."); const string::size_type num_to_replace = end - begin + trustinfo.size(); manifest.replace(begin, num_to_replace, num_to_replace, ' '); // Open the file to which you want to add the dialog box resource. hUpdateRes = BeginUpdateResource(argv[1], FALSE); if (hUpdateRes == NULL) ErrorHandler("Could not open file for writing."); // Overwrite the resource. result = UpdateResource(hUpdateRes, // update resource handle RT_MANIFEST, MAKEINTRESOURCE(1), MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // neutral language, guess/hack. (LPVOID)manifest.c_str(), manifest.size()); if (result == FALSE) ErrorHandler("Could not add resource."); if (!EndUpdateResource(hUpdateRes, FALSE)) ErrorHandler("Could not write changes to file."); } catch (std::exception& e) { std::cout << e.what() << "\n" << "Error code: " << GetLastError() << "." << std::endl; return 1; } return 0; }
true
1213822fbaa38feb54249b2214869f200e1a0397
C++
LastStranger0/PPVIS
/PIVAS.LAB2/PIVAS.LAB2/Fishes.cpp
UTF-8
2,160
3.234375
3
[]
no_license
#include "Fishes.h" #include <iostream> #include <math.h> Fishes::Fishes(): Animals(), dangerous(0), isPredator(0){} Fishes::Fishes(std::string Name, bool isDanger) : Animals(Name), dangerous(isDanger){ if (dangerous == 1) isPredator = 1; if (isPredator == 0) dangerous = 0; } Fishes::~Fishes() { } void Fishes::NameAnimal() { Animals::NameAnimal(); hunger -= 2; } void Fishes::setDangerous(bool temp) { dangerous = temp; if (dangerous == 1) isPredator = 1; } std::string Fishes::isDangerous() { if (dangerous) return "is dangerous"; else return "isn't dangerous"; hunger -= 2; } std::string Fishes::IsPredator() { if (isPredator) return "It is a predator"; else return "It's not a predator"; hunger -= 2; } void Fishes::swim(bool temp) { isSwimmingNow = temp; } void Fishes::swimmnig(double x, double y, double z) { Animals::moveto(x, y, z); hunger -= pow(pow(x, 2) + pow(y, 2) + pow(z, 2), 0.5); die(); } void Fishes::getHunger() { gethunger(); } void Fishes::eating(std::string whatEat) { if (IsPredator() == "It is a predator") { if (whatEat == "fish" || whatEat == "meat" || whatEat == "people" || whatEat == "bird" || whatEat == "frog") { NameAnimal(); std::cout << " eat " << whatEat << std::endl << " degree of hunger now: "; gethunger(); std::cout << "\n"; hunger += 50; if (hunger > 100) { hunger == 100; } } else{ NameAnimal(); std::cout << " don't eat " << whatEat << std::endl; } } if (IsPredator() == "It's not a predator") { if (whatEat == "grass" || whatEat == "plankton" || whatEat == "weed" || whatEat == "seaweed" || whatEat == "leaves") { NameAnimal(); std::cout << " eat " << whatEat << std::endl << " degree of hunger now: "; gethunger(); std::cout << "\n"; hunger += 50; if (hunger > 100) { hunger == 100; } } else { NameAnimal(); std::cout << " don't eat " << whatEat << std::endl; } } hunger -= 2; die(); } void Fishes::die() { if (hunger <= 0) { this == NULL; NameAnimal(); std::cout << " die"; } }
true
e421e524cdc1cf65e83cf7fa7f5d8723d0febe46
C++
spewspews/modern
/specialize.cpp
UTF-8
374
3.453125
3
[]
no_license
#include <iostream> template <class T, class U> struct Widget { void Foo() { std::cout << "Foo: Generic impl\n"; } void Bar() { std::cout << "Bar: Generic impl\n"; } }; template <> void Widget<int, int>::Foo() { std::cout << "Foo: Specialized impl\n"; } int main() { Widget<double, int> w1; w1.Foo(); w1.Bar(); Widget<int, int> w2; w2.Foo(); w2.Bar(); }
true
6771b98895c560a7f0cc97b34c350a667f37c916
C++
hansoloyi/ass2
/src2/utility/Ray.cpp
UTF-8
3,746
3.25
3
[]
no_license
/* Ray.cpp */ #include "Ray.h" using namespace std; Ray::Ray(VecPoint a, VecPoint b) { this->origin = a; this->vector = b; } VecPoint Ray::intersectTriangle(Triangle triangle) { VecPoint vertex1 = triangle.getV1(); VecPoint vertex2 = triangle.getV2(); VecPoint vertex3 = triangle.getV3(); VecPoint rayOrigin = this->getOrigin(); VecPoint rayDirection = this->getVector(); VecPoint P; // Compute the normal VecPoint a, b; a = vertex2.subtract(vertex1); b = vertex3.subtract(vertex1); VecPoint normal = a.crossProduct(b); // Find P double nDotRay = normal.dotProduct(rayDirection); if (nDotRay == 0) { return VecPoint(0,0,0,0); // Parallel: no intersection } double d = normal.dotProduct(vertex1); // Ax + By + Cz + D = 0 double t = -(normal.dotProduct(rayOrigin) + d) / nDotRay; // Check if triangle behind ray if (t < 0) { return VecPoint(0,0,0,0); } P = rayOrigin.add(rayDirection.scale(t)); // Inside Outside Test VecPoint C; // Vector perpendicular to plane of triangle // Edge 1 VecPoint edge1 = vertex2.subtract(vertex1); VecPoint pv1 = P.subtract(vertex1); C = edge1.crossProduct(pv1); if (normal.dotProduct(C) < 0) { return VecPoint(0,0,0,0); // P is on the right side } // Edge 2 VecPoint edge2 = vertex3.subtract(vertex2); VecPoint pv2 = P.subtract(vertex2); C = edge2.crossProduct(pv2); if (normal.dotProduct(C) < 0) { return VecPoint(0,0,0,0); } // Edge 3 VecPoint edge3 = vertex1.subtract(vertex3); VecPoint pv3 = P.subtract(vertex3); C = edge3.crossProduct(pv3); if (normal.dotProduct(C) < 0) { return VecPoint(0,0,0,0); } return P; // P is in the triangle } VecPoint Ray::intersectSphere(Sphere s) { double A, B, C, t0, t1; double discriminant; VecPoint intersection; double sphereX = s.getX(); double sphereY = s.getY(); double sphereZ = s.getZ(); double radius = s.getRadius(); VecPoint vector = this->getVector(); double vectorX = vector.getX(); double vectorY = vector.getY(); double vectorZ = vector.getZ(); VecPoint origin = this->getOrigin(); double originX = origin.getX(); double originY = origin.getY(); double originZ = origin.getZ(); A = pow(vectorX, 2) + pow(vectorY, 2) + pow(vectorZ, 2); B = 2 * (vectorX*originX - vectorX*sphereX + vectorY*originY - vectorY*sphereY + vectorZ*originZ - vectorZ*sphereZ); C = pow(originX,2) - 2*originX*sphereX + pow(sphereX,2) + pow(originY,2) - 2*originY*sphereY + pow(sphereY,2) + pow(originZ,2) - 2*originZ*sphereZ + pow(sphereZ,2) - pow(radius,2); discriminant = pow(B, 2) - 4 * A * C; t0 = (-B - sqrt(pow(B, 2) - 4 * A * C)) / (2*A); t1 = (-B + sqrt(pow(B, 2) - 4 * A * C)) / (2*A); if (discriminant < 0) { intersection = VecPoint(0,0,0,0); } else if (A == 0) { intersection = VecPoint(0,0,0,0); } else if (discriminant == 0) { intersection = origin.add(vector.scale(t1)); } else { if (t0 < 0 and t1 > 0) { intersection = origin.add(vector.scale(t1)); } else if (t0 > 0 and t1 < 0) { intersection = origin.add(vector.scale(t0)); } else if (t0 > 0 and t1 > 0) { double s = min(t0,t1); intersection = origin.add(vector.scale(s)); } else { intersection = VecPoint(0,0,0,0); } } return intersection; } void Ray::display() { cout << "origin: "; this->getOrigin().display(); cout << "\nvector: "; this->getVector().display(); }
true
fd8e7f539805cd27ccb59ce2590a2d1b4a077120
C++
absorber2018/study_coding
/水仙花素.cpp
UTF-8
282
3.0625
3
[]
no_license
#include <stdio.h> int flower(int t); int main() {int t,n; for(t=100;t<=999;t++) {n=flower(t); if(n==1) printf("%d ",t); }return(0);} int flower(int t) {int a,b,c,d,p; a=t/100; b=(t%100)/10; c=t%10; d=a*a*a+b*b*b+c*c*c; if(d==t) p=1; else p=0; return p;}
true
05d83f6e34e3b88b83f277a217cb3673d3ee90fe
C++
HargovindArora/Programming
/BitMasking/subsets_using_BM.cpp
UTF-8
476
2.953125
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; void filterChars(int n, char a[]){ int j=0; while(n>0){ int last_bit = (n&1); if(last_bit==1){ cout << a[j]; } j++; n=n>>1; } cout << endl; } void range(int n, char a[]){ for(int i=0; i<(1<<n); i++){ filterChars(i, a); } } int main(){ char a[1001]; cin >> a; int n = strlen(a); range(n, a); return 0; }
true
571f6860439f5d2209ade57f73cc3ec7801195ae
C++
201601984/OOP
/week10/vehicle.h
UTF-8
499
2.84375
3
[]
no_license
#ifndef VEHICLE_H #define VEHICLE_H #include <iostream> class vehicle { protected: bool has_name; int wheel_number; int max_speed; public: vehicle(); vehicle(int wheel_number, int max_speed); vehicle(int wheel_number, int max_speed, bool has_name); int get_wheel_number(); int get_get_max_speed(); bool get_has_name(); const char* get_class_name(); void set_wheel_number(int wheel_number); void set_max_speed(int max_speed); void set_has_name(bool has_name); }; #endif
true
33d613840e9aabb25085d85a8e03924a88ed65f3
C++
ViniciusDeep/Answers-URI-Online-Judge
/Answers/C++/1047.cpp
UTF-8
1,343
2.796875
3
[]
no_license
//Vinicius Mangueira #include <stdio.h> int main() { int a,b,c,d,x,y; scanf("%d%d%d%d", &a, &x, &b, &y); if(a==y && b==y && y==x) { c=x-y; d=24+a-b; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(a==b && y>x) { c=y-x; d=a-b; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(a==b && x>y) { c=60-x+y; d=24-a+b-1; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(x==y && a<b) { c=0; d=b-a; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(x==y && a>b) { c=0; d=24-a+b; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(b>a && y>x) { c=y-x; d=b-a; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(a<b && x>y) { c=60-x+y; d=b-a-1; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(a>b && x<y) { c=y-x; d=24-a-1+b; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } else if(a>b && x>y) { c=60+y-x; d=24+b-a-1; printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", d, c); } return 0; }
true
ca0b78ee52db7a626bce569f5da5afc5d54d17f2
C++
BelfordZ/cpsc3200
/awesome-o/2003/shake.cc
UTF-8
3,446
3.171875
3
[]
no_license
#define PROBLEM 0 /* The problem # here */ #define TEAM 0 /* Your team # here */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <cstdio> #include <cctype> using namespace std; ifstream in; ofstream out; void solve_problem(); int main(void) { char filename[64]; sprintf(filename, "prob%d.dat", PROBLEM); in.open(filename, ios::in); if (!in) { cout << "could not open input file " << filename << endl; exit(1); } sprintf(filename, "prob%d.out", PROBLEM); out.open(filename, ios::out); if (!out) { cout << "could not open output file " << filename << endl; exit(1); } out << "Program " << PROBLEM << " by team " << TEAM << endl; solve_problem(); out << "End of program " << PROBLEM << " by team " << TEAM << endl; return 0; } void shake(char A[101][101], int n) { bool up = true; char t; int i, j; for (j = 1; j <= n; j++) { if (up) { t = A[1][j]; for (i = 1; i < n; i++) { A[i][j] = A[i+1][j]; } A[n][j] = t; } else { t = A[n][j]; for (i = n; i > 1; i--) { A[i][j] = A[i-1][j]; } A[1][j] = t; } up = !up; } } void rattle(char A[101][101], int n) { bool right = true; char t; int i, j; for (i = 1; i <= n; i++) { if (!right) { t = A[i][1]; for (j = 1; j < n; j++) { A[i][j] = A[i][j+1]; } A[i][n] = t; } else { t = A[i][n]; for (j = n; j > 1; j--) { A[i][j] = A[i][j-1]; } A[i][1] = t; } right = !right; } } void roll(char A[101][101], int n) { bool right = true; char t, t2; int i, j; for (i = 1; i <= n/2; i++) { if (right) { t = A[i][n-i+1]; for (j = n-i+1; j > i; j--) { A[i][j] = A[i][j-1]; } t2 = A[n-i+1][n-i+1]; for (j = n-i+1; j > i+1; j--) { A[j][n-i+1] = A[j-1][n-i+1]; } A[i+1][n-i+1] = t; t = t2; t2 = A[n-i+1][i]; for (j = i; j < n-i; j++) { A[n-i+1][j] = A[n-i+1][j+1]; } A[n-i+1][n-i] = t; t = t2; for (j = i; j < n-i; j++) { A[j][i] = A[j+1][i]; } A[n-i][i] = t; } else { t = A[i][i]; for (j = i; j < n-i+1; j++) { A[i][j] = A[i][j+1]; } t2 = A[n-i+1][i]; for (j = n-i+1; j > i+1; j--) { A[j][i] = A[j-1][i]; } A[i+1][i] = t; t = t2; t2 = A[n-i+1][n-i+1]; for (j = n-i+1; j > i+1; j--) { A[n-i+1][j] = A[n-i+1][j-1]; } A[n-i+1][i+1] = t; t = t2; for (j = i; j < n-i; j++) { A[j][n-i+1] = A[j+1][n-i+1]; } A[n-i][n-i+1] = t; } right = !right; } } void solve_problem(void) { string key, msg; while (in >> key) { in.ignore(); getline(in, msg); int n; if ((n = (key[0]-'0')*10 + (key[1]-'0')) == 0) { n = 100; } char A[101][101]; unsigned int k = 0, p = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if (p >= msg.length()) { A[i][j] = k + 'A'; if (++k >= 26) { k = 0; } } else { A[i][j] = toupper(msg[p++]); } } } for (unsigned int i = 2; i < key.length(); i++) { if (key[i] == 'S') { shake(A, n); } else if (key[i] == 'R') { rattle(A, n); } else if (key[i] == 'L') { roll(A, n); } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { out << A[i][j]; } } out << endl; } }
true
d3884caea3c7ba028a222602a990bf31a4ad85c7
C++
NicolasGripont/AutomateArithmetique
/numberexpression.h
UTF-8
332
2.59375
3
[]
no_license
#ifndef NUMBEREXPRESSION_H #define NUMBEREXPRESSION_H #include "expression.h" using namespace std; class NumberExpression : public Expression { private: int value; public: NumberExpression(const int v); ~NumberExpression(); virtual int eval() ; virtual string print() const; }; #endif // NUMBEREXPRESSION_H
true
a35ec87cf2ecbd70c97e3498ceed43cc0a1cab5c
C++
mohammadimtiazz/histogram
/histExample/histExample/main.cpp
UTF-8
3,844
2.71875
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <conio.h> #include <cv.h> #include <cxcore.h> #include <highgui.h> using namespace std; int main(){ IplImage *imgA = cvLoadImage("imgC.bmp"); if (imgA) cout << "read image A successfully!" << endl; else{ cout << "Fail to read image A!" << endl; abort(); } IplImage *imgB = cvLoadImage("imgD.bmp"); if (imgB) cout << "read image A successfully!" << endl; else{ cout << "Fail to read image A!" << endl; abort(); } // conversion of color to gray IplImage *grayA = cvCreateImage(cvGetSize(imgA), 8, 1); cvCvtColor(imgA, grayA, CV_BGR2GRAY); IplImage *grayB = cvCreateImage(cvGetSize(imgB), 8, 1); cvCvtColor(imgB, grayB, CV_BGR2GRAY); //planes to obtain the histogram, in this case just one IplImage * planesA[] = {grayA}; IplImage * planesB[] = {grayB}; CvHistogram *hist; int a_bins = 256; int b_bins = 256; // histSize array with a_bins, b_bins int histSize[] = {a_bins, b_bins}; //array with 0 and 256 float a_ranges[] = {0,256}; float b_ranges[] = {0,256}; //List with array inside float *ranges[] = {a_ranges, b_ranges}; //get the histogram and some info about it CvHistogram* histA; CvHistogram* histB; histA = cvCreateHist(1, histSize, CV_HIST_ARRAY, ranges, 1); cvCalcHist(planesA, histA, 0, NULL); histB = cvCreateHist(1, histSize, CV_HIST_ARRAY, ranges, 1); cvCalcHist(planesB, histB, 0, NULL); float maxValue = 0, minValue = 0; cvGetMinMaxHistValue(histA, &minValue, &maxValue); printf("min: %f, max: %f\n", minValue, maxValue); maxValue = 0, minValue = 0; cvGetMinMaxHistValue(histB, &maxValue, &minValue); printf("min: %f, max: %f\n", minValue, maxValue); //create an 8 bits single channel image to hold the histogram //paint it white IplImage* imgHistogramA = cvCreateImage(cvSize(a_bins, 200), 8, 1); cvRectangle(imgHistogramA, cvPoint(0, 0), cvPoint(256, 200), CV_RGB(255, 255, 255), -1); //draw the histogram //value and normalized value float value; int normalized; for (int i = 0; i < a_bins; i++) { value = cvQueryHistValue_1D(histA, i); normalized = cvRound(value * 200 / minValue); cvLine(imgHistogramA, cvPoint(i, 200), cvPoint(i, 200 - normalized), CV_RGB(0, 0, 0)); printf("%d\n", normalized); } //Create 3 windows to show the results cvNamedWindow("original A", 1); cvNamedWindow("gray A", 1); cvNamedWindow("histogram A", 1); //show the image results cvShowImage("original A", imgA); cvShowImage("gray A", grayA); cvShowImage("histogram A", imgHistogramA); //create an 8 bits single channel image to hold the histogram //paint it white IplImage* imgHistogramB = cvCreateImage(cvSize(b_bins, 200), 8, 1); cvRectangle(imgHistogramB, cvPoint(0, 0), cvPoint(256, 200), CV_RGB(255, 255, 255), -1); //draw the histogram //value and normalized value for (int i = 0; i < b_bins; i++) { value = cvQueryHistValue_1D(histB, i); normalized = cvRound(value * 200 / minValue); cvLine(imgHistogramB, cvPoint(i, 200), cvPoint(i, 200 - normalized), CV_RGB(0, 0, 0)); printf("%d\n", normalized); } //Create 3 windows to show the results cvNamedWindow("original B", 1); cvNamedWindow("gray B", 1); cvNamedWindow("histogram B", 1); //show the image results cvShowImage("original B", imgB); cvShowImage("gray B", grayB); cvShowImage("histogram B", imgHistogramB); cvWaitKey(); cvReleaseImage(&grayA); cvReleaseImage(&grayB); cvReleaseImage(&imgA); cvReleaseImage(&imgB); cvReleaseHist(&histA); cvReleaseHist(&histB); getch(); return 0; }
true
a5317498d9c74665391a94bf7696cd5feba3f3ed
C++
BackupGGCode/alpha-terrain-gen
/TerrainManager.cpp
UTF-8
7,228
3.140625
3
[]
no_license
/* * TerrainManager.cpp * * Manager for the Terrain. * * Dynamically generates new terrain segments and removes existing distant * segments. * * Created on: Jun 3, 2012 * Author: Simon Davies */ #include "TerrainManager.h" #include <Math.h> #include "SDL.h" #include "SDL_thread.h" // How many segments (width) do we want to try and draw? #define SEGMENT_DRAW_COUNT 16 // Semaphore for the draw table SDL_sem *draw_table_lock = NULL; /** Constructor for terrain managers * ---------------------------------------------------------------------------- * Arguments: * GLuint terrain_texture - ID for the texture for the terrain * GLfloat segment_size - Size of the terrain segment in real-size coordinates * ControllableCamera* camera - The camera within the world, used to determine which * terrain segments should be in memory. * unsigned int world_width - The width of the world in terrain segments. * The world is assumed to be square, so this value is also * used as the height of the world. */ TerrainManager::TerrainManager(GLuint terrain_texture, GLfloat segment_size, ControllableCamera* camera, unsigned int world_width) { // Set values locally this->world_width = world_width; this->camera = camera; // Initialize array terrain_segments = new TerrainSegment*[world_width * world_width]; // Draw Table draw_table = new bool[world_width * world_width]; draw_table_lock = SDL_CreateSemaphore(1); // Set all segments to NULL for (unsigned int i = 0; i < world_width; i++) { for (unsigned int j = 0; j < world_width; j++) { terrain_segments[i * world_width + j] = NULL; } } // Set other variables // Terrain texture bitmap ID this->terrain_texture = terrain_texture; // Size of each segment variable this->segment_size = segment_size; array_start_value = 0 - (world_width / 2 * segment_size); } TerrainManager::~TerrainManager() { for (unsigned int i = 0; i < world_width; i++) { for (unsigned int j = 0; j < world_width; j++) { delete (terrain_segments[i * world_width + j]); } } delete (terrain_segments); } /** Takes a value and returns the coordinate that would be correct for starting a * new terrain segment. * e.g. removes the remainder from dividing by the segment size. * Arguments * ----------------------------------------------- * float x - input value */ float TerrainManager::get_nearest_segment_start(float x) { return x - (fmod(x, segment_size)); } /** Repopulates the terrain around the camera location */ void TerrainManager::repopulate_terrain() { float start_x = get_nearest_segment_start( camera->getPositions()->cam_pos.x - ((this->segment_size * SEGMENT_DRAW_COUNT) / 2)); float start_z = get_nearest_segment_start( camera->getPositions()->cam_pos.z - ((this->segment_size * SEGMENT_DRAW_COUNT) / 2)); // This must be a value that will divide evenly into segment_size float quad_size = 3.0f; float x = start_x; float z = start_z; int start_i = (int) translate_to_index_coordinates(x); int start_j = (int) translate_to_index_coordinates(z); // Statically generate terrain segments // TODO: Check for the boundaries of the world array for (int i = start_i; i < start_i + SEGMENT_DRAW_COUNT; i++) { for (int j = start_j; j < start_j + SEGMENT_DRAW_COUNT; j++) { if (terrain_segments[(i * world_width) + j] == NULL) { SDL_WM_SetCaption("Alpha - Loading new Terrain...", "alpha"); terrain_segments[(i * world_width) + j] = new TerrainSegment(x, z, segment_size, quad_size, terrain_texture); } z += segment_size; } z = start_z; x += segment_size; } erase_distant_segments(); SDL_WM_SetCaption("Alpha", "alpha"); } /** Initializes and compiles any uninitialized terrain segments * for use by OpenGL. */ void TerrainManager::initialize_new_terrain_segments() { float start_x = get_nearest_segment_start( camera->getPositions()->cam_pos.x - ((this->segment_size * SEGMENT_DRAW_COUNT) / 2)); float start_z = get_nearest_segment_start( camera->getPositions()->cam_pos.z - ((this->segment_size * SEGMENT_DRAW_COUNT) / 2)); float x = start_x; float z = start_z; unsigned int start_i = (int) translate_to_index_coordinates(x); unsigned int start_j = (int) translate_to_index_coordinates(z); // Lock the draw table SDL_SemWait(draw_table_lock); // The draw table stores information on which segments are still being // actively drawn by the program. // Anything that is set to false by the time the semaphore is released // can be removed from memory for(unsigned int i = 0; i < world_width * world_width; i++){ draw_table[i] = false; } /* Initialise terrain segments */ for (unsigned int i = start_i; i < start_i + SEGMENT_DRAW_COUNT; i++) { for (unsigned int j = start_j; j < start_j + SEGMENT_DRAW_COUNT; j++) { // Update the draw table, so that this information to inform the // garbage collection that this segment is being drawn draw_table[(i * world_width) + j] = true; TerrainSegment* current_segment = terrain_segments[(i * world_width) + j]; if (current_segment != NULL && !current_segment->get_initialized()) { current_segment->terrain_GL_obj = glGenLists(1); glNewList(current_segment->terrain_GL_obj, GL_COMPILE); current_segment->init_quads(); glEndList(); } } } // Unlock the draw table SDL_SemPost(draw_table_lock); } /** Erases any distant segment in memory. * This is determined by looking at which segments are set as * false in the draw table. */ void TerrainManager::erase_distant_segments() { SDL_SemWait(draw_table_lock); for (unsigned int i = 0; i < world_width; i++) { for (unsigned int j = 0; j < world_width; j++) { // If the draw table entry is false, // then delete the terrain segment if(!draw_table[(i * world_width) + j]){ delete(terrain_segments[(i * world_width) + j]); terrain_segments[(i * world_width) + j] = NULL; } } } SDL_SemPost(draw_table_lock); } /** Turns a real world coordinate into the index into the * terrain_segments array. Based on the size of the terrain segments. * * Arguments * ------------------------------------------------------- * float x : input coordinate value */ float TerrainManager::translate_to_index_coordinates(float x) { x -= array_start_value; x /= segment_size; return x; } /** * Draws the terrain. * Assumes all of the terrain segments that should be drawn have * already been initialized. */ void TerrainManager::draw() { float start_x = get_nearest_segment_start( camera->getPositions()->cam_pos.x - ((segment_size * SEGMENT_DRAW_COUNT) / 2)); float start_z = get_nearest_segment_start( camera->getPositions()->cam_pos.z - ((segment_size * SEGMENT_DRAW_COUNT) / 2)); int start_i = (int) translate_to_index_coordinates(start_x); int start_j = (int) translate_to_index_coordinates(start_z); // Draw Terrain for (int i = start_i; i < start_i + SEGMENT_DRAW_COUNT; i++) { for (int j = start_j; j < start_j + SEGMENT_DRAW_COUNT; j++) { TerrainSegment* current_segment = terrain_segments[(i * world_width) + j]; if (current_segment != NULL) { glCallList(current_segment->terrain_GL_obj); } } } }
true
5bcfde999c0e3537ef8e7d6f7a62dbd5aa724ff3
C++
robmister2/LAB1_NEW
/Lexer.cpp
UTF-8
3,035
3.203125
3
[]
no_license
#include <cctype> #include "Lexer.h" using namespace std; void Lexer::Run(string &inputString) { int lineNumber = 1; int totalLines = 1; //count total lines read for (int i = 0; i < (int) inputString.length(); i++) { if (inputString[i] == '\n') { totalLines++; } } //if input is empty string if (totalLines == 1) { if (inputString.empty()) { Token *eofToken = new Token("", totalLines, END_OF_FILE); tokens.push_back(eofToken); } } //loop through the entire input while (inputString.size() > 0) { int testNums = removeWhitespace(inputString); lineNumber += testNums; int maxChar = 0; int maxAuto = 0; //run through the automata for (unsigned int i = 0; i < automata.size(); i++) { int testChar = automata.at(i)->Start(inputString); if (testChar > maxChar) { maxChar = testChar; maxAuto = i; } if (testChar == -1){ maxChar = testChar; //in case of a broken string / comment break; } } string tokenString = ""; if(maxChar == -1){ tokens.push_back(new Token(inputString, lineNumber, UNDEFINED)); //ILL TAKE IT ALL maxChar = inputString.size() - 1; //erase rest of string except EOF tokenString = inputString.substr(0, maxChar); } else if(maxChar == 0){ //UNDEFINED CHARACTERS maxChar = 1; tokenString = inputString.substr(0, maxChar); if(inputString.size() == 0){ tokens.push_back(new Token(tokenString, lineNumber, END_OF_FILE)); } else { tokens.push_back(new Token(tokenString, lineNumber, UNDEFINED)); } } else { tokenString = inputString.substr(0, maxChar); tokens.push_back(automata.at(maxAuto)->CreateToken(tokenString, lineNumber)); } for (unsigned int i = 0; i < tokenString.size(); i++) { //Account for lines IN the token for next one if (tokenString.at(i) == '\n') { lineNumber++; } } inputString.erase(0, maxChar); } } string Lexer::toString() { string output = ""; for (unsigned int i = 0; i < tokens.size(); ++i){ output += tokens.at(i)->toString(); output += "\n"; } output += "Total Tokens = "; output += std::to_string(tokens.size()); return output; } int Lexer::removeWhitespace(string& input){ int count = 0; int lineNums = 0; for (unsigned int i = 0; i < input.size(); i++){ if(isspace(input.at(i))){ count += 1; if(input.at(i) == '\n') { lineNums++; } } else { break; } } input.erase(0, count); return lineNums; } vector<Token *> Lexer::GetTokens() { return tokens; }
true
fd927d5d0cc74367d19ed0744bafa9a22eabd17a
C++
cginternals/globjects
/source/globjects/include/globjects/base/CompositeStringSource.h
UTF-8
1,202
2.59375
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <vector> #include <globjects/globjects_api.h> #include <globjects/base/Instantiator.h> #include <globjects/base/AbstractStringSource.h> namespace globjects { class GLOBJECTS_API CompositeStringSource : public AbstractStringSource, public Instantiator<CompositeStringSource> { public: CompositeStringSource(); CompositeStringSource(const std::vector<AbstractStringSource *> & sources); virtual ~CompositeStringSource(); void appendSource(AbstractStringSource * source); virtual std::string string() const override; virtual std::vector<std::string> strings() const override; virtual void flattenInto(std::vector<const AbstractStringSource *> & vector) const override; void addSubject(AbstractStringSource * subject); void removeSubject(AbstractStringSource * subject); virtual std::string shortInfo() const override; protected: virtual void notifyChanged(const AbstractStringSource * changeable) override; void update() const; protected: std::vector<AbstractStringSource *> m_sources; mutable bool m_dirty; mutable std::vector<std::string> m_strings; }; } // namespace globjects
true
c0b8eb9d8158a2b7f963b0f3a84e8d711723f3d1
C++
vrandakoolwal/Hacker-earth-Problems
/Basics-of-Implementation/COUNTNUMBERS.cpp
UTF-8
579
3
3
[]
no_license
#include <iostream> using namespace std; int numbers(char str[10000], int *p, int count) { // int count=0; // cout<<*p<<endl; count++; for (int i=*p; str[i]<='9'; i++) { *p+=1; } return count; } int main() { int t; cin>>t; while (t--) { int n; cin>>n; char str[n]; cin>>str; int z=0, count=0; for (int i=0; i<n; i++) { if (str[i]>='0' && str[i]<='9') count=numbers(str, &i, count); } cout<<count<<endl; } }
true
70a7442634e97ad975e40d1ebbc921073dc9611e
C++
hoaf13/SPOJ_PTIT_DSA
/P167PROD.cpp
UTF-8
1,158
2.5625
3
[]
no_license
#include<iostream> #include<string> #include<sstream> using namespace std; int main(){ string a,b,c; cin>>a>>b>>c; string alpha="0123456789"; int vta=-1,vtb=-1,vtc=-1; int a1,b1,c1; for(int i=0;i< a.length();i++) if(a[i]=='?') vta=i; for(int i=0;i< b.length();i++) if(b[i]=='?') vtb=i; for(int i=0;i< c.length();i++) if(c[i]=='?') vtc=i; if (vta!= -1){ for (int j=0;j<10;j++){ a[vta]=alpha[j]; stringstream stranum(a); stringstream strbnum(b); stringstream strcnum(c); stranum >> a1; strbnum >> b1; strcnum >> c1; if (a1+b1==c1){ cout<<alpha[j]; break; } } } if (vtb!= -1){ for (int j=0;j<10;j++){ b[vtb]=alpha[j]; stringstream stranum(a); stringstream strbnum(b); stringstream strcnum(c); stranum >> a1; strbnum >> b1; strcnum >> c1; if (a1+b1==c1){ cout<<alpha[j]; break; } } } if (vtc!= -1){ for (int j=0;j<10;j++){ c[vtc]=alpha[j]; stringstream stranum(a); stringstream strbnum(b); stringstream strcnum(c); stranum >> a1; strbnum >> b1; strcnum >> c1; if (a1+b1==c1){ cout<<alpha[j]; break; } } } return 0; }
true
00895f223f731e4b8bc2df5fe5a414f254b8af14
C++
oisincoveney/PDF-Search-Engine-C-
/Parser/parser.h
UTF-8
2,604
2.71875
3
[]
no_license
#pragma once #include <unordered_set> #include <unordered_map> #include <string> #include <experimental/filesystem> #include <poppler/cpp/poppler-document.h> #include <poppler/cpp/poppler-page.h> #include <poppler/cpp/poppler-rectangle.h> #include <stemmer.h> #include <chrono> #include <sstream> #include <iostream> #include <iomanip> #include <Index/indexinterface.h> #include <ncurses.h> #include <list> #include <cstdlib> class IndexInterface; using namespace std::chrono; /** * * The Parser class is a static class that contains the functionality * for parsing a PDF and adding it to an IndexInterface index. The Parser class * also keeps track of the total number of files, words, and pages parsed, * as well as a table of documents and their respective word counts. * * NOTE: The word counts are the counts of words that have been parsed, * which does not include words shorter than 3, or stop words. * * By: Oisin Coveney * */ class Parser { private: //Stopword list static std::unordered_set<std::string> stopwords; //Gets maximum possible size for PDF to capture all data static poppler::rectf rectangle; //Steps 1 & 2 of parsing files and developing index static int getFileList(std::string directory, std::vector<std::string>& files); static void parseFile(std::string& file, IndexInterface*& index); public: //Counters for files, words, pages, and table for doc-wordount static int numFiles; static bool extraFiles; static int numWords; static int numPages; static std::unordered_map<std::string, int> totalWordsInDoc; //Checking validity of words static bool isStopWord(std::string& word); static bool invalidLength(std::string& word); //Parsing functions static void parse(std::string& directory, IndexInterface*& index, int row, int col); static void addExtraDoc(std::string& file, IndexInterface*& index); static void addExtraDirectory(std::string& directory, IndexInterface*& index, int row, int col); static void directoryParser(std::vector<std::__cxx11::string> files, IndexInterface*&index, int row, int col); //Getters and setters static int getNumFiles(); static void setNumFiles(int value); static int getNumPages(); static void setNumPages(int value); static int getNumWords(); static void setNumWords(int value); };
true
a60ce3461324dfc7fddcca949fe988134841d6d3
C++
nkahile/Tree-Based-Evaluator
/Queue.cpp
UTF-8
3,158
4.03125
4
[]
no_license
#include <iostream> #include <string> #include "Queue.h" //the Queue constructor template <typename T> Queue <T>::Queue(void) :queue_data_(50), queue_size_(0), front_(0), rear_(0) { } template <typename T> Queue <T>::~Queue(void) { //no pointers to delete here } //changed the code so instead of using unnecessary temp arrays and memory alocation //a simple check for self assignment is made, if the check is false, we start //assigning the data to the rhs data, the size to the rhs size, front to rhs front, //and finaly rear to rhs rear template <typename T> const Queue <T>& Queue <T>::operator = (const Queue& rhs) { if (this != &rhs) { this->queue_data_ = rhs.queue_data_; this->queue_size_ = rhs.queue_size_; this->front_ = rhs.front_; this->rear_ = rhs.rear; } return *this; } //The Queue copy constructor template <typename T> Queue<T>::Queue(const Queue& s) :queue_data_(s.queue_data_), queue_size_(s.queue_size_), front_(s.front_), rear_(s.rear_) { } template <typename T> void Queue <T>::enqueue(T element) { // COMMENT You are increasing the size of the queue, not you are not // adding the value to the queue. //=>Fixed it so it can change the size of the queue in real time while the //the values enter the queue ++this->rear_; ++this->queue_size_; this->queue_data_.resize(this->rear_); this->queue_data_.set(this->rear_-1 , element); } /*--------------- this is the front of the queue => 10 | 20 |30 | <= this is the rear of the queue ---------------*/ template <typename T> T Queue<T>::dequeue(void) { // COMMENT You are not returning the element removed from the queue. //=> fixed it so it can dequeue and return the dequeued element if (is_empty()) { throw Queue<T>::empty_exception(); } else { ++this->front_; --this->queue_size_; std::cout << (this->queue_data_.get(this->front_ - 1)) << std::endl; return (this->queue_data_.get(this->front_ - 1)); } } //check if the Queue is Empty template <typename T> bool Queue <T>::is_empty(void) const { if (this->rear_ == this->front_) { std::cout << "Queue is empty" << std::endl; return true; } else { std::cout << "Queue has " << this->queue_size_ << " values" << std::endl; return false; } } //retrieve the values in the Queue template<typename T> size_t Queue<T>::size(void) const { std::cout << this->queue_size_; return this->queue_size_; } //Clear the values in the Queue template <typename T> void Queue <T>::clear(void) { this->rear_ = this->front_; } //this method is to show the contents of the Queue template <typename T> void Queue <T>::show(void) { if (is_empty()) { throw Queue<T>::empty_exception(); } else { for (size_t i = front_; i < rear_; i++) { std::cout << this->queue_data_[i]; } } }
true
569c8dc508455ebba7a98783117dfb4e29c25d7d
C++
sjtujxwang/3Ddefectdetection
/pylon-5.2.0.13457-x86_64/Samples/C++/ParametrizeCamera_AutoFunctions/ParametrizeCamera_AutoFunctions_Usb.cpp
UTF-8
26,147
2.53125
3
[]
no_license
// ParametrizeCamera_AutoFunctions_Usb.cpp /* Note: Before getting started, Basler recommends reading the "Programmer's Guide" topic in the pylon C++ API documentation delivered with pylon. If you are upgrading to a higher major version of pylon, Basler also strongly recommends reading the "Migrating from Previous Versions" topic in the pylon C++ API documentation. This sample illustrates how to use the Auto Functions feature of Basler USB cameras. Features, like 'Gain', are named according to the Standard Feature Naming Convention (SFNC). The SFNC defines a common set of features, their behavior, and the related parameter names. This ensures the interoperability of cameras from different camera vendors. Cameras compliant with the USB 3 Vision standard are based on the SFNC version 2.0. Basler GigE and FireWire cameras are based on previous SFNC versions. Accordingly, the behavior of these cameras and some parameters names will be different. That's why this sample is different from the sample for FireWire and GigE cameras in ParametrizeCamera_AutoFunctions.cpp */ // Include files to use the pylon API. #include <pylon/PylonIncludes.h> #ifdef PYLON_WIN_BUILD # include <pylon/PylonGUI.h> #endif // Namespace for using pylon objects. using namespace Pylon; // Namespace for using cout. using namespace std; #if defined( USE_BCON ) // Settings to use Basler BCON cameras. #include <pylon/bcon/BaslerBconInstantCamera.h> typedef Pylon::CBaslerBconInstantCamera Camera_t; using namespace Basler_BconCameraParams; #else // Settings for using Basler USB cameras. #include <pylon/usb/BaslerUsbInstantCamera.h> typedef Pylon::CBaslerUsbInstantCamera Camera_t; using namespace Basler_UsbCameraParams; #endif // The camera specific grab result smart pointer. typedef Camera_t::GrabResultPtr_t GrabResultPtr_t; bool IsColorCamera(Camera_t& camera); void AutoGainOnce(Camera_t& camera); void AutoGainContinuous(Camera_t& camera); void AutoExposureOnce(Camera_t& camera); void AutoExposureContinuous(Camera_t& camera); void AutoWhiteBalance(Camera_t& camera); int main(int argc, char* argv[]) { // The exit code of the sample application. int exitCode = 0; // Before using any pylon methods, the pylon runtime must be initialized. PylonInitialize(); try { // Only look for cameras supported by Camera_t. CDeviceInfo info; info.SetDeviceClass( Camera_t::DeviceClass()); // Create an instant camera object with the first found camera device that matches the specified device class. Camera_t camera( CTlFactory::GetInstance().CreateFirstDevice( info)); // Print the name of the used camera. cout << "Using device " << camera.GetDeviceInfo().GetModelName() << endl; // Check to see if the camera supportsAutoFunction ROI parameters. // Former firmware versions supporting the AutoFunctionAOI parameters are no longer supported by this sample. if (!IsAvailable(camera.AutoFunctionROISelector) && IsAvailable(camera.GetNodeMap().GetNode("AutoFunctionAOISelector"))) { cout << "This camera only supports the deprecated AutoFunctionAOIxxxx camera parameters." << endl; cout << "If you want to configure the regions used by the auto functions on this camera, use" << endl; cout << "the AutoFunctionAOIxxxx parameters instead of the AutoFunctionROIxxxx parameters." << endl << endl; // Comment the following two lines to disable waiting on exit. cerr << endl << "Press Enter to exit." << endl; while( cin.get() != '\n'); // Releases all pylon resources. PylonTerminate(); return 0; } // Register the standard event handler for configuring single frame acquisition. // This overrides the default configuration as all event handlers are removed by setting the registration mode to RegistrationMode_ReplaceAll. // Please note that the camera device auto functions do not require grabbing by single frame acquisition. // All available acquisition modes can be used. camera.RegisterConfiguration( new CAcquireSingleFrameConfiguration, RegistrationMode_ReplaceAll, Cleanup_Delete); // Open the camera. camera.Open(); // Turn test image off. #if defined( USE_BCON ) camera.TestPattern = TestPattern_Off; #else // Handle test image selector for different USB camera models. if (IsAvailable(camera.TestImageSelector)) { camera.TestImageSelector = TestImageSelector_Off; } if (IsAvailable(camera.TestPattern)) { camera.TestPattern = TestPattern_Off; } #endif // Only area scan cameras support auto functions. if (camera.DeviceScanType.GetValue() == DeviceScanType_Areascan) { // All area scan cameras support luminance control. // Carry out luminance control by using the "once" gain auto function. // For demonstration purposes only, set the gain to an initial value. camera.Gain.SetValue( camera.Gain.GetMax()); AutoGainOnce(camera); cerr << endl << "Press Enter to continue." << endl; while( cin.get() != '\n'); // Carry out luminance control by using the "continuous" gain auto function. // For demonstration purposes only, set the gain to an initial value. camera.Gain.SetValue( camera.Gain.GetMax()); AutoGainContinuous(camera); cerr << endl << "Press Enter to continue." << endl; while( cin.get() != '\n'); // For demonstration purposes only, set the exposure time to an initial value. camera.ExposureTime.SetValue( camera.ExposureTime.GetMin()); // Carry out luminance control by using the "once" exposure auto function. AutoExposureOnce(camera); cerr << endl << "Press Enter to continue." << endl; while( cin.get() != '\n'); // For demonstration purposes only, set the exposure time to an initial value. camera.ExposureTime.SetValue( camera.ExposureTime.GetMin()); // Carry out luminance control by using the "continuous" exposure auto function. AutoExposureContinuous(camera); // Only color cameras support the balance white auto function. if (IsColorCamera(camera)) { cerr << endl << "Press Enter to continue." << endl; while( cin.get() != '\n'); // For demonstration purposes only, set the initial balance ratio values: camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Red); camera.BalanceRatio.SetValue(3.14); camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Green); camera.BalanceRatio.SetValue(0.5); camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Blue); camera.BalanceRatio.SetValue(0.125); // Carry out white balance using the balance white auto function. AutoWhiteBalance(camera); } } else { cerr << "Only area scan cameras support auto functions." << endl; } // Close camera. camera.Close(); } catch (const GenericException &e) { // Error handling. cerr << "An exception occurred." << endl << e.GetDescription() << endl; exitCode = 1; } // Comment the following two lines to disable waiting on exit. cerr << endl << "Press Enter to exit." << endl; while( cin.get() != '\n'); // Releases all pylon resources. PylonTerminate(); return exitCode; } void AutoGainOnce(Camera_t& camera) { // Check whether the gain auto function is available. if ( !IsWritable( camera.GainAuto)) { cout << "The camera does not support Gain Auto." << endl << endl; return; } // Maximize the grabbed image area of interest (Image AOI). if (IsWritable(camera.OffsetX)) { camera.OffsetX.SetValue(camera.OffsetX.GetMin()); } if (IsWritable(camera.OffsetY)) { camera.OffsetY.SetValue(camera.OffsetY.GetMin()); } camera.Width.SetValue(camera.Width.GetMax()); camera.Height.SetValue(camera.Height.GetMax()); if(IsAvailable(camera.AutoFunctionROISelector)) { // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics if (IsWritable(camera.AutoFunctionROIUseBrightness)) { camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); camera.AutoFunctionROIUseBrightness.SetValue(true); // ROI 1 is used for brightness control camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIUseBrightness.SetValue(false); // ROI 2 is not used for brightness control } // Set the ROI (in this example the complete sensor is used) camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); // configure ROI 1 camera.AutoFunctionROIOffsetX.SetValue(camera.OffsetX.GetMin()); camera.AutoFunctionROIOffsetY.SetValue(camera.OffsetY.GetMin()); camera.AutoFunctionROIWidth.SetValue(camera.Width.GetMax()); camera.AutoFunctionROIHeight.SetValue(camera.Height.GetMax()); } // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.AutoTargetBrightness.SetValue(0.3); // We are going to try GainAuto = Once. cout << "Trying 'GainAuto = Once'." << endl; cout << "Initial Gain = " << camera.Gain.GetValue() << endl; // Set the gain ranges for luminance control. camera.AutoGainLowerLimit.SetValue(camera.Gain.GetMin()); camera.AutoGainUpperLimit.SetValue(camera.Gain.GetMax()); camera.GainAuto.SetValue(GainAuto_Once); // When the "once" mode of operation is selected, // the parameter values are automatically adjusted until the related image property // reaches the target value. After the automatic parameter value adjustment is complete, the auto // function will automatically be set to "off" and the new parameter value will be applied to the // subsequently grabbed images. int n = 0; while (camera.GainAuto.GetValue() != GainAuto_Off) { GrabResultPtr_t ptrGrabResult; camera.GrabOne( 5000, ptrGrabResult); #ifdef PYLON_WIN_BUILD Pylon::DisplayImage(1, ptrGrabResult); #endif ++n; //For demonstration purposes only. Wait until the image is shown. WaitObject::Sleep(100); //Make sure the loop is exited. if (n > 100) { throw RUNTIME_EXCEPTION( "The adjustment of auto gain did not finish."); } } cout << "GainAuto went back to 'Off' after " << n << " frames." << endl; cout << "Final Gain = " << camera.Gain.GetValue() << endl << endl; } void AutoGainContinuous(Camera_t& camera) { // Check whether the Gain Auto feature is available. if ( !IsWritable( camera.GainAuto)) { cout << "The camera does not support Gain Auto." << endl << endl; return; } // Maximize the grabbed image area of interest (Image AOI). if (IsWritable(camera.OffsetX)) { camera.OffsetX.SetValue(camera.OffsetX.GetMin()); } if (IsWritable(camera.OffsetY)) { camera.OffsetY.SetValue(camera.OffsetY.GetMin()); } camera.Width.SetValue(camera.Width.GetMax()); camera.Height.SetValue(camera.Height.GetMax()); if(IsAvailable(camera.AutoFunctionROISelector)) { // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics. if (IsWritable(camera.AutoFunctionROIUseBrightness)) { camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); camera.AutoFunctionROIUseBrightness.SetValue(true); // ROI 1 is used for brightness control camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIUseBrightness.SetValue(false); // ROI 2 is not used for brightness control } // Set the ROI (in this example the complete sensor is used) camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); // configure ROI 1 camera.AutoFunctionROIOffsetX.SetValue(camera.OffsetX.GetMin()); camera.AutoFunctionROIOffsetY.SetValue(camera.OffsetY.GetMin()); camera.AutoFunctionROIWidth.SetValue(camera.Width.GetMax()); camera.AutoFunctionROIHeight.SetValue(camera.Height.GetMax()); } // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.AutoTargetBrightness.SetValue(0.3); // We are trying GainAuto = Continuous. cout << "Trying 'GainAuto = Continuous'." << endl; cout << "Initial Gain = " << camera.Gain.GetValue() << endl; camera.GainAuto.SetValue(GainAuto_Continuous); // When "continuous" mode is selected, the parameter value is adjusted repeatedly while images are acquired. // Depending on the current frame rate, the automatic adjustments will usually be carried out for // every or every other image unless the camera�s micro controller is kept busy by other tasks. // The repeated automatic adjustment will proceed until the "once" mode of operation is used or // until the auto function is set to "off", in which case the parameter value resulting from the latest // automatic adjustment will operate unless the value is manually adjusted. for (int n = 0; n < 20; n++) // For demonstration purposes, we will grab "only" 20 images. { GrabResultPtr_t ptrGrabResult; camera.GrabOne( 5000, ptrGrabResult); #ifdef PYLON_WIN_BUILD Pylon::DisplayImage(1, ptrGrabResult); #endif //For demonstration purposes only. Wait until the image is shown. WaitObject::Sleep(100); } camera.GainAuto.SetValue(GainAuto_Off); // Switch off GainAuto. cout << "Final Gain = " << camera.Gain.GetValue() << endl << endl; } void AutoExposureOnce(Camera_t& camera) { // Check whether auto exposure is available if ( !IsWritable( camera.ExposureAuto)) { cout << "The camera does not support Exposure Auto." << endl << endl; return; } // Maximize the grabbed area of interest (Image AOI). if (IsWritable(camera.OffsetX)) { camera.OffsetX.SetValue(camera.OffsetX.GetMin()); } if (IsWritable(camera.OffsetY)) { camera.OffsetY.SetValue(camera.OffsetY.GetMin()); } camera.Width.SetValue(camera.Width.GetMax()); camera.Height.SetValue(camera.Height.GetMax()); if(IsAvailable(camera.AutoFunctionROISelector)) { // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics. if (IsWritable(camera.AutoFunctionROIUseBrightness)) { camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); camera.AutoFunctionROIUseBrightness.SetValue(true); // ROI 1 is used for brightness control camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIUseBrightness.SetValue(false); // ROI 2 is not used for brightness control } // Set the ROI (in this example the complete sensor is used) camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); // configure ROI 1 camera.AutoFunctionROIOffsetX.SetValue(camera.OffsetX.GetMin()); camera.AutoFunctionROIOffsetY.SetValue(camera.OffsetY.GetMin()); camera.AutoFunctionROIWidth.SetValue(camera.Width.GetMax()); camera.AutoFunctionROIHeight.SetValue(camera.Height.GetMax()); } // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.AutoTargetBrightness.SetValue(0.3); // Try ExposureAuto = Once. cout << "Trying 'ExposureAuto = Once'." << endl; cout << "Initial exposure time = "; cout << camera.ExposureTime.GetValue() << " us" << endl; // Set the exposure time ranges for luminance control. camera.AutoExposureTimeLowerLimit.SetValue(camera.AutoExposureTimeLowerLimit.GetMin()); camera.AutoExposureTimeUpperLimit.SetValue(camera.AutoExposureTimeLowerLimit.GetMax()); camera.ExposureAuto.SetValue(ExposureAuto_Once); // When the "once" mode of operation is selected, // the parameter values are automatically adjusted until the related image property // reaches the target value. After the automatic parameter value adjustment is complete, the auto // function will automatically be set to "off", and the new parameter value will be applied to the // subsequently grabbed images. int n = 0; while (camera.ExposureAuto.GetValue() != ExposureAuto_Off) { GrabResultPtr_t ptrGrabResult; camera.GrabOne( 5000, ptrGrabResult); #ifdef PYLON_WIN_BUILD Pylon::DisplayImage(1, ptrGrabResult); #endif ++n; //For demonstration purposes only. Wait until the image is shown. WaitObject::Sleep(100); //Make sure the loop is exited. if (n > 100) { throw RUNTIME_EXCEPTION( "The adjustment of auto exposure did not finish."); } } cout << "ExposureAuto went back to 'Off' after " << n << " frames." << endl; cout << "Final exposure time = "; cout << camera.ExposureTime.GetValue() << " us" << endl << endl; } void AutoExposureContinuous(Camera_t& camera) { // Check whether the Exposure Auto feature is available. if ( !IsWritable( camera.ExposureAuto)) { cout << "The camera does not support Exposure Auto." << endl << endl; return; } // Maximize the grabbed area of interest (Image AOI). if (IsWritable(camera.OffsetX)) { camera.OffsetX.SetValue(camera.OffsetX.GetMin()); } if (IsWritable(camera.OffsetY)) { camera.OffsetY.SetValue(camera.OffsetY.GetMin()); } camera.Width.SetValue(camera.Width.GetMax()); camera.Height.SetValue(camera.Height.GetMax()); if(IsAvailable(camera.AutoFunctionROISelector)) { // Set the Auto Function ROI for luminance statistics. // We want to use ROI1 for gathering the statistics. if (IsWritable(camera.AutoFunctionROIUseBrightness)) { camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); camera.AutoFunctionROIUseBrightness.SetValue(true); // ROI 1 is used for brightness control camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIUseBrightness.SetValue(false); // ROI 2 is not used for brightness control } // Set the ROI (in this example the complete sensor is used) camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); // configure ROI 1 camera.AutoFunctionROIOffsetX.SetValue(camera.OffsetX.GetMin()); camera.AutoFunctionROIOffsetY.SetValue(camera.OffsetY.GetMin()); camera.AutoFunctionROIWidth.SetValue(camera.Width.GetMax()); camera.AutoFunctionROIHeight.SetValue(camera.Height.GetMax()); } // Set the target value for luminance control. // A value of 0.3 means that the target brightness is 30 % of the maximum brightness of the raw pixel value read out from the sensor. // A value of 0.4 means 40 % and so forth. camera.AutoTargetBrightness.SetValue(0.3); cout << "ExposureAuto 'GainAuto = Continuous'." << endl; cout << "Initial exposure time = "; cout << camera.ExposureTime.GetValue() << " us" << endl; camera.ExposureAuto.SetValue(ExposureAuto_Continuous); // When "continuous" mode is selected, the parameter value is adjusted repeatedly while images are acquired. // Depending on the current frame rate, the automatic adjustments will usually be carried out for // every or every other image, unless the camera�s microcontroller is kept busy by other tasks. // The repeated automatic adjustment will proceed until the "once" mode of operation is used or // until the auto function is set to "off", in which case the parameter value resulting from the latest // automatic adjustment will operate unless the value is manually adjusted. for (int n = 0; n < 20; n++) // For demonstration purposes, we will use only 20 images. { GrabResultPtr_t ptrGrabResult; camera.GrabOne( 5000, ptrGrabResult); #ifdef PYLON_WIN_BUILD Pylon::DisplayImage(1, ptrGrabResult); #endif //For demonstration purposes only. Wait until the image is shown. WaitObject::Sleep(100); } camera.ExposureAuto.SetValue(ExposureAuto_Off); // Switch off Exposure Auto. cout << "Final exposure time = "; cout << camera.ExposureTime.GetValue() << " us" << endl << endl; } void AutoWhiteBalance(Camera_t& camera) { // Check whether the Balance White Auto feature is available. if ( !IsWritable( camera.BalanceWhiteAuto)) { cout << "The camera does not support Balance White Auto." << endl << endl; return; } // Maximize the grabbed area of interest (Image AOI). if (IsWritable(camera.OffsetX)) { camera.OffsetX.SetValue(camera.OffsetX.GetMin()); } if (IsWritable(camera.OffsetY)) { camera.OffsetY.SetValue(camera.OffsetY.GetMin()); } camera.Width.SetValue(camera.Width.GetMax()); camera.Height.SetValue(camera.Height.GetMax()); if(IsAvailable(camera.AutoFunctionROISelector)) { // Set the Auto Function ROI for white balance. // We want to use ROI2 camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI1); camera.AutoFunctionROIUseWhiteBalance.SetValue(false); // ROI 1 is not used for white balance camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIUseWhiteBalance.SetValue(true); // ROI 2 is used for white balance // Set the Auto Function AOI for white balance statistics. // Currently, AutoFunctionROISelector_ROI2 is predefined to gather // white balance statistics. camera.AutoFunctionROISelector.SetValue(AutoFunctionROISelector_ROI2); camera.AutoFunctionROIOffsetX.SetValue(camera.OffsetX.GetMin()); camera.AutoFunctionROIOffsetY.SetValue(camera.OffsetY.GetMin()); camera.AutoFunctionROIWidth.SetValue(camera.Width.GetMax()); camera.AutoFunctionROIHeight.SetValue(camera.Height.GetMax()); } cout << "Trying 'BalanceWhiteAuto = Once'." << endl; cout << "Initial balance ratio: "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Red); cout << "R = " << camera.BalanceRatio.GetValue() << " "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Green); cout << "G = " << camera.BalanceRatio.GetValue() << " "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Blue); cout << "B = " << camera.BalanceRatio.GetValue() << endl; camera.BalanceWhiteAuto.SetValue(BalanceWhiteAuto_Once); // When the "once" mode of operation is selected, // the parameter values are automatically adjusted until the related image property // reaches the target value. After the automatic parameter value adjustment is complete, the auto // function will automatically be set to "off" and the new parameter value will be applied to the // subsequently grabbed images. int n = 0; while (camera.BalanceWhiteAuto.GetValue() != BalanceWhiteAuto_Off) { GrabResultPtr_t ptrGrabResult; camera.GrabOne( 5000, ptrGrabResult); #ifdef PYLON_WIN_BUILD Pylon::DisplayImage(1, ptrGrabResult); #endif ++n; //For demonstration purposes only. Wait until the image is shown. WaitObject::Sleep(100); //Make sure the loop is exited. if (n > 100) { throw RUNTIME_EXCEPTION( "The adjustment of auto white balance did not finish."); } } cout << "BalanceWhiteAuto went back to 'Off' after "; cout << n << " frames." << endl; cout << "Final balance ratio: "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Red); cout << "R = " << camera.BalanceRatio.GetValue() << " "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Green); cout << "G = " << camera.BalanceRatio.GetValue() << " "; camera.BalanceRatioSelector.SetValue(BalanceRatioSelector_Blue); cout << "B = " << camera.BalanceRatio.GetValue() << endl; } bool IsColorCamera(Camera_t& camera) { GenApi::NodeList_t Entries; camera.PixelFormat.GetEntries(Entries); bool Result = false; for (size_t i = 0; i < Entries.size(); i++) { GenApi::INode *pNode = Entries[i]; if (IsAvailable(pNode->GetAccessMode())) { GenApi::IEnumEntry *pEnum = dynamic_cast<GenApi::IEnumEntry *>(pNode); const GenICam::gcstring sym(pEnum->GetSymbolic()); if (sym.find(GenICam::gcstring("Bayer")) != GenICam::gcstring::_npos()) { Result = true; break; } } } return Result; }
true
e9382d64af7fa4b7d6dba23e3951771114f37b33
C++
gregoryjjb/invaders
/src/ofApp.cpp
UTF-8
3,347
2.578125
3
[]
no_license
#include "ofApp.h" #include "Config.h" #include <cstdint> #include <algorithm> #include "Star.h" //-------------------------------------------------------------- void ofApp::setup() { // Spawn world world = new World(); // Spawn player player = (Player*) world->addObject(new Player()); player->setLocation(ofPoint(ofGetViewportWidth() * 0.5, ofGetViewportHeight() - Config::playerYOffset)); // Spawn HUD hud = new HUD(world, player); // Automated enemy spawning /*EnemySpawn* spawn = new EnemySpawn(); spawn->setWorld(world); spawn->startSpawn();*/ // Spawn some stars lastStarSpawnTime = 0; for(int i = 0; i < 40; i++) { float xPos = ofRandom(ofGetViewportWidth()); float yPos = ofRandom(ofGetViewportHeight()); float speed = Config::playerYSpeed - ofRandom(100); Star* star = (Star*)world->addObject(new Star(speed)); star->setLocation(ofPoint(xPos, yPos)); } world->startGame(); } //-------------------------------------------------------------- void ofApp::update() { // Move player if (keys[OF_KEY_LEFT]) { player->addLocation(ofPoint(-1 * Config::playerXSpeed * ofGetLastFrameTime(), 0)); } else if (keys[OF_KEY_RIGHT]) { player->addLocation(ofPoint(Config::playerXSpeed * ofGetLastFrameTime(), 0)); } // Stars float now = ofGetElapsedTimef(); float interval = 0.1; if (now > lastStarSpawnTime + interval) { lastStarSpawnTime = now; float xPos = ofRandom(ofGetViewportWidth()); float speed = Config::playerYSpeed - ofRandom(100); Star* star = (Star*)world->addObject(new Star(speed)); star->setLocation(ofPoint(xPos, 0)); } } //-------------------------------------------------------------- void ofApp::draw() { if (world) { world->draw(); } if (hud) { hud->draw(); } } //-------------------------------------------------------------- void ofApp::keyPressed(int key) { if (key == GLFW_KEY_SPACE && !keys[GLFW_KEY_SPACE]) { player->startFiring(); } // Update key map keys[key] = true; } //-------------------------------------------------------------- void ofApp::keyReleased(int key) { if (key == GLFW_KEY_SPACE && keys[GLFW_KEY_SPACE]) { player->stopFiring(); } // Update key map keys[key] = false; } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ) { int deltaX = x - lastMousePosition.x; player->addLocation(ofPoint(deltaX, 0)); lastMousePosition = ofPoint(x, y); } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button) { } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y) { } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y) { } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h) { } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg) { } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo) { }
true
9cd03ba70c5866324386b2f7a3af156a4fa086ce
C++
hackur/kwm
/kwm/scratchpad.cpp
UTF-8
4,834
2.6875
3
[ "MIT" ]
permissive
#include "scratchpad.h" #include "display.h" #include "space.h" #include "window.h" #include "axlib/axlib.h" #define internal static extern kwm_settings KWMSettings; extern scratchpad Scratchpad; internal inline bool IsScratchpadSlotTaken(int Index) { std::map<int, ax_window*>::iterator It = Scratchpad.Windows.find(Index); return It != Scratchpad.Windows.end(); } int GetScratchpadSlotOfWindow(ax_window *Window) { int Slot = -1; std::map<int, ax_window*>::iterator It; for(It = Scratchpad.Windows.begin(); It != Scratchpad.Windows.end(); ++It) { if(It->second->ID == Window->ID) { Slot = It->first; break; } } if(Window->Name) DEBUG("GetScratchpadSlotOfWindow() " << Window->Name << " " << Slot); else DEBUG("GetScratchpadSlotOfWindow() " << "[Unknown]" << " " << Slot); return Slot; } internal inline bool IsWindowOnScratchpad(ax_window *Window) { return GetScratchpadSlotOfWindow(Window) != -1; } internal inline int GetFirstAvailableScratchpadSlot() { int Slot = 0; if(!Scratchpad.Windows.empty()) { while(IsScratchpadSlotTaken(Slot)) ++Slot; } return Slot; } void AddWindowToScratchpad(ax_window *Window) { if(!AXLibIsSpaceTransitionInProgress() && !IsWindowOnScratchpad(Window)) { int Slot = GetFirstAvailableScratchpadSlot(); Scratchpad.Windows[Slot] = Window; DEBUG("AddWindowToScratchpad() " << Slot); } } void RemoveWindowFromScratchpad(ax_window *Window) { if(!AXLibIsSpaceTransitionInProgress() && IsWindowOnScratchpad(Window)) { if(AXLibHasFlags(Window, AXWindow_Floating)) AXLibClearFlags(Window, AXWindow_Floating); ax_display *Display = AXLibWindowDisplay(Window); if(Display) { if(!AXLibSpaceHasWindow(Window, Display->Space->ID)) AXLibSpaceAddWindow(Display->Space->ID, Window->ID); AddWindowToNodeTree(Display, Window->ID); if(KWMSettings.Focus == FocusModeStandby) KWMSettings.Focus = FocusModeAutoraise; } int Slot = GetScratchpadSlotOfWindow(Window); Scratchpad.Windows.erase(Slot); DEBUG("RemoveWindowFromScratchpad() " << Slot); } } void ToggleScratchpadWindow(int Index) { if(!AXLibIsSpaceTransitionInProgress() && IsScratchpadSlotTaken(Index)) { ax_window *Window = Scratchpad.Windows[Index]; ax_display *Display = AXLibWindowDisplay(Window); if(Display) { if(AXLibSpaceHasWindow(Window, Display->Space->ID)) HideScratchpadWindow(Index); else ShowScratchpadWindow(Index); } } } void HideScratchpadWindow(int Index) { if(!AXLibIsSpaceTransitionInProgress() && IsScratchpadSlotTaken(Index)) { ax_window *Window = Scratchpad.Windows[Index]; ax_display *Display = AXLibWindowDisplay(Window); if(Display) { if(!AXLibHasFlags(Window, AXWindow_Floating)) AXLibAddFlags(Window, AXWindow_Floating); RemoveWindowFromNodeTree(Display, Window->ID); AXLibSpaceRemoveWindow(Display->Space->ID, Window->ID); if(KWMSettings.Focus == FocusModeStandby) KWMSettings.Focus = FocusModeAutoraise; if(Scratchpad.LastFocus != -1) FocusWindowByID(Scratchpad.LastFocus); } } } void ShowScratchpadWindow(int Index) { if(!AXLibIsSpaceTransitionInProgress() && IsScratchpadSlotTaken(Index)) { ax_application *Application = AXLibGetFocusedApplication(); if(!Application) return; ax_window *FocusedWindow = Application->Focus; if(FocusedWindow) Scratchpad.LastFocus = FocusedWindow->ID; ax_window *Window = Scratchpad.Windows[Index]; ax_display *Display = AXLibWindowDisplay(Window); if(Display) { AXLibSpaceAddWindow(Display->Space->ID, Window->ID); ResizeScratchpadWindow(Display, Window); FocusWindowByID(Window->ID); } } } void ResizeScratchpadWindow(ax_display *Display, ax_window *Window) { int NewX = Display->Frame.origin.x + Display->Frame.size.width * 0.125; int NewY = Display->Frame.origin.y + Display->Frame.size.height * 0.125; int NewWidth = Display->Frame.size.width * 0.75; int NewHeight = Display->Frame.size.height * 0.75; SetWindowDimensions(Window, NewX, NewY, NewWidth, NewHeight); } void ShowAllScratchpadWindows() { std::map<int, ax_window*>::iterator It; for(It = Scratchpad.Windows.begin(); It != Scratchpad.Windows.end(); ++It) ShowScratchpadWindow(It->first); }
true
3df53f314afb8fe8d1679da6c4c8e6a23ab3442e
C++
gaivits/code_Kidding
/overlapp.cpp
UTF-8
583
2.953125
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector< pair<int,int> > vec; int sz; int x,y; cin >> sz; int cnt = 0; for(int j = 0;j<sz;j++) { cin >> x >> y; vec.push_back( pair<int,int> (x,y) ); } sort(vec.begin(),vec.end()); for(int a=0;a<sz;a++) { for(int b = 0;b<vec[a].first;b++) { if(vec[a].first >= vec[b].second) { cnt++; } } } cnt=cnt+1; cout << cnt; }
true
6f7bbcc3f72bbe213644d4f11f214fd28d89b0b7
C++
ravi-kumar7/Power-Programmer
/Recursion/NQueen/code_cpp.cpp
UTF-8
913
3.28125
3
[]
no_license
int board[11][11]; bool isPossible(int n,int row,int col){ for(int i=row-1;i>=0;i--){ if(board[i][col]==1){ return false; } } for(int i=row-1,j=col-1;i<=0,j>=0;i--,j--){ if(board[i][j]==1){ return false; } } for(int i=row-1,j=col+1;i>=0,j<n;i--,j++){ if(board[i][j]==1){ return false; } } return true; } void nQueenHelper(int n,int row){ if(row==n){ //print the output //return; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ cout<<board[i][j]<<" "; } cout<<endl; }cout<<endl; } for(int j=0;j<n;j++){ if(isPossible(n,row,j)){ board[row][j]=1; nQueenHelper(n,row+1); board[row][j]=0; } } return; } void placeNQueens(int n){ /* Don't write main(). * Don't read input, it is passed as function argument. * Print output as specified in the question */ nQueenHelper(n,0); }
true
4c3b8cac3d800a32a00ee22684a7c36054dbe73c
C++
nfwaldron/CPlayground
/RandomNumberGenerator/RandomNumberGenerator/ExpoGenerator.cpp
UTF-8
686
3.140625
3
[]
no_license
#include "ExponentialGenerator.h" ExponentialGenerator::ExponentialGenerator(){ myLambda = 0.0; } ExponentialGenerator::ExponentialGenerator(double lambda){ myLambda = lambda; } void ExponentialGenerator::setLambda(double lambda){ myLambda = lambda; } double ExponentialGenerator::getLambda(){ return myLambda; } double ExponentialGenerator::ExpRandom(int bits){ double base = pow(2,bits); unsigned long int temp = random(bits); double lam = getLambda(); double temp2 = (double)temp / base; myT = temp2; return (lam*pow(2.71828, -lam*temp2)); } double ExponentialGenerator::getmyT() { return myT; } double ExponentialGenerator::ExpectedMean(){ return 1 / getLambda(); }
true
3bb20f09f4b6a4ece086f529f514c4e66bf87394
C++
Hide-in-blue/MyPAT
/a1120.cpp
UTF-8
523
2.5625
3
[]
no_license
#include<iostream> using namespace std; int main(){ int n, cnt = 0, visited[40]={0}; cin>>n; for(int i=0;i<n;i++){ int t, sum = 0; cin>>t; while(t){ sum += t%10; t /= 10; } if(visited[sum]==0){ cnt++; visited[sum] = 1; } } int f = 0; for(int i=0;i<40;i++){ if(visited[i]){ if(f) cout<<' '; cout<<i; f = 1; } } }
true
4ffe4ca8b655bd5cc2f33858eb5107b6ebcfcdcd
C++
lteacy/maxsum-cpp
/include/maxsum/register.h
UTF-8
4,306
3.15625
3
[]
no_license
/** * @file register.h * This Header defines functions for registering the set of all * variables on which maxsum::DiscreteFunction objects may depend. * * Variables are uniquely identified by a key of type maxsum::VarID and each as * a specified domain size. The purpose of the functions defined in this file * are to register the domain size for each variable before it is used, and * ensure that this size remains fixed throughout a programs execution. * Variables can be registered multiple times, but in each case the domain size * must not change. Variables must always be registered before they are * referenced by any function. * */ #ifndef MAX_SUM_REGISTER_H #define MAX_SUM_REGISTER_H #include "common.h" namespace maxsum { /** * Returns true if the specified variable is registered. * @param var id of the variable to search for. * @returns true if the specified variable is registered. */ bool isRegistered(VarID var); /** * Returns true if all specified variables are registered. * Parameters are iterators over a list of variable ids of type * maxsum::VarID. * @param varBegin iterator to begining of variable list. * @param varEnd iterator to end of variable list. * @returns true if all registered, false otherwise. */ template<class VarIt> bool allRegistered(VarIt varBegin, VarIt varEnd) { for(VarIt var=varBegin; var!=varEnd; var++) { if(!isRegistered(*var)) { return false; } } return true; } /** * Returns the registered domain size for a specified variable. * @param var id of the variable to search for. * @returns domain size of var * @throws UnknownVariableException if the variable is not registered. */ ValIndex getDomainSize(VarID var); /** * Returns the number of currently registered variables. * @returns the number of currently registered variables. */ int getNumOfRegisteredVariables(); /** * Registers a variable with a specified domain size. * Puts the specified variable in a global register, and stores its domain * size. Variables can be registered multiple times, but their domain size * must never change. * @throws InconsistentDomainException if this variable is already * registered, but with a different domain size. * @param var the unique id of this variable * @param siz the domain size of this variable * @see maxsum::registerVariables */ void registerVariable(VarID var, ValIndex siz); /** * Register a list of variables with specified domain sizes. * This works in the same was as maxsum::registerVariable - but does so * for multiple variables at a time. The parameters varBegin and varEnd are * iterators to the beginning and end of a list of variable ids, while * sizBegin and sizEnd specify the start and end of a list of their * respective domain sizes. Both lists must be ordered such that * the kth element of the size list is the domain size for the kth variable * in the variable list. * @param varBegin iterator to the start of a list of maxsum::VarID * @param varEnd iterator to the end of a list of maxsum::VarID * @param sizBegin iterator to the start of a list of maxsum::ValIndex * @param sizEnd iterator to the start of a list of maxsum::ValIndex * @see maxsum::registerVariable */ template<class VarIt, class IndIt> void registerVariables (VarIt varBegin, VarIt varEnd, IndIt sizBegin, IndIt sizEnd) { //************************************************************************ // Create iterators for the variable and domain size lists //************************************************************************ VarIt var = varBegin; IndIt siz = sizBegin; //************************************************************************ // Register each variable with its corresponding size //************************************************************************ while( (var!=varEnd) && (siz!=sizEnd) ) { registerVariable(*var,*siz); ++var; ++siz; } } // function registerVariables } // namespace maxsum #endif // MAX_SUM_REGISTER_H
true
c20741810069e0e1f2fb56c57a3a81216f34dc5c
C++
shi-mo/aoj
/ITP2_2_D.cpp
UTF-8
827
2.875
3
[]
no_license
#include <iostream> #include <list> #include <vector> using namespace std; int main() { int n, q, query; vector<list<long>> lst; cin >> n; cin >> q; lst.resize(n); while (cin >> query) { int t; cin >> t; switch (query) { case 0: // insert(t, x) int x; cin >> x; lst[t].push_back(x); break; case 1: // dump(t) for (auto itr = lst[t].begin(); itr != lst[t].end(); itr++) { if (lst[t].begin() != itr) cout << " "; cout << *itr; } cout << endl; break; case 2: // splice(t, u) int u; cin >> u; lst[u].splice(lst[u].end(), lst[t]); lst[t].clear(); } } lst.clear(); }
true
f8cc93045335694b3f3956d3db5ddea4a5b73668
C++
soqutto/practice
/AtCoder/ABC137/c.cpp
UTF-8
440
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main(){ int N; cin >> N; vector<string> S(N); unordered_map<string, int64_t> Smap; for(auto& s: S){ cin >> s; sort(s.begin(), s.end()); Smap[s]++; } int64_t ans = 0; for(auto it = Smap.begin(); it != Smap.end(); ++it){ int64_t n = it->second; ans += n*(n-1)/2; } cout << ans << endl; return 0; }
true
282b980af641960ec042c70bb2a6a43fe1475a89
C++
Max5254/RBE-2002-Final-Project
/2002 Robot Code/lib/Ultrasonic-Library-master/examples/ultrasonic/ultrasonic.ino
UTF-8
1,069
3.15625
3
[]
no_license
//Mandatory Includes #include <TimerOne.h> #include <UltrasonicSensor.h> #include <UltrasonicSensorArray.h> #define numOfUltrasonics 3 // not necessary for less than 5 sensors // first, create an Ultrasonic Sensor Array (USA) to receive inputs on pin 2 UltrasonicSensorArray usa(2); // And then create each ultrasonic sensor (with their output pins) UltrasonicSensor left(13); UltrasonicSensor right(12); UltrasonicSensor front(11); void setup() { // setup serial communication for print statements Serial.begin(115200); // Add each sensor to the UltrasonicSensorArray usa.addSensor(&left); usa.addSensor(&right); usa.addSensor(&front); // Initalize the USA timer and input interrupts usa.begin(); } void loop() { // each sensor is update asynchonously by the UltrasonicSesnorArray // so we don't have to do any work in loop delay(100); // clear the screen for(int j=0; j<11; j++) Serial.println(""); // print each distance Serial.println(left.distance()); Serial.println(right.distance()); Serial.println(front.distance()); }
true
d4555633aee700841e2ac6da1c722fa885994346
C++
milos1397/Project-1
/parallel/ActivationP.hpp
UTF-8
836
3.21875
3
[]
no_license
#ifndef ACTIVATION_HPP #define ACTIVATION_HPP #include <cmath> // Base abstract class for all activation functions. class ActivationFunction { public: virtual double calculate(double x) = 0; }; class Sigmoid : public ActivationFunction { public: double calculate(double x) { return (1 / (1 + exp(-1.0 * x))); } }; class Identity : public ActivationFunction { public: double calculate(double x) { return x; } }; class TanH : public ActivationFunction { public: double calculate(double x) { return ((exp(x) - exp(-1.0 * x)) / (exp(x) + exp(-1.0 * x))); } }; class ArcTan : public ActivationFunction { public: double calculate(double x) { return atan(-1.0 * x); } }; class BinaryStep : public ActivationFunction { public: double calculate(double x) { return (x < 0) ? 0 : 1; } }; #endif // ACTIVATION_HPP
true
30758e35de9a2464ec608f28bc21cbf6fa4f85a4
C++
juliejin/Videogames
/TowerDefense/Source/GameMode.h
UTF-8
1,159
2.65625
3
[]
no_license
#pragma once #include "Actor.h" #include "AudioComponent.h" #include "Spawner.h" #include "Tile.h" #include "HUD.h" class GameMode : public Actor { DECL_ACTOR(GameMode, Actor); public: GameMode(Game& game); void BeginPlay() override; void EndPlay() override; // Get the position that enemies should spawn from const Vector3& GetSpawnPos() const; // Handle mouse click selection void HandleSelect(); // Return the requested tile at the (x, y) index // in the grid of tiles TilePtr GetTile(const Vector2& gridPos); void CreateCannonTower(); void CreateFrostTower(); int GetMoney() { return mMoney; }; int GetHealth() { return mHealth; }; private: int mHealth; int mMoney; // Create the tiles void CreateTiles(); // All of the tiles in the grid std::vector<std::vector<TilePtr>> mTiles; // Current selected tile, or nullptr if none TilePtr mSelectedTile; SpawnerPtr mSpawnerPtr; AudioComponentPtr mAudioComponentPtr; SoundPtr mBuildingSoundPtr; SoundPtr mErrorSoundPtr; HUDPtr hud; }; DECL_PTR(GameMode);
true
af8bca5c1d1f425487f84a9262dc9311bb125908
C++
AnanyaKumar/symbiotic-rovers
/algorithms/Filters/archive/hellomodule.cpp
UTF-8
704
2.984375
3
[]
no_license
#include <iostream> #include <vector> #include <list> #include <boost/python.hpp> #include <boost/python/stl_iterator.hpp> #include <boost/python/object.hpp> using namespace std; using namespace boost::python; struct World { std::string greet() { return msg; } std::string msg; }; vector<double> to_vector(boost::python::list ns) { vector<double> v; for (int i = 0; i < len(ns); ++i) { int x; x = boost::python::extract<double>(ns[i]); v.push_back(x); } return v; } void lol (boost::python::list ns) { vector<double> v = to_vector(ns); for (int i = 0; i < v.size(); i++) { cout << v[i] << endl; } } BOOST_PYTHON_MODULE(hello) { def("to_vector", &lol); }
true
ec6f5dedbc1bf680a43acdfeb037a3e00433350b
C++
jwakely/Sprout
/sprout/algorithm/search_n.hpp
UTF-8
1,396
2.5625
3
[ "BSL-1.0" ]
permissive
#ifndef SPROUT_ALGORITHM_SEARCH_N_HPP #define SPROUT_ALGORITHM_SEARCH_N_HPP #include <sprout/config.hpp> #include <sprout/iterator/operation.hpp> namespace sprout { // Copyright (C) 2011 RiSK (sscrisk) // 25.2.13 Search template<typename ForwardIterator, typename Size, typename T> inline SPROUT_CONSTEXPR ForwardIterator search_n( ForwardIterator first, ForwardIterator last, Size count, T const& value ) { return first == last || count == 0 ? first : sprout::next(first) == last && count > 1 ? last : *first == value && sprout::search_n(sprout::next(first), last, count - 1, value) == sprout::next(first) ? first : sprout::search_n(sprout::next(first), last, count, value) ; } template<typename ForwardIterator, typename Size, typename T, typename BinaryPredicate> inline SPROUT_CONSTEXPR ForwardIterator search_n( ForwardIterator first, ForwardIterator last, Size count, T const& value, BinaryPredicate pred ) { return first == last || count == 0 ? first : sprout::next(first) == last && count > 1 ? last : *first == value && sprout::search_n(sprout::next(first), last, count - 1, value, pred) == sprout::next(first) ? first : sprout::search_n(sprout::next(first), last, count, value, pred) ; } } // namespace sprout #endif // #ifndef SPROUT_ALGORITHM_SEARCH_N_HPP
true
d26bc5887b05d44879835f4f7598f403c2491e75
C++
colinhp/searchEngine-12
/online/include/net/TcpServer.hpp
UTF-8
861
2.5625
3
[]
no_license
/// /// @file TcpSever.hpp /// @author yangyu/Icot(jobyang@163.com) /// @date 2017-03-18 00:05:58 /// #ifndef __WD_TCPSERVER_H__ #define __WD_TCPSERVER_H__ #include "Noncopyable.hpp" #include "EpollPoller.hpp" #include "Socket.hpp" #include "InetAddress.hpp" #include <string> using std::string; namespace wd { class TcpServer : Noncopyable { public: typedef EpollPoller::EpollCallback TcpServerCallback; TcpServer(const string & ip, unsigned short port); void start() { _poller.loop(); } void setConnectCallback(TcpServerCallback cb) { _poller.setConnectCallback(std::move(cb)); } void setMessageCallback(TcpServerCallback cb) { _poller.setMessageCallback(std::move(cb)); } void setCloseCallback(TcpServerCallback cb) { _poller.setCloseCallback(std::move(cb)); } private: InetAddress _addr; Socket _sockfd; EpollPoller _poller; }; } #endif
true
2fce11041ffdbb413ac879265714e08c48f26775
C++
Daniel-ef/OIMP_seminars_cpp
/197/seminar11/main.cpp
UTF-8
1,057
3.8125
4
[]
no_license
#include <iostream> class Simple { public: Simple() { std::cout << "1" << std::endl; } Simple(size_t count) : id_(count) { std::cout << "2" << std::endl; } Simple(const Simple& simple) : id_(simple.id_) { std::cout << "3" << std::endl; } Simple(Simple&& simple) : id_(simple.id_) { std::cout << "3" << std::endl; } size_t Count() const { return id_; } void Increment() { ++id_; } ~Simple() { std::cout << "Dtor " << id_ << std::endl; } Simple& operator= (const Simple& s) { id_ = s.id_; return *this; } private: size_t id_{0}; }; Simple makeSimple() { auto s = Simple{1}; return s; } void print_simple(Simple s) { std::cout << "print: " << s.Count() << std::endl; } int main() { { Simple s1; const Simple s2{2}; Simple s3{s2}; // Simple s4 = Simple{Simple{3}}; Simple s4{Simple{3}}; } Simple s5 = makeSimple(); Simple s6 = s5; print_simple(5); // std::cout << s1.Count() << s2.Count() << s3.Count() << s4.Count() << s5.Count(); }
true
3baba7638262958ed1db583ffebcd243eab4beb7
C++
SungOuk/test
/shiftregister.ino
UTF-8
592
2.640625
3
[]
no_license
int dataPin = 2; int clockPin = 3; int latchPin = 4; byte data = 0; void setup() { pinMode(dataPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(latchPin, OUTPUT); } void shiftWrite(int desiredPin, boolean desiredState) { bitWrite(data, desiredPin, desiredState); shiftOut(dataPin, clockPin, MSBFIRST, data); digitalWrite(latchPin, HIGH); digitalWrite(latchPin, LOW); } void loop(){ for(int i = 0; i<=3; i++) { shiftWrite(i, HIGH); delay(100); } for(int i = 3; i >=0; i--) { shiftWrite(i, LOW); delay(100); } }
true
1d989d231ecde53088bb6cc716277d4824adf8e9
C++
sarah-litz/Data-Structure-Project
/Code/hash.hpp
UTF-8
1,031
3.203125
3
[]
no_license
#ifndef HASH_HPP #define HASH_HPP #include <string> using namespace std; struct hashNode { int key; struct hashNode* next; }; class HashTable { int tableSize; // No. of buckets (linked lists) int collisionCount = 0; hashNode* chainingTable[40009]; //for chaining int intTable[40009]; //for open addressing public: HashTable(); // Constructor unsigned int hashFunction(int trackingID); // hash function to map values to key hashNode* createNode(int trackingID); //allocates space for new node and sets key val //Collision Method: chaining with a linked list void chainingInsert(int trackingID); void chainingSearch(int trackingID); //collision method: open addressing, linear probing void linearInsert(int trackingID); void linearSearch(int trackingID); //colision method: open addressing, quadratic probing void quadraticInsert(int trackingID); void quadraticSearch(int trackingID); void display(); int getNumOfCollision(); }; #endif
true
458c104f04f9c546c04185cea656fae11633b7cd
C++
AhmedMaher309/MarsExploration
/MarsExploration-OZER/UI/Input.cpp
UTF-8
845
3.09375
3
[]
no_license
#include "Input.h" Modes Input::getMode() { int c; cout << "choose a mode to enter " << endl; cout << "1- interactive \n" << "2-Step-By-Step\n" << "3-Silent\n"; do { cin >> c; switch (c - 1) { case 0: return Modes::Interactive; case 1: return Modes::StepbyStep; case 2: return Modes::Silent; default: cout << "Wrong Choice ! Please choose again..." << endl; } } while (c > 3); } void Input::GetPress() { char c; //cout << "Press any Button to continue ... " << endl; cin >> c; return; } string Input::Get_File_name() { string filename; ifstream infile; cout << "Please enter file name in (.txt) format : " << endl; cin >> filename; infile.open(filename); while (infile.fail()) { cout << "File not found , Please try again" << endl; cin >> filename; infile.open(filename); } return filename; }
true
db2b3fd4abe076672fa65c8d4f91be93ef1cd921
C++
kostyantyn/unit-e
/src/staking/transactionpicker.h
UTF-8
2,841
2.5625
3
[ "MIT" ]
permissive
// Copyright (c) 2018-2019 The Unit-e developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UNIT_E_STAKING_TRANSACTION_PICKER_H #define UNIT_E_STAKING_TRANSACTION_PICKER_H #include <vector> #include <amount.h> #include <chainparams.h> #include <dependency.h> #include <policy/policy.h> #include <primitives/transaction.h> namespace staking { //! \brief a component for picking transactions for a new block. //! //! When building a new block to be proposed the proposer has to fill //! that block with transactions. The TransactionPicker is the component //! which selects the transactions. //! //! This class is an interface. //! //! Currently the only implementation of the TransactionPicker is an //! adapter to bitcoins CBlockAssembler. A conceivable alternative //! implementation would take into account maybe a minimum transaction //! amount (but that might also have been taken care of by transaction //! relay policies – then again a proposer might still very well include //! his own micro transaction which would have to be tackled by a //! consensus rule anyway and therefore would be reflected in a //! TransactionPicker). class TransactionPicker { public: struct PickTransactionsParameters { //! \brief The maximum weight of the block to pick transactions for. //! //! BIP141 introduced a new method for computing the max block //! size which is the block weight. The block weight is defined //! as base-size * 3 + total_size. According to BIP141 the block //! weight must be less-than-or-equal-to 4M. unsigned int max_weight = DEFAULT_BLOCK_MAX_WEIGHT; //! \brief The minimum sum of transaction fees //! //! The incentive to include transactions into a block is to //! harvest the transaction fees. Fees are set when a transaction //! is created. The fees are the difference of the inputs being //! spent and the outputs created. unsigned int min_fees = DEFAULT_BLOCK_MIN_TX_FEE; }; //! \brief transactions and fees chosen. struct PickTransactionsResult { std::string error; std::vector<CTransactionRef> transactions; std::vector<CAmount> fees; explicit operator bool() const { return error.empty(); } }; //! \brief picks transactions for inclusion in a block //! //! Chooses transactions to be included into a newly proposed //! block, according to the parameters passed in. virtual PickTransactionsResult PickTransactions( const PickTransactionsParameters &) = 0; virtual ~TransactionPicker() = default; //! \brief Factory method for creating a BlockAssemblerAdapter static std::unique_ptr<TransactionPicker> New(); }; } // namespace staking #endif // UNIT_E_STAKING_TRANSACTION_PICKER_H
true
1240f103f96a68ad03a48e8c7760df09815d90bf
C++
intfloat/AlgoSolutions
/codeforces/CF311/E.cpp
UTF-8
1,780
2.609375
3
[]
no_license
#include <bits/stdc++.h> #define FOR(i, n) for (int i = 0; i < n; ++i) using namespace std; typedef long long ll; string s; struct Node { int cnt, lcnt, rcnt; Node* ch[2]; Node(): cnt(0), lcnt(0), rcnt(0) { ch[0] = ch[1] = NULL; } }; Node* root = new Node; int from, n; vector<vector<bool> > dp; void insert_trie(Node* ptr, int pos) { if (pos == n) return; int idx = s[pos] - 'a'; if (dp[from][pos]) { ++ptr->cnt; } if (pos + 1 < n) { idx = s[pos + 1] - 'a'; if (ptr->ch[idx] == NULL) { ptr->ch[idx] = new Node; } insert_trie(ptr->ch[idx], pos + 1); } } int dfs(Node* ptr) { if (ptr == NULL) return 0; ptr->lcnt = dfs(ptr->ch[0]); ptr->rcnt = dfs(ptr->ch[1]); return ptr->lcnt + ptr->rcnt + ptr->cnt; } string res; void solve(Node* ptr, int pos) { if (pos <= ptr->cnt) { return; } pos -= ptr->cnt; if (pos <= ptr->lcnt) { res += "a"; solve(ptr->ch[0], pos); } else { pos -= ptr->lcnt; res += "b"; solve(ptr->ch[1], pos); } } int main() { int k; cin >> s >> k; n = s.size(); dp.resize(n); FOR(i, n) dp[i] = vector<bool>(n, false); FOR(i, n) dp[i][i] = true; for (int len = 2; len <= n; ++len) { for (int i = 0; i < n; ++i) { int j = i + len - 1; if (j >= n) break; dp[i][j] = (s[i] == s[j]); if (i + 2 < j - 2) dp[i][j] = dp[i][j] && dp[i + 2][j - 2]; } } root->ch[0] = new Node; root->ch[1] = new Node; for (int i = 0; i < n; ++i) { from = i; insert_trie(root->ch[s[i] - 'a'], i); } dfs(root); solve(root, k); cout << res << endl; return 0; }
true
1896d55d3d6f3f279a4d35c32ab254a93dc0b627
C++
zalless/modern-cpp-training
/training-2017/examples/EmployeeDb/src/EmployeesDb.hpp
UTF-8
2,168
3.015625
3
[]
no_license
#ifndef EMPLOYEESDB_HPP #define EMPLOYEESDB_HPP #include <unordered_map> #include <vector> enum class Profession { ENGINEER, DOCTOR, LAWYER }; struct EmployeeRecord { std::string name; Profession position = Profession::ENGINEER; int age = 0; int salary = 0; uint64_t id = 0; EmployeeRecord() = default; EmployeeRecord(std::string name, Profession position, int age, int salary) : name(std::move(name)), position(position), age(age), salary(salary) { } }; class EmployeesDb { using Collection = std::vector<EmployeeRecord>; using NameLookup = std::unordered_map<std::string, uint64_t>; using IdLookup = std::unordered_map<uint64_t, size_t>; Collection mEmployees; NameLookup mNameLookup; IdLookup mIdLookup; public: using Iterator = Collection::const_iterator; EmployeesDb() = default; EmployeesDb(std::vector<EmployeeRecord> employees); ~EmployeesDb() = default; uint64_t insert(EmployeeRecord data); void remove(const std::string& name); void remove(uint64_t id); Iterator find(uint64_t id) const; Iterator find(const std::string& name) const; size_t size() const; Iterator begin() const; Iterator end() const; private: void generateIdLookup(); void generateNameLookup(); }; std::pair<EmployeesDb::Iterator, EmployeesDb::Iterator> range(const EmployeesDb& db, Profession position); std::pair<EmployeeRecord, EmployeeRecord> minMaxSalaryPerPosition(const EmployeesDb& db, Profession position); int avgSalaryPerPosition(const EmployeesDb& db, Profession position); int medianSalaryPerPosition(const EmployeesDb& db, Profession position); std::vector<EmployeeRecord> topNSalariesPerPosition(const EmployeesDb& db, Profession position, int n); int avgSalaryPerAgeRange(const EmployeesDb& db, std::pair<int, int> ageRange); std::string dumpEmployeeRecord(const EmployeeRecord& r); std::string dumpEmployeeDb(const EmployeesDb& db); #endif // EMPLOYEESDB_HPP
true
a5ac18b19dfe2fa32a2f0012823b4c4bf50db3f4
C++
UltraCoderRU/telebotxx
/include/telebotxx/BotApi.hpp
UTF-8
2,697
3.109375
3
[ "MIT" ]
permissive
#ifndef TELEBOTXX_BOTAPI_H #define TELEBOTXX_BOTAPI_H #include "User.hpp" #include "Message.hpp" #include "Update.hpp" #include "SendMessageRequest.hpp" #include "SendPhotoRequest.hpp" #include <string> #include <memory> namespace telebotxx { template <typename RequestType, typename T> void setRequestOption(RequestType& request, T t) { request.setOption(t); } template <typename RequestType, typename T, typename... Ts> void setRequestOption(RequestType& request, T&& t, Ts&&... ts) { setRequestOption(request, std::forward<T>(t)); setRequestOption(request, std::forward<Ts>(ts)...); }; class BotApi { public: /// \param [in] token bot's secret token BotApi(const std::string& token); ~BotApi(); /// \brief Get basic information about the bot /// \return User object with information about the bot User getMe(); /// \brief Send text message /// \param chatId chat identifier /// \param text text /// \return Message object, recieved from the server Message sendMessage(ChatId&& chatId, Text&& text); /// \brief Send text message /// \param chatId chat identifier /// \param text text /// \param args parameters /// \return Message object, recieved from the server template<typename... Ts> Message sendMessage(ChatId&& chatId, Text&& text, Ts&&... args) { SendMessageRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Text>(text)); setRequestOption(request, std::forward<Ts>(args)...); return request.execute(); } /// \brief Send image /// \param [in] chatId chat identifier /// \param [in] photo photo /// \return Message object, recieved from the server Message sendPhoto(ChatId&& chatId, Photo&& photo); /// \brief Send image /// \param [in] chatId chat identifier /// \param [in] photo photo /// \param [in] args parameters /// \return Message object, recieved from the server template<typename... Ts> Message sendPhoto(ChatId&& chatId, Photo&& photo, Ts&&... args) { SendPhotoRequest request(getTelegramMainUrl(), std::forward<ChatId>(chatId), std::forward<Photo>(photo)); setRequestOption(request, std::forward<Ts>(args)...); return request.execute(); } /// \brief Get updates using long polling /// \param offset identifier of the first update to be returned /// \param limit maximum number of updates to be retrieved /// \param timeout timeout in seconds for long polling /// \return Updates (vector of Update) Updates getUpdates(int offset = 0, unsigned short limit = 0, unsigned timeout = 0); private: std::string getTelegramMainUrl() const; class Impl; std::unique_ptr<Impl> impl_; }; } #endif // TELEBOTXX_BOTAPI_H
true
ad7344c7895830a43ebfd3b48a87291ec841bc5c
C++
sandychn/LeetCode-Solutions
/Algorithms/Heap/0778-swim-in-rising-water.cpp
UTF-8
1,560
3.078125
3
[ "MIT" ]
permissive
struct Node { pair<int, int> pos; int val; Node(const pair<int, int>& pos, int val): pos(pos), val(val) {} bool operator<(const Node& rhs) const { return val > rhs.val; } }; class Solution { public: static bool inRange(int val, int l, int r) { return l <= val && val <= r; } int swimInWater(vector<vector<int>>& grid) { int n = grid.size(); int currentTime = 0; const pair<int, int> start(0, 0); const pair<int, int> dest(n - 1, n - 1); const int dx[] = {0, 0, -1, 1}; const int dy[] = {-1, 1, 0, 0}; vector<vector<int>> visited(n, vector<int>(n)); priority_queue<Node> heap; heap.emplace(start, grid[start.first][start.second]); visited[start.first][start.second] = true; while (!heap.empty()) { while (heap.top().val <= currentTime) { Node now = heap.top(); heap.pop(); if (now.pos == dest) return currentTime; for (int i = 0; i < 4; i++) { int x = now.pos.first + dx[i]; int y = now.pos.second + dy[i]; if (inRange(x, 0, n - 1) && inRange(y, 0, n - 1) && !visited[x][y]) { heap.emplace(make_pair(x, y), grid[x][y]); visited[x][y] = true; } } } ++currentTime; } return -1; // should not run here } };
true
1866e4704ee3100cb1681e2dfd600db4a235e925
C++
2Sangyun/Data-Structure-Practice
/sylee/201214/readfile3.cpp
UTF-8
2,774
2.84375
3
[]
no_license
#include <fcntl.h> #include <iostream> #include <list> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> using namespace std; void readfile(char *pathName, string &str1, string &str2, int time); int main() { string str1, str2; int time; char *pathName = "./txt_list/read2.txt"; cout << "time : "; cin >> time; readfile(pathName, str1, str2, time); cout << str1 << endl; cout << str2 << endl; return 0; } void readfile(char *pathName, string &str1, string &str2, int time) { // char *pathName = "./read.txt"; char buf[1]; char c; int fd = 0, rsize = 0, enter = 0; list<char> list_full; // list<char> list_cur; // list<char> list_next; list<char>::iterator it; fd = open(pathName, O_RDONLY, 0644); rsize = read(fd, buf, 1); //---------- 1 글자씩 읽어서 list_full 에 저장 --------- do { list_full.push_back(buf[0]); memset(buf, '\0', sizeof(buf)); rsize = read(fd, buf, 1); } while (rsize > 0); int size = list_full.size(); char arr_full[size]; int i = -1; //----------- list_full을 arr_full로 옮김 ------------- for (it = list_full.begin(); it != list_full.end();) { arr_full[++i] = *(it++); } // ---------- cur와 next를 저장 ------------------------ int index = 0; i = 0; int save = 0; time += 1; while (time > 0) { char arr_cur[256] = { '\0', }; char arr_next[256] = { '\0', }; i = 0; int cur_len = 0, next_len = 0; index = save; while (index < size) { if (arr_full[index] == '\n') { index++; break; } else { arr_cur[i] = arr_full[index]; i++; index++; save++; cur_len++; } } save = index; i = 0; while (index < size) { if (arr_full[index] == '\n') { index++; break; } else { arr_next[i] = arr_full[index]; i++; index++; next_len++; } } // list<char> list_cur(arr_cur, arr_cur + cur_len); // list<char> list_next(arr_next, arr_next + next_len); if (time == 1) { for (int i = 0; i < cur_len; i++) { str1.push_back(arr_cur[i]); } for (int i = 0; i < next_len; i++) { str2.push_back(arr_next[i]); } } time--; } }
true
660a82571391ffc023303581f041c8598b074cfd
C++
MalinovayaZaya/Voenmeh-4sem
/system_software-main/pseudo-interpreter/src/ConditionInterpreter/ConditionInterpreter.cpp
UTF-8
3,130
3.125
3
[]
no_license
#include "ConditionInterpreter.hpp" bool execute_logic_expression(std::string str) { math_token result = _execute_expression( variable_controller::instance().fill_string_with_variables(str) ); if (result.type == token_type::number) { return (bool) std::stoll(result.value); } if (result.type == token_type::float_number) { return (bool) std::stold(result.value); } return false; } std::string find_logic_expression( std::string & str, std::string operator_name, size_t & condition_block_length ) { size_t bracket_depth = 0; token_type tt; if (str[condition_block_length++] != '(') { throw std::logic_error(operator_name + " condition must be into rounded brackets and follow behind it"); } else { bracket_depth++; } while (bracket_depth != 0 && condition_block_length < str.size()) { tt = char_type_func(str[condition_block_length++]); if (tt == token_type::bracket_open) { bracket_depth++; } else if (tt == token_type::bracket_close) { bracket_depth--; } } if (bracket_depth != 0) { throw std::logic_error(operator_name + " condition must be into rounded brackets and follow behind it"); } if (condition_block_length == str.size()) { throw std::logic_error(operator_name + " statement missed"); } return str.substr(0, condition_block_length); } size_t get_bindex_of_statement( std::string & str, std::string operator_name, size_t & condition_block_length ) { size_t bracket_depth = 0; token_type tt; if (str[condition_block_length++] != '{') { throw std::logic_error(operator_name + " statement must be into figured brackets and follow behind condition"); } else { bracket_depth++; } size_t statement_bindex = condition_block_length; while (bracket_depth != 0 && condition_block_length < str.size()) { tt = char_type_func(str[condition_block_length++]); if (tt == token_type::figured_bracket_open) { bracket_depth++; } else if (tt == token_type::figured_bracket_close) { bracket_depth--; } } if (bracket_depth != 0) { throw std::logic_error(operator_name + " statement must be into figured brackets and follow behind condition"); } return statement_bindex; } size_t if_proccessing(std::string input) { size_t condition_block_length = 0; bool condition_state = execute_logic_expression( find_logic_expression(input, "Operator-if", condition_block_length) ); size_t statement_bindex = get_bindex_of_statement(input, "Operator-if", condition_block_length); size_t statement_eindex = condition_block_length - 1; std::regex re("[a-zA-Z]\\w*"); if (std::sregex_iterator( input.begin() + condition_block_length, input.end(), re )->str() == "else") { condition_block_length += 4; size_t tmp = get_bindex_of_statement(input, "Operator-else", condition_block_length); if (!condition_state) statement_bindex = tmp; if (!condition_state) statement_eindex = condition_block_length; } interpreter_code(input.substr(statement_bindex, statement_eindex - statement_bindex)); return condition_block_length - 1; }
true
31c2870b279cd83dd180bdb418e824b38f09bc19
C++
mtraja/cpp-playground
/basic-oop-fun/main.cpp
UTF-8
313
3.265625
3
[ "Unlicense" ]
permissive
#include <iostream> using namespace std; class Printer { public: Printer(){ cout << "Creating Printer object. " << endl; } void print(string msg) { cout << msg << endl; } }; int main(){ Printer printer = Printer(); printer.print("Hi cpp!"); return 0; }
true
b5b47c005ffac4bf5f368d3d956319f4201e53ae
C++
jonsim/robin-project
/Common.cpp
UTF-8
2,628
2.75
3
[ "MIT" ]
permissive
#include "Common.h" sint8_t make_sint8_t (const uint8_t b) { return (b - 0xFF); } uint16_t make_uint16_t (const uint8_t bh, const uint8_t bl) { uint16_t r = (bh << 8) + bl; return r; } sint16_t make_sint16_t (const uint8_t bh, const uint8_t bl) { // sint16_t r = ((bh << 8) + bl) - 0xFFFF; sint16_t r = bl + ((bh & 0x7f) << 8) - ((bh & 0x80) << 8); // printf("bh=%x, bl = %x, r = %x, %d\n", bh, bl, r, r); return r; } float euclidean_distance (const Point2i& p1, const Point2i& p2) { float dx = (float) p1.x - p2.x; float dy = (float) p1.y - p2.y; return sqrt(dx*dx + dy*dy); } float euclidean_distance2 (const Point2i& p1, const Point2i& p2) { float dx = (float) p1.x - p2.x; float dy = (float) p1.y - p2.y; return dx*dx + dy*dy; } /// @brief Uses the Box-Muller transform to generate a single normally distributed random number. /// NB: This is not efficient. If I find myself calling it a lot consider using the polar /// form of the transform or potentially even the Ziggurat algorithm. /// NB: rand() must be seeded when this function is called. If in doubt, srand! /// @param mu The mean of the distribution. /// @param sigma The standard deviation of the distribution. /// @return A random number normally distributed according to the supplied parameters. float randNormallyDistributed (float mu, float sigma) { float U1 = ((float) rand()) / ((float) RAND_MAX); float U2 = ((float) rand()) / ((float) RAND_MAX); float Z0 = sqrt(-2 * log(U1)) * cos(2 * PI * U2); return (Z0 * sigma) + mu; } void msleep (const uint32_t msec) { usleep(msec * 1000); } int _kbhit (void) { static const int STDIN = 0; static bool initialized = false; if (! initialized) { // Use termios to turn off line buffering termios term; tcgetattr(STDIN, &term); term.c_lflag &= ~ICANON; tcsetattr(STDIN, TCSANOW, &term); setbuf(stdin, NULL); initialized = true; } int bytesWaiting; ioctl(STDIN, FIONREAD, &bytesWaiting); return bytesWaiting; } /// @brief Code snippet from stackoverflow std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) elems.push_back(item); return elems; } /// @brief Code snippet from stackoverflow std::vector<std::string> split(const std::string& s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; }
true
54664f61b152c1439ee3d4be139d03792a0d18f3
C++
thundercumt/leetspeak
/9.cpp
UTF-8
523
3.328125
3
[]
no_license
#include <iostream> using namespace std; class Solution { public: bool isPalindrome(int x) { int xx = x; int t=0; if (x < 0) return false; else if (x < 10) return true; while(xx) { t *= 10; t += xx % 10; xx /= 10; } return x == t; } }; #ifdef DEBUG int main() { Solution s; cout << s.isPalindrome(121) << '\n'; cout << s.isPalindrome(0) << '\n'; cout << s.isPalindrome(10) << '\n'; cout << s.isPalindrome(-121) << '\n'; } #endif
true
2e1a50dd924977e8473c1164d659677041ab2406
C++
chilin0525/NCTUCS_Database_HW2
/utils.cpp
UTF-8
2,100
3.078125
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include "utils.h" using namespace std; void read_input_file(int& num_rows, vector<int>& key, vector<int>& value) { //readfile fstream file; file.open("data.txt"); string line; while(getline(file, line, '\n')) { istringstream templine(line); string data; getline(templine, data,','); key.push_back(atoi(data.c_str())); getline(templine, data,','); value.push_back(atoi(data.c_str())); num_rows += 1; } file.close(); cout << "Data file reading complete, " << num_rows << " rows loaded."<< endl; return; } void read_key_query_file(int& num_key_query, vector<int>& query_keys) { //readfile fstream file; file.open("key_query.txt"); string line; while(getline(file, line, '\n')) { istringstream templine(line); string data; getline(templine, data, ','); query_keys.push_back(atoi(data.c_str())); num_key_query += 1; } file.close(); cout << "Key query file reading complete, " << num_key_query << " queries loaded."<< endl; return; } void read_range_query_file(int& num_range_query, vector<pair<int,int>>& query_pairs) { //readfile fstream file; file.open("range_query.txt"); string line; while(getline(file, line, '\n')) { istringstream templine(line); string data1, data2; getline(templine, data1,','); getline(templine, data2,','); query_pairs.push_back({atoi(data1.c_str()),atoi(data2.c_str())}); num_range_query += 1; } file.close(); cout << "Range query file reading complete, " << num_range_query << " queries loaded."<< endl; return; } void record_time_used(int time_to_build_index, int time_to_query_key, int time_to_query_range) { ofstream file ("time_used.txt"); if(file.is_open()) { file << time_to_build_index << "," << time_to_query_key << "," << time_to_query_range << endl; file.close(); } }
true
ccb2c6f84fbbf076e5227386cd0bb99a7750ef5a
C++
liarchgh/MyCode
/USE/方传宇改pdf名称.cc
GB18030
2,802
2.8125
3
[]
no_license
#include <cstdio> #include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <map> #include <io.h> #include <algorithm> #include <cstring> #include <ctime> #include <sstream> using namespace std; map<string,string>id2name; int main(){ string indpath; string path2findPdfs; string pathOfPdfs; ifstream indfile; cout << "ļ·ļ" << endl; cin >> indpath; while(indfile.open(indpath.c_str()), !indfile){ cout << "ļʧܣļ·ļ" <<endl; cin >> indpath; } string nums, names; int ind = 1; while(!indfile.eof()){ nums = ""; indfile >> names; stringstream ss; ss << ind; ss >> nums; cout << names << "'s id is " << nums << endl; id2name[nums] = names; ++ind; } cout << "pdfļĿ¼·" << endl; cin >> pathOfPdfs; pathOfPdfs = pathOfPdfs; if(pathOfPdfs[pathOfPdfs.length()-1] != '\\'){ pathOfPdfs.append("\\"); } path2findPdfs = pathOfPdfs + "*"; intptr_t handle; _finddata_t findData; handle = _findfirst(path2findPdfs.c_str(), &findData); while(handle == -1){ cout << "pdf·pdfļĿ¼·" << endl; cin >> path2findPdfs; if(path2findPdfs[path2findPdfs.length()-1] != '\\'){ path2findPdfs.append("\\"); } path2findPdfs.append("*"); intptr_t handle; _finddata_t findData; handle = _findfirst(path2findPdfs.c_str(), &findData); } do{ if(!strcmp(findData.name, ".") || !strcmp(findData.name, "..")){continue;} string pdfnames(findData.name); string filetype = pdfnames.substr(pdfnames.find_last_of('.')+1); string orifiletype(filetype); transform(filetype.begin(), filetype.end(), filetype.begin(), ::toupper); if(!strcmp(filetype.c_str(), "PDF")){ cout << "" << pdfnames << "..."; int numIndS = pdfnames.find_first_of('_')+1, numIndE = pdfnames.find_last_of('_'); string nameNum = pdfnames.substr(numIndS, numIndE-numIndS); cout << "num is " << nameNum << endl; string newName = id2name[nameNum] + "." + orifiletype; if(_access((pathOfPdfs+pdfnames).c_str(), 0)){cout << "file not exits" << endl;} rename((pathOfPdfs+pdfnames).c_str(), (pathOfPdfs+newName).c_str()); cout << "Ϊ" << newName << "" << endl; } }while(_findnext(handle, &findData) != -1); _findclose(handle); cout << "Over."<<endl; system("pause"); return 0; }
true
3a67006ee81849e92b163130e7bd5bff07ba0041
C++
junhuizhou/Algorithm_Learn
/LeetCode/List/142_cycle_list_2.cpp
UTF-8
1,161
3.140625
3
[]
no_license
/* * @Author: junhuizhou * @Date: 2021-06-03 19:11:02 * @LastEditor: junhuizhou * @LastEditTime: 2021-06-03 20:24:16 * @Description: header * @FilePath: \LeetCode\List\142_cycle_list_2.cpp */ // 找打链表环的入口 struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; class Solution { public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr) return nullptr; ListNode* slow = head; ListNode* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; if (slow == fast) { ListNode* index1 = head; ListNode* index2 = fast; while (index1 != index2) { index1 = index1->next; index2 = index2->next; } return index1; } } return nullptr; } };
true
ddeea99c78c066ae9df4da40e5f7a53b306b4d41
C++
lyb1234567/C-plus-plus-
/复习/自定义动态二维数组以及静态变量的应用/复习.cpp
UTF-8
894
3.453125
3
[]
no_license
#include<iostream> #include<string> using namespace std; double **create_matrix(int, int); void disp_matrix(double**,int ,int); int increase(); int main() { double **matrix1=create_matrix(2,3); disp_matrix(matrix1, 2, 3); double** matrix2 = create_matrix(2, 3); disp_matrix(matrix2, 2, 3); return 0; } double **create_matrix(int m, int n) { double** matrix = new double *[m]; for (int i = 0; i < m; i++) { matrix[i] = new double [n]; } for (int i = 0; i < m; i++) { cout << "Row " << i + 1 << ": "; for (int j = 0; j < n; j++) { cin >> matrix[i][j]; } } return matrix; } void disp_matrix(double **matrix,int m,int n) { int j = increase(); cout << "Matrix " <<j<<endl; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cout << matrix[i][j] << "\t"; } cout << endl; } cout << endl; } int increase() { static int i = 0; i++; return i; }
true
2940f25b5052b1b74eee0f2a799d45010cd70a82
C++
patsonm/intro-to-cs
/Prototyping and Classes/Box copy.hpp
UTF-8
598
2.5625
3
[]
no_license
/********************************************************************* ** Author: Michael Patson ** Date: October 5, 2017 ** Description: Assignment 3a hpp box *********************************************************************/ #ifndef BOX_HPP #define BOX_HPP //Defines the interface of the Box Class class Box { private: double b_height; double b_width; double b_length; public: Box(); Box(double, double, double); void setHeight(double); void setWidth(double); void setLength(double); double calcVolume(); double calcSurfaceArea(); }; #endif
true
1403804fc294acfc4f3830752cf52699258317a6
C++
MassonY/ZeraVentureT1
/PhysicalEntity.cpp
UTF-8
1,724
2.859375
3
[]
no_license
#include "PhysicalEntity.h" b2World* PhysicalEntity::m_world; const float PhysicalEntity::SCALE = 30.0f; PhysicalEntity::PhysicalEntity(){ } void PhysicalEntity::setWorld(b2World* world){ m_world = world; } void PhysicalEntity::draw(sf::RenderTarget &target){ m_sprite.setPosition(BtoSF<float>(m_body->GetPosition())*PhysicalEntity::SCALE); m_sprite.setRotation(m_body->GetAngle() * 180 / b2_pi); draw(target, sf::RenderStates::Default); } void PhysicalEntity::draw(sf::RenderTarget &target, sf::RenderStates states) const { target.draw(m_sprite); } void PhysicalEntity::create(b2BodyType type, sf::Vector2f& Position, std::string& path, float density, float friction, float restitution, bool fixrotate){ b2BodyDef def; def.type = type; def.fixedRotation = fixrotate; def.position = SFtoB(Position / PhysicalEntity::SCALE); m_body = m_world->CreateBody(&def); m_sprite.setPosition(Position); m_sprite.setRotation(m_body->GetAngle() * 180 / b2_pi); m_body->SetUserData(this); m_sprite.setTexture(*TextureHolder::getTexture("player/" + path)); m_sprite.setOrigin(sf::Vector2f(m_sprite.getLocalBounds().width / 2, m_sprite.getLocalBounds().height / 2)); b2PolygonShape Box; Box.SetAsBox((m_sprite.getTexture()->getSize().x / 2) / PhysicalEntity::SCALE, (m_sprite.getTexture()->getSize().y / 2) / PhysicalEntity::SCALE); b2FixtureDef fixtureDef; fixtureDef.shape = &Box; fixtureDef.density = density; fixtureDef.friction = friction; fixtureDef.restitution = restitution; m_body->CreateFixture(&fixtureDef); } const sf::Vector2f& PhysicalEntity::getPosition(){ return m_sprite.getPosition(); } const sf::Vector2f& PhysicalEntity::getSize(){ return sf::Vector2f(m_sprite.getTexture()->getSize()); }
true
2da6d34b2af475c7ee03289dfdbbada3498fe914
C++
ahmadreza-n/AP-HW4
/C++/Q3/square.h
UTF-8
479
2.875
3
[]
no_license
#ifndef SQUARE_H #define SQUARE_H #include "twoDimensionalShape.h" class CSquare : public CTwoDimensionalShape { private: double sideLen; double centerX, centerY; public: CSquare(const double &sideLen_ = 0, const double &centerX_ = 0, const double &centerY_ = 0); virtual ~CSquare(); double area() const override final; void print(std::ostream &out) const override final; CSquare operator+(const CPoint &); //changes square center }; #endif
true
2ebdfd53f4c6ae0d397d028214122989cf497fe3
C++
bmjoy/IOCPGameServer
/GameServer/GameServer/Monster.cpp
UHC
1,204
2.875
3
[]
no_license
#include "stdafx.h" void Monster::Update(float dTime) { if (Hp != 0) { MapRangeCheck(); SetPosition(GetPosition() + GetVelocity() * (5 * dTime)); //std::cout << GetPosition().mX << " " << GetPosition().mY << " " << GetPosition().mZ << " " << std::endl; } } void Monster::MapRangeCheck() { if (GetPosition().mX <= -50|| GetPosition().mX >= 50) { Vector3 Dir; Dir.Set(GetVelocity().mX, 0, GetVelocity().mZ); Dir.mX = -Dir.mX; SetVelocity(Dir); } if (GetPosition().mZ <= -50 || GetPosition().mZ >= 50) { Vector3 Dir; Dir.Set(GetVelocity().mX, 0, GetVelocity().mZ); Dir.mZ = -Dir.mZ; SetVelocity(Dir); } } void Monster::CalcDamage(float Damage) { if (Hp > 0) { Hp -= Damage; std::cout <<"̵ : " <<GetNetworkId() << " ü : " <<Hp << std::endl; } else if (Hp <= 0.f) { Hp = 0; SetDie(true); } } void Monster::Write(OutputMemoryStream& os) { os.Write(GetNetworkId()); os.Write(GetPosition()); os.Write(GetVelocity()); os.Write(Hp); } float Monster::RandomSet(float min, float max) { std::random_device randDevice; std::mt19937 mt(randDevice()); std::uniform_real_distribution<float> distribution(min, max); return distribution(randDevice); }
true
ffe128f8fcd360acd1ab373d73b7b902898b35e1
C++
sebeneyi/cs112
/proj01/PlayList.h
UTF-8
684
2.796875
3
[]
no_license
/* * PlayList.h declares class PlayList. * * Created on: Feb 10, 2019 * Author: ssy3 at Calvin College for CS 112 proj01 */ #ifndef PLAYLIST_H_ #define PLAYLIST_H_ #include "Song.h" #include <vector> // STL vector #include <string> using namespace std; class PlayList { public: PlayList(const string& filename); unsigned getNumSongs() const; vector<Song> searchByArtist(const string& artist) const; vector<Song> searchByYear(unsigned year) const; vector<Song> searchByTitlePhrase(const string& phrase) const; vector<Song> addSong(const Song& newSong); vector<Song> removeSong(const Song& aSong); private: vector<Song> mySongs; }; #endif /* PLAYLIST_H_ */
true
ffda5d9cd6d6e65936ff540c9a0df4f36d562bfb
C++
Acnapse/Labs
/oop9/TTree.hpp
UTF-8
946
2.546875
3
[]
no_license
#ifndef TTree_H #define TTree_H #include "TIterator.h" #include "TTreeItem.hpp" #include <memory> #include <future> #include <mutex> #include <thread> template <class T> class TTree { public: TTree(); void push(T* item, size_t index); bool empty(); size_t size(); TIterator<TTreeItem<T>, T> begin() const; TIterator<TTreeItem<T>, T> end() const; std::shared_ptr<T> operator[] (size_t i); std::shared_ptr<T> pop(std::shared_ptr<T> item); void Get(); void walk(std::shared_ptr<TTreeItem<T>>, int fl); void Change(TIterator<TTreeItem<T>, T> item); // int Find (std::shared_ptr<T> item); template <class A> friend std::ostream& operator<<(std::ostream& os,const TTree<A>& tree); void RemoveSubitem(int32_t value); virtual ~TTree(); private: std::recursive_mutex tree_mutex; size_t count; std::shared_ptr<TTreeItem<T>> root; }; #endif /* TTree_H */
true
748c8f597c7e490438e185252305bf313035c3d1
C++
zgthompson/fa13
/cs315/lab11/OpenHash.h
UTF-8
1,132
3.390625
3
[]
no_license
#ifndef OPEN_HASH_H #define OPEN_HASH_H #include <iostream> #include <vector> #include <string> #include <list> #include <algorithm> class OpenHash { public: OpenHash(); OpenHash(int startSize); void insert(std::string key); bool contains(std::string key); void remove(std::string key); private: std::vector<std::list<std::string> > H; int hash(std::string key); }; OpenHash::OpenHash() { H.resize(1337); } OpenHash::OpenHash(int startSize) { H.resize(startSize); } void OpenHash::insert(std::string key) { int i = hash(key); if ( std::find(H[i].begin(), H[i].end(), key) == H[i].end()) { H[i].push_front(key); } } bool OpenHash::contains(std::string key) { int i = hash(key); return std::find(H[i].begin(), H[i].end(), key) != H[i].end(); } void OpenHash::remove(std::string key) { int i = hash(key); H[i].remove(key); } int OpenHash::hash(std::string key) { int result = 0; for (int i = 0; i < key.length(); ++i) { result = (256 * result + key[i]) % H.capacity(); } return result; } #endif
true
a72171dbda533471cdbe2bbc0d7257b7aeee01a5
C++
qinzhengke/zebra_cv
/unit_test/raw_bmp_view/main.cpp
UTF-8
697
2.71875
3
[]
no_license
#include "rawbmpwidget.h" #include <QApplication> #include <iostream> using namespace std; void print_hex(string str) { cout<<str<<" = { "; for(int i=0; i<str.size(); i++) { cout<<std::hex<<str.at(i)<<", "; } cout<<" }"<<endl; } void print_hex(char *str) { int N = strlen(str); int i = 0; printf("len= %d, \"%s\"= { ", N, str); for(i=0; i<N; i++) { printf("%x, ", str[i]); } printf("}\n"); } int main(int argc, char *argv[]) { QApplication a(argc, argv); RawBmpWidget rbw; rbw.show(); if(argc >= 2) { rbw.open(string(argv[1])); } return a.exec(); }
true
bd6de83e16e202b100dbede95290b4d8af5a3e67
C++
Michaelhobo/hpv_electronics
/sensor_temp/sensor_temp/user_functions.ino
UTF-8
1,691
3.078125
3
[]
no_license
/* User Functions - Sensor Template * These functions should perform appropriate actions at every cycle of the loop. * Collected and formatted data should be stored in write_buffer[1] * This file is meant to pull user-defined functions out of the base template, * so the template can change without fear of merge conflicts. */ #include <dht11.h> dht11 DHT11; #define DHT11PIN 3 int i = 0; /* Allows user to set things up. */ void user_setup() { //Celsius to Fahrenheit conversion Serial.println("DHT11 TEST PROGRAM "); Serial.print("LIBRARY VERSION: "); Serial.println(DHT11LIB_VERSION); Serial.println(); } /* This function is called before we send. */ void data_manipulation() { Serial.println("\n"); int chk = DHT11.read(DHT11PIN); Serial.print("Read sensor: "); switch (chk) { case DHTLIB_OK: Serial.println("OK"); break; case DHTLIB_ERROR_CHECKSUM: Serial.println("Checksum error"); break; case DHTLIB_ERROR_TIMEOUT: Serial.println("Time out error"); break; default: Serial.println("Unknown error"); break; } if (i == 1) { Serial.print("Humidity (%): "); Serial.println((float)DHT11.humidity, 2); write_buffer[0] = 5; write_buffer[1] = (uint8_t) DHT11.humidity; i = 0; } else { Serial.print("Temperature (°C): "); Serial.println((float)DHT11.temperature, 2); write_buffer[0] = 2; write_buffer[1] = (uint8_t) DHT11.temperature; i = 1; } delay(2000); } /* These functions are called after we send data, * and we're figuring out what state * we're going to switch to. */ void connected_action() {} void sleep_action() {} void deep_sleep_action() {}
true
a95b765a7182e802caace3e5063a0949bcac51f6
C++
OUC-MYM/HDU
/2013.cpp
UTF-8
253
2.71875
3
[]
no_license
#include<iostream> using namespace std; int stop; int ans(int n) { if(n==stop) return 1; return (ans(++n)+1)*2; } int main() { int n; while(cin >> n) { stop=n; cout << ans(1) << endl; } return 0; }
true
92f410356d7f01be22a71e704c58356f505839a2
C++
NirViaje/node-serial
/embedded-code/Neopixel-Effect-Generator-adrianotiger/Neopixel-Effect-Generator-adrianotiger.ino
UTF-8
17,256
2.703125
3
[ "Apache-2.0" ]
permissive
#include <Adafruit_NeoPixel.h> class Strip { public: uint8_t effect; uint8_t effects; uint16_t effStep; unsigned long effStart; Adafruit_NeoPixel strip; Strip(uint16_t leds, uint8_t pin, uint8_t toteffects, uint16_t striptype) : strip(leds, pin, striptype) { effect = -1; effects = toteffects; Reset(); } void Reset(){ effStep = 0; effect = (effect + 1) % effects; effStart = millis(); } }; struct Loop { uint8_t currentChild; uint8_t childs; bool timeBased; uint16_t cycles; uint16_t currentTime; Loop(uint8_t totchilds, bool timebased, uint16_t tottime) {currentTime=0;currentChild=0;childs=totchilds;timeBased=timebased;cycles=tottime;} }; Strip strip_0(60, 8, 60, NEO_GRB + NEO_KHZ800); Strip strip_1(60, 9, 60, NEO_GRB + NEO_KHZ800); Strip strip_2(60, 10, 60, NEO_GRB + NEO_KHZ800); Strip strip_3(60, 11, 60, NEO_GRB + NEO_KHZ800); Strip strip_4(60, 12, 60, NEO_GRB + NEO_KHZ800); Strip strip_5(60, 13, 60, NEO_GRB + NEO_KHZ800); Strip strip_6(60, 14, 60, NEO_GRB + NEO_KHZ800); Strip strip_7(60, 15, 60, NEO_GRB + NEO_KHZ800); Strip strip_8(60, 16, 60, NEO_GRB + NEO_KHZ800); struct Loop strip0loop0(2, false, 1); struct Loop strip1loop0(0, false, 1); struct Loop strip2loop0(0, false, 1); struct Loop strip3loop0(1, false, 1); struct Loop strip4loop0(2, false, 1); struct Loop strip4loop00(3, false, 1); struct Loop strip5loop0(1, false, 1); struct Loop strip6loop0(0, false, 1); struct Loop strip7loop0(0, false, 1); struct Loop strip8loop0(2, false, 1); //[GLOBAL_VARIABLES] void setup() { //Your setup here: strip_0.strip.begin(); strip_1.strip.begin(); strip_2.strip.begin(); strip_3.strip.begin(); strip_4.strip.begin(); strip_5.strip.begin(); strip_6.strip.begin(); strip_7.strip.begin(); strip_8.strip.begin(); } void loop() { //Your code here: strips_loop(); } void strips_loop() { if(strip0_loop0() & 0x01) strip_0.strip.show(); if(strip1_loop0() & 0x01) strip_1.strip.show(); if(strip2_loop0() & 0x01) strip_2.strip.show(); if(strip3_loop0() & 0x01) strip_3.strip.show(); if(strip4_loop0() & 0x01) strip_4.strip.show(); if(strip5_loop0() & 0x01) strip_5.strip.show(); if(strip6_loop0() & 0x01) strip_6.strip.show(); if(strip7_loop0() & 0x01) strip_7.strip.show(); if(strip8_loop0() & 0x01) strip_8.strip.show(); } uint8_t strip0_loop0() { uint8_t ret = 0x00; switch(strip0loop0.currentChild) { case 0: ret = strip0_loop0_eff0();break; case 1: ret = strip0_loop0_eff1();break; } if(ret & 0x02) { ret &= 0xfd; if(strip0loop0.currentChild + 1 >= strip0loop0.childs) { strip0loop0.currentChild = 0; if(++strip0loop0.currentTime >= strip0loop0.cycles) {strip0loop0.currentTime = 0; ret |= 0x02;} } else { strip0loop0.currentChild++; } }; return ret; } uint8_t strip0_loop0_eff0() { // Strip ID: 0 - Effect: Move - LEDS: 60 // Steps: 60 - Delay: 50 // Colors: 0 () // Options: toLeft=true, rotate=true, if(millis() - strip_0.effStart < 50 * (strip_0.effStep)) return 0x00; uint32_t c = strip_0.strip.getPixelColor(0); for(uint16_t j=0;j<59;j++) strip_0.strip.setPixelColor(j, strip_0.strip.getPixelColor(j+1)); strip_0.strip.setPixelColor(59, c); if(strip_0.effStep >= 60) {strip_0.Reset(); return 0x03; } else strip_0.effStep++; return 0x01; } uint8_t strip0_loop0_eff1() { // Strip ID: 0 - Effect: Rainbow - LEDS: 60 // Steps: 60 - Delay: 20 // Colors: 3 (255.0.0, 0.255.0, 0.0.255) // Options: rainbowlen=60, toLeft=true, if(millis() - strip_0.effStart < 20 * (strip_0.effStep)) return 0x00; float factor1, factor2; uint16_t ind; for(uint16_t j=0;j<60;j++) { ind = strip_0.effStep + j * 1; switch((int)((ind % 60) / 20)) { case 0: factor1 = 1.0 - ((float)(ind % 60 - 0 * 20) / 20); factor2 = (float)((int)(ind - 0) % 60) / 20; strip_0.strip.setPixelColor(j, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2); break; case 1: factor1 = 1.0 - ((float)(ind % 60 - 1 * 20) / 20); factor2 = (float)((int)(ind - 20) % 60) / 20; strip_0.strip.setPixelColor(j, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2); break; case 2: factor1 = 1.0 - ((float)(ind % 60 - 2 * 20) / 20); factor2 = (float)((int)(ind - 40) % 60) / 20; strip_0.strip.setPixelColor(j, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2); break; } } if(strip_0.effStep >= 60) {strip_0.Reset(); return 0x03; } else strip_0.effStep++; return 0x01; } uint8_t strip1_loop0() { uint8_t ret = 0x00; switch(strip1loop0.currentChild) { } if(ret & 0x02) { ret &= 0xfd; if(strip1loop0.currentChild + 1 >= strip1loop0.childs) { strip1loop0.currentChild = 0; if(++strip1loop0.currentTime >= strip1loop0.cycles) {strip1loop0.currentTime = 0; ret |= 0x02;} } else { strip1loop0.currentChild++; } }; return ret; } uint8_t strip2_loop0() { uint8_t ret = 0x00; switch(strip2loop0.currentChild) { } if(ret & 0x02) { ret &= 0xfd; if(strip2loop0.currentChild + 1 >= strip2loop0.childs) { strip2loop0.currentChild = 0; if(++strip2loop0.currentTime >= strip2loop0.cycles) {strip2loop0.currentTime = 0; ret |= 0x02;} } else { strip2loop0.currentChild++; } }; return ret; } uint8_t strip3_loop0() { uint8_t ret = 0x00; switch(strip3loop0.currentChild) { case 0: ret = strip3_loop0_eff0();break; } if(ret & 0x02) { ret &= 0xfd; if(strip3loop0.currentChild + 1 >= strip3loop0.childs) { strip3loop0.currentChild = 0; if(++strip3loop0.currentTime >= strip3loop0.cycles) {strip3loop0.currentTime = 0; ret |= 0x02;} } else { strip3loop0.currentChild++; } }; return ret; } uint8_t strip3_loop0_eff0() { // Strip ID: 3 - Effect: Fade - LEDS: 60 // Steps: 20 - Delay: 5 // Colors: 2 (0.0.0, 255.255.255) // Options: duration=100, every=1, if(millis() - strip_3.effStart < 5 * (strip_3.effStep)) return 0x00; uint8_t r,g,b; double e; e = (strip_3.effStep * 5) / (double)100; r = ( e ) * 255 + 0 * ( 1.0 - e ); g = ( e ) * 255 + 0 * ( 1.0 - e ); b = ( e ) * 255 + 0 * ( 1.0 - e ); for(uint16_t j=0;j<60;j++) { if((j % 1) == 0) strip_3.strip.setPixelColor(j, r, g, b); else strip_3.strip.setPixelColor(j, 0, 0, 0); } if(strip_3.effStep >= 20) {strip_3.Reset(); return 0x03; } else strip_3.effStep++; return 0x01; } uint8_t strip4_loop0() { uint8_t ret = 0x00; switch(strip4loop0.currentChild) { case 0: ret = strip4_loop0_eff0();break; case 1: ret = strip4_loop00();break; } if(ret & 0x02) { ret &= 0xfd; if(strip4loop0.currentChild + 1 >= strip4loop0.childs) { strip4loop0.currentChild = 0; if(++strip4loop0.currentTime >= strip4loop0.cycles) {strip4loop0.currentTime = 0; ret |= 0x02;} } else { strip4loop0.currentChild++; } }; return ret; } uint8_t strip4_loop0_eff0() { // Strip ID: 4 - Effect: Move - LEDS: 60 // Steps: 60 - Delay: 50 // Colors: 0 () // Options: toLeft=true, rotate=true, if(millis() - strip_4.effStart < 50 * (strip_4.effStep)) return 0x00; uint32_t c = strip_4.strip.getPixelColor(0); for(uint16_t j=0;j<59;j++) strip_4.strip.setPixelColor(j, strip_4.strip.getPixelColor(j+1)); strip_4.strip.setPixelColor(59, c); if(strip_4.effStep >= 60) {strip_4.Reset(); return 0x03; } else strip_4.effStep++; return 0x01; } uint8_t strip4_loop00() { uint8_t ret = 0x00; switch(strip4loop00.currentChild) { case 0: ret = strip4_loop00_eff0();break; case 1: ret = strip4_loop00_eff1();break; case 2: ret = strip4_loop00_eff2();break; } if(ret & 0x02) { ret &= 0xfd; if(strip4loop00.currentChild + 1 >= strip4loop00.childs) { strip4loop00.currentChild = 0; if(++strip4loop00.currentTime >= strip4loop00.cycles) {strip4loop00.currentTime = 0; ret |= 0x02;} } else { strip4loop00.currentChild++; } }; return ret; } uint8_t strip4_loop00_eff0() { // Strip ID: 4 - Effect: Blink - LEDS: 60 // Steps: 36 - Delay: 5 // Colors: 2 (66.121.172, 138.255.255) // Options: timeBegin=50, timeToOn=10, timeOn=10, timeToOff=10, timeOver=100, every=1, if(millis() - strip_4.effStart < 5 * (strip_4.effStep)) return 0x00; uint8_t e,r,g,b; if(strip_4.effStep < 10) { for(uint16_t j=0;j<60;j++) strip_4.strip.setPixelColor(j, 66, 121, 172); } else if(strip_4.effStep < 12) { e = (strip_4.effStep * 5) - 50; r = 138 * ( e / 10 ) + 66 * ( 1.0 - e / 10 ); g = 255 * ( e / 10 ) + 121 * ( 1.0 - e / 10 ); b = 255 * ( e / 10 ) + 172 * ( 1.0 - e / 10 ); for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_4.strip.setPixelColor(j, r, g, b); else strip_4.strip.setPixelColor(j, 66, 121, 172); } else if(strip_4.effStep < 14) { for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_4.strip.setPixelColor(j, 138, 255, 255); else strip_4.strip.setPixelColor(j, 66, 121, 172); } else if(strip_4.effStep < 16) { e = (strip_4.effStep * 5) - 70; r = 66 * ( e / 10 ) + 138 * ( 1.0 - e / 10 ); g = 121 * ( e / 10 ) + 255 * ( 1.0 - e / 10 ); b = 172 * ( e / 10 ) + 255 * ( 1.0 - e / 10 ); for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_4.strip.setPixelColor(j, r, g, b); else strip_4.strip.setPixelColor(j, 66, 121, 172); } else { for(uint16_t j=0;j<60;j++) strip_4.strip.setPixelColor(j, 66, 121, 172); } if(strip_4.effStep >= 36) {strip_4.Reset(); return 0x03; } else strip_4.effStep++; return 0x01; } uint8_t strip4_loop00_eff1() { // Strip ID: 4 - Effect: Rainbow - LEDS: 60 // Steps: 60 - Delay: 20 // Colors: 3 (255.0.0, 0.255.0, 0.0.255) // Options: rainbowlen=60, toLeft=true, if(millis() - strip_4.effStart < 20 * (strip_4.effStep)) return 0x00; float factor1, factor2; uint16_t ind; for(uint16_t j=0;j<60;j++) { ind = strip_4.effStep + j * 1; switch((int)((ind % 60) / 20)) { case 0: factor1 = 1.0 - ((float)(ind % 60 - 0 * 20) / 20); factor2 = (float)((int)(ind - 0) % 60) / 20; strip_4.strip.setPixelColor(j, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2); break; case 1: factor1 = 1.0 - ((float)(ind % 60 - 1 * 20) / 20); factor2 = (float)((int)(ind - 20) % 60) / 20; strip_4.strip.setPixelColor(j, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2); break; case 2: factor1 = 1.0 - ((float)(ind % 60 - 2 * 20) / 20); factor2 = (float)((int)(ind - 40) % 60) / 20; strip_4.strip.setPixelColor(j, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2); break; } } if(strip_4.effStep >= 60) {strip_4.Reset(); return 0x03; } else strip_4.effStep++; return 0x01; } uint8_t strip4_loop00_eff2() { // Strip ID: 4 - Effect: Move - LEDS: 60 // Steps: 60 - Delay: 50 // Colors: 0 () // Options: toLeft=false, rotate=true, if(millis() - strip_4.effStart < 50 * (strip_4.effStep)) return 0x00; uint32_t c = strip_4.strip.getPixelColor(59); for(uint16_t j=60-1;j>0;j--) strip_4.strip.setPixelColor(j, strip_4.strip.getPixelColor(j-1)); strip_4.strip.setPixelColor(0, c); if(strip_4.effStep >= 60) {strip_4.Reset(); return 0x03; } else strip_4.effStep++; return 0x01; } uint8_t strip5_loop0() { uint8_t ret = 0x00; switch(strip5loop0.currentChild) { case 0: ret = strip5_loop0_eff0();break; } if(ret & 0x02) { ret &= 0xfd; if(strip5loop0.currentChild + 1 >= strip5loop0.childs) { strip5loop0.currentChild = 0; if(++strip5loop0.currentTime >= strip5loop0.cycles) {strip5loop0.currentTime = 0; ret |= 0x02;} } else { strip5loop0.currentChild++; } }; return ret; } uint8_t strip5_loop0_eff0() { // Strip ID: 5 - Effect: Fade - LEDS: 60 // Steps: 20 - Delay: 5 // Colors: 2 (0.0.0, 255.255.255) // Options: duration=100, every=1, if(millis() - strip_5.effStart < 5 * (strip_5.effStep)) return 0x00; uint8_t r,g,b; double e; e = (strip_5.effStep * 5) / (double)100; r = ( e ) * 255 + 0 * ( 1.0 - e ); g = ( e ) * 255 + 0 * ( 1.0 - e ); b = ( e ) * 255 + 0 * ( 1.0 - e ); for(uint16_t j=0;j<60;j++) { if((j % 1) == 0) strip_5.strip.setPixelColor(j, r, g, b); else strip_5.strip.setPixelColor(j, 0, 0, 0); } if(strip_5.effStep >= 20) {strip_5.Reset(); return 0x03; } else strip_5.effStep++; return 0x01; } uint8_t strip6_loop0() { uint8_t ret = 0x00; switch(strip6loop0.currentChild) { } if(ret & 0x02) { ret &= 0xfd; if(strip6loop0.currentChild + 1 >= strip6loop0.childs) { strip6loop0.currentChild = 0; if(++strip6loop0.currentTime >= strip6loop0.cycles) {strip6loop0.currentTime = 0; ret |= 0x02;} } else { strip6loop0.currentChild++; } }; return ret; } uint8_t strip7_loop0() { uint8_t ret = 0x00; switch(strip7loop0.currentChild) { } if(ret & 0x02) { ret &= 0xfd; if(strip7loop0.currentChild + 1 >= strip7loop0.childs) { strip7loop0.currentChild = 0; if(++strip7loop0.currentTime >= strip7loop0.cycles) {strip7loop0.currentTime = 0; ret |= 0x02;} } else { strip7loop0.currentChild++; } }; return ret; } uint8_t strip8_loop0() { uint8_t ret = 0x00; switch(strip8loop0.currentChild) { case 0: ret = strip8_loop0_eff0();break; case 1: ret = strip8_loop0_eff1();break; } if(ret & 0x02) { ret &= 0xfd; if(strip8loop0.currentChild + 1 >= strip8loop0.childs) { strip8loop0.currentChild = 0; if(++strip8loop0.currentTime >= strip8loop0.cycles) {strip8loop0.currentTime = 0; ret |= 0x02;} } else { strip8loop0.currentChild++; } }; return ret; } uint8_t strip8_loop0_eff0() { // Strip ID: 8 - Effect: Rainbow - LEDS: 60 // Steps: 60 - Delay: 20 // Colors: 3 (255.0.0, 0.255.0, 0.0.255) // Options: rainbowlen=60, toLeft=true, if(millis() - strip_8.effStart < 20 * (strip_8.effStep)) return 0x00; float factor1, factor2; uint16_t ind; for(uint16_t j=0;j<60;j++) { ind = strip_8.effStep + j * 1; switch((int)((ind % 60) / 20)) { case 0: factor1 = 1.0 - ((float)(ind % 60 - 0 * 20) / 20); factor2 = (float)((int)(ind - 0) % 60) / 20; strip_8.strip.setPixelColor(j, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2); break; case 1: factor1 = 1.0 - ((float)(ind % 60 - 1 * 20) / 20); factor2 = (float)((int)(ind - 20) % 60) / 20; strip_8.strip.setPixelColor(j, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2, 0 * factor1 + 255 * factor2); break; case 2: factor1 = 1.0 - ((float)(ind % 60 - 2 * 20) / 20); factor2 = (float)((int)(ind - 40) % 60) / 20; strip_8.strip.setPixelColor(j, 0 * factor1 + 255 * factor2, 0 * factor1 + 0 * factor2, 255 * factor1 + 0 * factor2); break; } } if(strip_8.effStep >= 60) {strip_8.Reset(); return 0x03; } else strip_8.effStep++; return 0x01; } uint8_t strip8_loop0_eff1() { // Strip ID: 8 - Effect: Blink - LEDS: 60 // Steps: 46 - Delay: 5 // Colors: 2 (0.0.0, 255.255.255) // Options: timeBegin=50, timeToOn=39, timeOn=31, timeToOff=10, timeOver=100, every=1, if(millis() - strip_8.effStart < 5 * (strip_8.effStep)) return 0x00; uint8_t e,r,g,b; if(strip_8.effStep < 10) { for(uint16_t j=0;j<60;j++) strip_8.strip.setPixelColor(j, 0, 0, 0); } else if(strip_8.effStep < 17.8) { e = (strip_8.effStep * 5) - 50; r = 255 * ( e / 39 ) + 0 * ( 1.0 - e / 39 ); g = 255 * ( e / 39 ) + 0 * ( 1.0 - e / 39 ); b = 255 * ( e / 39 ) + 0 * ( 1.0 - e / 39 ); for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_8.strip.setPixelColor(j, r, g, b); else strip_8.strip.setPixelColor(j, 0, 0, 0); } else if(strip_8.effStep < 24) { for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_8.strip.setPixelColor(j, 255, 255, 255); else strip_8.strip.setPixelColor(j, 0, 0, 0); } else if(strip_8.effStep < 26) { e = (strip_8.effStep * 5) - 120; r = 0 * ( e / 10 ) + 255 * ( 1.0 - e / 10 ); g = 0 * ( e / 10 ) + 255 * ( 1.0 - e / 10 ); b = 0 * ( e / 10 ) + 255 * ( 1.0 - e / 10 ); for(uint16_t j=0;j<60;j++) if((j%1)==0) strip_8.strip.setPixelColor(j, r, g, b); else strip_8.strip.setPixelColor(j, 0, 0, 0); } else { for(uint16_t j=0;j<60;j++) strip_8.strip.setPixelColor(j, 0, 0, 0); } if(strip_8.effStep >= 46) {strip_8.Reset(); return 0x03; } else strip_8.effStep++; return 0x01; }
true
05a6c7a98ee3ec0efad7398c2db2a7b61f80de61
C++
MacaScull/Vigenere-Cipher
/Vigenere cipher/Source.cpp
UTF-8
2,377
4.03125
4
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; //Bound checker, if value exceeds the high limit when excrypting - 26, if value exceeds the low limit for decryption + 26, otherwise return the value int boundCheck(int low, int high, int value, bool crypt) { if (crypt == true) { if (high < value) return value - 26; else return value; } else { if (low > value) return value + 26; else return value; } } //Converter, if the input value is uppercase then bound check with uppercase limits char convert(char input, int shift, bool crypt) { if (isupper(input) == 1) return boundCheck(65, 90, (input + shift), crypt); else return boundCheck(97, 122, (input + shift), crypt); } /*cryption, runs through each character in the input, skipping symbols and numbers. Resetting the key iterator, ensuring key values are repeated. Obtaining the shift, getting the lower value and subtracting the low limit. Converting the character based on a boolean; encrypt or decrypt. Finally, adding the char to a string, incrementing the iterator and returning the output*/ string crypt(string input, string key, bool crypt) { string output; int iter = 0; int shift; for (int i = 0; i < input.length(); i++) { if (isalpha(input[i]) == 0) { output += input[i]; continue; } if (iter > key.length() - 1) iter = 0; shift = (tolower(key[iter]) - 97); if (crypt == true) output += convert(input[i], shift, crypt); else output += convert(input[i], (shift * -1), crypt); iter++; } return output; } //Main function, asks for inputs and passed inputs into the cipher. int main() { string input; string output; string key; char value; cout << "Input a message" << endl; getline(cin, input); cout << "Input a key" << endl; cin >> key; cout << "Input a value to encrypt (Y) or decrypt (N)" << endl; cin >> value; if (value == 'Y') output = crypt(input, key, true); else if (value == 'N') output = crypt(input, key, false); cout << output; }
true
c58319738b4c5908397f14552c01268cdbac62be
C++
kbm0818/Portfolio
/GameProject/Object/Model/ModelBuffer.h
UTF-8
3,533
2.671875
3
[]
no_license
#pragma once class ModelBuffer : public ShaderBuffer { public: ModelBuffer() : ShaderBuffer(&data, sizeof(Data)) { data.ambient = D3DXCOLOR(0, 0, 0, 1); data.diffuse = D3DXCOLOR(0, 0, 0, 1); data.specular = D3DXCOLOR(0, 0, 0, 1); data.emissive = D3DXCOLOR(0, 0, 0, 1); data.normal = D3DXCOLOR(0, 0, 0, 1); //D3DXMatrixIdentity(&data.boneScale); D3DXMatrixScaling(&data.boneScale, 0.1f, 0.1f, 0.1f); for (int i = 0; i < 100; i++) D3DXMatrixIdentity(&data.boneArray[i]); data.isSkinning = false; } void SetSkinning(bool isSkinning) { data.isSkinning = (UINT)isSkinning; } void SetBoneArray(D3DXMATRIX* matrix, UINT count) { memcpy(data.boneArray, matrix, count * sizeof(D3DXMATRIX)); for (UINT i = 0; i < count; i++) D3DXMatrixTranspose(&data.boneArray[i], &data.boneArray[i]); } void SetBoneScale(D3DXMATRIX matrix) { data.boneScale = matrix; } D3DXCOLOR GetAmbient() { return data.ambient; } D3DXCOLOR GetDiffuse() { return data.diffuse; } D3DXCOLOR GetSpecular() { return data.specular; } D3DXCOLOR GetEmissive() { return data.emissive; } D3DXCOLOR GetNormal() { return data.normal; } void SetAmbient(D3DXCOLOR& color) { data.ambient = color; } void SetDiffuse(D3DXCOLOR& color) { data.diffuse = color; } void SetSpecular(D3DXCOLOR& color) { data.specular = color; } void SetEmissive(D3DXCOLOR& color) { data.emissive = color; } void SetNormal(D3DXCOLOR& color) { data.normal = color; } D3DXMATRIX GetBoneScale() { return data.boneScale; } struct Data { D3DXCOLOR ambient; D3DXCOLOR diffuse; D3DXCOLOR specular; D3DXCOLOR emissive; D3DXCOLOR normal; D3DXMATRIX boneScale; D3DXMATRIX boneArray[100]; UINT isSkinning; D3DXVECTOR3 padding; }; private: Data data; }; class MaterialBuffer : public ShaderBuffer { public: MaterialBuffer() : ShaderBuffer(&data, sizeof(Data)) { data.ambient = D3DXCOLOR(0, 0, 0, 1); data.diffuse = D3DXCOLOR(0, 0, 0, 1); data.specular = D3DXCOLOR(0, 0, 0, 1); data.emissive = D3DXCOLOR(0, 0, 0, 1); data.normal = D3DXCOLOR(0, 0, 0, 1); data.shininess = 0.0f; } D3DXCOLOR GetAmbient() { return data.ambient; } D3DXCOLOR GetDiffuse() { return data.diffuse; } D3DXCOLOR GetSpecular() { return data.specular; } D3DXCOLOR GetEmissive() { return data.emissive; } D3DXCOLOR GetNormal() { return data.normal; } void SetAmbient(D3DXCOLOR& color) { data.ambient = color; } void SetDiffuse(D3DXCOLOR& color) { data.diffuse = color; } void SetSpecular(D3DXCOLOR& color) { data.specular = color; } void SetEmissive(D3DXCOLOR& color) { data.emissive = color; } void SetNormal(D3DXCOLOR& color) { data.normal = color; } void SetShininess(float sh) { data.shininess = sh; } struct Data { D3DXCOLOR ambient; D3DXCOLOR diffuse; D3DXCOLOR specular; D3DXCOLOR emissive; D3DXCOLOR normal; float shininess; D3DXVECTOR3 padding; }; private: Data data; }; class SkeletonBuffer : public ShaderBuffer { public: SkeletonBuffer() : ShaderBuffer(&data, sizeof(Data)) { for (int i = 0; i < 100; i++) D3DXMatrixIdentity(&data.boneArray[i]); data.isSkinning = false; } void SetSkinning(bool isSkinning) { data.isSkinning = (UINT)isSkinning; } void SetBoneArray(D3DXMATRIX* matrix, UINT count) { memcpy(data.boneArray, matrix, count * sizeof(D3DXMATRIX)); for (UINT i = 0; i < count; i++) D3DXMatrixTranspose(&data.boneArray[i], &data.boneArray[i]); } struct Data { D3DXMATRIX boneArray[100]; UINT isSkinning; D3DXVECTOR3 padding; }; private: Data data; };
true
f4027d75e5223e65e875139b583f4b23f5bf6b21
C++
WASDi/sfml-graph-sandbox
/src/KruskalAlgorithm.h
UTF-8
334
2.546875
3
[]
no_license
#ifndef KRUSKALALGORITHM_H #define KRUSKALALGORITHM_H #include "Vertex.h" #include "Edge.h" #include <list> class KruskalAlgorithm { public: KruskalAlgorithm(std::list<Vertex*> vertices, std::list<Edge*> edges); void execute(); private: std::list<Vertex*> vertices; std::list<Edge*> edges; }; #endif /* KRUSKALALGORITHM_H */
true
8cbf25653743317690c43841e8390cbf6db0bcfb
C++
Ainslay/ColorMixing
/ColorMixing/ColorMixing.cpp
UTF-8
6,498
2.59375
3
[]
no_license
// Opracowane przez: Jakub Spałek, Aleksandra Pyrkosz #include <iostream> #include <stdlib.h> #include <GL/glut.h> using namespace std; enum State { MIRROR, SHADOW, NONE }; State state = NONE; GLfloat eyeX = 0.0; GLfloat eyeY = 40.0; GLfloat eyeZ = 50.0; GLfloat pointX = 0.5 * cos(-3.14 / 2); GLfloat pointY = 0.0; GLfloat pointZ = 0.5 * sin(-3.14 / 2); GLfloat lightPosition[] = { 100.0f, 100.0f, 50.0f, 1.0f }; GLfloat dimLight[] = { 0.25f, 0.25f, 0.25f, 1.0f }; GLfloat strongLight[] = { 1.0f, 1.0f, 1.0f, 1.0f }; GLfloat ambientMaterials[] = { 0.329412, 0.223529, 0.027451, 1.0 }; GLfloat diffuseMaterials[] = { 0.780392, 0.568627, 0.113725, 1.0 }; GLfloat specularMaterials[] = { 0.992157, 0.941176, 0.807843, 1.0 }; GLfloat shininessMaterials = 27.8974; GLfloat fLightPosition[] = { 100.0f, 100.0f, 50.0f, 1.0f }; GLfloat fLightPositionUnder[] = { 100.0f, -100.0f, 50.0f, 1.0f }; GLfloat transparency = 0.5f; GLfloat actorsRotate = 0.0f; void DrawActors(State state) { if (state == MIRROR) { actorsRotate += 0.5f; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glColor3f(0.7, 0.6, 0.0); glTranslatef(-3.0f, 10.0f, -5.0f); glRotatef(actorsRotate, 0, actorsRotate / 6, 1); glutSolidTeapot(3.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0.0, 0.0, 1.0, transparency); glTranslatef(10.0, 0.0, 9.0f); glutSolidTorus(1.0f, 3.0f, 32, 32); glDisable(GL_BLEND); glPopMatrix(); } else if (state == SHADOW) { glMatrixMode(GL_MODELVIEW); glEnable(GL_LIGHT0); glPushMatrix(); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glColor4f(0.0, 0.0, 0.0, 1.0); glTranslatef(-10.0f, 0.2f, -12.0f); glRotatef(actorsRotate, 0, actorsRotate / 6, 1); glScalef(1.2f, 0.02f, 1.2f); glutSolidTeapot(3.0f); glDisable(GL_BLEND); glEnable(GL_LIGHTING); glPopMatrix(); } else if (state == NONE) { actorsRotate += 0.5f; glMatrixMode(GL_MODELVIEW); glPushMatrix(); glColor3f(0.7, 0.6, 0.0); glTranslatef(-3.0f, 10.0f, -5.0f); glRotatef(actorsRotate, 0, actorsRotate / 6, 1); glutSolidTeapot(3.0f); glPopMatrix(); } } void DrawFloor() { glPushMatrix(); glMatrixMode(GL_MODELVIEW); glBegin(GL_TRIANGLES); glColor4f(0.0f, 1.0f, 0.0f, 0.5f); glVertex3f(0.0f, 0.0f, 150.0f); glVertex3f(0.0f, 0.0f, -150.0f); glVertex3f(130.0f, 0.0f, 0.0f); glColor4f(1.0f, 0.0f, 0.0f, 0.5f); glVertex3f(0.0f, 0.0f, 150.0f); glVertex3f(0.0f, 0.0f, -150.0f); glVertex3f(-130.0f, 0.0f, 0.0f); glEnd(); glPopMatrix(); } void Display() { glClearColor(0.0, 0.0, 0.0, 0.4); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); // materials glMaterialfv(GL_FRONT, GL_AMBIENT, ambientMaterials); glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuseMaterials); glMaterialfv(GL_FRONT, GL_SPECULAR, specularMaterials); glMateriali(GL_FRONT, GL_SHININESS, shininessMaterials); glPushMatrix(); glLoadIdentity(); // swiatło ogólne glLightfv(GL_LIGHT0, GL_AMBIENT, dimLight); glLightfv(GL_LIGHT0, GL_DIFFUSE, strongLight); glLightfv(GL_LIGHT0, GL_SPECULAR, strongLight); glPopMatrix(); glNormal3f(0.0f, 1.0f, 0.0f); if (state == MIRROR) { glPushMatrix(); gluLookAt(eyeX, eyeY, eyeZ, pointX, pointY, pointZ, 0.0, 1.0, 0.0); glLightfv(GL_LIGHT0, GL_POSITION, fLightPositionUnder); glPushMatrix(); glFrontFace(GL_CW); glScalef(1.0f, -1.0f, 1.0f); DrawActors(MIRROR); glFrontFace(GL_CCW); glPopMatrix(); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); DrawFloor(); glDisable(GL_BLEND); glEnable(GL_LIGHTING); glLightfv(GL_LIGHT0, GL_POSITION, fLightPosition); DrawActors(MIRROR); glPopMatrix(); } else if (state == SHADOW) { glPushMatrix(); gluLookAt(eyeX, eyeY, eyeZ, pointX, pointY, pointZ, 0.0, 1.0, 0.0); DrawFloor(); DrawActors(SHADOW); DrawActors(NONE); glPopMatrix(); } else { state = MIRROR; glEnable(GL_LIGHT0); glutPostRedisplay(); } glFlush(); glutSwapBuffers(); } void Reshape(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); if (width < height && width > 0) glFrustum(-1.0, 1.0, -1.0 * height / width, 1.0 * height / width, 2.0, 100.0); else if (width >= height && height > 0) glFrustum(-1.0 * width / height, 1.0 * width / height, -1.0, 1.0, 2.0, 100.0); glMatrixMode(GL_MODELVIEW); Display(); } void Key(unsigned char key, int x, int y) { switch (key) { case('+'): eyeZ = eyeZ - 1.0; break; case('-'): eyeZ = eyeZ + 1.0; break; case('1'): glEnable(GL_LIGHT0); break; case('2'): glDisable(GL_LIGHT0); break; case('s'): if (transparency <= 0.9) transparency += 0.1; break; case('a'): if (transparency >= 0.1) transparency -= 0.1; break; } Reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); } void SpecialKeys(int key, int x, int y) { switch (key) { case GLUT_KEY_LEFT: eyeX = eyeX - 1.0f; break; case GLUT_KEY_RIGHT: eyeX = eyeX + 1.0f; break; case GLUT_KEY_UP: eyeY = eyeY + 0.5f; break; case GLUT_KEY_DOWN: if (eyeY >= 1) eyeY = eyeY - 0.5f; break; } Reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT)); } void Menu(int value) { switch (value) { case MIRROR: state = MIRROR; break; case SHADOW: state = SHADOW; break; } } void TimerFunction(int value) { glutPostRedisplay(); glutTimerFunc(3, TimerFunction, 1); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowPosition(500, 100); glutInitWindowSize(800, 800); glutCreateWindow("Mieszanie kolorow - Jakub Spalek, Aleksandra Pyrkosz"); glutDisplayFunc(Display); glutReshapeFunc(Reshape); glutKeyboardFunc(Key); glutSpecialFunc(SpecialKeys); glutTimerFunc(33, TimerFunction, 1); glutCreateMenu(Menu); glutAddMenuEntry("Lustro", MIRROR); glutAddMenuEntry("Cienie", SHADOW); glutAttachMenu(GLUT_RIGHT_BUTTON); cout << "Ruch kamery: klawisze strzalek\n"; cout << "Zoom: [+]/[-]\n"; cout << "Przelacz swiatlo ogolne: [1]/[2]\n"; cout << "Zmiana przezroczystosci: [a]/[s]\n"; cout << "Wybor trybu: [PPM]"; glutMainLoop(); return 0; }
true
4eea40287a5a8ebaa4eabc7804f68e620cea6adc
C++
fursich/open_data_structure
/chapter3/practice/3_18/SEListDeque.h
UTF-8
2,438
3.734375
4
[]
no_license
#ifndef SELIST_DEQUE_H_ #define SELIST_DEQUE_H_ #include <iostream> #include "SEList.h" using namespace std; namespace data_structure { template <class T> class SEListDeque { protected: SEList<T>* front; SEList<T>* back; void balance(); T null; int b; /* arbitrary */ public: SEListDeque(); virtual ~SEListDeque(); int size(); T addFirst(T x); T removeFirst(); T addLast(T x); T removeLast(); void print_all(); }; template <class T> SEListDeque<T>::SEListDeque() { front = new SEList<T>; back = new SEList<T>; null = (T) NULL; } template <class T> SEListDeque<T>::~SEListDeque() { delete front; delete back; } template <class T> int SEListDeque<T>::size() { return front->size() + back->size(); } template <class T> void SEListDeque<T>::balance() { int n = size(); if (n <= 1) return; int i = (n+1)/2; if (i <= 0) return; if (3 * front->size() <= back->size() || 3 * back->size() <= front->size()) { cout << "balanced.." << endl; if(front->size() >= back->size()) { SEList<T> *new_front = front->truncate(front->size()-i); SEList<T> *transferred_list = SEList<T>::reverse(front); transferred_list->absorb(back); back = transferred_list; front = new_front; } else { SEList<T> *new_back = back->truncate(back->size()-i); SEList<T> *transferred_list = SEList<T>::reverse(back); transferred_list->absorb(front); front = transferred_list; back = new_back; } } } template <class T> T SEListDeque<T>::addFirst(T x) { front->push(x); balance(); return x; } template <class T> T SEListDeque<T>::addLast(T x) { back->push(x); balance(); return x; } template <class T> T SEListDeque<T>::removeFirst() { T y; if (front->size()==0 && back->size()==1) { y = back->pop(); /* the last one */ } else { y = front->pop(); } balance(); return y; } template <class T> T SEListDeque<T>::removeLast() { T y; if (back->size()==0 && front->size()==1) { y = front->pop(); /* the last one */ } else { y = back->pop(); } balance(); return y; } template <class T> inline void SEListDeque<T>::print_all() { SEList<T>::print_dual_stacks_with_counter_order(front, back); } } #endif
true
f499296e5c2a15609ee074706f6ad88a0df6b625
C++
haraldangell/GameInstitute
/7.9.1 Fraction Class/Fraction.cpp
UTF-8
2,706
3.703125
4
[]
no_license
#include <iostream> #include "Fraction.h" Fraction::Fraction() { mNumerator = 0.0f; mDenominator = 1.0f; } Fraction::Fraction(float num, float den) { mNumerator = num; mDenominator = den; } Fraction::~Fraction() { } void Fraction::Print() const { std::cout << "Numerator: " << mNumerator << std::endl << "Denominator: " << mDenominator << std::endl; } Fraction Fraction::operator+(const Fraction & rhs) const { Fraction sum; sum.mNumerator = mNumerator + rhs.mNumerator; sum.mDenominator = mNumerator + rhs.mDenominator; return sum; } Fraction Fraction::operator-(const Fraction & rhs) const { Fraction sum; sum.mNumerator = mNumerator - rhs.mNumerator; sum.mDenominator = mNumerator - rhs.mDenominator; return sum; } Fraction Fraction::operator*(const Fraction & rhs) const { Fraction sum; sum.mNumerator = mNumerator * rhs.mNumerator; sum.mDenominator = mNumerator * rhs.mDenominator; return sum; } Fraction Fraction::operator/(const Fraction & rhs) const { Fraction sum; if (rhs.mNumerator != 0 && rhs.mDenominator != 0) { sum.mNumerator = mNumerator / rhs.mNumerator; // = 0 NaN sum.mDenominator = mNumerator / rhs.mDenominator; } else { sum.mNumerator = 0.0f; sum.mDenominator = 1.0f; } return sum; } Fraction Fraction::operator=(const Fraction& rhs) const { Fraction f; f.mNumerator = rhs.mNumerator; f.mDenominator = rhs.mDenominator; return f; } bool Fraction::operator==(const Fraction & rhs) const { return mNumerator == rhs.mNumerator && mDenominator == rhs.mDenominator; } bool Fraction::operator!=(const Fraction & rhs) const // || = or and && = and { return mNumerator != rhs.mNumerator || mDenominator != rhs.mDenominator; } bool Fraction::operator<(const Fraction & rhs) const { return mNumerator < rhs.mNumerator && mDenominator < rhs.mDenominator; } bool Fraction::operator>(const Fraction & rhs) const { return mNumerator > rhs.mNumerator && mDenominator > rhs.mDenominator; } bool Fraction::operator<=(const Fraction & rhs) const { return mNumerator <= rhs.mNumerator && mDenominator <= rhs.mDenominator; } bool Fraction::operator>=(const Fraction & rhs) const { return mNumerator >= rhs.mNumerator && mDenominator >= rhs.mDenominator; } Fraction::operator float() const { float sum = 0.0f; if (mDenominator != 0.0f) sum = mNumerator / mDenominator; return sum; } std::istream& operator>>(std::istream& is, Fraction& v) { std::cout << "Enter Numerator: "; std::cin >> v.mNumerator; std::cout << "Enter Denominator: "; std::cin >> v.mDenominator; return is; } std::ostream& operator<<(std::ostream& os, const Fraction& v) { std::cout << "<" << v.mNumerator << ", " << v.mDenominator << "> \n"; return os; }
true
c80026fc50117b1a35c86883b85c75882368c562
C++
krzysztofMajchrzak-GIT/PSZT1
/ReversiGUI/table.h
UTF-8
1,386
2.796875
3
[]
no_license
#ifndef TABLE_H_ #define TABLE_H_ #define TABLE_SIZE 8 #include "position.h" #include "player.h" #include <vector> #define DEBUG #ifdef DEBUG #include <iostream> #endif //DEBUG class Position; class Player; class Table { public: Table(); ~Table(); enum pawn {white, black, proposal, none}; enum color {whitePlayer, blackPlayer}; void getStartConfig(Player::who player1, Player::who player2); bool isGameOver(); void nextPlayer(); void makeProposalFor(); bool makeMove(Position pawnPos); void makeAIMove(Position pawnPos); void updateScore(); void checkWinCondition(); int retScoreDiff(); bool canPlayerMove(); std::vector<Position> makeAllPossibleMoves(); #ifdef DEBUG void printTable(); #endif //DEBUG int getMaxDepth(); void incrementMaxDepth(); private: int maxDepth; Player player[2]; pawn table[TABLE_SIZE][TABLE_SIZE]; color whoWin; int canMove; color whoseMove; bool gameOver; void makeProposalForPawn(Position pawnPos, int directionX, int directionY); void makeMovePlayer(Position pawnPos); void changePawnColor(Position pawnPos); void changePawnInDirection(Position pawnPos, int directionX, int directionY); pawn opposite(); int getP1Score(); int getP2Score(); }; #endif //TABLE_H_
true
c40d6714d9b4a43d958ae0f56fb95d7053c1ee2d
C++
tolfaine/ProjetLabyrinthe
/Projet Laby/Labyrinthe2D.h
WINDOWS-1252
1,337
3.0625
3
[]
no_license
/** * @file Labyrinthe2D.h * Projet Labyrinthe * @author BURNER Whitney et DELERIN Maxime * @version 1 30/12/2013 * @brief Composant d'un labyrinthe deux dimensions. * Structures de donnes et algorithmes - DUT1 Paris 5 */ #ifndef LABYRINTHE2D_H_ #define LABYRINTHE2D_H_ #include <fstream> #include "Tableau2D.h" #include "IndexPosition2D.h" /** Type Labyrinthe2D * Stockage du tableau contenant les lments du labyrinthe * Repres de la position du minotaure et de l'entree du labyrinthe */ struct Labyrinthe2D{ Tableau2D tab2D; IndexPosition2D entree; IndexPosition2D minotaure; }; /** * brief Initialisation d'un Labyrinthe2D vide * Le Labyrinthe2D est alloue en mmoire dynamique * @see detruire, le Labyrinthe2D est dsallouer en fin dutilisation * @param[in,out] f : flux de sortie * @param[in,out] t : le Labyrinthe2D */ void initialiser(Labyrinthe2D& l, std::ifstream& f); /** * brief Desallocation d'un Labyrinthe2D * @see initialiser, le Labyrinthe2D a deja t allou en mmoire dynamique * @param[in,out] t : le Labyrinthe2D */ void detruire(Labyrinthe2D& l); /** * brief Affichage d'un Labyrinthe2D * @see initialiser, le Labyrinthe2D a deja t allou en mmoire dynamique * @param[in,out] t : le Labyrinthe2D */ void afficher (Labyrinthe2D& l); #endif /* LABYRINTHE2D_H_ */
true
71a524b4d52c9798b1b9b7b8a07e216e09dddcff
C++
nic-cs150-master/sp21-lecture
/14-sorting/sort.cpp
UTF-8
5,354
3.703125
4
[]
no_license
#include <iostream> #include <vector> using namespace std; void printArray(const int arr[], int size); void printVector(const vector<int> &vec); void bubbleSort(int arr[], int size); void bubbleSort(vector<int> &vec); void selectionSort(int arr[], int size); void insertionSort(int arr[], int size); int main() { // const int ARRAY_SIZE = 10; // int numbers[] = {23, 5, 35, 57, 212, 43, 657, 454, 89, 3}; // int numbers1[] = {23, 5, 35, 57, 212, 43, 657, 454, 89, 3}; // int numbers2[] = {23, 5, 35, 57, 212, 43, 657, 454, 89, 3}; vector<int> numVector{23, 5, 35, 57, 212, 43, 657, 454, 89, 3}; printVector(numVector); bubbleSort(numVector); printVector(numVector); numVector.push_back(34); bubbleSort(numVector); // printArray(numbers, ARRAY_SIZE); // bubbleSort(numbers, ARRAY_SIZE); // printArray(numbers, ARRAY_SIZE); // selectionSort(numbers1, ARRAY_SIZE); // printArray(numbers1, ARRAY_SIZE); // insertionSort(numbers2, ARRAY_SIZE); // printArray(numbers2, ARRAY_SIZE); return 0; } void insertionSort(int arr[], int size) { // For startScan = 1 to the last subscript in the array for (int startScan = 1; startScan < size; ++startScan) { // Set key to array[startScan] int key = arr[startScan]; // Set index = startScan - 1 int index = startScan - 1; // While index is greater than or equal first subscript and array[index] is greater than key while (index >= 0 && arr[index] > key) { // Set array[index + 1] to array[index] arr[index + 1] = arr[index]; // Decrement index --index; } // End While // Set array[index + 1] to key arr[index + 1] = key; // Increment startScan } // End For } void selectionSort(int arr[], int size) { // For startScan = 0 to the next-to-last array subscript for (int startScan = 0; startScan < size - 1; ++startScan) { // Set minIndex to startScan int minIndex = startScan; // Set minValue to array[startScan] int minValue = arr[startScan]; // For index = (startScan + 1) to the last subscript in the array for (int index = startScan + 1; index < size; ++index) { // If array[index] is less than minValue if (arr[index] < minValue) { // Set minValue to array[index] minValue = arr[index]; // Set minIndex to index minIndex = index; } // End If // Increment index } // End For // Set array[minIndex] to array[startScan] arr[minIndex] = arr[startScan]; // Set array[startScan] to minValue arr[startScan] = minValue; // Increment startScan } // End For } void bubbleSort(int arr[], int size) { // Set madeAswap to true bool madeAswap = true; // Set lastIndex to size of array - 1 int lastIndex = size - 1; // While the madeAswap flag is true while (madeAswap) { // Set madeAswap flag to false madeAswap = false; // For count = 0 to lastIndex for (int count = 0; count < lastIndex; ++count) { // If array[count] is greater than array[count + 1] if (arr[count] > arr[count + 1]) { // Swap the contents of array[count] and array[count + 1] int temp = arr[count]; arr[count] = arr[count + 1]; arr[count + 1] = temp; // int temp = arr[count + 1]; // arr[count + 1] = arr[count]; // arr[count] = temp; // Set madeAswap flag to true madeAswap = true; } // End If // Increment count } // End For // Subtract 1 from lastIndex --lastIndex; } // End While } void bubbleSort(vector<int> &vec) { // Set madeAswap to true bool madeAswap = true; // Set lastIndex to size of array - 1 int lastIndex = vec.size() - 1; // While the madeAswap flag is true while (madeAswap) { // Set madeAswap flag to false madeAswap = false; // For count = 0 to lastIndex for (int count = 0; count < lastIndex; ++count) { // If array[count] is greater than array[count + 1] if (vec[count] > vec[count + 1]) { // Swap the contents of array[count] and array[count + 1] int temp = vec[count]; vec[count] = vec[count + 1]; vec[count + 1] = temp; // int temp = arr[count + 1]; // arr[count + 1] = arr[count]; // arr[count] = temp; // Set madeAswap flag to true madeAswap = true; } // End If // Increment count } // End For // Subtract 1 from lastIndex --lastIndex; } // End While } void printArray(const int arr[], int size) { for (int i = 0; i < size; ++i) { cout << arr[i] << ' '; } cout << '\n'; } void printVector(const vector<int> &vec) { for (int i = 0; i < vec.size(); ++i) { cout << vec[i] << ' '; } cout << '\n'; }
true
157faa2beb5d13b802ec5302bf792d05bd47c9c6
C++
Lan-ce-lot/overflow
/Dp/5.cpp
UTF-8
1,272
2.78125
3
[]
no_license
# include<iostream> # include<queue> # define MAX 5842 using namespace std; __int64 humble_number[MAX+1]; struct cmp1{ bool operator()(__int64 &a,__int64 &b) { return a>b; } }; int main() { int i=1,n; humble_number[0]=0; priority_queue<__int64,vector<__int64>,cmp1> q; while(i<=MAX) { q.push(1); while(!q.empty()) { if(i>MAX) break; __int64 j=q.top(); q.pop(); if(j!=humble_number[i-1]) { humble_number[i++]=j; q.push(j*2); q.push(j*3); q.push(j*5); q.push(j*7); } } } while(cin>>n) { if(n==0) break; else { if(n%10==1&&n%100!=11) printf("The %dst humble number is %d.\n",n,humble_number[n]); else if(n%10==2&&n%100!=12) printf("The %dnd humble number is %d.\n",n,humble_number[n]); else if(n%10==3&&n%100!=13) printf("The %drd humble number is %d.\n",n,humble_number[n]); else printf("The %dth humble number is %d.\n",n,humble_number[n]); } } return 0; }
true