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
121b6e0bed9aff69326d6701f7300bd6484bbd5d
C++
Nightmare4214/connect_four
/Project1/TranspositionTable.cpp
GB18030
1,487
2.96875
3
[]
no_license
#include "TranspositionTable.hpp" void TranspositionTableNode::setValue(const uint64_t & key, const int & value, const int & depth, const int & flag, const int& bestMove) { this->key = key; this->value = value; this->depth = depth; this->flag = flag; this->bestMove = bestMove; } TranspositionTable::TranspositionTable() :table(tableSize) { } void TranspositionTable::reset() { memset(&table[0], 0, tableSize * sizeof(TranspositionTableNode)); } int TranspositionTable::probeHash(const uint64_t & key, const int & depth, const int & alpha, const int & beta, int& bestMove, bool& findedFlag) { findedFlag = false; //2Ϊ׵ȡԱ TranspositionTableNode& temp = table[key&tableSizeMask]; // if (temp.key == key) { findedFlag = true; //ֻѡȸ if (temp.depth >= depth) { if (TranspositionTableNode::EXACT_FLAG == temp.flag) { bestMove = temp.bestMove; return temp.value; } else if (TranspositionTableNode::ALPHA_FLAG == temp.flag&&temp.value <= alpha) { return alpha; } else if (TranspositionTableNode::BETA_FLAG == temp.flag&&temp.value >= beta) { return beta; } } } return unknown; } void TranspositionTable::recordHash(const uint64_t & key, const int & value, const int & depth, const int & flag, const int& bestMove) { TranspositionTableNode& temp = table[tableSizeMask&key]; if (0 != temp.key&&temp.depth > depth)return; temp.setValue(key, value, depth, flag, bestMove); }
true
c5164e1f0a0b87ca34b5d9b3e85bd698643b640c
C++
aaronsonderegger/Spring2020_StrainGauges
/Filter/TestFilter.cpp
UTF-8
2,924
3.015625
3
[]
no_license
#include <stdio.h> #include "Filter.cpp" void GenerateSignals(int numSignals, Filter fltr); // This generates signals for a filter. bool Test1(); // This test checks filter before UpdateFilter() function bool Test2(); // This test checks filter with 1 signal reading of UpdateFilter() bool Test3(); // This test checks filter with 20 signals bool Test4(); // This test checks RestartFilter() function bool Test5(); // This test checks GetFilteredSignal() bool Test6(); // This test checks UpdatedFilter() with 100 signals. bool Test7(); // This test checks filter for multiple filters before UpdateFilter() function bool Test8(); // This test checks filter for multiple filters with 1 signal reading of UpdateFilter() bool Test9(); // This test checks filter for multiple filters with 20 signals bool Test10(); // This test checks filter for multiple filters RestartFilter() function bool Test11(); // This test checks filter for multiple filters GetFilterSignal() bool Test12(); // This test checks filter for multiple filters UpdateFitler with 100 signals bool Test13(); // This test checks filter for multiple filters with reseting 1 filter and not others // bool Test14(); // This test checks int main() { int passedTests = 0; int totalTests = 13; passedTests += Test1(); passedTests += Test2(); passedTests += Test3(); passedTests += Test4(); passedTests += Test5(); passedTests += Test6(); passedTests += Test7(); passedTests += Test8(); passedTests += Test9(); passedTests += Test10(); passedTests += Test11(); passedTests += Test12(); passedTests += Test13(); passedTests += Test14(); std::cout << passedTests << " / " totalTests << "Passed\n"; return 0; } // This generates signals for a filter. void GenerateSignals(int numSignals, Filter fltr) { } // This test checks filter before UpdateFilter() function bool Test1() { } // This test checks filter with 1 signal reading of UpdateFilter() bool Test2() { } // This test checks filter with 20 signals bool Test3() { } // This test checks RestartFilter() function bool Test4() { } // This test checks GetFilteredSignal() bool Test5() { } // This test checks UpdatedFilter() with 100 signals. bool Test6() { } // This test checks filter for multiple filters before UpdateFilter() function bool Test7() { } // This test checks filter for multiple filters with 1 signal reading of UpdateFilter() bool Test8() { } // This test checks filter for multiple filters with 20 signals bool Test9() { } // This test checks filter for multiple filters RestartFilter() function bool Test10() { } // This test checks filter for multiple filters GetFilterSignal() bool Test11() { } // This test checks filter for multiple filters UpdateFitler with 100 signals bool Test12() { } // This test checks filter for multiple filters with reseting 1 filter and not others bool Test13() { }
true
1b4db219675fd3c100fbd0b8401a95d6157105a6
C++
gdarchen/webusb-arduino-nfc
/3-webusb/arduino/libraries/NDEF-master/NdefMessage.h
UTF-8
1,110
2.515625
3
[ "MIT", "BSD-3-Clause", "BSD-2-Clause" ]
permissive
#ifndef NdefMessage_h #define NdefMessage_h #include <Ndef.h> #include <NdefRecord.h> #define MAX_NDEF_RECORDS 4 class NdefMessage { public: NdefMessage(void); NdefMessage(const byte *data, const int numBytes); NdefMessage(const NdefMessage& rhs); ~NdefMessage(); NdefMessage& operator=(const NdefMessage& rhs); int getEncodedSize(); // need so we can pass array to encode void encode(byte *data); boolean addRecord(NdefRecord& record); void addMimeMediaRecord(String mimeType, String payload); void addMimeMediaRecord(String mimeType, byte *payload, int payloadLength); void addTextRecord(String text); void addTextRecord(String text, String encoding); void addUriRecord(String uri); void addEmptyRecord(); unsigned int getRecordCount(); NdefRecord getRecord(int index); NdefRecord operator[](int index); #ifdef NDEF_USE_SERIAL void print(); #endif private: NdefRecord _records[MAX_NDEF_RECORDS]; unsigned int _recordCount; }; #endif
true
5c748d71cf6ec13c08b30e4868336e630f965220
C++
takoikatakotako/atcoder
/aoj_ALDS1_1_D.cpp
UTF-8
534
2.9375
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; int aoj_ALDS1_1_D() { int N; cin >> N; vector<int> R(N); for (int i = 0; i < N; ++i) { cin >> R[i]; } int maxBenefit = R[1] - R[0]; int minNum = R[0]; for (int i = 1; i < N; ++i) { if (R[i-1] < minNum) { minNum = R[i-1]; } int benefit = R[i] - minNum; if (benefit > maxBenefit) { maxBenefit = benefit; } } cout << maxBenefit << endl; }
true
fbdaa7a54c350c42d9989b17af5b19a5d2bb7166
C++
yuujun09/yuuku
/草稿编程/源.cpp
UTF-8
337
2.609375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> int main() { int arr[20]; int i = 0; int sum = 0; for (i = 0;;) { scanf("%d", &arr[i]); if (arr[i] <= 0) break; if (arr[i] % 2 == 1) sum += arr[i]; i++; }printf("%d", sum); return 0; }
true
ee64b4865dadcee2c8389617ba583e1ad82d6058
C++
arubiom/ED
/reto2/piecelist.h
UTF-8
2,905
3.59375
4
[]
no_license
/** * @file Piecelist.h * @author Alejandro Rubio, Ximo Sanz * @brief The file which contains the TDA object Piecelist, a vector of pieces */ #ifndef PIECELIST_H #define PIECELIST_H #include "piece.h" #define MAX_PIECES = 4 /** * @brief The Piecelist class * */ class Piecelist { private: Piece* currentPieces; int nPieces; //Must be always between 0 and MAX_PIECES /** * @brief Allocates memory for the matrix * * @param n Rows to allocate * @pre @p n is greater than 0 */ void allocate(int n); /** * @brief Desallocate the vector memory in usage * */ void deallocate(); /** * @brief Copy an object in another one * * @param pl The object we want to copy */ void copy(const Piecelist &pl); /** * @brief Fill the list with pieces * * @param n The number of pieces we want to fill * @pre nPieces + @p n must be less or equal to MAX_PIECES */ void fill(int n); public: /** * @brief Construct a new Piecelist object * * @param n The number of pieces in the list, by default MAX_PIECES */ Piecelist(int n = MAX_PIECES); /** * @brief Copy constructor of the class * * @param pl The object we want to copy */ Piecelist(const Piecelist &pl); /** * @brief Destroy the Piecelist object * */ ~Piecelist(); /** * @brief Get the Size of the object * * @return int nPieces */ int getSize() const; /** * @brief Extract one piece from the list * * @return Piece The extracted piece * @post After a piece has been extraxted is called fill(1); */ Piece extract(); /** * @brief Remove a piece from the beggining * */ void pop(); /** * @brief Add a piece to the end of the list * * @param p The piece we want to introduce * @pre nPieces must be < MAX_PIECES */ void push(const Piece &p); /** * @brief Overload the += operator * * @param p The piece we want to add * @return Piecelist& The piecelist with the piece added */ Piecelist& operator+=(const Piece &p); /** * @brief Overload the [] operator for vectors of pieces * * @param i The position we want to return * @return Piece The piece */ Piece &operator[](int i); }; /** * @brief Overload the >> operator * * @param stream The stream of datas * @param pl The stats where we will introduce the data * @return std::istream& The stream */ std::istream& operator>>(std::istream& stream, Piecelist &pl); /** * @brief Overload the << operator * * @param stream The stream of datas * @param pl The stats from which we will show the datas * @return std::ostream& The stream */ std::ostream& operator<<(std::ostream& stream, const Piecelist &pl);
true
420f45c0aa1dac0dfcd1f7116946fdf81e18eb9b
C++
HusseinYoussef/Problem-Solving
/Code/Shortest path of the king.cpp
UTF-8
2,634
3.078125
3
[]
no_license
#include <iostream> #include <string> #include <cmath> using namespace std; int main () { int i=0,steps,lower; string home,end; char current; cin >> home >> end; if(abs(home[0]-end[0]) > abs(home[1]-end[1])) { steps = abs(home[0]-end[0]); lower = abs(home[1]-end[1]); } else { steps = abs(home[1]-end[1]); lower = abs(home[0]-end[0]); } cout << steps << endl; if(end[0] > home[0]) // Right Area { if(end[1] > home[1]) {current = home[1] + lower; for(i=0;i<steps;i++) { if(i<lower) // Right Up { cout << "RU" << endl; continue;} else if(current == end[1]) { cout << "R" << endl; } else cout << "U" << endl; } } else if(end[1] < home[1]) // Right Down {current = abs(home[1] - lower); for(i=0;i<steps;i++) { if(i<lower) {cout << "RD" << endl; continue;} else if(current == end[1]) cout << "R" << endl; else cout << "D" << endl; } } else // Only Right { for(i=0;i<steps;i++) cout << "R" << endl; } } else if(end[0] < home[0]) // Left Area { if(end[1] > home[1]) // Left Up {current = home[1] + lower; for(i=0;i<steps;i++) { if(i<lower) { cout << "LU" << endl; continue;} else if(current == end[1]) cout << "L" << endl; else cout << "U" << endl; } } else if(end[1] < home[1]) // Left Down {current = abs(home[1] - lower); for(i=0;i<steps;i++) { if(i<lower) { cout << "LD" << endl; continue;} else if(current == end[1]) cout << "L" << endl; else cout << "D" << endl; } } else // Only Left { for(i=0;i<steps;i++) cout << "L" << endl; } } else // Only Column { if(end[1] > home [1]) // Up for(i=0;i<steps;i++) cout << "U" << endl; else // Down for(i=0;i<steps;i++) cout << "D" << endl; } return 0; }
true
606974ee7a4932dcfa3ab3b81ba4af205bc4272c
C++
bes-germes/Vector
/vector.cpp
UTF-8
1,697
3.296875
3
[]
no_license
#include "vector.h" MyVector::MyVector(size_t size, ResizeStrategy,float coef){ this->_size = size; this->_capacity = 1; this->_data = nullptr; this->_coef = coef; } MyVector::~MyVector(){ } MyVector::MyVector(size_t size, ValueType value, ResizeStrategy, float coef){ this->_size = size; this->_capacity = 1; this->_data = &value; this->_coef = coef; } MyVector::MyVector(const MyVector& copy){ this->_size = copy._size; if (this->_size == 0) { this->_data = nullptr; return; } this->_data = copy._data; } size_t MyVector::capacity() const{ return this->_capacity; } size_t MyVector::size() const{ return this->_size; } void MyVector::pushBack(const ValueType& value){ if(this->_size == this->_capacity){ reserve(this->_capacity * _coef); } ValueType* newData = new ValueType[this->_size + 1]; memcpy(newData, this->_data, this->_size * sizeof(ValueType)); this->_data = newData; delete[] newData; } void MyVector::insert(const size_t i, const ValueType& value){ } void MyVector::reserve(const size_t capacity){ if (capacity > this->_capacity) { this->_capacity = (this->_capacity == 0) ? 1 : this->_capacity; while (this->_capacity < capacity) this->_capacity ++; if (this->_data == 0) this->_data = new ValueType[this->_capacity]; else { ValueType* newData = new ValueType[this->_capacity]; memcpy(newData, this->_data, this->_size * sizeof(ValueType)); this->_data = newData; delete[] newData; } } }
true
1b7d9ba57c1c379a82f7c5348f68095b322bc3db
C++
flutter/engine
/third_party/accessibility/base/simple_token.h
UTF-8
1,509
2.75
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_SIMPLE_TOKEN_H_ #define BASE_SIMPLE_TOKEN_H_ #include <functional> #include <optional> #include <string> namespace base { // A simple string wrapping token. class SimpleToken { public: // Create a random SimpleToken. static SimpleToken Create(); // Creates an empty SimpleToken. // Assign to it with Create() before using it. SimpleToken() = default; ~SimpleToken() = default; // Creates an token that wrapps the input string. SimpleToken(const std::string& token); // Hex representation of the unguessable token. std::string ToString() const { return token_; } explicit constexpr operator bool() const { return !token_.empty(); } constexpr bool operator<(const SimpleToken& other) const { return token_.compare(other.token_) < 0; } constexpr bool operator==(const SimpleToken& other) const { return token_.compare(other.token_) == 0; } constexpr bool operator!=(const SimpleToken& other) const { return !(*this == other); } private: std::string token_; }; std::ostream& operator<<(std::ostream& out, const SimpleToken& token); std::optional<base::SimpleToken> ValueToSimpleToken(std::string str); std::string SimpleTokenToValue(const SimpleToken& token); size_t SimpleTokenHash(const SimpleToken& SimpleToken); } // namespace base #endif // BASE_SIMPLE_TOKEN_H_
true
922fc114df38a0c3899890c914b68804754881de
C++
datnguyen25082000/SimplePongGame
/Source/Project2/Paddle.cpp
UTF-8
1,133
2.984375
3
[]
no_license
#include "Paddle.h" // get x(y) value of object int Paddle::GetX() { return _x; } int Paddle::GetY() { return _y; } // get and set color of Paddle object int Paddle::Getcolor() { return _color; } void Paddle::Setcolor(int color) { _color = color; } int Paddle::Getsize() { return _size; } // reset paddle with old data void Paddle::Reset() { _x = _originalx; _y = _originaly; } // Paddle move left void Paddle::moveLeft() { char bot = 223; textcolor(_color); gotoXY(_x + this->Getsize() - 1, _y); cout << ' '; _x--; gotoXY(_x, _y); cout << bot; textcolor(7); Sleep(5); } // Paddle move right void Paddle::moveRight() { char bot = 223; textcolor(_color); gotoXY(_x, _y); cout << ' '; _x++; gotoXY(_x + this->Getsize() - 1, _y); cout << bot; textcolor(7); Sleep(5); } Paddle::Paddle() { } // constructor to create new object with parameter Paddle::Paddle(int size, int originalx, int originaly) { _originalx = originalx; _originaly = originaly; _x = _originalx; _y = _originaly; _size = size; } Paddle::~Paddle() { }
true
a187eba8217a502b517a744371b5d1c662b52391
C++
tonningp/cis201-class-examples
/bcpp3-sourcecode/ch07/sec03/strings.cpp
UTF-8
1,993
4.5
4
[]
no_license
#include <iostream> #include <string> #include <cstdlib> #include <cctype> using namespace std; /** Makes an uppercase version of a string. @param str a string @return a string with the characters in str converted to uppercase */ string uppercase(string str) { string result = str; // Make a copy of str for (int i = 0; i < result.length(); i++) { result[i] = toupper(result[i]); // Convert each character to uppercase } return result; } int main() { /* To print character values in decimal, you must convert them to int. */ cout << "Some common char values:" << endl; cout << "The letter H: " << static_cast<int>('H') << endl; cout << "The digit 0: " << static_cast<int>('0') << endl; cout << "The space character: " << static_cast<int>(' ') << endl; cout << "The newline character: " << static_cast<int>('\n') << endl; cout << endl; const char* char_pointer = "Harry"; cout << "char_pointer points to: " << *char_pointer << endl; cout << "Or in decimal: " << static_cast<int>(*char_pointer) << endl; cout << "Here is the zero terminator: " << static_cast<int>(*(char_pointer + 5)) << endl; char char_array[] = "Harry"; cout << "Here is the zero terminator: " << static_cast<int>(char_array[5]) << endl; char_array[0] = 'L'; cout << "Now char_array holds " << char_array << endl; cout << endl; string year = "2012"; // A C++ string char_pointer = year.c_str(); // Converted to char* int y = atoi(char_pointer); // atoi requires a C style string cout << "string " << year << " converted to an int: " << y << endl; string name = "Harry"; string sub3 = name.substr(3, 1); char ch3 = name[3]; cout << "Substring of length 1 at index 3: " << sub3 << endl; cout << "Substring of length 1 at index 3: " << ch3 << endl; name[3] = 'd'; cout << "After changing name[3]: " << name << endl; cout << "Uppercase: " << uppercase(name) << endl; return 0; }
true
5bce5d15e65eed007f79d797a0cd4274a9baff2e
C++
eunjin917/algorithm
/Baekjoon/10951.cpp
UTF-8
237
2.84375
3
[]
no_license
// A+B - 4 // https://www.acmicpc.net/problem/10951 // 2021.03.07 #include <iostream> using namespace std; int main() { int A, B; while (scanf("%d %d", &A, &B) != EOF) { cout << A + B << '\n'; } return 0; }
true
0fff6eb1496deb66e70bbc5148049437eadd6d2a
C++
yilehu/CG_C
/MatrixOperation.cpp
UTF-8
1,483
3.046875
3
[]
no_license
void MatrixDefinition(double **Matrix,int m,int Bandwidth) { int i,j,k; for(i=0;i<m;i++) { Matrix[i][i] = (double)Bandwidth; if(i <= m-Bandwidth) { k = Bandwidth; } else { k = m - i; } for(j=1;j<k;j++) { Matrix[i][i+j] = Bandwidth - j; Matrix[i+j][i] = Bandwidth - j; } } } void MatrixDefinition_Banded(double **Matrix,int m,int Bandwidth) { int i,j,k,tid; for(i=0;i<m;i++) { for(j=0;j<Bandwidth;j++) { if(i>Bandwidth-j-2) { Matrix[i][j] = j+1; } if(i<m-(Bandwidth-1-j)) { Matrix[i][2*Bandwidth-2 - j] = j+1; } } } } void MatrixMultiply(double **A,double *x,double *b,int m,int n) { int i,j; for(i=0;i<m;i++) { b[i] = 0.0; for(j=0;j<n;j++) { b[i] += A[i][j]*x[j]; } } } void MatrixMultiply_Banded(double **A,double *x,double *b,int m,int n,int Bandwidth) { int i,j; for(i=0;i<Bandwidth-1;i++) { b[i] = 0.0; for(j=Bandwidth-1-i;j<n;j++) { b[i] += A[i][j]*x[i-(Bandwidth-1)+j]; } } for(i=Bandwidth-1;i<m-Bandwidth+1;i++) { b[i] = 0.0; for(j=0;j<n;j++) { b[i] += A[i][j]*x[i-(Bandwidth-1)+j]; } } for(i=m-Bandwidth+1;i<m;i++) { b[i] = 0.0; for(j=0;j<Bandwidth-1+m-i;j++) { b[i] += A[i][j]*x[i-(Bandwidth-1)+j]; } } } double Dotproduct(double *a,double *b,int n) { double temp = 0.0; for(int i=0;i<n;i++) { temp += a[i]*b[i]; } return temp; }
true
0109cf2bcbec3096653d8ab617853ef9633bc47d
C++
DragaSahiti/lab5
/sahiti4.cpp
UTF-8
324
3.484375
3
[]
no_license
/* program to print all even numbers between 1 and 100 */ //library # include <iostream> using namespace std; //main function int main() { //declarations int i = 1; //loops while( i <= 100 ) { //condition if(i % 2 == 0){ cout << i << endl; } i++; } return 0; }
true
99553668f4ee2a437a71f257893300a12ecc4d02
C++
Xopher00/binary-search
/binary_search.cpp
UTF-8
3,402
4.21875
4
[]
no_license
// This program demonstrates a Binary Search //Kris Price #include<iostream> using namespace std; int binarySearch(int [], int, int); // function prototype const int SIZE = 16; int main() { int found, value; int array[SIZE] ={0,2,2,3,5,9,11,12,12,12,13,17,18,19,19,34}; cout << "Enter an integer to search for:" << endl; cin >> value; found = binarySearch(array, SIZE, value); //function call to perform the binary search //on array looking for an occurrence of value if (found == -1) cout << "The value " << value << " is not in the list" << endl; else { cout << "The value " << value << " is in position number " << found + 1 << " of the list" << endl; } return 0; } //******************************************************************* // binarySearch // // task: This searches an array for a particular value // data in: List of values in an orderd array, the number of // elements in the array, and the value searched for // in the array // data returned: Position in the array of the value or -1 if value // not found // //******************************************************************* int binarySearch(int array[],int numElems,int value) //function heading { int first = 0; // First element of list int last = numElems - 1; // last element of the list int middle; // variable containing the current // middle value of the list int position = -1 ; //position of search value bool found = false ; //flag while (!found && first <= last){ middle = (first + last) / 2; //calculate mid point if (array[middle] == value) //if value is found at mid { found = true; position = middle; } else if (array[middle] > value) // if value is in lower half last = middle - 1; else first = middle + 1; //if value is in upper hal } return position; }/* while (first <= last) { //middle = first + (last - first) / 2 //search array in descending order if (array[middle] == value) return middle; // if value is in the middle, we are done else if (array[middle]<value) last = middle - 1; // toss out the second remaining half of // the array and search the first else first = middle + 1; // toss out the first remaining half of // the array and search the second } return -1; // indicates that value is not in the array } /* Exercise 1 The right side of the statement middle=first+(last-first)/2 is not an integer, but is defined by the values' positions within the computer memory; ie. 13eeFF28 + (14eeFF32 - 17eeFF36) / 2. This affects the computer's logic in that it doesn't use a specific value when calculating the middle variable, but instead takes in values from predetermined positions Exercise 2 Input 19 This is the first occurrence of 19 in the array position = 2 Input 12 Position = 8 This is the second occurrence of 12 in the array The difference is due to how the binary search splits the array in half continuously while searching for the value. For 19, the sequence of splits led to the second 19 value being found, and for 12 this sequence led to the eighth value being found Exercise 3 Input 34 position = 16 Input 12 position = 8 Input 19 position = 14 */
true
292f9c111c6a4cd2ed1866a07c7a38703944c492
C++
webstorage119/easyeye
/easyeye/src/easyeye/common/mylog.cc
UTF-8
2,682
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-public-domain" ]
permissive
#include <iostream> #include <cstdarg> #include <cstdlib> #include "mylog.h" #include <string> using namespace std; using namespace mylog; const string Logs::kGlobalName = ""; Logger Logs::global_logger(Logs::kGlobalName); LoggerSet Logs::logger_set; LoggerSet::LoggerSet() : loggers() {} Logger* LoggerSet::Get(const string& name) { for (size_t i = 0; i < loggers.size(); i++) { if (name.compare(loggers[i]->name()) == 0) { return loggers[i]; } } Logger* logger = new Logger(name); loggers.push_back(logger); return logger; } LoggerSet::~LoggerSet() { for (size_t i = 0; i < loggers.size(); i++) { Logger* logger = loggers[i]; delete logger; } } Logger& Logs::GetLogger() { return global_logger; } Logger& Logs::GetLogger(const string& name) { if (kGlobalName.compare(name) == 0) { return global_logger; } Logger* loggerp = logger_set.Get(name); return *loggerp; } /** * Parses a log level integer from string. Returns DEFAULT_LOG_LEVEL on * any error, otherwise the LOG_* constant is returned. */ bool Logs::ParseLevel(const string& level_name, Level* level) { if (level_name.compare("ALL") == 0) { *level = ALL; } else if (level_name.compare("TRACE") == 0) { *level = TRACE; } else if (level_name.compare("DEBUG") == 0) { *level = DEBUG; } else if (level_name.compare("INFO") == 0) { *level = INFO; } else if (level_name.compare("WARN") == 0) { *level = WARN; } else if (level_name.compare("ERROR") == 0) { *level = ERROR; } else if (level_name.compare("FATAL") == 0) { *level = FATAL; } else { return false; } return true; } Logger::Logger(const string& name) : name_(name), level_(Logs::DEFAULT_LOG_LEVEL), output_(stderr) { } const string& Logger::name() { return name_; } void Logger::Log(Level level, const char* fmt, ...) { if (IsLevelEnabled(level)) { va_list argptr; va_start(argptr, fmt); vfprintf(output_, fmt, argptr); va_end(argptr); } } Level Logger::set_level(Level level) { Level old = level_; level_ = level; return old; } Level Logger::level() { return level_; } bool Logger::IsLevelEnabled(Level level) { return level_ >= level; } void Logger::set_output(FILE* ofile) { output_ = ofile; } const char* GetName(Level level) { switch (level) { case ALL: return "ALL"; case TRACE: return "TRACE"; case DEBUG: return "DEBUG"; case INFO: return "INFO"; case WARN: return "WARN"; case ERROR: return "ERROR"; case FATAL: return "FATAL"; default: return "UNRECOGNIZED"; } assert(false); }
true
1fc28698087ac00a927ee2dece45955f6a720b1f
C++
vikaskbm/pepcoding
/foundation/cpp/1_basics_of_programming/3_function_and_arrays/1.cpp
UTF-8
521
3.6875
4
[ "MIT" ]
permissive
// Digit Frequency // 1. You are given a number n. // 2. You are given a digit d. // 3. You are required to calculate the frequency of digit d in number n. // n=994543234 // d=4 // 3 #include <iostream> using namespace std; void digit_frequency(int num, int k) { int count = 0; int n = num; while(n > 0) { int temp = n % 10; if (temp == k) count++; n = n / 10; } cout << count << endl; } int main() { int num, k; cin >> num >> k; digit_frequency(num, k); }
true
50f667358bb3e89a4a4bbeee68e666e9e4254ff4
C++
rajatgirotra/study
/cpp/ThreeArrowsCapital/reverseString.cpp
UTF-8
4,614
3.578125
4
[]
no_license
#include <iostream> #include <algorithm> #include <fstream> #include <boost/program_options.hpp> #include <thread> #include <memory> using namespace std; namespace po = boost::program_options; namespace { //Reverse a string in place. //Will only reverse charCount characters //Is re-entrant void reverse_func(string::iterator start, string::iterator end, size_t charCount) { while(charCount > 0) { string::iterator::value_type tmp(*start); *start++ = *(--end); *end = tmp; charCount -= 2; } } void process(string& inputText, const size_t& parallel_threads) { cout << "Input text size: " << inputText.size() << endl; //Calculate how many chars each thread will need to reverse. //All threads will be given (almost) equal load. size_t q = inputText.size() / parallel_threads; size_t r = inputText.size() % parallel_threads; if(q%2 != 0) { --q; r+=parallel_threads; } size_t charsPerThread[parallel_threads]; std::fill(charsPerThread, charsPerThread + parallel_threads, q); int index = 0; while(r > 1) { charsPerThread[index++] += 2; r -= 2; } //Create threads now. Each thread will reverse a portion/block of the string. std::thread* threadArr[parallel_threads]; string::iterator start = inputText.begin(); string::iterator end = inputText.end(); for(size_t i = 0; i < parallel_threads; ++i) { threadArr[i] = new std::thread(&reverse_func, start, end, charsPerThread[i]); cout << "Thread " << threadArr[i]->get_id() << " reversing " << charsPerThread[i] << " characters\n"; start += charsPerThread[i]/2; end -= charsPerThread[i]/2; } for(size_t i = 0; i < parallel_threads; ++i) { threadArr[i]->join(); } for(size_t i = 0; i < parallel_threads; ++i) { delete threadArr[i]; } } //Uses boost program_options. class Options { private: po::variables_map m_vm; po::options_description m_desc; public: Options() : m_desc("Allowed Options") { m_desc.add_options() // option to print the help message ("help,h", "Print this help message") // option to get the string from file ("file,f", po::value<string>()->default_value("inputFile.txt"), "filename containing text to be reversed") // option to get the number of threads to use to reverse the string. Default is 1 thread. ("parallelDegree,p", po::value<size_t>()->default_value(1), "Maximum number of blocks into which the text may be divided for reversing"); } //Process in the command line parameters argc and argv void process(int argc, char* argv[]) { po::store(po::parse_command_line(argc, argv, m_desc), m_vm); po::notify(m_vm); if(m_vm.count("help")) { usage(); exit(-1); } } //Function to get an option, converted to the correct type. template <typename T> T get(const char* optionName) { T value = m_vm[optionName].template as<T>(); return value; } void usage() { cout << m_desc << endl; } } _options; } int main(int argc, char* argv[]) { //Process options first _options.process(argc,argv); //Read the input text into a string std::stringstream buffer; //buffer to hold the input sequence of characters ifstream iFile(_options.get<string>("file").c_str()); if(!iFile) { cerr << "Unable to open file: " << _options.get<string>("file") << " for reading" << endl; return -1; } buffer << iFile.rdbuf(); string inputText = buffer.str(); inputText.pop_back();//remove the end of line character from the buffer. buffer.str(""); //clear buffer now. //How many threads do we need to run parallely?? size_t parallel_threads = _options.get<size_t>("parallelDegree"); //Reverse a string using multiple threads for better performance. process(inputText, parallel_threads); ofstream outFile("outFile.txt"); outFile << inputText; outFile.close(); iFile.close(); return 0; }
true
bc35fd3217ffac9fed4a8c2171a1b97c11068b1f
C++
ikrima/cxl
/include/cxl/iterator.hpp
UTF-8
1,778
3.40625
3
[ "MIT" ]
permissive
#pragma once #include "utility.hpp" #include <type_traits> namespace cxl { template <typename T, index_t Index> struct iterator { using container_type = T; constexpr auto index() const { return ::std::integral_constant<index_t, Index>{}; } constexpr auto operator*() const { return T{}[::std::integral_constant<size_t, Index>{}]; } constexpr auto operator++() const { static_assert(decltype(*this){} != T{}.end(), "iterator: index out of bounds"); return iterator<T, Index + 1>{}; } constexpr auto operator--() const { static_assert(decltype(*this){} != T{}.begin(), "iterator: index out of bounds"); return iterator<T, Index - 1>{}; } template <index_t D> constexpr bool operator==(iterator<T, D>) const { return D == Index; } template <typename U> constexpr bool operator!=(U) const { return !(decltype(*this){} == U{}); } }; template <typename T, index_t From, typename U, U Off> constexpr auto operator+(iterator<T, From>, ::std::integral_constant<U, Off>) { // static_assert((From + Off) < T{}.end().index(), "iterator: index out of bounds"); if constexpr ((From + Off) < T{}.end().index()) return iterator<T, From + Off>{}; else return T{}.end(); } template <typename T, index_t From, typename U, U Off> constexpr auto operator-(iterator<T, From>, ::std::integral_constant<U, Off>) { static_assert((From - Off) >= T{}.begin().index(), "iterator: index out of bounds"); return iterator<T, From - Off>{}; } template <typename T, index_t BeginIndex, index_t EndIndex> constexpr auto distance(iterator<T, BeginIndex>, iterator<T, EndIndex>) { constexpr index_t raw = BeginIndex - EndIndex; return ::std::integral_constant < index_t, (raw < 0) ? (raw * -1) : raw > {}; } } // namespace cxl
true
312dc33887bc85d40076a8660eb7c20ceea44dfa
C++
rystills/RaiderEngine
/RaiderEngine/audio.hpp
UTF-8
696
2.625
3
[ "MIT" ]
permissive
#pragma once #include "stdafx.h" /* initialize audio via OpenAL-Soft */ void initAudio(); void closeAudio(); /* custom deleter for smart pointers containing openal-soft audio buffers; deletes the buffer's contents before deleting the buffer itself @param b: the audio buffer to delete */ void deleteAudioBuffer(ALuint* b); /* load the sound file with the specified name @param soundName: the name of the sound file to load (including the extension; must be .ogg for now) @returns: the shared pointer in the sounds map to the sound */ ALuint loadSound(std::string soundName); /*play the specified sound @param soundName: the name of the sound to play */ void playSound(std::string soundName);
true
3dcfd57e52a7270d2ba7faaad42a75cb658bf761
C++
barisayyildiz/cpp-notes
/conversion_constructor.cpp
UTF-8
1,196
4.0625
4
[]
no_license
#include <iostream> using namespace std; class A { private: int x, y; public: A(); // conversion constructor?? A(int a); A(int a, int b); // copy constructor A(const A& right); // assignment operator A& operator=(const A& right); // destructor ~A(); // print void print()const; }; A::A() : x(0), y(0) { cout << "default constructor" << endl; } A::A(int a) : x(a), y(0) { cout << "tek parametre(conversion constructor)" << endl; } A::A(int a, int b) : x(a), y(b) { cout << "çift parametre(constructor)" << endl; } // copy constructor A::A(const A& right) { cout << "copy constructor" << endl; x = right.x; y = right.y; } // assignment operator A& A::operator=(const A& right) { cout << "assignment operator" << endl; x = right.x; y = right.y; return *this; } A::~A() { cout << "destructor" << endl; } void A::print()const { cout << "(" << x << "," << y << ")" << endl; } int main() { A a; a = 5; a.print(); a = 7; a.print(); // Output: // tek parametre(conversion constructor) // assignment operator // destructor // (5,0) // tek parametre(conversion constructor) // assignment operator // destructor // (7,0) // destructor return 0; }
true
7ab19c2e3dde8a00e6df1da30a6aebd427885c14
C++
joos5295/OOAD_SemesterProject
/inc/Game/Terrain/Goal.h
UTF-8
616
2.671875
3
[]
no_license
// // Created by user on 2019-04-23. // /* * The goal state of each level * When the player enters this cell they will move to the start of the next level */ #ifndef OOAD_SEMESTERPROJECT_GOAL_H #define OOAD_SEMESTERPROJECT_GOAL_H #include "Terrain.h" class Goal : public Terrain { Goal() = default; Goal(Goal const&) = delete; void operator=(Goal const&) = delete; public: static Terrain* getInstance(); char getChar() const override; Color getColor() const override; bool canEnter() const override; void enter(Player*) override; }; #endif //OOAD_SEMESTERPROJECT_GOAL_H
true
5dfce89d894cea291506977fa2724991ff555048
C++
elf-audio/cppsketch
/examples/audioweb/Biquad.h
UTF-8
4,202
2.59375
3
[ "BSD-3-Clause" ]
permissive
// // Was called - CFxRbjFilter.h // Someone's implementation of Robert Bristow-Johnson's biquad eqns. // // Created by Marek Bereza on 02/10/2012. // (found it on musicdsp.org) // Modified 04/04/19 by Marek Bereza #pragma once #include <cmath> class Biquad { public: constexpr static int LOWPASS = 0; constexpr static int HIGHPASS = 1; constexpr static int BANDPASS_CSG = 2; constexpr static int BANDPASS_CZPG = 3; constexpr static int NOTCH = 4; constexpr static int ALLPASS = 5; constexpr static int PEAKING = 6; constexpr static int LOWSHELF = 7; constexpr static int HIGHSHELF = 8; float filter(float in0) { // filter float const yn = b0a0*in0 + b1a0*in1 + b2a0*in2 - a1a0*ou1 - a2a0*ou2; // push in/out buffers in2=in1; in1=in0; ou2=ou1; ou1=yn; // return output return yn; }; void calc(int const type,double const frequency,double const sample_rate,double const q,double const db_gain,bool q_is_bandwidth) { // temp pi double const temp_pi=3.1415926535897932384626433832795; // temp coef vars double alpha,a0,a1,a2,b0,b1,b2; // peaking, lowshelf and hishelf if(type>=6) { double const A = pow(10.0,(db_gain/40.0)); double const omega = 2.0*temp_pi*frequency/sample_rate; double const tsin = sin(omega); double const tcos = cos(omega); if(q_is_bandwidth) alpha=tsin*sinh(std::log(2.0)/2.0*q*omega/tsin); else alpha=tsin/(2.0*q); double const beta = sqrt(A)/q; // peaking if(type==PEAKING) { b0=float(1.0+alpha*A); b1=float(-2.0*tcos); b2=float(1.0-alpha*A); a0=float(1.0+alpha/A); a1=float(-2.0*tcos); a2=float(1.0-alpha/A); } // lowshelf else if(type==LOWSHELF) { b0=float(A*((A+1.0)-(A-1.0)*tcos+beta*tsin)); b1=float(2.0*A*((A-1.0)-(A+1.0)*tcos)); b2=float(A*((A+1.0)-(A-1.0)*tcos-beta*tsin)); a0=float((A+1.0)+(A-1.0)*tcos+beta*tsin); a1=float(-2.0*((A-1.0)+(A+1.0)*tcos)); a2=float((A+1.0)+(A-1.0)*tcos-beta*tsin); } // hishelf else if(type==HIGHSHELF) { b0=float(A*((A+1.0)+(A-1.0)*tcos+beta*tsin)); b1=float(-2.0*A*((A-1.0)+(A+1.0)*tcos)); b2=float(A*((A+1.0)+(A-1.0)*tcos-beta*tsin)); a0=float((A+1.0)-(A-1.0)*tcos+beta*tsin); a1=float(2.0*((A-1.0)-(A+1.0)*tcos)); a2=float((A+1.0)-(A-1.0)*tcos-beta*tsin); } else { // stop compiler warning a0 = 0; b1 = 0; b2 = 0; a1 = 0; a2 = 0; } } else { // other filters double const omega = 2.0*temp_pi*frequency/sample_rate; double const tsin = sin(omega); double const tcos = cos(omega); if(q_is_bandwidth) alpha=tsin*sinh(std::log(2.0)/2.0*q*omega/tsin); else alpha=tsin/(2.0*q); // lowpass if(type==LOWPASS) { b0=(1.0-tcos)/2.0; b1=1.0-tcos; b2=(1.0-tcos)/2.0; a0=1.0+alpha; a1=-2.0*tcos; a2=1.0-alpha; } // hipass else if(type==HIGHPASS) { b0=(1.0+tcos)/2.0; b1=-(1.0+tcos); b2=(1.0+tcos)/2.0; a0=1.0+ alpha; a1=-2.0*tcos; a2=1.0-alpha; } // bandpass csg else if(type==BANDPASS_CSG) { b0=tsin/2.0; b1=0.0; b2=-tsin/2; a0=1.0+alpha; a1=-2.0*tcos; a2=1.0-alpha; } // bandpass czpg else if(type==BANDPASS_CZPG) { b0=alpha; b1=0.0; b2=-alpha; a0=1.0+alpha; a1=-2.0*tcos; a2=1.0-alpha; } // notch else if(type==NOTCH) { b0=1.0; b1=-2.0*tcos; b2=1.0; a0=1.0+alpha; a1=-2.0*tcos; a2=1.0-alpha; } // allpass else if(type==ALLPASS) { b0=1.0-alpha; b1=-2.0*tcos; b2=1.0+alpha; a0=1.0+alpha; a1=-2.0*tcos; a2=1.0-alpha; } else { // stop compiler warning a0 = 0; b1 = 0; b2 = 0; a1 = 0; a2 = 0; } } // set filter coeffs b0a0=float(b0/a0); b1a0=float(b1/a0); b2a0=float(b2/a0); a1a0=float(a1/a0); a2a0=float(a2/a0); }; void copyCoeffsFrom(const Biquad &b) { b0a0 = b.b0a0; b1a0 = b.b1a0; b2a0 = b.b2a0; a1a0 = b.a1a0; a2a0 = b.a2a0; } private: // filter coeffs float b0a0 = 0,b1a0 = 0,b2a0 = 0,a1a0 = 0,a2a0 = 0; // in/out history float ou1 = 0,ou2 = 0,in1 = 0,in2 = 0; };
true
37498ca868d143a95300336e53efcecd1b070a87
C++
LGriggles/3DGameEngine
/Actor.hpp
UTF-8
1,328
2.8125
3
[]
no_license
#ifndef ACTOR_HPP #define ACTOR_HPP //GLM #include <glm.hpp> //3DGameEngine #include "DrawingInstance.hpp" #include "Transform.hpp" #include "Collider.hpp" class CollisionEngine; class Scene; /*! The base object that all game objects derive from */ class Actor { private: bool _gridLocked; sf::Vector2i _gridPos; public: Scene* _gameScene; float _velocityX, _velocityY, _velocityZ; int _actorID; bool _destroyed; Transform _transform; //!< The transform of the gameobject, defines position rotatation scale etc DrawingInstance drawingInstance; //!< Handles the drawing of the game object, represents the game object visually CollisionEngine& getCollisionEngine(); CollisionEngine* _collisionEngine; Collider _collision; glm::vec3 _myTint; Actor() { _destroyed = false; } int getActorType(){ return _actorID; } bool isGridLocked(); void setGridLocked(bool s) { _gridLocked = s; } sf::Vector2i getGridPos(); void setGridPos(sf::Vector2i g) { _gridPos = g; } virtual void init(); //!< Called by the scene to initialize the object when it is created, override this to define the behaviour virtual void update(); //!< Called by the scene override this to define the behaviour of the object for updating void destroyMe() { _destroyed = true; } }; #endif // !GAMEOBJECT_H
true
48e4060541c47adefef45f0fb875e734733ed4ac
C++
Hanggansta/MirageRender
/src/materials/dielectric.cpp
UTF-8
2,893
2.84375
3
[ "MIT" ]
permissive
// std includes #include <iostream> // mirage includes #include "dielectric.h" #include "../macros.h" namespace mirage { DielectricMaterial::DielectricMaterial(vec3 kd, vec3 ks, vec3 ke, float ior) : Material(nullptr, nullptr, nullptr, kd, ks, ke, true), m_ior(ior) { } DielectricMaterial::~DielectricMaterial() { } // Explaining fresnel equations and the schlick approximations: // https://graphics.stanford.edu/courses/cs148-10-summer/docs/2006--degreve--reflection_refraction.pdf // Optimized versions of the functions: // http://www.kevinbeason.com/smallpt/ void DielectricMaterial::evalBSDF(const vec3 & P, const vec3 & N, const vec3 & Wr, const vec3 & Wt, const vec3 & Wo, float & brdf, float & btdf) const { // Are we going into the medium or out of it? auto normal = vec3::dot(N, Wo) > 0.0f ? N : N.negate(); bool direct = vec3::dot(N, normal) > 0.0f; // > 0.0 = going into the medium // Calculate the ratio of indices of refraction float eta = direct ? 1.0f / m_ior : m_ior; // Calculate variables for transmission or reflection float NdotWo = vec3::dot(normal, Wo); float cos2t = 1.0f - eta * eta * (1.0f - NdotWo * NdotWo); // Reflect the ray if (cos2t < 0.0f) { brdf = 1.0f; btdf = 0.0f; return; } // Calculate fresnel equations using Schlick's approximations // θi = incidence, θr = reflection, θt = refraction float n1 = m_ior - 1.0f; float n2 = m_ior + 1.0f; float R0 = n1 * n1 / (n2 * n2); // R0 = ((n1 - n2) / (n1 + n2))^2 float c = 1.0f - (direct ? NdotWo : vec3::dot(Wt, N)); // c = (1.0 - cos(θi ? θt))^5 float Rs = R0 + (1.0f - R0) * c * c * c * c * c; // Rschlick(θi) = R0 + (1.0 - R0) * (1.0 - cos(θi ? θt))^5 float Tr = 1.0f - Rs; float P_ = 0.5f * Rs + 0.25f; float R = Rs / P_; float T = Tr / (1.0f - P_); // Assign reflectivity and refractivity if (btdf > 2.0f) { float r = pseudorand(); brdf = (r < P_) ? R : 0.0f; btdf = (r > P_) ? T : 0.0f; } else { brdf = Rs; btdf = Tr; } } void DielectricMaterial::evalBSDF_direct(const vec3 & P, const vec3 & N, const vec3 & We, const vec3 & Wr, const vec3 & Wt, const vec3 & Wo, float & brdf, float & btdf) const { brdf = 0.0f; btdf = 0.0f; } void DielectricMaterial::evalPDF(float & pdf) const { pdf = 1.0f; } void DielectricMaterial::evalWi(const vec3 & Wo, const vec3 & N, vec3 & Wr, vec3 & Wt) { // Are we going into the medium or out of it? auto normal = vec3::dot(N, Wo) > 0.0f ? N : N.negate(); bool direct = vec3::dot(N, normal) > 0.0f; // Calculate the reflected ray Wr = vec3::reflect(Wo.negate(), N).normalize(); // Calculate the ratio of indices of refraction float eta = direct ? 1.0f / m_ior : m_ior; // Refract the ray through the surface, Wt becomes |0.0f| if total internal reflection Wt = vec3::refract(Wo.negate(), normal, eta).normalize(); } }
true
3faa0ee112359fcb07b4fc530a6aff3a9e7212c5
C++
ProkopHapala/SimpleSimulationEngine
/cpp/common/math/Convex2d.cpp
UTF-8
7,015
2.796875
3
[ "MIT" ]
permissive
//#include "arrayAlgs.h" #include "Convex2d.h" // THE HEADER /* bool Convex2d::lineIntersections( const Line2d& line, const Vec2d& p1, Vec2d& p2 ){ int i0,i1; double sign0 = line.dist_unitary( corners[0] ); double sign = line.dist_unitary( corners[1] ); for( i0=2; i0<n; i0++ ){ double sign = line.dist_unitary( corners[i0] ); if( sign * sign0 ) < 0 ) break; } if( i0 >= n )return false; for( i1=i0+1; i1<n; i1++ ){ double sign = line.dist_unitary( corners[i1] ); if( sign * sign0 ) > 0 ) break; } if( i1 >= n ) i1 = 0; } */ bool Convex2d::cut( const Line2d& line, Convex2d& left, Convex2d& right ){ //printf( " inside Convex2d::cut \n" ); // ---- find index of corners left and right of line int i0,i1,i1_; double sign0 = line.dist_unitary( corners[0] ); for( i0=1; i0<(n-1); i0++ ){ double sign = line.dist_unitary( corners[i0] ); if( ( sign * sign0 ) < 0 ) break; } if ( i0 >= n )return false; for( i1=i0+1; i1<n; i1++ ){ double sign = line.dist_unitary( corners[i1] ); if( ( sign * sign0 ) > 0 ) break; } // ---- find intersection points if( i1 >= n ){ i1_ = 0; }else{ i1_ = i1; } Vec2d p1,p2; //printf( " %i %i %i %i \n", i0-1, i0, i1, i1_ ); line.intersectionPoint( corners[i0-1], corners[i0 ], p1 ); line.intersectionPoint( corners[i1-1], corners[i1_], p2 ); // ---- copy the points int nleft = i1-i0; int szleft = 2 + nleft ; int szright = 2 + ( n - nleft ); //printf( " %i %i %i %i %i %i \n", i0, i1, nleft, n, szleft, szright ); //exit(0); left .reallocate( szleft ); right.reallocate( szright ); //printf( " allocated \n" ); right.corners[i0 ].set(p1); right.corners[i0+1].set(p2); left .corners[0].set(p2); left .corners[1].set(p1); int ileft = 2; int iright = 0; for( int i=0; i<n; i++ ){ if( ( i>=i0 ) && ( i<i1 ) ){ left .corners[ileft ].set( corners[i] ); ileft++; }else{ if( iright == i0 ) iright+=2; right.corners[iright].set( corners[i] ); iright++; } } //printf( " %i %i \n", ileft, iright ); return false; } void Convex2d::make_corners( ){ delete corners; } void Convex2d::fromPoints( int np, Vec2d * points, int * permut, double * vals ){ // ---- find left-most pivot point ... to make sure that all angles are within (-pi/2,pi/2) int ipivot = 0; double xmin = points[0].x; for( int i=1; i<np; i++ ){ double xi = points[i].x; if( xmin > xi ){ xmin = xi; ipivot = i; } } // ---- order points by angle to x-axis int ii = 0; for( int i=0; i<np; i++ ){ if( i != ipivot ){ Vec2d d; d.set_sub( points[i], points[ipivot] ); vals [ii] = d.y / d.x; // within (-pi/2,pi/2) if pivot is left-most point permut[ii] = ii; ii++; } } quickSort<double>( vals, permut, 0, np-1 ); for( int i=0; i<(np-1); i++ ){ if( i<ipivot ) permut[i]++; } //permute <double>( permut, A, out, 0, n ); // ---- copy points, exclude inward kinks Vec2d *p1,*p2,*p3; p1 = points + ipivot; p2 = points + permut[ 0 ]; p3 = points + permut[ 1 ]; int nput = 0; int ip = 0; for( int i=2; i<n; i++ ){ double side = line_side( *p2, *p1, *p3 ); if( side > 0 ){ permut[ nput ] = ip; nput++; p1 = p2; p2 = p3; p3 = points + permut[ i ]; }else{ p3 = points + permut[ i ]; } } // finally we copy the points corners[ 0 ].set( ipivot ); for( int i=1; i<nput; i++ ){ corners[ i ].set( points[ permut[i-1] ] ); } update_lines( ); } void Convex2d::fromPoints( int np, Vec2d * points ){ //int * permut = new int [ np ]; //double * vals = new double[ np ]; int permut[np]; double vals [np]; fromPoints( np, points, permut, vals ); //delete permut; //delete vals; } void Convex2d::projectToLine( const Vec2d& dir, double * xs, double * yLs, double * yRs ) const { // FIXME move this to .cpp // -- order corners by pos along direction //printf( " DEBUG 0 \n" ); double xs_ [ n ]; int ibot,itop; double xbot=+1e+300,xtop=-1e+308; for( int i=0; i<n; i++ ){ double xi = dir.dot( corners[i] ); _minit( i, xi, ibot, xbot ); //if( xi<xbot ){ xbot=xi; ibot=i; } _maxit( i, xi, itop, xtop ); //if( x>xmax ){ xmax=x; imax=i; } xs_[i] = xi; //printf( " %i %f \n", i, xi ); } //printf( " imin %i xmin %f \n", ibot, xbot ); //printf( " imax %i xmax %f \n", itop, xtop ); //printf( " DEBUG 1 \n" ); // -- initialize left and right bonder from bottom point "ibot" to top point "itop" Vec2d oleft,oright,pleft,pright; oleft .set( xs_[ibot], dir.dot_perp( corners[ibot] ) ); oright.set( oleft ); xs [ 0 ] = oleft.x; yRs[ 0 ] = oleft.y; yLs[ 0 ] = oleft.y; int index = 0; int ileft = ibot; _circ_inc( ileft, n ); int iright = ibot; _circ_dec( iright, n ); pleft .set( xs_[ileft], dir.dot_perp( corners[ileft ] ) ); pright.set( xs_[iright], dir.dot_perp( corners[iright] ) ); //printf( " DEBUG 3 \n" ); // -- iterate over left and right border resolving points acording to its order along the direction do { index++; //printf( " DEBUG index %i %i %i %f %f \n", index, ileft, iright, pleft.x, pright.x ); if( pleft.x < pright.x ){ // left is closer double yright = oright.y + ( pleft.x - oright.x ) * ( pright.y - oright.y ) / ( pright.x - oright.x ); yLs[ index ] = pleft.y; yRs[ index ] = yright; xs [ index ] = pleft.x; oleft.set( pleft ); _circ_inc( ileft, n ); pleft .set( xs_[ileft], dir.dot_perp( corners[ileft ] ) ); //printf( " left %i %i \n", index, ileft ); // FIXME : we should take care when it come to end ? probably not then ileft=itop }else{ double yleft = oleft.y + ( pright.x - oleft.x ) * ( pleft.y - oleft.y ) / ( pleft.x - oleft.x ); yLs[ index ] = yleft; yRs[ index ] = pright.y; xs [ index ] = pright.x; oright.set( pright ); _circ_dec( iright, n ); pright .set( xs_[iright], dir.dot_perp( corners[iright ] ) ); //printf( " right %i %i \n", index, iright ); } if( index >= (n-1) ){ printf( " loop should end %i %i %i %i \n", index, n, ileft, iright ); break; } // FIXME DEBUG just to prevent infinite loop } while( !( ( itop == ileft ) && ( itop == iright ) ) ); //printf( " index %i ileft %i iright %i itop %i \n", index, ileft, iright, itop ); index = n-1; yLs[ index ] = dir.dot_perp( corners[ itop ] ); yRs[ index ] = yLs[ index ]; xs [ index ] = xs_[itop]; }
true
8f5ac20926aea7b1f5cbdbccbb51b8d6d0f29b7a
C++
wembikon/baba.io
/detail/os/impl/kqueue_timer_impl.h
UTF-8
688
2.515625
3
[ "MIT" ]
permissive
/** * MIT License * Copyright (c) 2020 Adrian T. Visarra **/ #pragma once /** * Kqueue only needs an ident (not a file descriptor, but just an incrementing integer * to associate the timer) for EVFILT_TIMER. * * From BSD manual: * ident - Value used to identify this event. The exact interpretation * is determined by the attached filter, but often is a file descriptor. **/ #include "baba/io_handle.h" #include <cstdint> namespace baba::os { class kqueue_timer_impl { public: static io_handle create() noexcept; private: // We use a smaller than int integer type here so that it will wrap around safely static uint16_t _ident_generator; }; } // namespace baba::os
true
f49b0b91d93681d80ebbdacc66b869e368096149
C++
n-shingo/signal_finder
/src/SignalFinder2019.cpp
SHIFT_JIS
21,046
2.71875
3
[]
no_license
//------------------------------------------------- // SignalFinder2019.cpp // S. NAKAMURA // since: 2019-11-05 //------------------------------------------------- #include "SignalFinder2019.h" #include "ToolFunc.h" using namespace sn; using namespace sn::Tool; // Mo̊Jn void SignalFinder2019::Start() { MoveMode(Mode::FindingRed); } // MȍI(IɃAChOɂ) void SignalFinder2019::Stop() { MoveMode(Mode::Idling); } // 摜ljÁs Result SignalFinder2019::AnalyzeImage(Mat& img, Mat& dst, bool drawResult) { switch (_mode) { case Mode::Idling: return ProcessNothing(img, dst, drawResult); case Mode::FindingRed: return TryFindRedSignal(img, dst, drawResult); case Mode::WaitingBlue: return WaitForBlueSignal(img, dst, drawResult); case Mode::FoundBlue: return FoundBlueSignal(img, dst, drawResult); } return Result::Error; } // // J\bh // // AChỎȂs Result SignalFinder2019::ProcessNothing(Mat& img, Mat& dst, bool drawResult) { assert(_mode == Mode::Idling); if (drawResult) { dst = img.clone(); Labeling(dst, "Idling"); } return Result::NoProcess; } // ԐMTs Result SignalFinder2019::TryFindRedSignal(Mat& img, Mat& dst, bool drawResult) { assert(_mode == Mode::FindingRed); const int gaussKSize = 5; // KEXtB^̃J[lTCY const double gaussSigma = 3.0; // KEXtB^̔a const double red_threshold = 0.6; // ԐM̑֌W臒l // `p̌摜̃N[ if (drawResult) dst = img.clone(); // KEVA Mat gaussImg; Gaussian(img, gaussImg, gaussKSize, gaussSigma, true); // HSV臒l Mat hsvRes; GetRedSignalArea(gaussImg, hsvRes); this->_redAreaBuf.AddImage(hsvRes); if (!_redAreaBuf.IsFilled()) { // \ȉ摜obt@ɗ܂ĂȂꍇ͏I if (drawResult) Labeling(dst, "Looking for red", Point(0, 0), 0.375, Scalar(0, 200, 200)); return Result::LookingForRed; } // ω摜擾 Mat hsvAve; _redAreaBuf.AverageImage(hsvAve); cv::threshold(hsvAve, hsvAve, 100, 255, CV_THRESH_BINARY); // N[WO(c->k) cv::Mat hsvAveMo; cv::morphologyEx(hsvAve, hsvAveMo, cv::MORPH_CLOSE, Mat()); // ̈撊o std::vector< Mat > rgns; std::vector< Rect > rects; SplitImageRegion(hsvAveMo, rgns, rects); if (rgns.size() == 0) { // ɂȂ̈悪Ȃꍇ͏I if (drawResult) Labeling(dst, "Looking for red", Point(0, 0), 0.375, Scalar(0, 200, 200)); return Result::LookingForRed; } // dS擾 std::vector< Point > cogs; GetCOG(rgns, rects, cogs); if (drawResult) { // ԐMdS̕` for (int i = 0; i < cogs.size(); i++) cv::drawMarker(dst, cogs[i], Scalar(255, 0, 255), cv::MARKER_TILTED_CROSS, 7); } // 摜擾 std::vector < Mat > candImg; std::vector < Rect > candImgRect; Rect *sl = &SIGNAL_LOCATE_FROM_RED; for (int i = 0; i < cogs.size(); i++) { cv::Rect rct(cogs[i].x + sl->x, cogs[i].y + sl->y, sl->width, sl->height); if (rct.x >= 0 && rct.y >= 0 && rct.x + rct.width < img.cols && rct.y + rct.height < img.rows) { Mat cand = gaussImg(rct); candImg.push_back(cand.clone()); candImgRect.push_back(rct); } } if (candImg.size() == 0) { // ɂȂ摜Ȃꍇ͏I if (drawResult) Labeling(dst, "Looking for red", Point(0, 0), 0.375, Scalar(0, 200, 200)); return Result::LookingForRed; } if (drawResult) { // 摜̋`` for (int i = 0; i < cogs.size(); i++) { cv::Rect rct(cogs[i].x + sl->x, cogs[i].y + sl->y, sl->width, sl->height); cv::rectangle(dst, rct, Scalar(255, 255, 255)); } } // ֌W臒lȏł΁AԐMƂAꍇ͍ł̂Ƃ double maxCC = -1.0; Mat redSignal; Rect redSignalRect; size_t redIndex; for (int i = 0; i < candImg.size(); i++) { // ܂͌P‚ɑ΂ev[gł̍ōlo std::vector<double> r; for (int j = 0; j < RED_SIGNAL_FILE_CNT; j++) r.push_back(CompareImages(RED_SIGNAL_BASE_IMG[j], candImg[i])); size_t r_max_index = std::distance(r.begin(), std::max_element(r.begin(), r.end())); double r_max = r[r_max_index]; // ܂Ōǂ΁AXV if (r_max >= red_threshold && r_max > maxCC) { maxCC = r_max; redSignal = candImg[i]; redSignalRect = candImgRect[i]; redIndex = r_max_index; } // ԐM֌W̕` if (drawResult) { Point pt = Point(candImgRect[i].x + candImgRect[i].width, candImgRect[i].y); if (r_max >= red_threshold) Labeling(dst, std::to_string(r_max), pt, 0.3, Scalar(0, 0, 200)); else Labeling(dst, std::to_string(r_max), pt, 0.3); } } if (maxCC < red_threshold) { // 臒l𒴂̂ȂΏI if (drawResult) Labeling(dst, "Looking for red", Point(0, 0), 0.375, Scalar(0, 200, 200)); return Result::LookingForRed; } // // ܂ŗԐMۂ̂𔭌! // _redSigImgBuf.AddImage(redSignal); _redCCBuf.AddDouble(maxCC); if (drawResult) cv::rectangle(dst, redSignalRect, Scalar(0, 0, 255)); // ԐM̃obt@tłȂ΁AԐM摜XɎW邽߂ɏI if (!_redSigImgBuf.IsFilled()) { if (drawResult) Labeling(dst, "Looking for red", Point(0, 0), 0.375, Scalar(0, 200, 200)); return Result::LookingForRed; } // ŗǂ̐ԐM摜 int maxIndex = _redCCBuf.GetMaxIndex(); this->_redSignal = _redSigImgBuf[maxIndex].clone(); // ԐMTIAM҂ɑJڂ邷 MoveMode(Mode::WaitingBlue); if (drawResult) { Labeling(dst, "Found red signal", Point(0, 0), 0.375, Scalar(0, 200, 0)); // EɐԐMev[g摜\ Mat tmpArea = dst(Rect(dst.cols - _redSignal.cols, 0, _redSignal.cols, _redSignal.rows)); _redSignal.copyTo(tmpArea); } return Result::FoundRed; } // M҂s Result SignalFinder2019::WaitForBlueSignal(Mat& img, Mat& dst, bool drawResult) { assert(_mode == Mode::WaitingBlue); assert(_redAreaBuf.IsFilled()); const int gaussKSize = 5; // KEXtB^̃J[lTCY const double gaussSigma = 3.0; // KEXtB^̔a const double red_threshold = 0.925; // ԐM̑֌W臒l const double blu_threshold = 0.75; // M̑֌W臒l const double r2b_threshold = 0.25; // ԂMւ̕ϊx臒l // `揀 if (drawResult) { // `p̌摜̃N[ dst = img.clone(); // EɐԐMev[g摜\ Mat tmpArea = dst(Rect(dst.cols - _redSignal.cols, 0, _redSignal.cols, _redSignal.rows)); _redSignal.copyTo(tmpArea); } // KEVA Mat gaussImg; Gaussian(img, gaussImg, gaussKSize, gaussSigma, true); // HSV臒l Mat hsvRes; GetRedSignalArea(gaussImg, hsvRes); _redAreaBuf.AddImage(hsvRes); // ω摜擾 Mat hsvAve; _redAreaBuf.AverageImage(hsvAve); cv::threshold(hsvAve, hsvAve, 100, 255, CV_THRESH_BINARY); // N[WO(c->k) cv::Mat hsvAveMo; cv::morphologyEx(hsvAve, hsvAveMo, cv::MORPH_CLOSE, Mat()); // ̈撊o std::vector< Mat > rgns; std::vector< Rect > rects; SplitImageRegion(hsvAveMo, rgns, rects); // ɂȂ̈悪Ȃꍇ͏I if (rgns.size() == 0) { _redSignalLostCounter++; // MAX_LOST_FRAMESɒBĂAĂѐԐMT[hֈڍs if (_redSignalLostCounter == MAX_LOST_FRAMES) { if (drawResult) Labeling(dst, "Lost red signal!", Point(0, 0), 0.375, Scalar(0, 200, 0)); MoveMode(Mode::FindingRed); return Result::LostRed; } // MAX_LOST_FRAMESɒBĂȂ΁APɏI else { if (drawResult) Labeling(dst, "Waiting for blue", Point(0, 0), 0.375, Scalar(0, 0, 200)); return Result::WaitingForBlue; } } // dS擾 std::vector< Point > cogs; GetCOG(rgns, rects, cogs); if (drawResult) { // ԐMdS̕` for (int i = 0; i < cogs.size(); i++) cv::drawMarker(dst, cogs[i], Scalar(255, 0, 255), cv::MARKER_TILTED_CROSS, 7); } // 摜擾 std::vector < Mat > candImg; std::vector < Rect > candImgRect; Rect *sl = &SIGNAL_LOCATE_FROM_RED; for (int i = 0; i < cogs.size(); i++) { cv::Rect rct(cogs[i].x + sl->x, cogs[i].y + sl->y, sl->width, sl->height); if (rct.x >= 0 && rct.y >= 0 && rct.x + rct.width < img.cols && rct.y + rct.height < img.rows) { Mat cand = gaussImg(rct); candImg.push_back(cand.clone()); candImgRect.push_back(rct); } } // ɂȂ摜Ȃꍇ͏I if (candImg.size() == 0) { _redSignalLostCounter++; // MAX_LOST_FRAMESɒBĂAĂѐԐMT[hֈڍs if (_redSignalLostCounter == MAX_LOST_FRAMES) { if (drawResult) Labeling(dst, "Lost red signal!", Point(0, 0), 0.375, Scalar(0, 200, 0)); MoveMode(Mode::FindingRed); return Result::LostRed; } // MAX_LOST_FRAMESɒBĂȂ΁APɏI else { if (drawResult) Labeling(dst, "Waiting for blue", Point(0, 0), 0.375, Scalar(0, 0, 200)); return Result::WaitingForBlue; } } if (drawResult) { // 摜` for (int i = 0; i < cogs.size(); i++) { cv::Rect rct(cogs[i].x + sl->x, cogs[i].y + sl->y, sl->width, sl->height); cv::rectangle(dst, rct, Scalar(255, 255, 255)); } } // 摜ԐMf double red_maxCC = -1.0; Mat max_redImg; Rect max_redRect; for (int i = 0; i < candImg.size(); i++) { // ԐMev[gƂ̑֌WvZ double r = CompareImages(_redSignal, candImg[i]); if (r > red_maxCC) { red_maxCC = r; max_redImg = candImg[i]; max_redRect = candImgRect[i]; } } // ԐM̑֌W` if (drawResult && candImg.size() > 0) { Point pt = Point(max_redRect.x + max_redRect.width, max_redRect.y); if (red_maxCC >= red_threshold) Labeling(dst, std::to_string(red_maxCC), pt, 0.3, Scalar(0, 0, 200)); else Labeling(dst, std::to_string(red_maxCC), pt, 0.3); } // ԐMłꍇ̏ if (red_maxCC > red_threshold) { // ԐMev[g摜XVALOSTJE^0ɃZbgďI _redSignal = max_redImg.clone(); _redSignalLostCounter = 0; if (drawResult) { rectangle(dst, max_redRect, Scalar(0, 0, 255)); Labeling(dst, "Waiting for blue", Point(0, 0), 0.375, Scalar(0, 0, 200)); } return Result::WaitingForBlue; } // ԐMłȂꍇAMf double blu_maxCC = -1.0; Mat bluImg; Rect bluRect; for (int i = 0; i < candImg.size(); i++) { // ܂͌P‚ɑ΂ev[gł̑֌Wōlo std::vector<double> r; for (int j = 0; j < BLUE_SIGNAL_FILE_CNT; j++) r.push_back(CompareImages(BLUE_SIGNAL_BASE_IMG[j], candImg[i])); size_t r_max_index = std::distance(r.begin(), std::max_element(r.begin(), r.end())); double r_max = r[r_max_index]; // ܂ł̌ǂ΁AXV if (r_max > blu_maxCC) { blu_maxCC = r_max; bluImg = candImg[i]; bluRect = candImgRect[i]; } } // ʂ̐M̑֌W` if (drawResult && candImg.size() > 0 ) { Point pt = Point(bluRect.x + bluRect.width, bluRect.y + 20); if (blu_maxCC >= blu_threshold) Labeling(dst, std::to_string(blu_maxCC), pt, 0.3, Scalar(200, 200, 0)); else Labeling(dst, std::to_string(blu_maxCC), pt, 0.3); } // MۂꍇAԐMMւ̕ω`FbN double r2b_cc=0.0; int r2b = 0; if(blu_maxCC >= blu_threshold ){ r2b_cc = RedAndBlueDifCC(_redSignal, bluImg); if(drawResult){ Point pt = Point(bluRect.x + bluRect.width, bluRect.y + 40); if( r2b_cc >= r2b_threshold ) Labeling(dst, std::to_string(r2b_cc), pt, 0.3, Scalar(255,0,0)); else Labeling(dst, std::to_string(r2b_cc), pt, 0.3); } // 摜̑OK̏ꍇ if(r2b_cc >= r2b_threshold ){ r2b = RedToBlueCheck(_redSignal, bluImg); if(drawResult){ Point pt = Point(bluRect.x + bluRect.width, bluRect.y + 60); if( r2b == 1 ) Labeling(dst, std::to_string(r2b), pt, 0.3, Scalar(255,0,0)); else Labeling(dst, std::to_string(r2b), pt, 0.3); } } } // MłȂꍇ if (blu_maxCC < blu_threshold || r2b == 0 ) { _redSignalLostCounter++; // MAX_LOST_FRAMESɒBĂAĂѐԐMT[hֈڍs if (_redSignalLostCounter == MAX_LOST_FRAMES) { if (drawResult) Labeling(dst, "Lost red signal!", Point(0, 0), 0.375, Scalar(0, 200, 0)); MoveMode(Mode::FindingRed); return Result::LostRed; } // MAX_LOST_FRAMESɒBĂȂ΁APɏI else { if (drawResult) Labeling(dst, "Waiting for blue", Point(0, 0), 0.375, Scalar(0, 0, 200)); return Result::WaitingForBlue; } } // // ܂ŗMŔ! // MoveMode(Mode::FoundBlue); if (drawResult) { Labeling(dst, "Found blue signal", Point(0, 0), 0.375, Scalar(255, 0, 0)); } return Result::FoundBlueSignal; } Result SignalFinder2019::FoundBlueSignal(Mat& img, Mat& dst, bool drawResult) { // MK񐔂܂ŏo͂ if (_bluSignalCounter < BLUE_SIGNAL_FRAMES) { if (drawResult) { Labeling(dst, "Found blue signal", Point(0, 0), 0.375, Scalar(255, 0, 0)); } _bluSignalCounter++; return Result::FoundBlueSignal; } // AChO[hɑJڂ MoveMode(Mode::Idling); if (drawResult) { Labeling(dst, "Idling", Point(0, 0), 0.375); } return Result::FoundBlueSignal; } // [h̑Jڂs void SignalFinder2019::MoveMode(Mode mode) { if (mode == Mode::Idling) { _mode = Mode::Idling; } // ԐM[h֑J else if (mode == Mode::FindingRed) { _mode = Mode::FindingRed; _redAreaBuf.Clear(); // HSVɂQl摜̃obt@ _redSigImgBuf.Clear(); // ԐM摜obt@ _redCCBuf.Clear(); // ԐM֌Wobt@ } else if (mode == Mode::WaitingBlue) { _mode = Mode::WaitingBlue; _redSignalLostCounter = 0; //ԐMXg񐔂𐔂JE^[ } else if (mode == Mode::FoundBlue) { _mode = Mode::FoundBlue; _bluSignalCounter = 1; // JڂƂ͊1񔭌Ă̂1n܂ } } // HSVɂ臒lɂĐԐM̈摜擾 // src̓J[摜, dst8bit̂Ql摜 void SignalFinder2019::GetRedSignalArea(cv::Mat& src, cv::Mat& dst) { assert(src.type() == CV_8UC3); int h = src.rows, w = src.cols; cv::Mat imgH, imgS, imgV; SplitToHSV(src, imgH, imgS, imgV); dst = Mat::zeros(src.size(), CV_8U); uchar *p, *pH, *pS, *pV; for (int y = 0; y < h; y++) { p = dst.data + dst.step[0] * y; pH = imgH.data + y * w; pS = imgS.data + y * w; pV = imgV.data + y * w; for (int x = 0; x < w; x++) { //if (pS[x] > 100 && (pH[x] > 170 || pH[x] < 15) && pV[x] > 50) { //if (pS[x] > 120 && (pH[x] > 170 || pH[x] < 15) && pV[x] > 100) { if (pS[x] > 140 && (pH[x] > 170 || pH[x] < 15) && pV[x] > 100) { p[x] = 255; } } } } // ԐMMɕύXꂽ摜̑֌WvZ double SignalFinder2019::RedAndBlueDifCC(cv::Mat& red, cv::Mat& blu) { assert(red.type() == CV_8UC3); assert(blu.type() == CV_8UC3); assert(red.cols == blu.cols); assert(red.rows == blu.rows); // OC摜 int h = red.rows, w = red.cols; cv::Mat red_gray, blu_gray; cvtColor(red, red_gray, CV_BGR2GRAY); cvtColor(blu, blu_gray, CV_BGR2GRAY); // vZ Mat dif = Mat::zeros(red_gray.size(), CV_8U); for( int y=0; y<h; y++ ){ uchar *r_pt = red_gray.data + red_gray.step[0]*y; uchar *b_pt = blu_gray.data + blu_gray.step[0]*y; uchar *d_pt = dif.data + dif.step[0]*y; for( int x=0; x<dif.step[0]; x++ ){ d_pt[x] = (r_pt[x] - b_pt[x] + 255)/2; // vZ } } // ev[gƔr return CompareImages( dif, R2B_DIFF_IMG ); } int SignalFinder2019::RedToBlueCheck(cv::Mat& red, cv::Mat& blu) { assert(red.type() == CV_8UC3); assert(blu.type() == CV_8UC3); assert(red.cols == blu.cols); assert(red.rows == blu.rows); // 낢臒l const int th_dif1=132, th_dif2=115; // 摜ł̊Ԃ̒l͌Ȃ const int th_up = 136, th_up_cnt = 10; const int th_dn = 115, th_dn_cnt = 20; // OC摜 int h = red.rows, w = red.cols; cv::Mat red_gray, blu_gray; cvtColor(red, red_gray, CV_BGR2GRAY); cvtColor(blu, blu_gray, CV_BGR2GRAY); // vZ Mat dif = Mat::zeros(red_gray.size(), CV_8U); for( int y=0; y<h; y++ ){ uchar *r_pt = red_gray.data + red_gray.step[0]*y; uchar *b_pt = blu_gray.data + blu_gray.step[0]*y; uchar *d_pt = dif.data + dif.step[0]*y; for( int x=0; x<dif.step[0]; x++ ){ d_pt[x] = (r_pt[x] - b_pt[x] + 255)/2; // vZ } } // Ԃ‚֕ω dif 摜͏㔼͖邢~A͈Â~ł͂ // 臒l̏㉺̕ςƐZo int half_h = h/2; int cnt_up = 0, ave_up = 0; int cnt_dn = 0, ave_dn = 0; for( int y=0; y<h; y++ ){ uchar *pt = dif.data + dif.step[0]*y; for( int x=0; x<dif.step[0]; x++ ){ if( pt[x] < th_dif2 || pt[x] > th_dif1 ){ // 㔼 if( y < half_h ){ ave_up += pt[x]; cnt_up++; } // else{ ave_dn += pt[x]; cnt_dn++; } } else pt[x]=0; } } // LȉfȂFalseŏI if( cnt_up == 0 || cnt_dn == 0 ) return 0; ave_up /= cnt_up; ave_dn /= cnt_dn; // ʃ`FbN //imshow( "difference", dst ); //std::cout << "UP: " << ave_up << ", " << cnt_up << std::endl; //std::cout << "DN: " << ave_dn << ", " << cnt_dn << std::endl; // ԐMMւ̕ω if( ave_up >= th_up && cnt_up >= th_up_cnt && ave_dn <= th_dn && cnt_dn >= th_dn_cnt){ return 1; } else return 0; }
true
57eadbf20eb9a6278fc8589b70081414f4a10c68
C++
cryptocrowd-city/libxayagame
/xayagame/sqlitestorage.hpp
UTF-8
7,970
2.59375
3
[ "MIT" ]
permissive
// Copyright (C) 2018-2020 The Xaya developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef XAYAGAME_SQLITESTORAGE_HPP #define XAYAGAME_SQLITESTORAGE_HPP #include "storage.hpp" #include <xayautil/uint256.hpp> #include <sqlite3.h> #include <condition_variable> #include <map> #include <memory> #include <mutex> #include <string> namespace xaya { class SQLiteStorage; /** * Wrapper around an SQLite database connection. This object mostly holds * an sqlite3* handle (that is owned and managed by it), but it also * provides some extra services like statement caching. */ class SQLiteDatabase { private: /** Whether or not we have already set the SQLite logger. */ static bool loggerInitialised; /** * The SQLite database handle, which is owned and managed by the * current instance. It will be opened in the constructor, and * finalised in the destructor. */ sqlite3* db; /** * Whether or not we have WAL mode on the database. This is required * to support snapshots. It may not be the case if we have an in-memory * database. */ bool walMode; /** The "parent" storage if this is a read-only snapshot. */ const SQLiteStorage* parent = nullptr; /** * A cache of prepared statements (mapping from the SQL command to the * statement pointer). */ mutable std::map<std::string, sqlite3_stmt*> preparedStatements; /** * Marks this is a read-only snapshot (with the given parent storage). When * called, this starts a read transaction to ensure that the current view is * preserved for all future queries. It also registers this as outstanding * snapshot with the parent. */ void SetReadonlySnapshot (const SQLiteStorage& p); /** * Returns whether or not the database is using WAL mode. */ bool IsWalMode () const { return walMode; } friend class SQLiteStorage; public: /** * Opens the database at the given filename into this instance. The flags * are passed on to sqlite3_open_v2. */ explicit SQLiteDatabase (const std::string& file, int flags); /** * Closes the database connection. */ ~SQLiteDatabase (); /** * Returns the raw handle of the SQLite database. */ sqlite3* operator* () { return db; } /** * Returns the raw handle, like operator*. This function is meant * for code that then only does read operations and no writes. */ sqlite3* ro () const { return db; } /** * Prepares an SQL statement given as string and stores it in the cache, * or retrieves the existing statement from the cache. The prepared statement * is also reset, so that it can be reused right away. * * The returned statement is managed (and, in particular, finalised) by the * SQLiteDatabase object, not by the caller. */ sqlite3_stmt* Prepare (const std::string& sql); /** * Prepares an SQL statement given as string like Prepare. This method * is meant for statements that are read-only, i.e. SELECT. */ sqlite3_stmt* PrepareRo (const std::string& sql) const; }; /** * Implementation of StorageInterface, where all data is stored in an SQLite * database. In general, a no-SQL database would be more suitable for game * storage (as only key lookups are required), but this can be useful in * combination with games that keep their game state in SQLite as well (so that * a single database holds everything). * * The storage implementation here uses tables with prefix "xayagame_". * Subclasses that wish to store custom other data must not use tables * with this prefix. */ class SQLiteStorage : public StorageInterface { private: /** * The filename of the database. This is needed for resetting the storage, * which removes the file and reopens the database. */ const std::string filename; /** * The database connection we use (mainly) and for writes, if one is * opened at the moment. */ std::unique_ptr<SQLiteDatabase> db; /** * Set to true when we have a currently open transaction. This is used to * verify that BeginTransaction is not called in a nested way. (Savepoints * would in theory support that, but we exclude it nevertheless.) */ bool startedTransaction = false; /** * Number of outstanding snapshots. This has to drop to zero before * we can close the database. */ mutable unsigned snapshots = 0; /** Mutex for the snapshot number. */ mutable std::mutex mutSnapshots; /** Condition variable for waiting for snapshot unrefs. */ mutable std::condition_variable cvSnapshots; /** * Opens the database at filename into db. It is an error if the * database is already opened. */ void OpenDatabase (); /** * Closes the database, making sure to wait for all outstanding snapshots. */ void CloseDatabase (); /** * Decrements the count of outstanding snapshots. */ void UnrefSnapshot () const; friend class SQLiteDatabase; protected: /** * Sets up the database schema if it does not already exist. This function is * called after opening the database, including when it was first created (but * not only then). It creates the required tables if they do not yet exist. * * Subclasses can override the method to also set up their schema (and, * perhaps, to upgrade the schema when the software version changes). They * should make sure to call the superclass method as well in their * implementation. */ virtual void SetupSchema (); /** * Returns the underlying SQLiteDatabase instance. */ SQLiteDatabase& GetDatabase (); /** * Returns the underlying SQLiteDatabase instance. */ const SQLiteDatabase& GetDatabase () const; /** * Creates a read-only snapshot of the underlying database and returns * the corresponding SQLiteDatabase instance. May return NULL if the * underlying database is not using WAL mode (e.g. in-memory). */ std::unique_ptr<SQLiteDatabase> GetSnapshot () const; /** * Steps a given statement and expects no results (i.e. for an update). * Can also be used for statements where we expect exactly one result to * verify that no more are there. */ static void StepWithNoResult (sqlite3_stmt* stmt); /** * Returns the current block hash (if any) for the given database connection. * This method needs to be separated from the instance GetCurrentBlockHash * without database argument so that it can be used with snapshots in * SQLiteGame. */ static bool GetCurrentBlockHash (const SQLiteDatabase& db, uint256& hash); public: explicit SQLiteStorage (const std::string& f) : filename(f) {} ~SQLiteStorage (); SQLiteStorage () = delete; SQLiteStorage (const SQLiteStorage&) = delete; void operator= (const SQLiteStorage&) = delete; void Initialise () override; /** * Clears the storage. This deletes and re-creates the full database, * and does not only delete from the tables that SQLiteStorage itself uses. * This ensures that all data, including about game states, that is stored * in the same database is removed consistently. */ void Clear () override; bool GetCurrentBlockHash (uint256& hash) const override; GameStateData GetCurrentGameState () const override; void SetCurrentGameState (const uint256& hash, const GameStateData& data) override; bool GetUndoData (const uint256& hash, UndoData& data) const override; void AddUndoData (const uint256& hash, unsigned height, const UndoData& data) override; void ReleaseUndoData (const uint256& hash) override; void PruneUndoData (unsigned height) override; void BeginTransaction () override; void CommitTransaction () override; void RollbackTransaction () override; }; } // namespace xaya #endif // XAYAGAME_SQLITESTORAGE_HPP
true
c700d89edf1d39394090af8d255ebe5a9f5164be
C++
louislaaaw/CS161-162-260
/Assign01/Person.cpp
UTF-8
6,119
3.46875
3
[]
no_license
//---------------------------------------------------------- // CS260 Assignment 1 Starter Code // Copyright Andrew Scholer (ascholer@chemeketa.edu) // Neither this code, nor any works derived from it // may not be republished without approval. //---------------------------------------------------------- #include "Person.h" #include <fstream> #include <string> #include <algorithm> #include <utility> using namespace std; bool operator==(const Person& p1, const Person& p2){ if(p1.kNum == p2.kNum) return true; else return false; } //void check(Person* array, int low, int mid, int high, Person* temp){ // int a = low; // int b = mid + 1; // int c = low; // while((a <= mid) && (b <= high)){ //// if(array[a].last == array[b].last){ //// if(array[a].first[0] > array[b].first[0]){ //// temp[c] = array[b]; //// temp[c + 1] = array[a]; //// }else{ //// temp[c] = array[a]; //// temp[c + 1] = array[b]; //// } //// a++; //// b++; //// c += 2; //// } // if(array[a].last[0] > array[b].last[0]){ // temp[c] = array[b]; // b++; // c++; // } // else{ // temp[c] = array[a]; // a++; // c++; // } // } //} //Sort a portion of array of Persons by zicode // Range of elements to sort is [start-end) (inclusive or start, exclusive of end) void partialZipSort(Person* array, int start, int end){ for(int i = start ; i <= end ; i++){ for(int j = i + 1 ; j <= end ; j++){ if(array[j].zipCode < array[i].zipCode){ swap(array[i], array[j]); } } } } //Counts all the individuals in an array who have a given last name int countLastName(const std::string& lastName, const Person* array, int size){ int count = 0; for(int i = 0; i < size; i++){ if (array[i].last == lastName){ count++; } } return count; } void mergeFunc(Person* array, int low, int mid, int high, Person* temp) { //TODO - Fixme int a = low; int b = mid + 1; int c = low; //While either first sequence has an item left or second sequence has an item left while((a <= mid) && (b <= high)){ if(array[a].last > array[b].last){ temp[c] = array[b]; b++; c++; } else{ if(array[a].last == array[b].last){ if(array[a].first > array[b].first){ temp[c] = array[b]; b++; c++; }else{ temp[c] = array[a]; a++; c++; } }else{ temp[c] = array[a]; a++; c++; } } } while(a <= mid){ temp[c] = array[a]; c++; a++; } while(b <= high){ temp[c] = array[b]; c++; b++; } // Move smaller remaining item from front of first or second sequence // to next available location in temp //Copy indexes from low-high from temp back to arr for(int i = low; i < c; i++){ array[i] = temp[i]; } } void mergeSortInternal(Person* array, int low, int high, Person* temp) { if (low >= high) return; int mid = (low + high) / 2; mergeSortInternal(array, low, mid, temp); mergeSortInternal(array, mid+1, high, temp); mergeFunc(array, low, mid, high, temp); } //Sort an array of Persons so that they are alphabetized by last name // Individuals with the same last name should be ordered by first name void nameSort(Person* array, int size){ Person* temp = new Person[size]; mergeSortInternal(array, 0, size - 1, temp); delete [] temp; } //Returns index of the first Person with a given lastName // If there is no one with that last name, return the size to indicate failure int binaryFindFirstByLastName(const std::string& lastName, const Person* array, int size){ int minLoc = 0; int maxLoc = size - 1; if(array[minLoc].last == lastName){ return minLoc; } while(minLoc <= maxLoc){ int midLoc = (minLoc + maxLoc) / 2; int PrevLoc = midLoc - 1; if((array[midLoc].last == lastName)){ if ((maxLoc - midLoc == 1) || array[PrevLoc].last != array[midLoc].last){ return midLoc; }else{ maxLoc = midLoc - 1; } } else{ if(array[midLoc].last < lastName){ minLoc = midLoc + 1; } else{ maxLoc = midLoc - 1; } } } return size; } //Returns index of the last Person with a given lastName // If there is no one with that last name, return the size to indicate failure int binaryFindLastByLastName(const std::string& lastName, const Person* array, int size){ int minLoc = 0; int maxLoc = size - 1; if(array[maxLoc].last == lastName){ return maxLoc; } while(minLoc <= maxLoc){ int midLoc = (minLoc + maxLoc) / 2; int NextLoc = midLoc + 1; if((array[midLoc].last == lastName)){ if (((maxLoc - midLoc == 1) || array[NextLoc].last != array[midLoc].last)){ return midLoc; }else{ minLoc = midLoc + 1; } } else{ if(array[midLoc].last < lastName){ minLoc = midLoc + 1; } else{ maxLoc = midLoc - 1; } } } return size; } //Counts all the individuals in an array who have a given last name. // Function ONLY works on arrays sorted by last name. int countLastNameInSorted(std::string lastName, const Person* array, int size){ int low = binaryFindFirstByLastName(lastName, array, size); int high = binaryFindLastByLastName(lastName, array, size); int num_sorted = high - low + 1; return num_sorted; }
true
1975ab953560dc16cfa10277c4634f9bc9cba499
C++
phiwen96/MyLibs
/libs/ph/libs/core/src/core.cpp
UTF-8
677
2.75
3
[ "MIT" ]
permissive
#include <ph/core/core.hpp> namespace ph::core { template <> inline bool isInteger(const std::string & s) { if(s.empty() || ((!isdigit(s[0])) && (s[0] != '-') && (s[0] != '+'))) return false; char * p; strtol(s.c_str(), &p, 10); return (*p == 0); } template <> inline bool isInteger(const char* s) { return isInteger(std::string(s)); } template <> auto from_int (int i) -> const char* { // static mutex mtx; // lock_guard<mutex> lock (mtx); std::stringstream temp_str; temp_str<<(i); std::string str = temp_str.str(); const char* cstr2 = str.c_str(); return cstr2; } }
true
71f6ba5dc068dced90fa66f4498e9c6a39d3df96
C++
nathangurnee/Snake
/src/Pineapple.cpp
UTF-8
1,273
3.046875
3
[]
no_license
#include "../include/Pineapple.h" #include "../include/PineappleMovement.h" // Dimensions of pineapple const int PINEAPPLE_WIDTH = 50; const int PINEAPPLE_HEIGHT = 50; Pineapple::Pineapple() : Graphic(), renderer(NULL) { collisions = 0; x = 40 + rand() % 634; y = 40 + rand() % 634; } void Pineapple::setRenderer(SDL_Renderer* renderer) { this->renderer = renderer; } void Pineapple::draw() { // x, y = coordinates SDL_Rect location = { static_cast<int>(x), static_cast<int>(y), PINEAPPLE_WIDTH, PINEAPPLE_HEIGHT }; // Sets color of pineapple (white) // r, g, b, alpha (opacity) SDL_SetRenderDrawColor(renderer, 200, 255, 18, 255); // Colors the pineapple SDL_RenderFillRect(renderer, &location); } void Pineapple::update(Graphic* snake) { // Checks whether the snake has collided with the pineapple // and creates a new one if true if((snake->body[0].first + 20 >= x && snake->body[0].second + 20 >= y) && (snake->body[0].first <= x + PINEAPPLE_WIDTH && snake->body[0].second <= y + PINEAPPLE_HEIGHT)) { setMovement(new PineappleMovement()); movement->move(this); collisions++; } } void Pineapple::move() { if (movement != nullptr) { movement->move(this); } }
true
e6967d62dde9777f62e2302fff6a34bd7f0aef3d
C++
watashi/AlgoSolution
/zoj/16/1655.cpp
UTF-8
1,518
2.71875
3
[]
no_license
#include <cstdio> double mp[101][101]; double maxr[101]; double weight[101]; void Dijkstra(const int n) { static bool mark[101]; for (int i = 1; i <= n; i++) { mark[i] = false; maxr[i] = 0.0; } maxr[n] = 1.0; for (int i = 1; i <= n; i++) { int k = 0; for (int j = 1; j <= n; j++) if(!mark[j] && (k == 0 || maxr[j] > maxr[k])) k = j; mark[k] = true; for (int j = 1; j <= n; j++) if(!mark[j] && maxr[j] < maxr[k] * mp[k][j]) maxr[j] = maxr[k] * mp[k][j]; } } int main(void) { int a, b, n, m; double ans; while(scanf("%d%d", &n, &m) != EOF) { for (int i = 1; i <= n; i++) { if(i < n) scanf("%lf", &weight[i]); else weight[i] = 0; for (int j = 1; j <= n; j++) mp[i][j] = 0.0; } while(m--) { scanf("%d%d%lf", &a, &b, &ans); if(mp[a][b] < 1.0 - ans) // 555 tooold is also not old 555 mp[a][b] = mp[b][a] = 1.0 - ans; } Dijkstra(n); ans = 0.0; for (int i = 1; i < n; i++) ans += weight[i] * maxr[i]; printf("%.2lf\n", ans); } } //Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name //2840636 2008-04-12 20:24:23 Accepted 1655 C++ 00:00.04 480K Re:ReJudge // 2012-09-07 00:57:17 | Accepted | 1655 | C++ | 10 | 260 | watashi | Source
true
06e80fcf5ec338ec1841db0956c97ac972136849
C++
HyeongGunLee/ProblemSolving
/CrackingCoding/ConnectedCelss_DFS.cpp
UTF-8
928
3.28125
3
[]
no_license
#include <iostream> using namespace std; int getRegionSize(int matrix[100][100], int row, int col) { if (row < 0 || col < 0 || row > 100 || col > 100) { return 0; } if (matrix[row][col] == 0) { return 0; } matrix[row][col] = 0; int size = 1; for (int i = row-1; i <= row+1; i++) { for (int j = col-1; j <= col+1; j++) { if (i != row || j != col) { size += getRegionSize(matrix, i, j); } } } return size; } int getBiggestRegion(int matrix[100][100], int width, int height) { int maxRegion = 0; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { if (matrix[row][col] == 1) { int size = getRegionSize(matrix, row, col); maxRegion = max(maxRegion, size); } } } return maxRegion; } int main(void) { }
true
d3535264a8fcad1a07cc9926a73cffb809fbd2c5
C++
iloveooz/podbelsky
/03/p3-04.cpp
UTF-8
728
3.453125
3
[]
no_license
//p3-04.cpp - переопределение внешнего имени внутри блока #include <iostream> using namespace std; int main() { char cc[] = "Число"; // массив автоматической памяти float pi = 3.14; // переменная типа float cout << "Обращение по внешнему имени: pi = " << pi; { // переменная типа double переопределяет pi: long double pid = 3.1415926535897932385; // видимы double pi и массив cc[]: cout << '\n' << cc << " long double pid = " << pid; } // видимы float pi и массив cc[]: cout << '\n' << cc << " float pi = " << pi << endl; return 0; }
true
28471b1169a4d27924b9afe6fafb212a36190b14
C++
ByteLeopord/Examination
/剑指offer/offer04二维数组中的查找.cpp
UTF-8
526
3.09375
3
[]
no_license
class Solution { public: bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) { if(matrix.empty()) return false; int row = matrix.size(); int col = matrix[0].size(); int x = col-1, y = 0; while(x >= 0 && y < row){ if(matrix[y][x] > target){ x--; } else if(matrix[y][x] < target){ y++; } else{ return true; } } return false; } };
true
19897d01834931c72bbbd76ac5953f254b6fadce
C++
TheSennin/Arquivos_Facul
/Estruturas de Dados/2018 - 2/Trabalhos/M2/Trabalho M2 - Filas e Pilhas/Questão 2/Fila.cpp
ISO-8859-1
4,007
3.421875
3
[]
no_license
#include "Fila.h" #include "NodoDuplo.cpp" #include <stdio.h> #include <iostream> using namespace std; template <typename T> Fila<T>::Fila(){ this->numeroElementos = 0; this->inicio = NULL; this->fim = NULL; } template <typename T> Fila<T>::~Fila(){ NodoDuplo<T> *nodo; while(this->inicio != NULL){ nodo = this->inicio; this->inicio = this->inicio->getProximo(); delete nodo; } this -> numeroElementos = 0; } template <typename T> bool Fila<T>::ehVazia(){ return numeroElementos == 0; } template <typename T> int Fila<T>::numeroDeElementos(){ return this->numeroElementos; } template <typename T> bool Fila<T>::existeElemento(T elemento){ NodoDuplo<T> *nodo = this->inicio; while(nodo != NULL){ if(nodo->getElemento() == elemento){ return true; } nodo = nodo->getProximo(); } return false; } template <typename T> void Fila<T>::insere(T elemento, int prioridade){ NodoDuplo<T> *nodo = new NodoDuplo<T>(elemento, prioridade); if(this->inicio == NULL){ this->inicio = nodo; this->fim = nodo; } else{ nodo->setAnterior(this->fim); this->fim->setProximo(nodo); this->fim = nodo; } this->numeroElementos++; } template <typename T> void Fila<T>::retiraElemento(T elemento){ NodoDuplo<T> *nodo = this->inicio; while(nodo != NULL && nodo->getElemento() != elemento){ nodo = nodo->getProximo(); } if(nodo->getElemento() != elemento) cout << "No existe o elemento informado!" << endl; else if(this->inicio == this->fim){ this->inicio = NULL; this->fim = NULL; this->numeroElementos == 0; delete nodo; cout << "Elemento retirado!" << endl << endl; } else if(nodo == this->inicio){ NodoDuplo<T> *nodoSeguinte = nodo->getProximo(); this->inicio = nodoSeguinte; nodoSeguinte->setAnterior(NULL); numeroElementos--; delete nodo; cout << "Elemento retirado!" << endl << endl; } else if(nodo == this->fim){ NodoDuplo<T> *nodoAnterior = nodo->getAnterior(); this->fim = nodoAnterior; nodoAnterior->setProximo(NULL); numeroElementos--; delete nodo; cout << "Elemento retirado!" << endl << endl; } else{ NodoDuplo<T> *nodoAnterior = nodo->getAnterior(); NodoDuplo<T> *nodoSeguinte = nodo->getProximo(); nodoAnterior->setProximo(nodoSeguinte); nodoSeguinte->setAnterior(nodoAnterior); delete nodo; numeroElementos--; cout << "Elemento retirado!" << endl << endl; } } template <typename T> void Fila<T>::retiraComPrioridade(){ NodoDuplo<T> *nodo = this->inicio; bool retirou=false; do{ if(nodo->getPrioridade()==3){ retiraElemento(nodo->getElemento()); retirou = true; }else nodo = nodo->getProximo(); }while(!retirou && nodo!=NULL); nodo = this->inicio; while(!retirou && nodo!=NULL){ if(nodo->getPrioridade()==2){ retiraElemento(nodo->getElemento()); retirou = true; }else nodo = nodo->getProximo(); } if(!retirou){ nodo = this->inicio; retiraElemento(nodo->getElemento()); } } template <typename T> void Fila<T>::mostra(){ NodoDuplo<T> *nodo = this->inicio; cout << "Fila: "; if(numeroDeElementos()==0) cout << "Fila Vazia!"; else{ while(nodo != NULL){ cout << nodo->getElemento() << "(" << nodo->getPrioridade() << ")" << " "; nodo = nodo->getProximo(); } cout << endl << endl << "NOTA: Os numeros dentre os parenteses determinam a prioridade."; } cout << endl << endl; }
true
37a084473c72994a9cdd7f4c10f2926d058235e7
C++
Verdagon/extrude
/src/monotonify.cpp
UTF-8
27,299
2.75
3
[]
no_license
#include "monotonify.h" #include <unordered_map> #include <set> using std::unordered_set; using std::unordered_map; using std::vector; using std::set; using std::pair; using std::make_pair; using glm::vec2; namespace monotonify { owning_ptr<Graph> assembleNodes(const vector<vector<PointFromFont>> & contours) { owning_ptr<Graph> graph(new Graph()); for (int contourI = 0; contourI < contours.size(); contourI++) { owning_ptr<Contour> contour(new Contour()); const vector<PointFromFont> & points = contours[contourI]; vector<owning_ptr<ImprovedNode>> nodes; for (int i = 0; i < points.size(); i++) { PointFromFont point = points[i]; nodes.emplace_back(owning_ptr<ImprovedNode>(new ImprovedNode { point.location, point.insideCurve, std::set<NodeRef>(), PointType::REGULAR, vec2(0, 0), vec2(0, 0), contour })); } for (int i = 0; i < nodes.size(); i++) { int previousIndex = (i + nodes.size() - 1) % nodes.size(); int nextIndex = (i + 1) % nodes.size(); nodes[i]->neighbors.insert(nodes[previousIndex]); nodes[i]->neighbors.insert(nodes[nextIndex]); } for (int i = 0; i < nodes.size(); i++) { contour->insert(std::move(nodes[i])); } if (nodes.size() == 0) { std::cerr << "Warning: contour with zero points, skipping." << std::endl; } else if (nodes.size() < 3) { std::cerr << "Warning: contour with less than three points, skipping." << std::endl; } else { graph->insert(std::move(contour)); } } for (auto contour : *graph) { vassert(contour->size() >= 3); contour->forInOrder([](NodeRef previous, NodeRef current, NodeRef next) { vassert(!veeq(current->point, previous->point)); vassert(!veeq(current->point, next->point)); }); } return std::move(graph); } vec2 getInsideBisector(vec2 previousPointInsideBisector, vec2 previous, vec2 current, vec2 next, bool allowColinears = false) { vassert(previous != current); vassert(current != next); vassert(previous != next); // added after rust vassert(validVec(current)); vassert(validVec(previous)); vassert(validVec(next)); vec2 fromPrevious = glm::normalize(current - previous); vec2 fromNext = glm::normalize(current - next); vec2 perpendicularFromPrevious = vec2(-fromPrevious.y, fromPrevious.x); float dot = glm::dot(perpendicularFromPrevious, previousPointInsideBisector); if (dot == 0) { // Then there was a weird point that spiked outwards, like // 1 // 2 4 3 // 5 vassert(false); // Do we even want to handle that? } vec2 insidePerpendicular = dot > 0 ? perpendicularFromPrevious : -perpendicularFromPrevious; vassert(validVec(insidePerpendicular)); vassert(glm::dot(insidePerpendicular, previousPointInsideBisector) >= 0); vassert(glm::dot(insidePerpendicular, fromPrevious) == 0); // we now have a vector that's perpendicular to the vector coming from // the previous point. float posDot = std::abs(glm::dot(insidePerpendicular, fromNext)); if (posDot < 0.0001) { // then currentPoint is somewhere on a line between previousPoint and nextPoint if (!allowColinears) { vassert(false); } return insidePerpendicular; } else { vec2 bisector = glm::normalize(glm::normalize(current - previous) + glm::normalize(current - next)); vassert(validVec(bisector)); // The bisector on the inside has to have a positive dot product with the inside perpendicular. if (glm::dot(bisector, insidePerpendicular) > 0) { return bisector; } else { return -bisector; } } } void fillInsideBisectors(GraphRef graph) { NodeRef nodeLeastY; for (ContourRef contour : *graph) { NodeRef nodeLeastY; for (NodeRef node : *contour) { if (!nodeLeastY || node->point.y < nodeLeastY->point.y) { nodeLeastY = node; } } contour->forInOrder(nodeLeastY, [nodeLeastY](NodeRef previous, NodeRef current, NodeRef next) { vassert(!veeq(current->point, previous->point)); vassert(!veeq(current->point, next->point)); vec2 bisector = glm::normalize(glm::normalize(current->point - previous->point) + glm::normalize(current->point - next->point)); if (current == nodeLeastY) { current->insideBisector = bisector.y > 0 ? bisector : -bisector; } else { vec2 previousPointInsideBisector = previous->insideBisector; current->insideBisector = getInsideBisector(previousPointInsideBisector, previous->point, current->point, next->point); } previous = current; current = next; }); } } PointType getPointType(vec2 point, float interiorAngle, vec2 neighborA, vec2 neighborB) { vassert(validFloat(interiorAngle)); if (pointLessY(neighborA, point) && pointLessY(neighborB, point)) { if (interiorAngle < M_PI) { return PointType::END; } else { return PointType::MERGE; } } else if (pointLessY(point, neighborA) && pointLessY(point, neighborB)) { if (interiorAngle < M_PI) { return PointType::START; } else { return PointType::SPLIT; } } else { return PointType::REGULAR; } } void fillPointTypes(GraphRef graph) { for (ContourRef contour : *graph) { contour->forInOrder([](NodeRef previous, NodeRef current, NodeRef next) { vec2 pointToNext = glm::normalize(next->point - current->point); float dot = glm::dot(pointToNext, current->insideBisector); vassert(validFloat(dot)); float interiorAngle = acos(dot) * 2.0; vassert(validFloat(interiorAngle)); current->pointType = getPointType(current->point, interiorAngle, previous->point, next->point); }); } } float getXOnSegment(float y, vec2 start, vec2 end) { vassert(end.y != start.y); if (end.y < start.y) { return getXOnSegment(y, end, start); } else { vassert(start.y < end.y); vassert(start.y <= y); vassert(y <= end.y); float ratio = (y - start.y) / (end.y - start.y); return start.x + (end.x - start.x) * ratio; } } bool pointInContour(vec2 point, ContourRef contour) { int intersections = 0; contour->forInOrder([point, &intersections](NodeRef previous, NodeRef current, NodeRef next) { if (current->point.y == next->point.y) { // Horizontal line, do nothing } else { if (current->point.y <= point.y && point.y < next->point.y) { vassert(current->point.y != next->point.y); if (point.x < getXOnSegment(point.y, current->point, next->point)) { intersections++; } } if (next->point.y <= point.y && point.y < current->point.y) { vassert(current->point.y != next->point.y); if (point.x < getXOnSegment(point.y, current->point, next->point)) { intersections++; } } } }); return intersections % 2 == 1; } void flipInnerPolygonInsideBisectors(GraphRef graph) { vector<ContourRef> contours; for (ContourRef contour : *graph) { contours.push_back(contour); } for (int i = 0; i < contours.size(); i++) { ContourRef thisContour = contours[i]; vec2 thisContourPoint = (*thisContour->begin())->point; int numContainingContours = 0; for (int j = 0; j < contours.size(); j++) { ContourRef thatContour = contours[j]; if (i != j) { if (pointInContour(thisContourPoint, thatContour)) { numContainingContours++; } } } if (numContainingContours % 2 == 1) { for (NodeRef node : *thisContour) { node->insideBisector = -node->insideBisector; switch (node->pointType) { case PointType::REGULAR: break; case PointType::START: node->pointType = PointType::SPLIT; break; case PointType::SPLIT: node->pointType = PointType::START; break; case PointType::END: node->pointType = PointType::MERGE; break; case PointType::MERGE: node->pointType = PointType::END; break; } } } } } void fillOriginalInsideBisectors(GraphRef graph) { for (ContourRef contour : *graph) { contour->forInOrder([&](NodeRef previous, NodeRef current, NodeRef next) { current->originalInsideBisector = current->insideBisector; }); } } void addLines(shared_ptr<SVG> svg, GraphRef graph) { for (ContourRef contour : *graph) { contour->forInOrder([&](NodeRef previous, NodeRef current, NodeRef next) { svg->addLine(current->point, next->point); }); } } void addInsideBisectors(shared_ptr<SVG> svg, GraphRef graph) { for (ContourRef contour : *graph) { for (NodeRef node : *contour) { svg->addLine(node->point, node->point + node->insideBisector); } } } void addOriginalInsideBisectors(shared_ptr<SVG> svg, GraphRef graph) { for (ContourRef contour : *graph) { for (NodeRef node : *contour) { svg->addLine(node->point, node->point + node->originalInsideBisector, "gray"); } } } void addPointTypes(shared_ptr<SVG> svg, GraphRef graph) { for (ContourRef contour : *graph) { for (NodeRef node : *contour) { svg->addPoint(node->point, 0.3, "black"); std::string color; switch (node->pointType) { case PointType::REGULAR: color = "black"; break; case PointType::MERGE: color = "rgb(255, 0, 0)"; break; case PointType::SPLIT: color = "rgb(255, 0, 255)"; break; case PointType::START: color = "rgb(0, 255, 255"; break; case PointType::END: color = "rgb(255, 255, 0)"; break; } svg->addPoint(node->point + node->insideBisector, 0.3, color); } } } void addContourLabels(shared_ptr<SVG> svg, GraphRef graph) { int contourIndex = 0; for (ContourRef contour : *graph) { for (NodeRef node : *contour) { svg->addText(node->point + node->insideBisector, concat(contourIndex, ":", node->point.x, ",", node->point.y), -20); } contourIndex++; } } bool nodeLessY(NodeRef a, NodeRef b) { // to fix the yen, change this to nodesLessY, see rust if (pointLessY(a->point, b->point)) return true; if (pointLessY(b->point, a->point)) return false; if (pointLessY(a->insideBisector, b->insideBisector)) return true; if (pointLessY(b->insideBisector, a->insideBisector)) return false; // exactly equal?! vfail(); } struct NodeLessY { bool operator()(NodeRef a, NodeRef b) const { return nodeLessY(a, b); } }; struct PairHasher { typedef pair<NodeRef, NodeRef> argument_type; typedef std::size_t result_type; result_type operator()(const argument_type & p) const { return (std::size_t)p.first.get() * 13 + (std::size_t)p.second.get() * 7; } }; struct PairEqual { bool operator()(const pair<NodeRef, NodeRef> & a, const pair<NodeRef, NodeRef> & b) { return a.first.get() == b.first.get() && a.second.get() == b.second.get(); } }; float pointToLeft(vec2 from, unordered_set<pair<NodeRef, NodeRef>, PairHasher, PairEqual> liveEdges) { float nearestLeftX = from.x; for (pair<NodeRef, NodeRef> liveEdge : liveEdges) { vec2 begin = liveEdge.first->point; vec2 end = liveEdge.second->point; if (begin.y == end.y) { // skip. anything to the left is below me, according to lessY ordering // let x = begin.x; // if x < from.x && (nearestLeftX == from.x || x > nearestLeftX) { // nearestLeftX = x; // } // let x = end.x; // if x < from.x && (nearestLeftX == from.x || x > nearestLeftX) { // nearestLeftX = x; // } } else { float x = getXOnSegment(from.y, begin, end); if (x < from.x && (nearestLeftX == from.x || x > nearestLeftX)) { nearestLeftX = x; } } } return nearestLeftX; } float pointToRight(vec2 from, unordered_set<pair<NodeRef, NodeRef>, PairHasher, PairEqual> liveEdges) { float nearestRightX = from.x; for (pair<NodeRef, NodeRef> liveEdge : liveEdges) { vec2 begin = liveEdge.first->point; vec2 end = liveEdge.second->point; if (begin.y == end.y) { // skip. anything to the right is above me, according to lessY ordering // let x = begin.x; // if x > from.x && (nearestRightX == from.x || x < nearestRightX) { // nearestRightX = x; // } // let x = end.x; // if x > from.x && (nearestRightX == from.x || x < nearestRightX) { // nearestRightX = x; // } } else { float x = getXOnSegment(from.y, begin, end); if (x > from.x && (nearestRightX == from.x || x < nearestRightX)) { nearestRightX = x; } } } return nearestRightX; } NodeRef findHighestBelow(vec2 point, float leftX, float rightX, set<NodeRef, NodeLessY>::iterator nodeYOrderedIter, set<NodeRef, NodeLessY>::iterator limit) { vassert(nodeYOrderedIter != limit); nodeYOrderedIter--; while (true) { NodeRef currentNode = *nodeYOrderedIter; if (currentNode->point != point) { if (currentNode->point.x == leftX || currentNode->point.x == rightX) { vec2 currentTowardPoint = glm::normalize(currentNode->point - point); // If it's facing towards me if (glm::dot(currentNode->insideBisector, currentTowardPoint) < 0) { return currentNode; } // TODO: what happens if multiple are facing towards me? dont we want the one // that's most pointed towards me? } if (currentNode->point.x > leftX && currentNode->point.x < rightX) { return currentNode; } } vassert(nodeYOrderedIter != limit); nodeYOrderedIter--; } } NodeRef findLowestAbove(vec2 point, float leftX, float rightX, set<NodeRef, NodeLessY>::iterator nodeYOrderedIter, set<NodeRef, NodeLessY>::iterator limit) { vassert(nodeYOrderedIter != limit); nodeYOrderedIter++; vassert(nodeYOrderedIter != limit); while (true) { NodeRef currentNode = *nodeYOrderedIter; if (currentNode->point != point) { if (currentNode->point.x == leftX || currentNode->point.x == rightX) { vec2 currentTowardPoint = glm::normalize(currentNode->point - point); // If it's facing towards me if (glm::dot(currentNode->insideBisector, currentTowardPoint) < 0) { return currentNode; } // TODO: what happens if multiple are facing towards me? dont we want the one // that's most pointed towards me? } if (currentNode->point.x > leftX && currentNode->point.x < rightX) { return currentNode; } } nodeYOrderedIter++; vassert(nodeYOrderedIter != limit, point, " ", leftX, " ", rightX); } } pair<NodeRef, NodeRef> getNewEdge(GraphRef graph) { set<NodeRef, NodeLessY> nodesYRanked; for (ContourRef contour : *graph) { for (NodeRef node : *contour) { nodesYRanked.insert(node); } } // Lower of the two is first unordered_set<pair<NodeRef, NodeRef>, PairHasher, PairEqual> liveEdges; set<NodeRef, NodeLessY>::iterator nodeYOrderedIter = nodesYRanked.begin(); while (nodeYOrderedIter != nodesYRanked.end()) { NodeRef node = *nodeYOrderedIter; for (NodeRef neighbor : node->neighbors) { if (pointLessY(neighbor->point, node->point)) { bool removed = liveEdges.erase(make_pair(neighbor, node)); vassert(removed); } } for (NodeRef neighbor : node->neighbors) { if (pointLessY(node->point, neighbor->point)) { bool added = liveEdges.insert(make_pair(node, neighbor)).second; vassert(added); } } if (node->pointType == PointType::SPLIT) { float leftX = pointToLeft(node->point, liveEdges); float rightX = pointToRight(node->point, liveEdges); NodeRef newEdgemate = findHighestBelow(node->point, leftX, rightX, nodeYOrderedIter, nodesYRanked.begin()); return make_pair(node, newEdgemate); } if (node->pointType == PointType::MERGE) { float leftX = pointToLeft(node->point, liveEdges); float rightX = pointToRight(node->point, liveEdges); NodeRef newEdgemate = findLowestAbove(node->point, leftX, rightX, nodeYOrderedIter, nodesYRanked.end()); return make_pair(node, newEdgemate); } nodeYOrderedIter++; } return pair<NodeRef, NodeRef>(NodeRef(), NodeRef()); } NodeRef disconnect(NodeRef original) { NodeRef neighbor0 = *original->neighbors.begin(); NodeRef neighbor1 = *++original->neighbors.begin(); int erased0 = neighbor0->neighbors.erase(original); vassert(erased0); int erased1 = neighbor1->neighbors.erase(original); vassert(erased1); original->neighbors.clear(); original->pointType = PointType::REGULAR; // original will get the 0th neighbor, new will get the 1th neighbor owning_ptr<ImprovedNode> ownedClone(new ImprovedNode { original->point, original->insideCurve, std::set<NodeRef>(), PointType::REGULAR, original->insideBisector, original->originalInsideBisector, original->contour }); NodeRef clone = ownedClone; original->contour->insert(std::move(ownedClone)); // Connect original to neighbor 0 bool added1 = original->neighbors.insert(neighbor0).second; vassert(added1); bool added2 = neighbor0->neighbors.insert(original).second; vassert(added2); // Don't connect original to clone // Connect clone to neighbor 1 bool added3 = clone->neighbors.insert(neighbor1).second; vassert(added3); bool added4 = neighbor1->neighbors.insert(clone).second; vassert(added4); vassert(neighbor0->neighbors.size() == 2); vassert(original->neighbors.size() == 1); vassert(clone->neighbors.size() == 1); vassert(neighbor1->neighbors.size() == 2); return clone; } bool colinear(NodeRef node) { NodeRef neighbor0 = *node->neighbors.begin(); NodeRef neighbor1 = *++node->neighbors.begin(); vec2 towardNeighbor0 = glm::normalize(neighbor0->point - node->point); vec2 towardNeighbor1 = glm::normalize(neighbor1->point - node->point); vec2 perpendicular(-towardNeighbor0.y, towardNeighbor0.x); return std::abs(glm::dot(towardNeighbor1, perpendicular)) < 0.0001; } owning_ptr<ImprovedNode> removeNode(NodeRef node) { NodeRef neighbor0 = *node->neighbors.begin(); NodeRef neighbor1 = *++node->neighbors.begin(); int erased0 = neighbor0->neighbors.erase(node); vassert(erased0); int erased1 = neighbor1->neighbors.erase(node); vassert(erased1); node->neighbors.clear(); neighbor0->neighbors.insert(neighbor1); neighbor1->neighbors.insert(neighbor0); owning_ptr<ImprovedNode> own = node->contour->remove(node); node = nullptr; return std::move(own); } void classifyPoint(NodeRef node) { NodeRef neighbor0 = *node->neighbors.begin(); NodeRef neighbor1 = *++node->neighbors.begin(); vec2 pointToNext = glm::normalize(neighbor0->point - node->point); float dot = glm::dot(pointToNext, node->insideBisector); vassert(validFloat(dot)); float interiorAngle = acos(dot) * 2.0; vassert(validFloat(interiorAngle)); node->pointType = getPointType(node->point, interiorAngle, neighbor0->point, neighbor1->point); } std::vector<owning_ptr<ImprovedNode>> slice(GraphRef graph, NodeRef originalA, NodeRef originalB) { bool joiningContours = (originalA->contour != originalB->contour); if (joiningContours) { // Then we're slicing two contours together. // Take originalB's contour and combine it into originalA's. std::list<NodeRef> nodesToMove; originalB->contour->forInOrder([&nodesToMove](NodeRef previous, NodeRef current, NodeRef next) { nodesToMove.push_back(current); }); ContourRef oldContour = originalB->contour; for (NodeRef node : nodesToMove) { vassert(node->contour == oldContour); owning_ptr<ImprovedNode> ownedNode = node->contour->remove(node); node->contour = originalA->contour; node->contour->insert(std::move(ownedNode)); } owning_ptr<Contour> own = graph->remove(oldContour); oldContour = nullptr; own->clear(); } vec2 aPoint = originalA->point; NodeRef aNeighbor0 = *originalA->neighbors.begin(); NodeRef aNeighbor1 = *++originalA->neighbors.begin(); vec2 bPoint = originalB->point; NodeRef bNeighbor0 = *originalB->neighbors.begin(); NodeRef bNeighbor1 = *++originalB->neighbors.begin(); NodeRef cloneA = disconnect(originalA); NodeRef cloneB = disconnect(originalB); originalA->insideBisector = getInsideBisector( aNeighbor0->insideBisector, aNeighbor0->point, aPoint, bPoint, true); cloneA->insideBisector = getInsideBisector( aNeighbor1->insideBisector, aNeighbor1->point, aPoint, bPoint, true); originalB->insideBisector = getInsideBisector( bNeighbor0->insideBisector, bNeighbor0->point, bPoint, aPoint, true); cloneB->insideBisector = getInsideBisector( bNeighbor1->insideBisector, bNeighbor1->point, bPoint, aPoint, true); vec2 aToB = bPoint - aPoint; vec2 newEdgePerpendicular = glm::normalize(vec2(-aToB.y, aToB.x)); bool aOriginalOnPositiveSideOfNewEdge = glm::dot(originalA->insideBisector, newEdgePerpendicular) > 0.0; bool aCloneOnPositiveSideOfNewEdge = glm::dot(cloneA->insideBisector, newEdgePerpendicular) > 0.0; vassert(aOriginalOnPositiveSideOfNewEdge != aCloneOnPositiveSideOfNewEdge); bool bOriginalOnPositiveSideOfNewEdge = glm::dot(originalB->insideBisector, newEdgePerpendicular) > 0.0; bool bCloneOnPositiveSideOfNewEdge = glm::dot(cloneB->insideBisector, newEdgePerpendicular) > 0.0; vassert(bOriginalOnPositiveSideOfNewEdge != bCloneOnPositiveSideOfNewEdge); if (aOriginalOnPositiveSideOfNewEdge == bOriginalOnPositiveSideOfNewEdge) { // aOriginal and bOriginal are on the same side of the new edge, connect them. bool added1 = originalA->neighbors.insert(originalB).second; vassert(added1); bool added2 = originalB->neighbors.insert(originalA).second; vassert(added2); bool added3 = cloneA->neighbors.insert(cloneB).second; vassert(added3); bool added4 = cloneB->neighbors.insert(cloneA).second; vassert(added4); } else { vassert(aOriginalOnPositiveSideOfNewEdge == bCloneOnPositiveSideOfNewEdge); vassert(bOriginalOnPositiveSideOfNewEdge == aCloneOnPositiveSideOfNewEdge); bool added1 = originalA->neighbors.insert(cloneB).second; vassert(added1); bool added2 = cloneB->neighbors.insert(originalA).second; vassert(added2); bool added3 = originalB->neighbors.insert(cloneA).second; vassert(added3); bool added4 = cloneA->neighbors.insert(originalB).second; vassert(added4); } if (!joiningContours) { // Then we're slicing one contour into two // Pick a random node, and move it and all those connected to a new graph // Well, instead of random, we just pick originalA. std::list<NodeRef> nodesToSplitOff; originalA->contour->forInOrder([&nodesToSplitOff](NodeRef previous, NodeRef current, NodeRef next) { nodesToSplitOff.push_back(current); }); owning_ptr<Contour> newContour(new Contour()); for (NodeRef node : nodesToSplitOff) { owning_ptr<ImprovedNode> ownedNode = node->contour->remove(node); node->contour = newContour; node->contour->insert(std::move(ownedNode)); } graph->insert(std::move(newContour)); } set<ContourRef> involvedContours; involvedContours.insert(originalA->contour); involvedContours.insert(originalB->contour); involvedContours.insert(cloneA->contour); involvedContours.insert(cloneB->contour); if (joiningContours) { vassert(involvedContours.size() == 1); } else { vassert(involvedContours.size() == 2); } vassert(aNeighbor0->neighbors.size() == 2); vassert(aNeighbor1->neighbors.size() == 2); vassert(bNeighbor0->neighbors.size() == 2); vassert(bNeighbor1->neighbors.size() == 2); vassert(originalA->neighbors.size() == 2); vassert(originalB->neighbors.size() == 2); vassert(cloneA->neighbors.size() == 2); vassert(cloneB->neighbors.size() == 2); classifyPoint(originalA); classifyPoint(originalB); classifyPoint(cloneA); classifyPoint(cloneB); std::vector<owning_ptr<ImprovedNode>> doomedNodes; if (colinear(originalA)) { doomedNodes.emplace_back(removeNode(originalA)); } if (colinear(originalB)) { doomedNodes.emplace_back(removeNode(originalB)); } if (colinear(cloneA)) { doomedNodes.emplace_back(removeNode(cloneA)); } if (colinear(cloneB)) { doomedNodes.emplace_back(removeNode(cloneB)); } return std::move(doomedNodes); } void prepareContours(shared_ptr<SVGLogger> svgLogger, GraphRef graph) { if (graph->empty()) { return; } for (auto contour : *graph) { contour->forInOrder([](NodeRef previous, NodeRef current, NodeRef next) { vassert(!veeq(current->point, previous->point)); vassert(!veeq(current->point, next->point)); }); } fillInsideBisectors(graph); { auto svg = svgLogger->makeSVG(); addLines(svg, graph); addInsideBisectors(svg, graph); svgLogger->log(svg, "bisectors"); } fillPointTypes(graph); { auto svg = svgLogger->makeSVG(); addLines(svg, graph); addInsideBisectors(svg, graph); addPointTypes(svg, graph); svgLogger->log(svg, "pointtypesunadjusted"); } flipInnerPolygonInsideBisectors(graph); fillOriginalInsideBisectors(graph); { auto svg = svgLogger->makeSVG(); addLines(svg, graph); addInsideBisectors(svg, graph); addPointTypes(svg, graph); svgLogger->log(svg, "pointtypes"); } } void monotonifyContours(shared_ptr<SVGLogger> svgLogger, GraphRef graph) { if (graph->empty()) { return; } while (true) { pair<NodeRef, NodeRef> newEdge = getNewEdge(graph); if (newEdge.first) { std::vector<owning_ptr<ImprovedNode>> doomedNodes = slice(graph, newEdge.first, newEdge.second); newEdge.first = nullptr; newEdge.second = nullptr; doomedNodes.clear(); for (ContourRef contour : *graph) { contour->forInOrder([](NodeRef prev, NodeRef current, NodeRef next) { }); } { auto svg = svgLogger->makeSVG(); addLines(svg, graph); addInsideBisectors(svg, graph); addPointTypes(svg, graph); addContourLabels(svg, graph); svgLogger->log(svg, "afterslice"); } } else { break; } } { auto svg = svgLogger->makeSVG(); addLines(svg, graph); addOriginalInsideBisectors(svg, graph); svgLogger->log(svg, "originsidebisectors"); } } void updateInsideBisector(NodeRef node, NodeRef neighborWithGoodInsideBisector) { NodeRef otherNeighbor = node->getOtherNeighbor(neighborWithGoodInsideBisector); node->insideBisector = getInsideBisector( neighborWithGoodInsideBisector->insideBisector, neighborWithGoodInsideBisector->point, node->point, otherNeighbor->point, true); } owning_ptr<Contour> separate(NodeRef node) { NodeRef neighborA = *node->neighbors.begin(); NodeRef neighborB = *++node->neighbors.begin(); NodeRef neighborAOtherNeighbor = neighborA->getOtherNeighbor(node); NodeRef neighborBOtherNeighbor = neighborB->getOtherNeighbor(node); node->neighbors.clear(); bool removed1 = neighborA->neighbors.erase(node); vassert(removed1); bool removed2 = neighborB->neighbors.erase(node); vassert(removed2); bool added1 = neighborA->neighbors.insert(neighborB).second; vassert(added1); bool added2 = neighborB->neighbors.insert(neighborA).second; vassert(added2); updateInsideBisector(neighborA, neighborAOtherNeighbor); updateInsideBisector(neighborB, neighborBOtherNeighbor); owning_ptr<Contour> newContour(new Contour()); owning_ptr<ImprovedNode> ownedNode = node->contour->remove(node); ownedNode->contour = newContour; newContour->insert(std::move(ownedNode)); owning_ptr<ImprovedNode> neighborAClone(new ImprovedNode { neighborA->point, neighborA->insideCurve, std::set<NodeRef>(), PointType::REGULAR, vec2(0, 0), neighborA->originalInsideBisector, newContour }); owning_ptr<ImprovedNode> neighborBClone(new ImprovedNode { neighborB->point, neighborB->insideCurve, std::set<NodeRef>(), PointType::REGULAR, vec2(0, 0), neighborB->originalInsideBisector, newContour }); node->neighbors.insert(neighborAClone); node->neighbors.insert(neighborBClone); neighborAClone->neighbors.insert(node); neighborAClone->neighbors.insert(neighborBClone); neighborBClone->neighbors.insert(node); neighborBClone->neighbors.insert(neighborAClone); updateInsideBisector(neighborAClone, node); updateInsideBisector(neighborBClone, node); newContour->insert(std::move(neighborAClone)); newContour->insert(std::move(neighborBClone)); return std::move(newContour); } }
true
8c2c9ab30184fe842972be2cebb861183c4bf6a7
C++
SergioQuijanoRey/smallPrograms
/C++/Game of Life/Grid.cpp
UTF-8
2,279
3.265625
3
[]
no_license
#include "Grid.h" #include "Functions.h" //Contains some useful funtions //CONSTRUCTOR METHODS Grid::Grid(int _cols, int _rows){ cols = _cols; rows = _rows; population = 0; generation = 0; vector<int> aux(_cols, 0); vector<vector<int> > aux2(_rows, aux); data = aux2; } //MODIFIER'S METHODS void Grid::startGame(const vector<vector<int> > & startingPoints){ for(int i = 0; i < startingPoints.size(); i++){ int xCord = startingPoints[i][0]; int yCord = startingPoints[i][1]; data[xCord][yCord] = 1; } generation = 1; population = startingPoints.size(); } void Grid::nextGen(){ int aliveCells; //The states of the grid before the evolution must be saved vector<vector<int> > prevGrid = data; for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ aliveCells = countCells(i, j, prevGrid); if(prevGrid[j][i] == 0 && aliveCells == 3){ //This cell borns data[j][i] = 1; }else if((prevGrid[j][i] == 1) && (aliveCells == 2 || aliveCells == 3)){ //This cell remains alive data[j][i] = 1; }else{ //This cell dies data[j][i] = 0; } } } generation++; population = countPopulation(); } //OBSERVER METHODS void Grid::display() const{ clearScreen(); cout << "Population: " << population << endl; cout << "Generation: " << generation << endl; this->show(); } void Grid::show() const{ for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ if(data[i][j] == 0) cout << " . "; else cout << " o "; } cout << endl; } } int Grid::countCells(int _x, int _y, vector<vector<int> > prevGrid) const{ int liveCells = 0; for(int i = -1; i <= 1; i++){ for(int j = -1; j <= 1; j++){ if(_x + i < cols && _x + i >= 0 && _y + j < rows && _y + j >= 0){ int xCord = _x + i; int yCord = _y + j; liveCells += prevGrid[yCord][xCord]; } } } //If the central cell is alive, it must not be counted liveCells = liveCells - prevGrid[_y][_x]; return liveCells; } int Grid::countPopulation() const{ int total = 0; for(int i = 0; i < rows; i++){ for(int j = 0; j < cols; j++){ if(data[i][j] == 1){ total++; } } } return total; } //GET METHODS int Grid::getDelay()const{ return delayTime; } int Grid::getPopulation() const{ return population; }
true
aaa40c96164281e27e48ce4b0a9da7a578391819
C++
kliment-olechnovic/voronota
/src/scripting/operators/set_tag_of_contacts.h
UTF-8
1,683
2.671875
3
[ "MIT" ]
permissive
#ifndef SCRIPTING_OPERATORS_SET_TAG_OF_CONTACTS_H_ #define SCRIPTING_OPERATORS_SET_TAG_OF_CONTACTS_H_ #include "../operators_common.h" namespace voronota { namespace scripting { namespace operators { class SetTagOfContacts : public OperatorBase<SetTagOfContacts> { public: struct Result : public OperatorResultBase<Result> { SummaryOfContacts contacts_summary; void store(HeterogeneousStorage& heterostorage) const { VariantSerialization::write(contacts_summary, heterostorage.variant_object.object("contacts_summary")); } }; SelectionManager::Query parameters_for_selecting; std::string tag; SetTagOfContacts() { } void initialize(CommandInput& input) { parameters_for_selecting=OperatorsUtilities::read_generic_selecting_query(input); tag=input.get_value_or_first_unused_unnamed_value("tag"); } void document(CommandDocumentation& doc) const { OperatorsUtilities::document_read_generic_selecting_query(doc); doc.set_option_decription(CDOD("tag", CDOD::DATATYPE_STRING, "tag name")); } Result run(DataManager& data_manager) const { data_manager.assert_contacts_availability(); assert_tag_input(tag, false); std::set<std::size_t> ids=data_manager.selection_manager().select_contacts(parameters_for_selecting); if(ids.empty()) { throw std::runtime_error(std::string("No contacts selected.")); } for(std::set<std::size_t>::const_iterator it=ids.begin();it!=ids.end();++it) { data_manager.contact_tags_mutable(*it).insert(tag); } Result result; result.contacts_summary=SummaryOfContacts(data_manager.contacts(), ids); return result; } }; } } } #endif /* SCRIPTING_OPERATORS_SET_TAG_OF_CONTACTS_H_ */
true
fefeff05ae1f8eff21a7d05a51b50de4f43fe291
C++
faaizhashmi/DataStructuresAndAlgorithms-CPP
/tree/tree link list.cpp
UTF-8
1,991
3.640625
4
[]
no_license
#include<iostream> using namespace std; struct node{ int value; node *l; node *r; }; class tree{ node *root; void initialize(){ root = NULL; } void insertroot(int r){ if (root != NULL){ cout << "Root exists" << endl; return; } root = new node(); root->value = r; root->l = NULL; root->r = NULL; } void preorder(node *n){ if (n != NULL){ cout << n->value << endl; return; } if (n->l != NULL){ preorder(n->l); } if (n->r != NULL){ preorder(n->r); } } void deleteallnodes(node *n){ _delete (n->l); _delete(n->r); n->l = NULL; n->r = NULL; } void _delete(node *n){ if (n == NULL){ return; } _delete(n->l); _delete(n->r); n->l = NULL; n->r = NULL; delete n; } node *finddata(node *n, int child){ node *left; node *right; if (n != NULL){ if (n->l != NULL){ finddata(n->l, child); } if (n->r = NULL){ finddata(n->r, child); } if (n->value==child){ return n; } else{ return; } } else{ cout << "Empty Input" << endl; } } bool isUnique(node *n, int child){ bool left = false; bool right = false; if (n != NULL){ if (n->l != NULL){ left = isUnique(n->l,child); } if (n->r = NULL){ right = isUnique(n->r, child); } if (n->value == child){ return true; } else if (right || left){ return true; } else{ return false; } } else{ cout << "Empty Input" << endl; } } void insertleft(int data, int child){ if (isUnique(root,child)){ cout << "Child Exists" << endl; return; } else{ node *par = finddata(root, child); if (par == NULL){ cout << "Data doesnt exists" << endl; } if (par->l != NULL){ cout << "left exists" << endl; return; par->l = new node(); par->l->r = NULL; par->l->l = NULL; par->l->value = child; } } } };
true
d6389ea50138c1c6e1702bb8edc6a2d3e5e5e150
C++
alex8092/Sig
/include/signal.hpp
UTF-8
2,308
3.046875
3
[ "MIT" ]
permissive
#ifndef SIG_SIGNAL_HPP # define SIG_SIGNAL_HPP # include <vector> # include <functional> # include <map> using namespace std::placeholders; namespace sig { template <int N> struct _my_placeholder {}; } namespace std { template<int N> struct is_placeholder<sig::_my_placeholder<N>> : public integral_constant<int, N> {}; } namespace sig { namespace _priv { template <class U, class V, class W, int Current> struct _bind { template <typename ...Args> static inline void Do(U *vect, V func, W *object, Args&&... params) noexcept { sig::_priv::_bind<U, V, W, Current - 1>::Do(vect, func, object, _my_placeholder<Current>{}, params...); } }; template <class U, class V, class W> struct _bind<U, V, W, 0> { template <typename ...Args> static inline void Do(U *vect, V func, W *object, Args&&... params) noexcept { (*vect)[(void *)object] = std::bind(func, object, params...); } }; } template <typename ... Params> class Signal { private: Signal(Signal&) = delete; Signal(Signal&&) = delete; Signal& operator=(Signal&) = delete; Signal&& operator=(Signal&&) = delete; int _max_connections; int _current_connections = 0; protected: std::map<void *, std::function<void(Params...)>> _binds; typedef typename std::map<void *, std::function<void(Params...)>>::iterator iterator; virtual void onRemoveIterator(iterator) noexcept {}; public: Signal(int max_connections = 0) : _max_connections(max_connections) {}; virtual ~Signal() = default; template <class U, class V> bool connect(U func, V *object) { if (this->_max_connections && this->_current_connections >= this->_max_connections) return (false); sig::_priv::_bind<std::map<void *, std::function<void(Params...)>>, U, V, sizeof...(Params)>::Do(&this->_binds, func, object); ++this->_current_connections; return (true); } template <class V> bool disconnect(V *object) noexcept { auto it = this->_binds.find((void *)object); if (it == this->_binds.end()) return (false); onRemoveIterator(it); this->_binds.erase(it); --this->_current_connections; return (true); } virtual void emit(Params... parameters) noexcept { for (auto it : this->_binds) it.second(parameters...); } }; } #endif
true
844491a67ea1d78856eae66158ad256cfc07ad73
C++
UnholyCreations/programmiersprachen-raytracer
/framework/scene.hpp
UTF-8
2,936
2.625
3
[ "MIT" ]
permissive
#ifndef SCENE_HPP #define SCENE_HPP #include "shape.hpp" #include "box.hpp" #include "sphere.hpp" #include "camera.hpp" #include "material.hpp" #include "light.hpp" #include <map> #include <iostream> #include <ostream> #include <string> #include <memory> #include <vector> struct Scene { std::string file_name; unsigned int x_resolution; unsigned int y_resolution; float dof_focal=0.0f; Camera SceneCamera; std::map<std::string,Material> MaterialMap; std::vector<std::shared_ptr<Shape>> ShapeVector; std::vector<std::shared_ptr<Light>> LightVector; Color SceneAmbience{0,0,0}; void Print_Shapes() { for (int i=0;i<ShapeVector.size();i++) //if i dont mess the indices after a month pause its not me... :D { (*ShapeVector[i]).print(std::cout); }; } void Print_Materials() { //for (const auto &p : m) for (auto &i: MaterialMap) { std::cout<<i.second; } } void Print_Camera() { SceneCamera.print(); } void Print_Focal() { std::cout<<"DOF focal:"<<dof_focal<<"\n"; } void Print_Lights() { for (int i=0;i<LightVector.size();i++) //if i dont mess the indices after a month pause its not me... :D { (*LightVector[i]).print(); }; } void Print_Ambience() { std::cout<<"col:"<<SceneAmbience.r<<" "<<SceneAmbience.g<<" "<<SceneAmbience.b<<"\n"; } void Print_max_min() { /* for (int i=0;i<ShapeVector.size();i++) { std::string name=ShapeVector[i]->get_name(); glm::vec3 print_max= ShapeVector[i]->get_max(); glm::vec3 print_min= ShapeVector[i]->get_min(); / std::cout<<"-----------------------------------\n"; std::cout<<"name: "<<name<<"\n"; std::cout<<"m_max: "<<print_max.x<<" "<<print_max.y<<" "<<print_max.z<<"\n"; std::cout<<"m_min: "<<print_min.x<<" "<<print_min.y<<" "<<print_min.z<<"\n"; std::cout<<"-----------------------------------\n"; } */ glm::vec3 print_max=get_max(); glm::vec3 print_min=get_min(); std::cout<<"Scene max: "<<print_max.x<<" "<<print_max.y<<" "<<print_max.z<<"\n"; std::cout<<"Scene min: "<<print_min.x<<" "<<print_min.y<<" "<<print_min.z<<"\n"; } glm::vec3 get_max() { glm::vec3 max{0.0f,0.0f,0.0f}; glm::vec3 temp; for (int i=ShapeVector.size()-1;i>=0;i--) { temp=ShapeVector[i]->get_max(); if (temp.x>max.x) {max.x=temp.x;}; if (temp.y>max.y) {max.y=temp.y;}; if (temp.z>max.z) {max.z=temp.z;}; } return max; } glm::vec3 get_min() { glm::vec3 min{0.0f,0.0f,0.0f}; glm::vec3 temp; for (int i=ShapeVector.size()-1;i>=0;i--) { temp=ShapeVector[i]->get_min(); if (temp.x<min.x) {min.x=temp.x;}; if (temp.y<min.y) {min.y=temp.y;}; if (temp.z<min.z) {min.z=temp.z;}; } return min; } }; #endif
true
f12713a10fe66a61c7fe034029fdb2aaad6f6236
C++
atlc/WearMyHeartOnMySleeve
/HeartBeatLED.ino
UTF-8
2,970
2.625
3
[]
no_license
#include "LedControlMS.h" /* LED Matrix array pinout: Pin 12 is connected to DataIn Pin 11 is connected to CLK Pin 10 is connected to LOAD 4 MAX72XX devices in array */ LedControl lc=LedControl(12,11,10,4); /* Use heartrate sensor to obtain this value */ // unsigned long delaytime=500; /* Consts for a full 8x8 display of whatever sprite you choose to use make. * * I used: https://xantorohara.github.io/led-matrix-editor/# * to create 8x8 drawings and obtain either the byte array values * OR their hex values since you can store them as unsigned long ints. */ const uint64_t HEART_SPRITE[] = {0x183c7effffffff66}; const int HEART_SPRITE_LEN = sizeof(HEART_SPRITE)/8; const uint64_t HR_CHARS[] {0x00959555f7957500}; const int HR_CHARS_LEN = sizeof(HR_CHARS)/8; const uint64_t HR_NUMBERS[] = { 0x1824242424242418, 0x0808080808080808, 0x3c0404043c20203c, 0x1c2020201c20201c, 0x2020203c24242424, 0x1c2020201c04043c, 0x182424241c040438, 0x101010101010223e, 0x1824242418242418, 0x1824202038242418 }; const int HR_NUMBERS_LEN = sizeof(HR_NUMBERS)/8; //int pulseSensor = A0; //double alpha = 0.75; //int period = 200; //double change = 0.0; void setup() { // pinMode(LED_BUILTIN, OUTPUT); // Serial.begin(9600); // init all devices in a loop int devices=lc.getDeviceCount(); for(int address=0;address<devices;address++) { /*The MAX72XX is in power-saving mode on startup*/ lc.shutdown(address,false); /* Set the brightness to a medium values */ lc.setIntensity(address,1); /* and clear the display */ lc.clearDisplay(address); } } // TODO: Change delays to delaytime variable obtained by sensor void showHeart(uint64_t HEART_SPRITE) { for (int i = 0; i < 8; i++) { byte row = (HEART_SPRITE >> i * 8) & 0xFF; for (int j =0; j < 8; j++) { lc.setLed(0, i, j, bitRead(row, j)); } } delay(200); lc.clearDisplay(0); delay(200); for (int i = 0; i < 8; i++) { byte row = (HEART_SPRITE >> i * 8) & 0xFF; for (int j =0; j < 8; j++) { lc.setLed(0, i, j, bitRead(row, j)); } } delay(750); lc.clearDisplay(0); } void showHRchars(uint64_t HR_CHARS) { for (int i = 0; i < 8; i++) { byte row = (HR_CHARS >> i * 8) & 0xFF; for (int j =0; j < 8; j++) { lc.setLed(3, i, j, bitRead(row, j)); } } } void sampleNums(uint64_t HR_NUMBERS) { for (int i = 0; i < 8; i++) { byte row = (HR_NUMBERS >> i * 8) & 0xFF; for (int j =0; j < 8; j++) { lc.setLed(1, i, j, bitRead(row, j)); } } for (int i = 0; i < 8; i++) { byte row = (HR_NUMBERS >> i * 8) & 0xFF; for (int j =0; j < 8; j++) { lc.setLed(2, i, j, bitRead(row, j)); } } } int i = 0; void loop() { showHRchars(HR_CHARS[i]); if (++i >= HR_CHARS_LEN) { i = 0; } sampleNums(HR_NUMBERS[i]); if (++i >= HR_NUMBERS_LEN) { i = 0; } showHeart(HEART_SPRITE[i]); if (++i >= HEART_SPRITE_LEN) { i = 0; } }
true
a872496ca2c8bee3123bea75e992e81708254333
C++
kimyir111/kimyir
/partc3/Part 3/Chapter 1/part3_ch1_prob9.cpp
UTF-8
475
3.21875
3
[]
no_license
#include <stdio.h> struct node { int data; struct node* left_link; struct node* right_link; }; int main () { struct node n7 = {70, NULL, NULL}; struct node n6 = {60, NULL, NULL}; struct node n5 = {50, NULL, NULL}; struct node n4 = {40, NULL, NULL}; struct node n3 = {30, &n6, &n7}; struct node n2 = {20, &n4, &n5}; struct node n1 = {10, &n2, &n3}; printf("%d %d", n1.left_link->left_link->data, n1.right_link->right_link->data); return 0; }
true
a8c3b62bf4c001dc85599acbc296998f54a21eff
C++
BhuiyanMH/Uva
/10346 peter's Smoke myself.cpp
UTF-8
364
2.6875
3
[]
no_license
//it shows time limit exit #include <stdio.h> int main() { int a,b,eex; long int sum; while(scanf("%d %d", &a, &b)==2){ sum=a+(a/b); eex=(a/b)+a%b; while(1){ eex=eex/b; sum+=eex; if(eex<b) break; eex=eex+eex%b; } printf("%ld\n", sum); } }
true
1da6c724f1b44e48a204b98b97717084398b52ab
C++
jackson-nestelroad/cpp-keyboard-hook
/source/Error.cpp
UTF-8
322
3.375
3
[]
no_license
// Implementation file for Error class #include "Error.h" // Constructor Error::Error(int code, std::string reason) { this->code = code; this->reason = reason; } // << operator overload std::ostream &operator<<(std::ostream &stream, const Error &error) { stream << "ERROR: " << error.reason; return stream; }
true
2f260c773b202fbe535629bf19b2977153e9f37b
C++
moozon/Lcd_Encoder
/Lcd_Encoder.ino
WINDOWS-1251
4,112
2.578125
3
[]
no_license
#include <OneButton.h> #include <Wire.h> #include <LiquidCrystal_I2C.h> #define PIN_A 2 #define PIN_B 4 #define SW 5 #define PULSE_PIN_LEN 5 //8 volatile unsigned long failingTime = 0; volatile bool fl = false; // volatile bool value_b = 0; volatile byte prevA = 0; volatile int Value0 = 0; volatile int Value1 = 1; volatile int Value2 = 2; volatile int Value3 = 3; volatile unsigned long pulseLen = 0; boolean blinkEn = false; boolean editEn = false; uint8_t cursor_pos = 0; //Setup LCD LiquidCrystal_I2C lcd(0x3F, 16, 2); //Setup a new OneButton OneButton oneButton(SW, true); void click() { if (editEn) { if (cursor_pos < 3) { cursor_pos++; } else { cursor_pos = 0; } if (cursor_pos == 0) lcd.setCursor(0, 0); if (cursor_pos == 1) lcd.setCursor(8, 0); if (cursor_pos == 2) lcd.setCursor(0, 1); if (cursor_pos == 3) lcd.setCursor(8, 1); } } void doubleClick() { lcd.clear(); lcd.print("Double Click"); } void duringLongPress() { lcd.clear(); lcd.print("Multiple Long Press"); } void longPressStart() { if (editEn) { editEn = false; blinkEn = false; lcd.noBlink(); } else { editEn = true; blinkEn = true; lcd.home(); lcd.blink(); } } void longPressStop() { lcd.clear(); lcd.print("Long Press Stop"); } void setup() { Serial.begin(9600); pinMode(SW, INPUT_PULLUP); //OneButton oneButton.attachClick(click); oneButton.attachDoubleClick(doubleClick); //oneButton.setDebounceTicks(100000); //oneButton.attachDuringLongPress(duringLongPress); // oneButton.attachLongPressStart(longPressStart); // //oneButton.attachLongPressStop(longPressStop); // //Encoder digitalWrite(PIN_A, HIGH); digitalWrite(PIN_B, HIGH); attachInterrupt(0, handler_a, CHANGE); //LCD lcd.init(); lcd.backlight(); lcd.noAutoscroll(); lcd.print(Value0); lcd.setCursor(8, 0); lcd.print(Value1); lcd.setCursor(0, 1); lcd.print(Value2); lcd.setCursor(8, 1); lcd.print(Value3); } void handler_a() { byte A = digitalRead(PIN_A); if (!fl) { // if (prevA && !A) { // value_b = digitalRead(PIN_B); // , " " failingTime = millis(); // " ", } if (!prevA && A && failingTime) { // " pulseLen = millis() - failingTime; if (pulseLen > PULSE_PIN_LEN) { // - if (value_b) { if (cursor_pos == 0) Value0++; if (cursor_pos == 1) Value1++; if (cursor_pos == 2) Value2++; if (cursor_pos == 3) Value3++; } else { if (cursor_pos == 0) Value0--; if (cursor_pos == 1) Value1--; if (cursor_pos == 2) Value2--; if (cursor_pos == 3) Value3--; } fl = true; // Serial } failingTime = 0; // } } prevA = A; } void loop() { //OneButton oneButton.tick(); if (fl && editEn) { lcd.clear(); lcd.print(Value0); lcd.setCursor(8, 0); lcd.print(Value1); lcd.setCursor(0, 1); lcd.print(Value2); lcd.setCursor(8, 1); lcd.print(Value3); if (cursor_pos == 0) lcd.setCursor(0, 0); if (cursor_pos == 1) lcd.setCursor(8, 0); if (cursor_pos == 2) lcd.setCursor(0, 1); if (cursor_pos == 3) lcd.setCursor(8, 1); fl = false; } }
true
c0143d55462a5aa9beb2d9b24cebb7066331ab2f
C++
chromium/chromium
/components/user_notes/interfaces/user_note_metadata_snapshot.h
UTF-8
2,469
2.640625
3
[ "BSD-3-Clause" ]
permissive
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_ #define COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_ #include <memory> #include <string> #include <unordered_map> #include "base/unguessable_token.h" #include "url/gurl.h" namespace user_notes { class UserNoteMetadata; // In order to have GURL as a key in a hashmap, GURL hashing mechanism is // needed. struct GURLHash { size_t operator()(const GURL& url) const { return std::hash<std::string>()(url.spec()); } }; // A class that encapsulates an // `unordered_map<GURL, unordered_map<ID, UserNoteMetadata>>`. This represents // a snapshot of the note metadata contained in the database for a set of URLs. // The first map is to group metadata by URL, which makes it easy to look up // what notes are attached to that URL. The second map is for quick lookup of a // note's metadata by its ID. Using this class makes code simpler and clearer // than if using the raw type. class UserNoteMetadataSnapshot { public: using IdToMetadataMap = std::unordered_map<base::UnguessableToken, std::unique_ptr<UserNoteMetadata>, base::UnguessableTokenHash>; using UrlToIdToMetadataMap = std::unordered_map<GURL, IdToMetadataMap, GURLHash>; UserNoteMetadataSnapshot(); UserNoteMetadataSnapshot(UserNoteMetadataSnapshot&& other); UserNoteMetadataSnapshot(const UserNoteMetadataSnapshot&) = delete; UserNoteMetadataSnapshot& operator=(const UserNoteMetadataSnapshot&) = delete; ~UserNoteMetadataSnapshot(); // Returns false if there's at least one entry in the snapshot, true // otherwise. bool IsEmpty(); // Adds a metadata entry to this class, based on the URL the note is attached // to and its ID. void AddEntry(const GURL& url, const base::UnguessableToken& id, std::unique_ptr<UserNoteMetadata> metadata); // Returns a raw pointer to the Note ID -> Metadata hash map for the given // URL, or nullptr if the URL does not have any notes associated with it. const IdToMetadataMap* GetMapForUrl(const GURL& url) const; private: UrlToIdToMetadataMap url_map_; }; } // namespace user_notes #endif // COMPONENTS_USER_NOTES_INTERFACES_USER_NOTE_METADATA_SNAPSHOT_H_
true
045b11cc9c56484f5042ecca4604ff52dc5c4762
C++
RyanSwann1/Top-Down-Shooter
/TopDownShooter/TopDownShooter/src/States/StateBase.h
UTF-8
626
2.84375
3
[]
no_license
#pragma once #include <States\StateType.h> #include <SFML\Graphics.hpp> class StateManager; class StateBase { public: StateBase(StateManager& stateManager, StateType stateType) : m_type(stateType), m_stateManager(stateManager) {} virtual ~StateBase() {} StateBase(const StateBase&) = delete; StateBase& operator=(const StateBase&) = delete; StateBase(StateBase&&) = delete; StateBase&& operator=(StateBase&&) = delete; StateType getType() const { return m_type; } virtual void update() = 0; virtual void draw(sf::RenderWindow& window) = 0; private: const StateType m_type; StateManager& m_stateManager; };
true
8cbde5bc0c9974011a54591aa29fe1a026e81020
C++
cltwski/Engine
/Engine/FPS.cpp
UTF-8
336
2.75
3
[]
no_license
#include "FPS.h" FPS::FPS() {} FPS::FPS(const FPS& other) {} FPS::~FPS() {} void FPS::Init() { _fps = 0; _count = 0; _startTime = timeGetTime(); } void FPS::Frame() { _count++; if (timeGetTime() >= (_startTime + 1000)) { _fps = _count; _count = 0; _startTime = timeGetTime(); } } int FPS::GetFps() { return _fps; }
true
308ec5df3eb3a7e5515f80c81435a52dbb5090d4
C++
Sunday361/leetcode
/leetcode_456.h
UTF-8
953
2.96875
3
[]
no_license
// // Created by panrenhua on 3/24/21. // #ifndef LEETCODE_LEETCODE_456_H #define LEETCODE_LEETCODE_456_H #include "allheaders.h" /** 456. 132 模式 * * 用一个数组存储 一个数左边最小的值, 用一个单调栈存储依次递减的数 * 当栈中有比当前元素大的数, 查看是否满足 132原则 * */ class Solution { public: bool find132pattern(vector<int>& nums) { vector<int> lm(nums.size()); int m = INT32_MAX; for (int i = 0; i < nums.size(); i++) { lm[i] = m; m = min(m, nums[i]); } vector<int> s; for (int i = 0; i < nums.size(); i++) { while (!s.empty() && nums[s.back()] <= nums[i]) { s.pop_back(); } if (!s.empty() && lm[s.back()] < nums[i]) { return true; } s.push_back(i); } return false; } }; #endif //LEETCODE_LEETCODE_456_H
true
33941b328b92f0d1f46ae7311e2aab52539074a3
C++
buddyw/project-euler
/cpp/p004.cpp
UTF-8
1,325
2.953125
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; #define MAXSEARCH 999 int get_n(unsigned long int, int); bool check_pal(unsigned long int); int main() { int i_mx,i_my; int i_big; i_big = 0; cout << "checking palendromes as multipls of 3 digit #'s up to"<< MAXSEARCH << endl << endl; cout << endl << 1234321 << check_pal(1234321) << endl; for (i_mx=MAXSEARCH;i_mx>1;i_mx--) for (i_my=MAXSEARCH;i_my>1;i_my--) if (check_pal(i_mx*i_my)) if (i_big < i_mx*i_my) i_big = i_mx*i_my; cout << endl << "Biggest: " << i_big << endl; return 0; } int get_n(unsigned long int i_val, int i_pos) { unsigned long int i_tmp; i_tmp = i_val; i_tmp/=pow10(i_pos); return i_tmp%10; } bool check_pal(unsigned long int i_val) { int i_val_len, i_idx; unsigned long int i_tmp_val; bool b_pflag; //get the length of the number i_tmp_val = i_val; for(i_val_len=1;i_tmp_val>=10;i_tmp_val/=10) i_val_len++; //cout << endl << "len=" << i_val_len << endl; for (i_idx=1;i_idx<=i_val_len/2;i_idx++) { if (get_n(i_val,i_idx-1) != get_n(i_val,i_val_len-i_idx)) { //cout << i_idx << ':' << get_n(i_val,i_idx-1) << "!=" << get_n(i_val,i_val_len-i_idx) << '|'; return false; } //else //cout << get_n(i_val,i_idx-1) << "==" << get_n(i_val,i_val_len-i_idx) << '|'; } return true; }
true
2e7a0ba20559c1b62a9d019fef373df8a32dc845
C++
Delthii/AoC2018
/day6.cpp
UTF-8
2,185
2.734375
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <unordered_set> #include <unordered_map> #include <vector> #include <numeric> #include <functional> #include <algorithm> #include "Helpers.h" #include "Stopwatch.h" using namespace std; void partA6(vector<string> input) { auto co = unordered_map<int,pair<int, int>>(); int i = 0; auto occ = unordered_map<int, int>(); for (auto s : input) { auto ss = splitString(s, ", "); int x = stoi(ss[0]), y = stoi(ss[1]); co[i] = pair<int, int>(x, y); i++; } for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { unordered_map<int, int> distance; for (auto c : co) { int m = abs(c.second.first - i) + abs(c.second.second - j); distance[c.first] = m; } int minc = -1; int mindis = 1000000; unordered_set<int> candidates; for (auto d : distance) { if (d.second < mindis) { mindis = d.second; minc = d.first; candidates.clear(); candidates.insert(minc); } else if (d.second == mindis) { candidates.insert(d.first); } } if (candidates.size() == 1) { occ[*candidates.begin()]++; } } } vector<int> l; for (auto c : occ) { l.push_back(c.second); } sort(l.begin(), l.end()); for (auto e : l) { cout << e << endl; } } void partB6(vector<string> input) { auto co = unordered_map<int, pair<int, int>>(); int i = 0; auto occ = unordered_map<int, int>(); for (auto s : input) { auto ss = splitString(s, ", "); int x = stoi(ss[0]), y = stoi(ss[1]); co[i] = pair<int, int>(x, y); i++; } int sum = 0; for (int i = -4100; i < 4100; i++) { for (int j = -4100; j < 4100; j++) { unordered_map<int, int> distance; int all = 0; for (auto c : co) { int m = abs(c.second.first - i) + abs(c.second.second - j); all += m; } if (all < 10000) sum++; } } cout << sum << endl; } int main6() { string line; ifstream myfile("in.txt"); vector<string> input; if (myfile.is_open()) { while (getline(myfile, line)) { input.push_back(line); } myfile.close(); } else cout << "Unable to open file"; //partA6(input); partB6(input); system("pause"); return 0; }
true
4f25fbd5165a40acec55b13761e82d439ba92f23
C++
sathish1000/workspace
/BigNumberAddition.cpp
UTF-8
877
3.71875
4
[]
no_license
//The code is to add two big numbers that dont fall inside the size of the regular integer types. #include <iostream> #include <vector> #include <string> using namespace std; int main() { int N; int maxSize = 0; cout << "Enter the number of the items to be added" << endl; cin >> N; vector<string> Items(N); for (int i=0; i<N; i++) { cin >> Items[i]; } for (int i=0; i<N; i++) { if (Items[i].size() > maxSize) maxSize = Items[i].size(); } int prev = 0; vector<string> Sum(maxSize+1); for (int i=(maxSize-1); i>=0; i--) { int sum = int(Items[0][i] - '0') + int(Items[1][i] - '0') + prev; prev = 0; if (sum > 9) { prev = 1; sum = sum%10; } Sum[i+1] = std::to_string(sum); } if (prev == 0) Sum[0] = std::to_string(0); else Sum[0] = std::to_string(1); for (int i=0; i<Sum.size(); i++) cout << Sum[i]; }
true
cd6a76ac24c58ddc28f0de147bf78f67f30af8d7
C++
m43/fer-irg
/src/linalg/i_vector.h
UTF-8
5,478
2.953125
3
[]
no_license
// // Created by m43 on 16. 03. 2020.. // #ifndef FER_IRG_I_VECTOR_H #define FER_IRG_I_VECTOR_H #include <vector> #include <stdexcept> #include <boost/serialization/array.hpp> #include <array> #include "i_vector.h" #include "i_matrix.h" namespace linalg { class IMatrix; // TODO Got a circular reference, this is a quick fix. // TODO are interfaces a good way at all of modeling in C++? // Should I maybe have written only the AbstractVector? /** * This class models an abstract class that acts as an interface for vectors. These vectors are n-dimensional * structures that hold double values at indexes 0 - (n-1). * * @author Frano Rajič */ class IVector { public: virtual ~IVector() = default; /** * @param index the index of the value to get * @return the value in vector at index */ virtual double get(int index) = 0; /** * @param index the index of the value to set * @param value the value to set * @return this vector after update */ virtual IVector &set(int index, double value) = 0; /** * @return the number of dimensions of this vector */ virtual int getDimension() = 0; /** * @return a clone of this vector */ virtual std::unique_ptr<IVector> clone() = 0; /** * Get a part of the vector starting from index=0 till newSize-1. If newSize is greater than the number of * dimensions of the current vector, then the rest will be filled with zeros. * * @param dimensions how many dimensions to clone * @return a new vector representing a part of this vector */ virtual std::unique_ptr<IVector> copyPart(int newSize) = 0; /** * Function returns a new instance of an vector with given dimension number. * * @param dimension number of dimensions * @return the newly created vector with specified dimensions */ virtual std::unique_ptr<IVector> newInstance(int dimension) = 0; /** * @param other the vector to add * @return this vector after adding the given vector */ virtual IVector &add(IVector &other) = 0; /** * @param other the vector to add * @return a new vector that is the result of adding the given vector to this vector */ virtual std::unique_ptr<IVector> nAdd(IVector &other) = 0; /** * @param other the vector that will be used to subtract * @return this vector subtracted by the given vector */ virtual IVector &sub(IVector &other) = 0; /** * @param other the vector that will be used to subtract * @return a new vector that si the result of subtracting the given vector from this vector */ virtual std::unique_ptr<IVector> nSub(IVector &other) = 0; /** * @param scalar the scalar value to multiply with * @return this vector multiplied with given scalar value */ virtual IVector &scalarMultiply(double scalar) = 0; /** * @param scalar the scalar value to multiply with * @return a new vector that represents this vector multiplied with given scalar value */ virtual std::unique_ptr<IVector> nScalarMultiply(double scalar) = 0; /** * @return the norm value of this vector */ virtual double norm() = 0; /** * @return this vector normalized */ virtual IVector &normalize() = 0; /** * @return a new vector that is the result of normalization of this vector */ virtual std::unique_ptr<IVector> nNormalize() = 0; /** * @param other the other vector * @return the cosine of the angle between this and the given vector */ virtual double cosine(IVector &other) = 0; /** * @param other the vector to make the scalar (aka dot) product with * @return the scalar product of this vector with the given vector */ virtual double dotProduct(IVector &other) = 0; /** * Return the cross product of this vector with the given vector. This function only determines * the cross product for vectors of dimension=3. * * @param other the vector to make the vector (aka cross) product with * @return the vector product of this vector with the given vector */ virtual std::unique_ptr<IVector> nCrossProduct3D(IVector &other) = 0; /** * Return a new vector for which this vector is the homogeneous coordinate format. The resulting vector will * have (n-1) dimensions if this vector has n dimensions. * @return a new */ virtual std::unique_ptr<IVector> nFromHomogeneous() = 0; // TODO moved to static function of AbstractVector // virtual IMatrix &toRowMatrix(bool liveView) = 0; // virtual IMatrix &toColumnMatrix(bool) = 0; /** * Function that turns the this vector values into an std::vector. Not really an array, but still :P * @return std::vector containing the stored in this vector */ virtual std::vector<double> toArray() = 0; }; } #endif //FER_IRG_I_VECTOR_H
true
c61bc6a3e25b76c43ac486a39b233335f244bfbb
C++
Youlissize/polycube
/src/parsing.h
UTF-8
5,818
2.890625
3
[]
no_license
#ifndef PARSING_H #define PARSING_H #endif // PARSING_H #include <vector> #include <string> #include <iostream> #include <fstream> #include"Mesh.h" namespace MeshIO{ template< class point_t > bool open( const std::string & filename , std::vector< point_t > & vertices , std::vector< int > & tetras ) { std::ifstream myfile; myfile.open(filename.c_str()); if (!myfile.is_open()) { std::cout << filename << " cannot be opened" << std::endl; return false; } std::string dummy_s; unsigned int meshVersion , dataDimension , nVertices , nTriangles , nTetras; myfile >> dummy_s >> meshVersion; myfile >> dummy_s >> dataDimension; if( dataDimension != 3 ) { std::cout << "dataDimension != 3 , " << filename << " is not a tetrahedral mesh file !" << std::endl; myfile.close(); return false; } myfile >> dummy_s >> nVertices; vertices.resize( nVertices ); for( unsigned int v = 0 ; v < nVertices ; ++v ) { double x , y , z , dummy_i; myfile >> x >> y >> z >> dummy_i; vertices[v] = point_t(x,y,z); } myfile >> dummy_s >> nTriangles; for( unsigned int v = 0 ; v < nTriangles ; ++v ) { int x , y , z , dummy_i; myfile >> x >> y >> z >> dummy_i; } myfile >> dummy_s >> nTetras; tetras.resize(4 * nTetras ); for( unsigned int t = 0 ; t < nTetras ; ++t ) { int w , x , y , z , dummy_i; myfile >> w >> x >> y >> z >> dummy_i; tetras[ 4*t ] = w-1; tetras[ 4*t + 1 ] = x-1; tetras[ 4*t + 2 ] = y-1; tetras[ 4*t + 3 ] = z-1; } myfile.close(); return true; } template< class point_t , class int_t > bool openTrisAndTets( const std::string & filename , std::vector< point_t > & vertices , std::vector< Triangle > & tris , std::vector< std::vector< int_t > > & tetras , bool parseBoundaryTrisOnly = true , bool reverseTriangleOrientation = false ) { std::ifstream myfile; myfile.open(filename.c_str()); if (!myfile.is_open()) { std::cout << filename << " cannot be opened" << std::endl; return false; } std::string dummy_s; unsigned int meshVersion , dataDimension , nVertices , nTriangles , nTetras; myfile >> dummy_s >> meshVersion; myfile >> dummy_s >> dataDimension; if( dataDimension != 3 ) { std::cout << "dataDimension != 3 , " << filename << " is not a tetrahedral mesh file !" << std::endl; myfile.close(); return false; } myfile >> dummy_s >> nVertices; vertices.resize( nVertices ); for( unsigned int v = 0 ; v < nVertices ; ++v ) { double x , y , z , dummy_i; myfile >> x >> y >> z >> dummy_i; vertices[v] = point_t(x,y,z); } std::cout << "\t parsed vertices" << std::endl; myfile >> dummy_s >> nTriangles; tris.clear(); if(!parseBoundaryTrisOnly) tris.resize(nTriangles ); for( unsigned int t = 0 ; t < nTriangles ; ++t ) { int x , y , z , dummy_i; if(reverseTriangleOrientation) myfile >> x >> z >> y >> dummy_i; else myfile >> x >> y >> z >> dummy_i; if(!parseBoundaryTrisOnly) { //tris[t].resize(3); tris[t].corners[ 0 ] = x-1; tris[t].corners[ 1 ] = y-1; tris[t].corners[ 2 ] = z-1; } else { if( dummy_i != 0 ) { Triangle newTri; newTri.corners[ 0 ] = x-1; newTri.corners[ 1 ] = y-1; newTri.corners[ 2 ] = z-1; tris.push_back(newTri); } } } std::cout << "\t parsed tris : " << tris.size() << " tris out of " << nTriangles << " in the file" << std::endl; myfile >> dummy_s >> nTetras; tetras.resize(nTetras ); for( unsigned int t = 0 ; t < nTetras ; ++t ) { int w , x , y , z , dummy_i; myfile >> w >> x >> y >> z >> dummy_i; tetras[ t ].resize(4); tetras[ t ][0] = w-1; tetras[ t ][1] = x-1; tetras[ t ][2] = y-1; tetras[ t ][3] = z-1; } std::cout << "\t parsed tets" << std::endl; myfile.close(); return true; } template< class point_t , class int_t > bool openTris( const std::string & filename , std::vector< point_t > & vertices , std::vector< std::vector< int_t > > & tris ) { std::ifstream myfile; myfile.open(filename.c_str()); if (!myfile.is_open()) { std::cout << filename << " cannot be opened" << std::endl; return false; } std::string dummy_s; unsigned int meshVersion , dataDimension , nVertices , nTriangles; myfile >> dummy_s >> meshVersion; myfile >> dummy_s >> dataDimension; if( dataDimension != 3 ) { std::cout << "dataDimension != 3 , " << filename << " is not a tetrahedral mesh file !" << std::endl; myfile.close(); return false; } myfile >> dummy_s >> nVertices; std::cout << "allocate " << nVertices << " vertices" << std::endl; vertices.resize( nVertices ); for( unsigned int v = 0 ; v < nVertices ; ++v ) { double x , y , z , dummy_i; myfile >> x >> y >> z >> dummy_i; vertices[v] = point_t(x,y,z); } myfile >> dummy_s >> nTriangles; std::cout << "allocate " << nTriangles << " tris" << std::endl; tris.resize( nTriangles ); for( unsigned int t = 0 ; t < nTriangles ; ++t ) { tris[t].resize(3); int_t x , y , z , dummy_i; myfile >> x >> y >> z >> dummy_i; tris[ t ][ 0 ] = x-1; tris[ t ][ 1 ] = y-1; tris[ t ][ 2 ] = z-1; } myfile.close(); return true; } }
true
0b87cb259e6a4ec594aa36ae86693646c4918f67
C++
ak566g/Data-Structures-and-Algorithms
/Graph/18_bottom.cpp
UTF-8
3,232
2.984375
3
[]
no_license
//by Ankita Gupta // https://www.spoj.com/problems/BOTTOM/ // Basically the question is if you can visit one vertex to another then there must be a reverse path. // Idea to solve is find all the strongly connected components.. and if there is outgoing edge b/w first scc to second scc then don't include first // scc into the ans. #include<bits/stdc++.h> using namespace std; bool graph[5001][5001]; bool graphT[5001][5001]; bool visited[5001]; void dfs1(int si, int n, stack<int> &st) { visited[si]=true; for(int i=1;i<=n;i++) { if(visited[i]==false && graph[si][i]==1) { dfs1(i, n, st); } } st.push(si); } void dfs2(int si, int n, vector<int> &v) { visited[si]=true; v.push_back(si); for(int i=1;i<=n;i++) { if(visited[i]==false && graphT[si][i]==1) { dfs2(i, n, v); } } } vector<vector<int>> findSCC(int n) { stack<int>st; memset(visited, false, sizeof(visited)); for(int i=1;i<=n;i++) { if(visited[i]==false) { dfs1(i, n, st); } } memset(visited, false, sizeof(visited)); vector<vector<int>> scc; while(!st.empty()) { int start = st.top(); st.pop(); if(visited[start]==false) { vector<int>v; dfs2(start, n, v); scc.push_back(v); } } return scc; } int main() { int v, e; cin>>v; while(v!=0) { cin>>e; memset(graph,0,sizeof(graph)); memset(graphT,0,sizeof(graphT)); for(int i=0;i<e;i++) { int x, y; cin>>x>>y; graph[x][y]=1; graphT[y][x]=1; } vector<vector<int>>scc= findSCC(v); // for(int i=0;i<scc.size();i++) // { // for(int j=0;j<scc[i].size();j++) // { // cout<<scc[i][j]<<" "; // } // cout<<endl; // } unordered_map<int, int>mp; for(int i=0;i<scc.size();i++) { for(int j=0;j<scc[i].size();j++) { mp[scc[i][j]]=i; } } vector<int>ans; for(int i=0;i<scc.size();i++) { bool flag=false; for(int j=0;j<scc[i].size();j++) { int vertex= scc[i][j]; for(int k=1;k<=v;k++) { if(graph[vertex][k]==1 && mp[vertex]!=mp[k]) { flag=true; break; } } if(flag==true) break; } if(flag==false) { for(int k=0;k<scc[i].size();k++) { ans.push_back(scc[i][k]); } } } sort(ans.begin(), ans.end()); for(int i=0;i<ans.size();i++) cout<<ans[i]<<" "; cout<<endl; cin>>v; } return 0; }
true
f50f40ec95bf4a292afb93d4120918d6f92af102
C++
diohabara/competitive_programming
/aoj/dpl3_b.cpp
UTF-8
2,964
3.0625
3
[]
no_license
#include <bits/stdc++.h> #define rep(i, n) for (int i = 0; i < n; i++) #define ll long long #define endl '\n' using namespace std; #define MAX 1400 struct Rectangle { int height; int pos; }; int getLargestRectangle(int size, int buffer[]) { // 行ごとに計算する stack<Rectangle> S; int maxv = 0; buffer[size] = 0; for (int i = 0; i <= size; i++) { Rectangle rect; // まだ拡張される可能性のある長方形 rect.height = buffer[i]; // 長方形の高さ rect.pos = i; // 左端の位置 // Sが空->rectを入れる // Sが空でない->(Sの上の高さ < rectの高さ)->Sにpush // Sが空でない->(Sの上の高さ > rectの高さ)->Sにpush if (S.empty()) { S.push(rect); } else { if (S.top().height < rect.height) { // stackの上にある長方形の方がbufferの長方形の高さよりも低い時 S.push(rect); } else if (S.top().height > rect.height) { int target = i; // targetをiとする // 一番heightが高くなるpreのposをtargetとする while (!S.empty() && S.top().height >= rect.height) { // stackに貯まっていて,Sの上にあるものの高さよりrectの高さが高い Rectangle pre = S.top(); // stackの上のものをpreとする S.pop(); // stackの上のものを取り出す int area = pre.height * (i - pre.pos); // preの高さ * (現在の位置 - preの位置) maxv = max(maxv, area); // maxvとareaの最大値を比べて高い方をmaxvを入れる target = pre.pos; // targetを左端とする } rect.pos = target; // 拡張される可能性のある長方形の左端をtargetとする S.push(rect); } } } return maxv; } int H, W; int buffer[MAX][MAX]; // 入力のタイル int T[MAX][MAX]; // 入力から作るタイル int getLargestRectangle() { for (int j = 0; j < W; j++) { for (int i = 0; i < H; i++) { if (buffer[i][j]) { // もしbufferに1が入っていれば T[i][j] = 0; // T[i][j]は0 } else { // もしbufferに0が入っている時 T[i][j] = (i > 0) ? T[i - 1][j] + 1 : 1; // iが0より大きい時, T[i][j] = 上の行の同じ列の値+1 } } } int maxv = 0; for (int i = 0; i < H; i++) { maxv = max(maxv, getLargestRectangle(W, T[i])); } return maxv; } int main() { cin.tie(0); ios::sync_with_stdio(false); scanf("%d %d", &H, &W); for (int i = 0; i < H; i++) { for (int j = 0; j < W; j++) { scanf("%d", &buffer[i][j]); // i行j列目の要素をbufferに入れる } } cout << getLargestRectangle() << endl; return 0; }
true
bf8abe0572193ff0ced2061c3b8c1264d4fa144d
C++
OutOfTheVoid/ProjectRed
/include/Xenon/Math/Vec3.h
UTF-8
2,891
2.765625
3
[ "MIT" ]
permissive
#ifndef XENON_VEC3_H #define XENON_VEC3_H #include <Xenon/Xenon.h> #include <Xenon/Math/Math.h> namespace Xenon { namespace Math { class Quaternion; class Vec2; class Vec3 { public: enum NoInit { NO_INIT }; const static Vec3 RIGHT; // + X const static Vec3 LEFT; // - X const static Vec3 UP; // + Y const static Vec3 DOWN; // - Y const static Vec3 FORWARD; // + Z const static Vec3 BACKWARD; // - Z const static Vec3 IDENTITY; // <1, 1, 1> const static Vec3 ZERO; // <0, 0, 0> explicit Vec3 ( const float X = 0.0, const float Y = 0.0, const float Z = 0.0 ); Vec3 ( const Vec3 & CopyFrom ); explicit Vec3 ( const Vec2 & Lower, const float Z ); inline explicit Vec3 ( NoInit NO_INIT ) { (void) NO_INIT; }; ~Vec3 (); static void Set ( Vec3 & Target, const float X, const float Y, const float Z ); static void Copy ( Vec3 & Target, const Vec3 & Source ); static bool Equal ( const Vec3 & A, const Vec3 & B ); static float DotProduct ( const Vec3 & A, const Vec3 & B ); static void CrossProduct ( Vec3 & Target, const Vec3 & Source, const Vec3 & B ); static void CrossProduct ( Vec3 & A, const Vec3 & B ); static void Multiply ( Vec3 & Target, const float B ); static void Multiply ( Vec3 & Target, const Vec3 & Source, const float B ); static void Scale ( Vec3 & Target, const Vec3 & B ); static void Scale ( Vec3 & Target, const Vec3 & Source, const Vec3 & B ); static void Add ( Vec3 & Target, const Vec3 & B ); static void Add ( Vec3 & Target, const Vec3 & Source, const Vec3 & B ); static void Subtract ( Vec3 & Target, const Vec3 & B ); static void Subtract ( Vec3 & Target, const Vec3 & Source, const Vec3 & B ); static void Normalize ( Vec3 & Target ); static void Normalize ( Vec3 & Target, const Vec3 & Source ); static float Length ( const Vec3 & Source ); static float LengthSquared ( const Vec3 & Source ); static void Absolute ( Vec3 & Target ); static void Absolute ( Vec3 & Target, const Vec3 & Source ); static float AngleBetween ( const Vec3 & A, const Vec3 & B ); static void Interpolate ( Vec3 & Target, const Vec3 & B, const float Fraction ); static void Interpolate ( Vec3 & Target, const Vec3 & Source, const Vec3 & B, const float Fraction ); static void Rotate ( Vec3 & Target, const Quaternion & Rotation ); static void Rotate ( Vec3 & Target, const Vec3 & Source, const Quaternion & Rotation ); static void Orthogonal ( Vec3 & Target ); static void Orthogonal ( Vec3 & Target, const Vec3 & Source ); static void Project ( Vec3 & Target, const Vec3 & Direction ); static void Project ( Vec3 & Target, const Vec3 & Projected, const Vec3 & Direction ); float X; float Y; float Z; }; } } #endif
true
0b0022dee87c80c6d0352fddaa57317b0ce212ad
C++
hayat16/basic-programs
/vector related.cpp
UTF-8
561
3.265625
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<int>v;//array declare v.push_back(5);//value insert v.push_back(11); cout<<v[0]<<endl; v.push_back(9); v.push_back(200); for(int i=0;i<v.size();i++) { cout<<v[i]<<endl; } int cnt=count(v.begin(),v.end(),9);//count function cout<<" count:"<<cnt<<endl; cout<<"After sorting"<<endl; sort(v.begin(),v.end());//sort fun for(int i=0;i<v.size();i++) { cout<<v[i]<<endl; } return 0; }
true
f257eae847b313bc99da4cf822a276bb5d107aab
C++
hbashift/lab3
/functions.cpp
UTF-8
2,220
2.953125
3
[]
no_license
#include "functions.h" #include "Complex.h" #include "Person.h" int add_two(int a){ return a+2; } int square(int a){ return a*a; } int mult_tree(int a){ return a*3; } int mod_two(int a){ return a%2; } int sum(int a){ return a+a; } int mult_ten(int a){ return a*10; } int add_one(int a){ return a+1; } float add_four(float a){ return a+4; } float minus_ten_half(float a){ return a-10.5; } float divide_by_two(float a){ return a/2; } Complex add_treetree(Complex a){ Complex b = Complex(3,3); return a+b; } Complex minus_tenten(Complex a){ Complex b = Complex(-10,-10); return a+b; } Complex mult_two(Complex a){ Complex b = Complex(2,0); return a*b; } bool is_even (int a){ if (a%2==0){ return true; } else { return false; } } bool is_positive (int a){ if (a>0){ return true; } else { return false; } } bool compare_two (float a){ if (a>2){ return true; } else { return false; } } bool float_positive (float a){ if (a>0){ return true; } else { return false; } } bool comp_mod_two (Complex a){ float absm = sqrt(a.Im*a.Im+a.Re*a.Re); if (absm>2){ return true; } else { return false; } } int less_number(int a, int b){ if (a>b){ return b; } else { return a; } } float higher_number(float a, float b){ if (a>b){ return a; } else { return b; } } Complex higher_module(Complex a, Complex b){ float absm = sqrt(a.Im*a.Im+a.Re*a.Re); float bbsm = sqrt(b.Im*b.Im+b.Re*b.Re); if (absm>bbsm){ return a; } else { return b; } } char make_num(char a){ if (a < '0' || a > '9') { return '1'; } else { return a; } } bool comp_a(char a) { return (a > 'a'); } char less_letter(char a, char b) { return (a>b)?b:a; } Person less_id(Person a, Person b) { return (a>b)?b:a; } bool even_id(Person a) { if (a.id%2==0){ return true; } else { return false; } } Person id_plus_one(Person a) { Person b = Person(a.Name,a.Surname,a.id+1); return b; }
true
5d4a6c551bdccf8fc7a08d05f9ff4056473663c6
C++
google-code/advisor-consultant
/SOZ/Etaps/psyhtestvariantbutton.cpp
UTF-8
2,301
2.53125
3
[]
no_license
#include "psyhtestvariantbutton.h" PsyhTestVariantButton::PsyhTestVariantButton(int ID, int GroupID, QString lbl,int weight, QWidget *parent) : QWidget(parent) { this->ID=ID; this->GroupID=GroupID; this->label=lbl; this->weight=weight; update(); } void PsyhTestVariantButton::paintEvent(QPaintEvent *) { QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing,true); if (Choosen) { QColor color(Qt::white); color.setAlpha(100); painter.setBrush(QBrush(color)); painter.setPen(QPen(Qt::white)); painter.setFont(QFont("Times",13,QFont::Bold)); } else { if (!MouseOn) { QColor color(Qt::gray); color.setAlpha(50); painter.setBrush(QBrush(color)); painter.setPen(QPen(Qt::white)); painter.setFont(QFont("Times",13,QFont::Bold)); } else { QColor color(Qt::white); color.setAlpha(70); painter.setBrush(QBrush(color)); painter.setPen(QPen(Qt::white)); painter.setFont(QFont("Times",13,QFont::Bold)); } } painter.drawRect(rect()); painter.drawText(rect(),Qt::AlignCenter | Qt::TextWordWrap,label); painter.end(); } void PsyhTestVariantButton::mousePressEvent(QMouseEvent *) { emit (iPressed(ID,GroupID)); update(); } void PsyhTestVariantButton::resizeEvent(QResizeEvent *) { update(); } void PsyhTestVariantButton::enterEvent(QEvent *) { MouseOn=true; update(); } void PsyhTestVariantButton::leaveEvent(QEvent *) { MouseOn=false; update(); } void PsyhTestVariantButton::setLabel(QString &lbl) { label = lbl; } void PsyhTestVariantButton::setWeight(double &_weight) { weight=_weight; } int PsyhTestVariantButton::GetID() { return ID; } int PsyhTestVariantButton::GetGroupID() { return GroupID; } void PsyhTestVariantButton::SetUnChoosen() { Choosen=false; update(); } void PsyhTestVariantButton::SetChoosen() { Choosen=true; update(); } bool PsyhTestVariantButton::isChoosen() { return Choosen; }
true
f31f319594b4d962f288e7eafd7cec16cfe45286
C++
yazidrm98/tugas1
/knapsack fractional.cpp
UTF-8
1,902
3.890625
4
[]
no_license
// Permasalahan Knapsack Fractional dengan greedy #include <bits/stdc++.h> using namespace std; // Structure untuk item/barang // dimana terdapat weight dan profit struct Item { int profit, weight; Item(int profit, int weight) { this->profit=profit; this->weight=weight; } }; // Fungsi untuk mengurutkan item/barang // berdasarkan rasio perbandingan profit dengan weight bool cmp(struct Item a, struct Item b) { double r1 = (double)a.profit / (double)a.weight; double r2 = (double)b.profit / (double)b.weight; return r1 > r2; } // Fungsi utama greedy untuk memecahkan knapsack double fractionalKnapsack(int W, struct Item arr[], int n) { // sorting untuk greedy by density sort(arr, arr + n, cmp); for (int i = 0; i < n; i++) { cout << arr[i].profit << " " << arr[i].weight << " : " << ((double)arr[i].profit / arr[i].weight) << endl; } int curWeight = 0; // weight saat ini di knapsack double finalprofit = 0.0; // Hasil (profit di Knapsack) // Looping item for (int i = 0; i < n; i++) { // Jika item yang akan diambil belum melebihi kapasitas // maka diambil sepenuhnya if (curWeight + arr[i].weight <= W) { curWeight += arr[i].weight; finalprofit += arr[i].profit; } // Jika melebihi kapasitas // maka diambil sebagian(pecahan) untuk memenuhi sisa else { int remain = W - curWeight; finalprofit += arr[i].profit * ((double)remain / (double)arr[i].weight); break; } } // Mengembalikan hasil profit return finalprofit; } // Program utama int main() { int M = 20; // kapasitas knapsack Item arr[] = { { 25, 18 }, { 24, 15 }, { 15, 10 } }; //{profit,weight} int n = sizeof(arr) / sizeof(arr[0]); // Function call, untuk output cout << "\nProfit maksimal yang bisa kita dapatkan = " << fractionalKnapsack(M, arr, n); return 0; }
true
31ebcfe11a3a4673c015ca8529c698267ee33554
C++
runngezhang/sword_offer
/leetcode/cpp/494. 目标和.cpp
UTF-8
741
2.703125
3
[]
no_license
class Solution { public: int my_abs(const int& x) { return (x >= 0 ? x : -x); } int findTargetSumWays(vector<int>& nums, int S) { int n = nums.size(), sum = accumulate(nums.begin(), nums.end(), 0); if (my_abs(S) > sum) { return 0; } int row = n + 1, col = 2 * sum + 1, curr; vector<vector<int>> dp(row, vector<int>(col, 0)); dp[0][sum] = 1; for (int i = 1; i < row; i++) { curr = my_abs(nums[i - 1]); for (int j = 0; j < col; j++) { if (j >= curr) dp[i][j] += dp[i - 1][j - curr]; if (j < col - curr) dp[i][j] += dp[i - 1][j + curr]; } } return dp[n][S + sum]; } };
true
7c5ac30fa44f384c769bf09bd9ca1d2852d815c7
C++
csqs/homeworks
/design_pattern/hw4/search.cpp
UTF-8
696
2.609375
3
[]
no_license
#include <iostream> #include <fstream> #include <string.h> #include <vector> #include "search.h" Search::Search(std::string input_id) { student_id = input_id; } Search::~Search() { } void Search::dbSearch(){ std::ifstream db; db.open("/Users/macx/Desktop/database/database.txt", std::ios::out | std::ios::in); if(!db.is_open()){ db.close(); std::cout <<"open fail"<< std::endl; } else{ std::string buffer; while(getline(db, buffer)){ if(buffer.find(student_id) != std::string::npos){ std::cout << buffer << std::endl; break; } } db.close(); } }
true
1ae5a1d11487b4e6648330a6a8c7eaa0408ab360
C++
demalexx/small-backup
/CommonClasses.cpp
UTF-8
10,782
3.265625
3
[]
no_license
#include "CommonClasses.h" /////////////////////////////////////////////////////////////////////////////// // CString /////////////////////////////////////////////////////////////////////////////// CString::CString(WORD wInitSize) { Init(wInitSize); } CString::CString(LPCTSTR ccText) { Init(); Assign((LPTSTR) ccText, lstrlen(ccText)); } CString::CString(CString& csText) { Init(); Assign(csText.GetMemory(), csText.Length()); } CString::CString(CString* csText) { Init(); Assign(csText->GetMemory(), csText->Length()); } CString::CString(CString& csText, WORD wStart, WORD wLen) { Init(); Assign(csText.GetMemory() + wStart, wLen); } CString::~CString() { HeapFree(m_hHeap, 0, m_pMemory); } WORD CString::Length() { if (m_bCalcLength) { m_wLength = lstrlen(m_pMemory); m_bCalcLength = false; } return m_wLength; } void CString::Init(WORD wInitSize) { m_pMemory = NULL; m_wMemory = wInitSize * sizeof(TCHAR); m_wLength = 0; m_bCalcLength = false; m_hHeap = GetProcessHeap(); m_pMemory = (LPTSTR) HeapAlloc(m_hHeap, 0, m_wMemory); } void CString::Resize(WORD wNewSize, bool bExact) { if (wNewSize > m_wMemory) { if (bExact) m_wMemory = wNewSize; else m_wMemory = (wNewSize / CSTRING_MEM_BLOCK + 1) * CSTRING_MEM_BLOCK; m_pMemory = (LPTSTR) HeapReAlloc(m_hHeap, 0, m_pMemory, m_wMemory); } } void CString::Assign(LPTSTR pMemory, WORD wSize, WORD wPos) { // wSize и wPos - в символах, не в байтах Resize((wSize + wPos) * sizeof(TCHAR)); CopyMemory(m_pMemory + wPos, pMemory, wSize * sizeof(TCHAR)); m_wLength = wSize + wPos; } void CString::Trim() { WORD wDelChars = 0; // кол-во символов для удаления for (int i = 0; i < Length(); i++) if ((*this)[i] == TEXT(' ')) wDelChars++; else break; Delete(0, wDelChars); wDelChars = 0; for (int i = Length() - 1; i >= 0; i--) if ((*this)[i] == TEXT(' ')) wDelChars++; else break; Delete(Length() - wDelChars, wDelChars); } CString CString::ToLower() { CharLowerBuff((*this).C(), Length()); return this; } CString CString::ToUpper() { CharUpperBuff((*this).C(), Length()); return this; } CString CString::ToLowerNew() { CString res((*this)); res.ToLower(); return res; } CString CString::ToUpperNew() { CString res((*this)); res.ToUpper(); return res; } CString CString::SubStr(WORD wStart, WORD wLen) { CString res; res.Assign(m_pMemory + wStart, wLen); return res; } int CString::Find(TCHAR cFind, WORD wStart) { for (WORD i = wStart; i < Length(); i++) if ((*this)[i] == cFind) return i; return -1; } void CString::Delete(WORD wStart, WORD wLen) { if (wLen == 0) return; // Передвинем память только если не происходит удаления с конца строки if (wStart + wLen < Length()) { CopyMemory(m_pMemory + wStart, m_pMemory + wStart + wLen, (Length() - wStart - wLen) * sizeof(TCHAR)); } m_wLength -= wLen; } CString CString::FromInt(__int64 i64Value) { CString sBuf; wsprintf(sBuf.Buf(20), TEXT("%d"), i64Value); (*this) = sBuf; return this; } __int64 CString::ToInt(__int64 i64Default) { if (Empty()) return i64Default; // Удалим "пробелы"-разделители for (WORD i = 0; i < Length(); i++) if ((*this)[i] == 160 /* TEXT("\x00A0") Non-break space*/) { this->Delete(i, 1); break; } __int64 res = 0; WORD bPower = 1; for (int i = Length() - 1; i >=0 ; i--) { if ((*this)[i] < TEXT('0') || (*this)[i] > TEXT('9')) return i64Default; res = res + ((*this)[i] - TEXT('0')) * bPower; bPower *= 10; } return res; } bool CString::ToBool(bool bDefault) { if ((*this) == TEXT("1") || (*this).ToLowerNew() == TEXT("true")) return true; else if ((*this) == TEXT("0") || (*this).ToLowerNew() == TEXT("false")) return false; else return bDefault; } bool CString::Spaces() { if (Empty()) return false; return ((*this)[0] == TEXT(' ') || (*this)[Length() - 1] == TEXT(' ')); } LPTSTR CString::C() { // Увеличим размер строки на один символ Resize((Length() + 1) * sizeof(TCHAR)); // и добавим null-terminator m_pMemory[Length()] = 0; return m_pMemory; } LPTSTR CString::Buf(WORD wSize) { Resize(wSize * sizeof(TCHAR)); if (Length() == 0) m_pMemory[Length()] = 0; else m_pMemory[Length() - 1] = 0; m_bCalcLength = true; return m_pMemory; } CString CString::operator = (CString* sOther) { return (*this) = (*sOther); } CString CString::operator = (CString& sOther) { Assign(sOther.GetMemory(), sOther.Length()); return (*this); } CString CString::operator = (LPCTSTR cOther) { Assign((LPTSTR) cOther, lstrlen(cOther)); return (*this); } CString CString::operator + (CString& sOther) { return CString(*this) += sOther; } CString CString::operator + (LPTSTR cOther) { return CString(*this) += cOther; } CString CString::operator + (TCHAR cOther) { return CString(*this) += cOther; } CString CString::operator += (CString& sOther) { Assign(sOther.GetMemory(), sOther.Length(), Length()); return (*this); } CString CString::operator += (LPTSTR cOther) { Assign(cOther, lstrlen(cOther), Length()); return (*this); } CString CString::operator += (TCHAR cOther) { TCHAR c[2] = {0}; c[0] = cOther; Assign(c, 1, Length()); return (*this); } bool CString::operator == (CString& sOther) { return lstrcmp((*this).C(), sOther.C()) == 0; } bool CString::operator == (LPTSTR cOther) { return lstrcmp((*this).C(), cOther) == 0; } bool CString::operator != (CString& sOther) { return !((*this) == sOther); } bool CString::operator != (LPTSTR cOther) { return !((*this) == cOther); } /////////////////////////////////////////////////////////////////////////////// // CDateTime /////////////////////////////////////////////////////////////////////////////// CDateTime::CDateTime() { GetLocalTime(&m_SystemTime); } CDateTime::CDateTime(CDateTime& Other) { m_SystemTime = Other.GetSystemTime(); } CDateTime::CDateTime(SYSTEMTIME Other) { m_SystemTime = Other; } CDateTime::CDateTime(WORD wYear, WORD wMonth, WORD wDay, WORD wHour, WORD wMinute, WORD wSecond, WORD wMilliseconds) { m_SystemTime.wYear = wYear; m_SystemTime.wMonth = wMonth; m_SystemTime.wDay = wDay; m_SystemTime.wHour = wHour; m_SystemTime.wMinute = wMinute; m_SystemTime.wSecond = wSecond; m_SystemTime.wMilliseconds = wMilliseconds; } __int64 CDateTime::Delta(SYSTEMTIME st) { CDateTime dt(st); // если просят узнать разницу где один из аргументов - нулевая дата - вернём ноль if (dt.IsNullTime()) return 0; else dt -= (*this); return *(LONGLONG*) &dt.GetFileTime(); } FILETIME CDateTime::GetFileTime() { FILETIME ft; SystemTimeToFileTime(&m_SystemTime, &ft); return ft; } CString CDateTime::PackToString() { CString res(15); // "Пакует" дату в строку вида 'HHMMSSddmmyyyy' wsprintf(res.Buf(15), TEXT("%.2d%.2d%.2d%.2d%.2d%.4d"), m_SystemTime.wHour, m_SystemTime.wMinute, m_SystemTime.wSecond, m_SystemTime.wDay, m_SystemTime.wMonth, m_SystemTime.wYear); return res; } bool CDateTime::UnpackFromString(CString sDateTime) { // "Распаковывает" дату из строку вида 'HHMMSSddmmyyyy' m_SystemTime.wHour = sDateTime.SubStr(0, 2).ToInt(); m_SystemTime.wMinute = sDateTime.SubStr(2, 2).ToInt(); m_SystemTime.wSecond = sDateTime.SubStr(4, 2).ToInt(); m_SystemTime.wDay = sDateTime.SubStr(6, 2).ToInt(); m_SystemTime.wMonth = sDateTime.SubStr(8, 2).ToInt(); m_SystemTime.wYear = sDateTime.SubStr(10, 4).ToInt(); return true; } __int64 CDateTime::DeltaMSec(SYSTEMTIME st) { return Delta(st) / DT_MSECOND; } __int64 CDateTime::DeltaSec(SYSTEMTIME st) { return Delta(st) / (__int64) DT_SECOND; } __int64 CDateTime::DeltaMin(SYSTEMTIME st) { return Delta(st) / (__int64) DT_MINUTE; } __int64 CDateTime::DeltaHour(SYSTEMTIME st) { return Delta(st) / (__int64) DT_HOUR; } CDateTime CDateTime::operator + (SYSTEMTIME& st) { FILETIME ftThis, ftOther; SystemTimeToFileTime(&m_SystemTime, &ftThis); SystemTimeToFileTime(&st, &ftOther); *(LONGLONG*) &ftThis += *(LONGLONG*) &ftOther; FileTimeToSystemTime(&ftThis, &m_SystemTime); return *this; } CDateTime CDateTime::operator + (CDateTime& st) { operator + (st.GetSystemTime()); return *this; } CDateTime CDateTime::operator + (__int64 i64) { FILETIME ft; *(LONGLONG*) &ft = i64; SYSTEMTIME st; FileTimeToSystemTime(&ft, &st); operator + (st); return *this; } CDateTime CDateTime::operator - (SYSTEMTIME& st) { FILETIME ftThis, ftOther; SystemTimeToFileTime(&m_SystemTime, &ftThis); SystemTimeToFileTime(&st, &ftOther); *(LONGLONG*) &ftThis -= *(LONGLONG*) &ftOther; FileTimeToSystemTime(&ftThis, &m_SystemTime); return *this; } CDateTime CDateTime::operator - (CDateTime& st) { operator - (st.GetSystemTime()); return *this; } CDateTime CDateTime::operator - (__int64 i64) { operator + (-i64); return *this; } CDateTime CDateTime::operator += (SYSTEMTIME& st) { operator + (st); return *this; } CDateTime CDateTime::operator += (CDateTime& st) { operator + (st); return *this; } CDateTime CDateTime::operator += (__int64 i64) { operator + (i64); return *this; } CDateTime CDateTime::operator -= (SYSTEMTIME& st) { operator - (st); return *this; } CDateTime CDateTime::operator -= (CDateTime& st) { operator - (st); return *this; } CDateTime CDateTime::operator -= (__int64 i64) { operator + (-i64); return *this; } bool CDateTime::operator == (SYSTEMTIME& st) { return (m_SystemTime.wYear == st.wYear && m_SystemTime.wMonth == st.wMonth && m_SystemTime.wDay == st.wDay && m_SystemTime.wDayOfWeek == st.wDayOfWeek && m_SystemTime.wHour == st.wHour && m_SystemTime.wMinute == st.wMinute && m_SystemTime.wSecond == st.wSecond && m_SystemTime.wMilliseconds == st.wMilliseconds); } bool CDateTime::operator == (CDateTime& dt) { return operator == (dt.GetSystemTime()); } bool CDateTime::operator > (SYSTEMTIME& st) { FILETIME ft; SystemTimeToFileTime(&st, &ft); return *(LONGLONG*) &GetFileTime() > *(LONGLONG*) &ft; } bool CDateTime::operator >= (SYSTEMTIME& st) { FILETIME ft; SystemTimeToFileTime(&st, &ft); return *(LONGLONG*) &GetFileTime() >= *(LONGLONG*) &ft; } bool CDateTime::operator < (SYSTEMTIME& st) { FILETIME ft; SystemTimeToFileTime(&st, &ft); return *(LONGLONG*) &GetFileTime() < *(LONGLONG*) &ft; } bool CDateTime::operator <= (SYSTEMTIME& st) { FILETIME ft; SystemTimeToFileTime(&st, &ft); return *(LONGLONG*) &GetFileTime() <= *(LONGLONG*) &ft; } CDateTime DTNow() { return CDateTime(); } CDateTime DTNULL() { CDateTime dt; SYSTEMTIME st = {0}; *(dt.GetPSystemTime()) = st; return dt; }
true
8a68701846e5630b79ea9c2b6acd895b6a69c9aa
C++
indjev99/Particle-Structures
/sources/draw.cpp
UTF-8
2,342
2.890625
3
[ "MIT", "Zlib" ]
permissive
#include "../headers/draw.h" #include "../headers/window_size.h" #include "../headers/settings.h" #include "../headers/my_math.h" const double DEG2RAD = PI / 180; void initDraw(GLFWwindow* w) { float ratio; int width, height; glfwMakeContextCurrent(w); glfwGetFramebufferSize(w, &width, &height); ratio = width / (float) height; glViewport(0, 0, width, height); glClear(GL_COLOR_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-ratio, ratio, -1.f, 1.f, 1.f, -1.f); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void drawCircle(const Vec2D& pos, double radius) { glBegin(GL_TRIANGLES); for(int i = 0; i < 360; ++i) { double rad = i * DEG2RAD; double rad2 = (i+1) * DEG2RAD; glVertex2f(cos(rad) * radius + pos.x, sin(rad) * radius + pos.y); glVertex2f(cos(rad2) * radius + pos.x, sin(rad2) * radius + pos.y); glVertex2f(pos.x, pos.y); } glEnd(); } void drawParticle(const Particle& particle) { double scale = std::min(1.0, 1.0 * windowWidth / windowHeight) / currSettings.univRad; const Color& color = particle.getColor(); double mass = particle.getMass(); double radius = particle.getRadius(); glColor3f(color.r, color.g, color.b); drawCircle(particle.getPos() * scale, radius * scale); if (mass < 0) { radius *= 0.8; glColor3f(currSettings.backColor.r, currSettings.backColor.g, currSettings.backColor.b); drawCircle(particle.getPos() * scale, radius * scale); } } void drawBackground(GLFWwindow* w) { double widthHeightRatio = 1.0 * windowWidth / windowHeight; glColor3f(currSettings.backColor.r, currSettings.backColor.g, currSettings.backColor.b); glBegin(GL_QUADS); glVertex2f(-1.0 * widthHeightRatio, -1.0); glVertex2f(1.0 * widthHeightRatio, -1.0); glVertex2f(1.0 * widthHeightRatio, 1.0); glVertex2f(-1.0 * widthHeightRatio, 1.0); glEnd(); } void drawParticleSystem(GLFWwindow* w, const ParticleSystem& particleSystem) { initDraw(w); drawBackground(w); const std::vector<Particle>& particles = particleSystem.getParticles(); int numParticles = particles.size(); for (int i = 0; i < numParticles; ++i) { drawParticle(particles[i]); } glfwSwapBuffers(w); }
true
11d1ef8ec0fd3859c7f067a671ea3b8a02026c63
C++
patonoide/TrabalhoTP1
/TP1/view/user/cadastrar.cpp
UTF-8
3,570
2.71875
3
[]
no_license
#include "cadastrar.hpp" #include "../Home.hpp" #include "../../controller/user.hpp" #include <ctype.h> void CadastrarView::printTitulo(){ printw("\t\t\t%s\n", "Cadastrar"); refresh(); } void CadastrarView::ConfirmarDados(){ UserController newctr; std::string toPost[5]; toPost[0] = cpf; toPost[1] = password; toPost[2] = dataval; toPost[3] = codcart; toPost[4] = numcart; newctr.POST_signup(toPost); } void CadastrarView::mostrarOpcoes(){ printw("\t (ESC) VOLTAR PARA INICIO\n"); // Usuário printw(" ### Dados do usuario ### \n"); printw(" CPF :\n"); printw(" Senha: \n\n"); // Cartao de credito printw(" ### Dados do Cartão de crédito ### \n"); printw(" Data de validade: \n"); printw(" Codigo de Seguranca: \n"); printw(" Numero do Cartão: \n "); printw(" ==== Confirmar ===="); curs_set(1); cursorY = 3; cursorX = 6; keypad(stdscr, TRUE); this->editing = 1; move(cursorY, cursorX); } void CadastrarView::handleInput(){ int ch; int ret; while(true){ ch = getch(); ret = this->processarOpcao(ch); if(ret == 1) return; } } int CadastrarView::processarOpcao(int ch){ switch (ch){ //! Caso Seta para Baixo case KEY_DOWN: switch (editing){ case 1: editing +=1; cursorY +=1 ; cursorX = 8 + this->password.length() ; move(cursorY, cursorX); break; case 2: editing+=1; cursorY+=3 ; cursorX=19 + this->dataval.length(); move(cursorY, cursorX); break; case 3: editing+=1; cursorY+=1 ; cursorX=22 + this->codcart.length(); move(cursorY, cursorX); break; case 4: editing+=1; cursorY+=1 ; cursorX= 19 + this->numcart.length(); move(cursorY, cursorX); break; case 5: editing +=1; cursorY +=2; cursorX = 10; move(cursorY, cursorX); break; case 6: break; } break; //! Caso da Seta para cima case KEY_UP: switch (editing){ case 1: break; case 2: editing-=1; cursorY-=1 ; cursorX = 6 + this->cpf.length() ; move(cursorY, cursorX); break; case 3: editing-=1; cursorY-=3 ; cursorX=8 + this->password.length(); move(cursorY, cursorX); break; case 4: editing-=1; cursorY-=1 ; cursorX=19 + this->dataval.length(); move(cursorY, cursorX); break; case 5: editing -=1; cursorY -=1 ; cursorX= 22 + this->codcart.length(); move(cursorY, cursorX); break; case 6: editing -=1; cursorY -= 2; cursorX= 19 + this->numcart.length(); move(cursorY, cursorX); break; } break; case 10: //? TODO: Confirmar o usuário if (editing == 6){ ConfirmarDados(); } break; case 27: // Esc key return 1; break; default: if(ch != '/') if(!isalnum(ch))break; switch (editing){ case 2: echochar((int)'*'); this->password.push_back(ch); break; case 1: echochar(ch); this->cpf.push_back(ch); break; case 3: echochar(ch); this->dataval.push_back(ch); break; case 4: echochar(ch); this->codcart.push_back(ch); break; case 5: echochar(ch); this->numcart.push_back(ch); break; } } return 0; }
true
3635a61a7d1865358bedada73156cddb3e2187e7
C++
LQNew/Openjudge
/王道机试/北京航空航天大学-素数/素数.cpp
GB18030
791
2.90625
3
[]
no_license
//ѶȲʱ临ӶΪO(n)+O(n/10)*O(sqrt(n)),n<10000Ҳʮ򼶱Сڰ򼶱û~ #include<iostream> #include<cmath> #include<cstring> using namespace std; int n; int prime[10000]; bool judge(int m) { for(int i=2;i<=sqrt(m);i++) if(m%i==0) return false; return true; } int main() { while(cin>>n) { memset(prime,0,sizeof(prime[0])); int j=0; for(int i=2;i<n;i++) { if(i%10!=1) continue; else if(judge(i)) prime[j++]=i; } if(j==0) cout<<-1<<endl; else { for(int i=0;i<j-1;i++) cout<<prime[i]<<" "; cout<<prime[j-1]<<endl; } } return 0; }
true
eab0f446640ec96a27c40f1441d226ceb16cb313
C++
Kushwaha-abhay/Placement-Preparation
/DSA/GeeksForGeeks/DSA-Self-Paced/Recursion/Power Set Using Recursion.cpp
UTF-8
910
3.234375
3
[]
no_license
// { Driver Code Starts //Initial Template for C++ // CPP program to generate power set #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function Template for C++ //Complete this function void sub(vector<string> & ans, string s, string curr, int i) { if(i == s.length()) { ans.push_back(curr); return; } sub(ans, s, curr, i+1); sub(ans, s, curr + s[i], i+1); } vector <string> powerSet(string s) { vector<string> ans; sub(ans, s, "", 0); sort(ans.begin(), ans.end()); return ans; } // { Driver Code Starts. // Driver code int main() { int T; cin>>T; while(T--) { string s; cin>>s; vector<string> ans = powerSet(s); sort(ans.begin(),ans.end()); for(auto x:ans) cout<<x<<" "; cout<<endl; } return 0; } // } Driver Code Ends
true
074a8ef4e9fff55139c875058b2e3f678c037463
C++
Abdelrahman-Atia/My-Algorithms
/MCMF_using_SPFA.cpp
UTF-8
1,743
2.609375
3
[]
no_license
#define MAXN 507 #define MAXM 130000 // n*(n - 1)/2 typedef vector<int> VI; const int INF = 1e9; // $infinity$: be careful to make this big enough!!! int S; // source int T; // sink int FN; // number of nodes int FM; // number of edges (initialize this to 0) // ra[a]: edges connected to a (NO MATTER WHICH WAY!!!); clear this in the beginning VI ra[MAXN]; int kend[MAXM], cap[MAXM], cost[MAXM]; // size: TWICE the number of edges void init() { FM = 0; for (int i = 0; i < MAXN; ++i) { ra[i].clear(); } } // Adds an edge from a to b with capacity c and cost d and returns the number of the new edge int addedge(int a, int b, int c, int d) { int i = 2 * FM; kend[i] = b; cap[i] = c; cost[i] = d; ra[a].push_back(i); kend[i + 1] = a; cap[i + 1] = 0; cost[i + 1] = -d; ra[b].push_back(i + 1); FM++; return i; } int dst[MAXM], pre[MAXM], pret[MAXM]; bool spfa() { for (int i = 0; i < FN; ++i) dst[i] = INF; dst[S] = 0; queue<int> que; que.push(S); while (!que.empty()) { int x = que.front(); que.pop(); for (int t : ra[x]) { int y = kend[t], nw = dst[x] + cost[t]; if (cap[t] > 0 && nw < dst[y]) { dst[y] = nw; pre[y] = x; pret[y] = t; que.push(y); } } } return dst[T] != INF; } // returns the maximum flow and the minimum cost for this flow pair<vlong, vlong> solve() { vlong totw = 0, totf = 0; while (spfa()) { int minflow = INF; for (int x = T; x != S; x = pre[x]) { minflow = min(minflow, cap[pret[x]]); } for (int x = T; x != S; x = pre[x]) { cap[pret[x]] -= minflow; cap[pret[x] ^ 1] += minflow; } totf += minflow; totw += minflow * dst[T]; } return make_pair(totf, totw); }
true
09fc80dfed648d9db0b98e37ed5bb7ad0ec1fef8
C++
AndriusDap/SDL2
/SDL2/Input.cpp
UTF-8
1,687
2.734375
3
[]
no_license
#include "Includes.h" #include "Input.h" using namespace std; Input::Input(GLFWwindow *Window):Anchor(SCREEN_WIDTH/2, SCREEN_HEIGHT/2) { window = Window; PointerAngle = 0; Shoot = false; HorizontalMotion = 0.0f; VerticalMotion = 0.0f; Quit = false; for(int i = 0; i < 100; i++) { presed_keys[i] = false; } } void Input::SetPointerAnchor(glm::vec2 anchor) { Anchor = anchor; } void Input::Update(int gameTime) { PointerAngle = 0; Shoot = false; HorizontalMotion = 0.0f; VerticalMotion = 0.0f; int x, y; double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); x = (int) floor(xpos); y = (int) floor(ypos); MousePosition[0] = x; MousePosition[1] = y; y = SCREEN_HEIGHT - y; PointerAngle = (float) ( 180 - atan2((float)(x - Anchor.x),(float)(y - Anchor.y)) * 180 / 3.14159265); Shoot = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1) == GLFW_PRESS; if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { VerticalMotion = 1.0f; } if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { VerticalMotion = -1.0f; } if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { HorizontalMotion = -1.0f; } if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { HorizontalMotion = 1.0f; } for(int i = 65; i < 91; i++) { if(glfwGetKey(window, i) == GLFW_PRESS) { if(!presed_keys[i]) { text_buffer += (char) i; presed_keys[i] = true; } } else { presed_keys[i] = false; } } if(glfwGetKey(window, GLFW_KEY_BACKSPACE) == GLFW_PRESS) { text_buffer = text_buffer.length() == 1 ? "" : text_buffer.substr(0, text_buffer.length() - 1); } Quit = glfwWindowShouldClose(window) == 1? true : false; } Input::~Input(void) { }
true
02a877382c3593d22ff218156499578d4aed467a
C++
lemben01/SolutionLaboARemettre03
/SalairesDesRepresentants/BenjaminLemire.cpp
ISO-8859-1
2,929
3.578125
4
[]
no_license
// But : /* Dveloppez un programme qui entre les ventes brutes hebdomadaires de chaque reprsentant et qui calcule et affiche son salaire. Entrez -1 la valeur des ventes pour quitter le programme. */ // Auteur : Benjamin Lemire // Date : 2020-10-02 #include <iostream> using namespace std; int main() { // commande qui permet d'afficher correctement les carachtres setlocale(LC_ALL, ""); // dclaration des variables : const int MONTANT_DEPART = 250; const float POURCENTAGE = 7.5; float vente; float total; int numRepresentant = 1; // la console affiche ce message l'utilisateur pour savoir s'il veut quitter cout << "--Entrez -1 pour quitter--" << endl; // question pos au premier utilisateur cout << "1 er reprsentant, montant de vente : "; // permet au programme de lire la rponse du premier utilisateur cin >> vente; // on entre dans un boucle, tant que le montant de la vente n'est pas = -1 ou tout autre chiffre inferieur -1 while (vente > -1) { // commende qui permet de mettre le system sur pause system("pause"); // commande qui permet au system de nettoyer la console chaque fois qu'on entre ou recommence la boucle system("cls"); // le numro du reprsentant augmenta chaque tour numRepresentant++; // commande qui permet de calculer ce que le reprsantant obtien pour c'est vente. Dans ce cas, // nous avons un montant de dpart qui commence 250$ qui viens s'additionner 7.5% du montant de la vente du representant en question. total = MONTANT_DEPART + ((vente * POURCENTAGE) / 100); // la console affiche le montant total que le reprsantant a fait cout <<"Vous avez fait "<< total <<"$" << endl; // la console raffiche ce message l'utilisateur pour savoir s'il veut quitter cout << "--Entrez -1 pour quitter--" << endl; // question pos l'utilisateur qui suit cout <<numRepresentant << " em reprsentant, montant de vente : "; // permet au programme de lire la rponse de l'utilisateur qui suit cin >> vente; } return 0; } /* Plan de test venteDuRepresentant %deVente$ total 5000$ 7.5% 250 + (7.5% de 5000$) = 625$ 56 7.5% 250 + (7.5% de 5000$) = 254.2$ -1 -- -- -56 -- -- j'ai dcid de mettre tout les montants qui sont ngatifs pour sortir de la console puisque que oui, le reprsentant pourait avoir perdu de l'argent au lieu d'avoir eu une vente positive. Ce qui instite donc dire que: si les ventes ngatives doivent etre calcul, -1 serait une vente qui pourrait etre possible. Pour remdier cette situation, l'usage du carachtre '=' par exemple aurait t prfrable pour quitter */
true
bc9d0cb5097bb24876f3aa097bf3d1666e223f73
C++
lquatrin/CGT1-1D_DCT_IDCT
/CG_T1/src/ButtonGenerateValues.h
ISO-8859-1
4,010
2.984375
3
[]
no_license
/*Arquivo referente aos componentes usados na gerao de valores para a amostra inicial*/ #ifndef ___BUTTON__GENERATE___VALUES__H____ #define ___BUTTON__GENERATE___VALUES__H____ #include <SCV/Button.h> #include "MyDCTS.h" #include "Values.h" #include <SCV/Spinner.h> #include <SCV/Label.h> /*Label do gerador de valores*/ class labelGenValues : public scv::Label { public: labelGenValues() : scv::Label(scv::Point(48, 2), "Gerar Valores") { } ~labelGenValues() {} protected: private: }; /*Seta valores aleatorios para o vetor*/ class RandomValuesButton : public scv::Button { public: RandomValuesButton(Values *MValue) : scv::Button(scv::Point(0, 19),scv::Point(165, 43), "Aleatorios") { BValues = MValue; } ~RandomValuesButton() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: Values *BValues; MyDCTS * MDCT; }; /*Seta valores linearmente crescentes*/ class ButtonLinearlyIncreasing : public scv::Button { public: ButtonLinearlyIncreasing(Values *Values, scv::Spinner* Spin) : scv::Button(scv::Point(0, 47),scv::Point(122, 71), "Linearmente Crescente") { BValues = Values; SpinB = Spin; } ~ButtonLinearlyIncreasing() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: Values *BValues; scv::Spinner* SpinB; MyDCTS *MDCT; }; /*Seta valores em forma de senoide*/ class ButtonSenoide : public scv::Button { public: ButtonSenoide(Values *Values, scv::Spinner* Spin) : scv::Button(scv::Point(0, 75),scv::Point(122, 99), "Forma de Senoide") { BValues = Values; SpinB = Spin; } ~ButtonSenoide() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: Values *BValues; scv::Spinner* SpinB; MyDCTS *MDCT; }; /*Seta valores iguais*/ class ButtonSetEqual : public scv::Button { public: ButtonSetEqual(Values *Values, scv::Spinner* Spin) : scv::Button(scv::Point(0, 103),scv::Point(122, 127), "Iguais") { BValues = Values; SpinB = Spin; } ~ButtonSetEqual() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: Values *BValues; scv::Spinner* SpinB; MyDCTS *MDCT; }; /*Linear Congruential Generators [Xn+1 = a Xn +c(mod m) a->multiplicador c->constante m->mdulo*/ class LCGButton : public scv::Button { public: LCGButton(Values *MtValues, scv::Spinner *LCGA, scv::Spinner *LCGC, scv::Spinner *LCGM) : scv::Button(scv::Point(1, 131),scv::Point(165, 155), "LCG - Xn+1 = aXn+c(mod m)") { MValues = MtValues; _LCGA = LCGA; _LCGC = LCGC; _LCGM = LCGM; } ~LCGButton() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: Values* MValues; scv::Spinner *_LCGA; scv::Spinner *_LCGC; scv::Spinner *_LCGM; MyDCTS *MDCT; }; /*Seta valores de acordo com o valor escrito no spinner*/ class ButtonSetKeyboard : public scv::Button { public: ButtonSetKeyboard(scv::Spinner *SPos, scv::Spinner *SVal, Values *MValues) : scv::Button(scv::Point(2, 180), scv::Point(165, 202), "Ponto[x] = Valor") { Pos = SPos; Val = SVal; MyValues = MValues; } ~ButtonSetKeyboard() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: scv::Spinner *Pos; scv::Spinner *Val; Values *MyValues; }; /*Trunca uma parte dos valores do vetor*/ class ButtonTruncadeParts : public scv::Button { public: ButtonTruncadeParts(scv::Spinner *posIni, scv::Spinner *posFin, Values *MValues) : scv::Button(scv::Point(2, 227), scv::Point(165, 250), "Truncar valores(DCTEdit)") { _posIni = posIni; _posFin = posFin; _MyValues = MValues; } ~ButtonTruncadeParts() {} void onMouseUp(const scv::MouseEvent& evt); protected: private: scv::Spinner *_posIni; scv::Spinner *_posFin; Values *_MyValues; }; #endif
true
2f33d85f72f878ee279b9f8fcea0dea6fa082ddc
C++
fanxiaochen/Multi-View-Registration
/mvr/include/light_source.h
UTF-8
931
2.578125
3
[]
no_license
#pragma once #ifndef LIGHT_SOURCE_H #define LIGHT_SOURCE_H #include "renderable.h" namespace osg { class Light; class LightSource; class TranslateAxisDragger; } namespace osgManipulator { class TranslateAxisDragger; } class LightSource : public Renderable { public: LightSource(unsigned int num); virtual ~LightSource(void); virtual const char* className() const {return "LightSource";} void init(const osg::Vec3& position, const osg::Vec4& ambient=osg::Vec4(1, 1, 1, 1), const osg::Vec4& diffuse=osg::Vec4(1, 1, 1, 1), const osg::Vec4& specular=osg::Vec4(1, 1, 1, 1)); osg::Light* getLight(void); protected: virtual void clear(); virtual void updateImpl(); private: osg::ref_ptr<osg::LightSource> light_source_; osg::ref_ptr<osgManipulator::TranslateAxisDragger> dragger_; bool initialized_; }; #endif // LIGHT_SOURCE_H
true
fb187baefc26d490b092d1fe98c011b7c358b2ef
C++
adityanjr/code-DS-ALGO
/HackerRank/Algorithms/Implementation/Angry Professor.cpp
UTF-8
619
3.1875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; bool isCancelled(int *arr, int n, int k){ int count = 0; for(int i=0; i<n; i++){ if(arr[i]<=0){ count++; } } if(count < k){ return true; } else { return false; } } int main(){ int t; cin>>t; while(t--){ int n; cin>>n; int k; cin>>k; int arr[n]; for(int i=0; i<n; i++){ cin>>arr[i]; } if(isCancelled(arr, n, k)){ cout<<"YES"<<endl; } else cout<<"NO"<<endl; } }
true
bb40117ffcb9dd3b81ec2ad01de8517d0bf14cab
C++
elreplicante/algorithm-analysis
/algorithm-analysis/src/Helper.cpp
UTF-8
1,498
3.125
3
[]
no_license
/* * Helper.cpp * * Created on: 18/12/2012 * Author: repli */ #include "../include/Helper.h" void Helper::createRandomArray(int V[], int n, int maxInteger) { for (int i = 0; i < n; i++) { V[i] = rand() % maxInteger; } } void Helper::copyArray(int V[], int W[], int n) { for (int i = 0; i < n; i++) { W[i] = V[i]; } } bool Helper::checkSameLength(int V[], int W[]) { int vElements = sizeof(V) / sizeof(int); int wElements = sizeof(W) / sizeof(int); return vElements == wElements; } bool Helper::checkArrayEquality(int V[], int W[], int n) { bool equals; if (!Helper::checkSameLength(V, W)) { equals = false; } else { int i = 0; while (V[i] == W[i] && i < n) { i++; } if (i == n - 1) { equals = true; } else { equals = false; } } return equals; } bool Helper::checkIsOrdered(int V[], int n) { bool ordered; int i = n - 1; while (i > 0 && V[i] >= V[i - 1]) { i--; } if (i == 0) { ordered = true; } else { ordered = false; } return ordered; } void Helper::printArrayContents(int V[], int n) { for (int i = 0; i < n; i++) { cout << V[i] << " "; if (i % 8 == 0) { cout << '\n'; } } cout << endl << endl; } void Helper::executePlotCommand() { int i; printf ("Checking if processor is available..."); if (system(NULL)) puts ("Ok"); else exit (1); printf ("Executing command generate-plots.sh...\n"); i=system ("generate-plots.sh"); printf ("The value returned was: %d.\n",i); }
true
5455ef88d9bab02305410b6d2b6296074507ceb0
C++
gabialverga/competitiveProgramming
/spoj/SENHATIA.cpp
UTF-8
724
2.796875
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; int main(){ int N,M,A,K,contM=0,contA=0,contK=0; string nome; cin >> N >> M >> A >> K; cin >> nome; if (nome.size() < N){ cout << "Ufa :)"; return 0; } for (int i =0; i< nome.size();i++){ if ((nome[i] >= 65) && (nome[i] <=90)){ contA++; } if ((nome[i] >=97) && (nome[i]<=122)){ contM++; } if ((nome[i]>=48) && (nome[i]<=57)){ contK++; } } if (contM < M){ cout << "Ufa :)"; return 0; } else if (contA < A){ cout << "Ufa :)"; return 0; } else if (contK < K){ cout << "Ufa :)"; return 0; } else { cout << "Ok =/"; } return 0; }
true
57583fbd72e2f1b1775460a5eb6b1ca89b886dbf
C++
rocksat/Quad3DR
/quad_planner/include/quad_planner/rendering/shader_program.h
UTF-8
1,683
2.78125
3
[ "MIT" ]
permissive
//================================================== // shader_program.h // // Copyright (c) 2016 Benjamin Hepp. // Author: Benjamin Hepp // Created on: Aug 19, 2016 //================================================== #pragma once #include <iostream> #include <vector> #include <map> #include <GL/glew.h> #include <quad_planner/rendering/linalg.h> namespace quad_planner { namespace rendering { class ShaderProgram { GLuint program_id_; std::vector<GLuint> shader_ids_; std::map<std::string, GLint> uniform_locations_; void init(); void clear(); void ensureInitialized(); public: enum ShaderType { VERTEX = GL_VERTEX_SHADER, FRAGMENT = GL_FRAGMENT_SHADER, GEOMETRY = GL_GEOMETRY_SHADER, }; static std::string getShaderTypeString(ShaderType type) { switch (type) { case VERTEX: return "Vertex"; case FRAGMENT: return "Fragment"; case GEOMETRY: return "Geometry"; default: return "Unknown"; } } ShaderProgram(); virtual ~ShaderProgram(); void compileShader(const std::string &source, ShaderType type); void compileShaderFromStream(std::istream &input, ShaderType type); void compileShaderFromFile(const std::string &filename, ShaderType type); void link(); void use(); bool hasUniformLocation(const std::string &name); GLint getUniformLocation(const std::string &name, bool fail_if_not_found = true); void setUniform(const std::string &name, float value); void setUniform(const std::string &name, const glm::mat4 &matrix); void setUniform(const std::string &name, const Eigen::MatrixXd &matrix); void setUniform(const std::string &name, const Eigen::MatrixXf &matrix); }; } }
true
589add57022633df9b0bafc904147142851d9657
C++
yunpengxiao/LeetcodeSolution
/CppSolution/threeSumClosest.cpp
UTF-8
1,381
3.234375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; class Solution { public: int threeSumClosest(vector<int> &num, int target) { //vector<vector<int> > r; //vector<int> triple(3); sort(num.begin(), num.end()); int j, k; int min = 999999999; int sum; for (int i = 0; i < num.size(); i++) { if (num[i] == num[i - 1] && i > 0) continue; j = i + 1; k = num.size() - 1; while (j < k) { if (num[i] + num[j] + num[k] > target) { if (abs(target - (num[i] + num[j] + num[k])) < min) { min = abs(target - (num[i] + num[j] + num[k])); sum = num[i] + num[j] + num[k]; } k--; } else if (num[i] + num[j] + num[k] < target) { if (abs(target - (num[i] + num[j] + num[k])) < min) { min = abs(target - (num[i] + num[j] + num[k])); sum = num[i] + num[j] + num[k]; } j++; } else { min = 0; return num[i] + num[j] + num[k]; // if (num[j] != triple[1] || num[k] != triple[2] || r.size() == 0) // { // triple[0] = num[i]; // triple[1] = num[j]; // triple[2] = num[k]; // r.push_back(triple); // } // j++; // k--; } } } return sum; } }; int main() { Solution s; int te[3] = {0, 0, 0}; vector<int> n(te, te + 3); cout << s.threeSumClosest(n, 1) << endl; return 0; }
true
296407aa2ea2fadb2a47bc67185e5c4839824485
C++
fdkeylabhu/CPP_PRIMER
/第7章类/answer_7_1_1.cpp
UTF-8
1,196
3.359375
3
[]
no_license
/***************************************************** C++ Primer 5th edition P230 *****************************************************/ #include <iostream> #include <vector> #include <algorithm> #include <list> #include <numeric> using namespace std; struct Sales_data { string bookNo; unsigned units_sold = 0; double revenue = 0.0; }; int main() { Sales_data total; double price = 0.0; if ( cin >> total.bookNo >> total.units_sold >> price ) { //输入第一本书 total.revenue = total.units_sold * price; Sales_data cur; while (cin >> cur.bookNo >> cur.units_sold >> cur.revenue) { if ( cur.bookNo == total.bookNo ) { total.units_sold += cur.units_sold; total.revenue += cur.revenue; } else { cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; //打印前面一本书 total = cur; } } cout << total.bookNo << " " << total.units_sold << " " << total.revenue << endl; //打印最后一本书 } else { cerr << "No data?!" << endl; return -1; } return 0; }
true
c86eeac5113279014e2c175e7b8e72b786d5e9f7
C++
LG-LuisGarcia/Mis-20-programas-en-c-y-menu
/palindroma.cpp
UTF-8
397
3.1875
3
[]
no_license
#include<iostream> #include<cstring> using namespace std; int main(){ char cadena[100], copia[100]; cout<<"Poner la palabra aca: "<<endl; cin>>cadena; for(int i=(strlen(cadena)-1);i>=0;i--){ copia[strlen(cadena)-1-i]=cadena[i]; } copia[strlen(cadena)]='\0'; if(strcmp(cadena,copia)==0){ cout<<"Es palindroma"; }else{ cout<<"La palabra no es palindroma"; } return 0; }
true
9897278cfd61c88546c087f45437808fc6208299
C++
kure-ict-club/competition-assignment
/pointN/Q2/main.cpp
UTF-8
383
3.109375
3
[]
no_license
#include <iostream> #include "Vector2D.h" int main() { Vec2 v1(3, 4); Vec2 v2(5, -6); Vec2 v3(0, 0); Vec2 v4 = v1 + v2; std::cout << v1.dot(v2) << std::endl; std::cout << v1.cross(v2) << std::endl; std::cout << v4.lengthSquare() << std::endl; if (v1.isZero()) std::cout << "v1 is zero" << std::endl; if (v3.isZero()) std::cout << "v3 is zero" << std::endl; }
true
4207c716191e79ba8d9a7c858286d7e9f3530c6e
C++
the-coding-cloud/UBB
/Year I/Sem II/Data Structures and Algorithms/Lab 5/Lab5_Binary_Heap/Lab5_Binary_Heap/Heap.h
UTF-8
2,928
3.609375
4
[]
no_license
#pragma once #include <list> using namespace std; typedef int TElem; typedef bool(*Relation) (TElem e1, TElem e2); typedef struct { list<TElem>::iterator currentPosition; list<TElem>::iterator endOfList; } myPair; typedef myPair iteratorPair; class Heap { private: Relation relation; iteratorPair* elements; int totalSize = 0; int numberOfLists = 0; int capacity = 100; void swap(int index1, int index2) // theta(1) { iteratorPair aux = this->elements[index1]; this->elements[index1] = this->elements[index2]; this->elements[index2] = aux; } void bubbleDown(int index) // O(log n) - n is the number of lists { int leftChild = index * 2; int rightChild = index * 2 + 1; int toChange = index; if (leftChild <= this->numberOfLists && this->relation(*(this->elements[leftChild].currentPosition), *(this->elements[toChange].currentPosition))) toChange = leftChild; if (rightChild <= this->numberOfLists && this->relation(*(this->elements[rightChild].currentPosition), *(this->elements[toChange].currentPosition))) toChange = rightChild; if (toChange != index) { this->swap(index, toChange); this->bubbleDown(toChange); } } void bubbleUp(int index) // O(log n) - n is the number of lists { if (index == 1) return; if (this->relation(*(this->elements[index].currentPosition), *(this->elements[index / 2].currentPosition))) { this->swap(index, index / 2); this->bubbleUp(index / 2); } } void resize() // theta(n) - n is the number of lists { iteratorPair* newElements = new iteratorPair[this->capacity * 2]; for (int i = 0; i < this->capacity; i++) newElements[i] = this->elements[i]; delete[] this->elements; this->elements = newElements; this->capacity *= 2; } public: Heap() { } int length() // theta(1) { return this->totalSize; } void insert(std::list<std::list<TElem>>::iterator element) // O(log n) - taking into consideration the bubble up { iteratorPair newElement; newElement.currentPosition = element->begin(); newElement.endOfList = element->end(); this->totalSize += element->size(); this->numberOfLists++; if (this->capacity == this->numberOfLists) this->resize(); this->elements[this->numberOfLists] = newElement; this->bubbleUp(this->numberOfLists); } TElem popRoot() // O(log n) - taking into consideration the bubble down { if (this->totalSize > 0) { iteratorPair aux = this->elements[1]; this->elements[1].currentPosition++; if (this->elements[1].currentPosition == this->elements[1].endOfList) { this->elements[1] = this->elements[this->numberOfLists]; this->numberOfLists--; } this->bubbleDown(1); this->totalSize--; return *aux.currentPosition; } return -1; } Heap(Relation rel) { this->relation = rel; this->elements = new iteratorPair[this->capacity]; } ~Heap() { delete[] this->elements; } };
true
a4a841c9c19e03ee227061a48f0049aa0db5446f
C++
omp13188/CPlusPlus
/Set 2/currency/currency_tes.cc
UTF-8
1,650
3.09375
3
[]
no_license
#include "currency.h" #include "gtest/gtest.h" using namespace std; TEST(Currency,DefaultConstructor) { Currency a1; EXPECT_EQ(0.0,a1.getrupees()); EXPECT_EQ(0.0,a1.getpaise()); } TEST(Currency,ParameterizedConstructor) { Currency a1(12,5); EXPECT_EQ(12,a1.getrupees()); EXPECT_EQ(5,a1.getpaise()); } TEST(Currency,AddTest) { Currency a1(12,225); Currency b1(7,15); Currency c1; c1=a1+b1; EXPECT_EQ(21,c1.getrupees()); EXPECT_EQ(40,c1.getpaise()); } TEST(Currency,SubTest) { Currency a1(12,45); Currency b1(7,1); Currency c1; c1=a1-b1; EXPECT_EQ(5,c1.getrupees()); EXPECT_EQ(44,c1.getpaise()); } TEST(Currency,AddIntTest) { Currency a1(12,225); Currency c1; c1=a1+15; EXPECT_EQ(29,c1.getrupees()); EXPECT_EQ(25,c1.getpaise()); } TEST(Currency,SubIntTest) { Currency a1(12,45); Currency c1; c1=a1-7; EXPECT_EQ(5,c1.getrupees()); EXPECT_EQ(45,c1.getpaise()); } TEST(Currency,PreIncTest) { Currency a1(12,100); Currency c1; c1=++a1; EXPECT_EQ(14,c1.getrupees()); EXPECT_EQ(0,c1.getpaise()); } TEST(Currency,PostIncTest) { Currency a1(12,5); Currency c1=a1++; EXPECT_EQ(13,c1.getrupees()); EXPECT_EQ(5,c1.getpaise()); } TEST(Currency,IsEqualTest) { Currency a1(12,5); Currency b1(12,5); EXPECT_EQ(true,a1==b1); } TEST(Currency,IsGreaterTest) { Currency a1(24,5); Currency b1(13,5); EXPECT_EQ(true,a1>b1); } TEST(Currency,IsLesserTest) { Currency a1(4,5); Currency b1(13,5); EXPECT_EQ(true,a1<b1); }
true
2f52670f8f6e042f6b2d98ecf53921d735d73538
C++
kyum1n/videocontrols
/DistSensorAttinySerial/DistSensorAttinySerial.ino
UTF-8
624
2.609375
3
[]
no_license
#include <TinyDebugSerial.h> int sensorPin = A1; // select the input pin for the potentiometer int sensorPin2 = A2; int sensorValue = 0; // variable to store the value coming from the sensor TinyDebugSerial mySerial = TinyDebugSerial(); void setup() { Serial.begin(9600); } void sendInt(int val) { Serial.write( (val>> 8) & 0xff ); Serial.write( (val ) & 0xff ); } void loop() { int sync = 0xaabb; int sens1 = 255; int sens2 = 260; //* sens1 = analogRead(sensorPin); sens2 = analogRead(sensorPin2); //*/ delay(20); sendInt(sync); sendInt(sens1); sendInt(sens2); }
true
f5185c12084c8af14e961b382003c2bdf02848cd
C++
Bendomey/homework
/a5_10670196.cpp
UTF-8
3,166
3.359375
3
[]
no_license
#include<iostream> #include <string> #include <iomanip> #include <fstream> using namespace std; void validateInput(int); struct studentType { string id, name; int age, score; char gender; string grade; }; int main(int argc, char const *argv[]) { studentType student[5]; ofstream outfile; double averageAge, averageScore; static int maleCount = 0, femaleCount = 0; // for (int i = 0; i < 5; ++i) { cout << "\n\n\t\t\tStudent " << i+1 << endl; // for id cout << "Student ID: "; cin >> student[i].id; // for name cout << "Name: "; cin >> student[i].name; // for age cout << "Age: "; cin >> student[i].age; validateInput(student[i].age); // for grade cout << "Gender (m or f): "; cin >> student[i].gender; if (student[i].gender == 'm' || student[i].gender == 'f') { if (student[i].gender == 'm') { maleCount += 1; }else if (student[i].gender == 'f') { femaleCount += 1; } } // for score cout << "Score: "; cin >> student[i].score; validateInput(student[i].score); //for grade if (student[i].score <= 100 && student[i].score >= 80) { student[i].grade = 'A'; }else if (student[i].score <= 79 && student[i].score >=70) { student[i].grade = 'B'; }else if (student[i].score <= 69 && student[i].score >= 60) { student[i].grade = 'C'; }else if (student[i].score <= 59 && student[i].score >=50) { student[i].grade = 'D'; }else if (student[i].score <= 49 && student[i].score >=40) { student[i].grade = 'E'; }else if (student[i].score <=39 && student[i].score >= 0) { student[i].grade = 'F'; }else if (student[i].score < 0 || student[i].score > 100) { student[i].grade = "Invalid Score"; } // end of first loop } // for sum int ageSum = 0, scoreSum = 0; for (int i = 0; i < 5; ++i) { ageSum += student[i].age; scoreSum += student[i].score; } // for averages averageAge = ageSum / 5; averageScore = scoreSum / 5; // output to file outfile.open("messages.txt"); //for the ouptut outfile <<"\n\n\n"; outfile << "No. " << setw(10) << "ID Number" << setw(15) << "Name"<< setw(15) << "Age"<< setw(15) << "Gender" << setw(15) << "Score" << setw(15) << "Grade\n"; outfile << "********************************************************************************************"; for (int i = 0; i < 5; ++i) { outfile << "\n" <<i+1 << ". " << "\t" ; outfile << student[i].id <<"\t\t"; outfile << student[i].name << "\t\t" << setw(3); outfile << student[i].age << "\t\t"; outfile << student[i].gender << "\t\t"; outfile << student[i].score << "\t\t"; outfile << student[i].grade << endl; } outfile << "\n********************************************************************************************"; outfile << "\nAverage Age: " << averageAge << endl; outfile << "Average Score: " << averageScore << endl; outfile << "Male Count: " << maleCount << endl; outfile << "Female Count: " << femaleCount << endl; return 0; } // for input validation void validateInput(int a){ while(cin.fail()){ cin.clear(); cin.ignore(200, '\n'); cout <<"Please enter a valid number: "; cin >> a; } }
true
cdfe786f65ae246bcebd225b6c032025f7511fa2
C++
Tsuzee/PortfolioProjects
/CrossPlatformEngine/PC_Engine/PC_Engine/PInput.cpp
UTF-8
3,339
2.65625
3
[ "Apache-2.0" ]
permissive
// Darren Farr #include "../../SharedCode/PInput.h" #include <DirectXMath.h> using namespace DirectX; // -------------------------------------------------------- // Default Constructor // -------------------------------------------------------- PInput::PInput() {} // -------------------------------------------------------- // Override Constructor, Camera Parameter // -------------------------------------------------------- PInput::PInput(Camera* _cam) { Cam = _cam; } // -------------------------------------------------------- // Override Constructor, Camera and Player Parameters // -------------------------------------------------------- PInput::PInput(Camera* _cam, Player* _p) { Cam = _cam; MyPlayer = _p; } // -------------------------------------------------------- // Deconstructor // -------------------------------------------------------- PInput::~PInput() {} // -------------------------------------------------------- // Handle User Input // -------------------------------------------------------- bool PInput::HandleUserEvents(float deltaTime) { XMVECTOR moveDir = XMVectorZero(); float moveAmount = 0.7f * deltaTime; // Parse Key input if (GetAsyncKeyState('W') & 0x8000) { //Cam->MoveCamPos({ 0.0f, 0.1f }); MyPlayer->MovePlayer({ 0.0f, 0.0f, 0.1f }, deltaTime); } if (GetAsyncKeyState('S') & 0x8000) { //Cam->MoveCamPos({ 0.0f, -0.1f }); MyPlayer->MovePlayer({ 0.0f, 0.0f, -0.1f }, deltaTime); } if (GetAsyncKeyState('A') & 0x8000) { //Cam->MoveCamPos({ -0.1f, 0.0f }); MyPlayer->MovePlayer({ -0.1f, 0.0f, 0.0f }, deltaTime); } if (GetAsyncKeyState('D') & 0x8000) { //Cam->MoveCamPos({ 0.1f, 0.0f }); MyPlayer->MovePlayer({ 0.1f, 0.0f, 0.0f }, deltaTime); } if (GetAsyncKeyState('R') & 0x8000) { //Cam->MoveCamPos({ 0.0f, 0.1f, 0.0f }); MyPlayer->MovePlayer({ 0.0f, 0.1f, 0.0f }, deltaTime); } if (GetAsyncKeyState('F') & 0x8000) { //Cam->MoveCamPos({ 0.0f, -0.5f, 0.0f }); MyPlayer->MovePlayer({ 0.0f, -0.1f, 0.0f }, deltaTime); } if (GetAsyncKeyState(VK_SPACE) & 0x8000) { // Will become Player Jump } // Test Player Rotations if (GetAsyncKeyState('I') & 0x8000) { //Cam->MoveCamPos({ 0.0f, 0.1f }); MyPlayer->RotatePlayer({ 0.0f, 0.0f, 0.1f }, deltaTime); } if (GetAsyncKeyState('K') & 0x8000) { //Cam->MoveCamPos({ 0.0f, -0.1f }); MyPlayer->RotatePlayer({ 0.0f, 0.0f, -0.1f }, deltaTime); } if (GetAsyncKeyState('J') & 0x8000) { //Cam->MoveCamPos({ -0.1f, 0.0f }); MyPlayer->RotatePlayer({ 0.1f, 0.0f, 0.0f }, deltaTime); } if (GetAsyncKeyState('L') & 0x8000) { //Cam->MoveCamPos({ 0.1f, 0.0f }); MyPlayer->RotatePlayer({ -0.1f, 0.0f, 0.0f }, deltaTime); } if (GetAsyncKeyState('U') & 0x8000) { //Cam->MoveCamPos({ -0.1f, 0.0f }); MyPlayer->RotatePlayer({ 0.0f, 0.1f, 0.0f }, deltaTime); } if (GetAsyncKeyState('O') & 0x8000) { //Cam->MoveCamPos({ 0.1f, 0.0f }); MyPlayer->RotatePlayer({ 0.0f, -0.1f, 0.0f }, deltaTime); } // Quit Game if (GetAsyncKeyState(VK_ESCAPE)) { return true; } return false; } // -------------------------------------------------------- // Handle User Input, Unused // -------------------------------------------------------- bool PInput::HandleUserEvents(double g_act_secs, float deltaTime) { return false; }
true
ff233aa6b002aaf34ab9dfa22ce3981a0a8f2811
C++
j-dong/FPS
/VertexArray.cpp
UTF-8
1,973
3.09375
3
[]
no_license
#include "VertexArray.h" VertexArray::VertexArray(GLsizei size, GLenum mode) : id(0), buffers(), indices(), size(size), mode(mode), index_type(0) { glGenVertexArrays(1, &id); } VertexArray::VertexArray(VertexArray &&move) : id(move.id), indices(std::move(move.indices)), size(move.size), mode(move.mode), index_type(move.index_type) { move.id = 0; move.size = 0; move.mode = 0; move.index_type = 0; for (int i = 0; i < ATTRIBUTE_NUM; i++) buffers[i] = std::move(move.buffers[i]); } VertexArray::~VertexArray() { glDeleteVertexArrays(1, &id); } VertexArray &VertexArray::operator=(VertexArray &&move) { if (this != &move) { this->~VertexArray(); id = move.id; move.id = 0; for (int i = 0; i < ATTRIBUTE_NUM; i++) buffers[i] = std::move(move.buffers[i]); indices = std::move(move.indices); size = move.size; move.size = 0; mode = move.mode; move.mode = 0; index_type = move.index_type; move.index_type = 0; } return *this; } void VertexArray::activate() { glBindVertexArray(id); } void VertexArray::deactivate() { glBindVertexArray(0); } // assume already active // small performance gain when binding multiple buffers // most common use case void VertexArray::bindBuffer(VertexBuffer &&buf, std::size_t i, GLint size, GLenum type, GLsizei stride) { buffers[i] = std::unique_ptr<VertexBuffer>(new VertexBuffer(std::move(buf))); buffers[i]->activate(); glEnableVertexAttribArray(i); glVertexAttribPointer(i, size, type, GL_FALSE, stride, 0); } void VertexArray::bindBuffer(IndexBuffer &&buf, GLenum index_type) { indices = std::unique_ptr<IndexBuffer>(new IndexBuffer(std::move(buf))); indices->activate(); this->index_type = index_type; } void VertexArray::draw() { if (indices) glDrawElements(mode, size, index_type, 0); else glDrawArrays(mode, 0, size); }
true
8ec14c8ecb0f675b49b86ec9f5609c44dbb245ba
C++
vaibhavarena/cpp-reference
/Memory Management/9.smart_pointers.cpp
UTF-8
2,509
4.0625
4
[]
no_license
#include<iostream> #include<string> #include<memory> class myClass { private: std::string _text; public: myClass(){} myClass(std::string t){ _text = t; } ~myClass(){ std::cout<<"\n" << _text << " Destroyed"; } void setText(std::string x) { _text = x; } std::string getText() { return _text; } }; int main() { // ***Unique pointer*** std::unique_ptr<myClass> a(new myClass()); std::unique_ptr<myClass> unique(new myClass("vaibhav")); unique->setText("V"); *a = *unique; a->setText("Z"); std::cout<<a->getText() << " " << unique->getText() << "\n"; // .get() gives the location of the new instances created on the heap as unique and a are created on the stack // but new myclass() will allocate memory on the heap std::cout<<a.get() << " " << unique.get(); // ***Shared and weak pointers*** // Weak pointer can only be made from shared pointer or from another weak pointer - Doesn't effect reference count std::shared_ptr<int> s1(new int); std::cout<<"\nShared count = "<<s1.use_count()<<"\n"; { std::shared_ptr<int> s2 = s1; std::weak_ptr<int> s3 = s2; std::weak_ptr<int> s4 = s3; std::cout<< "Shared count = " << s1.use_count()<<"\n"; s2.reset(new int); // Redirecting a shared pointer std::cout<< "Shared count = " << s1.use_count()<<"\n"; if(s3.expired()) // when s2 got reset, s3 expires { std::cout<<"\ns3 expired\n"; } else { std::cout<<"\ns3 not expired\n"; } } std::cout<<"Shared count = "<<s1.use_count()<<"\n"; // Copying pointers // Unique and weak pointers can be converted to shared pointers using std::move and .lock() // Unique to shared std::shared_ptr<int> c_shared = std::move(s1); std::weak_ptr<int> w_shared(c_shared); // Weak to shared std::shared_ptr<int> c_shared2 = w_shared.lock(); // Makes sure that the weak pointer remains in scope if(w_shared.expired()) std::cout<<"\nWeak pointer expired\n"; else std::cout<<"\nWeak pointer not expired\n"; std::cout<<"\nCopying pointers shared usage : "<<w_shared.use_count() << "\n"; int *r = c_shared.get(); // Calling delete on r not required because smart pointer will clear the memory anyway }
true
a5528c577a5a8025900383b39821f7b712da75bb
C++
Arinarina/TickTackToe
/Game.cpp
UTF-8
11,635
3.15625
3
[]
no_license
#include <iostream> #include "Game.h" using namespace std; Game *Game::myGame = nullptr; // конструктор без параметров Game::Game() { first = 1; second = 2; firstMove = 'O'; secondMove = 'X'; cout << "Enter side value" << endl; cin >> side; this->board = new char*[side]; for (int i = 0; i< side; i++) { this->board[i] = new char[side]; } this->moves = new int[side*side]; for (int i=0; i<side; i++) { for (int j=0; j<side; j++) this->board[i][j] = ' '; } for (int i=0; i<side*side; i++) this->moves[i] = i; } // конструктор с параметрами, введены раазмеры поля Game::Game(int side) { this->side = side; first = 1; second = 2; firstMove = 'O'; secondMove = 'X'; this->board = new char*[side]; for (int i = 0; i< side; i++) { this->board[i] = new char[side]; } this->moves = new int[side*side]; for (int i=0; i<side; i++) { for (int j=0; j<side; j++) board[i][j] = '_'; } for (int i=0; i<side*side; i++) moves[i] = i; } // деструктор Game::~Game() { first = 0; second = 0; side = 0; for (int i = 0; i< side; i++) { delete this->board[i]; } delete[] board; delete[] moves; } Game *Game::GetInstance() { if (myGame == nullptr) { myGame = new Game(); } return myGame; } Game *Game::GetInstance(int side) { if (myGame == nullptr) { myGame = new Game(side); } return myGame; } void Game::setSide(int side) { this->side = side; } int Game::getSide() { return side; } void Game::setWindow(sf::RenderWindow *window) { this->window = window; } sf::RenderWindow *Game::getWindow() { return window; } void Game::setRenderWindow(sf::RenderWindow *window) { this->window = window; } void Game::renderGameField() { for (int i = 1; i <= side; i++) { sf::Vertex line[] = { sf::Vertex(sf::Vector2f(i * (DISP_WIDTH / side), 0)), sf::Vertex(sf::Vector2f(i * (DISP_WIDTH / side), 320)) }; (*window).draw(line, 2, sf::Lines); line[0] = sf::Vertex(sf::Vector2f(0, i * (DISP_WIDTH / side))); line[1] = sf::Vertex(sf::Vector2f(320, i * (DISP_WIDTH / side))); (*window).draw(line, 2, sf::Lines); } // will be rendered on next tick } void Game::checkDisplayClosed(sf::RenderWindow *window) { (*window).clear(sf::Color::Black); while ((*window).isOpen()) { sf::Event event; while ((*window).pollEvent(event)) { if (event.type == sf::Event::Closed) (*window).close(); } // (*window).display(); } } // показываем инструкции void Game::showInstruction() { cout << endl << "Choose the field" << endl; for (int i = 0 ; i < side; i++) { for (int j = 0; j < side; j++) { cout << "| " << i << "/" << j << " |"; } cout << endl; for (int j = 0; j < side; j++) cout << "-------"; cout << endl; } return; } // показываем игровое поле void Game::showBoard() { cout << endl; cout << side << endl; for (int i = 0 ; i < side; i++) { for (int j = 0; j < side; j++) { cout << "| " << board[i][j] << " |"; } cout << endl; for (int j = 0; j < side; j++) cout << "-----"; cout << endl; } return; } // 5 в один столбец bool Game::rowCrossed() { int xx = 0; int yy = 0; int starting = 0; for (int i = 0; i < side; i++) { for (int j = 0; j < side; j++) { if (board[i][j] == 'X') { xx++; yy = 0; } if (board[i][j] == 'O') { yy++; xx = 0; } if ((xx >= 5) || (yy >= 5)) { return true; } } } return(false); } // 5 в одну колонку bool Game::columnCrossed() { int xx = 0; int yy = 0; int starting = 0; for (int j = 0; j < side; j++) { for (int i = 0; i < side; i++) { if (board[i][j] == 'X') { xx++; yy = 0; } if (board[i][j] == 'O') { yy++; xx = 0; } if ((xx >= 5) || (yy >= 5)) { return true; } } } return(false); } // 5 по диагонали bool Game::diagonalCrossed() { // проверка диагоналей основной и обратной int xx, yy; int starting = 0; xx = 0; yy = 0; for (int i = 0; i < side; i++) { if (board[i][i] == 'O') { xx++; } if (board[i][i] == 'X') { yy++; } if (board[i][i] == '_') { xx = 0; yy = 0; } if ((xx == 5) || (yy == 5)) { return true; } } // обратная диагональ xx = 0; yy = 0; for (int i = 0; i < side; i++) { if (board[side - 1 - i][side - 1 - i] == 'O') { xx++; } if (board[side - 1 - i][side - 1 - i] == 'X') { yy++; } if (board[side - 1 - i][side - 1 - i] == '_') { xx = 0; yy = 0; } if ((xx == 5) || (yy == 5)) { return true; } } // побочные диагонали по наравлению главной int preX = 1; for (int i = 1; i <= side - 5; i++) { xx = 0; yy = 0; for (int j = 0; j < side - i; j++) { if (board[preX + j][j] == 'O') { xx++; yy = 0; } if (board[preX + j][j] == 'X') { yy++; xx = 0; } if (board[preX + j][j] == '_') { yy = 0; xx = 0; } if ((xx == 5) || (yy == 5)) { return true; } } preX++; } preX = 1; for (int i = 1; i <= side - 5; i++) { xx = 0; yy = 0; for (int j = 0; j < side - i; j++) { if (board[j][preX + j] == 'O') { xx++; yy = 0; } if (board[j][preX + j] == 'X') { yy++; xx = 0; } if (board[j][preX + j] == '_') { yy = 0; xx = 0; } if ((xx == 5) || (yy == 5)) { return true; } } preX++; } // Побочные диагонали preX = 1; for (int i = 1; i <= side - 5; i++) { xx = 0; yy = 0; for (int j = 0; j < side - i; j++) { if (board[side - 1 - (preX + j)][side - 1 - j] == 'O') { xx++; yy = 0; } if (board[side - 1 - (preX + j)][side - 1 - j] == 'X') { yy++; xx = 0; } if (board[side - 1 - (preX + j)][side - 1 - j] == '_') { yy = 0; xx = 0; } if ((xx == 5) || (yy == 5)) { return true; } } preX++; } preX = 1; for (int i = 1; i <= side - 5; i++) { xx = 0; yy = 0; for (int j = 0; j < side - i; j++) { if (board[side - 1 - j][side - 1 - (preX + j)] == 'O') { xx++; yy = 0; } if (board[side - 1 - j][side - 1 - (preX + j)] == 'X') { yy++; xx = 0; } if (board[side - 1 - j][side - 1 - (preX + j)] == '_') { yy = 0; xx = 0; } if ((xx == 5) || (yy == 5)) { return true; } } preX++; } return false; } // новый ход в игре (считываем куда ходим, устанавливаем на доску) int Game::newMove(int turn, int move, int x, int y){ char currentSym; if (turn == first) currentSym = firstMove; else if (turn == second) currentSym = secondMove; if (x > side - 1 || y > side - 1) { cout << "Field out of range" << endl; return -1; } if (board[x][y] != '_'){ cout << "Field is bisy" << endl; return -1; } cout << x << " " << y << endl; board[x][y] = currentSym; if (currentSym == firstMove) { drawTick(x, y); } else { drawRound(x, y); } cout << board[x][y] << " in " << moves[move] / side << " " << moves[move] %side << endl; showBoard(); (*window).display(); return 0; } // Проверяем победителя по всем правилам int Game::checkWin(int move, int turn){ if (move == side * side) { printf("No winner\n"); return 1; } else if (rowCrossed() || columnCrossed() || diagonalCrossed()) { if (turn == first) { clearText(); drawWinnerText("SECOND WIN!"); printf("second win\n"); } else { clearText(); drawWinnerText("FIRST WIN!"); printf("first win\n"); } return 1; } else return 0; } void Game::drawTick(int x, int y) { sf::Vertex line[] = { sf::Vertex(sf::Vector2f(x * (DISP_WIDTH / side), y * (DISP_WIDTH / side))), sf::Vertex(sf::Vector2f((x+1) * (DISP_WIDTH / side), (y + 1) * (DISP_WIDTH / side))) }; (*window).draw(line, 2, sf::Lines); line[0] = sf::Vertex(sf::Vector2f((x + 1) * (DISP_WIDTH / side), y * (DISP_WIDTH / side))); line[1] = sf::Vertex(sf::Vector2f(x * (DISP_WIDTH / side), (y + 1) * (DISP_WIDTH / side))); (*window).draw(line, 2, sf::Lines); } void Game::drawRound(int x, int y) { sf::CircleShape shape((DISP_WIDTH / side) / 2 - 4); shape.move(sf::Vector2f(x * (DISP_WIDTH / side) + 4, y * (DISP_WIDTH / side) + 4)); shape.setOutlineThickness(2.f); shape.setFillColor(sf::Color::Black); shape.setOutlineColor(sf::Color::White); (*window).draw(shape); } void Game::drawWinnerText(string winner) { sf::Text text; sf::Font font; font.loadFromFile("roboto.ttf"); text.setFont(font); text.setString(winner); text.setCharacterSize(24); text.setFillColor(sf::Color::Red); text.setStyle(sf::Text::Bold | sf::Text::Underlined); text.move(10, 340); (*window).draw(text); (*window).display(); } void Game::drawInfo(int state) { sf::Text text; sf::Font font; font.loadFromFile("roboto.ttf"); text.setFont(font); if (state == 1) { text.setString("Please wait..."); } else { text.setString("You turn..."); } text.setCharacterSize(24); text.setFillColor(sf::Color::White); text.setStyle(sf::Text::Bold | sf::Text::Underlined); text.move(10, 340); (*window).draw(text); (*window).display(); } void Game::clearText() { sf::RectangleShape rectangle(sf::Vector2f(320.f, 80.f)); rectangle.move(0, 320); rectangle.setFillColor(sf::Color::Black); (*window).draw(rectangle); (*window).display(); }
true
e4b1912bcc462fb1f9bb6603c7b5844b890428e8
C++
kevinhughes27/2809_vision2013
/segmentTargets.cpp
UTF-8
4,741
2.609375
3
[]
no_license
#include "segmentTargets.h" using namespace cv; using namespace std; void segmentTargets(const Mat &image, vector<Mat> &candidates, vector<Point> &locations, bool log, bool debug) { candidates.clear(); locations.clear(); if(log) { imwrite("logs/0_image.png", image); } // Convert to CV_8UC1 (8 bit single channel) // split channels vector<Mat> channels; split(image, channels); // Blur Mat img_gray; blur(channels[2], img_gray, Size(5,5)); if(debug) { imshow("image", img_gray); waitKey(); } if(log) { imwrite("logs/1_image_gray.png", img_gray); } // Sobel Filter Mat img_sobely; Sobel(img_gray, img_sobely, CV_8U, 0, 1, 3, 1, 0, BORDER_DEFAULT); Mat img_threshold; threshold(img_sobely, img_threshold, 0, 255, CV_THRESH_OTSU+CV_THRESH_BINARY); if(debug) { imshow("image", img_threshold); waitKey(); } if(log) { imwrite("logs/2_sobel.png", img_threshold); } // Morphological Operator Mat img_rectangle; Mat element = getStructuringElement(MORPH_RECT, Size(MORPH_RECT_WIDTH, MORPH_RECT_HEIGHT) ); morphologyEx(img_threshold, img_rectangle, CV_MOP_CLOSE, element); Mat img_dilate; dilate(img_rectangle, img_dilate, Mat(), Point(-1,-1), 5); Mat img_erode; erode(img_dilate, img_erode, Mat(), Point(-1,-1), 6); if(debug) { imshow("image", img_erode); waitKey(); } if(log) { imwrite("logs/3_morpho.png", img_erode); } // findContours vector< vector< Point> > contours; findContours(img_erode,contours,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE); vector<vector<Point> >::iterator itc = contours.begin(); vector<RotatedRect> rects; // filter by contour size while (itc!=contours.end()) { //Create bounding rect of object RotatedRect mr = minAreaRect(Mat(*itc)); if( !verifySizes(mr)) { itc= contours.erase(itc); } else { ++itc; rects.push_back(mr); } } if(debug) { // Draw blue contours on a black image cv::Mat result = cv::Mat::zeros(image.size(),image.type()); cv::drawContours(result,contours, -1, cv::Scalar(255,0,0),1); imshow("image", result); waitKey(); } if(log) { // Draw blue contours on a black image cv::Mat result = cv::Mat::zeros(image.size(),image.type()); cv::drawContours(result,contours, -1, cv::Scalar(255,0,0),1); imwrite("logs/4_contours.png", result); } // transform the segmented regions for(unsigned int i = 0; i < rects.size(); i++) { // rotated rectangle drawing Point2f rect_points[4]; rects[i].points( rect_points ); if(debug) { cv::Mat result = cv::Mat::zeros(image.size(),image.type()); for( int j = 0; j < 4; j++ ) { line( result, rect_points[j], rect_points[(j+1)%4], Scalar(0,0,255), 1, 8 ); } imshow("image", result); waitKey(); } // Get rotation matrix float r= (float)rects[i].size.width / (float)rects[i].size.height; float angle=rects[i].angle; if(r<1) angle=90+angle; Mat rotmat= getRotationMatrix2D(rects[i].center, angle,1); // Create and rotate image Mat img_rotated; warpAffine(image, img_rotated, rotmat, image.size(), CV_INTER_CUBIC); // Crop image Size rect_size=rects[i].size; if(r < 1) swap(rect_size.width, rect_size.height); Mat img_crop; getRectSubPix(img_rotated, rect_size, rects[i].center, img_crop); // resize Mat resultResized; resultResized.create(TARGET_HEIGHT_PIXELS,TARGET_WIDTH_PIXELS, CV_8UC3); resize(img_crop, resultResized, resultResized.size(), 0, 0, INTER_CUBIC); //Equalize croped image resultResized=histeq(resultResized); if(debug) { imshow("image", resultResized); waitKey(); } // add target candidates.push_back(resultResized.clone()); locations.push_back(rects[i].center); } return; } bool verifySizes(RotatedRect mr) { //target: 120x40 aspect 3 float error=0.4; float aspect = 3; //Set a min and max area. All other patchs are discarded int min = 15*aspect*15; // minimum area int max = 80*aspect*80; // maximum area //Get only patchs that match to a respect ratio. float rmin = aspect-aspect*error; float rmax = aspect+aspect*error; int area= mr.size.height * mr.size.width; float r = (float)mr.size.width / (float)mr.size.height; if(r<1) r= (float)mr.size.height / (float)mr.size.width; //cout << "area " << area << " r " << r << endl; if(( area < min || area > max ) || ( r < rmin || r > rmax )) { return false; } else { return true; } } Mat histeq(Mat in) { Mat out(in.size(), in.type()); if(in.channels()==3) { Mat hsv; vector<Mat> hsvSplit; cvtColor(in, hsv, CV_BGR2HSV); split(hsv, hsvSplit); equalizeHist(hsvSplit[2], hsvSplit[2]); merge(hsvSplit, hsv); cvtColor(hsv, out, CV_HSV2BGR); } else if(in.channels()==1) { equalizeHist(in, out); } return out; }
true
b2b4ad8555ac4cc5ec03e015504194004dbc7256
C++
reed123456/c-
/Test_06_24/Test_06_24/test.cpp
GB18030
3,646
3.109375
3
[]
no_license
#include<iostream> #include<vld.h> #include<string> using namespace std; int main() { cout << "hh" << endl; } //template<class Type> //class BST; // ////ʵһö //template<class Type> //class BSTNode //{ // friend class BST<Type>; //public: // BSTNode(Type d = Type(), BSTNode<Type> *left = nullptr, BSTNode<Type> *right = nullptr) // : data(d), leftChild(left), rightChild(right) // {} // ~BSTNode() // {} //private: // Type data; // BSTNode<Type> *leftChild; // BSTNode<Type> *rightChild; //}; // //template<class Type> //class BST //{ //public: // BST() : root(nullptr) // {} // BST(Type ar[], int n) : root(nullptr) // { // for (int i = 0; i<n; ++i) // Insert(ar[i]); // } // ~BST() // { // MakeEmpty(root); // root = nullptr; // } //public: // Type Min()const // { // return Min(root); // } // Type Max()const // { // return Max(root); // } // bool Insert(const Type &x) // { // return Insert(root, x); // } // bool Remove(const Type &key) // { // return Remove(root, key); // } // BSTNode<Type>* Search(const Type &key) // { // return Search(root, key); // } // void Sort() // { // Sort(root); // } // void SortPair() // { // SortPair(root); // } // void MakeEmpty() // { // MakeEmpty(root); // } //protected: // Type& Min(BSTNode<Type> *t)const // { // while (t->leftChild != nullptr) // t = t->leftChild; // return t->data; // } // Type& Max(BSTNode<Type> *t)const // { // while (t->rightChild != nullptr) // t = t->rightChild; // return t->data; // } // bool Insert(BSTNode<Type> *&t, const Type &x) // { // if (t == nullptr) // { // t = new BSTNode<Type>(x); // return true; // } // else if (x < t->data) // Insert(t->leftChild, x); // else if (x > t->data) // Insert(t->rightChild, x); // else // return false; // } // bool Remove(BSTNode<Type> *&t, const Type &key) // { // BSTNode<Type> *p = nullptr; // if (t != nullptr) // { // if (key < t->data) // Remove(t->leftChild, key); // else if (key > t->data) // Remove(t->rightChild, key); // else if (t->leftChild != nullptr && t->rightChild != nullptr) // { // p = t->leftChild; // while (p->rightChild != nullptr) // p = p->rightChild; // t->data = p->data; // Remove(t->leftChild, p->data); // } // else // { // p = t; // if (t->leftChild != nullptr) // t = p->leftChild; // else // t = p->rightChild; // delete p; // // return true; // } // } // return false; // } // BSTNode<Type>* Search(BSTNode<Type> *t, const Type &key) // { // if (t == nullptr) // return nullptr; // if (t->data == key) // return t; // else if (key < t->data) // return Search(t->leftChild, key); // else // return Search(t->rightChild, key); // } // void Sort(BSTNode<Type> *t) // { // if (t != nullptr) // { // Sort(t->leftChild); // cout << t->data << " "; // Sort(t->rightChild); // } // } // void SortPair(BSTNode<Type> *t) // { // if (t != nullptr) // { // SortPair(t->leftChild); // cout << (t->data).first << ":" << (t->data).second << endl; // SortPair(t->rightChild); // } // } // void MakeEmpty(BSTNode<Type> *&t) // { // if (t != nullptr) // { // MakeEmpty(t->leftChild); // MakeEmpty(t->rightChild); // delete t; // } // // } //private: // BSTNode<Type> *root; // //}; // //void main() //{ // //key value ֵ // pair<int, string> v1 = { 1, "abc" }; //stu_id --> name // //cout<<v1.first<<" : "<<v1.second<<endl; // pair<int, string> v2 = { 4, "xyz" }; // pair<int, string> v3 = { 2, "hjk" }; // // BST<pair<int, string>> bst; // bst.Insert(v1); // bst.Insert(v2); // bst.Insert(v3); // // bst.SortPair(); // //}
true
46dfb1f00adb9316afe11edb5b1b1baaaf4f8786
C++
Justin-Singh125125/CISP-360
/CISP 360/Problem set #2/6.cpp
UTF-8
172
2.53125
3
[]
no_license
#include <iostream> using namespace std; int main() { int units; float mass; double weight; units = 4; mass = 34.2; units = mass; cout <<units; return 0; }
true
d41c952566dd64780b82ee4d69d94fef4957ae59
C++
lewellen/proceduralEnvironment
/src/Vector.cpp
UTF-8
1,335
3.46875
3
[]
no_license
#include <cstdio> #include <cmath> #include "Vector.h" #define PI 3.14159265 Vector::Vector() { x = y = z = 0; } Vector::Vector(Vector* v) { if (v == NULL) return; x = v->x; y = v->y; z = v->z; } Vector::Vector(float _x, float _y, float _z) { x = _x; y = _y; z = _z; } Vector* Vector::Cross(Vector* b) { Vector* v = new Vector( (y * b->z - z * b->y), -(x * b->z - z * b->x), (x * b->y - y * b->x) ); return v; } float Vector::Inner(Vector* b) { return x * b->x + y * b->y + z * b->z; } float Vector::Magnitude() { return sqrtf(x*x + y*y + z*z); } Vector* Vector::Normalize() { float n = Magnitude(); if (n == 0) return this; return Scale(1.0 / n); } void Vector::RotateAboutX(int deg) { float rad = deg / 180.0 * PI; float s = sin(rad); float c = cos(rad); float _y = y; float _z = z; y = _y * c - _z * s; z = _y * s + _z * c; } void Vector::RotateAboutY(int deg) { float rad = deg / 180.0 * PI; float s = sin(rad); float c = cos(rad); float _x = x; float _z = z; x = _x * c + _z * s; z = -_x * s + _z * c; } void Vector::RotateAboutZ(int deg) { float rad = deg / 180.0 * PI; float s = sin(rad); float c = cos(rad); float _x = x; float _y = y; x = _x * c - _y * s; y = _x * s + _y * c; } Vector* Vector::Scale(float a) { x *= a; y *= a; z *= a; return this; }
true
cdf65e973c9bb21a9a0d3c85c7d3ad8b4852741f
C++
AbelTesfaye/Competitive-Programming
/week 9/nonDecreasingArray.cpp
UTF-8
1,044
2.53125
3
[]
no_license
class Solution { public: bool checkPossibility(vector<int>& nums) { vector<int> lModified, rModified; lModified.push_back(nums[0]); rModified.push_back(nums[0]); bool isModified = false; for(int i = 1; i < nums.size(); i++){ int p = nums[i - 1], c = nums[i]; if(c < p){ if(isModified) return false; lModified.back() = c; lModified.push_back(c); rModified.push_back(rModified.back()); isModified = true; } else { lModified.push_back(c); rModified.push_back(c); } } bool isLModBad = false, isRModBad = false; for(int i = 1; i < nums.size(); i++){ isLModBad |= lModified[i] < lModified[i-1]; isRModBad |= rModified[i] < rModified[i-1]; } if(isLModBad && isRModBad) return false; return true; } };
true
30fa4429f543bb363a8639892c3716f6f229796f
C++
martinamalberti/ECAL
/Calibration/CommonTools/templateUtils.cc
UTF-8
1,207
2.875
3
[]
no_license
#include "templateUtils.h" /*** double crystall ball ***/ double crystalBallLowHigh(double* x, double* par) { //[0] = N //[1] = mean //[2] = sigma //[3] = alpha //[4] = n //[5] = alpha2 //[6] = n2 //[7] = scale //double xx = x[0] * par[7]; double xx = x[0]; double mean = par[1]; double sigma = par[2]; double alpha = par[3]; double n = par[4]; double alpha2 = par[5]; double n2 = par[6]; if( (xx-mean)/sigma > fabs(alpha) ) { double A = pow(n/fabs(alpha), n) * exp(-0.5 * alpha*alpha); double B = n/fabs(alpha) - fabs(alpha); // return par[0] * par[7] * A * pow(B + (xx-mean)/sigma, -1.*n); return par[0] * A * pow(B + (xx-mean)/sigma, -1.*n); } else if( (xx-mean)/sigma < -1.*fabs(alpha2) ) { double A = pow(n2/fabs(alpha2), n2) * exp(-0.5 * alpha2*alpha2); double B = n2/fabs(alpha2) - fabs(alpha2); // return par[0] * par[7] * A * pow(B - (xx-mean)/sigma, -1.*n2); return par[0] * A * pow(B - (xx-mean)/sigma, -1.*n2); } else { //return par[0] * par[7] * exp(-1. * (xx-mean)*(xx-mean) / (2*sigma*sigma) ); return par[0] * exp(-1. * (xx-mean)*(xx-mean) / (2*sigma*sigma) ); } }
true
1824929aa8ec214c83771832b79c70d33180f702
C++
daimonster/Graduate-Life
/C++primer/1708262_stock10.h
UTF-8
2,251
3.875
4
[]
no_license
/*析构函数 用构造函数创建对象后,程序负责跟踪该对象,直到其过期为止。对象过期时,程序将自动调用一个特殊的成员函数:析构函数/析构函数完成清理工作。 例如,如果构造函数使用new来分配内存,则析构函数将使用delete来释放内存。Stock的构造函数没有使用new,因此析构函数实际上没有要完成的任务。在这种情况要,只需要让编译器生成一个什么都不做的隐私析构函数即可 和构造函数一样析构函数的名称也很特殊:在类名前加上~.因此,Stock类的析构函数为~Stock().另外,和构造函数一样,异构函数也可以没有返回值和声明类型。与构造函数不同的是,析构函数没有参数,因此Stock的原型必须是这样的: ~Stock() 可以将它编写为不执行任何操作的函数 Stock::~Stock(){} 什么时候应该调用析构函数呢?这由编译器决定,通常不应在代码中显式第调用析构函数。如果创建的是静态存储来对象,则其析构函数将在程序结束时自动被调用。如果创建的是自动存储类对象,则其析构函数将在程序执行完代码块是自动被调用。如果对象是通过new创建的,则它将驻留在栈内存或自由存取中,当使用delete来释放内存是,其析构函数将自动被调用。最后程序可以创建临时对象来完成特定的操作,在这种情况下,程序将在结束对象的使用时自动调用其析构函数 由于在对对象过期时析构函数将自动被调用,因此必须右一个析构函数。如果程序员没有提供析构函数,编译器将隐式第声明一个默认析构函数,并在发现导致对象被删除的代码后,提供默认析构函数的定义*/ #ifndef STOCK10_H_ #define STOCK10_H_ #include<string> class Stock { private: std::string company; long shares; double share_val; double total_val; void set_tot(){total_val=shares*share_val;} public: Stock(); Stock(const std::string&co,long n=0,double pr=0.0); ~Stock(); void buy(long num,double price); void sell(long num,double price); void update(double price); void show(); }; #endif
true
be00f36ed064f8fe7781e5bb04cd18e4595fdf4f
C++
hoholidayx/Android-App-Security
/appsecurity/src/main/cpp/utils/md5.cpp
UTF-8
7,425
3.109375
3
[]
no_license
#include "md5.h" MD5::MD5() {} MD5::MD5(const string &str) : input_msg(str) {} void MD5::init() { // init the binary message bin_msg.clear(); for (std::size_t i = 0; i < input_msg.size(); ++i) { auto temp = bitset<8>(input_msg[i]); // cout << temp << " " << input_msg[i] << endl; for (int j = 7; j >= 0; --j) { bin_msg.push_back(temp[j]); } } // calculate the binary b bin_b.clear(); b = bin_msg.size(); bitset<64> tempb(bin_msg.size()); // cout << "tempb: " << tempb << endl; for (int i = 63; i >= 0; --i) { bin_b.push_back(tempb[i]); } } void MD5::showBinmsg(const vector<bool> &msg) { for (unsigned int i = 0; i < msg.size(); ++i) { cout << msg[i]; } cout << endl; cout << msg.size(); } const string MD5::getDigest() { init(); // Step 1. Append Padding Bits padding(); // Step 2. Append Length appendLength(); // Step 3. Initialize MD Buffer A = 0x67452301; B = 0xefcdab89; C = 0x98badcfe; D = 0x10325476; // Step 4. Process Message in 16-Word Blocks int L = bin_msg.size() / 512; for (int i = 0; i < L; ++i) { transform(i); } // cout << "basic transform" << endl // << "A:" << bitset<32>(A) << endl // << "B:" << bitset<32>(B) << endl // << "C:" << bitset<32>(C) << endl // << "D:" << bitset<32>(D) << endl; // Step 5. Output return to_str(); } void MD5::padding() { int diff; if (b % 512 < 448) { diff = 448 - b % 512; } else { diff = 960 - b % 512; } // cout << b << endl << diff << endl; bin_msg.push_back(1); vector<bool> pad(diff - 1, 0); bin_msg.insert(bin_msg.end(), pad.begin(), pad.end()); sort_little_endian(); } void MD5::sort_little_endian() { // in each word, all 4 bytes should be sorted as little-endian // That means: // in the original msg: 00000001 00000010 00000011 00000100 // after the sort: 00000100 00000011 00000010 00000001 int wordnums = bin_msg.size() / 32; vector<bool> ret; for (int i = 0; i < wordnums; ++i) { vector<bool> word(bin_msg.begin() + i * 32, bin_msg.begin() + (i + 1) * 32); ret.insert(ret.end(), word.begin() + 24, word.end()); ret.insert(ret.end(), word.begin() + 16, word.begin() + 24); ret.insert(ret.end(), word.begin() + 8, word.begin() + 16); ret.insert(ret.end(), word.begin(), word.begin() + 8); } bin_msg.clear(); bin_msg.insert(bin_msg.end(), ret.begin(), ret.end()); } void MD5::appendLength() { bin_msg.insert(bin_msg.end(), bin_b.begin() + 32, bin_b.end()); bin_msg.insert(bin_msg.end(), bin_b.begin(), bin_b.begin() + 32); }; void MD5::decode(int beginIndex, bit32 *x) { // prepare each 512 bits part in the x[16], and use the x[] for the // transform vector<bool>::const_iterator st = bin_msg.begin() + beginIndex; vector<bool>::const_iterator ed = bin_msg.begin() + beginIndex + 512; vector<bool> cv(st, ed); // cout << cv.size() << endl; // for (int i = 0; i < 512; ++i) { // if (i % 32 == 0) cout << endl; // cout << cv[i]; // } for (int i = 0; i < 16; ++i) { vector<bool>::const_iterator first = cv.begin() + 32 * i; vector<bool>::const_iterator last = cv.begin() + 32 * (i + 1); vector<bool> newvec(first, last); x[i] = convertToBit32(newvec); } // for (int i = 0; i < 16; ++i) { // if (i % 4 == 0) cout << endl; // cout << bitset<32>(x[i]) << " "; // } } bit32 MD5::convertToBit32(const vector<bool> &a) { // convert a 32 bits long vector<bool> to bit32(int) type int partlen = 32; bit32 res = 0; for (int i = 0; i < partlen; ++i) { res = res | (a[i] << (partlen - i - 1)); } return res; } void MD5::transform(int beginIndex) { bit32 AA = A, BB = B, CC = C, DD = D; bit32 x[16]; decode(512 * beginIndex, x); /* Round 1 */ FF(A, B, C, D, x[0], S11, 0xd76aa478); FF(D, A, B, C, x[1], S12, 0xe8c7b756); FF(C, D, A, B, x[2], S13, 0x242070db); FF(B, C, D, A, x[3], S14, 0xc1bdceee); FF(A, B, C, D, x[4], S11, 0xf57c0faf); FF(D, A, B, C, x[5], S12, 0x4787c62a); FF(C, D, A, B, x[6], S13, 0xa8304613); FF(B, C, D, A, x[7], S14, 0xfd469501); FF(A, B, C, D, x[8], S11, 0x698098d8); FF(D, A, B, C, x[9], S12, 0x8b44f7af); FF(C, D, A, B, x[10], S13, 0xffff5bb1); FF(B, C, D, A, x[11], S14, 0x895cd7be); FF(A, B, C, D, x[12], S11, 0x6b901122); FF(D, A, B, C, x[13], S12, 0xfd987193); FF(C, D, A, B, x[14], S13, 0xa679438e); FF(B, C, D, A, x[15], S14, 0x49b40821); /* Round 2 */ GG(A, B, C, D, x[1], S21, 0xf61e2562); GG(D, A, B, C, x[6], S22, 0xc040b340); GG(C, D, A, B, x[11], S23, 0x265e5a51); GG(B, C, D, A, x[0], S24, 0xe9b6c7aa); GG(A, B, C, D, x[5], S21, 0xd62f105d); GG(D, A, B, C, x[10], S22, 0x2441453); GG(C, D, A, B, x[15], S23, 0xd8a1e681); GG(B, C, D, A, x[4], S24, 0xe7d3fbc8); GG(A, B, C, D, x[9], S21, 0x21e1cde6); GG(D, A, B, C, x[14], S22, 0xc33707d6); GG(C, D, A, B, x[3], S23, 0xf4d50d87); GG(B, C, D, A, x[8], S24, 0x455a14ed); GG(A, B, C, D, x[13], S21, 0xa9e3e905); GG(D, A, B, C, x[2], S22, 0xfcefa3f8); GG(C, D, A, B, x[7], S23, 0x676f02d9); GG(B, C, D, A, x[12], S24, 0x8d2a4c8a); /* Round 3 */ HH(A, B, C, D, x[5], S31, 0xfffa3942); HH(D, A, B, C, x[8], S32, 0x8771f681); HH(C, D, A, B, x[11], S33, 0x6d9d6122); HH(B, C, D, A, x[14], S34, 0xfde5380c); HH(A, B, C, D, x[1], S31, 0xa4beea44); HH(D, A, B, C, x[4], S32, 0x4bdecfa9); HH(C, D, A, B, x[7], S33, 0xf6bb4b60); HH(B, C, D, A, x[10], S34, 0xbebfbc70); HH(A, B, C, D, x[13], S31, 0x289b7ec6); HH(D, A, B, C, x[0], S32, 0xeaa127fa); HH(C, D, A, B, x[3], S33, 0xd4ef3085); HH(B, C, D, A, x[6], S34, 0x4881d05); HH(A, B, C, D, x[9], S31, 0xd9d4d039); HH(D, A, B, C, x[12], S32, 0xe6db99e5); HH(C, D, A, B, x[15], S33, 0x1fa27cf8); HH(B, C, D, A, x[2], S34, 0xc4ac5665); /* Round 4 */ II(A, B, C, D, x[0], S41, 0xf4292244); II(D, A, B, C, x[7], S42, 0x432aff97); II(C, D, A, B, x[14], S43, 0xab9423a7); II(B, C, D, A, x[5], S44, 0xfc93a039); II(A, B, C, D, x[12], S41, 0x655b59c3); II(D, A, B, C, x[3], S42, 0x8f0ccc92); II(C, D, A, B, x[10], S43, 0xffeff47d); II(B, C, D, A, x[1], S44, 0x85845dd1); II(A, B, C, D, x[8], S41, 0x6fa87e4f); II(D, A, B, C, x[15], S42, 0xfe2ce6e0); II(C, D, A, B, x[6], S43, 0xa3014314); II(B, C, D, A, x[13], S44, 0x4e0811a1); II(A, B, C, D, x[4], S41, 0xf7537e82); II(D, A, B, C, x[11], S42, 0xbd3af235); II(C, D, A, B, x[2], S43, 0x2ad7d2bb); II(B, C, D, A, x[9], S44, 0xeb86d391); A = A + AA; B = B + BB; C = C + CC; D = D + DD; } const string MD5::to_str() { // Output in Big-Endian // For a value 0x6789abcd // Output as "cdab8967" bit32 input[4]; input[0] = A; input[1] = B; input[2] = C; input[3] = D; string ret; char buffer[4]; for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) { snprintf(buffer, 4, "%02x", input[i] >> j * 8 & 0xff); ret += buffer; } } return ret; }
true