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
5e475c209e8d7610c6dffdcda301dcae3cefaf72
C++
YangYang/LibraryManager
/LibraryManager/TransformPlus.cpp
UTF-8
1,744
2.65625
3
[]
no_license
#include "StdAfx.h" #include "TransformPlus.h" TransformPlus::TransformPlus(void) { } TransformPlus::~TransformPlus(void) { } //CString CString TransformPlus::toCString(string str){ CString cstr(str.c_str()); return cstr; } CString TransformPlus::toCString(double dbl){ CString t; t.Format(L"%f",dbl); return t; } CString TransformPlus::toCString(int i){ CString t; t.Format(L"%d",i); return t; } //String string TransformPlus::toString(CString cstr){ USES_CONVERSION; string str = T2A(( cstr.GetBuffer())); return str; } string TransformPlus::toString(double dbl){ char buffer[20]; sprintf_s(buffer, "%f", dbl); string str = buffer; return buffer; } string TransformPlus::toString(int i){ char str[8]; int length = sprintf(str, "%05X", i); return str; } string TransformPlus::toString(TCHAR *STR){ int iLen = WideCharToMultiByte(CP_ACP, 0,STR, -1, NULL, 0, NULL, NULL); char* chRtn =new char[iLen*sizeof(char)]; WideCharToMultiByte(CP_ACP, 0, STR, -1, chRtn, iLen, NULL, NULL); string str(chRtn); return str; } string TransformPlus::toString(char* c){ string s(c); return s; } //double double TransformPlus::toDouble(CString cstr){ return _wtof(cstr); } double TransformPlus::toDouble(string str){ double value = atof(str.c_str()); return value; } double TransformPlus::toDouble(int i){ double dbl = (double)i; return dbl; } //int int TransformPlus::toInt(CString cstr){ int i = _ttoi(cstr); return i; } int TransformPlus::toInt(string str){ int n = atoi(str.c_str()); return n; } int TransformPlus::toInt(double dbl){ int i = (int)dbl; return i; } long TransformPlus::toLong(CString cstr) { long L=_ttoi(cstr); return L; } const char* toConstChar(string s){ return s.c_str(); }
true
485ceb655eb89ec4240c14297037f23c4bfd6fe0
C++
blue-yonder/turbodbc
/cpp/turbodbc/Library/turbodbc/description.h
UTF-8
1,640
2.96875
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
#pragma once #include <turbodbc/field.h> #include <turbodbc/type_code.h> #include <cpp_odbc/multi_value_buffer.h> #ifdef _WIN32 #include <windows.h> #endif #include <sqltypes.h> namespace turbodbc { /** * @brief Represents all information to bind a buffer to a column or parameter and * how to store/load values */ class description { public: /** * @brief Returns the size of an element in a buffer */ std::size_t element_size() const; /** * @brief Returns the type code for the associated C data type */ SQLSMALLINT column_c_type() const; /** * @brief Returns the type code for the associated SQL column data type */ SQLSMALLINT column_sql_type() const; /** * @brief Returns the number of digits a parameter supports */ SQLSMALLINT digits() const; /** * @brief Retrieve a code which indicates this field's type */ type_code get_type_code() const; /** * @brief Retrieve the name associated with the described column or parameter */ std::string const & name() const; /** * @brief Retrieve whether null values are supported or not */ bool supports_null_values() const; description (description const &) = delete; description & operator=(description const &) = delete; virtual ~description(); protected: description(); description(std::string name, bool supports_null); private: virtual std::size_t do_element_size() const = 0; virtual SQLSMALLINT do_column_c_type() const = 0; virtual SQLSMALLINT do_column_sql_type() const = 0; virtual SQLSMALLINT do_digits() const = 0; virtual type_code do_get_type_code() const = 0; std::string name_; bool supports_null_; }; }
true
727e64e0b6533ea2f9ba6e1f35d1d8965a87c215
C++
lederle-david/work-examples
/OOP244-Final-Project/Date.cpp
UTF-8
2,350
3.09375
3
[]
no_license
// OOP244 Final Project - MS6 // File: Date.cpp // Date: 2016/04/04 // David Lederle // 104026158 dlederle@myseneca.ca #include <iomanip> #include <iostream> using namespace std; #include "Date.h" #include "general.h" namespace sict{ Date::Date(){ year_ = 0; mon_ = 0; day_ = 0; readErrorCode_ = NO_ERROR; } Date::Date(int year, int month, int day){ year_ = year; mon_ = month; day_ = day; readErrorCode_ = NO_ERROR; } int Date::value()const{ return year_ * 372 + mon_ * 31 + day_; } void Date::errCode(int errorCode){ readErrorCode_ = errorCode; } bool Date::operator==(const Date& D)const{ return (value() == D.value()); } bool Date::operator!=(const Date& D)const{ return !(value() == D.value()); } bool Date::operator<(const Date& D)const{ return (value() < D.value()); } bool Date::operator>(const Date& D)const{ return (value() > D.value()); } bool Date::operator<=(const Date& D)const{ return (value() <= D.value()); } bool Date::operator>=(const Date& D)const{ return (value() >= D.value()); } int Date::mdays()const{ int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, -1 }; int mon = mon_ >= 1 && mon_ <= 12 ? mon_ : 13; mon--; return days[mon] + int((mon == 1)*((year_ % 4 == 0) && (year_ % 100 != 0)) || (year_ % 400 == 0)); } int Date::errCode()const{ return readErrorCode_; } bool Date::bad()const{ return readErrorCode_; } std::istream& Date::read(std::istream& istr){ char placeHolder; istr >> year_ >> placeHolder >> mon_ >> placeHolder >> day_; if (cin.fail()){ errCode(CIN_FAILED); } else{ if (year_ < MIN_YEAR || year_ > MAX_YEAR){ errCode(YEAR_ERROR); } else if (mon_ < 1 || mon_ > 12){ errCode(MON_ERROR); } else if (day_ < 1 || day_ > mdays()){ errCode(DAY_ERROR); } } return istr; } std::ostream& Date::write(std::ostream& ostr)const{ ostr << year_ << '/' << setw(2)<< setfill('0') << mon_ << '/' << setw(2) << setfill('0') << day_; return ostr; } std::ostream& operator<<(std::ostream& ostr, const Date& D){ D.write(ostr); return ostr; } std::istream& operator>>(std::istream& istr, Date& D){ D.read(istr); return istr; } }
true
441ddc0444d251a16e91708f6a8b46364ba09cad
C++
Terry-Ma/Leetcode
/面试题05-替换空格-a.cpp
UTF-8
265
2.609375
3
[]
no_license
class Solution { public: string replaceSpace(string s) { string result; for(auto i : s){ if(i == ' ') result += "%20"; else result += i; } return result; } };
true
f25ea226068356f25a28535159a3502fdabf30b8
C++
zaeval/data-structure-example
/data-structure-lab/data-structure-lab/adt_queue.hpp
UTF-8
861
2.96875
3
[ "MIT" ]
permissive
// // adt_queue.hpp // data-structure-lab // // Created by 홍승의 on 2018. 3. 26.. // Copyright © 2018년 홍승의. All rights reserved. // #ifndef adt_queue_hpp #define adt_queue_hpp #include <iostream> using namespace std; template<typename T> class Queue{ private: int top; int size; int bottom; T *arr; void resize() { size_t newSize = ++size; T* newArr = new T[newSize]; memcpy( newArr, arr, size * sizeof(T) ); size = newSize; delete [] arr; arr = newArr; } public: Queue(); Queue(int size); ~Queue(); void reserve(int size); bool isFull(); int getTop(); int getBottom(); int getSize(); bool isEmpty(); void push(T input); T getTopValue(); T pop(); T getBottomValue(); }; #endif /* adt_queue_hpp */
true
19ce7ec314658964b00e71342c99344acd5bd79a
C++
rehassachdeva/coding-practice
/leet/trees/complete-binary-tree-inserter.cpp
UTF-8
1,291
3.609375
4
[]
no_license
// Linearising / Linear complete binary tree /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class CBTInserter { public: CBTInserter(TreeNode* root) { tree.emplace_back(root); for (int i=0; i<tree.size(); i++) { if (tree[i]->left) tree.emplace_back(tree[i]->left); if (tree[i]->right) tree.emplace_back(tree[i]->right); } } int insert(int v) { int n=tree.size(); tree.emplace_back(new TreeNode(v)); int par=(n-1)/2; if (n%2==0) tree[par]->right = tree[n]; else tree[par]->left = tree[n]; return tree[par]->val; } TreeNode* get_root() { return tree[0]; } vector<TreeNode*> tree; }; /** * Your CBTInserter object will be instantiated and called as such: * CBTInserter* obj = new CBTInserter(root); * int param_1 = obj->insert(v); * TreeNode* param_2 = obj->get_root(); */
true
b92b09a51194afaa7962bebafa6acb4fc3b1eef2
C++
LQNL/Design-Mode
/C++设计模式/Template method/code/template1_app.cpp
UTF-8
358
2.734375
3
[]
no_license
// 应用程序开发人员 class Appplication { public: bool Step2(){ //.... } bool Step4(){ //... } }; // 应用程序使用库 template1_lib.cpp int main() { Library lib(); Application app(); lib.Step1(); if (app.Step2()){ lib.Step3(); } for (int i = 0; i < 4; i++){ app.Step4(); } lib.Step5(); }
true
1d19d0882485b10ab5abfe56e9151279c7c471f6
C++
CJBussey/zug
/zug/detail/tuple_utils.hpp
UTF-8
1,434
2.828125
3
[ "BSL-1.0" ]
permissive
// // zug: transducers for C++ // Copyright (C) 2019 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <tuple> #include <type_traits> namespace zug { namespace detail { template <std::size_t Index, std::size_t Max> struct tuple_all_neq_t { template <typename Tuple1T, typename Tuple2T> bool operator()(Tuple1T&& t1, Tuple2T&& t2) { return std::get<Index>(std::forward<Tuple1T>(t1)) != std::get<Index>(std::forward<Tuple2T>(t2)) && tuple_all_neq_t<Index + 1, Max>{}(std::forward<Tuple1T>(t1), std::forward<Tuple2T>(t2)); } }; template <std::size_t Max> struct tuple_all_neq_t<Max, Max> { template <typename Tuple1T, typename Tuple2T> bool operator()(Tuple1T&&, Tuple2T&&) { return true; } }; template <typename Tuple1T, typename Tuple2T> bool tuple_all_neq(Tuple1T&& t1, Tuple2T&& t2) { constexpr auto size1 = std::tuple_size<std::decay_t<Tuple1T>>{}; constexpr auto size2 = std::tuple_size<std::decay_t<Tuple2T>>{}; static_assert(size1 == size2, ""); using impl_t = tuple_all_neq_t<0u, (size1 > size2 ? size2 : size1)>; return impl_t{}(std::forward<Tuple1T>(t1), std::forward<Tuple2T>(t2)); } } // namespace detail } // namespace zug
true
94b7c7824f1368064978fc7b44815fecf9930034
C++
Ares7/efficientAlgorithms
/hw1/t3/main.cpp
UTF-8
873
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include "regex" using namespace std; int main() { std::ios::sync_with_stdio(false); int t = 1; int n = 3; cin>>t; cin>>n; cin.ignore(); vector<string> results; string line; for (int i = 0; i < n; ++i) { getline(cin, line); results.push_back(line); } // ich bin ein student // a potent element went through a vent // ein zentner enten enthaelt keine studenten for (int j = 0; j < n; ++j) { results[j] = regex_replace(results[j], regex("enten"), "ierende"); results[j] = regex_replace(results[j], regex("entin"), "ierende"); results[j] = regex_replace(results[j], regex("ent"), "ierender"); } cout << "Case #" << t << ":" << endl; for (int i = 0; i < n; ++i) { cout << results[i] << endl; } return 0; }
true
2b94b36bfe6eebb1e0b2c8eb7a80a6183e5d97df
C++
CyJay96/Lab-cpp
/lab_9/lab_9.1/functions.cpp
UTF-8
1,206
3.390625
3
[]
no_license
#include "functions.h" bool search_char(string str, char ch) { for (int i = 0; i < str.length(); ++i) { if (ch == str[i]) { return true; } } return false; } bool search_str(string s1, string s2) { for (int i = 0; i < s2.length(); ++i) { if (!search_char(s1, s2[i])) { return false; } } return true; } string select_word(string str, int start_pos) { string current_word = ""; int i = 0; while (!search_char(separators, str[start_pos]) && start_pos < str.length()) { current_word += str[start_pos++]; } return current_word; } void create_arr(vector<string>& words, string current_word) { words.push_back(current_word); } string create_new_str(vector<string>& words) { string new_str = ""; vector<string>::iterator i = words.begin(); while (i != words.end()) { string s1 = *i; string new_str_before = new_str; new_str += s1 + " "; string new_str_after = new_str; vector<string>::iterator j = i + 1; while (j != words.end()) { string s2 = *j; if (search_str(s1, s2)) { new_str += s2 + " "; } ++j; } if (new_str_after == new_str) { new_str = new_str_before; } if (new_str != "") { break; } ++i; } return new_str; }
true
60f45453eb14cd9f9f7f37ef54554797010bb912
C++
xiaoguangcong/WebServer
/base/include/noncopyable.h
UTF-8
442
3.09375
3
[]
no_license
#pragma once // 如果不想让外面的用户直接构造一个类的对象,而希望用户只能构造这个类的子类, // 那你就可以将类的构造函数/析构函数声明为protected,而将类的子类的构造函数/析构函数声明为public class NonCopyable { protected: NonCopyable() {} ~NonCopyable() {} private: NonCopyable(const NonCopyable&); const NonCopyable& operator=(const NonCopyable&); };
true
8979429fc3aebe9532485d68fb6d28820057ecf6
C++
timkwist/CS479
/PA1-Bayes_Classifier/main.cpp
UTF-8
8,853
2.796875
3
[]
no_license
#include <iostream> #include <Eigen/Dense> #include <vector> #include "BayesClassifier.h" #include <iostream> #include <fstream> using namespace Eigen; using namespace std; void writeSamplesToFile(const char* fileName, vector<Vector2f> sampleOne, vector<Vector2f> sampleTwo); int main() { srand(time(NULL)); ofstream generalOutput; generalOutput.open("./results/PA1-Output.txt"); Matrix2f sigmaOne, sigmaTwo; Vector2f muOne, muTwo; float priorOne, priorTwo; BayesClassifier classifier; vector<Vector2f> sampleOne, sampleTwo; vector<Vector2f> sampleMis; int misclassifiedOne, misclassifiedTwo; pair<float, float> chernoffBound; // <index, value> //================================================ // Begin Part One Configuration //================================================ muOne << 1, 1; muTwo << 6, 6; sigmaOne << 2, 0, 0, 2; sigmaTwo << 2, 0, 0, 2; priorOne = priorTwo = 0.5; misclassifiedOne = misclassifiedTwo = 0; sampleOne = classifier.generateSamples(muOne, sigmaOne); sampleTwo = classifier.generateSamples(muTwo, sigmaTwo); //================================================ // End Part One Configuration //================================================ //================================================ // Begin Part One Tests //================================================ for(int i = 0; i < 10000; i++) { if(classifier.classifierCaseOne(sampleOne[i], muOne, muTwo, sigmaOne(0,0), sigmaTwo(0,0)) == 2) { misclassifiedOne++; sampleMis.push_back(sampleOne[i]); } if(classifier.classifierCaseOne(sampleTwo[i], muOne, muTwo, sigmaOne(0,0), sigmaTwo(0,0)) == 1) { misclassifiedTwo++; sampleMis.push_back(sampleTwo[i]); } } writeSamplesToFile("./results/Part-OneA-Misclassified.txt", sampleMis, sampleMis); generalOutput << "================================================\n Part One (A) - (Using the Bayesian Classifier) \n================================================" << endl; generalOutput << "Samples from one misclassified: " << misclassifiedOne << endl; generalOutput << "Samples from two misclassified: " << misclassifiedTwo << endl; generalOutput << "Total misclassified: " << misclassifiedOne + misclassifiedTwo << endl; // Begin Part B Configuration misclassifiedOne = misclassifiedTwo = 0; sampleMis.clear(); priorOne = 0.2; priorTwo = 0.8; // End Part B Configuration for(int i = 0; i < 10000; i++) { if(classifier.classifierCaseOne(sampleOne[i], muOne, muTwo, sigmaOne(0,0), sigmaTwo(0,0), priorOne, priorTwo) == 2) { misclassifiedOne++; sampleMis.push_back(sampleOne[i]); } if(classifier.classifierCaseOne(sampleTwo[i], muOne, muTwo, sigmaOne(0,0), sigmaTwo(0,0), priorOne, priorTwo) == 1) { misclassifiedTwo++; sampleMis.push_back(sampleTwo[i]); } } chernoffBound = classifier.findChernoffBound(muOne, muTwo, sigmaOne, sigmaTwo); generalOutput << "================================================\n Part One (B) - (Using the Bayesian Classifier) \n================================================" << endl; generalOutput << "Samples from one misclassified: " << misclassifiedOne << endl; generalOutput << "Samples from two misclassified: " << misclassifiedTwo << endl; generalOutput << "Total misclassified: " << misclassifiedOne + misclassifiedTwo << endl; generalOutput << "================================================\n Part One - Error Bounds \n================================================" << endl; generalOutput << "With beta = " << chernoffBound.first << " , Chernoff Bound = " << chernoffBound.second << endl; generalOutput << "With beta = 0.5, Bhattacharyya Bound = " << classifier.findBhattacharyyaBound(muOne, muTwo, sigmaOne, sigmaTwo) << endl; writeSamplesToFile("./results/Part-One.txt", sampleOne, sampleTwo); writeSamplesToFile("./results/Part-OneB-Misclassified.txt", sampleMis, sampleMis); //================================================ // End Part One Tests //================================================ //================================================ // Begin Part Two Configuration //================================================ muOne << 1, 1; muTwo << 6, 6; sigmaOne << 2, 0, 0, 2; sigmaTwo << 4, 0, 0, 8; priorOne = priorTwo = 0.5; misclassifiedOne = misclassifiedTwo = 0; sampleOne = classifier.generateSamples(muOne, sigmaOne); sampleTwo = classifier.generateSamples(muTwo, sigmaTwo); sampleMis.clear(); //================================================ // End Part Two Configuration //================================================ //================================================ // Begin Part Two Tests //================================================ for(int i = 0; i < 10000; i++) { if(classifier.classifierCaseThree(sampleOne[i], muOne, muTwo, sigmaOne, sigmaTwo) == 2) { misclassifiedOne++; sampleMis.push_back(sampleOne[i]); } if(classifier.classifierCaseThree(sampleTwo[i], muOne, muTwo, sigmaOne, sigmaTwo) == 1) { misclassifiedTwo++; sampleMis.push_back(sampleTwo[i]); } } generalOutput << "================================================\n Part Two (A) - (Using the Bayesian Classifier) \n================================================" << endl; generalOutput << "Samples from one misclassified: " << misclassifiedOne << endl; generalOutput << "Samples from two misclassified: " << misclassifiedTwo << endl; generalOutput << "Total misclassified: " << misclassifiedOne + misclassifiedTwo << endl; writeSamplesToFile("./results/Part-TwoA-Misclassified.txt", sampleMis, sampleMis); // Begin Part B Configuration misclassifiedOne = misclassifiedTwo = 0; priorOne = 0.2; priorTwo = 0.8; sampleMis.clear(); // End Part B Configuration for(int i = 0; i < 10000; i++) { if(classifier.classifierCaseThree(sampleOne[i], muOne, muTwo, sigmaOne, sigmaTwo, priorOne, priorTwo) == 2) { misclassifiedOne++; sampleMis.push_back(sampleOne[i]); } if(classifier.classifierCaseThree(sampleTwo[i], muOne, muTwo, sigmaOne, sigmaTwo, priorOne, priorTwo) == 1) { misclassifiedTwo++; sampleMis.push_back(sampleTwo[i]); } } chernoffBound = classifier.findChernoffBound(muOne, muTwo, sigmaOne, sigmaTwo); generalOutput << "================================================\n Part Two (B) - (Using the Bayesian Classifier) \n================================================" << endl; generalOutput << "Samples from one misclassified: " << misclassifiedOne << endl; generalOutput << "Samples from two misclassified: " << misclassifiedTwo << endl; generalOutput << "Total misclassified: " << misclassifiedOne + misclassifiedTwo << endl; generalOutput << "================================================\n Part Two - Error Bounds \n================================================" << endl; generalOutput << "With beta = " << chernoffBound.first << " , Chernoff Bound = " << chernoffBound.second << endl; generalOutput << "With beta = 0.5, Bhattacharyya Bound = " << classifier.findBhattacharyyaBound(muOne, muTwo, sigmaOne, sigmaTwo) << endl; writeSamplesToFile("./results/Part-Two.txt", sampleOne, sampleTwo); writeSamplesToFile("./results/Part-TwoB-Misclassified.txt", sampleMis, sampleMis); //================================================ // End Part Two Tests //================================================ //================================================ // Begin Part Three Tests //================================================ misclassifiedOne = misclassifiedTwo = 0; sampleMis.clear(); for(int i = 0; i < 10000; i++) { if(classifier.minimumDistanceClassifier(sampleOne[i], muOne, muTwo) == 2) { misclassifiedOne++; sampleMis.push_back(sampleOne[i]); } if(classifier.minimumDistanceClassifier(sampleTwo[i], muOne, muTwo) == 1) { misclassifiedTwo++; sampleMis.push_back(sampleTwo[i]); } } generalOutput << "================================================\n Part Three (A) - (Using the Minimum Distance Classifier) \n================================================" << endl; generalOutput << "Samples from one misclassified: " << misclassifiedOne << endl; generalOutput << "Samples from two misclassified: " << misclassifiedTwo << endl; generalOutput << "Total misclassified: " << misclassifiedOne + misclassifiedTwo << endl; writeSamplesToFile("./results/Part-Three-Misclassified.txt", sampleMis, sampleMis); generalOutput.close(); } void writeSamplesToFile(const char* fileName, vector<Vector2f> sampleOne, vector<Vector2f> sampleTwo) { ofstream partSpecificOutput; partSpecificOutput.open(fileName); for(unsigned int i = 0; i < sampleOne.size(); i++) { partSpecificOutput << sampleOne[i](0) << "\t" << sampleOne[i](1) << "\t" << sampleTwo[i](0) << "\t" << sampleTwo[i](1) << endl; } partSpecificOutput.close(); }
true
405529a8c320f9a681d1a76771fd9571b2dadcc4
C++
hwangJi-dev/Algorithm_Practice
/algorithm_2178.cpp
UTF-8
921
2.78125
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <queue> using namespace std; int maze[100][100] = { 0 }; bool check[100][100]; int squareCnt[100][100] = { 0 }; int N, M; int dx[] = { 0, 1, 0, -1 }; int dy[] = { -1, 0, 1, 0 }; void bfs(int x, int y) { check[x][y] = true; squareCnt[x][y]++; queue<pair<int, int>> q; q.push({ x, y }); while (!q.empty()) { int xx = q.front().first; int yy = q.front().second; q.pop(); for (int i = 0; i < 4; i++) { int nx = xx + dx[i]; int ny = yy + dy[i]; if (nx >= 0 && nx < N && ny >= 0 && ny < M && !check[nx][ny] && maze[nx][ny] == 1) { check[nx][ny] = true; q.push({ nx, ny }); squareCnt[nx][ny] = squareCnt[xx][yy]+1; } } } } int main() { cin >> N >> M; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { scanf("%1d", &maze[i][j]); } } bfs(0, 0); cout << squareCnt[N - 1][M - 1]; return 0; }
true
3dbf76c40cb12f57ca6875ee9dd3b218cdcae5c6
C++
DenisCarriere/flashloans
/borrower.cpp
UTF-8
951
2.578125
3
[]
no_license
#include <eosio/eosio.hpp> #include <eosio/asset.hpp> #include <flashloans.hpp> #include <eosio.token.hpp> using namespace eosio; using namespace std; class [[eosio::contract]] borrower : public contract { public: using contract::contract; [[eosio::action]] void execute( const extended_asset ext_quantity ) { // trigger execution of flashloan flashloans::borrow_action borrow( "flashloans"_n, { get_self(), "active"_n }); borrow.send( get_self(), ext_quantity, "" ); } [[eosio::on_notify("*::transfer")]] void on_transfer( const name from, const name to, const asset quantity, const string memo ) { // only intercept transfers from flashloans if ( from != "flashloans"_n ) return; // do actions before sending funds back // =====>>>> PLACE YOUR CODE HERE // repay flashloan token::transfer_action transfer( get_first_receiver(), { get_self(), "active"_n }); transfer.send( get_self(), from, quantity, memo ); } };
true
0d7c82032c1174e391f578b5e4cec21097dad6b4
C++
BewareMyPower/Algorithm-Learning
/FindArticul/FindArticul.cpp
GB18030
2,498
3.109375
3
[]
no_license
// FindArticul.cpp: Ѱͼĸ㣬ǿ֧ͨ #include <string> #include <map> #include <list> #include <stack> #include <algorithm> #include <cstdio> typedef std::string Vertex; // õַڵ typedef std::map<Vertex, std::list<Vertex>> AdjList; // ڽӱΪÿ㵽ڽӵӳ typedef AdjList Graph; // ʹڽӱΪͼıʾ typedef std::map<Vertex, int> VexIntMap; // ɽڵ㵽intӳ typedef std::stack<std::pair<Vertex, Vertex>> LineStack; // űߵջ // ʹȫֱ¼Ϣⱻݹã Graph graph; // ڽӱ VexIntMap DFN; // DFSʱÿĴ VexIntMap DFNL; // õڵͨܵ int n0 = 1; // ˳򣬳ʼΪ0 LineStack lines; // ¼ʹı void initAdjList() { graph = Graph { { "A", { "B", "F" } }, { "B", { "A", "C" } }, { "C", { "B", "D", "E", "F" } }, { "D", { "C" } }, { "E", { "C" } }, { "F", { "A", "C", "G", "I", "J" } }, { "G", { "F", "H", "I" } }, { "H", { "G" } }, { "I", { "F", "G", "J" } }, { "J", { "F", "G", "I" } } }; } // v0Ϊǰʵ, prevΪv0֮ǰʵĽڵ void DFSArticul(const Graph& g, const Vertex& v0, const Vertex& prev) { DFN[v0] = DFNL[v0] = n0++; for (const Vertex& vadj : g.at(v0)) { // v0ÿڽӵvadj if (vadj != prev) { // vadjδ±(v0,vadj) if (DFN.count(vadj) == 0) lines.emplace(v0, vadj); // vadjv0ӻر(v0,vadj) else if (DFN[vadj] < DFN[v0]) lines.emplace(v0, vadj); } if (DFN.count(vadj) == 0) { DFSArticul(g, vadj, v0); // ʽݹɺѾDFNL[vadj] if (DFNL[vadj] >= DFN[v0]) { printf("µ2-ͨ\n"); while (true) { auto line = lines.top(); lines.pop(); printf("(%s, %s)\n", line.first.c_str(), line.second.c_str()); if (line.first == v0 && line.second == vadj) break; if (line.first == vadj && line.second == v0) break; } } DFNL[v0] = std::min(DFNL[v0], DFNL[vadj]); } else { // vadjѷζvadjv0 // DFN[vadj]<DFN[v0],(v0, vadj)ڻر if (vadj != prev) DFNL[v0] = std::min(DFNL[v0], DFN[vadj]); } } } int main() { initAdjList(); DFSArticul(graph, "A", ""); return 0; }
true
2f1a57b76faf482c1b525c921e763e1a272b82be
C++
ComiteMexicanoDeInformatica/OMI-Archive
/2022/OMI-presencial/OMI-2022-feliz-encuentro/solutions/sol_sub3.cpp
UTF-8
975
2.796875
3
[]
no_license
#include <iostream> #include <set> using namespace std; #define debugsl(x) std::cout << #x << " = " << x << ", " #define debug(x) debugsl(x) << "\n"; #define MAX 100000 int t, q, l, r, res, acumulado[MAX + 2]; string st; int main() { std::cin >> t >> q >> st; // HAZ UNA CUENTA ACUMULADA DE LOS ENCUENTROS QUE HA HABIDO, ES DECIR, // acumulado[i] = NUMERO DE ENCUENTROS DESDE LA PRIMERA POSICION HASTA LA // POSICION i for (int i = 1; i < t; ++i) { acumulado[i] = acumulado[i - 1]; // SEGURO LLEVA LOS MISMOS ENCUENTROS QUE // LA POSICION ANTERIOR if (st[i] == st[i - 1]) ++acumulado[i]; // SI EL ES UN ENCUENTRO, ENTONCES ACUMULA UNO MAS } // PARA CADA PREGUNTA TE PIDEN LOS ACUMULADOS DESDE LA POSICION 1 HASTA r, // JUSTO ESE VALOR ES EL QUE SE TIENE EN EL ARREGLO DE ACUMULADOS. while (q--) { std::cin >> l >> r; --l; --r; std::cout << acumulado[r] << "\n"; } return 0; }
true
fef2bf9d0740a44e3af9710f27e82e14778810bb
C++
Game-Made-with-OpenGL/OpenGL-Game
/vs/Lesson07/Demo.cpp
UTF-8
5,777
2.53125
3
[]
no_license
#include "Demo.h" Demo::Demo() { } Demo::~Demo() { if (Mix_Playing(sfx_channel) == 0) { Mix_FreeChunk(sound); } if (music != NULL) { Mix_FreeMusic(music); } Mix_CloseAudio(); } void Demo::Init() { BuildInfoSprite(); InitAudio(); AddInputs(); } void Demo::Update(float deltaTime) { if (IsKeyDown("Quit")) { SDL_Quit(); exit(0); } if (Mix_Playing(sfx_channel) == 0 && IsKeyDown("SFX")) { sfx_channel = Mix_PlayChannel(-1, sound, 0); if (sfx_channel == -1) { Err("Unable to play WAV file: " + string(Mix_GetError())); } } if (IsKeyDown("BGM")) { if (Mix_PlayingMusic() == 0) { //Play the music Mix_PlayMusic(music, -1); SDL_Delay(150); } //If music is being played else { //If the music is paused if (Mix_PausedMusic() == 1) { //Resume the music Mix_ResumeMusic(); SDL_Delay(150); } //If the music is playing else { //Pause the music Mix_PauseMusic(); SDL_Delay(150); } } } } void Demo::Render() { //Setting Viewport glViewport(0, 0, GetScreenWidth(), GetScreenHeight()); //Clear the color and depth buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //Set the background color glClearColor(1.0f, 1.0f, 1.0f, 1.0f); DrawInfoSprite(); } void Demo::InitAudio() { int flags = MIX_INIT_MP3 | MIX_INIT_FLAC | MIX_INIT_OGG; if (flags != Mix_Init(flags)) { Err("Unable to initialize mixer: " + string(Mix_GetError())); } int audio_rate = 22050; Uint16 audio_format = AUDIO_S16SYS; int audio_channels = 2; int audio_buffers = 4096; if (Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) != 0) { Err("Unable to initialize audio: " + string(Mix_GetError())); } music = Mix_LoadMUS("bensound-funkyelement.ogg"); if (music == NULL) { Err("Unable to load Music file: " + string(Mix_GetError())); } sound = Mix_LoadWAV("grsites.com_whirls.wav"); if (sound == NULL) { Err("Unable to load WAV file: " + string(Mix_GetError())); } } void Demo::AddInputs() { InputMapping("Quit", SDLK_ESCAPE); InputMapping("BGM", SDLK_m); InputMapping("SFX", SDLK_s); } void Demo::BuildInfoSprite() { this->program = BuildShader("infoSprite.vert", "infoSprite.frag"); UseShader(this->program); // Load and create a texture glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object // Set texture filtering glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Load, create texture int width, height; unsigned char* image = SOIL_load_image("info.png", &width, &height, 0, SOIL_LOAD_RGBA); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); SOIL_free_image_data(image); glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture. // Set up vertex data (and buffer(s)) and attribute pointers frame_width = (float)width; frame_height = (float)height; GLfloat vertices[] = { // Positions // Colors // Texture Coords 1, 1, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, // Bottom Right 1, 0, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Top Right 0, 0, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, // Top Left 0, 1, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f // Bottom Left }; GLuint indices[] = { // Note that we start from 0! 0, 3, 2, 1 }; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // Position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0); glEnableVertexAttribArray(0); // Color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(1); // TexCoord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glBindVertexArray(0); // Unbind VAO // Set orthographic projection mat4 projection; projection = ortho(0.0f, static_cast<GLfloat>(GetScreenWidth()), static_cast<GLfloat>(GetScreenHeight()), 0.0f, -1.0f, 1.0f); glUniformMatrix4fv(glGetUniformLocation(this->program, "projection"), 1, GL_FALSE, value_ptr(projection)); // set sprite position, gravity, velocity xpos = (GetScreenWidth() - frame_width) / 2; ypos = (GetScreenHeight() - frame_height) / 2; } void Demo::DrawInfoSprite() { // Enable transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Bind Textures using texture units glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); // Activate shader UseShader(this->program); glUniform1i(glGetUniformLocation(this->program, "ourTexture"), 0); mat4 model; // Translate sprite along x-axis model = translate(model, vec3(xpos, ypos, 0.0f)); // Scale sprite model = scale(model, vec3(frame_width, frame_height, 1)); glUniformMatrix4fv(glGetUniformLocation(this->program, "model"), 1, GL_FALSE, value_ptr(model)); // Draw sprite glBindVertexArray(VAO); glDrawElements(GL_QUADS, 4, GL_UNSIGNED_INT, 0); glBindVertexArray(0); glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture. glDisable(GL_BLEND); } int main(int argc, char** argv) { Engine::Game &game = Demo(); game.Start("Audio Demo : SDL Mixer", 800, 600, false, WindowFlag::WINDOWED, 60, 1); return 0; }
true
fe8926ef436892aa7f6bff89a828b00733ff316b
C++
mingchengzack/Phong-Model-with-Gouraud-Shading
/main.cpp
UTF-8
13,465
2.578125
3
[]
no_license
#include <GL/glut.h> #include <cstdlib> #include <cmath> #include <fstream> #include <iostream> #include <cstdlib> #include <ctime> #include <string> #include <algorithm> #include "glm/glm.hpp" #include "object.h" #include "utility.h" #include "slider.h" using namespace std; GLvoid *font_style = GLUT_BITMAP_HELVETICA_12; //font style void display(); //display function float* PixelBuffer; //the pixel buffer for normal shading float* halfTone; //the pixel buffer for half toning int WinW = 900; //window width int WinH = 900; //window height int option = 1; //half-tone on or off glm::vec3 viewpoint; //view position glm::vec3 light; //light position //phong model constants glm::vec3 ka; glm::vec3 kd; glm::vec3 ks; float n; int select = -1; float Ia, IL, K; vector<slider> sliders; //sliders vector<object*> objects; //3D objects vector<triangle*> faces; //all the triangles void sortXY(); //sort the triangles using z depths void sortXZ(); //sort the triangles using y depths void sortYZ(); //sort the triangles using x depths void KeyBoardFunc(unsigned char key, int x, int y); //the keyboard function void MouseFunc(int button, int state, int x, int y); //the mouse function void MotionFunc(int x, int y); //mouse motion function float* halfToning(); //compute the half tone buffer void initSliders(); //initialize sliders void drawPlaneLabel(); //draw the plane labels and grid void drawSliders(); //draw the sliders void projectObjects(); //shading the object and compute half toning void display(); //display function //sort all the triangles using z values (min value first) void sortXY() { float zmin; unsigned int index; triangle* tri; //insertion sort for (unsigned int i = 0; i < faces.size() - 1; i++) { zmin = faces[i]->findZmin(); index = i; for (unsigned int j = i + 1; j < faces.size(); j++) { if (faces[j]->findZmin() <= zmin) { zmin = faces[j]->findZmin(); index = j; } } tri = faces[index]; faces.erase(faces.begin() + index); faces.insert(faces.begin() + i, tri); } } //sort all the triangles using y values (min value first) void sortXZ() { float ymax; unsigned int index; triangle* tri; //insertion sort for (unsigned int i = 0; i < faces.size() - 1; i++) { ymax = faces[i]->findYmax(); index = i; for (unsigned int j = i + 1; j < faces.size(); j++) { if (faces[j]->findYmax() >= ymax) { ymax = faces[j]->findYmax(); index = j; } } tri = faces[index]; faces.erase(faces.begin() + index); faces.insert(faces.begin() + i, tri); } } //sort all the triangles using x values (min value first) void sortYZ() { float xmin; unsigned int index; triangle* tri; //insertion sort for (unsigned int i = 0; i < faces.size() - 1; i++) { xmin = faces[i]->findXmin(); index = i; for (unsigned int j = i + 1; j < faces.size(); j++) { if (faces[j]->findXmin() <= xmin) { xmin = faces[j]->findXmin(); index = j; } } tri = faces[index]; faces.erase(faces.begin() + index); faces.insert(faces.begin() + i, tri); } } //the keyboard function for switching normal and half tone void KeyBoardFunc(unsigned char key, int x, int y) { switch (key) { //half tone is off case '1': { option = 1; glutPostRedisplay(); break; } //half tone is on case '2': { option = 2; glutPostRedisplay(); break; } case 27: { exit(0); } case 'a': { break; } } } //mouse function for sliders void MouseFunc(int button, int state, int x, int y) { int yp = WinH - y, xp = x; switch (button) { case GLUT_LEFT_BUTTON: { //press down the mouse if (state == GLUT_DOWN) { //inside the cursor box for (unsigned int i = 0; i < sliders.size(); i++) { if (yp >= sliders[i].getYmin() && yp <= sliders[i].getYmax() && xp <= sliders[i].getXmax() && xp >= sliders[i].getXmin()) select = i; } } //release else if (state == GLUT_UP) { if (select != -1) { select = -1; //project the new phong model projectObjects(); glutPostRedisplay(); } } break; } } } //motion function for sliders void MotionFunc(int x, int y) { int xp = x; if (select != -1) { //move sliders sliders[select].MoveSlider(xp); //update parameters ka = glm::vec3(sliders[0].updatedValue(), sliders[1].updatedValue(), sliders[2].updatedValue()); kd = glm::vec3(sliders[3].updatedValue(), sliders[4].updatedValue(), sliders[5].updatedValue()); ks = glm::vec3(sliders[6].updatedValue(), sliders[7].updatedValue(), sliders[8].updatedValue()); Ia = sliders[9].updatedValue(); IL = sliders[10].updatedValue(); n = sliders[11].updatedValue(); light = glm::vec3(sliders[12].updatedValue(), sliders[13].updatedValue(), sliders[14].updatedValue()); viewpoint = glm::vec3(sliders[15].updatedValue(), sliders[16].updatedValue(), sliders[17].updatedValue()); K = sliders[18].updatedValue(); glutPostRedisplay(); } } //compute the half toning using mega pixels float* halfToning() { float* halfTone = new float[WinW * WinH * 3]; float block[9][3]; int row, col; //divide WinW x WinH into WinW / 3 x WinH / 3 mega pixels for (int i = 0; i < WinW * WinH / 9; i++) { int x, y, index, num_activate; //find the row col in pixel buffers row = i / (WinH / 3) + (i / (WinH / 3)) * 2; col = (i % (WinW / 3)) * 3; //initializes block for (int j = 0; j < 9; j++) { x = col + j % 3; y = row + j / 3; block[j][0] = PixelBuffer[WinW * 3 * y + x * 3]; block[j][1] = PixelBuffer[WinW * 3 * y + x * 3 + 1]; block[j][2] = PixelBuffer[WinW * 3 * y + x * 3 + 2]; } index = findBlockMax(block); //rounding down num_activate = (int)(max(max(block[index][0], block[index][1]), block[index][2]) * 9); //not turnning on any pixel in the mega pixels if (num_activate == 0) continue; //randomize the pixels to be turned on vector<int> choices; //random seed srand((unsigned int)(time(NULL) + i)); int pick; //randomize the pixels to be turned on for (int k = 0; k < num_activate; k++) { bool repeat = true; //make sure no repetition while (repeat) { pick = rand() % 9; repeat = false; for (unsigned int j = 0; j < choices.size(); j++) { if (choices[j] == pick) { repeat = true; break; } } } choices.push_back(pick); } //activate on the halftone pixel buffer for (unsigned int j = 0; j < choices.size(); j++) { x = col + choices[j] % 3; y = row + choices[j] / 3; halfTone[WinW * 3 * y + x * 3] = block[index][0]; halfTone[WinW * 3 * y + x * 3 + 1] = block[index][1]; halfTone[WinW * 3 * y + x * 3 + 2] = block[index][2]; } } return halfTone; } //initialize sliders void initSliders() { //initializes all the sliders for all the inputs for phong model slider ka_r(-0.75f, 0.9f, 1.0f, 0.0f, 10.0f, "ka_r"); slider ka_g(-0.75f, 0.8f, 1.0f, 0.0f, 10.0f, "ka_g"); slider ka_b(-0.75f, 0.7f, 1.0f, 0.0f, 10.0f, "ka_b"); slider kd_r(-0.75f, 0.6f, 1.0f, 0.0f, 10.0f, "kd_r"); slider kd_g(-0.75f, 0.5f, 1.0f, 0.0f, 10.0f, "kd_g"); slider kd_b(-0.75f, 0.4f, 1.0f, 0.0f, 10.0f, "kd_b"); slider ks_r(-0.75f, 0.3f, 1.0f, 0.0f, 10.0f, "ks_r"); slider ks_g(-0.75f, 0.2f, 1.0f, 0.0f, 10.0f, "ks_g"); slider ks_b(-0.75f, 0.1f, 1.0f, 0.0f, 10.0f, "ks_b"); slider Ia(-0.75f, 0.0f, 1.0f, 0.0f, 10.0f, "Ia"); slider IL(-0.75f, -0.1f, 1.0f, 0.0f, 10.0f, "IL"); slider n(-0.75f, -0.2f, 10.0f, 0.005f, 10.0f, "n"); //sliders for light position slider light_x(0.25f, 0.9f, 5.0f, -5.0f, 10.0f, "l_x"); slider light_y(0.25f, 0.8f, 5.0f, -5.0f, 10.0f, "l_y"); slider light_z(0.25f, 0.7f, 5.0f, -5.0f, 10.0f, "l_z"); //sliders for view position slider view_x(0.25f, 0.6f, 5.0f, -5.0f, 10.0f, "v_x"); slider view_y(0.25f, 0.5f, 5.0f, -5.0f, 10.0f, "v_y"); slider view_z(0.25f, 0.4f, 5.0f, -5.0f, 10.0f, "v_z"); slider K(-0.75f, -0.3f, 2.0f, 0.0f, 10.0f, "K"); //add all the sliders sliders.push_back(ka_r); sliders.push_back(ka_g); sliders.push_back(ka_b); sliders.push_back(kd_r); sliders.push_back(kd_g); sliders.push_back(kd_b); sliders.push_back(ks_r); sliders.push_back(ks_g); sliders.push_back(ks_b); sliders.push_back(Ia); sliders.push_back(IL); sliders.push_back(n); sliders.push_back(light_x); sliders.push_back(light_y); sliders.push_back(light_z); sliders.push_back(view_x); sliders.push_back(view_y); sliders.push_back(view_z); sliders.push_back(K); } //main program: read files, set default parameters for phong and project objects int main(int argc, char *argv[]) { int numOfObjects; //default value for phong models viewpoint = glm::vec3(0, 0, 0); light = glm::vec3(0, 0, 0); ka = glm::vec3(0.5f, 0.5f, 0.5f); kd = glm::vec3(0.5f, 0.5f, 0.5f); ks = glm::vec3(0.5f, 0.5f, 0.5f); n = 5.0; Ia = 0.5f, IL = 0.5f, K = 1.0f; //allocate buffer PixelBuffer = new float[WinW * WinH * 3]; //initialize to black for (int i = 0; i < WinW * WinH * 3; i++) PixelBuffer[i] = 0; //read in file ifstream inf; inf.open("test.txt"); inf >> numOfObjects; for (int i = 0; i < numOfObjects; i++) { object *obj = new object(); inf >> *obj; obj->computeNormal(); for (unsigned int j = 0; j < obj->faces.size(); j++) faces.push_back(obj->faces[j]); objects.push_back(obj); } inf.close(); //project the objects when program runs for the first time projectObjects(); //initialize sliders initSliders(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); //set window size to 500*500 glutInitWindowSize(WinW, WinH); //set window position glutInitWindowPosition(100, 100); //create and set main window title int MainWindow = glutCreateWindow("Project 3!"); glClearColor(1, 1, 1, 0); //clears the buffer of OpenGL glutKeyboardFunc(KeyBoardFunc); //keyboard function glutMouseFunc(MouseFunc); //mouse function glutMotionFunc(MotionFunc); //motion function glutDisplayFunc(display); //display function glutMainLoop();//main display loop, will display until terminate return 0; } //draw the plane labels and grid void drawPlaneLabel() { //draw plane labels glViewport(0, WinH / 2, WinW / 2, WinH / 2); glColor3f(1, 0, 0); string str = "XY Plane"; drawstr(-0.2f, 0.9f, str.c_str(), str.length()); glViewport(WinW / 2, WinH / 2, WinW / 2, WinH / 2); glColor3f(0, 1, 0); str = "XZ Plane"; drawstr(-0.2f, 0.9f, str.c_str(), str.length()); glViewport(0, 0, WinW / 2, WinH / 2); glColor3f(0, 0, 1); str = "YZ Plane"; drawstr(-0.2f, 0.9f, str.c_str(), str.length()); //DRAW GRID ON SCREEN glViewport(0, 0, WinW, WinH); //draw grid glBegin(GL_LINES); glColor3f(0.5, 0.5, 0.5); glVertex2f(0, -1); glVertex2f(0, 1); glVertex2f(-1, 0); glVertex2f(1, 0); glEnd(); //draw user information for half tone glColor3f(1, 1, 1); glViewport(WinW / 2, 0, WinW / 2, WinH / 2); str = "Press 1 for Normal Shading"; drawstr(0.25f, -0.1f, str.c_str(), str.length()); str = "Press 2 for Half Toning"; drawstr(0.25f, -0.2f, str.c_str(), str.length()); str = "Press esc to exit"; drawstr(0.25f, -0.3f, str.c_str(), str.length()); } //draw the sliders void drawSliders() { for (unsigned int i = 0; i < sliders.size(); i++) sliders[i].drawSlider(); } //project the objects void projectObjects() { //compute the phong models using world coordinates for (unsigned int i = 0; i < objects.size(); i++) { objects[i]->computePhong(viewpoint, light, ka, kd, ks, n, Ia, IL, K); //transfer to pixel coordinates for shading objects[i]->toPixel(); } //sort the faces according to z depths sortXY(); for (unsigned int i = 0; i < faces.size(); i++) { if (dot(faces[i]->n, glm::vec3(0, 0, 1)) > 0) { //draw the edge faces[i]->GedgeXY(); //shading the interior faces[i]->GshadingXY(); } } //sort the faces according to y depths sortXZ(); for (unsigned int i = 0; i < faces.size(); i++) { if (dot(faces[i]->n, glm::vec3(0, -1, 0)) > 0) { //draw the edge faces[i]->GedgeXZ(); //shading the interior faces[i]->GshadingXZ(); } } //sort the faces according to x depths sortYZ(); for (unsigned int i = 0; i < faces.size(); i++) { if (dot(faces[i]->n, glm::vec3(1, 0, 0)) > 0) { //draw the edge faces[i]->GedgeYZ(); //shading the interior faces[i]->GshadingYZ(); } } //convert back to world coordinates for next phong calculation for (unsigned int i = 0; i < objects.size(); i++) objects[i]->toWorld(); //half toning halfTone = halfToning(); } //display function void display() { glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); //draws pixel on screen glViewport(0, 0, WinW, WinH); glRasterPos3f(-1.0f, -1.0f, 0.0f); if(option == 1) glDrawPixels(WinW, WinH, GL_RGB, GL_FLOAT, PixelBuffer); else { glDrawPixels(WinW, WinH, GL_RGB, GL_FLOAT, halfTone); } //draw the plane labels drawPlaneLabel(); //draw all the sliders drawSliders(); //window refresh glFlush(); }
true
efa18dfadf4054358a54f5785f06ed1444df9073
C++
skwee357/math-lib
/quaternion.cpp
UTF-8
5,193
3.53125
4
[ "MIT" ]
permissive
/** * @file quaternion.cpp * @author skwo * @brief Realization of quaternion class. */ #include <cmath> #include "quaternion.hpp" #include "matrix.hpp" namespace skmath{ //Constructor Quaternion::Quaternion() { //Multiplicaiton identity quaternion _w = 1.0f; _v[0] = 0.0f; _v[1] = 0.0f; _v[2] = 0.0f; } Quaternion::Quaternion(const Quaternion& q) { _w = q.w(); _v = q.v(); } Quaternion::Quaternion(float w, const Vector& vec) { _w = w; _v = vec; } //Destructor Quaternion::~Quaternion() { } //Get Vector const Vector& Quaternion::v() const { return _v; } Vector& Quaternion::v() { return _v; } //Get Scalar const float& Quaternion::w() const { return _w; } float& Quaternion::w() { return _w; } //Norm float Quaternion::norm() const { return (_w * _w + _v[0] * _v[0] + _v[1] * _v[1] + _v[2] * _v[2]); } //Magnitude float Quaternion::magnitude() const { return static_cast<float>(sqrt(this->norm())); } //Normalize Quaternion Quaternion::normalize() const { float length = this->magnitude(); Quaternion res; if(length != 0.0f) { res[3] = _w / length; res[0] = _v[0] / length; res[1] = _v[1] / length; res[2] = _v[2] / length; } return res; } //Conjugate Quaternion Quaternion::conjugate() const { Quaternion res(_w, _v.inverse()); return res; } //Inverse Quaternion Quaternion::inverse() const { Quaternion res(*this); res.conjugate() / res.norm(); return res; } //Dot float Quaternion::inner(const Quaternion& rhs) const { return (_v[0] * rhs[0] + _v[1] * rhs[1] + _v[2] * rhs[2] + _w * rhs.w()); } //Create Rotation void Quaternion::createRotation(const Vector& vec, float angle) { float a = angle * cAngToRad; float half_a = a / 2.0f; _v = vec * sin(half_a); _w = cos(half_a); } //Operator [] const float& Quaternion::operator [](const int place) const { if((place >= 0) && (place <= 2)) return _v[place]; return _w; } float& Quaternion::operator [](const int place) { if((place >= 0) && (place <= 2)) return _v[place]; return _w; } //Operator == bool Quaternion::operator ==(const Quaternion& rhs) const { if(&rhs == this) return true; else { if((_w == rhs.w()) && (_v == rhs.v())) return true; else return false; } return false; } //Operator != bool Quaternion::operator !=(const Quaternion& rhs) const { return !(*this == rhs); } //Operator = Quaternion& Quaternion::operator =(const Quaternion& rhs) { if(&rhs == this) return *this; else { _v = rhs.v(); _w = rhs.w(); } return *this; } //Operator + Quaternion Quaternion::operator +(const Quaternion& rhs) const { Vector resV = _v + rhs.v(); Quaternion res(_w + rhs.w(), resV); return res; } //Operator - Quaternion Quaternion::operator -(const Quaternion& rhs) const { Vector resV = _v - rhs.v(); Quaternion res(_w - rhs.w(), resV); return res; } //Operator * Quaternion Quaternion::operator *(const Quaternion& rhs) const { Vector resV(_w * rhs[0] + _v[0] * rhs.w() + _v[1] * rhs[2] - _v[2] * rhs[1], //X _w * rhs[1] + _v[1] * rhs.w() + _v[2] * rhs[0] - _v[0] * rhs[2], //Y _w * rhs[2] + _v[2] * rhs.w() + _v[0] * rhs[1] - _v[1] * rhs[0]); //Z Quaternion res(_w * rhs.w() - _v[0] * rhs[0] - _v[1] * rhs[1] - _v[2] * rhs[2], resV); return res; } //Operator * Quaternion Quaternion::operator *(const float& rhs) const { Vector resV = _v * rhs; Quaternion res(_w * rhs, resV); return res; } //Operator / Quaternion Quaternion::operator /(const float& rhs) const { Vector resV = _v / rhs; Quaternion res(_w / rhs, resV); return res; } //Quaternion to matrix void quaternionToMatrix(Quaternion& q, Matrix& m) { float qx, qy, qz, qw; qx = q[0]; qy = q[1]; qz = q[2]; qw = q[3]; m[ 0] = 1.0f - 2.0f * (qy * qy + qz * qz); m[ 1] = 2.0f * (qx * qy - qz * qw); m[ 2] = 2.0f * (qx * qz + qy * qw); m[ 4] = 2.0f * (qx * qy + qz * qw); m[ 5] = 1.0f - 2.0f * (qx * qx + qz * qz); m[ 6] = 2.0f * (qy * qz - qx * qw); m[ 8] = 2.0f * (qx * qz - qy * qw); m[ 9] = 2.0f * (qy * qz + qx * qw); m[10] = 1.0f - 2.0f * (qx * qx + qy * qy); m[3] = m[7] = m[11] = m[12] = m[13] = m[14] = 0.0f; m[15] = 1.0f; } //Rotate Vector rotate(const Quaternion& rotQuat, const Vector& point) { Quaternion p(0.0f, point); //convert point to quaternion. Quaternion result = (rotQuat * p) * rotQuat.conjugate(); Vector res(result[0], result[1], result[2]); return res; } };
true
9dfcd6b69bdec95c5108dee12829ef49e33c0ac6
C++
bagobor/Beetle
/src/materials/blurmaterial.cpp
UTF-8
1,954
2.5625
3
[]
no_license
#include "blurmaterial.h" #include <math.h> #include "utils/math.h" BlurMaterial::BlurMaterial(QGLShaderProgram *shader): QuadMaterial(shader) { adrOffsetSize = shader->uniformLocation("offsetSize"); adrOffsets = shader->uniformLocation("offsets"); adrLowTexture = shader->uniformLocation("lowTexture"); adrSeed = shader->uniformLocation("seed"); offsets.reserve(MAX_OFFSET_SIZE); } BlurMaterial::~BlurMaterial() { } void BlurMaterial::updateOffsets() { offsets.clear(); float aspect = static_cast<float>(screenSize.width())/screenSize.height(); float radius = blurSize*screenSize.width()/1000000.0; if (radius/DELTA_SAMPLES>sqrt(MAX_OFFSET_SIZE/M_PI)) radius = sqrt(MAX_OFFSET_SIZE/M_PI)*DELTA_SAMPLES; float yMax = radius; float yMin = -radius; yMin += fmod(yMax-yMin, DELTA_SAMPLES)/2; for (float y=yMin; y<yMax; y+=DELTA_SAMPLES) { float xMax = cos(asin(y/radius))*radius; float xMin = -xMax; xMin += fmod(xMax-xMin, DELTA_SAMPLES)/2; for (float x=xMin; x<xMax; x+=DELTA_SAMPLES) offsets.append(QVector2D((x+Math::realRand(-DELTA_SAMPLES/4, DELTA_SAMPLES/4)), (y+Math::realRand(-DELTA_SAMPLES/4, DELTA_SAMPLES/4))*aspect)); } qDebug() << "Blur radius:" << radius << "samples count:" << offsets.count(); } bool BlurMaterial::bind() { if (QuadMaterial::bind()) { shader->setUniformValue(adrOffsetSize, offsets.count()); shader->setUniformValueArray(adrOffsets, offsets.data(), offsets.count()); shader->setUniformValue(adrLowTexture, lowTexture->bind(1)); shader->setUniformValue(adrSeed, seed); return true; } return false; } void BlurMaterial::setBlurSize(float blurSize) { this->blurSize = blurSize; updateOffsets(); } void BlurMaterial::setScreenSize(const QSize &screenSize) { this->screenSize = screenSize; updateOffsets(); } void BlurMaterial::setLowTexture(Texture *lowTexture) { this->lowTexture = lowTexture; } void BlurMaterial::setSeed(float seed) { this->seed = seed; }
true
4af78e15ce0d4d4f3431356eaedfc92680b6da82
C++
dangfugui/note-C
/oj题目/其他人/李春阳/P1056(S10908).cpp
UTF-8
312
2.8125
3
[]
no_license
#include<iostream> using namespace std; long long pow(long long a,long long b,long long c) { if(a==1||b==0) return 1; if(b==1) return a%c; long long t=pow(a,b/2,c); if(b%2) return t*t*a%c; return t*t%c; } int main() { long long x,y,z; cin>>x>>y>>z; cout<<pow(x,y,z); return 0; }
true
c2ea8a99a609cdebf5f4b17daa886d75655f79ba
C++
wi1k1n/simulation-dynamic-systems
/CPPSFNetworksTest/main.cpp
UTF-8
1,443
2.78125
3
[]
no_license
#include "SFNetwork.h" #include <iostream> #include <vector> #include <algorithm> #include <ctime> #include <functional> #include <random> #include <fstream> #include <thread> #include <Windows.h> #include <string> #define PI 3.1415926535897932384626433832795 using namespace std; using namespace Diploma2; double measureRuntime(const function<void()> f) { clock_t start(clock()); f(); return (clock() - start) / (double)CLOCKS_PER_SEC; } bool stop_current_execution = false; void cli() { while (!stop_current_execution) { int t; cin >> t; stop_current_execution = t == 9; } } void foo() { double start_local = clock(); SFNetworkOscillator nw(75, 3, .4, 1, 10, -PI, PI, 0, .1, .005, 626); cout << "Network generated in " << clock() - start_local << "ms" << endl; while(!stop_current_execution) { start_local = clock(); nw.SimulateDynamicStep(); cout << "Dynamic:\ttime: " << nw.time << "\t" << clock() - start_local << "ms" << endl; } nw.Binarize(("network_75_3_.4_1_10_-pi_pi_0_.1_.005_626_" + to_string(nw.states.size()) + ".bin").data(), 1); cout << "Network successfully binarized. Press any key to resume." << endl; } double start = clock(); int main(int argc, char* argv) { srand(start); double runtime = measureRuntime([]()->void { thread calculation(&foo); thread cli(&cli); cli.join(); calculation.join(); }); cout << endl << "Runtime: " << runtime << endl; system("pause"); return 0; }
true
3edf2ac6a5df0c2d976cae703c86e2cc95a69d50
C++
freesinger/Algorithm_DS
/Binary Search Tree/btreeDelete.cpp
UTF-8
2,843
3.78125
4
[]
no_license
/* 二叉搜索树删除操作 */ #include <iostream> #include <string> using namespace std; struct Node { int key; Node *right, *left, *parent; }; static Node *root = NULL; Node *treeMinimum(Node *x) { while (x->left != NULL) x = x->left; return x; } Node *getSuccessor(Node *x) { if (x->right != NULL) return treeMinimum(x->right); Node *y = x->parent; while (y != NULL && x == y->right) { x = y; y = y->parent; } return y; } void insert(int key) { Node *cur = root; Node *pre; Node *n = (Node*)malloc(sizeof(Node)); n->key = key; n->left = n->right = NULL; while (cur != NULL) { pre = cur; if (n->key > cur->key) cur = cur->right; else cur = cur->left; } n->parent = pre; if (pre == NULL) root = n; else if (pre->key > n->key) pre->left = n; else pre->right = n; } Node* find(int key) { Node *cur = root; while (cur != NULL && cur->key != key) if (key > cur->key) cur = cur->right; else cur = cur->left; return cur; } void treeDelete(Node *z) { // 删除的对象 Node *tar; Node *tarChild; // 确定要删除的节点 if (z->left == NULL && z->right == NULL) tar = z; else tar = getSuccessor(z); // 确定tar的子节点 if (tar->left != NULL) tarChild = tar->left; else tarChild = tar->right; if (tarChild != NULL) tarChild->parent = tar->parent; if (tar->parent == NULL) root = tar; else { if (tar == tar->parent->left) tar->parent->left = tarChild; else tar->parent->right = tarChild; } if (tar != z) z->key = tar->key; free(tar); } void inOrder(Node *u) { if (u == NULL) return; inOrder(u->left); cout << u->key << ' '; inOrder(u->right); } void preOrder(Node *u) { if (u == NULL) return; cout << u->key << ' '; preOrder(u->left); preOrder(u->right); } int main(void) { int num, tar; string com; cin >> num; for (int i = 0; i < num; i++) { cin >> com; if (com[0] == 'f') { cin >> tar; Node *tem = find(tar); if (tem != NULL) cout << "yes" << endl; else cout << "no" << endl; } else if (com[0] == 'i') { cin >> tar; insert(tar); } else if (com[0] == 'p') { inOrder(root); cout << endl; preOrder(root); cout << endl; } else if (com[0] == 'd') { cin >> tar; treeDelete(find(tar)); } } return 0; }
true
3d52fce4811dedbc3f487bd8da014600461578d6
C++
semeyon/getratebot
/src/types/Country.cpp
UTF-8
449
2.546875
3
[]
no_license
// // Created by Semeyon Svetliy on 07/10/2018. // #include <string> #include <fmt/format.h> #include "Country.hpp" using namespace std; string Country::msg() { return fmt::format("{0}({1}) – {2}, {3}", this->currencyId, this->currencySymbol, this->currencyName, this->name); } string Country::forSearch() { string msg = fmt::format("{0} {1} {2} {3}", this->currencyId, this->currencyName, this->name, this->currencySymbol); return msg; }
true
972e2f631f42b79cefe0e7c618782495a6aa274b
C++
andikan/GaussMesh
/GaussMesh/main.cpp
UTF-8
75,432
2.671875
3
[]
no_license
// // main.cpp // GaussMesh // // Created by Andikan on 13/8/2. // Copyright (c) 2013 Andikan. All rights reserved. // #include "IncludeLib.h" int main( void ) { // Initialise GLFW if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE,GL_TRUE); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2); glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1); // Open a window and create its OpenGL context if( !glfwOpenWindow( 1024, 768, 0,0,0,0, 32,0, GLFW_WINDOW ) ) { fprintf( stderr, "Failed to open GLFW window.\n" ); glfwTerminate(); return -1; } // Initialize GLEW if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } // Initialize variable glfwSetWindowTitle( "GaussOrganic Mesh" ); // Ensure we can capture the escape key being pressed below glfwEnable( GLFW_STICKY_KEYS ); glfwSetMousePos( 1024/2, 700/2 ); // Dark blue background glClearColor(1.0f, 1.0f, 1.0f, 1.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders( "/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/TransformVertexShader.vertexshader", "/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/ColorFragmentShader.fragmentshader" ); // Get a handle for our "MVP" uniform GLuint MatrixID = glGetUniformLocation(programID, "MVP"); // Get a handle for our buffers GLuint vertexPosition_modelspaceID = glGetAttribLocation(programID, "vertexPosition_modelspace"); GLuint vertexColorID = glGetAttribLocation(programID, "vertexColor"); // Use our shader glUseProgram(programID); // Our vertices. Tree consecutive floats give a 3D vertex; Three consecutive vertices give a triangle. // A cube has 6 faces with 2 triangles each, so this makes 6*2=12 triangles, and 12*3 vertices static const GLfloat g_vertex_buffer_data[] = { -1.0f,-1.0f,-1.0f, -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; GLuint cubevertexbuffer; glGenBuffers(1, &cubevertexbuffer); glBindBuffer(GL_ARRAY_BUFFER, cubevertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW); GLuint cubecolorbuffer; glGenBuffers(1, &cubecolorbuffer); // One color for each vertex. They were generated randomly. static GLfloat g_color_buffer_data[12*3*3]; srand((unsigned)time(NULL)); for (int v = 0; v < 12*3 ; v++){ g_color_buffer_data[3*v+0] = (float)((rand()%255)+1)/(float)255; // R g_color_buffer_data[3*v+1] = (float)((rand()%255)+1)/(float)255; // G g_color_buffer_data[3*v+2] = (float)((rand()%255)+1)/(float)255; // B } glBindBuffer(GL_ARRAY_BUFFER, cubecolorbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_color_buffer_data), g_color_buffer_data, GL_STATIC_DRAW); GLuint vertexbuffer; glGenBuffers(1, &vertexbuffer); GLuint colorbuffer; glGenBuffers(1, &colorbuffer); GLuint spineVertexBuffer; glGenBuffers(1, &spineVertexBuffer); GLuint spineColorBuffer; glGenBuffers(1, &spineColorBuffer); GLuint jointVertexBuffer; glGenBuffers(1, &jointVertexBuffer); GLuint jointColorBuffer; glGenBuffers(1, &jointColorBuffer); GLuint axesVertexBuffer; glGenBuffers(1, &axesVertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, axesVertexBuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_axes_vertex_buffer_data), g_axes_vertex_buffer_data, GL_STATIC_DRAW); GLuint axesColorbuffer; glGenBuffers(1, &axesColorbuffer); glBindBuffer(GL_ARRAY_BUFFER, axesColorbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(g_axes_color_buffer_data), g_axes_color_buffer_data, GL_STATIC_DRAW); // Initialize variable bool mouseDrawPress = false; bool spineDetect = false; bool readContourData = false; int readContourDataCount = 0; vector<vec3> clickPoint; vector<vec3> vertices; vector<vec3> colors; vector<vec3> spineVertice; vector<vec3> spineColors; vector<vec3> jointVertice; vector<vec3> jointColors; Mesh mesh; Mesh findSkeletonMesh; GLenum drawMode; int filenum = 0; float thinLine = 1.5; float boldLine = 4.5; float lineWidth = thinLine; do{ // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // detect mouse to draw if (glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ) == GLFW_PRESS){ if(!mouseDrawPress) // refresh a point set { clickPoint.clear(); vertices.clear(); colors.clear(); spineDetect = false; } // get origin mouse position int xpos, ypos; glfwGetMousePos( &xpos, &ypos ); cout << "x: " << xpos-512 << ", y: " << 350-ypos << endl; // modify origin mouse position by decrease 100 times double xmodpos, ymodpos; xmodpos = (double)(xpos-512)/100; ymodpos = (double)(350-ypos)/100; cout << "xm: " << xmodpos << ", ym: " << ymodpos << endl; if(clickPoint.size() == 0) { clickPoint.push_back(vec3( xmodpos, ymodpos, 0)); vertices.push_back(vec3( xmodpos, ymodpos, 0)); colors.push_back(vec3(255, 255, 255)); } else { double distance = pow(pow(xmodpos - clickPoint[clickPoint.size()-1].x, 2) + pow(ymodpos - clickPoint[clickPoint.size()-1].y, 2), 0.5); cout << "distance : " << distance << endl; if(distance > 0.3){ if(vertices.size() % 2 == 0){ //clickPoint.push_back(vec3(clickPoint[clickPoint.size() - 1].x, clickPoint[clickPoint.size() - 1].y, 0)); vertices.push_back(vec3(vertices[vertices.size() - 1].x, vertices[vertices.size() - 1].y, 0)); colors.push_back(vec3(255, 255, 255)); } clickPoint.push_back(vec3(xmodpos, ymodpos, 0)); vertices.push_back(vec3( xmodpos, ymodpos, 0)); colors.push_back(vec3(255, 255, 255)); } } glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); mouseDrawPress = true; drawMode = GL_LINES; } if (glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT ) == GLFW_RELEASE){ if(mouseDrawPress){ cout << "draw down\n"; mouseDrawPress = false; mesh.loadEdgeFromMouse(clickPoint); // point insert to mesh mesh.loadAndSortPointSet(); // delaunayTriangulation // mesh.delaunayTriangulation(); mesh.loadEdgeFromPointSet(*mesh.ps); // constraintBound // mesh.constraintBound(); mesh.loadEdgeFromPointSet(*mesh.ps); vertices.clear(); colors.clear(); cout << "mesh vertices : " << mesh.pNum << endl; for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(255, 255, 255)); } glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); drawMode = mesh.drawMode; } } if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { if( filenum == 1 ) { filenum = 32; } filenum = filenum - 1; // filenum = 6; double xpos, ypos; int vertexCount; vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); cout << "contour points number " << contourpoints.size() << endl; clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); // for (int i = 0; i < findSkeletonMesh.pNum; i++) { // vertices.push_back(vec3(findSkeletonMesh.vertexBuffer[i*3], findSkeletonMesh.vertexBuffer[i*3+1], findSkeletonMesh.vertexBuffer[i*3+2])); // colors.push_back(vec3(255, 255, 255)); // } for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } for (int i = 0; i < spineEdgeSet.size(); i++) { spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); spineColors.push_back(vec3(0.16f, 0.50f, 0.73f)); } // // for (int i = 0; i < jointPointEdgeSet.size(); i++) { // jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); // jointColors.push_back(vec3(255, 255, 0)); // } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { if( filenum == 31 ) { filenum = 0; } filenum = filenum + 1; // filenum = 6; double xpos, ypos; int vertexCount; vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); cout << "contour points number " << contourpoints.size() << endl; clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); // for (int i = 0; i < findSkeletonMesh.pNum; i++) { // vertices.push_back(vec3(findSkeletonMesh.vertexBuffer[i*3], findSkeletonMesh.vertexBuffer[i*3+1], findSkeletonMesh.vertexBuffer[i*3+2])); // colors.push_back(vec3(255, 255, 255)); // } for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } for (int i = 0; i < spineEdgeSet.size(); i++) { spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); spineColors.push_back(vec3(0.16f, 0.50f, 0.73f)); } // // for (int i = 0; i < jointPointEdgeSet.size(); i++) { // jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); // jointColors.push_back(vec3(255, 255, 0)); // } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if(glfwGetKey(GLFW_KEY_TAB) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); spineEdgeSet = findSkeletonMesh.removeRedundantTerminalEdges(spineEdgeSet); // findSkeletonMesh.getPipeHole(contourpoints, spineEdgeSet); // jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } for (int i = 0; i < spineEdgeSet.size(); i++) { spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); spineColors.push_back(vec3(0.16f, 0.50f, 0.73f)); } // for (int i = 0; i < jointPointEdgeSet.size(); i++) { // jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); // jointColors.push_back(vec3(0.086f, 0.627f, 0.521f)); // } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_SPACE ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { cout << "press space : get contour edges" << endl; vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); cout << "contour points number " << contourpoints.size() << endl; clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < contourpoints.size(); i++) { if(i != 0) { vertices.push_back(vec3(contourpoints[i-1]->p[0], contourpoints[i-1]->p[1], 0)); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); vertices.push_back(vec3(contourpoints[i]->p[0], contourpoints[i]->p[1], 0)); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } else { vertices.push_back(vec3(contourpoints[i]->p[0], contourpoints[i]->p[1], 0)); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); vertices.push_back(vec3(contourpoints[contourpoints.size()-1]->p[0], contourpoints[contourpoints.size()-1]->p[1], 0)); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = GL_LINES; lineWidth = boldLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); // findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); // findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S // findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... // spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); // jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ spineEdgeSet = mesh.getChordalAxisPointSet(*mesh.ps); mesh.loadEdgeFromPointSet(*mesh.ps); // glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } for (int i = 0; i < spineEdgeSet.size(); i++) { spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); spineColors.push_back(vec3(0.16f, 0.50f, 0.73f)); } // for (int i = 0; i < jointPointEdgeSet.size(); i++) { // jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); // jointColors.push_back(vec3(0.086f, 0.627f, 0.521f)); // } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); // spineEdgeSet = findSkeletonMesh.removeRedundantTerminalEdges(spineEdgeSet); jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); // jointPointEdgeSet = findSkeletonMesh.getSimplifiedPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < jointPointEdgeSet.size()/2; i++) { Point* p1 = jointPointEdgeSet[2*i]; Point* p2 = jointPointEdgeSet[2*i+1]; double dx = p2->p[0]-p1->p[0]; double dy = p2->p[1]-p1->p[1]; double width = 12.0; double height = 6.0; glm::vec2 lineVec = vec2(dx*height/sqrt(dx*dx+dy*dy) , dy*height/sqrt(dx*dx+dy*dy)); glm::vec2 verticalLineVec = vec2(-dy*width/sqrt(dx*dx+dy*dy) , dx*width/sqrt(dx*dx+dy*dy)); Point* p1_r = new Point(1, p1->p[0]+(-lineVec.x)+(verticalLineVec.x), p1->p[1]+(-lineVec.y)+(verticalLineVec.y), 0); Point* p1_l = new Point(1, p1->p[0]+(-lineVec.x)+(-verticalLineVec.x), p1->p[1]+(-lineVec.y)+(-verticalLineVec.y), 0); Point* p2_r = new Point(1, p2->p[0]+(lineVec.x)+(verticalLineVec.x), p2->p[1]+(lineVec.y)+(verticalLineVec.y), 0); Point* p2_l = new Point(1, p2->p[0]+(lineVec.x)+(-verticalLineVec.x), p2->p[1]+(lineVec.y)+(-verticalLineVec.y), 0); vertices.push_back(vec3(p1_r->p[0], p1_r->p[1], p1_r->p[2])); vertices.push_back(vec3(p1_l->p[0], p1_l->p[1], p1_l->p[2])); vertices.push_back(vec3(p2_r->p[0], p2_r->p[1], p2_r->p[2])); vertices.push_back(vec3(p2_l->p[0], p2_l->p[1], p2_l->p[2])); vertices.push_back(vec3(p1_r->p[0], p1_r->p[1], p1_r->p[2])); vertices.push_back(vec3(p2_r->p[0], p2_r->p[1], p2_r->p[2])); vertices.push_back(vec3(p1_l->p[0], p1_l->p[1], p1_l->p[2])); vertices.push_back(vec3(p2_l->p[0], p2_l->p[1], p2_l->p[2])); for(int num=0; num < 6; num++) { colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } } // for (int i = 0; i < spineEdgeSet.size(); i++) // { // spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); // spineColors.push_back(vec3(0, 0, 255)); // } // for (int i = 0; i < jointPointEdgeSet.size(); i++) { jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); jointColors.push_back(vec3(0.086f, 0.627f, 0.521f)); } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = GL_LINES; // drawMode = GL_QUADS; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_RSHIFT ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); // spineEdgeSet = findSkeletonMesh.removeRedundantTerminalEdges(spineEdgeSet); // jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); // jointPointEdgeSet = findSkeletonMesh.removeSmallRedundantTerminalEdges(jointPointEdgeSet); jointPointEdgeSet = findSkeletonMesh.getSimplifiedPointEdgeSet(spineEdgeSet); jointPointEdgeSet = findSkeletonMesh.removeSmallRedundantTerminalEdges(jointPointEdgeSet); // jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(jointPointEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < jointPointEdgeSet.size()/2; i++) { Point* p1 = jointPointEdgeSet[2*i]; Point* p2 = jointPointEdgeSet[2*i+1]; double dx = p2->p[0]-p1->p[0]; double dy = p2->p[1]-p1->p[1]; double width = 12.0; double height = 6.0; glm::vec2 lineVec = vec2(dx*height/sqrt(dx*dx+dy*dy) , dy*height/sqrt(dx*dx+dy*dy)); glm::vec2 verticalLineVec = vec2(-dy*width/sqrt(dx*dx+dy*dy) , dx*width/sqrt(dx*dx+dy*dy)); Point* p1_r = new Point(1, p1->p[0]+(-lineVec.x)+(verticalLineVec.x), p1->p[1]+(-lineVec.y)+(verticalLineVec.y), 0); Point* p1_l = new Point(1, p1->p[0]+(-lineVec.x)+(-verticalLineVec.x), p1->p[1]+(-lineVec.y)+(-verticalLineVec.y), 0); Point* p2_r = new Point(1, p2->p[0]+(lineVec.x)+(verticalLineVec.x), p2->p[1]+(lineVec.y)+(verticalLineVec.y), 0); Point* p2_l = new Point(1, p2->p[0]+(lineVec.x)+(-verticalLineVec.x), p2->p[1]+(lineVec.y)+(-verticalLineVec.y), 0); vertices.push_back(vec3(p1_r->p[0], p1_r->p[1], p1_r->p[2])); vertices.push_back(vec3(p1_l->p[0], p1_l->p[1], p1_l->p[2])); vertices.push_back(vec3(p2_r->p[0], p2_r->p[1], p2_r->p[2])); vertices.push_back(vec3(p2_l->p[0], p2_l->p[1], p2_l->p[2])); vertices.push_back(vec3(p1_r->p[0], p1_r->p[1], p1_r->p[2])); vertices.push_back(vec3(p2_r->p[0], p2_r->p[1], p2_r->p[2])); vertices.push_back(vec3(p1_l->p[0], p1_l->p[1], p1_l->p[2])); vertices.push_back(vec3(p2_l->p[0], p2_l->p[1], p2_l->p[2])); for(int num=0; num < 6; num++) { colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } } // for (int i = 0; i < spineEdgeSet.size(); i++) // { // spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); // spineColors.push_back(vec3(0, 0, 255)); // } // for (int i = 0; i < jointPointEdgeSet.size(); i++) { jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); jointColors.push_back(vec3(0.086f, 0.627f, 0.521f)); } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = GL_LINES; // drawMode = GL_QUADS; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_ENTER ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } // for (int i = 0; i < spineEdgeSet.size(); i++) // { // spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); // spineColors.push_back(vec3(0.75f, 0.22f, 0.16f)); // } for (int i = 0; i < jointPointEdgeSet.size(); i++) { jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); jointColors.push_back(vec3(0.086f, 0.627f, 0.521f)); } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; lineWidth = thinLine; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } if (glfwGetKey( GLFW_KEY_BACKSPACE ) == GLFW_PRESS) { if(readContourData) { readContourDataCount++; if(readContourDataCount%9 == 0) { readContourData = false; } } if(!readContourData) { vector<Point*> contourpoints; /* p2t data */ /// Constrained triangles vector<p2t::Triangle*> triangles; /// Triangle map (include edge outside the contour) list<p2t::Triangle*> map; /// Polylines (if there are holes in the polygon) // vector< vector<p2t::Point*> > polylines; /// Polyline vector<p2t::Point*> polyline; string filenum_str = to_string(filenum); string filename ="/Users/andikan/Dev/gauss/GaussMesh/GaussMesh/data/"; filename.append(filenum_str); filename.append(".txt"); cout << "Start processing " << filenum_str << ".txt" << endl; ContourReader reader(filename); contourpoints = reader.getContourPoints(); clickPoint.clear(); vertices.clear(); colors.clear(); for(int i=0; i<contourpoints.size(); i++) { polyline.push_back(new p2t::Point(contourpoints[i]->p[0], contourpoints[i]->p[1])); } /* * STEP 1: Create CDT and add primary polyline * NOTE: polyline must be a simple polygon. The polyline's points * constitute constrained edges. No repeat points!!! */ clock_t init_time = clock(); p2t::CDT* cdt = new p2t::CDT(polyline); cdt->Triangulate(); triangles = cdt->GetTriangles(); clock_t end_time = clock(); cout << "Elapsed time (sec) = " << (end_time-init_time)/(double)(CLOCKS_PER_SEC) << " sec" << endl; map = cdt->GetMap(); mesh.loadP2tPoints(polyline); findSkeletonMesh.loadP2tPoints(polyline); mesh.addP2tTriangles(triangles); findSkeletonMesh.addP2tTriangles(triangles); cout << "mesh vertex num : " << mesh.ps->pSet.size() << endl; /* find skeleton */ vector<Point*> spineEdgeSet; vector<Point*> jointPointEdgeSet; // remove some T triangle, like T-J, T-S findSkeletonMesh.removeTerminalTriangleWithJoint(*findSkeletonMesh.ps); // findSkeletonMesh.removeTerminalTriangleWithSleeve(*findSkeletonMesh.ps); // get edge of points, return vector<Point*> // edge 1 = vectorPoints[0], vectorPoints[1] // edge 2 = vectorPoints[2], vectorPoints[3] // edge 3 = .... spineEdgeSet = findSkeletonMesh.getSkeletonPointSet(*findSkeletonMesh.ps); // jointPointEdgeSet = findSkeletonMesh.getJointPointEdgeSet(spineEdgeSet); /* END find skeleton END */ mesh.getSpinePoints(*mesh.ps); mesh.loadEdgeFromPointSet(*mesh.ps); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); vertices.clear(); colors.clear(); spineVertice.clear(); spineColors.clear(); jointVertice.clear(); jointColors.clear(); for (int i = 0; i < mesh.pNum; i++) { vertices.push_back(vec3(mesh.vertexBuffer[i*3], mesh.vertexBuffer[i*3+1], mesh.vertexBuffer[i*3+2])); colors.push_back(vec3(0.17f, 0.24f, 0.31f)); } for (int i = 0; i < spineEdgeSet.size(); i++) { spineVertice.push_back(vec3(spineEdgeSet[i]->p[0], spineEdgeSet[i]->p[1], spineEdgeSet[i]->p[2])); spineColors.push_back(vec3(0.16f, 0.50f, 0.73f)); } // for (int i = 0; i < jointPointEdgeSet.size(); i++) { // jointVertice.push_back(vec3(jointPointEdgeSet[i]->p[0], jointPointEdgeSet[i]->p[1], jointPointEdgeSet[i]->p[2])); // jointColors.push_back(vec3(0, 255, 255)); // } glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glBufferData(GL_ARRAY_BUFFER, spineVertice.size() * sizeof(vec3), &spineVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glBufferData(GL_ARRAY_BUFFER, spineColors.size() * sizeof(vec3), &spineColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glBufferData(GL_ARRAY_BUFFER, jointVertice.size() * sizeof(vec3), &jointVertice[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glBufferData(GL_ARRAY_BUFFER, jointColors.size() * sizeof(vec3), &jointColors[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(vec3), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, colors.size() * sizeof(vec3), &colors[0], GL_STATIC_DRAW); // drawMode = GL_LINES; drawMode = mesh.drawMode; // drawMode = findSkeletonMesh.drawMode; readContourData = true; readContourDataCount++; } } // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units glm::mat4 Projection; if(!mouseDrawPress) { // Projection = glm::perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f); Projection = glm::perspective(45.0f, 4.0f / 3.0f, 1.0f, 1000.0f); } else { Projection = glm::ortho(-5.12f, 5.12f, -3.50f, 3.50f, 0.1f, 100.0f); } // Camera matrix glm::mat4 View; if(!mouseDrawPress) View = glm::lookAt(glm::vec3(0,0,400), glm::vec3(0,0,0), glm::vec3(0,1,0) ); else View = glm::lookAt(glm::vec3(0,0,10), glm::vec3(0,0,0), glm::vec3(0,1,0) ); // Model matrix : an identity matrix (model will be at the origin) glm::mat4 Model = glm::mat4(1.0f); // Our ModelViewProjection : multiplication of our 3 matrices glm::mat4 MVP = Projection * View * Model; // Remember, matrix multiplication is the other way around // Send our transformation to the currently bound shader, // in the "MVP" uniform glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); // // Draw axes // // 1rst attribute buffer : vertices // glEnableVertexAttribArray(vertexPosition_modelspaceID); // glBindBuffer(GL_ARRAY_BUFFER, axesVertexBuffer); // glVertexAttribPointer( vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // // // 2nd attribute buffer : colors // glEnableVertexAttribArray(vertexColorID); // glBindBuffer(GL_ARRAY_BUFFER, axesColorbuffer); // glVertexAttribPointer(vertexColorID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // // Draw axes lines // glLineWidth(1.0); // glDrawArrays(GL_LINES, 0, 6*3); // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // 2nd attribute buffer : colors glEnableVertexAttribArray(vertexColorID); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glVertexAttribPointer(vertexColorID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // Draw the triangleS ! glPointSize(3.0); glEnable(GL_POINT_SMOOTH); glLineWidth(lineWidth); glDrawArrays(drawMode, 0, (int)vertices.size()); // GL_TRIANGLES, GL_POINTS, GL_LINES // Draw spine point // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, spineVertexBuffer); glVertexAttribPointer( vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // 2nd attribute buffer : colors glEnableVertexAttribArray(vertexColorID); glBindBuffer(GL_ARRAY_BUFFER, spineColorBuffer); glVertexAttribPointer(vertexColorID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // Draw spine point glLineWidth(boldLine); glDrawArrays(GL_LINES, 0, (int)spineVertice.size()); // Draw joint point // 1rst attribute buffer : vertices glEnableVertexAttribArray(vertexPosition_modelspaceID); glBindBuffer(GL_ARRAY_BUFFER, jointVertexBuffer); glVertexAttribPointer( vertexPosition_modelspaceID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // 2nd attribute buffer : colors glEnableVertexAttribArray(vertexColorID); glBindBuffer(GL_ARRAY_BUFFER, jointColorBuffer); glVertexAttribPointer(vertexColorID, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 ); // Draw spine point glLineWidth(boldLine); // glEnable(GL_POINT_SMOOTH); glDrawArrays(GL_LINES, 0, (int)jointVertice.size()); // glDisableVertexAttribArray glDisableVertexAttribArray(vertexPosition_modelspaceID); glDisableVertexAttribArray(vertexColorID); // Swap buffers glfwSwapBuffers(); } // Check if the ESC key was pressed or the window was closed while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS && glfwGetWindowParam( GLFW_OPENED ) ); // Cleanup VBO and shader glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &colorbuffer); glDeleteBuffers(1, &spineVertexBuffer); glDeleteBuffers(1, &spineColorBuffer); glDeleteBuffers(1, &cubevertexbuffer); glDeleteBuffers(1, &cubecolorbuffer); glDeleteBuffers(1, &axesVertexBuffer); glDeleteBuffers(1, &axesColorbuffer); glDeleteProgram(programID); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
true
c8298cdf8108fe91f64d46b4e52de86b1fbdbbb6
C++
Chris443/GeKo
/GeKo/Math/vec4.cpp
UTF-8
667
3.140625
3
[]
no_license
#include "vec4.h" namespace gkm { vec4::vec4(float x, float y, float z, float w) :e{x,y,z,w} {} vec4::vec4(const vec4& other) : e{ other.e[0] ,other.e[1],other.e[2], other.e[3] } {} vec4::vec4(vec4&& other) { std::swap(e[0], other.e[0]); std::swap(e[1], other.e[1]); std::swap(e[2], other.e[2]); std::swap(e[3], other.e[3]); } vec4& vec4::operator=(const vec4& other) { e[0] = other.e[0]; e[1] = other.e[1]; e[2] = other.e[2]; e[3] = other.e[3]; return *this; } //throws at wrong access float& vec4::operator[](int idx) { try { return e[idx]; } catch (std::exception& e) { std::cout << e.what() << std::endl; } } }
true
ea089e3460de5a2ac3fdab675e6fec8ef68b27d5
C++
KkyuCone/DirectX3D_MSJ_PO
/MSJ_DirectX_3D/Engine/Include/Component/TPCamera.h
UHC
1,410
2.546875
3
[]
no_license
#pragma once #include "Component.h" ENGINE_BEGIN // 3Ī ī޶ Ʈ // 1Ī ó ϴ. (Ÿ 0 ϸ ) class ENGINE_DLL TPCamera : public Component { private: friend class GameObject; protected: TPCamera(); TPCamera(const TPCamera& _Com); virtual ~TPCamera(); private: class GameObject* m_pTargetObj; class Transform* m_pTarget; // Ÿ ġ Vector3 m_vDistance; // Ÿ ٶ󺸴 bool m_bMouseEnable; // 콺 翩 bool m_bSoketMove; // Ÿ bool m_bBaseNoneMove; // Idle bool m_bToolCamera; // ī޶ public: void SetTarget(class GameObject* _pTarget); void SetTarget(Component* _pTarget); void SetDistance(const Vector3& _vDistance); void SetMouseEnable(bool _bEnable); void SetSoketMoveEnable(bool _bEnable); void SetBaseNoneMoveEnable(bool _bEnable); void SetToolCamera(bool _bValue); public: GameObject* GetTargetObject(); public: virtual void Start(); virtual bool Init(); virtual int Input(float _fTime); virtual int Update(float _fTime); virtual int LateUpdate(float _fTime); virtual int Collision(float _fTime); virtual int PrevRender(float _fTime); virtual int Render(float _fTime); virtual int RenderShadow(float _fTime); virtual TPCamera* Clone() const; }; ENGINE_END
true
ac8aa63f9208ffcce9ca3697efab85663f312fce
C++
makisto/prog
/1/6/6.3.cpp
WINDOWS-1251
476
2.953125
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; int main(int argc, char *argv[]) { srand(time(NULL)); double arr[20]; double a = 0; double b = 10; for(int i = 0; i < 20; i++) { arr[i] = rand() * (b - a) / RAND_MAX + a; cout << arr[i] << " "; } cout << endl << " :" << endl; for(int i = 1; i < 19; i++) { if(arr[i] > arr[i - 1] && arr[i] > arr[i + 1]) { cout << arr[i] << " "; } } return 0; }
true
7578a7aaea30fa0ff679c2171e3b8ab384e9e8fe
C++
scylla-zpp-blas/scylla_matrix_test
/float_value_factory.hh
UTF-8
332
2.609375
3
[ "Apache-2.0" ]
permissive
#pragma once #include <random> #include "matrix_value_factory.hh" class float_value_factory: public matrix_value_factory<float> { private: std::mt19937 _rng; float _min, _max; std::uniform_real_distribution<float> _dist; public: float_value_factory(float min, float max, int seed); float next() override; };
true
d9773c523323714dcb8a937178e69bf33a208807
C++
raidoxin/PA9-Repository
/paperclone/visa.cpp
UTF-8
1,678
2.953125
3
[]
no_license
#include "visa.h" string & visa::getDestCountry() { return destinationCountry; } string & visa::getDestCity() { return destinationCity; } string & visa::getVisatype() { return visatype; } void visa::setDestCountry(string & newnation) { destinationCountry = newnation; } void visa::setDestCity(string & newcity) { destinationCity = newcity; } void visa::setVisaType(string & newtype) { visatype = newtype; } void visa::print_all() { std::cout << this->getID() << std::endl << this->getLastN() << std::endl << this->getFirstN() << std::endl << this->getSex() << std::endl << destinationCountry << std::endl << destinationCity << std::endl << visatype << std::endl; } visa & visa::operator=(passport & copied) { this->setFirst(copied.getFirstN()); this->setLast(copied.getLastN()); this->setSex(copied.getSex()); return *this; } void visa::corrupt_destination_Country(int odds) { for (int i = 0; i < destinationCountry.length(); i++) { if (!(rand() % (100 / odds)) && valid != false) { destinationCity[i] = 97 + rand() % 26; valid = false; } } } void visa::corrupt_destination_City(int odds) { for (int i = 0; i < destinationCity.length(); i++) { if (!(rand() % (100 / odds)) && valid != false) { destinationCity[i] = 97 + rand() % 26; valid = false; } } } void visa::corrupt_visatype(int odds) { for (int i = 0; i < visatype.length(); i++) { if (!(rand() % (100 / odds)) && valid != false) { visatype[i] = 97 + rand() % 26; valid = false; } } } /* void visa_mastercorrupt(int odds) { visa::corrupt_destination_City(odds); visa::corrupt_destination_Country(odds); visa::corrupt_visatype(odds); } */
true
8f8b2e2983b730f7c4fe129dd9a37395a1c9d27d
C++
zeagle01/graphics_play_ground
/examples/shellet/shellet/src/FEM_Simulator.h
UTF-8
1,011
2.578125
3
[]
no_license
#ifndef FEM_SIMULATOR_H #define FEM_SIMULATOR_H #include "Simulator.h" #include "Topology_Computer.h" #include "predef_types.h" #include <vector> #include <memory> class FEM_Simulator :public Simulator { public: FEM_Simulator() : topology_computer(std::make_shared<Topology_Computer>()) {} virtual void update(std::vector<float>& positions,std::vector<int>& triangle_indices); public: virtual void setMesh(const std::vector<float>& positions,const std::vector<int>& triangle_indices) override; virtual void setGravity(const std::vector<float>& g)override; virtual void setMass(const float mass)override; virtual void setDeltaT(const float dt)override; private: std::shared_ptr<Topology_Computer> topology_computer; m3xf m_forces ; m3xf m_velocities ; m3xf m_positions ; m2xf m_init_positions ; std::vector<int> m_indices; //implicit m3xf m_delta_velocities; float dt; public: void compute_new_stretched_positions( std::vector<float>& x); void implicit_method(); }; #endif
true
329bec38cbc173b8eca6916eb0c7e2b72faf4615
C++
VictorEijkhout/EduDL-public
/src/vector.cpp
UTF-8
2,722
3.046875
3
[]
no_license
/**************************************************************** **************************************************************** **** **** This text file is part of the source of **** `Introduction to High-Performance Scientific Computing' **** by Victor Eijkhout, copyright 2012-2021 **** **** Deep Learning Network code **** copyright 2021 Ilknur Mustafazade **** **************************************************************** ****************************************************************/ #include <algorithm> #include "vector.h" #include <iostream> #include <cassert> /* * These are the vector routines that do not have a optimized implementation, * such as using BLIS. */ Vector::Vector(){ } int Vector::size() const { return vals.size(); }; Vector::Vector( std::vector<float> vals ) : vals(vals) { r = vals.size(); c = 1; }; void Vector::square() { std::for_each(vals.begin(), vals.end(), [](auto &n) {n*=n;}); } Vector& Vector::operator=(const Vector &m2) { // Overloading the = operator vals = m2.vals; return *this; } // Note: no element-wise, non destructive operations in BLIS, so no implementations for those yet // There are element wise operations in MKL I believe Vector Vector::operator+(const Vector &m2) { assert(m2.size()==this->size()); Vector out(m2.size(),0); for (int i=0;i<m2.size();i++) { out.vals[i] = this->vals[i] + m2.vals[i]; } return out; } Vector Vector::operator-(const Vector &m2) { assert(m2.size()==this->size()); Vector out(m2.size(),0); for (int i=0;i<m2.size();i++) { out.vals[i] = this->vals[i] - m2.vals[i]; } return out; } Vector operator-(const float &c, const Vector &m) { Vector o=m; for (int i=0;i<m.size();i++) { o.vals[i] = c - o.vals[i]; } return o; } Vector operator*(const float &c, const Vector &m) { Vector o=m; for (int i=0;i<m.size();i++) { o.vals[i] = c * o.vals[i]; } return o; } Vector operator/(const Vector &m, const float &c) { Vector o=m; for (int i=0;i<m.size();i++) { o.vals[i] = o.vals[i] / c; } return o; } Vector Vector::operator*(const Vector &m2) { // Hadamard product Vector out(m2.size(), 0); for (int i = 0; i < m2.size(); i++) { out.vals[i] = this->vals[i] * m2.vals[i]; } return out; } Vector Vector::operator/(const Vector &m2) { // Element wise division Vector out(m2.size(), 0); for (int i = 0; i < m2.size(); i++) { out.vals[i] = this->vals[i] / m2.vals[i]; } return out; } Vector Vector::operator-() { Vector result = *this; for (int i = 0; i < size(); i++){ result.vals[i] = -vals[i]; } return result; };
true
08ee1ef901b22e79819fb07d8ba65d834915baea
C++
rustam-azimov/homeWork
/thirdSemester/hw3/roboGraph/roboGraph.h
UTF-8
854
3.265625
3
[]
no_license
#ifndef ROBOGRAPH_H #define ROBOGRAPH_H /** * @file RoboGraph.h * * Implementation of RoboGraph class. * Determine, whether there is a sequence of teleportations, * in which all robots self-destruct. */ #include <QVector> class RoboGraph { public: RoboGraph(const int& size); /// Adds one robot. If vertex > number of verteces in graph, does nothing. void addRobot(const int& vertex); /// Adds link between vertex1 and vertex2. If vertex1 or vertex2 > number of verteces in graph, does nothing. void addLink(const int& vertex1, const int& vertex2); enum RobotContain { noRobot = false, hasRobot = true }; /// Returns true, if all robots can self-destruct, otherwise returns false. bool isAllRobotDestroyed(); private: QVector<QVector<bool> > mAdjacencyMatrix; QVector<bool> mIsRobotSet; int mSize; }; #endif // ROBOGRAPH_H
true
bfbdcebba94f795f19f322e58fa1dbf859a2bcc3
C++
tan2/DynEarthSol
/libadaptivity/load_balance/include/ElementVector.h
UTF-8
3,334
2.6875
3
[ "LGPL-2.1-only", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-1.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-other-copyleft", "MIT" ]
permissive
/* Copyright (C) 2006 Imperial College London and others. Please see the AUTHORS file in the main source directory for a full list of copyright holders. Dr Gerard J Gorman Applied Modelling and Computation Group Department of Earth Science and Engineering Imperial College London g.gorman@imperial.ac.uk This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef ELEMENTVECTOR_H #define ELEMENTVECTOR_H #include "confdefs.h" #include <vector> #include <deque> #include <iostream> #include "samtypes.h" // // This class describes a template container for storing elements. // template<class ElementType> class ElementVector: public std::deque<ElementType>{ public: ElementVector(); ElementVector(const ElementVector&); ~ElementVector(); // Overloaded operators. ElementVector &operator=(const ElementVector<ElementType> &in); #ifndef NDEBUG const ElementType &operator[](const unsigned in) const; ElementType &operator[](const unsigned in); #endif // Other member functions. void shrink(const unsigned); void push_back(const ElementType& in); unsigned size() const; void clear(); private: unsigned len; }; template<class ElementType> ElementVector<ElementType>::ElementVector(){ len=0; } template<class ElementType> ElementVector<ElementType>::ElementVector(const ElementVector& newkid){ *this = newkid; } template<class ElementType> ElementVector<ElementType>::~ElementVector(){ clear(); } // Overloaded operators. template<class ElementType> ElementVector<ElementType>& ElementVector<ElementType>::operator=(const ElementVector<ElementType>& in){ len = in.len; insert( (*this).end(), in.begin(), in.end() ); return *this; } #ifndef NDEBUG template<class ElementType> ElementType& ElementVector<ElementType>::operator[](const unsigned i){ // Don't forgive out of bounds referencing. assert(i<len); return *(this->begin() + i); } template<class ElementType> const ElementType& ElementVector<ElementType>::operator[](const unsigned i) const{ // Don't forgive out of bounds referencing. assert( (i>=0)&&(i<len)); return *(this->begin() + i); } #endif // Other member functions template<class ElementType> void ElementVector<ElementType>::push_back(const ElementType& in){ this->insert(this->end(), in); len++; } template<class ElementType> void ElementVector<ElementType>::shrink(const unsigned newlen){ if(newlen == len) return; assert(newlen < len); this->resize( newlen ); len = newlen; } template<class ElementType> unsigned ElementVector<ElementType>::size() const{ return len; } template<class ElementType> void ElementVector<ElementType>::clear(){ len = 0; this->erase(this->begin(), this->end()); } #endif
true
c3a39d09fbee22e6aa2eced956cf7da5e1913c99
C++
jamesshao8/udoo_neo_flight_controller
/A9/observer.hpp
UTF-8
704
3.1875
3
[ "MIT" ]
permissive
#ifndef OBSERVERPATTERN_H #define OBSERVERPATTERN_H #include <iostream> #include <vector> class Observer { public: Observer(){}; virtual void update() = 0; }; class Observable { private: std::vector<Observer*> observers; bool ch; public: Observable(){ch = false;}; void notifyObservers() { for (std::vector<Observer*>::iterator it = observers.begin(); it != observers.end(); ++it) (*it)->update(); ch = false; }; void setChanged() { ch = true; }; bool hasChanged() { return ch; }; void AddObserver(Observer &o) { observers.push_back(&o); }; void ClearObservers() { observers.clear(); }; }; #endif //OBSERVERPATTERN_H
true
8540e620649e9b808ebca251d1edb9f093213125
C++
Onederflow/CYBER-KNU-OOP_and_LABS
/Part2/laboratory/lab5/main.cpp
UTF-8
3,422
3.34375
3
[]
no_license
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; struct Node { int data_1; int data_2; Node *Last; Node *left; Node *center; Node *right; }; void add_new_node(int data, Node *&NowTr, Node *Last); void write_node(Node *NowTr); int main() { srand ( time(NULL) ); Node *head ;// = new Node; head = NULL; int dt[20]; int i; for(i=1;i<=3;i++) { dt[i] = rand()%100; add_new_node(dt[i],head,NULL); }; cout << "__________" << endl; for(i=1;i<=3;i++) cout << dt[i] << endl; cout << "__________" << endl; cout << "_____________"<< endl; write_node(head); cout << "Hello world!" << endl; return 0; }; void add_new_node(int data, Node *&NowTr, Node *Last) { bool t = true; if (NowTr == NULL) { NowTr = new Node; NowTr->Last = Last; NowTr->data_1 = data; NowTr->data_2 = 0; NowTr->left = NULL; NowTr->center = NULL; NowTr->right = NULL; t = false; }; if ((NowTr->data_2 == 0) && (t)) { if (NowTr->data_1 <= data) NowTr->data_2 = data; else { NowTr->data_2 = NowTr->data_1; NowTr->data_1 = data; }; } else if(t) { if (data<NowTr->data_1) { if (NowTr->left != NULL) add_new_node(data, NowTr->left, NowTr); else { NowTr->left = new Node; NowTr->left->Last = Last; NowTr->left->left = NowTr->left->right = NowTr->left->center = NULL; NowTr->left->data_2 = NowTr->left->data_1 = 0; if (NowTr->left->data_1 > data) { NowTr->left->data_2 = NowTr->left->data_1; NowTr->left->data_1 = data; } else { if (NowTr->left->data_1 == 0) NowTr->left->data_1 = data; else NowTr->left->data_2 = data; }; }; }; if ((data >= NowTr->data_1) && (data <= NowTr->data_2)) { if (NowTr->center != NULL) add_new_node(data, NowTr->center, NowTr); else { NowTr->center = new Node; NowTr->center->Last = Last; NowTr->center->left = NowTr->center->right = NowTr->center->center = NULL; NowTr->center->data_2 = NowTr->center->data_1 = 0; if (NowTr->center->data_1 > data) { NowTr->center->data_2 = NowTr->center->data_1; NowTr->center->data_1 = data; } else { if (NowTr->center->data_1 == 0) NowTr->center->data_1 = data; else NowTr->center->data_2 = data; }; }; }; if (data > NowTr->data_2) { if (NowTr->right != NULL) add_new_node(data, NowTr->right, NowTr); else { NowTr->right = new Node; NowTr->right->Last = Last; NowTr->right->left = NowTr->right->right = NowTr->right->center = NULL; NowTr->right->data_2 = NowTr->right->data_1 = 0; if (NowTr->right->data_1 > data) { NowTr->right->data_2 = NowTr->right->data_1; NowTr->right->data_1 = data; } else { if (NowTr->right->data_1 == 0) NowTr->right->data_1 = data; else NowTr->right->data_2 = data; }; }; }; }; }; void write_node(Node *NowTr) { if(NowTr!= NULL) { cout << "|_"; if(NowTr->data_1 != 0) cout << NowTr->data_1; cout << "_|_"; if(NowTr->data_2 != 0) cout << NowTr->data_2; cout << "_|"; cout << endl; cout << "Left = "; write_node(NowTr->left); cout << "Center = "; write_node(NowTr->center); cout << "Right = "; write_node(NowTr->right); cout << endl; }; };
true
f90a90fcc963cc3ccf95c8091ac74a48e54bd48f
C++
Mu-Ahmad/OOP-CMP-244-241
/Lecture Codes/Lecture 14/File Handling OOP/File08.cpp
UTF-8
395
2.828125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main(){ int val; ofstream out("numbers.txt"); for (int i=1; i<=50 ; i++) out << i << ' '; out << '\n'; out.close(); ifstream in("numbers.txt"); while (true){ in >> val; if (in.fail()) break; cout << val << ' '; } cout << '\n' ; in.close(); return 0; }
true
d3885a9fbc681556911e59110ee97921b8e1dba7
C++
tmichi/mibase
/src/Parse.cpp
UTF-8
1,507
2.640625
3
[ "MIT" ]
permissive
#include <mi/Parse.hpp> #include <string> #include <cstdlib> namespace mi { template<> char parse ( const std::string& value ) { return static_cast<char> ( std::atoi ( value.c_str() ) ); } template<> unsigned char parse ( const std::string& value ) { return static_cast<unsigned char> ( std::atoi ( value.c_str() ) ); } template<> short parse ( const std::string& value ) { return static_cast<short> ( std::atoi ( value.c_str() ) ); } template<> unsigned short parse ( const std::string& value ) { return static_cast<unsigned short> ( std::atoi ( value.c_str() ) ); } template<> int parse ( const std::string& value ) { return std::atoi ( value.c_str() ); } template<> unsigned int parse ( const std::string& value ) { return static_cast<unsigned int> ( std::atoi ( value.c_str() ) ); } template<> float parse ( const std::string& value ) { return static_cast<float> ( std::atof ( value.c_str() ) ); } template<> double parse ( const std::string& value ) { return std::atof ( value.c_str() ); } template<> std::string parse ( const std::string& value ) { return value; } }//namespace mi
true
bde29f3646c46a3b811c767acb76bb4d537e082e
C++
baender/The_Coding_Den_Share
/main.cpp
UTF-8
986
2.640625
3
[]
no_license
#include <Arduino.h> #include "mySensorInterface.h" #include "mySensorAnalog.h" #include "mySensorCTD.h" char lineBuffer[255]; SensorAnalog a("SensorA", 8, 1.4142); SensorAnalog b("Sensor321", 6, 3.1415); SensorCTD c("CTD1", 'H'); SensorCTD d("CTD2", 'Q'); SensorInterface *sensors[] = {&a, &b, &c, &d, nullptr}; void setup() { Serial.begin(9600); while(!Serial); Serial.print("Init sensors... "); uint8_t i = 0; while (sensors[i]) { sensors[i]->init(); i++; } Serial.println("done!"); Serial.println(""); } void loop() { uint8_t i; Serial.println("### Start cycle ###"); Serial.println(""); Serial.print("Read value... "); i = 0; while (sensors[i]) { sensors[i]->readValues(); i++; } Serial.println("done!"); Serial.println(""); Serial.println("### End cycle ###"); Serial.println(""); delay(5000); }
true
d4fc1d421a35e81e095b7b6b6d5c10ec3fdc456d
C++
Grzego/agh-miss-project
/MISS Project/simulation/map.h
UTF-8
2,400
3.046875
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <string> #include <memory> #include <unordered_map> #include <unordered_set> #include <SFML\Graphics.hpp> #include "utils.h" #include "knowledge.h" class Agent; /** * Enum opisujacy pola dostepne na mapie. */ enum class Field { Empty, Food, Water, Danger, Blocked, Population, // ----- }; /** * Klasa odpowiedzialna za przechowywanie informacji o mapie i znajdowanie sciezek */ class Map : public sf::Drawable { public: /** * Konstruktor klasy */ Map(); /** * Destruktor klasy */ virtual ~Map(); /** * Metoda zluzaca do wczytywania mapy z pliku * @param _file nazwa pliku z mapa */ void load(std::string const &_file); /** * Metoda sluzaca do wyznaczania sciezki na mapie * @param _start poczatek sciezki * @param _end koniec sciezki * @param _knowledge wiedza do wyznacznia trasy * @param out _total_cost calkowity koszt trasy * @return path wyznaczona sciezka */ std::vector<Vec2> search_path(Vec2 const &_start, Vec2 const &_end, std::shared_ptr<Knowledge> _knowledge, int &_total_cost) const; /** * Metoda pozwala na zmiane typu danego pola * @param pos miejsce * @param field nowy typ */ void change_field(Vec2 const &, Field); /** * Metoda pozwala pobrac typ pola w danym miejscu * @param place miejsce * @return field typ pola */ Field get_field(Vec2 const &) const; /** * Metoda zwraca otoczenia dla danego miejsca * @param place miejsce * @return places pobliskie miejsca */ std::vector<Vec2> places(Vec2 const &) const; /** * Metoda zwraca wymiary mapy * @return wymiary */ Vec2 dimensions() const; /** * Metoda zwraca miejsce startowe populacji * @return miejsce startowe populacji */ Vec2 start() const; // ----- /** * Metoda ustawia podglad na agencie * @param wskaznik do agenta */ void set_agent_view(Agent const *); /** * Metoda z biblioteki SFML sluzaca do rysowania na oknie */ virtual void draw(sf::RenderTarget &, sf::RenderStates) const override; private: std::vector<std::vector<Field>> fields; int width; int height; Vec2 population; // ----- Agent const *agent_view; };
true
aaa3a4818ac5feb24bb0a597e1210c07a38a4448
C++
mamysa/ShaderPreviewer
/src/Logger.cpp
UTF-8
327
2.8125
3
[]
no_license
#include <list> #include "Logger.h" #define MAX_LOG_ENTRIES 32 std::list<LogEntry> Logger::m_buf; void Logger::add(const std::string& str, LogType type) { if (m_buf.size() == MAX_LOG_ENTRIES) m_buf.pop_front(); m_buf.push_back(LogEntry(str, type)); } const std::list<LogEntry>& Logger::getBuf(void) { return m_buf; }
true
781897480570c002b4f1ff75b1b4d9725c49abc8
C++
asutton/beaker-akron
/beaker/sys.int/expr.hpp
UTF-8
5,190
2.640625
3
[ "MIT" ]
permissive
// Copyright (c) 2015-2017 Andrew Sutton // All rights reserved #ifndef BEAKER_SYS_INT_EXPRESSION_HPP #define BEAKER_SYS_INT_EXPRESSION_HPP #include <beaker/base/expr.hpp> namespace beaker { namespace sys_int { enum { first_expr_kind = sys_int_lang_block, #define def_expr(NS, E) E ## _expr_kind, #include "expr.def" last_expr_kind }; // -------------------------------------------------------------------------- // // Expressions /// Represents integer literals. /// /// The type of the expression shall be an integral type. struct int_expr : literal_expr_impl<int_expr_kind> { using literal_expr_impl<int_expr_kind>::literal_expr_impl; std::intmax_t get_integer() const; }; /// Returns the integer value of the expression. inline std::intmax_t int_expr::get_integer() const { return get_value().get_int(); } /// Represents the expression `e1 == e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the values of `e1` and `e2` /// are equal. struct eq_expr : binary_expr_impl<eq_expr_kind> { using binary_expr_impl<eq_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 != e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the values of `e1` and `e2` /// are different. struct ne_expr : binary_expr_impl<ne_expr_kind> { using binary_expr_impl<ne_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 < e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the value of `e1` is less than /// the value of `e2`. struct lt_expr : binary_expr_impl<lt_expr_kind> { using binary_expr_impl<lt_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 > e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the value of `e1` is greater /// than the value of `e2`. struct gt_expr : binary_expr_impl<gt_expr_kind> { using binary_expr_impl<gt_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 <= e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the value of `e1` is less than /// or equal to the value of `e2`. struct le_expr : binary_expr_impl<le_expr_kind> { using binary_expr_impl<le_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 >= e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall be `bool`. /// /// The value of the expression is `true` when the value of `e1` is greater /// than or equal to the value of `e2`. struct ge_expr : binary_expr_impl<ge_expr_kind> { using binary_expr_impl<ge_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 + e2`. /// /// The operands `e1` and `e2` shall have the same type `t`, and `t` shall be /// an arithmetic type. The type of the expression shall also be `t`. /// /// The value of the expression is the sum of the values of `e1` and `e2`. struct add_expr : binary_expr_impl<add_expr_kind> { using binary_expr_impl<add_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 - e2`. /// /// \todo Document me. struct sub_expr : binary_expr_impl<sub_expr_kind> { using binary_expr_impl<sub_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 * e2`. /// /// \todo Document me. struct mul_expr : binary_expr_impl<mul_expr_kind> { using binary_expr_impl<mul_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 / e2`. The operands shall have integral /// type. The division of integer values results in the quotient of division. /// /// \todo Document me. struct quo_expr : binary_expr_impl<quo_expr_kind> { using binary_expr_impl<quo_expr_kind>::binary_expr_impl; }; /// Represents the expression `e1 % e2`. /// /// \todo Document me. struct rem_expr : binary_expr_impl<rem_expr_kind> { using binary_expr_impl<rem_expr_kind>::binary_expr_impl; }; /// Represents the negation expression `-e`. /// /// \todo Document me. struct neg_expr : unary_expr_impl<neg_expr_kind> { using unary_expr_impl<neg_expr_kind>::unary_expr_impl; }; /// Represents the reciprocal expression `/e`. /// /// \todo Document me. /// /// \todo Is this even useful for integers? It's 0 in all cases but 2. struct rec_expr : unary_expr_impl<rec_expr_kind> { using unary_expr_impl<rec_expr_kind>::unary_expr_impl; }; // -------------------------------------------------------------------------- // // Operations bool is_integral_expression(const expr&); } // namespace numeric } // namespace beaker #endif
true
87674a31222203607edb8cd8cd4dc3f3f2a4ee9f
C++
MjVlad/Strassen
/Strassen/Main.cpp
UTF-8
453
2.78125
3
[]
no_license
#include "Matrix.h" #include<iostream> #include<vector> #include <ctime> using namespace std; int main() { int size = 0; cin >> size; Matrix mat1 = Matrix(size); mat1.set(); Matrix mat2(size); mat2.set(); Matrix mat3(size); int beg = clock(); mat3 = multiStrassen(mat1, mat2); int end = clock(); cout << endl << endl << end - beg; beg = clock(); mat1 = mat1 * mat2; end = clock(); cout << endl << endl << end - beg; //mat1.print(); }
true
787b4a8a0cc1c20f8f918c45362039f3383d7702
C++
lvdou2518/YBT
/1192:放苹果.cpp
GB18030
865
2.875
3
[]
no_license
#include<cstdio> #include<iostream> #include<cmath> using namespace std; int main() { int t,m,n,i,j; int f[100][100];//һάŵƻάӸ ,ֵΪŵķ scanf("%d",&t); //Сߴ //ʼ ߽ for(i=1;i<=20;i++) f[0][i]=1;//0ƻ for(i=1;i<=20;i++) f[i][1]=1;//1 for(i=1;i<=20;i++) for(j=2;j<=20;j++) { if(i<j) f[i][j]=f[i][i];//ȼ,ΪҲŲƻ else f[i][j]=f[i][j-1]+f[i-j][j];//״̬תƷ //f[i][j-1]̳ͬƻj-1ӵķ //f[i-j][j]ǵǰ״̬δŵڵǰƻµķ } for(int k=0;k<t;k++)//ѭ { scanf("%d%d",&m,&n); printf("%d\n",f[m][n]); } return 0; }
true
287fc4a1048bc2a7bf9aa001efa2f4ca41d89778
C++
Arotte/matura-exercises
/13-may_valasztas.cc
UTF-8
3,497
3.109375
3
[]
no_license
/* Solution for the <2013 May> Hungarian IT matura exam's 4th task */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <algorithm> using namespace std; bool bigger (int a, int b) { return (a<b); } struct Jelolt { int valasztoKer, szavazatok; string nev[2], part; }; int main() { vector<Jelolt> valasztas; //1 ifstream ifs("szavazatok.txt"); int be; while (ifs >> be) { Jelolt jl; jl.valasztoKer = be; ifs >> jl.szavazatok; ifs >> jl.nev[0]; ifs >> jl.nev[1]; ifs >> jl.part; valasztas.push_back(jl); } ifs.close(); //2 cout <<"2.feladat"<<endl << "A kepviselojelolti valasztason osszesen " << valasztas.size() << " emberke indult." << endl; //3 string vezetek, uto; cout <<"3. feladat" << endl << "Bassz ide egy nevet te geci: "; cin >> vezetek >> uto; for (auto it = valasztas.begin(); it != valasztas.end(); ++it) { if (it->nev[0] == vezetek && it->nev[1] == uto) { cout << endl << "Ennyi szavazatot kapott " << vezetek << " " << uto << " : " << it->szavazatok << endl; break; } else if (it == valasztas.end()-1) { cout << "Noope" << endl; } } //4 cout << "4. feladat" <<endl; int count = 0; for (auto it = valasztas.begin(); it != valasztas.end(); ++it) count += it->szavazatok; cout << "A valasztason " << count <<" emberke, a jogosultak "; cout.precision(2); cout << fixed << (double) 100*count/12345<<" %-a vett reszt." << endl; //5 cout << "5. feladat" << endl; int kimutatas[5] = {0}; for (auto it = valasztas.begin(); it != valasztas.end(); ++it) { if (it->part == "GYEP") ++kimutatas[0]; else if (it->part == "HEP") ++kimutatas[1]; else if (it->part == "TISZ") ++kimutatas[2]; else if (it->part == "ZEP") ++kimutatas[3]; else if (it->part == "-") ++kimutatas[4]; } cout.precision(2); cout << "GYEP: " << fixed << (double) (100*kimutatas[0])/valasztas.size() << endl << "HEP: " << fixed << (double) (100*kimutatas[1])/valasztas.size() << endl << "TISZ: " << fixed << (double) (100*kimutatas[2])/valasztas.size() << endl << "ZEP: " << fixed << (double) (100*kimutatas[3])/valasztas.size() << endl << "FUGGETLEN: " << fixed << (double) (100*kimutatas[4])/valasztas.size() << endl; //6 cout << "6. feladat" << endl; vector <int> temp; for (auto it = valasztas.begin(); it != valasztas.end(); ++it) { temp.push_back(it->szavazatok); } sort(temp.begin(), temp.end(), bigger); for (auto it = valasztas.begin(); it != valasztas.end(); ++it) { if (it->szavazatok == temp.back()) { cout << it->nev[0] << " " <<it->nev[1] << " "; if (it->part == "-") cout << "fuggetlen"; else cout << it->part; cout << endl; } } Jelolt kerkimutatas[8]; int kerki_int[8] = {0}; //todo: no need for this array for (auto it = valasztas.begin(); it != valasztas.end(); ++it) { if ( it->szavazatok >= kerki_int[it->valasztoKer-1] ){ kerki_int[it->valasztoKer-1] = it->szavazatok; kerkimutatas[it->valasztoKer-1] = *it; } } ofstream ofs("kepviselok.txt"); for (int i=0; i<8; ++i) { ofs << i+1 << " : "<< kerkimutatas[i].nev[0] << " " << kerkimutatas[i].nev[1]; if (kerkimutatas[i].part == "-") ofs << " fuggetlen" << endl; else ofs <<" " <<kerkimutatas[i].part << endl; } ofs.close(); return 0; }
true
9ed82b847a2337b67d17ebeb85cc6af897244258
C++
bryik/experiments-in-cpp
/experiments/12-functor.cpp
UTF-8
334
3.5625
4
[]
no_license
#include <iostream> using namespace std; // I'm not sure how well C++ handles closures, but it does have functors // (functions with state). struct Counter { int count = 0; int operator()() { return count++; } }; int main() { Counter c; cout << c() << endl; // 0 cout << c() << endl; // 1 cout << c() << endl; // 2 }
true
afcd6e28f4e78d01320bacb1d73383c6445b85c4
C++
wizleysw/backjoon
/6588/solve.cpp
UTF-8
1,130
2.953125
3
[]
no_license
// https://www.acmicpc.net/problem/6588 // 골드바흐의 추측 // Written in C++ langs // 2020. 02. 04. // Wizley #include <iostream> #include <algorithm> #include <string> #include <vector> #include <cmath> using namespace std; long long NUMBER[1000001]={0,}; vector<int> PRIME; void eratosthenes(int until){ for(auto i=2; i<=until; i++){ NUMBER[i] = i; } int r = int(sqrt(until)); for(auto i=2; i<=r; i++){ if(NUMBER[i]==i){ for(auto j=i*i; j<=until; j+=i){ if(NUMBER[j]==j) NUMBER[j]=i; } } } for(int i=3; i<=until; i++){ if(NUMBER[i] == i) PRIME.push_back(i); } } int main(){ ios_base :: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int no; cin >> no; eratosthenes(1000000); while(no!=0){ for(int i=0; i<PRIME.size(); i++){ if(NUMBER[no-PRIME[i]] == no-PRIME[i]){ cout << no << " = " << PRIME[i] << " + " << no-PRIME[i] << "\n"; break; } } cin >> no; } return 0; }
true
c26180d831b737acae624328c8b257e78bafc015
C++
drlongle/leetcode
/algorithms/problem_0941/solution2.cpp
UTF-8
482
3.078125
3
[]
no_license
class Solution { public: bool validMountainArray(vector<int>& arr) { int sz = arr.size(); if (sz < 3 || arr[0] >= arr[1]) return false; bool up = true; for (int i = 1; i < sz; ++i) { if (arr[i] == arr[i-1]) return false; if (up && arr[i] < arr[i-1]) up = false; else if (!up && arr[i] > arr[i-1]) return false; } return !up; } };
true
e40e870b8d9b82dc57018aab645c8358706debe2
C++
BetaOrbiter/CPP_PRIMER
/Chapter_10/10_22.cpp
UTF-8
443
3
3
[]
no_license
#include <string> #include <vector> #include <iostream> #include <algorithm> #include <functional> using namespace std::placeholders; bool lessOrEqualThanN(const std::string &s, std::string::size_type n){ return s.size()<=n; } int main(void){ std::vector<std::string> words{"12345","123456","1234567","12345678"}; auto f = bind(lessOrEqualThanN,_1,6); std::cout << std::count_if(words.cbegin(),words.cend(),f); return 0; }
true
3538d6430854fcde924fd160b142ab8d2541234a
C++
acamargosonosa/imart
/src/affine.h
UTF-8
3,291
2.734375
3
[]
no_license
/* * @Author: jose * @Date: 2019-11-15 13:55:00 * @Last Modified by: jose * @Last Modified time: 2019-11-05 13:55:00 */ #ifndef __AFFINE_H__ #define __AFFINE_H__ // local libs #include "global.h" namespace imart { // Class affine template <typename type, typename container=vector_cpu<type>> class affine: public inherit<affine<type,container>, global<type,container>> { public: //Type definitions using self = affine; using pointer = std::shared_ptr<self>; using vector = std::vector<self::pointer>; // Inherited variables using transform<type,container>::parameters; using transform<type,container>::inverse_parameters; using transform<type,container>::get_parameters; using transform<type,container>::get_inverse_parameters; using transform<type,container>::operator=; using global<type,container>::init; using global<type,container>::inverse_; using inherit<affine<type,container>, global<type,container>>::inherit; protected: // =========================================== // Functions // =========================================== // void init(int d); public: // =========================================== // Constructor Functions // =========================================== affine() : inherit<affine<type,container>, global<type,container>>() { this->class_name = "affine"; }; affine(int d) : inherit<affine<type,container>, global<type,container>>(d) { this->class_name = "affine"; }; affine(int d, typename image<type,container>::pointer params) : inherit<affine<type,container>, global<type,container>>(d, params) { this->class_name = "affine"; }; affine( type a1, type a2, type a3, type a4, type tx, type ty ); affine( type a1, type a2, type a3, type a4, type a5, type a6, type a7, type a8, type a9, type tx, type ty, type tz ); }; template<typename type> using affine_cpu = affine<type,vector_cpu<type>>; // template<typename type> // using affine_gpu = affine<type,vector_opencl<type>>; #ifdef IMART_WITH_OPENCL template<typename type> using affine_opencl = affine<type,vector_opencl<type>>; #endif #ifdef IMART_WITH_CUDA template<typename type> using affine_cuda = affine<type,vector_cuda<type>>; #endif // =========================================== // Functions of Class affine // =========================================== // =========================================== // Constructor Functions // =========================================== template <typename type, typename container> affine<type,container>::affine( type a1, type a2, type a3, type a4, type tx, type ty ) { this->class_name = "affine"; init(2); std::initializer_list<type> ll{ a1, a2, a3, a4, tx, ty }; this->set_parameters( image<type,container>::new_pointer(ll) ); inverse_(); }; template <typename type, typename container> affine<type,container>::affine( type a1, type a2, type a3, type a4, type a5, type a6, type a7, type a8, type a9, type tx, type ty, type tz ) { this->class_name = "affine"; init(3); std::initializer_list<type> ll{ a1, a2, a3, a4, a5, a6, a7, a8, a9, tx, ty, tz }; this->set_parameters( image<type,container>::new_pointer(ll) ); inverse_(); }; }; //end namespace #endif
true
eeb4aeba5861b1025fd3706feb03cb1d053c00c4
C++
m4scosta/contests-training
/URI/1478.cpp
UTF-8
863
2.890625
3
[]
no_license
#include <cstdlib> #include <iostream> #include <stdio.h> #include <vector> using namespace std; void imp_mat_quad(int n){ int m[n][n]; int i, j, k; for(i = 0; i < n; i++){ k = i+2; for(j = 0; j < n; j++){ if(i == j) k = 1; if(i > j) k -= 1; if(i < j) k += 1; m[i][j] = k; } } for(i = 0; i < n; i++){ for(j = 0; j < n; j++){ printf("%3d", m[i][j]); if(j < n-1) cout << " "; } cout << endl; } } int main(int argc, char *argv[]) { int i; cin >> i; while(i){ imp_mat_quad(i); cout << endl; cin >> i; } }
true
1557acf5c7df8d174701d8ff826f5faece8dfd58
C++
WhiZTiM/coliru
/Archive2/21/ab8ed2c97cc879/main.cpp
UTF-8
1,383
3.34375
3
[]
no_license
#include <utility> template<typename F> struct ScopeGuard { ScopeGuard(F&& f) : mFunction(std::forward<F>(f)) { } // disable copy ScopeGuard(const ScopeGuard&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete; // enable move ScopeGuard(ScopeGuard&&) noexcept = default; ScopeGuard& operator=(ScopeGuard&&) noexcept = default; ~ScopeGuard() { if (mActive) { mFunction(); } } void release() { mActive.release(); } private: F mFunction; // Movable boolean. struct Flag { Flag() : mFlag(true) {} Flag(Flag&& rhs) noexcept : mFlag(rhs.mFlag) { rhs.mFlag = false; } Flag& operator=(Flag&& rhs) noexcept { mFlag = rhs.mFlag; rhs.mFlag = false; return *this; } Flag(const Flag&) = default; Flag& operator=(const Flag&) = default; explicit operator bool() const { return mFlag; } void release() { mFlag = false; } private: bool mFlag; }; Flag mActive; }; template<typename F> inline ScopeGuard<F> make_scope_guard(F&& f) { return ScopeGuard<F>(std::forward<F>(f)); } #include <iostream> int main() { auto guard = make_scope_guard([]{ std::cout << "bye" << std::endl; }); }
true
070acfd562871dde82415d3b67df2ae7187aa17a
C++
agangavaram/rcj-2018-soccer-lightweight
/motorTests/motorMovement.ino
UTF-8
826
2.609375
3
[]
no_license
#include <SoftwareSerial.h> #include <PololuQik.h> PololuQik2s9v1 qikF(2, 3, 4); PololuQik2s9v1 qikB(10,11,12); void go(float degree) { float pi = 3.1415; float rad = degree/(180/pi); int FLSpeed = (-(sin(rad)*127)*(sqrt(3)/2)) - ((cos(rad)*127)/2); // front-left int FRSpeed = (sin(rad)*127)*sqrt(3)/2 - (cos(rad)*127)/2; // front-right int BSpeed = (cos(rad)*127); qikF.setM0Speed(FLSpeed); qikF.setM1Speed(FRSpeed); qikB.setM1Speed(BSpeed); } void stop() { qikF.setM0Speed(0); qikF.setM1Speed(0); qikB.setM0Speed(0); } void setup() { qikF.init(); qikB.init(); go(90); delay(1000); stop(); delay(1000); go(270); delay(1000); stop(); delay(1000); go(0); delay(1000); stop(); delay(1000); go(180); delay(1000); stop(); delay(1000); } void loop() { }
true
7251165957ee157cb9b242f2679a1498669980c3
C++
jokerpwn/heuristic-algorithm-learning
/tabu.cpp
UTF-8
12,843
2.859375
3
[]
no_license
#include <iostream> #include <ctime> #include <string> #include <cstdlib> #include <vector> #include <fstream> #include <ostream> using namespace std; const int MaxIter=100000; void string2arc(const string &a,vector<int> &b,const string &delim){ string::size_type pos1=a.find(delim),pos2=a.find(delim,pos1+1); string str1=a.substr(pos1,pos2-pos1),str2=a.substr(pos2); const char *num_str1=str1.c_str(),*num_str2=str2.c_str(); b[0]=atoi(num_str1); b[1]=atoi(num_str2); } void string2vex(const string &a,vector<int> &b,const string &delim){ string::size_type pos0=a.find(delim),pos1=a.find(delim,pos0+1)+1,pos2=a.find(delim,pos1+1); string str1=a.substr(pos1,pos2-pos1); string str2=a.substr(pos2); const char *num_str1=str1.c_str(),*num_str2=str2.c_str(); b.push_back(atoi(num_str1)); b.push_back(atoi(num_str2)); cout<<atoi(num_str1)<<" "<<atoi(num_str2)<<endl; } class tabu_search{ public: int *Sol;//节点对应颜色值 int f;//冲突值 // int *BestSol;//最优解 int best_f;//历史最优冲突值 long long **TabuTenure;//禁忌表 int **Adjacent_Color_Table;//邻接颜色表 int N,e;//点数,边数 int K;//颜色数 int neibor_bucket[9][10000][2]={0};//存放各邻域动作的桶 int ****Pos;//辅助桶排序数据结构 int **graph;//图--记录邻接边,方便更新邻接颜色表 long long iter;//步数记录 int tabu_best_move[2];//记录当前禁忌表中BEST_MOVE int non_tabu_best_move[2];//记录当前非禁忌表中BEST_MOVE void put_color_num(int color_num){ K=color_num; } //初始化各数据结构 void Initialization(){ ifstream infile("DSJC125.1.col.txt",ios::in); string delim=" "; string str; int tmp_delt;//桶初始化 if(!infile.good()) { cout<<"file open error"<<endl; return; } vector<int> num; f=0; while(!infile.fail()){ getline(infile,str); if(str.find("p")==0){ string2vex(str,num,delim); N=num[0]; e=num[1]; //内存分配 Sol=new int[N]; Adjacent_Color_Table=new int *[N]; graph=new int*[N]; TabuTenure=new long long*[N]; Pos=new int ***[N]; //数值初始化 for(int i=0;i<N;i++){ Adjacent_Color_Table[i]=new int[K]; TabuTenure[i]=new long long[K]; graph[i]=new int[N]; Pos[i]=new int **[K]; for(int k=0;k<K;k++) { Adjacent_Color_Table[i][k] = 0; TabuTenure[i][k] = 0; Pos[i][k]=new int *[K+1]; for(int j=0;j<K+1;j++) { Pos[i][k][j]=new int[2]; Pos[i][k][j][0]=0; Pos[i][k][j][1]=0; } } graph[i][0]=0; for(int j=1;j<N;j++) graph[i][j]=-1; } for(int i=0;i<N;i++){ Sol[i]=rand()%K;//初始解 } } else if(str.find("e")==0){ string2arc(str,num,delim); int first=num[0]-1,next=num[1]-1;//对应数组下标 //邻接颜色表统计+图数据初始化 graph[first][0]++; graph[next][0]++; graph[first][graph[first][0]]=next; graph[next][graph[next][0]]=first; Adjacent_Color_Table[first][Sol[next]]++; Adjacent_Color_Table[next][Sol[first]]++; if(Sol[first]==Sol[next])//存在冲突,加入邻域动作 { f++; for(int k=0;k<K;k++){ if(k!=Sol[first]){ tmp_delt=Adjacent_Color_Table[first][k]-Adjacent_Color_Table[first][Sol[first]]; put_buc(tmp_delt,k,first); Pos[first][Sol[first]][K][1]=true;//新增冲突标志位 } if(k!=Sol[next]){ tmp_delt=Adjacent_Color_Table[next][k]-Adjacent_Color_Table[next][Sol[next]]; put_buc(tmp_delt,k,next); Pos[next][Sol[next]][K][1]=true;//新增冲突标志位 } } } } } best_f=f; infile.close(); } void FindMove(int &u,int &vi,int &vj,int &delt){ delt=10000; int delt1=10000; int i,pos,new_color,j,count,final_node,final_color; int tabu_count; bool tabu=false; for(j=0;j<9;j++){ tabu_count=0; bool in=true; count=neibor_bucket[j][0][0]; while(in&&count){ pos=rand()%count+1;//随机选择动作 i=neibor_bucket[j][pos][0]; new_color=neibor_bucket[j][pos][1]; if(Pos[i][Sol[i]][new_color][1]) { if(TabuTenure[i][new_color]<iter){ delt=Adjacent_Color_Table[i][new_color]-Adjacent_Color_Table[i][Sol[i]]; in=false; } else{ delt1=Adjacent_Color_Table[i][new_color]-Adjacent_Color_Table[i][Sol[i]]; tabu_count++; if(f+delt1<best_f) { in=false; tabu=true; } } } else//此动作不存在,则进行删除 { final_node=neibor_bucket[j][count][0]; final_color=neibor_bucket[j][count][1]; neibor_bucket[j][pos][0]=final_node; neibor_bucket[j][pos][1]=final_color; count=--neibor_bucket[j][0][0]; Pos[final_node][Sol[final_node]][final_color][1]=pos; } if(!count||tabu_count==count) in=false; } if(count&&tabu_count!=count) break; } //最终判断 if(tabu) { delt=delt1; u=i; vj=new_color; } else{ u=i; vj=new_color; } int tag; if(delt==10000) cin>>tag; vi=Sol[u]; } void MakeMove(int &u,int &vi,int &vj, int &delt){ Sol[u]=vj; f=f+delt; if(best_f>f) best_f=f; //更新禁忌表 TabuTenure[u][vi]=iter+f+rand()%10; int tmp,tmp_delt; int i; int pos,final,count; bool tag; //邻接颜色表和桶更新 for(int m=1;m<=graph[u][0];m++) { i = graph[u][m]; tmp = Sol[i]; Adjacent_Color_Table[i][vi]--; Adjacent_Color_Table[i][vj]++; tag=Pos[i][tmp][K][1]; if (!Adjacent_Color_Table[i][tmp]&&tag) {//冲突消除,标志 for(int k=0;k<K;k++){ Pos[i][tmp][k][1]=0; } Pos[i][tmp][K][1]=false; } else if (vj == tmp && !tag) {//新增加冲突,邻域动作更新 for (int k = 0; k < K; k++) { if (k == tmp) continue; tmp_delt = Adjacent_Color_Table[i][k] - Adjacent_Color_Table[i][tmp]; put_buc(tmp_delt,k,i); } Pos[i][tmp][K][1]=true; } else if (tag) {//仍为冲突节点,考虑DELT变化的动作加入桶 if (vi == Sol[i]) {//该节点在老颜色中 tmp_delt= Adjacent_Color_Table[i][vj] - Adjacent_Color_Table[i][vi] + 2;//移到新颜色delt+2 put_buc(tmp_delt,vj,i); for (int k = 0; k < K; k++) {//移到其他颜色DELT+1 if (k == vi || k == vj) continue; tmp_delt=Adjacent_Color_Table[i][k] - Adjacent_Color_Table[i][vi] + 1; Pos[i][vi][k][1]=0; put_buc(tmp_delt,k,i); } } else if (vj == Sol[i]) {//该节点在新颜色中 tmp_delt= Adjacent_Color_Table[i][vi] - Adjacent_Color_Table[i][vj] - 2;//移到老颜色DELT-2 Pos[i][vj][vi][1]=0; put_buc(tmp_delt,vi,i); for (int k = 0; k < K; k++) { if (k == vi || k == vj) continue; tmp_delt= Adjacent_Color_Table[i][k] - Adjacent_Color_Table[i][vj] - 1;//移到其他颜色DELT-1 Pos[i][vj][k][1]=0; put_buc(tmp_delt,k,i); } } else { //其他颜色移到老颜色中 tmp_delt= Adjacent_Color_Table[i][vi] - Adjacent_Color_Table[i][Sol[i]] - 1; Pos[i][Sol[i]][vi][1]=0; put_buc(tmp_delt,vi,i); //其他颜色移到新颜色中 tmp_delt= Adjacent_Color_Table[i][vj] - Adjacent_Color_Table[i][Sol[i]] + 1; Pos[i][Sol[i]][vj][1]=0; put_buc(tmp_delt,vj,i); } } } //若节点本身不再有冲突,邻域动作应删除 if(!Adjacent_Color_Table[u][vj]&&Pos[u][vi][vj][1]) for(int k=0;k<k;k++) Pos[u][vj][k][1]=0; } inline void put_buc(int tmp_delt,int new_color,int node) { int buc_num,count; int old_color=Sol[node]; if (tmp_delt <= -4) buc_num = 0; else if (tmp_delt >= 4) buc_num = 8; else { switch (tmp_delt) { case -3: buc_num = 1; break; case -2: buc_num = 2; break; case -1: buc_num = 3; break; case 0: buc_num = 4; break; case 1: buc_num = 5; break; case 2: buc_num = 6; break; case 3: buc_num = 7; break; } } int i,color; //插到第一个非空位置 if(neibor_bucket[buc_num][0][0]>=N*K){ while(true){ count=rand()%neibor_bucket[buc_num][0][0]+1;//随机选择动作 i=neibor_bucket[buc_num][count][0]; color=neibor_bucket[buc_num][count][1]; if(!Pos[i][Sol[i]][color][1])//空位插入 break; } } else{//插到末尾 count=++neibor_bucket[buc_num][0][0]; } neibor_bucket[buc_num][count][0] = node; neibor_bucket[buc_num][count][1] = new_color; Pos[node][old_color][new_color][0] = buc_num; Pos[node][old_color][new_color][1]=count; } void run(){ iter=0; ofstream ofile("/Users/jokerpwn/Desktop/instances/test.txt ", ios::out); if(!ofile.good()) { cout<<"file open error"<<endl; return; } srand(clock()); ofile<<"随机种子"<<clock()<<endl; Initialization(); double start_time,end_time,elapsed_time; start_time=clock(); int u,vi,vj,delt; while(f>0){//冲突仍存在 iter++; FindMove(u,vi,vj,delt); MakeMove(u,vi,vj,delt); if(iter%100000==0) cout<<best_f<<" "<<delt<<" "<<iter<<" "<<f<<endl; } end_time=clock(); elapsed_time=(end_time - start_time)/CLOCKS_PER_SEC; ofile<<"颜色数"<<K<<"解具体情况:"<<endl; for(int i=0;i<N;i++) ofile<<i+1<<" "<<Sol[i]<<endl; ofile<<"时间"<<elapsed_time<<endl; ofile<<"迭代次数"<<iter<<endl; ofile.close(); } }; int main(){ tabu_search init; int color_num; cout<<"输入颜色数:"; cin>>color_num; init.put_color_num(color_num); init.run(); }
true
cdb0d27992b8de388fb0ad60af8ab17cb00bb5e6
C++
raginghawk/smash-up
/Smash Up PreDesign/Model/ActionCards/Pirates/PowderKegAction.cpp
UTF-8
809
2.625
3
[]
no_license
#include "PowderKegAction.h" #include <Board.h> #include <Player.h> #include <Base.h> #include <MinionCard.h> PowderKegAction::PowderKegAction(Player *owner) : ActionCard(owner) { this->_name = "Powderkeg"; _cardType = INSTANT_CARD; } void PowderKegAction::play() { std::vector<MinionCard *> minionOptions = vBoard->playersMinionsInPlay(_currentOwner); if (minionOptions.size() == 0) return; MinionCard *selection = _currentOwner->selectCard(minionOptions); int power = selection->currentPower(); Base * base = selection->base(); std::vector<MinionCard *> minionsToDestory = base->minionsWithPowerLessThan(power + 1); std::vector<MinionCard *>::iterator itMinions; for (itMinions = minionsToDestory.begin(); itMinions != minionsToDestory.end(); itMinions++) { (*itMinions)->destroy(); } }
true
6327a4dcb93b328aecb9a4c7930e14c54ba3c986
C++
Leslie-Fang/C-Solution2Leetcode
/605CanPlaceFlowers/main.cpp
UTF-8
1,382
3.359375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int res = 0; int index = 0; while(index < flowerbed.size()) { if(flowerbed[index] == 0) { if(index+1<flowerbed.size() && index-1>=0) { if(flowerbed[index+1] == 0 && flowerbed[index-1] == 0) { res+=1; flowerbed[index] = 1; index += 2; }else if(flowerbed[index+1] == 0) { index += 1; }else { index += 2; } }else if(index+1<flowerbed.size()) { if(flowerbed[index+1] == 0) { res+=1; flowerbed[index] = 1; } index += 2; } else if(index-1>=0) { if(flowerbed[index-1] == 0) { res +=1; } index += 1; }else { res += 1; index += 2; } }else { index += 1; } if(res >= n) { return true; } } if(res >= n) { return true; } return false; } }; int main(int argc, char ** argv) { int a[6] = {1,0,0,0,0,1}; vector<int> input(a,a+6); Solution * mySolution = new Solution(); cout<<mySolution->canPlaceFlowers(input, 2)<<endl; delete mySolution; return 0; }
true
055a3b91685f1117570dbcdbfbe142eca35abb59
C++
tomer-shinar/advanced1-ex4
/solvers/SearcherAdapter.cpp
UTF-8
1,088
2.890625
3
[]
no_license
// // Created by tomer on 01/02/2020. // #include "SearcherAdapter.h" #include "../search/SearchableMatrix.h" #include <sstream> #include "../search/a_star.h" vector<int> to_vector(string s) { /** * takes string and split it to vector of ints */ stringstream ss(s); string token; vector<int> values; while (getline(ss, token, ',')) values.push_back(stoi(token)); return values; } SearchSolution SearcherAdapter::solve(StringVectorProblem problem) { vector<vector<int>> mat; int i; for (i = 0; i < problem.GetVec().size() - 2; i++) { //going other all lines accept the last 2 int line = problem.GetVec().size(); //to_vector(line); vector<int> push = to_vector(problem.GetVec()[i]); mat.push_back(push); } pair<int, int> src, dst; src.first = to_vector(problem.GetVec()[i])[0]; src.second = to_vector(problem.GetVec()[i])[1]; dst.first = to_vector(problem.GetVec()[i + 1])[0]; dst.second = to_vector(problem.GetVec()[i + 1])[1]; AStar<pair<int, int>> searcher; return searcher.Search(new SearchableMatrix(mat, src, dst)); }
true
14e03b7652006838701cf5d2fbb8f1352dd9b020
C++
stefanRuffler/JUCE-Drum-Sequencer
/Source Code/SequencerRow.cpp
UTF-8
1,804
2.703125
3
[]
no_license
// // SequencerRow.cpp // JuceBasicAudio // // Created by Stefan Ruffler on 22/12/2016. // // #include "SequencerRow.hpp" SequencerRow::SequencerRow() { } SequencerRow::~SequencerRow() { audioTransportSource.setSource(0);//unload the current file deleteAndZero(currentAudioFileSource);//delete the current file } void SequencerRow::setPlaying (const bool newState) { if(newState == true) { audioTransportSource.setPosition(0.0); audioTransportSource.start(); } else { audioTransportSource.stop(); } } /** Gets the current playback state of the sequencerRow */ bool SequencerRow::isPlaying () const { return audioTransportSource.isPlaying(); } /** Loads the specified file into the transport source */ void SequencerRow::loadFile(const File& newFile) { setPlaying(false); audioTransportSource.setSource (0); //deleteAndZero (currentAudioFileSource); AudioFormatManager formatManager; formatManager.registerBasicFormats(); AudioFormatReader* reader = formatManager.createReaderFor (newFile); if (reader != 0) { currentAudioFileSource = new AudioFormatReaderSource (reader, true); audioTransportSource.setSource (currentAudioFileSource); } } void SequencerRow::setGain(float newGainValue) { audioTransportSource.setGain(newGainValue); } //AudioSource void SequencerRow::prepareToPlay (int samplesPerBlockExpected, double sampleRate) { audioTransportSource.prepareToPlay (samplesPerBlockExpected, sampleRate); } void SequencerRow::releaseResources() { audioTransportSource.releaseResources(); } void SequencerRow::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { audioTransportSource.getNextAudioBlock (bufferToFill); }
true
94bc1608974dcd7a8b04b10b671f269155fd06d0
C++
tonymontaro/leetcode-submissions
/01-July-2021/sorting-the-sentence/Accepted/5-30-2021, 6:10:43 AM/Solution.cpp
UTF-8
629
3.28125
3
[]
no_license
// https://leetcode.com/problems/sorting-the-sentence vector<string> splitWord(string &text) { istringstream iss(text); vector<string> results((istream_iterator<string>(iss)), istream_iterator<string>()); return results; } class Solution { public: string sortSentence(string s) { map<int, string> seen; auto words = splitWord(s); for (const auto &w: words) { seen[w[w.size() - 1] - '0'] = w.substr(0, w.size() - 1); } string ans = ""; for (int i = 0; i < seen.size(); i++) ans += seen[i+1] + " "; return ans.substr(0, ans.size() - 1); } };
true
201ccda33fb97f7247ee7df41849b59eca3750cf
C++
JesseKrepelka/CSCI-21-FALL-2015
/pp1.cpp
UTF-8
10,339
3.484375
3
[]
no_license
/* * Programming Project 1 * Written by: Jesse Krepelka * Unittest taken from provided file. * * completed on: 9/18/15 */ #include <iostream> #include <sstream> #include <string> #include <cctype> #include <cassert> #include <climits> using namespace std; /* * counts the number of both alphabetic characters and numeric characters * in a provided string. * @param aString The string provided * @param numOfAlph Counter holding the number of alphabetic characters * @param numOfNum Counter holding the number of numeric characters */ void countCharacters(string aString, int& numOfAlph, int& numOfNum); /* * capitalize/lowercases every other character in a string starting with * the first character * @param aString The string provided * @return the altered string */ string upAndDown(string aString); /* * counts the number of words in the provided string, assumes that there * will be no back to back spaces and that string will never begin or end * with spaces. * @param aString The string provided * @return an int containing the number of words in the given string */ int countWords(string aString); /* * computes the average of the values in an array, assumes that the sized of * the provided array is never 0 * @param array the array to be averaged * @param size the size of the provided array * @return an int containing the average of all values in the provided array */ int computeAverage(int array[], int size); /* * loops through the array to find the smallest value. * @param array the array to be looped through * @param size the size of the provided array * @return an int containing the smallest of all values in the provided array */ int findMinValue(int array[], int size); /* * loops through the array to find the largest value. * @param array the array to be looped through * @param size the size of the provided array * @return an int containing the largest of all values in the provided array */ int findMaxValue(int array[], int size); template <typename X, typename A> void btassert(A assertion); void unittest (); int main(int argc, char* argv[]){ unittest(); return 0; } void countCharacters(string aString, int& numOfAlph, int& numOfNum){ numOfNum = 0; numOfAlph = 0; for(int i = 0; i < aString.length(); i++){ if(isdigit(aString[i])){ numOfNum++; } else if(isalpha(aString[i])){ numOfAlph++; } } } string upAndDown(string aString){ for(int i = 0; i<aString.length(); i++){ if(i%2 == 0){ aString[i] = toupper(aString[i]); } else{ aString[i] = tolower(aString[i]); } } return(aString); } int countWords(string aString){ int numOfWords = 0; if(aString.length() > 0){ numOfWords++; } for(int i = 0; i<aString.length(); i++){ if(isspace(aString[i])){ numOfWords++; } } return(numOfWords); } int computeAverage(int array[], int size){ int sum = 0; for(int i = 0; i < size; i++){ sum = sum + array[i]; } sum = sum/size; return(sum); } int findMinValue(int array[], int size){ int min = array[0]; for(int i = 1; i < size; i++){ if(min > array[i]){ min = array[i]; } } return(min); } int findMaxValue(int array[], int size){ int max = array[0]; for(int i = 1; i < size; i++){ if(max < array[i]){ max = array[i]; } } return(max); } void unittest () { unsigned short utCount = 30; unsigned short utPassed = 0; cout << "\nSTARTING UNIT TEST\n\n"; int n1=0, n2=0; try { countCharacters("", n1, n2); btassert<bool>((n1 == 0) && (n2 == 0)); cout << "Passed TEST 1: countCharacters(empty string)\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 1 #\n"; } try { countCharacters("hello", n1, n2); btassert<bool>((n1 == 5) && (n2 == 0)); cout << "Passed TEST 2: countCharacters(\"hello\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 2 #\n"; } try { countCharacters("12345", n1, n2); btassert<bool>((n1 == 0) && (n2 == 5)); cout << "Passed TEST 3: countCharacters(\"12345\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 3 #\n"; } try { countCharacters("hello 12345", n1, n2); btassert<bool>((n1 == 5) && (n2 == 5)); cout << "Passed TEST 4: countCharacters(\"hello 12345\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 4 #\n"; } try { countCharacters("&,.", n1, n2); btassert<bool>((n1 == 0) && (n2 == 0)); cout << "Passed TEST 5: countCharacters(\"&,.\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 5 #\n"; } string s; try { s = upAndDown("hello"); btassert<bool>(s == "HeLlO"); cout << "Passed TEST 6: upAndDown(\"hello\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 6 #\n"; } try { s = upAndDown("HeLlO"); btassert<bool>(s == "HeLlO"); cout << "Passed TEST 7: upAndDown(\"HeLlO\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 7 #\n"; } try { s = upAndDown("hElLo"); btassert<bool>(s == "HeLlO"); cout << "Passed TEST 8: upAndDown(\"hElLo\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 8 #\n"; } try { s = upAndDown(""); btassert<bool>(s == ""); cout << "Passed TEST 9: upAndDown(empty string)\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 9 #\n"; } try { s = upAndDown("a"); btassert<bool>(s == "A"); cout << "Passed TEST 10: upAndDown(\"a\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 10 #\n"; } try { btassert<bool>(countWords("") == 0); cout << "Passed TEST 11: countWords(empty string)\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 11 #\n"; } try { btassert<bool>(countWords("hello") == 1); cout << "Passed TEST 12: countWords(\"hello\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 12 #\n"; } try { btassert<bool>(countWords("hello,world") == 1); cout << "Passed TEST 13: countWords(\"hello world\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 13 #\n"; } try { btassert<bool>(countWords("hello world") == 2); cout << "Passed TEST 14: countWords(\"hello world\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 14 #\n"; } try { btassert<bool>(countWords("hello, world") == 2); cout << "Passed TEST 15: countWords(\"hello, world\")\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 15 #\n"; } int values [] = {10, 20, 30}; try { btassert<bool>(computeAverage(values, 3) == 20); cout << "Passed TEST 16: computeAverage([10,20,30])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 16 #\n"; } values[0] = 0, values[1] = 0, values[2] = 0; try { btassert<bool>(computeAverage(values, 3) == 0); cout << "Passed TEST 17: computeAverage([0,0,0])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 17 #\n"; } values[0] = 5, values[1] = 7, values[2] = 11; try { btassert<bool>(computeAverage(values, 3) == 7); cout << "Passed TEST 18: computeAverages([5,7,11])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 18 #\n"; } values[0] = -10, values[1] = -20, values[2] = -30; try { btassert<bool>(computeAverage(values, 3) == -20); cout << "Passed TEST 19: computeAverages([-10,-20,-30])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 19 #\n"; } values[0] = -5, values[1] = 0, values[2] = 5; try { btassert<bool>(computeAverage(values, 3) == 0); cout << "Passed TEST 20: computeAverages([-5,0,5])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 20 #\n"; } values[0] = -1, values[1] = 0, values[2] = 1; try { btassert<bool>(findMinValue(values, 3) == -1); cout << "Passed TEST 21: findMinValue([-1,0,1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 21 #\n"; } values[0] = -3, values[1] = -2, values[2] = -1; try { btassert<bool>(findMinValue(values, 3) == -3); cout << "Passed TEST 22: findMinValue([-3,-2,-1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 22 #\n"; } values[0] = 0, values[1] = 1, values[2] = 2; try { btassert<bool>(findMinValue(values, 3) == 0); cout << "Passed TEST 23: findMinValue([0,1,2])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 23 #\n"; } values[0] = 1, values[1] = 1, values[2] = 1; try { btassert<bool>(findMinValue(values, 3) == 1); cout << "Passed TEST 24: findMinValue([1,1,1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 24 #\n"; } values[0] = INT_MAX, values[1] = INT_MAX, values[2] = INT_MAX; try { btassert<bool>(findMinValue(values, 3) == INT_MAX); cout << "Passed TEST 25: findMinValue([INT_MAX,INT_MAX,INT_MAX])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 25 #\n"; } values[0] = -1, values[1] = 0, values[2] = 1; try { btassert<bool>(findMaxValue(values, 3) == 1); cout << "Passed TEST 26: findMaxValue([-1,0,1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 26 #\n"; } values[0] = -3, values[1] = -2, values[2] = -1; try { btassert<bool>(findMaxValue(values, 3) == -1); cout << "Passed TEST 27: findMaxValue([-3,-2,-1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 27 #\n"; } values[0] = 0, values[1] = 1, values[2] = 2; try { btassert<bool>(findMaxValue(values, 3) == 2); cout << "Passed TEST 28: findMaxValue([0,1,2])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 28 #\n"; } values[0] = 1, values[1] = 1, values[2] = 1; try { btassert<bool>(findMaxValue(values, 3) == 1); cout << "Passed TEST 29: findMaxValue([1,1,1])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 29 #\n"; } values[0] = INT_MIN, values[1] = INT_MIN, values[2] = INT_MIN; try { btassert<bool>(findMaxValue(values, 3) == INT_MIN); cout << "Passed TEST 30: findMaxValue([INT_MIN,INT_MIN,INT_MIN])\n"; ++utPassed; } catch (bool b) { cout << "# FAILED TEST 30 #\n"; } cout << "\nUNIT TEST COMPLETE\n\n"; cout << "PASSED " << utPassed << " OF " << utCount << " UNIT TEST"; if (utCount > 1) { cout << "S"; } cout << "\n\n"; } template <typename X, typename A> void btassert (A assertion) { if (!assertion) throw X(); }
true
65e971cd227302b1687e97a7b3024c8ed2e37fe2
C++
babamore/olymp
/coruption.cpp
UTF-8
548
2.59375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int n , i , a; double proc , tmpa , tmpb; vector<double> v; cin >> n >> proc; for (i=0; i<n; i++){ cin >> a; v.push_back(a); } while (v.size()!=0){ sort(v.begin() , v.end()); tmpa = v[0]; tmpb = v[v.size()-1]; cout << tmpa << " "<<tmpb<<endl; v.erase(v.begin()); v.pop_back(); que.push((tmpa+tmpb)*(1-(proc/100))); } cout << v[0]<<endl; }
true
d58b1165d1ac90ed6df9df29f170780cb66bb42f
C++
isaveu/OpenGLRenderFramework
/Vector2.h
UTF-8
1,080
3.03125
3
[ "Zlib" ]
permissive
#pragma once #include "Helpers.h" struct Vector2 { public: Vector2(); Vector2(float x, float y); virtual ~Vector2(); bool operator==(const Vector2& v1) { if (x == v1.x && y == v1.y) return true; return false; } bool operator!=(const Vector2& v1) { if (x == v1.x && y == v1.y) return false; return true; } bool operator()(const Vector2& v1) { if (x == v1.x && y == v1.y) return false; return true; } float length(); float dot(Vector2 vec2); float dot(Vector2 vec1, Vector2 vec2); float cross(Vector2 vec); Vector2 absolute(); Vector2 normalized(); Vector2 rotate(float angle); float x; float y; }; Vector2 operator+(Vector2 v1, Vector2 v2); Vector2 operator-(Vector2 v); Vector2 operator-(Vector2 v1, Vector2 v2); Vector2 operator*(Vector2 v1, float s); Vector2 operator*(float s, Vector2 v1); Vector2 operator/(Vector2 v1, float s); float operator^(Vector2 v1, Vector2 v2); // DOT product Vector2 operator*(Vector2 v1, Vector2 v2); // CROSS product Vector2 planelineintersection(Vector2 n, float d, Vector2 p1, Vector2 p2);
true
adff6ba15024ee3d96c4167c5351501da923c261
C++
parakram10/CP_CipherSchool
/Recursion and Backtracking/SubsetSum.cpp
UTF-8
712
3.21875
3
[]
no_license
// https://www.geeksforgeeks.org/subset-sum-backtracking-4/ #include<bits/stdc++.h> using namespace std; void subsetSum(vector<int> v, vector<string>& res, int n, int k, int i, int sum, string currVal){ if(sum == k){ res.push_back(currVal); return; } if(i==n) { return; } subsetSum(v,res,n,k,i+1,sum,currVal); currVal+=" "; currVal+= to_string(v[i]); subsetSum(v,res,n,k,i+1,sum+v[i],currVal); } int main(){ vector<int> v = {15, 22, 14, 26, 32, 9, 16, 8}; int k = 53; int n = v.size(); vector<string> res; subsetSum(v,res,n,k,0,0,""); for(int i=0;i<res.size();i++){ cout<<res[i]<<"\n"; } }
true
b039e3331e779bc27c95cd728b969fb7c2aa2997
C++
Swaransh2903/Open-DSA
/Algorithms/arrays/frequency of occurence/freq.cpp
UTF-8
825
3.484375
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; //NAIVE O(n*n) void frequency1(int arr[], int n){ for(int i=0; i<n; i++){ cout<<arr[i]<<" : "; int count = 1; for(int j=i+1; j<n;j++){ if(arr[j] == arr[i]){ count++; } } i+=(count-1); cout<<count<<endl; } } //theta(n) void frequency2(int arr[], int n){ int freq=1,i=1; while(i<n){ while(i<n && arr[i] == arr[i-1]){ freq++; i++; } cout<<arr[i-1]<<" : "<<freq<<endl; i++; freq = 1; } if(n==1 || arr[n-1] != arr[n-2]){ cout<<arr[n-1]<<" : "<<1<<endl; } } int main(){ int arr[] = {10,10,10,25,30,30}; int n = 6; frequency1(arr,n); cout<<endl; frequency2(arr,n); return 0; }
true
80fae29412d2dc977a091f58b034656b6d63b353
C++
dim49v/polarCodes
/PolarCodes/SCDecoderMinsum.cpp
UTF-8
2,662
2.71875
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <random> #include <vector> #include <thread> #include <mutex> #include <string> #include <time.h> #include "Resources.cpp" namespace SCDecoderMinsum { inline double Decodef(double r1, double r2) { return std::min(abs(r1), abs(r2)) * (r1 * r2 < 0 ? -1. : 1.); } char Decodef_char(char r1, char r2) { unsigned char mr1 = (r1 > 0) ? r1 : -r1; unsigned char mr2 = (r2 > 0) ? r2 : -r2; unsigned char mm = (mr1 < mr2) ? mr1 : mr2; unsigned char sr = (r1 ^ r2) & 0x80; return (sr == 0) ? mm : -mm; } inline double Decodeg(double r1, double r2, int b) { return r2 + r1 * (1 - b * 2); } char Decodeg_char(char r1, char r2, int b) { return r2 + r1 * (1 - b * 2); } void DecodeNode(int n, int m, int& solSize, double** decTree1, int** decTree2, int* sol, const std::vector<int>& frozenBits) { if (2 << m == n) { int u1, u2; u1 = frozenBits[solSize] != -1 ? frozenBits[solSize] : Decodef(decTree1[m][0], decTree1[m][1]) > 0 ? 0 : 1; sol[solSize] = u1; solSize++; u2 = frozenBits[solSize] != -1 ? frozenBits[solSize] : Decodeg(decTree1[m][0], decTree1[m][1], u1) > 0 ? 0 : 1; sol[solSize] = u2; solSize++; decTree2[m][0] = u1 ^ u2; decTree2[m][1] = u2; return; } else { int nodeSize = n >> m; for (int i = 0; i < nodeSize; i += 2) { decTree1[m + 1][i / 2] = Decodef(decTree1[m][i], decTree1[m][i + 1]); } DecodeNode(n, m + 1, solSize, decTree1, decTree2, sol, frozenBits); for (int i = 0; i < nodeSize; i += 2) { decTree2[m][i] = decTree2[m + 1][i / 2]; decTree1[m + 1][i / 2] = Decodeg(decTree1[m][i], decTree1[m][i + 1], decTree2[m][i]); } DecodeNode(n, m + 1, solSize, decTree1, decTree2, sol, frozenBits); for (int i = 0; i < nodeSize; i += 2) { decTree2[m][i] = decTree2[m][i] ^ decTree2[m + 1][i / 2]; decTree2[m][i + 1] = decTree2[m + 1][i / 2]; } return; } } void Decode(int n, double* c, double** decTree1, int** decTree2, int* sol, const std::vector<int>& frozenBits) { for (int i = 0; i < n; i++) { decTree1[0][i] = c[i]; } int solSize = 0; DecodeNode(n, 0, solSize, decTree1, decTree2, sol, frozenBits); return; } }
true
0ad9cb4bac0f69c3d6db8b91457d296adf30f69d
C++
Howaner/NBTEditor
/src/NBT/NBTHelper.cpp
UTF-8
2,714
2.65625
3
[ "BSD-3-Clause" ]
permissive
#include "NBTHelper.h" #include "NBTTag.h" #include <algorithm> namespace NBT { const NBTTag** NBTHelper::tagsByType = [] { const NBTTag** tags = new const NBTTag*[MAX_TAG + 1]; std::fill(tags, tags + MAX_TAG, (const NBTTag*)NULL); tags[NbtByte] = new NBTTagByte(); tags[NbtShort] = new NBTTagShort(); tags[NbtInt] = new NBTTagInt(); tags[NbtLong] = new NBTTagLong(); tags[NbtFloat] = new NBTTagFloat(); tags[NbtDouble] = new NBTTagDouble(); tags[NbtByteArray] = new NBTTagByteArray(); tags[NbtString] = new NBTTagString(); tags[NbtList] = new NBTTagList(); tags[NbtCompound] = new NBTTagCompound(); tags[NbtIntArray] = new NBTTagIntArray(); return tags; }(); const NBTTag* NBTHelper::GetTagByType(NBTType type) { if (type < MIN_TAG || type > MAX_TAG) return NULL; return tagsByType[type]; } template<typename T> const T* NBTHelper::GetTag(NBTType type) { const NBTTag* tag = GetTagByType(type); if (tag == NULL) return NULL; return static_cast<const T*>(tag); } template const NBTTagByteArray* NBTHelper::GetTag<NBTTagByteArray>(NBTType type); template const NBTTagIntArray* NBTHelper::GetTag<NBTTagIntArray>(NBTType type); const NBTTag** NBTHelper::GetAllTags() { return tagsByType; } jbyte NBTHelper::GetByte(NBTEntry& entry) { return GetTag<NBTTagByte>(NbtByte)->GetData(entry); } jshort NBTHelper::GetShort(NBTEntry& entry) { return GetTag<NBTTagShort>(NbtShort)->GetData(entry); } jint NBTHelper::GetInt(NBTEntry& entry) { return GetTag<NBTTagInt>(NbtInt)->GetData(entry); } jlong NBTHelper::GetLong(NBTEntry& entry) { return GetTag<NBTTagLong>(NbtLong)->GetData(entry); } jfloat NBTHelper::GetFloat(NBTEntry& entry) { return GetTag<NBTTagFloat>(NbtFloat)->GetData(entry); } jdouble NBTHelper::GetDouble(NBTEntry& entry) { return GetTag<NBTTagDouble>(NbtDouble)->GetData(entry); } NBTArray<jbyte>& NBTHelper::GetByteArray(NBTEntry& entry) { return GetTag<NBTTagByteArray>(NbtByteArray)->GetData(entry); } QString& NBTHelper::GetString(NBTEntry& entry) { return GetTag<NBTTagString>(NbtString)->GetData(entry); } NBTList& NBTHelper::GetList(NBTEntry& entry) { return GetTag<NBTTagList>(NbtList)->GetData(entry); } NBTCompound* NBTHelper::GetCompound(NBTEntry& entry) { return GetTag<NBTTagCompound>(NbtCompound)->GetData(entry); } NBTArray<jint>& NBTHelper::GetIntArray(NBTEntry& entry) { return GetTag<NBTTagIntArray>(NbtIntArray)->GetData(entry); } void NBTHelper::SetDouble(NBTEntry& entry, jdouble value) { GetTag<NBTTagDouble>(NbtDouble)->SetData(entry, value); } void NBTHelper::SetString(NBTEntry& entry, QString value) { GetTag<NBTTagString>(NbtString)->SetData(entry, value); } }
true
6e8ec0207d9f73c06601c58f86c5e7b6368c5062
C++
mapu/toolchains
/llvm-3.8.0-r267675/lib/Target/UCPM/MCTargetDesc/UCPMInsnLine.h
UTF-8
1,148
2.875
3
[ "NCSA" ]
permissive
/* This file defines data structures for encoding/decoding UCPM instruction lines. */ #ifndef UCPM_INSN_LINE_H #define UCPM_INSN_LINE_H #include "llvm/Support/raw_ostream.h" #include <stdint.h> namespace llvm { namespace UCPM { struct EncodingLayout { unsigned startBit; // start bit in current byte unsigned numBits; // how many bits unsigned startByte; // offset in code buffer unsigned numBytes; // how many bytes }; #define NUMSLOTS 14 extern const unsigned numBitsForSlot[]; class InsnLine { private: EncodingLayout layout[NUMSLOTS]; uint8_t* codeBuf; unsigned sumBits; unsigned sumBytes; void initLayout(); public: InsnLine() { initLayout(); codeBuf = new uint8_t[sumBytes]; memset(codeBuf, 0, sumBytes); } virtual ~InsnLine() { delete codeBuf; } void ConcatCode(uint64_t code, unsigned slot); void ExtractCode(uint64_t &code, unsigned slot); void EmitCode(raw_ostream &OS); uint8_t* getCodeBuf() {return codeBuf;} unsigned getSumBytes() {return sumBytes;} }; } } #endif // UCPM_INSN_LINE_H
true
f19eff8de694d1797cc5ab9af4b2b05dbc2f1329
C++
Yanglv-rookie/paragraph
/src/c++/include/statistics/Basics.hh
UTF-8
5,641
3
3
[ "Apache-2.0" ]
permissive
// -*- mode: c++; indent-tabs-mode: nil; -*- // // Paragraph // Copyright (c) 2016-2019 Illumina, Inc. // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied // See the License for the specific language governing permissions and limitations // // /** * \brief Basic statistical functions * * \file basics.hh * \author Mitch Bekritsky * \email mbekritsky@illumina.com * */ #pragma once #include <algorithm> #include <cmath> #include <functional> #include <iterator> #include <numeric> #include <utility> #include <vector> #include "common/Error.hh" namespace statistics { namespace basics { /** * Compute the median of an STL container of numeric types * @tparam T an STL container of a numeric type * @param nums an STL container of a numeric type * @return the median of the container */ template <typename T> double median(const T& nums) { if (nums.size() == 1) { return static_cast<double>(*(nums.cbegin())); } // this circumvents the fact that std::list does not use // std::sort, but has its own member sort function std::vector<typename T::value_type> nums_copy(nums.cbegin(), nums.cend()); // this could be reimplemented with quickselect std::sort(nums_copy.begin(), nums_copy.end()); std::size_t size = nums_copy.size(); if (size % 2 != 0) { auto mid_it = std::next(nums_copy.cbegin(), size / 2); return static_cast<double>(*(mid_it)); } auto mid_it = std::next(nums_copy.cbegin(), (size / 2) - 1); auto m = static_cast<double>(*(mid_it)); m += static_cast<double>(*(++mid_it)); return m / 2; } /** * Compute the mean of an STL container of numeric types * @tparam T an STL container of a numeric type * @param nums an STL container of a numeric type * @return the mean of the container */ template <typename T> double mean(const T& nums) { return std::accumulate(nums.cbegin(), nums.cend(), 0.0) / nums.size(); } /** * Compute the sample variance of an STL container of numeric types * @tparam T an STL container of a numeric type * @param nums a container of a numeric type * @return the variance of the container */ template <typename T> double var(const T& nums) { double n_mean = mean(nums); double var = 0; for (auto it = nums.cbegin(); it != nums.cend(); ++it) { var += pow(*it - n_mean, 2); } return var / (nums.size() - 1); } /** * Compute the mean and variance of an STL container of numeric types in a single pass * Taken from: http://mathworld.wolfram.com/SampleVarianceComputation.html * @tparam an STL container of a numeric type * @param nums an STL container of a numeric type * @return a pair of doubles (mean, variance) */ template <typename T> std::pair<double, double> one_pass_mean_var(const T& nums) { assert(nums.size() > 1); auto it = nums.cbegin(); auto mean = static_cast<double>(*(it++)); double var = 0; for (double count = 2; it != nums.end(); ++it, ++count) { double last_mean = mean; mean = last_mean + ((static_cast<double>(*it) - last_mean) / count); double v1 = var * (1 - (1 / (count - 1))); double v2 = count * (pow(mean - last_mean, 2)); var = v1 + v2; } return std::make_pair(mean, var); } /** * Calculate the z-scores for a set of numbers compared to a normal distribution * defined by mean and variance * @tparam T an STL container of a numeric type * @param nums an STL container of a numeric type * @param mean the distribution mean * @param variance the distribution variance * @return a vector of doubles */ template <typename T> std::vector<double> zscore(const T& nums, double mean, double variance) { assert(variance > 0); std::vector<double> zscores; std::transform( nums.cbegin(), nums.cend(), std::back_inserter(zscores), [mean, variance](typename T::value_type x) { return (static_cast<double>(x) - mean) / std::sqrt(variance); }); return zscores; } /** * Return all indices with the minimum element in an STL container of numeric types * @tparam T an STL container of a numeric type * @param nums an STL container of a numeric type * @return unsigned integer index of minimum value in container */ template <typename T> std::vector<unsigned> min_element_indices(const T& nums) { auto min = *std::min_element(nums.cbegin(), nums.cend()); std::vector<unsigned> min_element_indices; auto it = nums.cbegin(); while ((it = std::find(it, nums.end(), min)) != nums.end()) { auto index = static_cast<unsigned>(std::distance(nums.cbegin(), it)); min_element_indices.emplace_back(index); ++it; } assert(!min_element_indices.empty()); return min_element_indices; } } }
true
62d7e80261e684640cda69207a80324e0a4e227e
C++
danielkulakouski/watan
/subject.h
UTF-8
576
3.15625
3
[]
no_license
#ifndef SUBJECT_H #define SUBJECT_H #include <vector> #include <iostream> template <typename StateType> class Observer; template <typename StateType> class Subject { private: std::vector<Observer<StateType>*> observers; public: void attach(Observer<StateType> *o); void notify(StateType state); }; template <typename StateType> void Subject<StateType>::attach(Observer<StateType> *o) { observers.emplace_back(o); } template <typename StateType> void Subject<StateType>::notify(StateType state) { for (auto &ob : observers) { ob->update(state); } } #endif
true
c8ee15ff1658b55d0f60097ecae0f6988e072eff
C++
kannavue/ChartPatternRecognitionLib
/src/patternMatch/DoubleBottomPatternMatch.h
UTF-8
487
2.59375
3
[ "MIT" ]
permissive
#ifndef DOUBLEBOTTOMPATTERNMATCH_H #define DOUBLEBOTTOMPATTERNMATCH_H #include "PatternMatch.h" class DoubleBottomPatternMatch : public PatternMatch { private: PatternMatchPtr lhsV_; PatternMatchPtr rhsV_; public: DoubleBottomPatternMatch(const PatternMatchPtr &lhsV, const PatternMatchPtr &rhsV); virtual void acceptVisitor(PatternMatchVisitor &visitor); virtual std::string matchType() const { return "Double Bottom"; } }; #endif // DOUBLEBOTTOMPATTERNMATCH_H
true
179dd0d227c861f98ac4e1c5b9d8850d2a1805c8
C++
ANLAB-KAIST/NBA
/elements/standards/RandomWeightedBranch.cc
UTF-8
879
2.625
3
[ "MIT" ]
permissive
#include "RandomWeightedBranch.hh" #include <cassert> #include <nba/core/enumerate.hh> using namespace std; using namespace nba; int RandomWeightedBranch::initialize() { return 0; } int RandomWeightedBranch::configure(comp_thread_context *ctx, std::vector<std::string> &args) { Element::configure(ctx, args); vector<float> weights; for (auto& arg : args) weights.push_back(stof(arg)); ddist = discrete_distribution<int>(weights.begin(), weights.end()); assert(ddist.min() == 0); assert((unsigned) (ddist.max() + 1) == args.size()); /* Example input: 0.3, 0.5 * Example discrete distribution: * (0, 0.3/(0.3+0.5)) * (1, 0.5/(0.3+0.5)) */ return 0; } int RandomWeightedBranch::process(int input_port, Packet *pkt) { int idx = ddist(gen); output(idx).push(pkt); return 0; } // vim: ts=8 sts=4 sw=4 et
true
93cfa9e3e65b616d77691fea4dabb5db180cd73e
C++
qinjiajuny/preparePAT
/1032 挖掘机技术哪家强.cpp
GB18030
569
2.765625
3
[]
no_license
#include<cstdio> int main() { // int N; //ѧУ int schID, schScore; //洢ѧУܷͬ int scoreSum[100000] = {0};//Ϊ10000ʾδ scanf("%d", &N); while (N) { scanf("%d%d", &schID,&schScore); scoreSum[schID] += schScore;//߼ܷ N--; } int k=1; int MAX = -1; for (int i = 0; i <= schID; i++) { if (scoreSum[i]>MAX){//ȽϳIJk¼ѧУ MAX = scoreSum[i]; k = i; } } printf("%d %d\n", k, MAX); return 0; }
true
e9c8bb22427a6ccb8e6d73cfea66796ef31b334c
C++
Flargy/SDL_Asteroids_Submission
/src/HighscoreSystem.h
UTF-8
437
2.625
3
[]
no_license
#pragma once #include <iostream> #include <fstream> #include <vector> #include <string> #include <algorithm> class HighscoreSystem { public: HighscoreSystem(); void SetScore(); void IncreaseCurrentScore(int value); std::vector<std::string> GetHighscores(); void Reset(); int currentScore = 0; private: std::vector<int> scores; std::ifstream fromFile; std::ofstream toFile; std::string path = "res/highscoreList.txt"; };
true
b59c78fa2f119f58f39172eec0ae812e4f7ae658
C++
WattanaixKU/204214-problemsolving-lab
/elab2/week1/normalization.cpp
UTF-8
236
2.9375
3
[]
no_license
#include <iostream> using namespace std; int gcd(int a,int b) { if (a%b!=0) return gcd(b,a%b); return b; } int main() { int a,b; cin >> a >> b; cout << a/gcd(a,b) << "/" << b/gcd(a,b) << endl; return 0; }
true
aa75ca98be3c7b10ae62d48bd0d3fc0edc5e82f5
C++
aurantst/windows-XP-SP1
/XPSP1/NT/ds/ese98/src/inc/view.hxx
UTF-8
14,910
2.546875
3
[]
no_license
#define JET_cbtypMax 16 /* imported dispatch-function definitions */ extern CODECONST(VTFNDEF) vtfndefVC; extern CODECONST(VTFNDEF) vtfndefVCCallback; extern CODECONST(VTFNDEF) vtfndefVC2; extern CODECONST(VTFNDEF) vtfndefVC2Callback; extern CODECONST(VTFNDEF) vtfndefVI; extern CODECONST(VTFNDEF) vtfndefVICallback; /* expression node */ enum EXPRNTYP { exprntypNil, // the empty type // NOTE: every expression will ultimately evaluate to one of the three major types below exprntypConstInt, // any fixed-point value (int,short,long,bool,etc) stored as __int64 exprntypConstFloat, // any floating-point value (float,double,long dbl) stored as double exprntypConstBlob, // any non-fixed-point/non-floating-point value stored as byte-array exprntypColumn, // Int/Float/Blob: reference to a column from a child table exprntypParameter, // Int/Float/Blob: reference to a parameter in a VI // functions of 1 parameter exprntypNot, // Int( Int ) !x exprntypComplement, // Int( Int ) ~x exprntypNeg, // Float( Int/Float ) -x exprntypAbs, // Float( Int/Float ) fabs(x) exprntypSin, // Float( Int/Float ) sin(x) exprntypCos, // Float( Int/Float ) cos(x) exprntypTan, // Float( Int/Float ) tan(x) exprntypArcsin, // Float( Int/Float ) asin(x) exprntypArccos, // Float( Int/Float ) acos(x) exprntypArctan, // Float( Int/Float ) atan(x) exprntypLog10, // Float( Int/Float ) log10(x) exprntypLn, // Float( Int/Float ) ln(x) exprntypExp, // Float( Int/Float ) exp(x) // functions of 2 parameters exprntypBitwiseAnd, // Int( Int,Int ) x & y exprntypBitwiseOr, // Int( Int,Int ) x | y exprntypBitwiseXor, // Int( Int,Int ) x ^ y exprntypShiftLeft, // Int( Int,Int ) x << y exprntypShiftRight, // Int( Int,Int ) x >> y exprntypAnd, // Int( Int,Int ) x && y exprntypOr, // Int( Int,Int ) x || y exprntypEQ, // Int( Int/Float,Int/Float ) x == y exprntypNE, // Int( Int/Float,Int/Float ) x != y exprntypLE, // Int( Int/Float,Int/Float ) x <= y exprntypGE, // Int( Int/Float,Int/Float ) x >= y exprntypLT, // Int( Int/Float,Int/Float ) x < y exprntypGT, // Int( Int/Float,Int/Float ) x > y exprntypAdd, // Float( Int/Float,Int/Float ) x + y exprntypMinus, // Float( Int/Float,Int/Float ) x - y exprntypMultiply, // Float( Int/Float,Int/Float ) x * y exprntypDivide, // Float( Int/Float,Int/Float ) x / y exprntypModulus, // Int( Int,Int ) x % y exprntypPower, // Float( Int/Float,Int/Float ) x^y // functions of N parameters exprntypSum, // Float( Int/Float, ... ) a+b+c+...+z exprntypAverage, // Float( Int/Float, ... ) (a+b+c+...+z)/n // user-defined functions of N parameters exprntypFuncInt, // Int( Int/Float/Blob, ... ) ??? exprntypFuncFloat, // Float( Int/Float/Blob, ... ) ??? exprntypFuncBlob // Blob( Int/Float/Blob, ... ) ??? }; // user-defined function (cannot be used in a Constraint or Order expression; Output only!) // 1. we collect the data from each node in m_rgexprn[0 ... m_cexprn] and put it in a blob // 2. we then pass the blob as an input // 3. the user de-martials the blob, operates on the columns in it, and puts the result column // into another blob // 4. the user then sets out pointer and length to their blob // 5. they return ok/fail based on how the function performed // 6. we cast their blob based on the expected return-type and check it for validity // ( non-terminated strings, floats which will cause exceptions, etc. ) // 7. once their blob is of a known type, we continue processing the expression typedef long (__stdcall *pfnEXPRN)( const void *pvInput, unsigned long cbInput, const void **ppvOutput, unsigned long *cbOutput ); struct EXPRN { EXPRNTYP exprntyp; union { // exprntypConstInt __int64 l; // constant integer value // exprntypCountFloat double d; // constant double value // exprntypConstBlob struct { BYTE *pb; // constant string or binary blob unsigned long cb; }; // exprntypColumn struct { char *pszColumnName; // fully-qualified column name JET_COLUMNID columnid; // column id JET_COLTYP coltyp; // column type unsigned long colsize; // column size }; // exprntypParameter unsigned int paramIndex; // index into the array of params in the VD/VI // functions of 1 parameter EXPRN *child; // functions of 2 parameters struct { EXPRN *left; EXPRN *right; }; // functions of N parameters struct { int cexprn; EXPRN *rgexprn; }; // user-defined functions of N parameters struct { int cexprn; EXPRN *rgexprn; pfnEXPRN pfnExprn; } user; }; }; /* view node / view node instance */ class VD; // view descriptor class VI; // view instance struct VN; // view node struct VNI; // view node instance enum VNTYP { vntypBase, // base table node vntypBaseIndex, // base table with index node vntypConstraint, // single input constraint vntypConstraint2, // 2 inputs constraint vntypIntermediate, // Intermediate table or temp sort node // vntypAgg // Aggregate node }; enum VNITYP { vnitypConstraint, // constraint instance vnitypConstraint2, // 2 input constraint instance vnitypIntermediate, // intermediate instance // vnitypAgg // aggregate instance }; /* //----- I don't get this yet; the int * should probably be an EXPRN ** ----- struct AGGFNS { int ciexprn; int *rgiexprn; // Index into rgiexprnOutput of this node }; */ struct VN { char *m_pszName; // name of this view-node VNTYP m_vntyp; // type of this view-node union { // vntypBase struct { // traversal direction is done with MoveNext/MovePrevious //BOOL m_fForward; // base tables should not have associated expressions of any kind //int m_cexprnStart; // ??? //EXPRN *m_rgexprnStart; // ??? //int m_cexprnLimit; // ??? //EXPRN *m_rgexprnLimit; // ??? } bt; // vntypBaseIndex -- ?? what does this type of VN do ?? struct { } bti; // vntypConstraint struct { EXPRN *m_pexprn; // root of the constraining expression int m_cexprnOutput; // array of the roots of the output expressions EXPRN **m_rgpexprnOutput; char **m_ppszexprnOutput; // array of ptrs to names of each output exprn VN *m_pvnChild; // VN which is contrained by this VN } c; // vntypConstraint2 struct { EXPRN *m_pexprn; // order of the base tables -- who is first, who is second // traversal method: loop index, merge, etc. // traversal dir: forward/reverse on the first table, and on the second table int m_cexprnOutput; // array of the roots of the output expressions EXPRN **m_rgpexprnOutput; char **m_ppszexprnOutput; // array of ptrs to names of each output exprn VN *m_pvnChild[2]; // VNs which are each contrained by this VN } c2; // vntypIntermediate struct { int m_cexprnOrder; // array of the roots of the ordering expressions EXPRN **m_rgpexprnOrder; int m_cexprnOutput; // array of the roots of the output expressions EXPRN **m_rgpexprnOutput; char **m_ppszexprnOutput; // array of ptrs to names of each output exprn VN *m_pvnChild; // VN which is populating this VN char *m_pszTableName; // name of temp-table which holds intermediate data } i; /* // vntypAgg struct { int m_cGroupLevels; // group levels int *m_rgivocolLevelStart; // offset into rgiexprnOutput for start of each group level int m_caggfns; AGGFNS *m_rgaggfns; // Aggregate functions of each level. // do aggregate functions even HAVE a set of output expressions? int m_cexprnOutput; // array of the roots of the output expressions EXPRN **m_rgpexprnOutput; VN *m_pvnChild; // VN which is the input to this VN } a; */ }; }; struct VNI // view node instance { VTFNDEF *m_pvtfndef; // table functions (must be first for ErrDispXXX funcs) CBGROUP m_cbgroup; // callback functions VN *m_pvn; // point back to associated VN VI *m_pvi; // point back to the parent VI VNITYP m_vnityp; union { // vnitypConstraint struct { JET_TABLEID m_tableid; // input tableid JET_HANDLE m_rgcbid[JET_cbtypMax]; // ids of callbacks registered with child } c; // vnitypConstraint2 struct { JET_TABLEID m_tableid[2]; // input tableids JET_HANDLE m_rgcbid[2][JET_cbtypMax]; // ids of callbacks registered with child } c2; // vnitypIntermediate struct { JET_TABLEID m_tableid; // input tableid JET_HANDLE m_rgcbid[JET_cbtypMax]; // ids of callbacks registered with child char *szTableName; // name of the temp-table JET_TABLEID m_temptableid; // tableid of temp-table } i; /* // vnitypAgg struct { int m_cline; LINE *m_rgline; // cursors, one for each group by column. int *m_rgiline; // group level is defined in VNAGG, index to level break }; */ }; }; /* view descriptor / view instance */ // BUGBUG: no ctor for struct that contains classes class VD { public: VD(); char *m_pszName; // name of this view int m_cRef; // how many VI is referencing this VD VI *m_pviList; // list of VI using this VD CCriticalSection m_critBind; // used to protect the list of bound VIs int m_cvn; // all vnode in the tree, including base/index table VN *m_rgvn; int m_cexprn; // set of all expressions for all VNs in this VD EXPRN *m_rgexprn; int m_cparam; // set of parameters for inputs to exprntypParameter nodes EXPRNTYP *m_rgparamType; unsigned long *m_rgparamSize; }; class VI { public: VI(); VD *m_pvd; // point to the view discriptor VI *m_pviNext; // next instance of the VD VI *m_pviPrev; // previous instance of the VD BOOL m_fClosing; CReaderWriterLock m_rwlock; JET_SESID m_vsesid; // bind to a specific sesid int m_cvni; // all vnode in the tree, including base/index table VNI *m_rgvni; // first entry is root VNI EXPRN *m_rgparam; // exprn parameters }; /* macros / gadgets / misc-toys */ INLINE ERR ErrVNICheck( JET_SESID vsesid, VNI *pvni ) { if ( pvni && pvni->m_pvi->m_vsesid == vsesid ) { switch ( pvni->m_vnityp ) { case vnitypConstraint: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVCCallback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); case vnitypConstraint2: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC2 ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC2Callback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); case vnitypIntermediate: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVI ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVICallback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); // case vnitypAgg: } } return ErrERRCheck( JET_errInvalidViewId ); } INLINE ERR ErrVNICheckLimited( VNI *pvni ) { if ( pvni ) { switch ( pvni->m_vnityp ) { case vnitypConstraint: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVCCallback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); case vnitypConstraint2: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC2 ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVC2Callback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); case vnitypIntermediate: return ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVI ) ? JET_errSuccess : ( pvni->m_pvtfndef == (VTFNDEF *)&vtfndefVICallback ) ? JET_errSuccess : ErrERRCheck( JET_errInvalidViewId ); // case vnitypAgg: } } return ErrERRCheck( JET_errInvalidViewId ); } /****** VIEW.CXX *******/ ERR ErrVIEWOpen( JET_SESID vsesid, JET_DBID vdbid, const char *szViewName, const void *pvParameters, unsigned long cbParameters, JET_GRBIT grbit, JET_VIEWID *pviewid ); ERR ErrVIEWLoad( JET_SESID vsesid, JET_DBID vdbid, const char *szViewName, VD **ppvd ); ERR ErrVIEWBind( JET_SESID vsesid, JET_DBID vdbid, VD *pvd, const void *pvParameters, unsigned long cbParameters, VI **ppvi ); // view creation/storage starts with the query-processor // QP compiles a view, optimizes it, then stores it // ** no one else should touch the functions below (unless making a hack :) ** // compile an unoptimized view from a query // SELECT ... FROM ... WHERE ... ORDERBY/GROUPBY ... ERR ErrVIEWCompile( JET_SESID vsesid, JET_DBID vdbid, const char *szQuery, VD **ppvd ); // create an optimized view from an unoptimized view ERR ErrVIEWOptimize( JET_SESID vsesid, JET_DBID vdbid, VD *pvdInput, VD **ppvdOutput ); // store a view by name ERR ErrVIEWStore( JET_SESID vsesid, JET_DBID dbid, VD *pvd ); /****** EXPRN.CXX *******/ // Evaluate an expression ERR ErrEXPRNCompute( JET_SESID vsesid, VNI *pvni, EXPRN *pexprn, void *pvWorkspace, unsigned long cbWorkspace, EXPRNTYP *pType, unsigned long *pSize ); // Get the type/size information for any exprn node ERR ErrEXPRNInfo( VNI *pvni, EXPRN *pexprn, EXPRNTYP *pType, unsigned long *pSize ); // Get the type/size information for any exprn node as a JET_COLTYP ERR ErrEXPRNInfoJet( VNI *pvni, EXPRN *pexprn, JET_COLTYP *pType, unsigned long *pSize ); /******** save these goodies for later (they are at the bottom of VIEW.CXX) ************/ // compile an SQL query ERR ErrVIEWCompile( JET_SESID vsesid, JET_DBID vdbid, const char *szQuery, VD **ppvd ); // create an optimized view from an unoptimized view ERR ErrVIEWOptimize( JET_SESID vsesid, JET_DBID vdbid, VD *pvdInput, VD **ppvdOutput ); // store a view by name ERR ErrVIEWStore( JET_SESID vsesid, JET_DBID dbid, VD *pvd );
true
8d6e43c03b951cafda373b9fb87a5ecdfd78166b
C++
Br0kensword/shapes-project
/RectangleJustinU.h
UTF-8
1,232
2.703125
3
[]
no_license
/* * Program Name: RectangleJustinU.h * Written By: Justin Unverricht * Date: 11/26/13 * Part of Project: Lab 7 Ex 1 */ #ifndef FINALRECTANGLEJUSTINU_H #define FINALRECTANGLEJUSTINU_H #include "FinalFractionJustinU.h" #include "PointJustinU.h" #include "shapeJustinU.h" #include <iostream> class FinalRectangleJustinU : public virtual ShapeJustinU { public: FinalRectangleJustinU(void); ~FinalRectangleJustinU(void); FinalRectangleJustinU(const FinalRectangleJustinU&); FinalRectangleJustinU(const FinalPointJustinU&, const FinalPointJustinU&); FinalRectangleJustinU(const FinalFractionJustinU&, const FinalFractionJustinU&); virtual FinalRectangleJustinU& operator=(const FinalRectangleJustinU&); FinalRectangleJustinU operator+(const FinalRectangleJustinU&); FinalFractionJustinU getArea(void) const; FinalFractionJustinU getVolume(void) const; FinalFractionJustinU getLength(void) const; FinalFractionJustinU getWidth(void) const; FinalPointJustinU getUpRight(void) const; FinalPointJustinU getLowLeft(void) const; void setUpRight(const FinalPointJustinU&); void setLowLeft(const FinalPointJustinU&); ostream& printOut(ostream&) const; protected: FinalPointJustinU* upRight; FinalPointJustinU lowLeft; }; #endif
true
2443500b57df7d5fa03fe1b3090f541a4b60d086
C++
nontraditional-tech/GoFishCpp
/GameSetup.cpp
UTF-8
2,439
3.234375
3
[]
no_license
#include "GameSetup.h" GameSetup::GameSetup() { int playerNum; std::cout << "How many players?" << std::endl; std::cin >> playerNum; bool isPlayerNumValid = is_player_num_valid(playerNum); if (isPlayerNumValid) { std::cout << playerNum << " players selected" << '\n' << std::endl; } else { std::cout << "you entered a bogus player number" << std::endl; } bool vectorMatchesPlayers = create_players_vector(playerNum); // if vector player objects match playerNum, set playersCreated if (vectorMatchesPlayers) { playersCreated = playerNum; get_players_name(); } else { std::cout << "vector/player error, exit now" << std::endl; } } bool GameSetup::create_players_vector(int playerNum) { for (int i = 0; i < playerNum; i++) { players.push_back(Player()); } // if num of players == size of players vector, true return (playerNum == players.size()); } void GameSetup::get_players_name() { int playerNumTemp = 1; std::string nameTemp; for (std::vector<Player>::iterator it = players.begin(); it != players.end(); it++) { std::cout << "Player " << playerNumTemp << " enter your name" << std::endl; std::cin >> nameTemp; it->set_player_name(nameTemp); playerNumTemp++; } } void GameSetup::print_players_name() { std::cout << "\nWelcome to Go Fish "; for (auto &i : players) { std::cout << i.get_player_name(); if (!(&i == &players.back())) { std::cout << ","; } } } bool GameSetup::is_player_num_valid(int playerNum) { return ((PLAYER_NUM_MIN <= playerNum) && (playerNum <= PLAYER_NUM_MAX)); } //void GameSetup::print_table_two_players() { // using namespace std; // // cout << " \n"; // cout << " \n"; // cout << " ------------- \n"; // cout << " / \\ \n"; // cout << " / \\ \n"; // cout << " / \\ \n"; // cout << " | | \n"; // cout << " | | \n"; // cout << " | | \n"; // cout << " \\ / \n"; // cout << " \\ / \n"; // cout << " \\ / \n"; // cout << " ------------ \n"; // cout << " Dealer \n"; //}
true
bba7616534098c41b78cd1ca491cd3fdbb760531
C++
azureitstepkharkov/33pr11gitserver
/Exam/Работы_для_проверки/Pavlyuchenko Sergey/pavlyuchenko.exam_13_09_19/Pavlyuchenko.Exam/Department.cpp
WINDOWS-1251
1,967
3.6875
4
[]
no_license
// Department #include "Department.h" // Department::Department() { this->departmentName = ""; this->bossName = ""; } // Department::Department(string departmentName, std::list<Employee> employees, string bossName) : departmentName(departmentName), employees(employees), bossName(bossName) { } // Department::Department(const Department & obj) { this->departmentName = obj.departmentName; this->employees = obj.employees; this->bossName = obj.bossName; } // void Department::setDepartmentName(string departmentName) { this->departmentName = departmentName; } void Department::setListEmployees(std::list<Employee> employees) { this->employees = employees; } void Department::setBossName(string bossName) { this->bossName = bossName; } // string Department::getDepartmentName() const { return this->departmentName; } std::list<Employee> Department::getListEmployees() const { return this->employees; } string Department::getBossName() const { return this->bossName; } // void Department::addToEmployeeList(Employee &obj) { employees.push_back(obj); } // ostream ostream & operator<<(ostream & out, const Department & obj) { out << " : " << obj.getDepartmentName() << endl; out << " : " << obj.getBossName() << endl; out << ":" << endl; for (Employee val : obj.employees) { out << val; } return out; } // Department::~Department() { // cout << "Department object " << this << " deleted!" << endl; // , }
true
35ee7a0ad1050d8833dc3da74de1994174054bf8
C++
aladine/awesome-leetcode
/cpp/algoexpert/10-jul.cpp
UTF-8
3,764
2.796875
3
[ "Apache-2.0" ]
permissive
#include <bits/stdc++.h> using namespace std; typedef long long int ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<string> vs; #define len(container) int((container).size()) #define all(c) (c).begin(), (c).end() const int M = 1e9 + 7; template <typename ITER> void show(ITER begin, ITER end) { for (int i = 1; begin != end; i++) { printf("%d ", *(begin++)); if (i % 20 == 0 or begin == end) printf("\n"); } }; template <typename T> void addMod(T& a, T b) { a = (a + b) % M; } class ContinuousMedianHandler { public: double median; priority_queue<int, vector<int>> maxH; priority_queue<int, vector<int>, std::greater<int>> minH; void insert(int number) { if (maxH.empty() || number < maxH.top()) maxH.push(number); else minH.push(number); if (minH.size() > maxH.size() + 1) { auto ele = minH.top(); minH.pop(); maxH.push(ele); } else if (maxH.size() > minH.size() + 1) { auto ele = maxH.top(); maxH.pop(); minH.push(ele); } if (minH.size() > maxH.size()) median = minH.top(); else if (maxH.size() > minH.size()) median = maxH.top(); else median = 0.5 * ((double)minH.top() + (double)maxH.top()); } double getMedian() { return median; } }; vector<int> mergeSortedArrays(vector<vector<int>> arrays) { vector<int> res = arrays[0]; for (int i = 1; i < arrays.size(); ++i) { int mid = res.size(); copy(arrays[i].begin(), arrays[i].end(), std::back_inserter(res)); inplace_merge(res.begin(), res.begin() + mid, res.end()); } return res; } class MinHeap { public: vector<int> heap; MinHeap(vector<int> vector) { heap = buildHeap(&vector); } vector<int> buildHeap(vector<int> *vector) { heap = *vector; for (int i = vector->size() - 1; i >= vector->size() / 2; --i) { siftUp(i, &heap); } return heap; } int getParentIndex(int idx) { return (idx - 1) / 2; } void siftDown(int currentIdx, int endIdx, vector<int> *heap) { swap(heap[currentIdx], heap[endIdx]); } void siftUp(int currentIdx, vector<int> *heap) { swap(heap[currentIdx], heap[getParentIndex(currentIdx)]); } int peek() { if (!heap.empty()) { return heap[0]; } return -1; } int remove() { if (heap.empty()) return -1; int v = peek(); heap[0] = heap.back(); heap.pop_back(); int idx = 0; while (idx < heap.size()) { int cid = 2 * idx + 1; if (heap[idx] > heap[cid]) { siftDown(idx, cid, &heap); } idx = cid; } return v; } void insert(int value) { heap.push_back(value); int idx = heap.size() - 1; while (idx) { if (heap[idx] < heap[getParentIndex(idx)]) { siftUp(idx, &heap); } idx = getParentIndex(idx); } } }; class LRUCache { public: struct KVPair { string k; int v; }; int maxSize; unordered_map<string, list<KVPair>::iterator> m; list<KVPair> l; LRUCache(int maxSize) { this->maxSize = maxSize > 1 ? maxSize : 1; } void insertKeyValuePair(string key, int value) { auto val = getValueFromKey(key); if (val != NULL) { m[key]->v = value; return; } l.push_front({key, value}); m[key] = l.begin(); while (l.size() > maxSize) { auto ele = l.back(); l.pop_back(); m.erase(ele.k); } } int *getValueFromKey(string key) { if (m.count(key)) { auto it = m[key]; l.push_front(*it); l.erase(it); m[key] = l.begin(); return &((*it).v); } return NULL; } string getMostRecentKey() { if (!l.empty()) { return l.front().k; } return ""; } }; int main(int argc, char *argv[]) { // return 0; }
true
10b31248d629d42020bb7d47654184e0e6c5f068
C++
dldlowndes/LD_QuarcTracker
/src/LD_Camera.cpp
UTF-8
14,338
2.5625
3
[]
no_license
#include <fstream> #include <iostream> #include "LD_Camera.h" namespace LD_Camera{ int FindCameras(){ int num_Cameras = 0; is_GetNumberOfCameras(&num_Cameras); std::cout << num_Cameras << " cameras found" << "\n"; // From the API manual docs for function is_GetCameraList() UEYE_CAMERA_LIST* pucl; pucl = (UEYE_CAMERA_LIST*) new BYTE [sizeof(DWORD) + (num_Cameras * sizeof(UEYE_CAMERA_INFO))]; pucl->dwCount = num_Cameras; if(is_GetCameraList(pucl) == IS_SUCCESS){ for(int iCamera = 0; iCamera < (int)pucl->dwCount; iCamera++){ std::cout << "Camera: " << iCamera << ", ID: " << pucl->uci[iCamera].dwCameraID << ", Model: " << pucl->uci[iCamera].FullModelName << ", Serial: " << pucl->uci[iCamera].SerNo << std::endl; } } return num_Cameras; } Camera::Camera() { //ctor } Camera::Camera(CameraOptions my_Options) { Init(my_Options); } Camera::~Camera() { //dtor } int Camera::Init(CameraOptions my_Options){ std::cout << "Opening camera ID: " << my_Options.Camera_ID << "\n"; m_hG = (HCAM)my_Options.Camera_ID; m_Ret = is_InitCamera(&m_hG, NULL); // NULL for window handle since we are using DIB mode. std::cout << "Connect to camera says: " << m_Ret << "\n"; if (m_Ret == IS_SUCCESS){ is_Connected = true; } else{ std::cout << "########## FAIL. Incorrect camera ID? ##########" << "\n"; return 1; } // retrieve original image size. If this fails assume 1280x1024. m_Ret = is_GetSensorInfo(m_hG, &sInfo); if (m_Ret != IS_SUCCESS){ sInfo.nMaxWidth = 1280; sInfo.nMaxHeight = 1024; } // Define the full frame as a massive AOI. full_Frame.aoi_Position = {0,0}; full_Frame.aoi_Size = {(int)sInfo.nMaxWidth, (int)sInfo.nMaxHeight}; // Set the default AOI from the options file. default_AOI.aoi_Size = my_Options.aoi_Dimensions.aoi_Size; default_AOI.aoi_Position = my_Options.aoi_Dimensions.aoi_Position; my_AOI = default_AOI; // Camera does not allow arbitary AOIs, get the allowed increments. is_AOI(m_hG, IS_AOI_IMAGE_GET_POS_INC, (void*)&aoi_Position_Increment, sizeof(aoi_Position_Increment)); is_AOI(m_hG, IS_AOI_IMAGE_GET_SIZE_INC, (void*)&aoi_Size_Increment, sizeof(aoi_Size_Increment)); // Set camera modes: // DIB is the sort of raw low level access we want. is_SetDisplayMode(m_hG, IS_SET_DM_DIB); m_nBitsPerPixel = my_Options.bits_Per_Pixel; // TODO: Check whether camera is USB3 (10 bit is USB3 only). if (m_nBitsPerPixel > 8){ std::cout << "Setting colour mode to MONO16" << "\n"; m_Ret = is_SetColorMode(m_hG, IS_CM_MONO16); } else{ std::cout << "Setting colour mode to MONO8" << "\n"; m_Ret = is_SetColorMode(m_hG, IS_CM_MONO8); } std::cout << "Set colour mode says: " << m_Ret << "\n"; // Rather than free running. Quite a bit faster! is_SetExternalTrigger(m_hG, IS_SET_TRIGGER_SOFTWARE); // Allocate image memories. is_AllocImageMem(m_hG, sInfo.nMaxWidth, sInfo.nMaxHeight, m_nBitsPerPixel, &frame_Memory.buffer, &frame_Memory.id); is_AllocImageMem(m_hG, my_AOI.aoi_Size.s32Width, my_AOI.aoi_Size.s32Height, m_nBitsPerPixel, &aoi_Memory.buffer, &aoi_Memory.id); // set memory active is_SetImageMem(m_hG, frame_Memory.buffer, frame_Memory.id); // Make some vectors to copy the horrible image memories to. // TODO: experiment if this can be done directly by passing // vector.data instead of &Camera_Memory.buffer... full_Image_Data.resize(full_Frame.aoi_Size.s32Width * full_Frame.aoi_Size.s32Height, 0); aoi_Image_Data.resize(my_AOI.aoi_Size.s32Width * my_AOI.aoi_Size.s32Height, 0); // Gain settings perform strangely, let's just leave it at the max for now. int max_Gain = is_SetHWGainFactor(m_hG, IS_INQUIRE_MASTER_GAIN_FACTOR, 100); std::cout << "Max gain: " << max_Gain << "\n"; is_SetHWGainFactor(m_hG, IS_SET_MASTER_GAIN_FACTOR, max_Gain); int gain_Actual = is_SetHWGainFactor(m_hG, IS_SET_MASTER_GAIN_FACTOR, 100); std::cout << "Gain set to: " << gain_Actual << "\n"; // Set exposure settings to default. default_Exposure = my_Options.exposure_Full; full_Frame_Exposure = default_Exposure; default_AOI_Exposure = my_Options.exposure_AOI; aoi_Exposure = default_AOI_Exposure; Set_Exposure(default_Exposure); is_Initted = true; std::cout << "Camera ready" << "\n"; return 0; } AOI Camera::Get_Sensor_Size(){ return full_Frame; } Exposure Camera::Get_Exposure(){ return current_Exposure; } int Camera::Set_Exposure(Exposure new_Exposure){ // Set pixel clock. std::cout << "Requesting " << new_Exposure.pixel_Clock << "MHz pixel clock" << "\n"; int pix_Ret = is_PixelClock(m_hG, IS_PIXELCLOCK_CMD_SET, (void*)&new_Exposure.pixel_Clock, sizeof(new_Exposure.pixel_Clock)); std::cout << "\tPixel clock says: " << pix_Ret << "\n"; if (pix_Ret == IS_SUCCESS){ current_Exposure.pixel_Clock = new_Exposure.pixel_Clock; } // Frame rate has specific values it can be so is_SetFrameRate returns the actual value it set to. double new_FPS; std::cout << "Requesting " << new_Exposure.frame_Rate << "FPS" << "\n"; int frame_Ret = is_SetFrameRate(m_hG, new_Exposure.frame_Rate, &new_FPS); std::cout << "\tFrame set says: " << frame_Ret << " set to " << new_FPS << "\n"; if (frame_Ret == IS_SUCCESS){ current_Exposure.frame_Rate = new_FPS; } // Set exposure std::cout << "Requesting " << new_Exposure.exposure << "ms exposure" << "\n"; int exp_Ret = is_Exposure(m_hG, IS_EXPOSURE_CMD_SET_EXPOSURE, (void*)&new_Exposure.exposure, sizeof(new_Exposure.exposure)); std::cout << "\tExposure says: " << exp_Ret << "\n"; if (exp_Ret == IS_SUCCESS){ current_Exposure.exposure = new_Exposure.exposure; } if (aoi_Set){ aoi_Exposure = current_Exposure; } else{ full_Frame_Exposure = current_Exposure; } return pix_Ret & frame_Ret & exp_Ret; } int Camera::Reset_Exposure(){ if (aoi_Set){ return Set_Exposure(default_AOI_Exposure); } else{ return Set_Exposure(default_Exposure); } } int Camera::Take_Picture(){ //std::cout << "Take picture" << "\n"; if (is_Connected && is_Initted){ // Capture image into memory buffer. m_Ret = is_FreezeVideo(m_hG, IS_WAIT); if (m_Ret != IS_SUCCESS) { std::cout << "Fail. Camera says: " << m_Ret << "\n"; return 1; } if(aoi_Set){ Copy_Memory(aoi_Memory, aoi_Image_Data); } else{ Copy_Memory(frame_Memory, full_Image_Data); } } else{ std::cout << "Camera not connected or not initialized" << "\n"; return 1; } return 0; } const std::vector<uint16_t>& Camera::Get_Picture(){ Take_Picture(); if(aoi_Set){ return aoi_Image_Data; } else{ return full_Image_Data; } } int Camera::Copy_Memory(Camera_Memory &my_Buffer, std::vector<uint16_t> &my_Dest_Vector){ //std::cout << "Copy memory" << "\n"; if (m_nBitsPerPixel > 8){ uint16_t first_Byte; uint16_t second_Byte; uint16_t shift = 16 - m_nBitsPerPixel; for(unsigned int i=0; i < my_Dest_Vector.size() * 2; i+=2){ first_Byte = (uint8_t)my_Buffer.buffer[i]; second_Byte = (uint8_t)my_Buffer.buffer[i+1]; my_Dest_Vector[i/2] = ((first_Byte << 0) + (second_Byte << 8)) >> shift; } } else{ for(unsigned int i=0; i < my_Dest_Vector.size(); i++){ my_Dest_Vector[i] = (uint8_t)my_Buffer.buffer[i]; } } return 0; } int Camera::Save_Picture(std::string filename, bool binary){ if(aoi_Set == false){ if (binary){ return Dump_Binary(full_Image_Data, filename); } else{ return To_CSV(full_Image_Data, filename, full_Frame.aoi_Size.s32Width); } } else{ if (binary){ return Dump_Binary(aoi_Image_Data, filename); } else{ return To_CSV(aoi_Image_Data, filename, my_AOI.aoi_Size.s32Width); } } } int Camera::To_CSV(std::vector<uint16_t> &image_Vector, std::string file_Name, int line_Length){ std::ofstream file_Out(file_Name, std::ofstream::out); std::cout << "Saving " << image_Vector.size() << " pixels" << "\n"; for(unsigned int i=0; i < image_Vector.size(); i++){ file_Out << image_Vector[i]; if(((i+1) % line_Length == 0) && (i != 0)){ file_Out << "\n"; } else{ file_Out << ","; } } file_Out.close(); return 0; } int Camera::Dump_Binary(std::vector<uint16_t> &image_Vector, std::string file_Name){ std::ofstream file_Out(file_Name, std::ofstream::binary); std::cout << "Saving " << image_Vector.size() << " pixels" << "\n"; for(auto pixel : image_Vector){ file_Out << (uint8_t)((pixel >> 8) & 0xFF); file_Out << (uint8_t)(pixel & 0xFF); } file_Out.close(); return 0; } AOI Camera::Get_Active_Frame_Info(){ AOI this_AOI; m_Ret = is_AOI(m_hG, IS_AOI_IMAGE_GET_POS, (void*)&this_AOI.aoi_Position, sizeof(this_AOI.aoi_Position)); m_Ret = is_AOI(m_hG, IS_AOI_IMAGE_GET_SIZE, (void*)&this_AOI.aoi_Size, sizeof(this_AOI.aoi_Size)); //std::cout << "Current frame at: " << this_AOI.aoi_Position.s32X << ", " << this_AOI.aoi_Position.s32Y << "\n"; //std::cout << "and size is:" << this_AOI.aoi_Size.s32Width << ", " << this_AOI.aoi_Size.s32Height << "\n"; return this_AOI; } AOI Camera::Get_AOI_Info(){ return my_AOI; } int Camera::Set_AOI_Info(AOI new_AOI){ // Check the requested AOI conforms to the constraints of size // and position increments. new_AOI.aoi_Position.s32X = new_AOI.aoi_Position.s32X - (new_AOI.aoi_Position.s32X % aoi_Position_Increment.s32X); new_AOI.aoi_Position.s32Y = new_AOI.aoi_Position.s32Y - (new_AOI.aoi_Position.s32Y % aoi_Position_Increment.s32Y); new_AOI.aoi_Size.s32Height = new_AOI.aoi_Size.s32Height - (new_AOI.aoi_Size.s32Height % aoi_Size_Increment.s32Height); new_AOI.aoi_Size.s32Width = new_AOI.aoi_Size.s32Width - (new_AOI.aoi_Size.s32Width % aoi_Size_Increment.s32Width); my_AOI = new_AOI; // Reallocate memory for this image buffer // TODO: only do this if my_AOI.aoi_Size != new_AOI.aoi_Size is_AllocImageMem(m_hG, my_AOI.aoi_Size.s32Width, my_AOI.aoi_Size.s32Height, m_nBitsPerPixel, &aoi_Memory.buffer, &aoi_Memory.id); // and reallocate the vector container too. aoi_Image_Data.resize(my_AOI.aoi_Size.s32Width * my_AOI.aoi_Size.s32Height, 0); return 0; } int Camera::Set_AOI_Info(AOI new_AOI, Exposure new_Exposure){ Set_AOI_Info(new_AOI); aoi_Exposure = new_Exposure; return 0; } int Camera::Change_AOI(AOI &new_AOI){ // Setting using an IS_RECT object (I hope) ensures that errors from // resize then move or move then resize sometimes not working because // the first command overflows the AOI off the sensor. IS_RECT temp_New_AOI; temp_New_AOI.s32Height = new_AOI.aoi_Size.s32Height; temp_New_AOI.s32Width = new_AOI.aoi_Size.s32Width; temp_New_AOI.s32X = new_AOI.aoi_Position.s32X; temp_New_AOI.s32Y = new_AOI.aoi_Position.s32Y; // Set the AOI. m_Ret = is_AOI(m_hG, IS_AOI_IMAGE_SET_AOI, (void*)&temp_New_AOI, sizeof(temp_New_AOI)); std::cout << "Set AOI says: " << m_Ret << "\n"; // Activate relevant image memory based on whether this was called by // Enable_AOI or Disable_AOI. if (aoi_Set){ is_SetImageMem(m_hG, aoi_Memory.buffer, aoi_Memory.id); } else{ is_SetImageMem(m_hG, frame_Memory.buffer, frame_Memory.id); } return 0; } int Camera::Enable_AOI(){ std::cout << "Putting AOI at: " << my_AOI.aoi_Position.s32X << ", " << my_AOI.aoi_Position.s32Y << std::endl; aoi_Set = true; Change_AOI(my_AOI); Set_Exposure(aoi_Exposure); return 0; } int Camera::Disable_AOI(){ aoi_Set = false; Set_Exposure(full_Frame_Exposure); Change_AOI(full_Frame); return 0; } } // namespace LD_Camera int Test_AOI(LD_Camera::CameraOptions my_Options){ LD_Camera::Camera my_Camera(my_Options); my_Camera.Enable_AOI(); my_Camera.Take_Picture(); my_Camera.Save_Picture("images/aoi.dat", true); my_Camera.Disable_AOI(); my_Camera.Reset_Exposure(); my_Camera.Take_Picture(); my_Camera.Save_Picture("images/full.dat", true); return 0; } int Test_Multi(LD_Camera::CameraOptions my_Options){ LD_Camera::Camera my_Camera(my_Options); for(int i=0; i<50; i++){ my_Camera.Take_Picture(); my_Camera.Save_Picture("images/frame"+std::to_string(i)+".dat", true); } return 0; }
true
a954d693e4ea1f6c2411b3b6d6075ebc5b8a7be9
C++
adnammit/sandbox
/bst/main.cpp
UTF-8
874
3
3
[]
no_license
#include "table.h" using namespace std; int main() { table BST; // BUILD OUR TABLE: BST.insert(52); BST.insert(26); BST.insert(78); BST.insert(12); BST.insert(47); BST.insert(68); BST.insert(84); BST.insert(8); BST.insert(20); BST.insert(56); BST.insert(70); BST.insert(81); BST.insert(99); BST.insert(1); BST.insert(18); BST.insert(24); BST.insert(5); BST.insert(25); BST.insert(76); // DO SOME THINGS TO OUR TABLE: BST.display(); BST.countLeaves(); BST.countNodes(); // cout << "Count: " << BST.count() << endl; // cout << "Height: " << BST.height() << endl; // table BST_new; // BST_new.copy(BST); // BST_new.display(); // cout << "Sum: " << BST.sum() << endl; // cout << "\nNOW WE ERASE THE NEW ONE:\n"; // BST_new.remove_all(); // BST_new.display(0); // // BST.display(0); return 0; }
true
e9bd274f34aa32d7be6872d71ab681d08b52d541
C++
shamiul94/Problem-Solving-Online-Judges
/LeetCode/1. Two Sum.cpp
UTF-8
633
2.890625
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { unordered_map<int, int> um; vector<int> v; for (int i = 0; i < nums.size(); i++) { um[nums[i]] = i; } for (int i = 0; i < nums.size(); i++) { int a, b; a = nums[i]; b = target - a; if (um.find(b) != um.end()) { // found if (i == um[b]) continue; v.push_back(i); v.push_back(um[b]); break; } } return v; } };
true
02cb11961ba1679b7272bd0e58be57309b5d8b92
C++
wannaBpark/BOJ
/10845.cpp
UTF-8
658
2.546875
3
[]
no_license
#include <iostream> #include <cstdio> #include <queue> #include <string> using namespace std; queue<int> q; int N, input; string s; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> N; while (N--) { cin >> s; if (s=="push") { cin>>input; q.push(input); } else if (s=="front") printf("%d\n", (q.empty()) ? -1 : q.front()); else if (s=="empty") printf("%d\n", q.empty()); else if (s=="back") printf("%d\n", (q.empty()) ? -1 : q.back()); else if (s=="size") printf("%d\n", q.size()); else if (s=="pop") { if (q.empty()) puts("-1"); else { printf("%d\n", q.front()); q.pop(); } } } return 0; }
true
5878891f280c521eb8069157083b5008021411a9
C++
dheerajsharma0401/GeeksForGeeks-Solutions
/Greedy/Minimum Platforms.cpp
UTF-8
520
2.75
3
[]
no_license
class Solution{ public: //Function to find the minimum number of platforms required at the //railway station such that no train waits. int findPlatform(int arr[], int dep[], int n) { // Your code here sort(arr,arr+n); sort(dep,dep+n); int count=0; int j=0; for(int i=0;i<n;i++) { if(arr[i]<=dep[j]) count++; else j++; } /*for(int i=0;i<mindep.size();i++) cout<<mindep[i]<<" ";*/ return count; } };
true
bc56f39a561ed521757cf503cbf4866083315e07
C++
liubincodelife/opencv3_sketchs
/chapter6_imgproc_imageprocess/src/imgproc_functionality_imageprocess.cpp
UTF-8
16,361
2.75
3
[]
no_license
#include "imgproc_functionality_imageprocess.h" Mat g_filterSrcImage, g_morphologySrcImage; int g_nBoxFilterKernelSize = 6; int g_nMeanBlurFilterKernelSize = 6; int g_nGaussianBlurFilterKernelSize = 6; int g_nMedianBlurFilterKernelSize = 6; int g_nBilateralFilterKernelSize = 6; int g_nDilateKernelSize = 1; int g_nErodeKernelSize = 1; int g_nOpenKernelSize = 1; int g_nCloseKernelSize = 1; int g_nTopHatKernelSize = 1; int g_nBlackHatKernelSize = 1; int g_nMorphologyGradientKernelSize = 1; imgproc_functionality_imageprocess::imgproc_functionality_imageprocess(Mat &input_image) { image = input_image.clone(); } imgproc_functionality_imageprocess::~imgproc_functionality_imageprocess() { } void boxFilterTrackbar_cb(int , void *) { Mat boxFilterDstImage; int kSize = g_nBoxFilterKernelSize * 2 + 1; boxFilter(g_filterSrcImage, boxFilterDstImage, -1, Size(kSize, kSize)); imshow("BoxFilter Window", boxFilterDstImage); } void meanBlurFilterTrackbar_cb(int , void *) { Mat meanBlurFilterDstImage; int kSize = g_nMeanBlurFilterKernelSize * 2 + 1; blur(g_filterSrcImage, meanBlurFilterDstImage, Size(kSize, kSize)); imshow("MeanBlurFilter Window", meanBlurFilterDstImage); } void gaussianBlurFilterTrackbar_cb(int , void *) { Mat gaussianBlurFilterDstImage; int kSize = g_nGaussianBlurFilterKernelSize * 2 + 1; GaussianBlur(g_filterSrcImage, gaussianBlurFilterDstImage, Size(kSize, kSize), 0, 0); imshow("GaussianBlurFilter Window", gaussianBlurFilterDstImage); } bool linearFilterProcess() { namedWindow("BoxFilter Window"); namedWindow("MeanBlurFilter Window"); namedWindow("GaussianBlurFilter Window"); createTrackbar("ksize:", "BoxFilter Window", &g_nBoxFilterKernelSize, 50, boxFilterTrackbar_cb); createTrackbar("ksize:", "MeanBlurFilter Window", &g_nMeanBlurFilterKernelSize, 50, meanBlurFilterTrackbar_cb); createTrackbar("ksize:", "GaussianBlurFilter Window", &g_nGaussianBlurFilterKernelSize, 50, gaussianBlurFilterTrackbar_cb); boxFilterTrackbar_cb(g_nBoxFilterKernelSize, 0); meanBlurFilterTrackbar_cb(g_nMeanBlurFilterKernelSize, 0); gaussianBlurFilterTrackbar_cb(g_nGaussianBlurFilterKernelSize, 0); return true; } void medianBlurFilterTrackbar_cb(int, void*) { Mat medianBlurFilterDstImage; int kSize = g_nMedianBlurFilterKernelSize * 2 + 1; medianBlur(g_filterSrcImage, medianBlurFilterDstImage, kSize); imshow("MedianBlurFilter Window", medianBlurFilterDstImage); } void bilateralFilterTrackbar_cb(int, void*) { Mat bilateralFilterDstImage; int kSize = g_nGaussianBlurFilterKernelSize * 2 + 1; bilateralFilter(g_filterSrcImage, bilateralFilterDstImage, kSize, kSize * 2, kSize / 2); imshow("BilateralFilter Window", bilateralFilterDstImage); } bool nonlinearFilterProcess() { namedWindow("MedianBlurFilter Window"); namedWindow("BilateralFilter Window"); createTrackbar("ksize:", "MedianBlurFilter Window", &g_nMedianBlurFilterKernelSize, 50, medianBlurFilterTrackbar_cb); createTrackbar("ksize:", "BilateralFilter Window", &g_nBilateralFilterKernelSize, 50, bilateralFilterTrackbar_cb); medianBlurFilterTrackbar_cb(g_nMedianBlurFilterKernelSize, 0); bilateralFilterTrackbar_cb(g_nBilateralFilterKernelSize, 0); return true; } bool imageFilterProcess() { // g_filterSrcImage = imread("../images/car.jpg"); // g_filterSrcImage = imread("../images/girl.jpg"); g_filterSrcImage = imread("../images/girlcartoon.jpg"); if(g_filterSrcImage.empty()) { cout<<"g_filterSrcImage is empty!!!"<<endl; return false; } imshow("filterSrcImage window", g_filterSrcImage); linearFilterProcess(); nonlinearFilterProcess(); return true; } void dilateTrackbar_cb(int , void* ) { Mat dilateDstImage, element; int kSize = g_nDilateKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, dilateDstImage, MORPH_DILATE, element); imshow("Morphology Dialate Window", dilateDstImage); } bool imageDilateProcess() { namedWindow("Morphology Dialate Window"); createTrackbar("ksize:", "Morphology Dialate Window", &g_nDilateKernelSize, 50, dilateTrackbar_cb); dilateTrackbar_cb(g_nDilateKernelSize, 0); return true; } void erodeTrackbar_cb(int , void* ) { Mat erodeDstImage, element; int kSize = g_nErodeKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, erodeDstImage, MORPH_ERODE, element); imshow("Morphology Erode Window", erodeDstImage); } bool imageErodeProcess() { namedWindow("Morphology Erode Window"); createTrackbar("ksize:", "Morphology Erode Window", &g_nErodeKernelSize, 50, erodeTrackbar_cb); erodeTrackbar_cb(g_nErodeKernelSize, 0); return true; } void openTrackbar_cb(int , void* ) { Mat openDstImage, element; int kSize = g_nOpenKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, openDstImage, MORPH_OPEN, element); imshow("Morphology Open Window", openDstImage); } bool imageOpenProcess() { namedWindow("Morphology Open Window"); createTrackbar("ksize:", "Morphology Open Window", &g_nOpenKernelSize, 50, openTrackbar_cb); openTrackbar_cb(g_nOpenKernelSize, 0); return true; } void closeTrackbar_cb(int , void* ) { Mat closeDstImage, element; int kSize = g_nCloseKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, closeDstImage, MORPH_CLOSE, element); imshow("Morphology Close Window", closeDstImage); } bool imageCloseProcess() { namedWindow("Morphology Close Window"); createTrackbar("ksize:", "Morphology Close Window", &g_nCloseKernelSize, 50, closeTrackbar_cb); closeTrackbar_cb(g_nCloseKernelSize, 0); return true; } void topHatTrackbar_cb(int , void* ) { Mat topHatDstImage, element; int kSize = g_nTopHatKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, topHatDstImage, MORPH_TOPHAT, element); imshow("Morphology TopHat Window", topHatDstImage); } bool imageTopHatProcess() { namedWindow("Morphology TopHat Window"); createTrackbar("ksize:", "Morphology TopHat Window", &g_nTopHatKernelSize, 50, topHatTrackbar_cb); topHatTrackbar_cb(g_nTopHatKernelSize, 0); return true; } void blackHatTrackbar_cb(int , void* ) { Mat blackHatDstImage, element; int kSize = g_nBlackHatKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, blackHatDstImage, MORPH_BLACKHAT, element); imshow("Morphology BlackHat Window", blackHatDstImage); } bool imageBlackHatProcess() { namedWindow("Morphology BlackHat Window"); createTrackbar("ksize:", "Morphology BlackHat Window", &g_nBlackHatKernelSize, 50, blackHatTrackbar_cb); blackHatTrackbar_cb(g_nBlackHatKernelSize, 0); return true; } void morphologyGradientTrackbar_cb(int , void* ) { Mat morphologyGradientDstImage, element; int kSize = g_nMorphologyGradientKernelSize * 2 + 1; element = getStructuringElement(MORPH_RECT, Size(kSize, kSize)); morphologyEx(g_morphologySrcImage, morphologyGradientDstImage, MORPH_GRADIENT, element); imshow("Morphology Gradient Window", morphologyGradientDstImage); } bool imageMorphologyGradientProcess() { namedWindow("Morphology Gradient Window"); createTrackbar("ksize:", "Morphology Gradient Window", &g_nMorphologyGradientKernelSize, 50, morphologyGradientTrackbar_cb); morphologyGradientTrackbar_cb(g_nMorphologyGradientKernelSize, 0); return true; } bool imageMorphologyProcess() { g_morphologySrcImage = imread("../images/captain.jpg"); if(g_morphologySrcImage.empty()) { cout<<"g_morphologySrcImage is empty!!!"<<endl; return false; } imshow("morphologySrcImage window", g_morphologySrcImage); imageDilateProcess(); imageErodeProcess(); imageOpenProcess(); imageCloseProcess(); imageTopHatProcess(); imageBlackHatProcess(); imageMorphologyGradientProcess(); return true; } bool imageFloodFillNoMask() { Mat floodFillSrcImage = imread("../images/building.jpg"); if(floodFillSrcImage.empty()) { cout<<"floodFillSrcImage is empty!!!"<<endl; return false; } imshow("floodFillSrcImage", floodFillSrcImage); Rect rect; floodFill(floodFillSrcImage, Point(50, 300), Scalar(155, 255, 55), &rect, Scalar(20, 20, 20), Scalar(20, 20, 20)); imshow("floodFillSrcImage dstImage", floodFillSrcImage); return true; } Mat g_floodFillSrcImage, g_floodFillDstImage,g_floodFillGrayImage, g_floodFillMaskImage; int g_nFillMode = 1; int g_nLowDifference = 20, g_nUpDifference = 20; int g_nConnectivity = 4; bool g_bIsColor = true; bool g_bIsShowMask = false; int g_nNewMaskVal = 255; static void mouseClick_cb(int event, int x, int y, int, void*) { if(event != EVENT_LBUTTONDOWN) return; cout<<"mouce left button click..."<<endl; Point seed = Point(x, y); int nLowDifference = g_nFillMode == 0 ? 0 : g_nLowDifference; int nUpDifference = g_nFillMode == 0 ? 0 : g_nUpDifference; int flags = g_nConnectivity + (g_nNewMaskVal << 8) + (g_nFillMode == 1 ? FLOODFILL_FIXED_RANGE : 0); int b = (unsigned)theRNG() & 0xFF; int g = (unsigned)theRNG() & 0xFF; int r = (unsigned)theRNG() & 0xFF; Rect rect; Scalar newVal = g_bIsColor ? Scalar(b, g, r) : Scalar(r*0.229 + g*0.587 + b*0.114); Mat floodFillDstImage = g_bIsColor ? g_floodFillDstImage : g_floodFillGrayImage; int area = 0; if(g_bIsShowMask) { threshold(g_floodFillMaskImage, g_floodFillMaskImage, 1, 128, THRESH_BINARY); area = floodFill(floodFillDstImage, g_floodFillMaskImage, seed, newVal, &rect, Scalar(nLowDifference, nLowDifference, nLowDifference), Scalar(nUpDifference, nUpDifference, nUpDifference), flags); imshow("mask image", g_floodFillMaskImage); } else { area = floodFill(floodFillDstImage, seed, newVal, &rect, Scalar(nLowDifference, nLowDifference, nLowDifference), Scalar(nUpDifference, nUpDifference, nUpDifference), flags); } imshow("FloodFill Prcess Window", floodFillDstImage); cout<<"num:"<<area<<" pixels is been redraw..."<<endl; } bool imageFloodFillWithMask() { // g_floodFillSrcImage = imread("../images/building.jpg"); g_floodFillSrcImage = imread("../images/house.jpg"); if(g_floodFillSrcImage.empty()) { cout<<"g_floodFillSrcImage is empty!!!"<<endl; return false; } g_floodFillDstImage = g_floodFillSrcImage.clone(); cvtColor(g_floodFillSrcImage, g_floodFillGrayImage, COLOR_BGR2GRAY); g_floodFillMaskImage.create(g_floodFillSrcImage.rows + 2, g_floodFillSrcImage.cols + 2, CV_8UC1); namedWindow("FloodFill Prcess Window", WINDOW_AUTOSIZE); createTrackbar("LowDiff", "FloodFill Prcess Window", &g_nLowDifference, 255, 0); createTrackbar("UpDiff", "FloodFill Prcess Window", &g_nUpDifference, 255, 0); setMouseCallback("FloodFill Prcess Window", mouseClick_cb); while(1) { imshow("FloodFill Prcess Window", g_bIsColor ? g_floodFillDstImage : g_floodFillGrayImage); int c = waitKey(0); if((c & 0xFF) == 27) { cout<<"process exit......"<<endl; return false; } switch(char(c)) { case '1': if(g_bIsColor) { cout<<"key \"1\" pressed, switch rgb/gray mode. Now switch to gray mode."<<endl; cvtColor(g_floodFillSrcImage, g_floodFillGrayImage, COLOR_BGR2GRAY); g_floodFillMaskImage = Scalar::all(0); g_bIsColor = false; } else { cout<<"key \"1\" pressed, switch rgb/gray mode. Now switch to rgb mode."<<endl; g_floodFillDstImage = g_floodFillSrcImage.clone(); g_floodFillMaskImage = Scalar::all(0); g_bIsColor = true; } break; case '2': cout<<"key \"2\" pressed, switch to use mask or not."<<endl; if(g_bIsShowMask) { destroyWindow("mask image"); g_bIsShowMask = false; } else { namedWindow("mask image", WINDOW_NORMAL); g_floodFillMaskImage = Scalar::all(0); imshow("mask image", g_floodFillMaskImage); g_bIsShowMask = true; } break; case '3': cout<<"key \"3\" pressed, refresh to src image."<<endl; g_floodFillDstImage = g_floodFillSrcImage.clone(); cvtColor(g_floodFillDstImage, g_floodFillGrayImage, COLOR_BGR2GRAY); g_floodFillMaskImage = Scalar::all(0); break; case '4': cout<<"key \"4\" pressed, use empty range flood fill mode."<<endl; g_nFillMode = 0; break; case '5': cout<<"key \"5\" pressed, use const range flood fill mode."<<endl; g_nFillMode = 1; break; case '6': cout<<"key \"6\" pressed, use float range flood fill mode."<<endl; g_nFillMode = 2; break; case '7': cout<<"key \"7\" pressed, use 4bits connectivity mode."<<endl; g_nConnectivity = 4; break; case '8': cout<<"key \"8\" pressed, use 8bits connectivity mode."<<endl; g_nConnectivity = 8; break; default: break; } } return true; } bool gaussianPyrAndResize() { Mat gaussianPyrSrcImage = imread("../images/car2.jpg"); if(gaussianPyrSrcImage.empty()) { cout<<"gaussianPyrSrcImage is empty!!!"<<endl; return false; } Mat gaussianPyrDstImage, gaussianPyrTmpImage; namedWindow("GaussianPyr and Resize Window", WINDOW_AUTOSIZE); imshow("GaussianPyr and Resize Src Window", gaussianPyrSrcImage); gaussianPyrTmpImage = gaussianPyrSrcImage.clone(); while(1) { int c = waitKey(0); if((c & 0xFF) == 27) { cout<<"process exit......"<<endl; return false; } switch(char(c)) { case 'q': cout<<"key \"q\" pressed, switch to use mask or not."<<endl; break; case 'u': cout<<"key \"u\" pressed, pyr up to double size."<<endl; pyrUp(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols * 2, gaussianPyrTmpImage.rows * 2)); break; case 'd': cout<<"key \"d\" pressed, pyr down to double size."<<endl; pyrDown(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols / 2, gaussianPyrTmpImage.rows / 2)); break; case 'r': cout<<"key \"r\" pressed, resize up to double size with default mode."<<endl; resize(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols * 2, gaussianPyrTmpImage.rows * 2)); break; case 's': cout<<"key \"s\" pressed, resize down to double size with default mode."<<endl; resize(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols / 2, gaussianPyrTmpImage.rows / 2)); break; case 'e': cout<<"key \"e\" pressed, resize up to double size with INTER_CUBIC mode."<<endl; resize(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols * 2, gaussianPyrTmpImage.rows * 2), 0.0, 0.0, INTER_CUBIC); break; case 'a': cout<<"key \"a\" pressed, resize down to double size with INTER_CUBIC mode."<<endl; resize(gaussianPyrTmpImage, gaussianPyrDstImage, Size(gaussianPyrTmpImage.cols / 2, gaussianPyrTmpImage.rows / 2), 0.0, 0.0, INTER_CUBIC); break; default: break; } imshow("GaussianPyr and Resize Drc Window", gaussianPyrDstImage); gaussianPyrTmpImage = gaussianPyrDstImage; } return true; } Mat g_thresholdSrcImage, g_thresholdDstImage, g_thresholdGrayImage; int g_nThresholdType = THRESH_TOZERO; int g_nThresholdValue = 100; void threshold_cb(int, void *) { if(g_nThresholdType != 5) { threshold(g_thresholdGrayImage, g_thresholdDstImage, g_nThresholdValue, 255, g_nThresholdType); } else { adaptiveThreshold(g_thresholdGrayImage, g_thresholdDstImage, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 5, 0); } imshow("Threshold Process Dst Window", g_thresholdDstImage); } bool thresholdOperation() { g_thresholdSrcImage = imread("../images/sea.jpg"); if(g_thresholdSrcImage.empty()) { cout<<"g_thresholdSrcImage is empty!!!"<<endl; return false; } cvtColor(g_thresholdSrcImage, g_thresholdGrayImage, COLOR_BGR2GRAY); namedWindow("Threshold Process Dst Window", WINDOW_AUTOSIZE); imshow("Threshold Process Src Window", g_thresholdSrcImage); createTrackbar("mode", "Threshold Process Dst Window", &g_nThresholdType, 5, threshold_cb); createTrackbar("value", "Threshold Process Dst Window", &g_nThresholdValue, 255, threshold_cb); threshold_cb(0, 0); while(1) { int c = waitKey(0); if(c == 27) break; } return true; } void imgproc_functionality_imageprocess::process() { // imageFilterProcess(); // imageMorphologyProcess(); // imageFloodFillNoMask(); // imageFloodFillWithMask(); // gaussianPyrAndResize(); thresholdOperation(); }
true
7e683dee146ddc316098436de91d0d17435fe599
C++
FFFFFUNKYMUZIK/alg_practice
/Leetcode/91/91/91.cpp
UTF-8
795
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; //fibonacci w/ special case('1' & '2') class Solution { public: int numDecodings(string s) { int n = s.length(); vector<int> noc(n+1, 0); noc[0] = noc[1] = 1; if (s[0] == '0') return 0; for (int i = 2; i <= n; i++) { if (s[i - 1] != '0') noc[i] = noc[i - 1]; if (s[i - 2] == '1') { noc[i] += noc[i - 2]; } else if (s[i - 2] == '2' && s[i - 1] <= '6') { noc[i] += noc[i - 2]; } } return noc[n]; } }; int main() { Solution sol; int ret; ret = sol.numDecodings(string("12")); ret = sol.numDecodings(string("226")); return 0; }
true
31cd24ad40713d1d0a6e168c549a6b8640767297
C++
Kbzinho-66/Analise-Covid
/Trabalho_I_CPP/Registry.hpp
UTF-8
1,650
3.40625
3
[]
no_license
#include <string> #include <iostream> class Registry { private: char patient_sex; int patient_code; int patient_age; int category_code; std::string patient_b_day; std::string vaccination_city; std::string category_name; public: Registry(int patient_code, int patient_age, std::string patient_b_day, std::string vaccination_city, std::string category_name); void printRegistry(); template <class T> void Serialize(T &archive); ~Registry(); }; Registry::Registry(int patient_code, int patient_age, std::string patient_b_day, std::string vaccination_city, std::string category_name) { // this->patient_b_day = new std::string(13, '\0'); // this->vaccination_city = new std::string(32, '\0'); // this->category_name = new std::string(100, '\0'); this->patient_code = patient_code; this->patient_age = patient_age; this->patient_b_day = patient_b_day; this->vaccination_city = vaccination_city; this->category_name = category_name; } void Registry::printRegistry() { std::cout << "Codigo " << patient_code << std::endl; std::cout << "Idade " << patient_age << std::endl; std::cout << "Dt. Nascimento " << patient_b_day << std::endl; std::cout << "Cidade " << vaccination_city << std::endl; std::cout << "Categoria " << category_name << std::endl; std::cout << std::endl; } template <class T> void Registry::Serialize(T &archive) { archive & patient_code & patient_age & patient_b_day; } Registry::~Registry() { }
true
f529ad0b2059e5b6c54f977195dcef4c9bfa992f
C++
rajul/UVa
/11933/splitting.cpp
UTF-8
678
3.4375
3
[]
no_license
#include <iostream> using namespace std; int one_positions[40]; int t, index; int calculate_a() { int res = 0, i; for(i=0; i<index; i=i+2) { res = res | (1 << one_positions[i]); } return res; } int calculate_b() { int res = 0, i; for(i=1; i<index; i=i+2) { res = res | (1 << one_positions[i]); } return res; } void calculate_one_positions(int n) { index = 0; t = 0; while(n) { if(n & 1 == 1) { one_positions[index] = t; index++; } t++; n = n >> 1; } } int main() { int n, i; while(1) { cin >> n; if(n == 0) break; calculate_one_positions(n); cout << calculate_a() << " " << calculate_b() << endl; } return 0; }
true
669501aa1f3a0fa131acd2eb1cabed5193efbe89
C++
JiangSir857/C-Plus-Plus-1
/Object Oriented Programming(C++)/模仿练习参考代码/chapter5/ex3.cpp
GB18030
790
3.671875
4
[]
no_license
/* 1. һƽɼĺNѧijɼú 2. ʹַΪβΣдַƺ */ #include "iostream.h" float fnAve(int *arry,int n); void MyCopy(char *object,char *source); void main() { int a[]={13,56,66,90,65,78}; char b[80]; float fAve; fAve = fnAve(a,6); cout<<"ƽɼ="<<fAve<<endl; MyCopy(b,"how are you"); cout<<b<<endl; } //ƽɼĺ float fnAve(int *arry,int n) { int i,*p,sum; p = arry; sum = *p; for(i=1,p++;i<n;i++,p++) sum += *p; return ((float)sum/n); } //ַƺ void MyCopy(char *object,char *source) { char *s = source,*p=object; while(*s) { *p = *s; p++; s++; } *p = '\0'; }
true
18bdc971b11490f79d7f4eb0ca7074403a211b6c
C++
angelgomezsa/Cplusplus
/Examens/Entrenament Control 3/ex4.cc
UTF-8
521
3.171875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; bool found(int x, const vector<int>& v, int left, int right) { while (left <= right) { int i = (left+right)/2; if (x > v[i]) left = left+1; else if ( x < v[i]) right = right-1; else return true; } return false; } int main() { int n; cin >> n; vector<int> v(n); for (int i=0;i<n;i++) { cin >> v[i]; } int count=0; int right = n-1; for (int i=0;i<n;i++) { int left = i; if (found(-v[i],v,i,right)) count++; } cout << count << endl; }
true
0589786b50869f079bb0e7129756ce4c8c150244
C++
flylofty/coding_test
/programmers200721-02.cpp
UTF-8
430
3.390625
3
[]
no_license
#include <iostream> #include <string> #include <vector> using namespace std; //프로그래머스 연습문제 가운데 글자 가져오기. string solution(string s) { string answer = ""; int size = s.size(); if (s.size() % 2 == 0) { answer += s[s.size() / 2 - 1]; } answer += s[s.size() / 2]; return answer; } int main() { /*string s = "abcde";*/ string s = "abcdef"; cout << solution(s) << endl; return 0; }
true
d4594bab13e5fbdf35e06f76d5520b450c43ac07
C++
Twisterok/NovaCardTestTask
/MyDate.cpp
UTF-8
1,023
3.5
4
[]
no_license
#include "MyDate.h" //CONSTRUCTORS MyDate::MyDate() { this->year = 0; this->month = 0; this->day = 1; } MyDate::MyDate(int _year,int _month,int _day) { this->year = _year; this->month = _month; this->day = _day; } MyDate::MyDate(tm _time) { this->year = _time.tm_year; this->month = _time.tm_mon; this->day = _time.tm_mday; } //OPERATORS bool MyDate::operator==(const MyDate& other) const { if (other.year != this->year) return false; else if (other.month != this->month) return false; else if (other.day != this->day) return false; else return true; } bool MyDate::operator<(const MyDate& other) const { if (this->year < other.year) return true; else if(this->year == other.year && this->month < other.month) return true; else if(this->year == other.year && this->month == other.month && this->day < other.day) return true; else return false; } void MyDate::operator=(const MyDate& other) { this->year = other.year; this->month = other.month; this->day = other.day; }
true
442c570a487e65cb99afdc541a1cb13351fb2327
C++
dikshajain228/ADA-Lab
/randomnobinary search.cpp
UTF-8
345
2.703125
3
[]
no_license
#include<iostream> #include<stdlib.h> using namespace std; int main() { int i,j,max,n; cout<<"Enter the size:"; cin>>n; int a[n]; for(i=0;i<n;i++) a[i]=rand(); for(i=0;i<n;i++) { for(j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } for(i=0;i<n;i++) cout<<a[i]<<"\t";
true
fa0d409341ea5677c73c9e298d528f6edba3ba8d
C++
feixuedudu/network
/protocol/contentprotocol.h
UTF-8
1,704
2.65625
3
[]
no_license
/************************************************************************/ /* 具有一个完整package的protocol 此成会维护对应的contentpackage.同提供给上层应用层的接口; 主要是上层协议XXXXProtocol利用Protocol.Send()写入到CContentProtocol层。 CContentProtocol.Push()会写入到CChannelProtocol 进行缓存,或者直接发送。 见contentprotocol的send与push的描述 /************************************************************************/ /* 此协议需要保证会话和数据包的一致性 在pop时就已经能够获取到正确的包。 同时需要指定protocol的会话状态。 主要是通过报文时间进行确定。 服务器和客服端采用点到点通信。 在一个协议连接起来后。如果设置进行心跳验证 服务器和客服端会进行心跳包的通信。 */ #ifndef PROTOCOL_CONTENTPROTOCOL_H #define PROTOCOL_CONTENTPROTOCOL_H #include "Protocol.h" class CContentProtocol:public CProtocol { public: CContentProtocol(CDispatcher* reactor); virtual ~CContentProtocol(); virtual int Pop( CPackage* package ); virtual int OnRecvErrPackage( CPackage* package ); //向channelprotocol传送package时,添加content层的头部。 virtual int Push( CPackage* package,CProtocol* protocol ); virtual void OnTimer( int event ); //发送timeout到对方,进行设置 void send_timeout(int timeout); //利用收到的CContentPackage设置对应的心跳超时时间 void set_timeout(CPackage* package); //不进行心跳的测试 void set_timecheck(bool flag); bool SendHeartTag(); private: time_t m_timeOut; bool m_needchecktime; time_t m_LastReadTime; time_t m_LastWriteTime; }; #endif
true
73b2ee871f5573d80e9153e6cb4789a9a85258a1
C++
cyssure/miniRSA
/encryptiontest.cpp
UTF-8
2,217
3.1875
3
[]
no_license
/** *This program test the process of encryption */ #include "miniRSA.h" #include "Encryption.h" #include <iostream> #include <string> using namespace std; int main(int argc, char** argv) { cout << "Enter the nth prime and the mth prime to compute" << endl; string line; getline(cin, line); int p1 = line.find(" ", 0); if (p1 == string::npos) { cout << "Please enter a white space between two numbers" << endl; exit(0); } int first_num = atoi(line.substr(0, p1).c_str()); int second_num = atoi(line.substr(p1 + 1, string::npos).c_str()); Encryption en; int first_b = first_num; int second_b = second_num; en.generate_primes(&first_num, &second_num); cout << first_b << "th prime = " << first_num << ", " << second_b << "th prime = " << second_num << ", "; long c = en.compute_c(first_num, second_num); cout << "c = " << c << ", "; long m = en.compute_m(first_num, second_num); cout << "m = " << m << ", "; long e = en.compute_key(m); cout << "e = " << e << ", "; long d = en.compute_d(e, m); cout << "d = " << d << ", "; cout << "Public Key = (" << e << ", " << c << "), "; cout << "Private Key = (" << d << ", " << c << ")" << endl; }
true
033fae4923953c654500cb5f329f8ea956eec799
C++
yoyonel/holyspirit-softshadow2d
/src/Light.h
UTF-8
2,943
3.125
3
[]
no_license
#ifndef LIGHTH #define LIGHTH #include <SFML/System.hpp> #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> struct Wall { Wall (sf::Vector2f p1,sf::Vector2f p2) { pt1=p1; pt2=p2; } // Pt1 et Pt2 sont les deux extremites du mur sf::Vector2f pt1; sf::Vector2f pt2; }; // Wall_Entity est une variable qui permet de representer dans le programme un mur struct Wall_Entity { Wall_Entity (int id) { m_ID=id; } int ID() { return m_ID; } private: int m_ID; }; // Light_Entity est une variable qui permet de representer dans le programme une lumiere struct Light_Entity { Light_Entity (){m_Dynamic=false,m_ID=0; m_SoftShadow=false; m_NormalMap=false;} Light_Entity (int id,bool d, bool ss=false, bool nm=false) { m_ID=id; m_Dynamic=d; m_SoftShadow=ss; m_NormalMap=nm; } int ID() const { return m_ID; } bool Dynamic() const { return m_Dynamic; } bool SoftShadow() const { return m_SoftShadow; } bool NormalMap() const { return m_NormalMap; } private: int m_ID; bool m_Dynamic; bool m_SoftShadow; bool m_NormalMap; }; class Light { public : // Constructeur et destructeur Light(); Light(sf::Vector2f position, float intensity, float radius, int quality, sf::Color color); ~Light(); // Afficher la lumiere virtual void Draw(sf::RenderTarget *App); // Calculer la lumiere virtual void Generate(std::vector <Wall> &m_wall); // Ajouter un triangle a la lumiere, en effet, les lumieres sont composee de triangles virtual void AddTriangle(sf::Vector2f pt1,sf::Vector2f pt2, int minimum_wall,std::vector <Wall> &m_wall); // Changer differents attributs de la lumiere void SetIntensity(float); void SetRadius(float); void SetQuality(int); void SetColor(sf::Color); void SetPosition(sf::Vector2f); virtual void SetOtherParameter(unsigned, float); // Retourner differents attributs de la lumiere float GetIntensity(); float GetRadius(); int GetQuality(); sf::Color GetColor(); sf::Vector2f GetPosition(); // Une petite bool pour savoir si la lumiere est allumee ou eteinte bool m_actif; protected : //Position a l'ecran sf::Vector2f m_position; //Intensite, gere la transparence ( entre 0 et 255 ) float m_intensity; //Rayon de la lumiere float m_influence_radius; //Couleur de la lumiere sf::Color m_color; //Tableau dynamique de Shape, ce sont ces shapes de type triangle qui compose la lumiere std::vector <sf::Shape> m_shape; private : //Qualite de la lumiere, c'est a dire le nombre de triangles par defaut qui la compose. int m_quality; }; #endif
true
2f1191ceb1e27c653f860b0fb796075a6d0cac60
C++
HrishikeshP-01/Beginning-Cpp-Game-Programming
/GameOver2.cpp
UTF-8
134
2.828125
3
[]
no_license
#include <iostream> // Employing a using directive using namespace std; int main() { cout << "Game Over!" << endl; return 0; }
true
b44a44611eca47f9c36960154b3f6f81bcb5849c
C++
nobled/clang
/test/CodeGenCXX/const-init-cxx11.cpp
UTF-8
7,718
2.59375
3
[ "NCSA" ]
permissive
// RUN: %clang_cc1 -verify -triple x86_64-apple-darwin -emit-llvm -o - %s -std=c++11 | FileCheck %s // FIXME: The padding in all these objects should be zero-initialized. namespace StructUnion { struct A { int n; double d; union U { constexpr U(int x) : x(x) {} constexpr U(const char *y) : y(y) {} int x; const char *y; } u; constexpr A(int n, double d, int x) : n(n), d(d), u(x) {} constexpr A(int n, double d, const char *y) : n(n), d(d), u(y) {} }; // CHECK: @_ZN11StructUnion1aE = global {{.*}} { i32 1, double 2.000000e+00, {{.*}} { i32 3, [4 x i8] undef } } extern constexpr A a(1, 2.0, 3); // CHECK: @_ZN11StructUnion1bE = global {{.*}} { i32 4, double 5.000000e+00, {{.*}} { i8* getelementptr inbounds ([6 x i8]* @{{.*}}, i32 0, i32 0) } } extern constexpr A b(4, 5, "hello"); struct B { int n; }; // CHECK: @_ZN11StructUnion1cE = global {{.*}} zeroinitializer // CHECK: @_ZN11StructUnion2c2E = global {{.*}} zeroinitializer B c; B c2 = B(); // CHECK: @_ZN11StructUnion1dE = global {{.*}} zeroinitializer B d[10]; struct C { constexpr C() : c(0) {} int c; }; // CHECK: @_ZN11StructUnion1eE = global {{.*}} zeroinitializer C e[10]; struct D { constexpr D() : d(5) {} int d; }; // CHECK: @_ZN11StructUnion1fE = global {{.*}} { i32 5 } D f; } namespace BaseClass { template<typename T, unsigned> struct X : T {}; struct C { char c = 1; }; template<unsigned... Ns> struct Cs : X<C,Ns>... {}; struct N { int n = 3; }; struct D { double d = 4.0; }; template<typename ...Ts> struct Test : Ts... { constexpr Test() : Ts()..., n(5) {} int n; }; using Test1 = Test<N, C, Cs<1,2>, D, X<C,1>>; // CHECK: @_ZN9BaseClass2t1E = global {{.*}} { i32 3, i8 1, i8 1, i8 1, double 4.000000e+00, i8 1, i32 5 }, align 8 extern constexpr Test1 t1 = Test1(); struct DN : D, N {}; struct DND : DN, X<D,0> {}; struct DNN : DN, X<N,0> {}; // CHECK: @_ZN9BaseClass3dndE = global {{.*}} { double 4.000000e+00, i32 3, double 4.000000e+00 } extern constexpr DND dnd = DND(); // Note, N subobject is laid out in DN subobject's tail padding. // CHECK: @_ZN9BaseClass3dnnE = global {{.*}} { double 4.000000e+00, i32 3, i32 3 } extern constexpr DNN dnn = DNN(); struct E {}; struct Test2 : X<E,0>, X<E,1>, X<E,2>, X<E,3> {}; // CHECK: @_ZN9BaseClass2t2E = global {{.*}} undef extern constexpr Test2 t2 = Test2(); } namespace Array { // CHECK: @_ZN5Array3arrE = constant [2 x i32] [i32 4, i32 0] extern constexpr int arr[2] = { 4 }; // CHECK: @_ZN5Array1cE = constant [6 x [4 x i8]] [{{.*}} c"foo\00", [4 x i8] c"a\00\00\00", [4 x i8] c"bar\00", [4 x i8] c"xyz\00", [4 x i8] c"b\00\00\00", [4 x i8] c"123\00"] extern constexpr char c[6][4] = { "foo", "a", { "bar" }, { 'x', 'y', 'z' }, { "b" }, '1', '2', '3' }; struct C { constexpr C() : n(5) {} int n, m = 3 * n + 1; }; // CHECK: @_ZN5Array5ctorsE = global [3 x {{.*}}] [{{.*}} { i32 5, i32 16 }, {{.*}} { i32 5, i32 16 }, {{.*}} { i32 5, i32 16 }] extern const C ctors[3]; constexpr C ctors[3]; // CHECK: @_ZN5Array1dE = constant {{.*}} { [2 x i32] [i32 1, i32 2], [3 x i32] [i32 3, i32 4, i32 5] } struct D { int n[2]; int m[3]; } extern constexpr d = { 1, 2, 3, 4, 5 }; } namespace MemberPtr { struct B1 { int a, b; virtual void f(); void g(); }; struct B2 { int c, d; virtual void h(); void i(); }; struct C : B1 { int e; virtual void j(); void k(); }; struct D : C, B2 { int z; virtual void l(); void m(); }; // CHECK: @_ZN9MemberPtr2daE = constant i64 8 // CHECK: @_ZN9MemberPtr2dbE = constant i64 12 // CHECK: @_ZN9MemberPtr2dcE = constant i64 32 // CHECK: @_ZN9MemberPtr2ddE = constant i64 36 // CHECK: @_ZN9MemberPtr2deE = constant i64 16 // CHECK: @_ZN9MemberPtr2dzE = constant i64 40 extern constexpr int (D::*da) = &B1::a; extern constexpr int (D::*db) = &C::b; extern constexpr int (D::*dc) = &B2::c; extern constexpr int (D::*dd) = &D::d; extern constexpr int (D::*de) = &C::e; extern constexpr int (D::*dz) = &D::z; // CHECK: @_ZN9MemberPtr2baE = constant i64 8 // CHECK: @_ZN9MemberPtr2bbE = constant i64 12 // CHECK: @_ZN9MemberPtr2bcE = constant i64 8 // CHECK: @_ZN9MemberPtr2bdE = constant i64 12 // CHECK: @_ZN9MemberPtr2beE = constant i64 16 // CHECK: @_ZN9MemberPtr3b1zE = constant i64 40 // CHECK: @_ZN9MemberPtr3b2zE = constant i64 16 extern constexpr int (B1::*ba) = (int(B1::*))&B1::a; extern constexpr int (B1::*bb) = (int(B1::*))&C::b; extern constexpr int (B2::*bc) = (int(B2::*))&B2::c; extern constexpr int (B2::*bd) = (int(B2::*))&D::d; extern constexpr int (B1::*be) = (int(B1::*))&C::e; extern constexpr int (B1::*b1z) = (int(B1::*))&D::z; extern constexpr int (B2::*b2z) = (int(B2::*))&D::z; // CHECK: @_ZN9MemberPtr2dfE = constant {{.*}} { i64 1, i64 0 } // CHECK: @_ZN9MemberPtr2dgE = constant {{.*}} { i64 {{.*}}2B11gEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr2dhE = constant {{.*}} { i64 1, i64 24 } // CHECK: @_ZN9MemberPtr2diE = constant {{.*}} { i64 {{.*}}2B21iEv{{.*}}, i64 24 } // CHECK: @_ZN9MemberPtr2djE = constant {{.*}} { i64 9, i64 0 } // CHECK: @_ZN9MemberPtr2dkE = constant {{.*}} { i64 {{.*}}1C1kEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr2dlE = constant {{.*}} { i64 17, i64 0 } // CHECK: @_ZN9MemberPtr2dmE = constant {{.*}} { i64 {{.*}}1D1mEv{{.*}}, i64 0 } extern constexpr void (D::*df)() = &C::f; extern constexpr void (D::*dg)() = &B1::g; extern constexpr void (D::*dh)() = &B2::h; extern constexpr void (D::*di)() = &D::i; extern constexpr void (D::*dj)() = &C::j; extern constexpr void (D::*dk)() = &C::k; extern constexpr void (D::*dl)() = &D::l; extern constexpr void (D::*dm)() = &D::m; // CHECK: @_ZN9MemberPtr2bfE = constant {{.*}} { i64 1, i64 0 } // CHECK: @_ZN9MemberPtr2bgE = constant {{.*}} { i64 {{.*}}2B11gEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr2bhE = constant {{.*}} { i64 1, i64 0 } // CHECK: @_ZN9MemberPtr2biE = constant {{.*}} { i64 {{.*}}2B21iEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr2bjE = constant {{.*}} { i64 9, i64 0 } // CHECK: @_ZN9MemberPtr2bkE = constant {{.*}} { i64 {{.*}}1C1kEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr3b1lE = constant {{.*}} { i64 17, i64 0 } // CHECK: @_ZN9MemberPtr3b1mE = constant {{.*}} { i64 {{.*}}1D1mEv{{.*}}, i64 0 } // CHECK: @_ZN9MemberPtr3b2lE = constant {{.*}} { i64 17, i64 -24 } // CHECK: @_ZN9MemberPtr3b2mE = constant {{.*}} { i64 {{.*}}1D1mEv{{.*}}, i64 -24 } extern constexpr void (B1::*bf)() = (void(B1::*)())&C::f; extern constexpr void (B1::*bg)() = (void(B1::*)())&B1::g; extern constexpr void (B2::*bh)() = (void(B2::*)())&B2::h; extern constexpr void (B2::*bi)() = (void(B2::*)())&D::i; extern constexpr void (B1::*bj)() = (void(B1::*)())&C::j; extern constexpr void (B1::*bk)() = (void(B1::*)())&C::k; extern constexpr void (B1::*b1l)() = (void(B1::*)())&D::l; extern constexpr void (B1::*b1m)() = (void(B1::*)())&D::m; extern constexpr void (B2::*b2l)() = (void(B2::*)())&D::l; extern constexpr void (B2::*b2m)() = (void(B2::*)())&D::m; } // Constant initialization tests go before this point, // dynamic initialization tests go after. namespace CrossFuncLabelDiff { // Make sure we refuse to constant-fold the variable b. constexpr long a(bool x) { return x ? 0 : (long)&&lbl + (0 && ({lbl: 0;})); } void test() { static long b = (long)&&lbl - a(false); lbl: return; } // CHECK: sub nsw i64 ptrtoint (i8* blockaddress(@_ZN18CrossFuncLabelDiff4testEv, {{.*}}) to i64), // CHECK: store i64 {{.*}}, i64* @_ZZN18CrossFuncLabelDiff4testEvE1b, align 8 }
true
0e03cb9c555d6a734e01be3acecfc801c51ffee6
C++
DataYI/cplusplus
/CppSTL/algorithm/nth_element.cpp
UTF-8
355
3.0625
3
[ "AFL-2.0" ]
permissive
#include<bits/stdc++.h> using namespace std; int main() { vector<int> v{1, 3, 4, 5, 2, 6, 8, 7, 9}; for_each(v.begin(), v.end(), [](int x) { cout << x << " "; }); cout << endl; nth_element(v.begin(), v.begin() + 5, v.end()); copy(v.begin(), v.end(), ostream_iterator<int>(cout, " ")); cout << endl; return 0; }
true
3bf5790cd943cd0f8e2e44bc5587dc9e2c26588c
C++
garyuppal/OldMicrobeSimulator
/common/bacteria/fitness.h
UTF-8
909
2.625
3
[]
no_license
#ifndef MICROBE_SIMULATOR_FITNESS_H #define MICROBE_SIMULATOR_FITNESS_H #include <deal.II/base/point.h> using dealii::Point; #include <array> // #include "../utility/argparser.h" // #include "../chemicals/chemicals.h" namespace MicrobeSimulator{ template<int dim, int NumberChemicals> class FitnessBase{ public: FitnessBase(); virtual ~FitnessBase() {} virtual double value(const Point<dim>& location, const std::array<double, NumberChemicals>& secretion_rates) const; // can include pointers to chemicals as private variables in specific instantiation }; template<int dim, int NumberChemicals> FitnessBase<dim, NumberChemicals>::FitnessBase() {} template<int dim, int NumberChemicals> double FitnessBase<dim, NumberChemicals>::value(const Point<dim>& /* location */, const std::array<double, NumberChemicals>& /* secretion_rates */) const { return 0.; } } #endif
true