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
468200506411ce54e7056439503b527601c7a123
C++
icl-rocketry/Avionics
/Ricardo_OS/Python_backend/venv/lib/python3.8/site-packages/greenlet/tests/_test_extension_cpp.cpp
UTF-8
3,212
2.84375
3
[ "MIT" ]
permissive
/* This is a set of functions used to test C++ exceptions are not * broken during greenlet switches */ #include "../greenlet.h" struct exception_t { int depth; exception_t(int depth) : depth(depth) {} }; /* Functions are called via pointers to prevent inlining */ static void (*p_test_exception_throw)(int depth); static PyObject* (*p_test_exception_switch_recurse)(int depth, int left); static void test_exception_throw(int depth) { throw exception_t(depth); } static PyObject* test_exception_switch_recurse(int depth, int left) { if (left > 0) { return p_test_exception_switch_recurse(depth, left - 1); } PyObject* result = NULL; PyGreenlet* self = PyGreenlet_GetCurrent(); if (self == NULL) return NULL; try { PyGreenlet_Switch(self->parent, NULL, NULL); p_test_exception_throw(depth); PyErr_SetString(PyExc_RuntimeError, "throwing C++ exception didn't work"); } catch (exception_t& e) { if (e.depth != depth) PyErr_SetString(PyExc_AssertionError, "depth mismatch"); else result = PyLong_FromLong(depth); } catch (...) { PyErr_SetString(PyExc_RuntimeError, "unexpected C++ exception"); } Py_DECREF(self); return result; } /* test_exception_switch(int depth) * - recurses depth times * - switches to parent inside try/catch block * - throws an exception that (expected to be caught in the same function) * - verifies depth matches (exceptions shouldn't be caught in other greenlets) */ static PyObject* test_exception_switch(PyObject* self, PyObject* args) { int depth; if (!PyArg_ParseTuple(args, "i", &depth)) return NULL; return p_test_exception_switch_recurse(depth, depth); } static PyMethodDef test_methods[] = { {"test_exception_switch", (PyCFunction)&test_exception_switch, METH_VARARGS, "Switches to parent twice, to test exception handling and greenlet " "switching."}, {NULL, NULL, 0, NULL}}; #if PY_MAJOR_VERSION >= 3 # define INITERROR return NULL static struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, "greenlet.tests._test_extension_cpp", NULL, 0, test_methods, NULL, NULL, NULL, NULL}; PyMODINIT_FUNC PyInit__test_extension_cpp(void) #else # define INITERROR return PyMODINIT_FUNC init_test_extension_cpp(void) #endif { PyObject* module = NULL; #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); #else module = Py_InitModule("greenlet.tests._test_extension_cpp", test_methods); #endif if (module == NULL) { INITERROR; } PyGreenlet_Import(); if (_PyGreenlet_API == NULL) { INITERROR; } p_test_exception_throw = test_exception_throw; p_test_exception_switch_recurse = test_exception_switch_recurse; #if PY_MAJOR_VERSION >= 3 return module; #endif }
true
aeb6635aa150c2bcaa65f2a663d53ab9574a306b
C++
UG-SEP/DSA-guide
/Arrays/cpp/merge_two_sorted_arrays.cpp
UTF-8
1,551
4.5
4
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <algorithm> using namespace std; // Function to merge two arrays without extra space void merge_two_arrays(vector <int> &arr1 , vector <int> &arr2) { // The approach is to traverse the first array from right to left and the // second array from left to right and swap elements if first array's element // larger than the second array's element, else continue. // During each swap we need to sort the arrays, to make the smallest element // of the second array be always at front and the largest element of the first // array be always at the rear. // Time Complexity - O(nlogn) // Space Complexity - O(1) int i = arr1.size() - 1 , j = 0; while(true) { if(arr1[i] > arr2[j]) { swap(arr1[i] , arr2[j]); sort(arr1.begin() , arr1.end()); sort(arr2.begin() , arr2.end()); } else { break; } } } int main() { int n1 , n2; cout << "Enter the size of the first array : " << endl; cin >> n1; cout << "Enter the size of the second array : " << endl; cin >> n2; vector <int> arr1(n1) , arr2(n2); cout << "Enter the elements of first array in sorted order : " << endl; for(int i = 0; i < n1; i++) { cin >> arr1[i]; } cout << "Enter the elements of second array in sorted order : " << endl; for(int i = 0; i < n2; i++) { cin >> arr2[i]; } merge_two_arrays(arr1 , arr2); cout << "After merging : " << endl; for(int i = 0; i < n1; i++) { cout << arr1[i] << " "; } for(int i = 0; i < n2; i++) { cout << arr2[i] << " "; } cout << endl; return 0; }
true
5c8f1bdf068b216d7bdcdd9972377b880f647e8a
C++
Tudor67/Competitive-Programming
/LeetCode/Explore/March-LeetCoding-Challenge-2021/#Day#2_SetMismatch_sol5_int_sign_as_visited_mark_O(N)_time_O(1)_extra_space_28ms_21.4MB.cpp
UTF-8
695
2.5625
3
[ "MIT" ]
permissive
class Solution { public: vector<int> findErrorNums(vector<int>& nums) { const int N = nums.size(); int duplicate = -1; int missing = -1; for(int num: nums){ int idx = abs(num) - 1; if(nums[idx] < 0){ duplicate = abs(num); } nums[idx] = -abs(nums[idx]); } for(int idx = 0; idx < N; ++idx){ if(nums[idx] > 0){ missing = idx + 1; } } for(int idx = 0; idx < N; ++idx){ nums[idx] = abs(nums[idx]); } return {duplicate, missing}; } };
true
2c0d668d703f7cd43a987d96244a58d491ba9e81
C++
timmorey/nvn
/libnvn/Layer.hpp
UTF-8
545
2.546875
3
[]
no_license
/** Layer.hpp - Created by Timothy Morey on 1/12/2013 */ #ifndef __LAYER_HPP__ #define __LAYER_HPP__ #include "nvn.h" #include "CartesianCRS.hpp" class Layer { protected: Layer() : _ModelCrs(4) {}; public: virtual ~Layer() {}; public: virtual int Render() = 0; virtual int SetModelCRS(const CartesianCRS& crs) = 0; public: virtual NVN_BBox GetBounds() const = 0; virtual const CRS& GetDataCRS() const = 0; virtual const CartesianCRS& GetModelCRS() const { return _ModelCrs; } protected: CartesianCRS _ModelCrs; }; #endif
true
aa95eb9e4ccb13907db43d6e421438c48436e4c1
C++
widemouthfrog1/Chess
/Chess/Rook.cpp
UTF-8
511
2.78125
3
[]
no_license
#include "stdafx.h" #include "Rook.h" Rook::Rook(std::shared_ptr<Image> image, bool white, POINT pos) { this->image = image; this->white = white; this->pos = pos; } Rook::~Rook() { } void Piece::move(Tile before, Tile after) { before.setPiece(NULL); after.setPiece(shared_from_this()); } void Piece::draw(Graphics* canvas) { UINT width = this->image->GetWidth(); UINT height = this->image->GetHeight(); canvas->DrawImage(&(*(this->image)), this->pos.x, this->pos.y, Tile::SIZE, Tile::SIZE); }
true
78daa79a4ebdf8b6a3771c6bdfb0469ba2764ff6
C++
God-Ra/CP-Library
/Math/Miller Rabin primality test.cpp
UTF-8
1,457
3.265625
3
[]
no_license
#include <iostream> using ull = unsigned long long int; using ll = long long int; ll mulmod(ull a, ull b, ull mod) { ull res = 0; a %= mod; for (; b > 0; b >>= 1) { if (b & 1) res = (res + a) % mod; a = (a + a) % mod; } return res; } ll powmod(ll a, ll b, ll mod) { a %= mod; ll res = 1; for (; b > 0; b >>= 1) { if (b & 1) res = mulmod(res, a, mod); a = mulmod(a, a, mod); } return res; } bool check_composite(ll n, ll r, ll d, ll a) { ll x = powmod(a, d, n); if (x == 1 || x == n - 1) return false; for (int i = 1; i < r; ++i) { x = mulmod(x, x, n); if (x == n - 1) return false; } return true; } //returns 1 if prime, otherwise 0 bool MillerRabin(ull n) { if (n < 2) return false; //for a 32 bit integer, it is enough to check 2, 3, 5, 7 //for a 64 bit integer, first 12 primes int r = 0; ull d = n - 1; while (!(d & 1)) { d >>= 1; ++r; } for (int a : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37}) { if (n == a) return true; else if (check_composite(n, r, d, a)) return false; } return true; } int main() { int t; std::cin >> t; while (t--) { ull n; std::cin >> n; std::cout << (MillerRabin(n) ? "YES\n" : "NO\n"); } }
true
0d674969f08b2885628fc7104a46bafa55c3129b
C++
iskislamov/kyapr
/virtual/main.cpp
UTF-8
857
2.78125
3
[]
no_license
#include <iostream> #include "classes.h" VIRTUAL_CLASS(Base) int a = 5; DECLARE_METHOD(Base, Both) std::cout << ptr_->a; END_DECLARE DECLARE_METHOD(Base, OnlyBase) END_DECLARE CONSTRUCTOR_BASE(Base, ADD_METHOD(Base, Both) ADD_METHOD(Base, OnlyBase)) END(Base) VIRTUAL_CLASS_DERIVED(Derived, Base) int b = 10; DECLARE_METHOD(Derived, Both) std::cout << ptr_->b; END_DECLARE DECLARE_METHOD(Derived, OnlyDerived) END_DECLARE CONSTRUCTOR_DERIVED(Derived, Base, ADD_METHOD(Derived, Both) ADD_METHOD(Derived, OnlyDerived)) END(Derived) int main() { Base base; Derived derived; Base* reallyDerived = reinterpret_cast<Base*>(&derived); VIRTUAL_CALL((&base), Both); VIRTUAL_CALL(reallyDerived, Both); VIRTUAL_CALL(reallyDerived, OnlyBase); VIRTUAL_CALL(reallyDerived, OnlyDerived); system("pause"); return 0; }
true
9aefefaa45d183c92988362e913a53e507cedac1
C++
joeykrakowski/enjin-cpp-sdk
/test/unit/models/NotificationsTest.cpp
UTF-8
2,902
2.609375
3
[ "Apache-2.0", "BSD-3-Clause", "OpenSSL", "MIT" ]
permissive
/* Copyright 2021 Enjin Pte. Ltd. * * 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 under the License. */ #include "gtest/gtest.h" #include "JsonTestSuite.hpp" #include "enjinsdk/models/Notifications.hpp" #include <string> using namespace enjin::sdk::models; using namespace enjin::test::suites; class NotificationsTest : public JsonTestSuite, public testing::Test { public: Notifications class_under_test; constexpr static char POPULATED_JSON_OBJECT[] = R"({"pusher":{}})"; }; TEST_F(NotificationsTest, DeserializeEmptyStringFieldsDoNotHaveValues) { // Arrange const std::string json; // Act class_under_test.deserialize(json); // Assert EXPECT_FALSE(class_under_test.get_pusher().has_value()); } TEST_F(NotificationsTest, DeserializeEmptyJsonObjectFieldsDoNotHaveValues) { // Arrange const std::string json(EMPTY_JSON_OBJECT); // Act class_under_test.deserialize(json); // Assert EXPECT_FALSE(class_under_test.get_pusher().has_value()); } TEST_F(NotificationsTest, DeserializePopulatedJsonObjectFieldsHaveExpectedValues) { // Arrange const Pusher expected_pusher; const std::string json(POPULATED_JSON_OBJECT); // Act class_under_test.deserialize(json); // Assert EXPECT_EQ(expected_pusher, class_under_test.get_pusher().value()); } TEST_F(NotificationsTest, EqualityNeitherSideIsPopulatedReturnsTrue) { // Arrange Notifications lhs; Notifications rhs; // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(NotificationsTest, EqualityBothSidesArePopulatedReturnsTrue) { // Arrange Notifications lhs; Notifications rhs; lhs.deserialize(POPULATED_JSON_OBJECT); rhs.deserialize(POPULATED_JSON_OBJECT); // Act bool actual = lhs == rhs; // Assert ASSERT_TRUE(actual); } TEST_F(NotificationsTest, EqualityLeftSideIsPopulatedReturnsFalse) { // Arrange Notifications lhs; Notifications rhs; lhs.deserialize(POPULATED_JSON_OBJECT); // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); } TEST_F(NotificationsTest, EqualityRightSideIsPopulatedReturnsFalse) { // Arrange Notifications lhs; Notifications rhs; rhs.deserialize(POPULATED_JSON_OBJECT); // Act bool actual = lhs == rhs; // Assert ASSERT_FALSE(actual); }
true
6d75b8d11a8640f1834f2e1951ee46ebde4ff2b3
C++
JAllyn/HighSchool_C-
/WhileLoops.cpp
UTF-8
2,181
3.546875
4
[]
no_license
// WhileLoops.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <iomanip> #include <string> using namespace std; int main() {//begin main /******************************** While () loop - pretest loop The condition is tested before it enters the body of the loop. ********************************/ /******************************* Enter 10 numbers, add them together and print out the result. The sentinel value is the used to end or break out of the loop. *******************************/ double n = 0, //value sum = 0, //total of the values entered count = 1, //counts the number of values i = 0; /*cout<<"Enter a number or a -999 to end: "; cin>>n; while(n != -999) {//begin while cout<<"Number = "<<"\t"<<n<<"\tcount = \t"<<count<<endl; sum += n; //sum = sum + n if(count >= 5) n = -999; else { cout<<"Enter a number or a -999 to end: "; cin>>n; count++; //increment count } }//end while cout<<"sum= "<<sum<<endl; cout<<"Average = "<<sum/count<<endl; /****************************************** do...while() - This is a post test loop. This means the condition is tested at the end of the loop. This loop will run at least once. ******************************************/ /* n = 0; count = 0; sum = 0; do {// begin do...while() cout<<"Enter a number or a -999 to end: "; cin>>n; count++; //increment count cout<<"Number = "<<"\t"<<n<<"\tcount = \t"<<count<<endl; sum += n; //sum = sum + n if(count >= 5) n = -999; }while(n != -999); /************************************************* for loop - counting loop this loop will only perform a certain amount of times *************************************************/ count = 0; for ( int i = 1; i <=10; i++) { cout<<"Enter a number: "; cin>>n; count++; cout<<"Number = "<<"\t"<<n<<"\tcount = \t"<<count<<endl; sum += n; } cout<<"sum = "<<sum<<endl; cout<<"Average = "<<sum/count<<endl; return 0; }//end main
true
6f78cf5962e7e185c7b238c92c5580907f60da47
C++
nitikgoyal/C-_prog
/copyconstructor/main.cpp
UTF-8
460
3.46875
3
[]
no_license
#include <iostream> using namespace std; class complex { int a,b; public: complex(int x) /* or write complex(int x):a(x),b(2x) */ { a=x; b=2*x; } complex(complex &ob) { a=ob.a; b=ob.b; } void put() { cout<<a<<endl<<b<<endl; } }; int main() { int x; cin>>x; complex c(x); complex c2=c; /* or write complex c1(c) */ c.put(); c2.put(); return 0; }
true
834500f4d271754a095a10cb90e6ca4ec2d64c38
C++
GuerfelMohamed/Syst-me-temps-r-el-embarqu-et-mobile
/CalculePI/Pi_Serial.cpp
UTF-8
1,263
3.53125
4
[]
no_license
#include <iostream> #include <stdlib.h> #include <time.h> using namespace std; /** * @desc: Estime la valeur de Pi par l'experience de DartBoard * @return: Renvoie la valeur estimée de Pi pour une iteration. */ double DartBoard(){ double darts = 5000; double circle_count = 0.0f; // Simuler le lancement d'une flèche sur un plateau et récupérer ses x et y for(int i = 0; i < darts; i++){ double xcoordinate, ycoordinate; xcoordinate = (double) rand()/RAND_MAX; ycoordinate = (double) rand()/RAND_MAX; // Obtenir le nombre de flèches qui sont tombées dans le cercle de rayon 1 if ((xcoordinate * xcoordinate) + (ycoordinate * ycoordinate) <= 1){ circle_count++; } } // La valeur estimer de PI double PI = (4.0f*circle_count)/darts; return PI; } int main() { srand( (unsigned)time( NULL ) ); // continent les valeurs estimées cumulées de PI afin de calculer la moyenne et la valeur finale de PI. double valuePI = 0.0f; for(int i = 0; i < 500000; i++){ valuePI += DartBoard(); cout << "iterations: " << i+1 << ", valeur de PI: " << valuePI/(i+1) << endl; } return 0; }
true
bc95d5e9ce716e406b0266c7e3266d7670160b90
C++
HelgaEmese/ideiinfo
/hazi04/main.cpp
UTF-8
943
2.625
3
[]
no_license
#include <iostream> #include <string> #include <fstream> using namespace std; int main() { string telefonszam ; ifstream input("input.txt"); ofstream vezetekes("vezetekes.txt"); ofstream orange("orange.txt"); ofstream vodafone ("vodafone.txt"); ofstream digi("digi.txt"); while (getline (input,telefonszam)) { if(telefonszam[0]=='6') { telefonszam.insert(0,"00402"); vezetekes<<telefonszam<<endl; } if(telefonszam[0]=='7') { telefonszam.insert(0,"00407"); digi<<telefonszam<<endl; } if(telefonszam[0]=='2') { telefonszam.insert(0,"00407"); vodafone<<telefonszam<<endl; } if(telefonszam[0]=='4') { telefonszam.insert(0,"00407"); orange<<telefonszam<<endl; } } return 0; }
true
e90b1b4adec26eed942d48f4fa46f7e2bbea2803
C++
sergiosvieira/wrapper
/mid-scroll-area.h
UTF-8
989
2.671875
3
[]
no_license
#ifndef MID_SCROLL_AREA_H #define MID_SCROLL_AREA_H #include "mid-object.h" #include "mid-window.h" #include "definitions.h" /*! * \brief MidScrollArea Template */ template <class T> class MidScrollArea : public MidObject { public: /*! * \brief MidScrollArea * \param id * \param parent */ MidScrollArea(Id id = 0, MidObject parent = nullptr): MidObject(new T{id, parent}){} void setComponent(MidObject component) { T *obj = static_cast<T*>(this->get()); if (obj) obj->setComponent(component); } void setMidGeometry(int originX, int originY, int width, int height) { T *obj = static_cast<T*>(this->get()); if (obj) obj->setMidGeometry(originX, originY, width, height); } void setMidScrollBarPolicy(MidScrollBarPolicy policy) { T *obj = static_cast<T*>(this->get()); if (obj) obj->setMidScrollBarPolicy(policy); } }; #endif /* MID_SCROLL_AREA_H */
true
874f50946c60cb99d3adb5a4f4b5d1df4bbe53ba
C++
BogdanYaroslav/Shariy-C-
/laba 3/Musician.cpp
WINDOWS-1251
3,101
3.28125
3
[]
no_license
#include "Musician.h" #include <iostream> #include <fstream> Musician::Musician() : Personality(), tool_(Tools::Strings), rating_(0), experience_(0) { cout << " " << name_ << " " << surname_ << " " << endl << endl; } Musician::Musician(const string& name, const string& surname, char gender, int year, const Tools& tool, int rating, int experience) : Personality(name,surname,gender,year),tool_(tool), rating_(rating), experience_(experience) { cout << " " << name_ << " " << surname_ << " " << endl << endl; } Musician::~Musician() { cout << " " << name_ << " " << surname_ << " " << endl << endl; } Tools Musician::getTool()const { return tool_; } int Musician::getRating()const { return rating_; } void Musician::setTool(const Tools tool) { tool_ = tool; } void Musician::setRating(const int rating) { rating_ = rating; } void Musician::serialize()const { const string path = name_ + surname_ + ".txt"; ofstream fout(path); if (fout.is_open()) { fout << " : " << name_ << endl; fout << " : " << surname_ << endl; fout << " : " << year_ << endl; fout << " : " << gender_ << endl; fout << " : " << experience_ << endl; fout << " : " << rating_ << endl; switch (tool_) { case 1: fout << " : " << endl; break; case 2: fout << " : " << endl; break; case 3: fout << " : " << endl; break; case 4: fout << " : " << endl; break; } } fout.close(); } void Musician::Imitation() { for (int i = 0; i < 3; i++) { cout << " " << i + 1 << " " << name_ << endl; rating_ += rand() % 5 + 1; cout << " " << name_ << " " << surname_ << " : " << rating_ << endl << endl; } cout << "----------------------------------------------------------------------------" << endl; } void Musician::visit() { experience_++; rating_ += rand() % 5 + 1; cout << " " << name_ << " " << surname_ << " : " << rating_ << endl << endl; } void Musician::Print() { cout << " : " << name_ << endl; cout << " : " << surname_ << endl; cout << " : " << year_ << endl; cout << " : " << gender_ << endl; cout << " : " << experience_ << endl; cout << " : " << rating_ << endl; cout << " : " << tool_ << endl<<endl; }
true
706222bf166645429fdba7735de4a2df5b0a5825
C++
cl-kn/cpp_study
/b_dokushu_cpp/ch05/list_5.18/main.cpp
UTF-8
723
4.09375
4
[]
no_license
//*************************************************** /** 21/4/6 * P279 「メンバー変数を参照で返す」 */ //*************************************************** #include <iostream> #include <string> class Object { std::string name; public: Object(std::string name); const std::string &get_name() const; }; Object::Object(std::string name) : name{name} { //文字列をメンバ変数 name にコピー } const std::string &Object::get_name() const { return name; //nameを参照で返す } int main(void) { Object obj{"Big Object !!!!"}; //メンバ変数への参照を取得 const std::string &name = obj.get_name(); std::cout << name << std::endl; return 0; }
true
6fe35b1fe14d3cd25f82f0c8883ee4a8cb36e485
C++
nitind10/levelUp
/7_DP/04_targetSet.cpp
UTF-8
13,728
3.234375
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; void print1D(vector<int>& arr) { for (int ele : arr) { cout << ele << " "; } cout << endl; } void print2D(vector<vector<int>>& arr) { for (vector<int>& ar : arr) { print1D(ar); } } //infinite coin int coinChangePermutation_memo(vector<int>&arr, int tar, vector<int>& dp) { if (tar == 0) { return dp[tar] = 1; } if (dp[tar] != -1) return dp[tar]; int count = 0; for (int ele : arr) { if (tar - ele >= 0) { count += coinChangePermutation_memo(arr, tar - ele, dp); } } return dp[tar] = count; } int coinChangePermutation_tab(vector<int>&arr, int Tar, vector<int>& dp) { dp[0] = 1; for (int tar = 0; tar <= Tar; tar++) { for (int ele : arr) { if (tar - ele >= 0) { dp[tar] += dp[tar - ele]; } } } return dp[Tar]; } int coinChangeCombination_memo(vector<int>&arr, int tar, int li, vector<vector<int>>& dp) { if (tar == 0) { return dp[li][tar] = 1; } int count = 0; for (int i = li; i >= 0; i--) if (tar - arr[i] >= 0) { count += coinChangeCombination_memo(arr, tar - arr[i], i, dp); } return dp[li][tar] = count; } int coinChangeCombination_2D_tab(vector<int>&arr, int Tar, int LI, vector<vector<int>>& dp) { for (int li = 0; li <= LI; li++) { for (int tar = 0; tar <= Tar; tar++) { if (tar == 0) { dp[li][tar] = 1; continue; } for (int i = li; i >= 0; i--) if (tar - arr[i] >= 0) { dp[li][tar] += dp[i][tar - arr[i]]; } } } return dp[LI][Tar]; } int coinChangeCombination_1D_tab(vector<int>&arr, int Tar, vector<int>& dp) { dp[0] = 1; for (int ele : arr) { for (int tar = ele; tar <= Tar; tar++) { if (tar - ele >= 0) { dp[tar] += dp[tar - ele]; } } } return dp[Tar]; } void coinChange() { vector<int> arr = { 2, 3, 5, 7 }; int tar = 10; vector<vector<int>> dp(arr.size(), vector<int>(tar + 1)); cout << coinChangeCombination_2D_tab(arr, tar, arr.size() - 1, dp) << endl; print2D(dp); } //518 ========================================================================================= int change(int amount, vector<int>& coins) { vector<int> dp(amount+1, 0); dp[0] = 1; for(int i = 0; i < coins.size(); ++i){ for(int j = coins[i]; j <= amount; ++j){ dp[j] += dp[j - coins[i]]; } } return dp[amount]; } //322 ================================================================================== int coinChangeHelper(vector<int>& coins, int tar, vector<int>& dp){ if(tar == 0) return 0; if(dp[tar] != -1) return dp[tar]; int myAns = 1e9; for(int coin : coins){ if(tar - coin >= 0) myAns = min(myAns, coinChangeHelper(coins, tar-coin, dp)); } return dp[tar] = myAns + 1; } int coinChange(vector<int>& coins, int amount) { vector<int> dp(amount+1,-1); int ans = coinChangeHelper(coins, amount, dp); return ans == 1e9 + 1 ? -1 : ans; } //377 ============================================================================================= int combinationSum4(vector<int>& nums, int target) { vector<unsigned int> dp(target+1, 0); dp[0] = 1; for(int i = 1; i <= target; ++i){ for(int j = 0; j < nums.size(); ++j){ if(i - nums[j] > -1) dp[i] += dp[i - nums[j]]; } } return dp[target]; } // https://www.geeksforgeeks.org/find-number-of-solutions-of-a-linear-equation-of-n-variables/ =========================================== int numberOfSolution(vector<int>& arr, int Tar) { vector<int> dp(Tar + 1, 0); for (int tar = 0; tar <= Tar; tar++) { for (int ele : arr) { if (tar - ele >= 0) dp[tar] += dp[tar - ele]; } } return dp[Tar]; } int numberOfSolution_print(vector<int>& arr, int Tar, int aTar, int idx, vector<int>& coff) { if (Tar == 0) { for (int i = 0; i < arr.size(); i++) { cout << arr[i] << "(" << coff[i] << ")"; if (i != arr.size() - 1) cout << " + "; } cout << " = " << aTar << endl; return 1; } int count = 0; for (int i = idx; i < arr.size(); i++) { if (Tar - arr[i] >= 0) { coff[i]++; count += numberOfSolution_print(arr, Tar - arr[i], aTar, i, coff); coff[i]--; } } return count; } void numberOfSolution() { vector<int> arr = { 2, 3, 5, 7 }; int tar = 10; vector<int> coff(arr.size(), 0); cout << numberOfSolution_print(arr, tar, tar, 0, coff) << endl; } //https://www.geeksforgeeks.org/subset-sum-problem-dp-25/ ============================================== // {2,3,5,7} target = 10, return true or false int isTargetPossible_memo(vector<int>& arr, int tar, int idx, vector<vector<int>>& dp){ if(idx == arr.size() || tar == 0){ return dp[idx][tar] = (tar == 0) ? 1 : 0; } if(dp[idx][tar] != -1) return dp[idx][tar]; bool res = false; if(tar - arr[idx] >= 0) res = res || (isTargetPossible_memo(arr, tar-arr[idx], idx+1, dp) == 1); res = res || isTargetPossible_memo(arr, tar, idx+1, dp); return dp[idx][tar] = res ? 1 : 0; } //passing n as idx initially int isTargetPossible_memo_02(vector<int>& arr, int tar, int n, vector<vector<int>>& dp){ if(n == 0 || tar == 0){ return dp[n][tar] = (tar == 0) ? 1 : 0; } if(dp[n][tar] != -1) return dp[n][tar]; bool res = false; if(tar - arr[n-1] >= 0) res = res || (isTargetPossible_memo_02(arr, tar-arr[n-1], n-1, dp) == 1); res = res || isTargetPossible_memo_02(arr, tar, n-1, dp); return dp[n][tar] = res ? 1 : 0; } bool isTargetPossible_tab_02(vector<int>& arr, int Tar, int N, vector<vector<bool>>& dp){ for(int n = 0; n <= N; ++n){ for(int tar = 0; tar <= Tar; ++tar){ if(n == 0 || tar == 0){ dp[n][tar] = (tar == 0) ? true : false; continue; } if(tar - arr[n-1] >= 0) dp[n][tar] = dp[n-1][tar-arr[n-1]]; dp[n][tar] = dp[n][tar] || dp[n-1][tar]; } } return dp[N][Tar]; } //back engineering void printTheSubarray(int n, int tar, string asf, vector<int>& arr, vector<vector<bool>>& dp2){ if(tar == 0){ cout << asf << endl; return; } if(tar - arr[n-1] >= 0 && dp2[n-1][tar-arr[n-1]]) printTheSubarray(n-1, tar-arr[n-1], to_string(arr[n-1]) + "," + asf, arr, dp2); if(dp2[n-1][tar]) printTheSubarray(n-1, tar, asf, arr, dp2); } //counting ways of possibility int countTargetWays_tab(vector<int>& arr, int Tar, int N, vector<vector<int>>& dp){ for(int n = 0; n <= N; ++n){ for(int tar = 0; tar <= Tar; ++tar){ if(n == 0 || tar == 0){ dp[n][tar] = (tar == 0) ? 1 : 0; continue; } if(tar - arr[n-1] >= 0) dp[n][tar] += dp[n-1][tar-arr[n-1]]; dp[n][tar] += dp[n-1][tar]; } } return dp[N][Tar]; } //416 =========================================================================================================== bool isTargetPossible_tab_02(vector<int>& arr, int Tar, int N, vector<vector<bool>>& dp){ for(int n = 0; n <= N; ++n){ for(int tar = 0; tar <= Tar; ++tar){ if(n == 0 || tar == 0){ dp[n][tar] = (tar == 0) ? true : false; continue; } if(tar - arr[n-1] >= 0) dp[n][tar] = dp[n-1][tar-arr[n-1]]; dp[n][tar] = dp[n][tar] || dp[n-1][tar]; } } return dp[N][Tar]; } bool canPartition(vector<int>& nums) { int tar = 0; for(int ele : nums) tar += ele; if((tar&1) == 1) return false; tar /= 2; int n = nums.size(); vector<vector<bool>> dp(n+1, vector<bool>(tar+1, false)); return isTargetPossible_tab_02(nums, tar, n, dp); } //494 ===================================================================================== //test cases are week, therefore only recursion will also work int fnTarget(vector<int>& nums, int target, int idx){ if(idx == 0){ return (target == 0) ? 1 : 0; } int count = 0; count += fnTarget(nums, target - nums[idx-1], idx-1); //taking as positive count += fnTarget(nums, target - (-nums[idx-1]), idx-1); //taking as negative return count; } int findTargetSumWays(vector<int>& nums, int target) { int n = nums.size(); int sum = 0; for(int ele : nums) sum += ele; if(target > sum || target < -sum) return 0; return fnTarget(nums, target, n); } //memoized sol int fnTarget(vector<int>& nums, int starting, int target, int n, vector<vector<int>>& dp){ if(n == 0){ dp[n][starting] = (starting == target) ? 1 : 0; } if(dp[n][starting] != -1) return dp[n][starting]; int count = 0; count += fnTarget(nums, starting+nums[n-1], target, n-1, dp); //taking as positive count += fnTarget(nums, starting-nums[n-1], target, n-1, dp); //taking as negative return dp[n][starting] = count; } int findTargetSumWays(vector<int>& nums, int target) { int n = nums.size(); int sum = 0; for(int ele : nums) sum += ele; if(target > sum || target < -sum) return 0; vector<vector<int>> dp(n+1, vector<int>(2*sum +1, -1)); return fnTarget(nums, sum, sum+target, n, dp); } //knapsack 0/1 https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1 int knapSack01(int bagWt, int wt[], int val[], int n, vector<vector<int>>& dp){ if(bagWt == 0 || n == 0) return dp[n][bagWt] = 0; if(dp[n][bagWt] != -1) return dp[n][bagWt]; int ans = 0; if(bagWt - wt[n-1] >= 0) ans = knapSack01(bagWt-wt[n-1], wt, val, n-1, dp) + val[n-1]; ans = max(ans, knapSack01(bagWt, wt, val, n-1, dp)); return dp[n][bagWt] = ans; } int knapSack(int bagWt, int wt[], int val[], int n) { vector<vector<int>> dp(n+1, vector<int>(bagWt+1, -1)); return knapSack01(bagWt, wt, val, n, dp); } //unbounded knapsack (same as inf coin comb) https://practice.geeksforgeeks.org/problems/knapsack-with-duplicate-items4201/1 int knapSack_unbounded(int n, int BagWeight, int value[], int weight[]) { // combination vector<int> dp(BagWeight + 1, 0); for (int i = 0; i < n; i++) { for (int bagWeight = weight[i]; bagWeight <= BagWeight; bagWeight++) { dp[bagWeight] = max(dp[bagWeight], dp[bagWeight - weight[i]] + value[i]); } } return dp[BagWeight]; } //698 =========================================================================================== bool canPartitionKSubsets(vector<int>& arr, int k, int idx, int sumSF, int tar, vector<bool>& vis) { if (k == 0) return true; if (sumSF > tar) return false; if (sumSF == tar) { return canPartitionKSubsets(arr, k - 1, 0, 0, tar, vis); } bool res = false; for (int i = idx; i < arr.size(); i++) { if (vis[i]) continue; vis[i] = true; res = res || canPartitionKSubsets(arr, k, i + 1, sumSF + arr[i], tar, vis); vis[i] = false; } return res; } bool canPartitionKSubsets(vector<int> arr, int k) { int n = arr.size(); int sum = 0; int maxEle = 0; for (int ele : arr) { sum += ele; maxEle = max(maxEle, ele); } if (sum % k != 0 || maxEle > sum / k) return false; vector<bool> vis(n, false); return canPartitionKSubsets(arr, k, 0, 0, sum / k, vis); } void targetSum(){ vector<int> arr {2,3,5,7}; int n = arr.size(); int tar = 10; //vector<vector<int>> dp(n+1, vector<int>(tar+1, -1)); // bool res = isTargetPossible_memo_02(arr, tar, n, dp) == 1; // cout << boolalpha << res << endl; //print2D(dp); vector<vector<bool>> dp2(n+1, vector<bool>(tar+1, false)); cout << boolalpha << isTargetPossible_tab_02(arr, tar, n, dp2) << endl; // for (vector<bool>& ar : dp2) { // for(bool ele : ar)cout << ele << " "; // cout<<endl; // } printTheSubarray(n, tar, "", arr, dp2); vector<vector<int>> dp3(n+1, vector<int>(tar+1, 0)); cout << countTargetWays_tab(arr, tar, n, dp3) << endl; } int main(){ //coinChange(); targetSum(); return 0; }
true
532d89981080217f65a1842599475df923cadcdf
C++
xibeilang524/QtFtpServer
/ftpsqlconnection.cpp
UTF-8
7,330
2.9375
3
[]
no_license
#include "ftpsqlconnection.h" #include <QDebug> /* * FtpSqlConnection包含所有数据库的操作 */ FtpSqlConnection::FtpSqlConnection(QString path,QString username,QString password) { database=QSqlDatabase::addDatabase("QSQLITE"); database.setDatabaseName(path); database.setUserName(username); database.setPassword(password); if(!database.open()){ qDebug()<<"Error: Failed to connect database."<<database.lastError(); }else{ qDebug()<<"Succeed to connect database."; } } FtpSqlConnection::~FtpSqlConnection(){ database.close(); } /* * 根据name判断在ftpgroup表中是否已存在 * @return bool */ bool FtpSqlConnection::hasGroupByName(QString name){ QString sql="select * from ftpgroup where name=:name;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",name); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return true; }else{ if(sqlQuery.next()){ return true; }else{ return false; } } } /* * 根据name判断在ftpuser表中是否已存在 * @return bool */ bool FtpSqlConnection::hasUserByName(QString name){ QString sql="select * from ftpuser where name=:name;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",name); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return true; }else{ if(sqlQuery.next()){ return true; }else{ return false; } } } /* * ftpuser插入数据 * @return bool */ bool FtpSqlConnection::insertUser(FtpUser user){ if(!hasUserByName(user.getName())){ QString sql="insert into ftpuser(id,name,password,ftpgroup,path,file,directory) values(null,:name,:password,:ftpgroup,:path,:file,:directory);"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",user.getName()); sqlQuery.bindValue(":password",user.getPassword()); sqlQuery.bindValue(":ftpgroup",user.getFtpGroup()); sqlQuery.bindValue(":path",user.getPath()); sqlQuery.bindValue(":file",user.getFile()); sqlQuery.bindValue(":directory",user.getDirectory()); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return false; }else{ return true; } } return false; } /* * ftpgroup插入数据 * @return bool */ bool FtpSqlConnection::insertGroup(FtpGroup group){ if(!hasGroupByName(group.getName())){ QString sql="insert into ftpgroup(id,name,count,path,file,directory) values(null,:name,:count,:path,:file,:directory);"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",group.getName()); sqlQuery.bindValue(":count",group.getCount()); sqlQuery.bindValue(":path",group.getPath()); sqlQuery.bindValue(":file",group.getFile()); sqlQuery.bindValue(":directory",group.getDirectory()); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return false; }else{ return true; } } return false; } /* * 根据id从ftpuser删除数据 * @return bool */ bool FtpSqlConnection::deleteUserById(int id){ QString sql="delete from ftpuser where id=:id;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":id",id); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return false; }else{ return true; } } /* * 根据name从ftpuser查询数据 * @return FtpUser */ FtpUser FtpSqlConnection::queryUserByName(QString name){ QString sql="select * from ftpuser where name=:name;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",name); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return FtpUser(); }else{ if(sqlQuery.next()){ return FtpUser(sqlQuery.value(0).toInt(),sqlQuery.value(1).toString(),sqlQuery.value(2).toString(),sqlQuery.value(3).toInt(),sqlQuery.value(4).toString(),sqlQuery.value(5).toString(),sqlQuery.value(6).toString()); }else{ return FtpUser(); } } } /* * 根据id从ftpgroup查询数据 * @return FtpGroup */ FtpGroup FtpSqlConnection::queryGroupById(int id){ QString sql="select * from ftpgroup where id=:id;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":id",id); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return FtpGroup(); }else{ if(sqlQuery.next()){ return FtpGroup(sqlQuery.value(0).toInt(),sqlQuery.value(1).toString(),sqlQuery.value(2).toInt(),sqlQuery.value(3).toString(),sqlQuery.value(4).toString(),sqlQuery.value(5).toString()); }else{ qDebug()<<"id"<<id; return FtpGroup(); } } } /* * 根据id从ftpgroup查询name * @return QString */ QString FtpSqlConnection::queryGroupNameById(int id){ QString sql="select name from ftpgroup where id=:id;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":id",id); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return ""; }else{ if(sqlQuery.next()){ return sqlQuery.value(0).toString(); }else{ return ""; } } } /* * 根据name从ftpgroup查询id * @return int */ int FtpSqlConnection::queryGroupIdByName(QString name){ QString sql="select id from ftpgroup where name=:name;"; QSqlQuery sqlQuery; sqlQuery.prepare(sql); sqlQuery.bindValue(":name",name); if(!sqlQuery.exec()){ qDebug()<<sqlQuery.lastError(); return 0; }else{ if(sqlQuery.next()){ return sqlQuery.value(0).toInt(); }else{ return 0; } } } /* * 从ftpgroup查询全部的id,name * @return QList<QMap<QString,QStirng>> */ QList<QMap<QString,QString>> FtpSqlConnection::listGroupNames(){ QSqlQuery sqlQuery; QList<QMap<QString,QString>> list; if(!sqlQuery.exec("select id,name from ftpgroup;")){ qDebug()<<sqlQuery.lastError(); }else{ while (sqlQuery.next()) { QMap<QString,QString> map; map.insert("id",sqlQuery.value(0).toString()); map.insert("name",sqlQuery.value(1).toString()); list.append(map); } } return list; } /* * 从ftpuser查询全部的id,name * @return QList<QMap<QString,QStirng>> */ QList<QMap<QString,QString>> FtpSqlConnection::listUserNames(){ QSqlQuery sqlQuery; QList<QMap<QString,QString>> list; if(!sqlQuery.exec("select id,name from ftpuser;")){ qDebug()<<sqlQuery.lastError(); }else{ while (sqlQuery.next()) { QMap<QString,QString> map; map.insert("id",sqlQuery.value(0).toString()); map.insert("name",sqlQuery.value(1).toString()); list.append(map); } } return list; }
true
7da8b6b8bea08ec8996f859b446c02be2e6e34e8
C++
larrylebron/CMPS164
/gameEngine/gameEngine/fileReader.cpp
UTF-8
10,652
2.890625
3
[]
no_license
#include "fileReader.h" fileReader::fileReader() { } fileReader::~fileReader() { } bool fileReader::readCourseFile(char* filename, CMMPointer<Course> course) { // read files into streams ifstream mapInput(filename); if (mapInput.fail()){ std::string stringFile(filename); //string filename for passing to the logger Logger::Instance()->err("failed to open " + stringFile + " attempting to add .db extension"); mapInput.clear(); char fileExt[] = ".db"; strcat(filename, fileExt); Logger::Instance()->write("Attempting to open level file with appended name: " + stringFile + ".db"); mapInput.open(filename, ifstream::in); // throws error if reading failed if (mapInput.fail()) { Logger::Instance()->err("Error: File not Found: " + stringFile); return false; } } string line; int lineNumber = 1; int numLevelsToParse = 0; int beginCount = 0; int endCount = 0; bool beganTile = false; CMMPointer<level> newLevel; while (getline(mapInput, line)) { vector<string> tokens = strSplit(line); // first token to the dataType string type = tokens[0]; //A string stream of the line number for the logger std::stringstream sLineNumber; sLineNumber << lineNumber; // loads course name and number of levels if (tokens[0].compare("course") == 0) { vector<string> names = strSplit(line, "\""); if (tokens.size() < 3) { Logger::Instance()->err("Error: Invalid course tokens, line " + sLineNumber.str() ); return false; } else if (names.size() < 2) { Logger::Instance()->err("Error: Invalid course name, line " + sLineNumber.str() ); return false; } else { numLevelsToParse = atoi(tokens.back().c_str()); course->setNumLevels(numLevelsToParse); course->setCourseName(names[1]); } // does check for begin holes and end holes } else if (tokens[0].compare("begin_hole") == 0) { if (beganTile) { Logger::Instance()->err("Error: trying to begin_hole when another begin_hole has started, line " + sLineNumber.str()); return false; } else { beginCount++; newLevel = new level(); beganTile = true; } } else if (tokens[0].compare("end_hole") == 0) { if (!beganTile) { Logger::Instance()->err("Error: trying to end_hole before a valid begin_hole, line " + sLineNumber.str()); return false; } else { endCount++; beganTile = false; if (!newLevel->checkLevel()) { return false; } else { course->addLevel(beginCount, newLevel); } } // parsing of level name } else if (tokens[0].compare("name") == 0) { vector<string> names = strSplit(line, "\""); if (names.size() < 2) { Logger::Instance()->err("Error: Invalid level name, line " + sLineNumber.str() ); return false; } else { newLevel->setLevelName(names[1]); } } else if (tokens[0].compare("par") == 0) { if (tokens.size() < 2) { Logger::Instance()->err("Error: Invalid par entry, line " + sLineNumber.str() ); return false; } else { newLevel->setPar(atoi(tokens[1].c_str())); } // parsing of actual tile, tee, cups } else { if (tokens.size() < 5) { Logger::Instance()->err("Error: Invalid data in data file, line " + sLineNumber.str() ); return false; } else if (tokens[0].compare(DataTypeTile) == 0) { int id = atoi(tokens[1].c_str()); int numVertices = atoi(tokens[2].c_str()); // if total number of tokens dont add up, throw an error //type, id, numVertices + 3 verts and 1 neighbor per vertex if (tokens.size() != 3 + 4 * numVertices) { Logger::Instance()->err("Error: Invalid data in data file, line " + sLineNumber.str() ); return false; } vector<Vec3f> verticesTemp; vector<int> neighborsTemp; int index = 3; int neighborIndex = tokens.size() - numVertices; for (int i = 0; i < numVertices; i++) { // load the vertices Vec3f vert = Vec3f (atof(tokens[index].c_str()), atof(tokens[index + 1].c_str()), atof(tokens[index + 2].c_str())); // add the vertices and the neighbor indices verticesTemp.push_back(vert); neighborsTemp.push_back( atoi(tokens[neighborIndex].c_str()) ); index += 3; neighborIndex ++; } CMMPointer<tile>* tempTile = new CMMPointer<tile>(new tile(id, verticesTemp, neighborsTemp, TILE_COLOR)); newLevel->addTile(id, tempTile); delete tempTile; } else if (tokens[0].compare(DataTypeCup) == 0) { int id = atoi(tokens[1].c_str()); Vec3f position(atof(tokens[2].c_str()), atof(tokens[3].c_str()), atof(tokens[4].c_str())); CMMPointer<cup>* tempCup = new CMMPointer<cup>(new cup(id, position)); newLevel->addCup(id, tempCup); tempCup = 0; delete tempCup; } else if (tokens[0].compare(DataTypeTee) == 0) { int id = atoi(tokens[1].c_str()); Vec3f position = Vec3f(atof(tokens[2].c_str()), atof(tokens[3].c_str()), atof(tokens[4].c_str())); CMMPointer<tee>* tempTee = new CMMPointer<tee>(new tee(id, position)); newLevel->addTee(id, tempTee); //add a ball in the location of the tee CMMPointer<ball>* tempBall = new CMMPointer<ball>(new ball(0, position, BALL_COLOR, BALL_RADIUS)); newLevel->addBall(0, tempBall); tempTee = 0; tempBall = 0; delete tempTee; delete tempBall; } else { Logger::Instance()->err("Error: Unknown Type in data file, line " + sLineNumber.str() ); return false; } } lineNumber++; } mapInput.close(); course->setNumLevels(numLevelsToParse); if (beginCount != endCount || course->getNumLevels() != endCount) { std::stringstream errorLog; errorLog << "Error: Invalid number of levels parse. Expected: " << numLevelsToParse << " being_hole count: " << beginCount << " end_hole count: " << endCount; Logger::Instance()->err(errorLog.str()); return false; } return true; } bool fileReader::readFile(char* filename, CMMPointer<level> map) { // read files into streams ifstream mapInput(filename); if (mapInput.fail()){ std::string stringFile(filename); //string filename for passing to the logger Logger::Instance()->err("failed to open " + stringFile + " attempting to add .db extension"); mapInput.clear(); char fileExt[] = ".db"; strcat(filename, fileExt); Logger::Instance()->write("Attempting to open level file with appended name: " + stringFile + ".db"); mapInput.open(filename, ifstream::in); // throws error if reading failed if (mapInput.fail()) { Logger::Instance()->err("Error: File not Found: " + stringFile); return false; } } string line; int lineNumber = 1; getline(mapInput, line); while (line.length() > 0) { vector<string> tokens = strSplit(line); // first token to the dataType string type = tokens[0]; //A string stream of the line number for the logger std::stringstream sLineNumber; sLineNumber << lineNumber; if (tokens.size() < 5) { Logger::Instance()->err("Error: Invalid data in data file, line " + sLineNumber.str() ); return false; } else if (tokens[0].compare(DataTypeTile) == 0) { int id = atoi(tokens[1].c_str()); int numVertices = atoi(tokens[2].c_str()); // if total number of tokens dont add up, throw an error //type, id, numVertices + 3 verts and 1 neighbor per vertex if (tokens.size() != 3 + 4 * numVertices) { Logger::Instance()->err("Error: Invalid data in data file, line " + sLineNumber.str() ); return false; } vector<Vec3f> verticesTemp; vector<int> neighborsTemp; int index = 3; int neighborIndex = tokens.size() - numVertices; for (int i = 0; i < numVertices; i++) { // load the vertices Vec3f vert = Vec3f (atof(tokens[index].c_str()), atof(tokens[index + 1].c_str()), atof(tokens[index + 2].c_str())); // add the vertices and the neighbor indices verticesTemp.push_back(vert); neighborsTemp.push_back( atoi(tokens[neighborIndex].c_str()) ); index += 3; neighborIndex ++; } CMMPointer<tile>* tempTile = new CMMPointer<tile>(new tile(id, verticesTemp, neighborsTemp, TILE_COLOR)); map->addTile(id, tempTile); delete tempTile; } else if (tokens[0].compare(DataTypeCup) == 0) { int id = atoi(tokens[1].c_str()); Vec3f position(atof(tokens[2].c_str()), atof(tokens[3].c_str()), atof(tokens[4].c_str())); CMMPointer<cup>* tempCup = new CMMPointer<cup>(new cup(id, position)); map->addCup(id, tempCup); tempCup = 0; delete tempCup; } else if (tokens[0].compare(DataTypeTee) == 0) { int id = atoi(tokens[1].c_str()); Vec3f position = Vec3f(atof(tokens[2].c_str()), atof(tokens[3].c_str()), atof(tokens[4].c_str())); CMMPointer<tee>* tempTee = new CMMPointer<tee>(new tee(id, position)); map->addTee(id, tempTee); //add a ball in the location of the tee CMMPointer<ball>* tempBall = new CMMPointer<ball>(new ball(id, position, BALL_COLOR, BALL_RADIUS)); map->addBall(id, tempBall); tempTee = 0; tempBall = 0; delete tempTee; delete tempBall; } else { Logger::Instance()->err("Error: Unknown Type in data file, line " + sLineNumber.str() ); return false; } lineNumber++; getline(mapInput, line); } mapInput.close(); if (!map->checkLevel()) { return false; } return true; } vector<string> fileReader::strSplit(string data, string delims) { // loops through character by character and delimits when the delimiter is found vector<string> toks; size_t start = 0, end = 0; for (size_t i = 0; i < data.length(); i++) { // if you dont find the delimiting character, increment the end char ptr if (delims.find(data[i]) == string::npos) { ++end; // if a delimiting character is found // if it is valid, ie the end ptr is more than the start ptr, add the entry into the vector } else if (end > start) { string token = data.substr(start, end - start); // only save the token if its non "" toks.push_back(token); // move the end ptr and reset the start ptr ++end; start = end; // if a delimiter is found but no additional token is found, increment both ptrs } else { ++start; ++end; } } //grab the last token (if any) if (end > start) { toks.push_back(data.substr(start, end - start)); } return toks; }
true
0bf17b9d4b7c39303d6a8e7ab0fd3320ff01ab6d
C++
PositronicsLab/Moby
/include/Moby/GaussianMixture.h
UTF-8
3,082
2.53125
3
[]
no_license
#ifndef _GAUSSMIX_H_ #define _GAUSSMIX_H_ #include <Moby/Primitive.h> namespace Moby { class GaussianMixture : public Primitive { public: struct Gauss { double A; // height of the Gaussian double sigma_x; // variance in x direction double sigma_y; // variance in y direction double x0; // x coordinate of Gaussian center double y0; // y coordinate of Gaussian center double th; // planar rotation of the Gaussian }; void rebuild(const std::vector<Gauss>& gauss); virtual void load_from_xml(boost::shared_ptr<const XMLTree> node, std::map<std::string, BasePtr>& id_map); virtual void save_to_xml(XMLTreePtr node, std::list<boost::shared_ptr<const Base> >& shared_objects) const; virtual void set_pose(const Ravelin::Pose3d& T); virtual BVPtr get_BVH_root(CollisionGeometryPtr geom); virtual bool point_inside(BVPtr bv, const Point3d& p, Ravelin::Vector3d& normal) const; virtual void get_vertices(boost::shared_ptr<const Ravelin::Pose3d> P, std::vector<Point3d>& vertices); virtual bool intersect_seg(BVPtr bv, const LineSeg3& seg, double& t, Point3d& isect, Ravelin::Vector3d& normal) const; virtual boost::shared_ptr<const IndexedTriArray> get_mesh(boost::shared_ptr<const Ravelin::Pose3d> P) { return _mesh; } virtual osg::Node* create_visualization(); virtual double calc_dist_and_normal(const Point3d& p, Ravelin::Vector3d& normal) const; virtual double calc_signed_dist(boost::shared_ptr<const Primitive> p, boost::shared_ptr<const Ravelin::Pose3d> pose_this, boost::shared_ptr<const Ravelin::Pose3d> pose_p, Point3d& pthis, Point3d& pb) const; private: static Ravelin::Vector3d grad(const Gauss& g, double x, double y); static double f(const Gauss& g, const Point3d& p, const Point3d& q, double t); static double df(const Gauss& g, const Point3d& p, const Point3d& q, double t); static double newton_raphson(const Gauss& g, const Point3d& p, const Point3d& q); static Gauss read_gauss_node(boost::shared_ptr<const XMLTree> node); static double gauss(const Gauss& g, double x, double y); void construct_vertices(); void construct_BVs(CollisionGeometryPtr geom); void create_mesh(); /// Note: there are no mass properties, because this can have no mass! virtual void calc_mass_properties() { } /// Mesh pointer boost::shared_ptr<IndexedTriArray> _mesh; /// Submesh pair std::pair<boost::shared_ptr<const IndexedTriArray>, std::list<unsigned> > _mesh_pair; /// The collision geometry this mixture is associated with CollisionGeometryPtr _geom; /// The bounding volumes (OBB) OBBPtr _root; /// The set of Gaussians std::vector<Gauss> _gauss; /// The mapping from bounding volumes to Gaussians std::map<OBBPtr, unsigned> _obbs; /// Set of vertices sampled at regular intervals std::vector<std::vector<Point3d> > _vertices; }; // end class } // end namespace Moby #endif // _GAUSSMIX_H
true
31b87443330f59683e58070af5c2c761ce71ac27
C++
respu/allium
/test/write_metadata_test.cpp
UTF-8
2,802
2.53125
3
[]
no_license
#define BOOST_TEST_DYN_LINK #include <canard/network/protocol/openflow/v13/instruction/write_metadata.hpp> #include <boost/test/unit_test.hpp> #include <cstdint> #include <utility> #include <vector> namespace canard { namespace network { namespace openflow { namespace v13 { BOOST_AUTO_TEST_SUITE(write_metadata_test) BOOST_AUTO_TEST_SUITE(instantiation_test) BOOST_AUTO_TEST_CASE(constructor_test) { auto const metadata = std::numeric_limits<std::uint64_t>::max(); auto const sut = instructions::write_metadata{metadata}; BOOST_CHECK_EQUAL(sut.type(), OFPIT_WRITE_METADATA); BOOST_CHECK_EQUAL(sut.length(), 24); BOOST_CHECK_EQUAL(sut.metadata(), metadata); BOOST_CHECK_EQUAL(sut.metadata_mask(), std::numeric_limits<std::uint64_t>::max()); } BOOST_AUTO_TEST_CASE(constructor_test_when_has_mask) { auto const metadata = std::numeric_limits<std::uint64_t>::max() - 1; auto const metadata_mask = 1; auto const sut = instructions::write_metadata{metadata, metadata_mask}; BOOST_CHECK_EQUAL(sut.type(), OFPIT_WRITE_METADATA); BOOST_CHECK_EQUAL(sut.length(), 24); BOOST_CHECK_EQUAL(sut.metadata(), metadata); BOOST_CHECK_EQUAL(sut.metadata_mask(), metadata_mask); } BOOST_AUTO_TEST_CASE(copy_constructor_test) { auto sut = instructions::write_metadata{1, 0x00FF00FF00FF00FF}; auto const copy = sut; BOOST_CHECK_EQUAL(copy.type(), sut.type()); BOOST_CHECK_EQUAL(copy.length(), sut.length()); BOOST_CHECK_EQUAL(copy.metadata(), sut.metadata()); BOOST_CHECK_EQUAL(copy.metadata_mask(), sut.metadata_mask()); } BOOST_AUTO_TEST_CASE(move_constructor_test) { auto sut = instructions::write_metadata{0, 0x11FF00FF11FF00FF}; auto const copy = std::move(sut); BOOST_CHECK_EQUAL(copy.type(), sut.type()); BOOST_CHECK_EQUAL(copy.length(), sut.length()); BOOST_CHECK_EQUAL(copy.metadata(), sut.metadata()); BOOST_CHECK_EQUAL(copy.metadata_mask(), sut.metadata_mask()); } BOOST_AUTO_TEST_SUITE_END() // instantiation_test BOOST_AUTO_TEST_CASE(encode_decode_test) { auto buffer = std::vector<std::uint8_t>{}; auto const sut = instructions::write_metadata{1234, 5678}; sut.encode(buffer); BOOST_CHECK_EQUAL(buffer.size(), sut.length()); auto it = buffer.begin(); auto const decoded_instruction = instructions::write_metadata::decode(it, buffer.end()); BOOST_CHECK_EQUAL(decoded_instruction.type(), sut.type()); BOOST_CHECK_EQUAL(decoded_instruction.length(), sut.length()); BOOST_CHECK_EQUAL(decoded_instruction.metadata(), sut.metadata()); BOOST_CHECK_EQUAL(decoded_instruction.metadata_mask(), sut.metadata_mask()); } BOOST_AUTO_TEST_SUITE_END() // write_metadata_test } // namespace v13 } // namespace openflow } // namespace network } // namespace canard
true
66a575c48fadb7c74f20fdc6070006df21292109
C++
cozyBoi/BOJ-algorithm-practice
/10971.cpp
UTF-8
1,076
2.984375
3
[]
no_license
#include <iostream> #include <algorithm> #include <functional> #include <vector> const int VERY_BIG = 100000001; int main(){ std::ios_base::sync_with_stdio(false); std::vector<std::vector<int> > dist; int n; std::cin >> n; dist.resize(n); for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ int now; std::cin >> now; if(now == 0) now = VERY_BIG; dist[i].push_back(now); } } //input std::vector<int> pmt; //permutaion for(int i = 0; i < n; i++) pmt.push_back(i); int grobal_min = VERY_BIG; do{ int local_min = 0, first = pmt[0]; int prev = first; for(auto&curr : pmt){ if(first == curr) continue; local_min += dist[prev][curr]; prev = curr; } local_min += dist[pmt[pmt.size()-1]][first]; // last -> first if(local_min < grobal_min) grobal_min = local_min; }while(std::next_permutation(pmt.begin(), pmt.end())); std::cout << grobal_min; return 0; }
true
eecd0b16eb75f16312945e0232caafe214b62180
C++
vvvictorlee/eossmartcontractssafeframeworks
/contractscxx/mocks/ERC721BasicTokenMock.hpp
UTF-8
419
2.703125
3
[]
no_license
#include "../token/ERC721/ERC721BasicToken.hpp" /** * @title ERC721BasicTokenMock * This mock just provides a public mint and burn functions for testing purposes */ class ERC721BasicTokenMock :public ERC721BasicToken { public: void mint(account_name _to, uint256_t _tokenId) { super._mint(_to, _tokenId); } void burn(uint256_t _tokenId) public { super._burn(ownerOf(_tokenId), _tokenId); } }
true
0bbfbcccc895cd0ba6bae9222de3d95c33dd2cfe
C++
justaneee/WebServer
/WebServer/QuickFile/QuickFile.cpp
UTF-8
564
2.78125
3
[]
no_license
#include "QuickFile.h" std::string QuickFile::readFile(std::string filename) { std::string fileContent, fileLine; std::ifstream fileStream(filename); if (fileStream.is_open()) { while (std::getline(fileStream, fileLine, '\n')) fileContent += fileLine + "\n"; fileStream.close(); } return fileContent; } void QuickFile::writeFile(std::string filename, std::string content) { std::ofstream fileStream(filename); if (fileStream.is_open()) { fileStream << content; fileStream.close(); } }
true
fb5b364f6dd6714ca11b6b63f07848cba875cae2
C++
Babtsov/Symbolic-Calculator
/COP3503_Project/Addition.cpp
UTF-8
7,565
3.234375
3
[]
no_license
// // Addition.cpp // COP3503_Project // // Created by Ben on 7/21/15. // Copyright © 2015 Ben. All rights reserved. // #include "Addition.hpp" #include "Integer.hpp" #include <algorithm> using namespace std; bool Addition::sortTerms(Expression *lhs, Expression *rhs){ return !lhs->isNegative(); } Addition::Addition(Expression* ls,Expression* rs) { leftSide = ls; rightSide = rs; } double Addition::getDecimalRepresentation() { return leftSide->getDecimalRepresentation() + rightSide->getDecimalRepresentation(); } std::vector<Expression*> Addition::getNumeratorFactors(bool breakIntoPrimes) { vector<Expression*> factors; factors.push_back(this->duplicate()); return factors; } std::vector<Expression*> Addition::getDenominatorFactors(bool breakIntoPrimes) { vector<Expression*> factors; factors.push_back(new Integer(1)); return factors; } Expression* Addition::simplify() { vector<Expression*> simplifiedTerms; for (auto term : this->getAdditiveTerms()) { simplifiedTerms.push_back(term->simplify()); delete term; } bool combOccured; //a flag to test if a combination occured. if no combination occured at all, we are done adding do { combOccured = false; for (int i = 0; i < simplifiedTerms.size() - 1; i++) { if (simplifiedTerms[i] == nullptr) continue; for (int j = i + 1; j < simplifiedTerms.size(); j++) { if (simplifiedTerms[j] == nullptr || simplifiedTerms[i] == nullptr) continue; Expression* sum = simplifiedTerms[i]->addExpression(simplifiedTerms[j]); Addition* sumAsAddition = dynamic_cast<Addition*>(sum); if (sum != nullptr) { delete simplifiedTerms[i]; delete simplifiedTerms[j]; simplifiedTerms[i] = nullptr; simplifiedTerms[j] = nullptr; combOccured = true; } if (sum != nullptr && sumAsAddition == nullptr) simplifiedTerms.push_back(sum); else if(sum != nullptr && sumAsAddition != nullptr) { simplifiedTerms.push_back(sumAsAddition->getLeftSide()->duplicate()); simplifiedTerms.push_back(sumAsAddition->getRightSide()->duplicate()); delete sumAsAddition; } } } } while(combOccured); // clean up the array of simplified terms from null pointers stack<Expression*> itemsToReturn; for (Expression* exp : simplifiedTerms) { if (exp == nullptr) { continue; } itemsToReturn.push(exp); } // build the new simplified addition tree while (itemsToReturn.size() > 1) { Expression* item1 = itemsToReturn.top(); itemsToReturn.pop(); Expression* item2 = itemsToReturn.top(); itemsToReturn.pop(); itemsToReturn.push(new Addition(item1, item2)); } assert(itemsToReturn.size() == 1); return itemsToReturn.top(); } std::vector<Expression*> Addition::getAdditiveTerms() { vector<Expression*> additiveTerms; for (auto expression : leftSide->getAdditiveTerms()) { additiveTerms.push_back(expression); } for (auto expression : rightSide->getAdditiveTerms()) { additiveTerms.push_back(expression); } return additiveTerms; } std::string Addition::toString(){ stringstream str; auto terms = getAdditiveTerms(); std::sort(begin(terms), end(terms), sortTerms); assert(terms.size() > 1); //make sure we have at least 2 terms to print str << terms[0]->toString(); for (int i = 1; i < terms.size(); i++) { if (terms[i]->isNegative()) str << terms[i]->toString(); // negative representation is taken care of by the term else str << "+" <<terms[i]->toString(); } for (auto term : terms) { delete term; } return str.str(); } Expression* Addition::getLeftSide() { return leftSide; } Expression* Addition::getRightSide() { return rightSide; } Expression* Addition::addExpression(Expression* e){ vector<Expression*> combinedTerms; auto thisTerms = getAdditiveTerms(); for (auto term : thisTerms) { combinedTerms.push_back(term->simplify()); delete term; } auto thatTerms = e->getAdditiveTerms(); for (auto term : thatTerms) { combinedTerms.push_back(term->simplify()); delete term; } for (int i = 0; i < combinedTerms.size() - 1; i++) { if (combinedTerms[i] == nullptr) continue; for (int j = i + 1; j < combinedTerms.size(); j++) { if (combinedTerms[j] == nullptr) continue; Expression* sum = combinedTerms[i]->addExpression(combinedTerms[j]); if (sum != nullptr) { delete combinedTerms[i]; delete combinedTerms[j]; combinedTerms[i] = sum; combinedTerms[j] = nullptr; } } } // clean up the array of simplified terms from null pointers stack<Expression*> itemsToReturn; for (Expression* exp : combinedTerms) { if (exp == nullptr) { continue; } itemsToReturn.push(exp); } // build the new simplified addition tree while (itemsToReturn.size() > 1) { Expression* item1 = itemsToReturn.top(); itemsToReturn.pop(); Expression* item2 = itemsToReturn.top(); itemsToReturn.pop(); itemsToReturn.push(new Addition(item2, item1)); } return itemsToReturn.top(); } Expression* Addition::multiplyExpression(Expression* e) { return nullptr; } Expression* Addition::duplicate() { return new Addition(leftSide->duplicate(),rightSide->duplicate()); } void Addition::negate(){ leftSide->negate(); rightSide->negate(); } bool Addition::isNegative() { bool valueToReturn = true; vector<Expression*> AdditiveTerms = getAdditiveTerms(); for (auto term : AdditiveTerms) { if (!term->isNegative()) { valueToReturn = false; delete term; break; } delete term; } return valueToReturn; } bool Addition::isEqual(Expression* e) { bool valueToReturn = true; Addition* thatAddition = dynamic_cast<Addition*>(e); if (thatAddition == nullptr) return false; auto thisAdditiveTerms = this->getAdditiveTerms(); auto thatAdditiveTerms = thatAddition->getAdditiveTerms(); for (auto thisTerm : thisAdditiveTerms) { bool termFound = false; for (auto& thatTerm : thatAdditiveTerms) { if (thatTerm == nullptr) continue; if (thisTerm->isEqual(thatTerm)) { termFound = true; delete thatTerm; thatTerm = nullptr; break; } } if (!termFound){ valueToReturn = false; break; } } if (thisAdditiveTerms.size() != thatAdditiveTerms.size()) valueToReturn = false; //cleanup for (auto term : thisAdditiveTerms) { delete term; } for (auto term : thatAdditiveTerms) { if (term != nullptr) delete term; } return valueToReturn; } bool Addition::isCombinedExpression() { return true; } Addition::~Addition(){ delete leftSide; delete rightSide; }
true
457e43b813d67f4801182e2af52a7494f063a6fb
C++
EDAII/Lista3_BrunoNunes_GuilhermeDourado
/inc/cliente.hpp
UTF-8
712
2.5625
3
[]
no_license
#ifndef CLIENTE_HPP #define CLIENTE_HPP #include <string> #include <vector> #include <fstream> #include "produto.hpp" using namespace std; class Cliente{ private: string nomeCliente; string cpf; char socio; public: vector<Produto *> lista_produtos; vector<Categoria *> recomendacoes; Cliente(); Cliente(string nomeCliente,string cpf,char socio); Cliente(string nomeCliente,string cpf,char socio,vector<Produto *> lista_produtos); ~Cliente(); string get_nomeCliente(); void set_nomeCliente(string nomeCliente); string get_cpf(); void set_cpf(string cpf); char get_socio(); void set_socio(char socio); void salvar_cliente(); }; #endif
true
63ec05850175d2aa21a95489d22230f4c65b1c0d
C++
sinairv/Cpp-Tutorial-Samples
/Math Library Functions/Prog.cpp
UTF-8
2,056
3.78125
4
[]
no_license
// All functions in math.h library get and return values of type double. // Note that function abs() returns an integer. In order to return a float use fabs() instead. #include <iostream> #include <iomanip> #include <cmath> //also <math.h> using namespace std; int main() { int Col1 = 13 , Col2 = 15 , Col3 = 12; cout << setw(Col1) << "Function Name" << setw(Col2) << "Usage Example" << setw(Col3) <<"Result" << " " << "Discription\n\n"; cout << setw(Col1) << "ceil()" << setw(Col2) << "ceil(-8.5)" << setw(Col3) << ceil(-8.5) << " " << "Ceiling.Integer more or equal to x." << endl; cout << setw(Col1) << "floor()" << setw(Col2) << "floor(-8.5)" << setw(Col3) << floor(-8.5) << " " << "Integer less or equal to x.\n"; cout << setw(Col1) << "abs()" << setw(Col2) << "abs(-10)" << setw(Col3) << abs(-10) << " " << "Absolute value of x.\n"; cout << setw(Col1) << "exp()" << setw(Col2) << "exp(1)" << setw(Col3) << exp(1) << " " << "Takes e to the power of x.\n"; cout << setw(Col1) << "log()" << setw(Col2) << "log(2.718282)" << setw(Col3) << log(2.718282) << " " << "Natural logarithm base e.\n"; cout << setw(Col1) << "log10()" << setw(Col2) << "log10(100)" << setw(Col3) << log10(100) << " " << "logarithm base 10.\n"; cout << setw(Col1) << "pow(x,y)" << setw(Col2) << "pow(2.0,10)" << setw(Col3) << pow(2.0,10) << " " << "Raises x to the power of y.\n"; cout << setw(Col1) << "sqrt()" << setw(Col2) << "sqrt(25)" << setw(Col3) << sqrt(25) << " " << "Square root of x.\n"; cout << setw(Col1) << "fmod(x,y)" << setw(Col2) << "fmod(2.7,1.3)" << setw(Col3) << fmod(2.7,1.3) << " " << "Remainder as a floating point number.\n"; cout << setw(Col1) << "cos()" << setw(Col2) << "cos(0)" << setw(Col3) << cos(0) << " " << "Cosine. (x in radians)\n"; cout << setw(Col1) << "sin()" << setw(Col2) << "sin(0)" << setw(Col3) << sin(0) << " " << "Sine. (x in radians)\n"; cout << setw(Col1) << "tan()" << setw(Col2) << "tan(0)" << setw(Col3) << tan(0) << " " << "Tangent. (x in radians)\n\n"; return 0; }
true
c1672e12795e986c9920a01e813dfe716db64ccf
C++
kumaran-14/cp
/cpp/Dynamic Programming/editdistance.cpp
UTF-8
1,213
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define debug(x) cout << '>' << #x << ':' << x << endl; #define all(v) v.begin(), v.end() #define pii pair<int, int> #define mxN 1e7 #define newl cout << "\n" #define vi vector<int> #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) typedef pair<int, pair<int, int>> threepair; class Solution { public: int minDistance(string s1, string s2) { int n = s1.size(); int m = s2.size(); if(n == 0 || m == 0) return max(n, m); if(s1 == s2) return 0; vector<vi> dp(n+1, vi(m+1, 1e9)); dp[0][0] = 0; rep(i, 1, n+1) dp[i][0] = i; rep(i, 1, m+1) dp[0][i] = i; rep(i, 1, n+1) { rep(j, 1, m+1) { if(s1[i-1] == s2[j-1]) { dp[i][j] = min(dp[i][j], dp[i-1][j-1]); } else { dp[i][j] = 1 + min({dp[i-1][j], dp[i][j-1], dp[i-1][j-1]}); } } } return dp[n][m]; } }; int main() { auto sol = Solution(); vector<vector<int>> arr = {{1, 2}, {1, 3}, {2, 3}}; vector<string> vec = {"leet", "code"}; int n = arr.size(); auto res = sol.minDistance("sea", "eat"); debug(res); }
true
f92f048115076921c4b274c6542d3b4ce35595d7
C++
jkennel/aquifer
/src/ogata_banks.cpp
UTF-8
3,236
2.546875
3
[]
no_license
#include "aquifer.h" // Ogata, A., Banks, R.B., 1961. A solution of the differential equation of // longitudinal dispersion in porous media. U. S. Geol. Surv. Prof. Pap. 411-A. // // 1-D // infinite source // uniform flow // constant parameters // no decay // no retardation //============================================================================== //' @title //' Ogata-Banks solution for 1-D flow. //' //' @description //' Ogata, A., Banks, R.B., 1961. A solution of the differential equation of //' longitudinal dispersion in porous media. U. S. Geol. Surv. Prof. Pap. 411-A. //' 1-D, infinite source, uniform flow, constant parameters, no decay, no retardation //' //' @param D diffusion coefficient //' @param v double velocity //' @param C0 double concentration //' @param x double x position //' @param t double time //' //' @return ogata banks solution //' //' @export //' // [[Rcpp::export]] double ogata_banks_ind(double D, double v, double C0, double x, double t) { return 0.5*C0 * (erfc((x-v*t) / (2*sqrt(D*t))) + exp(v*x/D) * erfc((x+v*t) / (2*sqrt(D*t)))); } // Ogata, A., Banks, R.B., 1961. A solution of the differential equation of // longitudinal dispersion in porous media. U. S. Geol. Surv. Prof. Pap. 411-A. // // 1-D // infinite source // uniform flow // constant parameters // no decay // no retardation //============================================================================== //' @title //' Ogata-Banks solution for 1-D flow (vectorized). //' //' @description //' Ogata, A., Banks, R.B., 1961. A solution of the differential equation of //' longitudinal dispersion in porous media. U. S. Geol. Surv. Prof. Pap. 411-A. //' 1-D, infinite source, uniform flow, constant parameters, decay, retardation //' //' To have values match the excel sheet //' https://www.civil.uwaterloo.ca/jrcraig/pdf/OgataBanks.xlsm the decay //' coefficient needs to be scaled by the retardation coefficient. //' //' @param D doublediffusion coefficient //' @param R double retardation coefficient //' @param decay double decay coefficient //' @param v double velocity //' @param C0 double concentration //' @param x vector x position //' @param t vector time //' //' @return ogata banks solution each row is an x value and each column is a time //' //' @export //' // [[Rcpp::export]] arma::mat ogata_banks(double D, double R, double decay, double v, double C0, arma::vec x, arma::rowvec t) { int n_x = x.n_elem; int n_t = t.n_elem; double B = sqrt(pow((v / (2 * D)), 2) + (decay * R / D)); double term = sqrt(pow((v / R), 2) + (4 * decay * D / R)); arma::mat output(n_x, n_t); for (int i = 0; i < n_t; i++) { output.col(i) = x; } output = 0.5 * C0 * exp(v * output / (2 * D)) % ((exp(-B * output) % arma::erfc((output.each_row() - term * t).each_row() / (2 * sqrt(D * t / R)))) + (exp(B * output) % arma::erfc((output.each_row() + term * t).each_row() / (2 * sqrt(D * t / R))))); return(output); } /*** R D <- 0.1 R <- 1 decay <- 0 v <- 0.1 C0 <- 1 x <- 1:100 t <- 1:100 ogata_banks(D = D, R = R, decay = decay, v = v, C0 = C0, x = x, t = t) */
true
e227728cc013c8c7eea59fbb2cc185b95140f198
C++
hyunho9304/Practice_Algorithm
/Practice_Algorithm/difficulty2/1979.cpp
UTF-8
1,307
2.703125
3
[]
no_license
/* 1979. 어디에 단어가 들어갈 수 있을까 https://www.swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5PuPq6AaQDFAUq&categoryId=AV5PuPq6AaQDFAUq&categoryType=CODE < input > 1 5 3 0 0 1 1 1 1 1 1 1 0 0 0 1 0 0 0 1 1 1 1 1 1 1 0 1 < output > #1 2 */ #include<iostream> #include<vector> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std ; int arr[16][16] ; int N = 0 , K = 0 ; int main() { int totalNum = 0; scanf("%d" , &totalNum ) ; int i = 0 ; while( i < totalNum ) { scanf("%d" , &N ) ; scanf("%d" , &K ) ; for( int j = 0 ; j < N ; j++ ) { for( int k = 0 ; k < N ; k++ ) scanf("%d" , &arr[j][k] ) ; } int flag = 0 , cnt = 0 ; for( int j = 0 ; j < N ; j++ ) { flag = 0 ; for( int k = 0 ; k < N ; k++ ) { if( arr[j][k] == 1 ) flag++ ; else { if( flag == K ) { cnt++ ; } flag = 0 ; } } if( flag == K ) cnt++ ; } for( int k = 0 ; k < N ; k++ ) { flag = 0 ; for( int j = 0 ; j < N ; j++ ) { if( arr[j][k] == 1 ) flag++ ; else { if( flag == K ) { cnt++ ; } flag = 0 ; } } if( flag == K ) cnt++ ; } printf("#%d %d\n" , ( i + 1 ) , cnt ) ; i++ ; } return 0 ; }
true
1828e7e36474a222478b11343ae72ee571e03b07
C++
kutiny/ApoyoCpp
/Curso/Clase6/03-inicializacion_arreglos.cpp
UTF-8
528
3.546875
4
[]
no_license
#include <iostream> using namespace std; const int SIZE = 3; int main() { int datos[SIZE][SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Tambien es posible definirlos en una sola linea ya que el compilador ignora los espacios y saltos de linea del codigo. // int datos[SIZE][SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for(int i = 0 ; i < SIZE ; i++) { for(int j = 0 ; j < SIZE ; j++) { cout << datos[i][j] << " "; } cout << endl; } return 0; }
true
6603321619b2c366987757ccd1dea2721e7c9744
C++
apache/arrow
/cpp/src/arrow/util/time.h
UTF-8
2,988
2.546875
3
[ "Apache-2.0", "MIT", "BSD-3-Clause", "BSD-2-Clause", "ZPL-2.1", "BSL-1.0", "LicenseRef-scancode-public-domain", "NTP", "OpenSSL", "CC-BY-4.0", "LLVM-exception", "Python-2.0", "CC0-1.0", "LicenseRef-scancode-protobuf", "JSON", "Zlib", "CC-BY-3.0", "LicenseRef-scancode-unknown-licens...
permissive
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 // under the License. #pragma once #include <chrono> #include <memory> #include <utility> #include "arrow/type_fwd.h" #include "arrow/util/visibility.h" namespace arrow { namespace util { enum DivideOrMultiply { MULTIPLY, DIVIDE, }; ARROW_EXPORT std::pair<DivideOrMultiply, int64_t> GetTimestampConversion(TimeUnit::type in_unit, TimeUnit::type out_unit); // Converts a Timestamp value into another Timestamp value. // // This function takes care of properly transforming from one unit to another. // // \param[in] in the input type. Must be TimestampType. // \param[in] out the output type. Must be TimestampType. // \param[in] value the input value. // // \return The converted value, or an error. ARROW_EXPORT Result<int64_t> ConvertTimestampValue(const std::shared_ptr<DataType>& in, const std::shared_ptr<DataType>& out, int64_t value); template <typename Visitor, typename... Args> decltype(std::declval<Visitor>()(std::chrono::seconds{}, std::declval<Args&&>()...)) VisitDuration(TimeUnit::type unit, Visitor&& visitor, Args&&... args) { switch (unit) { default: case TimeUnit::SECOND: break; case TimeUnit::MILLI: return visitor(std::chrono::milliseconds{}, std::forward<Args>(args)...); case TimeUnit::MICRO: return visitor(std::chrono::microseconds{}, std::forward<Args>(args)...); case TimeUnit::NANO: return visitor(std::chrono::nanoseconds{}, std::forward<Args>(args)...); } return visitor(std::chrono::seconds{}, std::forward<Args>(args)...); } /// Convert a count of seconds to the corresponding count in a different TimeUnit struct CastSecondsToUnitImpl { template <typename Duration> int64_t operator()(Duration, int64_t seconds) { auto duration = std::chrono::duration_cast<Duration>(std::chrono::seconds{seconds}); return static_cast<int64_t>(duration.count()); } }; inline int64_t CastSecondsToUnit(TimeUnit::type unit, int64_t seconds) { return VisitDuration(unit, CastSecondsToUnitImpl{}, seconds); } } // namespace util } // namespace arrow
true
9955db4a06104c76f9cb409576452306e5802790
C++
Renl1001/Template
/1_Math/2_Gauss/2_01.cpp
UTF-8
946
3.203125
3
[]
no_license
//有equ个方程,var个变元。增广矩阵行数为equ,列数为var+1,分别为0到var int a[MAXN][MAXN]; int b[MAXN][MAXN]; //返回值为-1表示无解,为0是唯一解,否则返回自由变元个数 int Gauss(int equ, int var) { int max_r, col, k; for(k = 0, col = 0 ; k < equ && col < var ; k++, col++) { max_r = k; for(int i = k + 1; i < equ; i++) { if(abs(a[i][col]) > abs(a[max_r][col])) max_r = i; } if(a[max_r][col] == 0) { k--; continue; } if(max_r != k) { for(int j = col; j < var + 1; j++) swap(a[k][j], a[max_r][j]); } for(int i = k + 1; i < equ; i++) { if(a[i][col] != 0) { for(int j = col; j < var + 1; j++) a[i][j] ^= a[k][j]; } } } return k; }
true
962772c7a233a689fb8780cb47c315c5b5a34174
C++
fengwang/operator_traits
/operator_traits.hpp
UTF-8
14,546
2.828125
3
[]
no_license
#ifndef _OPERATOR_TRAITS_HPP_INCLUDED_OJISDFLJASOIJ498UAFDKLJ489UALFKJALDFKJF #define _OPERATOR_TRAITS_HPP_INCLUDED_OJISDFLJASOIJ498UAFDKLJ489UALFKJALDFKJF #include <type_traits> #include <utility> #include <iostream> namespace operator_traits { template< typename, typename = void, typename = void > struct has_assignment : std::false_type {}; template< typename T, typename U > struct has_assignment< T, U, std::void_t<decltype( std::declval<T&>() = std::declval<U const&>() )>> : std::true_type {}; template< typename T > struct has_assignment< T, void, std::void_t<decltype( std::declval<T&>() = std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_assignment_v = has_assignment<T>::value; template< class T, class U > inline constexpr bool has_assignment_v2 = has_assignment<T, U>::value; template< typename, typename = void, typename = void > struct has_move_assignment : std::false_type {}; template< typename T, typename U > struct has_move_assignment< T, U, std::void_t<decltype( std::declval<T&>() = std::declval<U&&>() )>> : std::true_type {}; template< typename T > struct has_move_assignment< T, void, std::void_t<decltype( std::declval<T&>() = std::declval<T&&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_move_assignment_v = has_move_assignment<T>::value; template< class T, class U > inline constexpr bool has_move_assignment_v2 = has_move_assignment<T, U>::value; template< typename, typename = void > struct has_addition : std::false_type {}; template< typename T > struct has_addition < T, std::void_t < decltype( std::declval<T const&>() + std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_addition_v = has_addition<T>::value; template< typename, typename = void > struct has_subtraction : std::false_type {}; template< typename T > struct has_subtraction < T, std::void_t < decltype( std::declval<T const&>() - std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_subtraction_v = has_subtraction<T>::value; template< typename, typename = void > struct has_unary_plus : std::false_type {}; template< typename T > struct has_unary_plus < T, std::void_t < decltype( + std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_unary_plus_v = has_unary_plus<T>::value; template< typename, typename = void > struct has_unary_minus : std::false_type {}; template< typename T > struct has_unary_minus < T, std::void_t < decltype( - std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_unary_minus_v = has_unary_minus<T>::value; template< typename, typename = void > struct has_multiplication : std::false_type {}; template< typename T > struct has_multiplication< T, std::void_t<decltype( std::declval<T const&>() * std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_multiplication_v = has_multiplication<T>::value; template< typename, typename = void > struct has_division : std::false_type {}; template< typename T > struct has_division < T, std::void_t < decltype( std::declval<T const&>() / std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_division_v = has_division<T>::value; template< typename, typename = void > struct has_modulo : std::false_type {}; template< typename T > struct has_modulo < T, std::void_t < decltype( std::declval<T const&>() % std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_modulo_v = has_modulo<T>::value; template< typename, typename = void > struct has_prefix_increment : std::false_type {}; template< typename T > struct has_prefix_increment < T, std::void_t < decltype( ++std::declval<T&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_prefix_increment_v = has_prefix_increment<T>::value; template< typename, typename = void > struct has_postfix_increment : std::false_type {}; template< typename T > struct has_postfix_increment < T, std::void_t < decltype( std::declval<T&>()++ ) > > : std::true_type {}; template< class T > inline constexpr bool has_postfix_increment_v = has_postfix_increment<T>::value; template< typename, typename = void > struct has_prefix_decrement : std::false_type {}; template< typename T > struct has_prefix_decrement < T, std::void_t < decltype( --std::declval<T&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_prefix_decrement_v = has_prefix_decrement<T>::value; template< typename, typename = void > struct has_postfix_decrement : std::false_type {}; template< typename T > struct has_postfix_decrement < T, std::void_t < decltype( std::declval<T&>()-- ) > > : std::true_type {}; template< class T > inline constexpr bool has_postfix_decrement_v = has_postfix_decrement<T>::value; template< typename, typename = void > struct has_equal_to : std::false_type {}; template< typename T > struct has_equal_to< T, std::void_t<decltype( std::declval<T const&>() == std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_equal_to_v = has_equal_to<T>::value; template< typename, typename = void > struct has_not_equal_to : std::false_type {}; template< typename T > struct has_not_equal_to < T, std::void_t < decltype( std::declval<T const&>() != std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_not_equal_to_v = has_not_equal_to<T>::value; template< typename, typename = void > struct has_greater_than : std::false_type {}; template< typename T > struct has_greater_than< T, std::void_t<decltype( std::declval<T const&>() > std::declval<T const&>() )> > : std::true_type {}; template< class T > inline constexpr bool has_greater_than_v = has_greater_than<T>::value; template< typename, typename = void > struct has_less_than : std::false_type {}; template< typename T > struct has_less_than < T, std::void_t<decltype( std::declval<T const&>() < std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_less_than_v = has_less_than<T>::value; template< typename, typename = void > struct has_greater_than_or_equal_to : std::false_type {}; template< typename T > struct has_greater_than_or_equal_to< T, std::void_t<decltype( std::declval<T const&>() >= std::declval<T const&>() )> > : std::true_type {}; template< class T > inline constexpr bool has_greater_than_or_equal_to_v = has_greater_than_or_equal_to<T>::value; template< typename, typename = void > struct has_less_than_or_equal_to : std::false_type {}; template< typename T > struct has_less_than_or_equal_to < T, std::void_t<decltype( std::declval<T const&>() <= std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_less_than_or_equal_to_v = has_less_than_or_equal_to<T>::value; template< typename, typename = void > struct has_logical_not : std::false_type {}; template< typename T > struct has_logical_not < T, std::void_t < decltype( !std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_logical_not_v = has_logical_not<T>::value; template< typename, typename = void > struct has_logical_and : std::false_type {}; template< typename T > struct has_logical_and < T, std::void_t < decltype( std::declval<T const&>()&& std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_logical_and_v = has_logical_and<T>::value; template< typename, typename = void > struct has_logical_or : std::false_type {}; template< typename T > struct has_logical_or < T, std::void_t < decltype( std::declval<T const&>() || std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_logical_or_v = has_logical_or<T>::value; template< typename, typename = void > struct has_bitwise_not : std::false_type {}; template< typename T > struct has_bitwise_not < T, std::void_t < decltype( ~ std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_not_v = has_bitwise_not<T>::value; template< typename, typename = void > struct has_bitwise_and : std::false_type {}; template< typename T > struct has_bitwise_and< T, std::void_t<decltype( std::declval<T const&>() & std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_bitwise_and_v = has_bitwise_and<T>::value; template< typename, typename = void > struct has_bitwise_or : std::false_type {}; template< typename T > struct has_bitwise_or < T, std::void_t < decltype( std::declval<T const&>() | std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_or_v = has_bitwise_or<T>::value; template< typename, typename = void > struct has_bitwise_xor : std::false_type {}; template< typename T > struct has_bitwise_xor< T, std::void_t<decltype( std::declval<T const&>() ^ std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_bitwise_xor_v = has_bitwise_xor<T>::value; template< typename, typename = void > struct has_bitwise_left_shift : std::false_type {}; template< typename T > struct has_bitwise_left_shift < T, std::void_t < decltype( std::declval<T const&>() << 1 ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_left_shift_v = has_bitwise_left_shift<T>::value; template< typename, typename = void > struct has_bitwise_right_shift : std::false_type {}; template< typename T > struct has_bitwise_right_shift < T, std::void_t < decltype( std::declval<T const&>() >> 1 ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_right_shift_v = has_bitwise_right_shift<T>::value; template< typename, typename = void > struct has_addition_assignment : std::false_type {}; template< typename T > struct has_addition_assignment < T, std::void_t < decltype( std::declval<T&>() += std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_addition_assignment_v = has_addition_assignment<T>::value; template< typename, typename = void > struct has_subtraction_assignment : std::false_type {}; template< typename T > struct has_subtraction_assignment < T, std::void_t < decltype( std::declval<T&>() -= std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_subtraction_assignment_v = has_subtraction_assignment<T>::value; template< typename, typename = void > struct has_multiplication_assignment : std::false_type {}; template< typename T > struct has_multiplication_assignment< T, std::void_t<decltype( std::declval<T&>() *= std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_multiplication_assignment_v = has_multiplication_assignment<T>::value; template< typename, typename = void > struct has_division_assignment : std::false_type {}; template< typename T > struct has_division_assignment < T, std::void_t < decltype( std::declval<T&>() /= std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_division_assignment_v = has_division_assignment<T>::value; template< typename, typename = void > struct has_modulo_assignment : std::false_type {}; template< typename T > struct has_modulo_assignment < T, std::void_t < decltype( std::declval<T&>() %= std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_modulo_assignment_v = has_modulo_assignment<T>::value; template< typename, typename = void > struct has_bitwise_and_assignment : std::false_type {}; template< typename T > struct has_bitwise_and_assignment< T, std::void_t<decltype( std::declval<T&>() &= std::declval<T const&>() )>> : std::true_type {}; template< class T > inline constexpr bool has_bitwise_and_assignment_v = has_bitwise_and_assignment<T>::value; template< typename, typename = void > struct has_bitwise_or_assignment : std::false_type {}; template< typename T > struct has_bitwise_or_assignment < T, std::void_t < decltype( std::declval<T&>() |= std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_or_assignment_v = has_bitwise_or_assignment<T>::value; template< typename, typename = void > struct has_bitwise_left_shift_assignment : std::false_type {}; template< typename T > struct has_bitwise_left_shift_assignment < T, std::void_t < decltype( std::declval<T&>() <<= 1 ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_left_shift_assignment_v = has_bitwise_left_shift_assignment<T>::value; template< typename, typename = void > struct has_bitwise_right_shift_assignment : std::false_type {}; template< typename T > struct has_bitwise_right_shift_assignment < T, std::void_t < decltype( std::declval<T&>() >>= 1 ) > > : std::true_type {}; template< class T > inline constexpr bool has_bitwise_right_shift_assignment_v = has_bitwise_right_shift_assignment<T>::value; template< typename, typename = void > struct has_ostream : std::false_type {}; template< typename T > struct has_ostream < T, std::void_t < decltype( std::declval<std::ostream&>() << std::declval<T const&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_ostream_v = has_ostream<T>::value; template< typename, typename = void > struct has_istream : std::false_type {}; template< typename T > struct has_istream < T, std::void_t < decltype( std::declval<std::istream&>() >> std::declval<T&>() ) > > : std::true_type {}; template< class T > inline constexpr bool has_istream_v = has_istream<T>::value; template< typename, typename = void > struct has_bracket : std::false_type {}; template< typename T > struct has_bracket< T, std::void_t<decltype( ( std::declval<T&>() )[0] )>> : std::true_type {}; template< class T > inline constexpr bool has_bracket_v = has_bracket<T>::value; template< typename, typename = void > struct has_const_bracket : std::false_type {}; template< typename T > struct has_const_bracket< T, std::void_t<decltype( ( std::declval<T const&>() )[0] )>> : std::true_type {}; template< class T > inline constexpr bool has_const_bracket_v = has_const_bracket<T>::value; }//namespace operator detection #endif//_OPERATOR_TRAITS_HPP_INCLUDED_OJISDFLJASOIJ498UAFDKLJ489UALFKJALDFKJF
true
65369113b935b4846a1fb1ea5e93592d8a3c243a
C++
Ben-Weisman/E-Store-Project
/E-Store-Project-Updated/Date.h
UTF-8
552
3.171875
3
[]
no_license
#ifndef __Date_h #define __Date_h #include <iostream> using namespace std; class Date { int m_day; int m_month; int m_year; public: Date(int day, int month, int year); ~Date() = default; public: bool setDay(int day); bool setMonth(int month); bool setYear(int year); public: inline int getDay()const { return m_day; } inline int getMonth()const { return m_month; } inline int getYear()const { return m_year; } public: inline void showDate()const { cout << m_day << "/" << m_month << "/" << m_year << endl; } }; #endif //!__Date_h
true
b929dee60b2189b078796d1f21c984a3546d4236
C++
CarlosMa15/Linux
/cs3505/Assignment3/tester1.cpp
UTF-8
4,880
3.84375
4
[]
no_license
/* * This is a tester that I started to write in class. It reads * words from a text file, then adds the words to two sets: A built-in * set class, and our string_set class. After reading the file, it * prints out all the words stored in the STL set object. At the end * of the test, it prints out the sizes of both sets to see that they * are the same. * * After the test completes, I make sure the local variabls are properly * cleaned up. * * If the comments wrap lines, widen your emacs window. * * Peter Jensen * January 30, 2018 */ #include <iostream> #include <fstream> #include <set> #include <iterator> #include "string_set.h" #include "node.h" // For convenience only: using namespace std; // Note: Our classes were declared in a cs3505 namepsace. // Instead of 'using namespace cs3505', I qualify the class names // below with cs3505:: int main () { // Open up another block. This way, when the block ends, // variables local to the block will be destroyed, but main // will still be running. (Did you know that you can open // up a block at any time to control local variable scope and // lifetime?) { // Create the two sets. Declaring the local variables constructs the objects. set<string> stl_set; // The built-in set class - no constructor parameters. cs3505::string_set our_set(1000); // Our set class, with a hashtable of 1000 slots. // Open the file stream for reading. (We'll be able to use it just like // the keyboard stream 'cin'.) ifstream in("Yankee.txt"); // Loop for reading the file. Note that it is controlled // from within the loop (see the 'break'). while (true) { // Read a word (don't worry about punctuation) string word; in >> word; // If the read failed, we're probably at end of file // (or else the disk went bad). Exit the loop. if (in.fail()) break; // Word successfully read. Add it to both sets. stl_set.insert(word); our_set.add(word); } // Close the file. in.close(); cout<<"These are the elements of the stl set:"<<endl; // Print out all the words in the reference solution. for (set<string>::iterator it = stl_set.begin(); it != stl_set.end(); it++) { string word = *it; cout <<"STL: "<< word << endl; } vector<string> ourSetVector = our_set.get_elements(); our_set.remove("exhausted"); // HERE IT IS !!!!!!!!!!!!!!!!!!!!! vector<string> osv = our_set.get_elements(); cout<<"\n\nTheses are the elements of the our set:"<<endl; for(vector<string>::iterator iter = osv.begin(); iter != osv.end();iter++ ){ cout <<"OSV: "<< *iter << endl; } cout<<"\n\nTheses are the elements of the mySet:"<<endl; cs3505::string_set mySet = our_set; vector<string> mosv = mySet.get_elements(); for(vector<string>::iterator iter = mosv.begin(); iter != mosv.end();iter++ ){ cout <<"MOSV: "<< *iter << endl; } cout<<"\n\nMosv set conatins "<<mosv.size()<<" unique words"<<endl; // Print out the number of words found in each set. cout << "STL set contains " << stl_set.size() << " unique words.\n"; cout << "Our set contains " << our_set.size() << " unique words.\n"; cout << "Our set vector get elements " <<osv.size()<< " unique words. \n\n"; bool answer = our_set.contains("yours"); if(answer){ cout<<"Yes, it contains word yours"<<endl<<endl;; }else { cout<<"No, it does not contain work yours"<<endl<<endl; } answer = our_set.contains("jdasgkljadg"); if(answer){ cout<<"Yes, it contains word jdasgkljadg"<<endl<<endl;; }else { cout<<"No, it does not contain work jdasgkljadg"<<endl<<endl; } // Done. Notice that this code block ends below. Any local // variables declared within this block will be automatically // destroyed. Local objects will have their destructors // called. (Blocks are great for controlling scope/lifetime.) } // Now that the objects have been destroyed, I will simply call my auditing // code to print out how many times constructors have been called, and // how many times destructors have been called. They should exactly match. // If not, we have a memory problem. cout << "Class cs3505::string_set:" << endl; cout << " Objects created: " << cs3505::string_set::constructor_count() << endl; cout << " Objects deleted: " << cs3505::string_set::destructor_count() << endl; cout << endl; cout << "Class cs3505::node:" << endl; cout << " Objects created: " << cs3505::node::constructor_count() << endl; cout << " Objects deleted: " << cs3505::node::destructor_count() << endl; cout << endl; // Now we're really done. End main. return 0; }
true
89ffdafccb1796e4dd56d91391b0af373702db04
C++
KingWapo/GenesisEngine
/GenesisEngine/GenesisEngine/CircCollidableComponent.h
UTF-8
937
2.640625
3
[]
no_license
#pragma once #include "CollidableComponent.h" #include "Transform2dComponent.h" #include "Vector2.h" class CircCollidableComponent : public CollidableComponent { public: CircCollidableComponent(); CircCollidableComponent(float p_r); CircCollidableComponent(Circ2D p_circ, bool p_static); ~CircCollidableComponent() { } virtual bool vUpdate(int deltaMs); virtual void vOnChanged(void); // Collidable interface virtual void onCollision() {} virtual void onCollisionBegin() {} virtual void onCollisionEnd() {} virtual void onOverlap() {} virtual void onOverlapBegin() {} virtual void onOverlapEnd() {} Circ2D getCirc() { return m_circ; } float getRadius() { return m_circ.R(); } void setCirc(Circ2D p_circ) { m_circ = p_circ; } void setRadius(float p_r) { m_circ.setRadius(p_r); } virtual ColliderType getColType() override { return colType; } private: Circ2D m_circ; protected: static ColliderType colType; };
true
24b558b2ba6e0adce21ad0b88524e9f353b89cc1
C++
nanno-nanno/RandomCreations
/PROG3_Project/NEngine/Label.h
UTF-8
834
2.984375
3
[]
no_license
#ifndef LABEL_H #define LABEL_H #include "Component.h" #include <string> #include <SDL2_ttf/SDL_ttf.h> /* En klass som placerar en textstrang i ett SDL_Window. Anvander sig av NGameEngine-objektets givna typsnitt och en SDL_Texture att rita med. - Subklass till Component */ namespace nengine { class Label : public Component { public: static Label* getInstance(int x, int y, int w, int h, std::string labelText); void draw(); void create(); std::string getLabelText() const { return text; } SDL_Texture* getTexture(){ return texture; } void setLabelText(std::string newLabelText); ~Label(); protected: Label(int x, int y, int w, int h, std::string labelText); private: SDL_Texture* texture; std::string text; }; } #endif
true
258776d7db2ce6371f1f61d5573c9e1e138d1351
C++
bluekingsong/convergence-analysis
/code/vec_op.cpp
UTF-8
773
3.109375
3
[]
no_license
#include <cstring> #include <cmath> #include "vec_op.h" using namespace std; double vec_dot(double *vec1,double *vec2,int vec_len){ double result=0; for(int i=0;i<vec_len;++i) result+=vec1[i]*vec2[i]; return result; } void vec_add(double *result_vec,double *vec1,double *vec2,int vec_len,double factor1,double factor2){ for(int i=0;i<vec_len;++i) result_vec[i]=factor1*vec1[i]+factor2*vec2[i]; } void vec_cpy(double *dest,double *src,int vec_len){ if(0==dest ||0==src || dest==src) return; memcpy(dest,src,sizeof(dest)*vec_len); } double vec_l1_norm(double *vec,int vec_len){ double result=0.0; for(int i=0;i<vec_len;++i) result+=abs(vec[i]); return result; } void vec_mul(double *vec,int vec_len,double factor){ for(int i=0;i<vec_len;++i) vec[i]*=factor; }
true
c2e0bd84475842988ec00a0f8b60c0a6db859736
C++
Yang-zhizhang/pat
/03-7-10.cpp
UTF-8
369
3.703125
4
[]
no_license
/*基础编程题库集 编程题7-10 计算工资*/ #include<stdio.h> int main() { int year; int hour; float salary; scanf("%d %d",&year,&hour); if(year<5) { if(hour<=40) salary=hour*30; else salary=1200+(hour-40)*30*1.5; } else { if(hour<=40) salary=hour*50; else salary=2000+(hour-40)*50*1.5; } printf("%.2f", salary); return 0; }
true
e1db021cfb434a789938975ffe19bb9eb3a33fe9
C++
raxracks/chadOS
/userspace/libraries/libio/Path.h
UTF-8
8,279
3.140625
3
[ "MIT", "BSD-2-Clause" ]
permissive
#pragma once #include <abi/Filesystem.h> #include <libio/MemoryReader.h> #include <libio/MemoryWriter.h> #include <libio/Scanner.h> #include <libio/Write.h> #include <libutils/String.h> #include <libutils/Vector.h> namespace IO { struct Path { private: bool _absolute = false; Vector<String> _elements{}; public: static constexpr int PARENT_SHORTHAND = 1; // .... -> ../../.. bool absolute() const { return _absolute; } bool relative() const { return !_absolute; } size_t length() const { return _elements.count(); } static Path parse(const String &string, int flags = 0) { return parse(string.cstring(), string.length(), flags); } static Path parse(const char *path, int flags = 0) { return parse(path, strlen(path), flags); } static Path parse(const char *path, size_t size, int flags) { IO::MemoryReader memory{path, size}; IO::Scanner scan{memory}; bool absolute = false; if (scan.skip(PATH_SEPARATOR)) { absolute = true; } auto parse_element = [](auto &scan) { IO::MemoryWriter memory; while (!scan.skip(PATH_SEPARATOR) && !scan.ended()) { IO::write(memory, scan.next()); } return memory.string(); }; auto parse_shorthand = [](auto &scan) { Vector<String> elements{}; scan.skip_word(".."); elements.push(".."); while (scan.skip('.')) { elements.push(".."); } scan.skip('/'); return elements; }; Vector<String> elements{}; while (!scan.ended()) { if ((flags & PARENT_SHORTHAND) && scan.peek_is_word("..")) { elements.push_back_many(parse_shorthand(scan)); } else { auto el = parse_element(scan); if (el->size() > 0) { elements.push_back(el); } } } return {absolute, std::move(elements)}; } static Path join(String left, String right) { return join(parse(left), parse(right)); } static Path join(Path &&left, String right) { return join(left, parse(right)); } static Path join(String left, Path &&right) { return join(parse(left), right); } static Path join(const Path &left, String right) { return join(left, parse(right)); } static Path join(String left, Path &right) { return join(parse(left), right); } static Path join(Path &&left, Path &&right) { return join(left, right); } static Path join(Path &left, Path &&right) { return join(left, right); } static Path join(Path &&left, Path &right) { return join(left, right); } static Path join(const Path &left, const Path &right) { Vector<String> combined_elements{}; combined_elements.push_back_many(left._elements); combined_elements.push_back_many(right._elements); return {left.absolute(), std::move(combined_elements)}; } Path() { } Path(const Path &other) : _absolute{other.absolute()}, _elements{other._elements} { } Path(bool absolute, Vector<String> &&elements) : _absolute(absolute), _elements(elements) { } Path(Path &&other) { std::swap(_absolute, other._absolute); std::swap(_elements, other._elements); } Path &operator=(const Path &other) { if (this != &other) { _absolute = other.absolute(); _elements = other._elements; } return *this; } Path &operator=(Path &&other) { if (this != &other) { std::swap(_absolute, other._absolute); std::swap(_elements, other._elements); } return *this; } String operator[](size_t index) const { return _elements[index]; } bool operator!=(const Path &other) const { return !(*this == other); } bool operator==(const Path &other) const { if (this == &other) { return true; } if (_absolute != other._absolute) { return false; } return _elements == other._elements; } Path normalized() { Vector<String> stack{}; _elements.foreach([&](auto &element) { if (element == ".." && stack.count() > 0) { stack.pop_back(); } else if (_absolute && element == "..") { if (stack.count() > 0) { stack.pop_back(); } } else if (element != ".") { stack.push_back(element); } return Iteration::CONTINUE; }); return {_absolute, std::move(stack)}; } String basename() const { if (length() > 0) { return _elements.peek_back(); } else { if (_absolute) { return "/"; } else { return ""; } } } String basename_without_extension() const { IO::MemoryWriter builder{basename().length()}; IO::MemoryReader reader{basename().slice()}; IO::Scanner scan{reader}; // It's not a file extention it's an hidden file. if (scan.peek() == '.') { IO::write(builder, scan.next()); } while (scan.peek() != '.' && !scan.ended()) { IO::write(builder, scan.next()); } return builder.string(); } String dirname() const { IO::MemoryWriter builder{}; if (_absolute) { IO::write(builder, PATH_SEPARATOR); } else if (_elements.count() <= 1) { IO::write(builder, '.'); } if (_elements.count() >= 2) { for (size_t i = 0; i < _elements.count() - 1; i++) { IO::write(builder, _elements[i]); if (i != _elements.count() - 2) { IO::write(builder, PATH_SEPARATOR); } } } return builder.string(); } Path dirpath() const { Vector<String> stack{}; if (length() > 0) { for (size_t i = 0; i < length() - 1; i++) { stack.push_back(_elements[i]); } } return {_absolute, std::move(stack)}; } String extension() const { auto filename = basename(); IO::MemoryWriter builder{basename().length()}; IO::MemoryReader reader{basename().slice()}; IO::Scanner scan{reader}; // It's not a file extention it's an hidden file. scan.skip('.'); while (scan.peek() != '.' && !scan.ended()) { scan.next(); } while (!scan.ended()) { IO::write(builder, scan.next()); } return builder.string(); } Path parent(size_t index) const { Vector<String> stack{}; if (index <= length()) { for (size_t i = 0; i <= index; i++) { stack.push_back(_elements[i]); } } return {_absolute, std::move(stack)}; } String string() const { IO::MemoryWriter builder{basename().length()}; if (_absolute) { IO::write(builder, PATH_SEPARATOR); } for (size_t i = 0; i < _elements.count(); i++) { IO::write(builder, _elements[i]); if (i != _elements.count() - 1) { IO::write(builder, PATH_SEPARATOR); } } return builder.string(); } }; } // namespace IO
true
7a58d2b364dcde8e6e9e91fafdeedd50bdea9edd
C++
chinoudea/LabInfo2
/Practica4/router.h
UTF-8
729
3.046875
3
[]
no_license
#ifndef ROUTER_H #define ROUTER_H #include <map> #include <iostream> using namespace std; class router { private: string name; map<string,int> links; public: // Constructor con nombre de router router(string routerName); // Destructor ~router(); // Funcion para obtener el nombre del router string getName(); // Funcion para obtener las relaciones del router map<string,int> getLinks(); // Funcion para actualizar una relacion en el router void updateLink(string routerName, int cost); // Funcion para eliminar una relacion en el router void removeLink(string routerName); // Funcion para contar las relaciones de un router int countLinks(); }; #endif // ROUTER_H
true
439b1250f756e10011bd0f42bb6c587d34adc1a4
C++
keuhdall/Piscine_cpp
/rush00/Object/AObject.hpp
UTF-8
621
2.921875
3
[]
no_license
#ifndef AOBJECT_HPP # define AOBJECT_HPP # include <iostream> # include <string> typedef struct { int x; int y; } t_point; class AObject { public: AObject(void); AObject(const AObject &copy); AObject &operator=(const AObject &copy); virtual ~AObject(void); virtual bool getEnabled(void); virtual t_point getPosition(void); virtual void setPosition(int y, int x); virtual void setEnabled(bool); virtual void move(void) = 0; char getShape(void) const; protected: t_point pos; bool enabled; char shape; }; #endif
true
0bc9b3ca1106e16b6d9b8b18815892af16ef686f
C++
ArtyomAdov/learning_sibsutis
/learning/thirdparty/2k2s/2k2s/PVT/pruf/main.cpp
UTF-8
1,660
2.578125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include "hpctimer.h" enum { N = 512, NREPS = 99999999 }; int main(int argc, char **argv) { int i; double t; int rand_num; int counter_one; printf("vetki: "); /* t = hpctimer_getwtime(); for (i = 0; i < NREPS; i++) { rand_num = rand() % 2; if (rand_num == 1) counter_one++; else counter_one--; } t = hpctimer_getwtime() - t; // t = t / NREPS; printf("Elapsed time: %.6f sec.\n", t); printf("main: "); t = hpctimer_getwtime(); for (i = 0; i < NREPS; i++) { rand_num = rand() % 2; counter_one += (rand_num == 1) * 2 - 1; } t = hpctimer_getwtime() - t; // t = t / NREPS; printf("Elapsed time: %.6f sec.\n", t);*/ t = hpctimer_getwtime(); for (i = 0; i < NREPS; i++) { rand_num = rand() % 10; if (rand_num == 1) counter_one++; else if (rand_num == 2) counter_one--; else if (rand_num == 3) counter_one += 7; else if (rand_num == 4) counter_one -= 7; } t = hpctimer_getwtime() - t; // t = t / NREPS; printf("Elapsed time: %.6f sec.\n", t); printf("main: "); t = hpctimer_getwtime(); for (i = 0; i < NREPS; i++) { rand_num = rand() % 10; counter_one += (rand_num == 1) * 1 + (rand_num == 2) * (-1) + (rand_num == 3) * 7 + (rand_num == 4) * (-7); } t = hpctimer_getwtime() - t; // t = t / NREPS; printf("Elapsed time: %.6f sec.\n", t); return 0; }
true
aaa9e01786df789282e0a7197db12f5802fce0fc
C++
no-glue/chained-hash-table
/hash_simple_string.h
UTF-8
295
3.0625
3
[]
no_license
template<typename Type>class HashSimpleString { public: unsigned int position(Type key, unsigned int size) { // simple hash just add up bytes and return unsigned int length = key.length(), i, sum; for(i = 0, sum = 0; i < length; i++) sum += key.at(i); return sum % size; } };
true
ed0af3be54d762e7cac56408c312c1cc3cac883c
C++
Snigdhabhatnagar/Competitive-Programming
/Code Forces Problems/CFnearest Interesting Num(1183A).cpp
UTF-8
457
2.859375
3
[]
no_license
#include<iostream> using namespace std; int main() { int a; cin>>a; int n=a; int sum=0; while(a!=0) { sum+=a%10; a/=10; } if(sum%4==0) { cout<<n; } else { int sum1=sum; while(sum1%4!=0) { n+=1; a=n; sum1=0; while(a!=0) { sum1+=a%10; a/=10; } } cout<<n; } }
true
6d72daafed119eac565afe08c6eced789e7c7bb9
C++
xeon2007/WSProf
/Projects/bdda/src/CPP/Excel/XlCharts/XlChartDataModel/inc/XlChartBar.h
UTF-8
3,992
2.828125
3
[]
no_license
/** * @file XlChartBar.h * * Header file for Excel Chart Bar record. * Definition of a bar or column chart group * * (c) Schema Software Inc., 2003 * @ingroup ExcelChart */ #if !defined __XLCHART_BAR_H__ #define __XLCHART_BAR_H__ #include "XlObject.h" #include "XlRecord.h" /** * Excel Chart Bar record representation * Definition of a bar or column chart group * * @ingroup ExcelChart */ class XlChartBar : public XlRecord { public: enum { ID = 0x1017, FIX_SIZE = 6 }; /** * Constructor for this class. */ ChIMPORT XlChartBar (); /** * Constructor that initializes the bar record using the XlHeader * information. NOTE: this constructor should only be used for data-level * access (mainly through the parser). Clients should NOT use this * constructor when dealing with objects at the semantic level. * * @param in_header - The header info. */ ChIMPORT XlChartBar (XlHeader& in_header); /** * Destructor for this class. */ virtual ChIMPORT ~XlChartBar (); /** * Accessors to the space between bars, specified in percents of the bar * width. Note: this is the opposite of what you see in the user-interface * in Excel, which references it in terms of overlap. For example, if the * overlap in Excel says -100%, the space between the bars is actually 100%. */ ChIMPORT ChSINT2 getSpaceBetweenBars () const { return m_nPcOverlap; } ChIMPORT void setSpaceBetweenBars (const ChSINT2 in_nPcOverlap) { m_nPcOverlap = in_nPcOverlap; } /** * Accessors to the space between categories, specified in percents of the * bar width. */ ChIMPORT ChSINT2 getGap () const { return m_nPcGap; } ChIMPORT void setGap (const ChSINT2 in_nPcGap){ m_nPcGap = in_nPcGap; } /** * Accessors to the flag indicating wehther to transpose the bars. If * set to true, the chart has horizontal bars (bar chart). If set to * false, the chart has vertical bars (column chart). */ ChIMPORT bool isTranspose () const; ChIMPORT void setTransposeFlag (const bool in_val); /** * Accessors to the flag indiciating whether to stack the display values. * This means that the bars or columns within a category are stacked one * on top of the next. */ ChIMPORT bool isStacked () const; ChIMPORT void setStackedFlag (const bool in_val); /** * Accessors to the flag indicating whether each category is displayed as * a percentage. Note: this flag is valid if and only if isStacked() is * true, which indicates that each category is broken down into percentages. */ ChIMPORT bool isCategoryPercentage () const; ChIMPORT void setCategoryPercentageFlag (const bool in_val); /** * Accessors to the flag indicating whether this bar has a shadow. */ ChIMPORT bool isShadow () const; ChIMPORT void setShadowFlag (const bool in_val); /** * Accessors to the option flags. NOTE: this function is used for data-level * access and should NOT be used by the clients who should be accessing * the various options through the accessors provided. */ ChIMPORT ChSINT2 getOptionFlags () const { return m_nGrbit; } ChIMPORT void setOptionFlags (const ChSINT2 in_nGrbit) { m_nGrbit = in_nGrbit; } /** * Implementation of virtual function for XlRecord. * * @param in_visitor - the visitor to accept. */ ChIMPORT void accept (XlDataModelVisitor& in_visitor) { in_visitor.visit(*this); }; /** * Calculate size required to persist current state of the object */ ChUINT2 getPersistLength() const { return FIX_SIZE; } private: ChSINT2 m_nPcOverlap; // Space between bars (percent of bar width) ChSINT2 m_nPcGap; // Space between categories (percent of bar width) ChSINT2 m_nGrbit; // Format flags }; #endif //__XLCHART_BAR_H__
true
a9c00e3129d4303175b290c3eb6afff0d6a37002
C++
shravya-bhaskara/ctf2021
/baby_ctf_simulator/private/chall.cpp
UTF-8
7,941
3.03125
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <unistd.h> #include <string.h> #include <string> #include <iostream> #include <exception> #include <sstream> #include <map> #include <limits> #include <alloca.h> #include "Exceptions.hpp" #include "Colors.hpp" #include "chall.hpp" #define DEBUG using namespace std; ReleasedChallenge::ReleasedChallenge(): points(0), solved(false) { set_points(); set_flag(); } ReleasedChallenge::ReleasedChallenge(Challenge* uc): Challenge(uc->name) { if (dynamic_cast<UnreleasedChallenge *>(uc) == NULL) { throw new AlreadyReleasedChallengeException(uc); } set_points(); set_flag(); } void ReleasedChallenge::set_points() { cout << "How many points should this challenge have?" << endl; if (!(cin >> points)) { cin.clear(); cin.ignore(); throw new InvalidInputException(); } } void ReleasedChallenge::set_flag() { string _flag; cout << "What should the flag be?" << endl; cin >> _flag; if (_flag.rfind("flag{", 0) != 0) throw new InvalidInputException(); if (_flag.back() != '}') throw new InvalidInputException(); flag = _flag; } string read_multiline() { stringstream ss; string line, output; cout << "Terminate input with a . on a single line" << endl; while (true) { getline(cin, line); if (!line.compare(".")) break; ss << line << endl; }; output = ss.str(); if (!output.length()) { throw new InvalidInputException(); } return output; }; BrokenChallenge::BrokenChallenge(Challenge* uc): Challenge(uc->name) { if (dynamic_cast<BrokenChallenge *>(uc)) { throw new AlreadyBrokenChallengeException(uc); } cout << "Enter the reason why this challenge is borken. "; reason = read_multiline(); } Challenge::Challenge() { string _name; cout << "What do you want to call your challenge?" << endl << "House of " << flush; cin >> _name; stringstream ss; ss << "House of " << _name; name = ss.str(); } int ReleasedChallenge::solve() { if (solved) { throw new AlreadySolvedException(name); } bool correct = check_flag(flag.c_str(), flag.length()); if (correct) { cout << GREEN << "CONGRATS! YOU WIN " << points << " POINTS!" << RESET << endl; solved = true; return points; } throw new InvalidFlagException(); } void CTF::play() { while (true) { try { if (menu()) break; } catch (NonFatalException *e) { cout << RED << "Error: " << e->what() << RESET << endl; delete e; } } } void CTF::list() { if (challenges.empty()) { throw new NoChallengesYetException(); } map<string, Challenge*>::iterator it = challenges.begin(); while(it != challenges.end()) { if (ReleasedChallenge * rc = dynamic_cast<ReleasedChallenge*>(it->second)) cout << *rc << endl; else if (BrokenChallenge *bc = dynamic_cast<BrokenChallenge*>(it->second)) cout << *bc << endl; else if (UnreleasedChallenge *uc = dynamic_cast<UnreleasedChallenge*>(it->second)) cout << *uc << endl; it++; } } void CTF::make_chall() { UnreleasedChallenge *new_challenge = NULL; new_challenge = new UnreleasedChallenge(); try { challenges.at(new_challenge->name); } catch (out_of_range &e) { challenges[new_challenge->name] = new_challenge; return; } throw new DuplicateNameException(new_challenge->name); delete new_challenge; } void CTF::release_chall() { struct { ReleasedChallenge *rc; Challenge *challenge; string challenge_name; } stack = { 0 }; cout << "What challenge?" << endl; getline(cin, stack.challenge_name); try { stack.challenge = challenges.at(stack.challenge_name); } catch (out_of_range &e) { throw new NoSuchChallengeException(stack.challenge_name); } if (dynamic_cast<BrokenChallenge*>(stack.challenge)) { throw new BrokenChallengeException(stack.challenge_name); } while (true) { try { stack.rc = new ReleasedChallenge(stack.challenge); } catch (InvalidInputException *e) { cout << "Error releasing challenge " << stack.challenge << ", try again." << endl; continue; } break; } challenges[stack.challenge_name] = stack.rc; delete stack.challenge; } void CTF::break_chall() { struct { BrokenChallenge *bc; Challenge *challenge; string challenge_name; } stack = { 0 }; cout << "What challenge?" << endl; getline(cin, stack.challenge_name); try { stack.challenge = challenges.at(stack.challenge_name); } catch (out_of_range &e) { throw new NoSuchChallengeException(stack.challenge_name); } while (true) { try { stack.bc = new BrokenChallenge(stack.challenge); } catch (InvalidInputException *e) { cout << "Error releasing challenge " << stack.challenge << ", try again." << endl; continue; } break; } challenges[stack.challenge_name] = stack.bc; delete stack.challenge; } void CTF::solve_chall() { struct { ReleasedChallenge *rc; Challenge *challenge; string challenge_name; } stack = { 0 }; cout << "What challenge?" << endl; getline(cin, stack.challenge_name); try { stack.challenge = challenges.at(stack.challenge_name); } catch (out_of_range &e) { throw new NoSuchChallengeException(stack.challenge_name); } if (dynamic_cast<BrokenChallenge*>(stack.challenge)) { throw new BrokenChallengeException(stack.challenge->name); } stack.rc = dynamic_cast<ReleasedChallenge*>(stack.challenge); if (!stack.rc) { throw new UnreleasedChallengeException(); } points += stack.rc->solve(); } bool CTF::menu() { long choice = 0; string challenge_name; Challenge *challenge = NULL; cout << "You currently have " << YELLOW << points << " points" << RESET << ". What do you want to do?" << endl << RED << " 0. " << RESET << " List Challenges" << endl << YELLOW << " 1. " << RESET << " Make Challenge" << endl << GREEN << " 2. " << RESET << " Release Challenge" << endl << CYAN << " 3. " << RESET << " Break Challenge" << endl << BLUE << " 4. " << RESET << " Solve Challenge" << endl << MAGENTA << " 5. " << RESET << " Quit" << endl << ">_ "; if (!(cin >> choice)) { cin.clear(); cin.ignore(); if(cin.eof()) return true; throw new InvalidChoiceException(); } cin.ignore(numeric_limits<streamsize>::max(),'\n'); switch (choice) { case LIST: list(); break; case MAKE: make_chall(); break; case RELEASE: release_chall(); break; case BREAK: break_chall(); break; case SOLVE: solve_chall(); break; case QUIT: return true; default: throw new InvalidChoiceException(choice); } return false; } extern void* __stack_chk_guard; extern "C" void __real___stack_chk_fail(); extern "C" void __wrap___stack_chk_fail() { throw new SSP(); } extern "C" void enter_flag(char *ptr) { std::cout << "Enter flag: " << std::flush; if (scanf("%s", ptr) == EOF) { throw new InvalidFlagException(); } } int main() { cout << "Welcome to the exceptionally good CTF Simulator 9000++!" << endl; CTF *ctf = new CTF(); ctf->play(); }
true
705647910bcf669efe421b940303b027c51dd7a6
C++
ueclectic/step-homeworks
/Cpp/wapi_exam/AlarmDll/AlarmDlg.cpp
UTF-8
2,201
2.59375
3
[]
no_license
#include "AlarmDlg.h" AlarmDlg* AlarmDlg::ptr = nullptr; AlarmDlg::AlarmDlg(std::wstring action, const time_t alarmTime) { ptr = this; mAction = action; mAlarm = alarmTime; } BOOL CALLBACK AlarmDlg::DlgProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { HANDLE_MSG(hWnd, WM_CLOSE, ptr->Cls_OnClose); HANDLE_MSG(hWnd, WM_INITDIALOG, ptr->Cls_OnInitDialog); HANDLE_MSG(hWnd, WM_COMMAND, ptr->Cls_OnCommand); } return FALSE; } BOOL AlarmDlg::Cls_OnInitDialog(HWND hWnd, HWND hwndFocus, LPARAM lParam) { mhDlg = hWnd; HWND hYear = GetDlgItem(hWnd, IDC_YEAR); HWND hMonth = GetDlgItem(hWnd, IDC_MONTH); HWND hDay = GetDlgItem(hWnd, IDC_DAY); HWND hHour = GetDlgItem(hWnd, IDC_HOUR); HWND hMin = GetDlgItem(hWnd, IDC_MIN); if (mAction == L"Add") { SetWindowText(mhDlg, L"Add alarm"); mAlarmTime = new DateTime(hYear, hMonth, hDay, hHour, hMin); } else if (mAction == L"Edit") { SetWindowText(mhDlg, L"Edit alarm"); mAlarmTime = new DateTime(hYear, hMonth, hDay, hHour, hMin, mAlarm); } else if (mAction == L"View") { SetWindowText(mhDlg, L"View alarm"); mAlarmTime = new DateTime(hYear, hMonth, hDay, hHour, hMin, mAlarm); for (int i = 0; i < 5; ++i) { EnableWindow(GetDlgItem(mhDlg, IDC_YEAR+i), FALSE); } } return TRUE; } void AlarmDlg::Cls_OnCommand(HWND hWnd, int id, HWND hwndCtl, UINT codeNotify) { if (codeNotify == CBN_SELCHANGE || codeNotify == EN_KILLFOCUS) { mAlarmTime->CheckLastDay(); return; } if (id == IDC_OK) { if (mAction == L"View") EndDialog(hWnd, 0); try { mAlarm = mAlarmTime->GetDateTime(); time_t now; time(&now); if (mAlarm <= now) { MessageBox(hWnd, L"Time is up!", L"Correct record", MB_OK | MB_ICONEXCLAMATION); return; } } catch (wchar_t* err) { MessageBox(hWnd, L"Incorrect date/time!", L"Error", MB_OK | MB_ICONEXCLAMATION); mAlarm = 0; return; } EndDialog(hWnd, 0); } else if (id == IDC_CANCEL) { mAlarm = 0; EndDialog(hWnd, 0); } } void AlarmDlg::Cls_OnClose(HWND hWnd) { mAlarm = 0; EndDialog(mhDlg, 0); }
true
9c5e91ceb62761301b96d49dd06091add38ba629
C++
ncompere/Interpreter
/parser.hpp
UTF-8
1,409
3.28125
3
[]
no_license
#ifndef PARSER_HPP #define PARSER_HPP #include <exception> #include <string> /* Token type */ enum TOKEN { TOKEN_OPEN, TOKEN_CLOSE, TOKEN_VAR, TOKEN_PRINT, TOKEN_ERROR, TOKEN_INCREMENT, TOKEN_DECREMENT }; // des tokens ont été rajoutés ici /* Parser of a line of the asd2 language */ class parser { public: // constructor parser(); /* Parsing function that returns a token given a line of a program: - T_OPEN for an opening brace { - T_CLOSE for a closing brace } - T_VAR for the declaration of a variable of the form 'var value' - T_PRINT for a printing instruction of the form '> var' - T_ERROR for a parsing error */ TOKEN parse(const std::string& line); /* Returns the variable name from the last call to parse if it returned T_VAR or T_PRINT; throws an exception std::logic_error() otherwise */ std::string var() const; /* Returns the variable value from the last call to parse if it returned T_VAR ; throws an exception std::logic_error() otherwise */ int value() const; /* Returns the error message from the last call to parse if it returned T_ERROR ; throws an exception std::logic_error() otherwise */ std::string error() const; private: TOKEN last_; // last token parsed std::string error_; // error message std::string var_; // variable name int value_; // variable value }; #endif
true
e1fd01a8a7c8c0f3544a1337d4165853e641f89a
C++
YIUECHEN/Practice
/第一个只出现一次的字符/第一个只出现一次的字符/test.cpp
UTF-8
717
3.109375
3
[]
no_license
#include<iostream> #include<string> #include<map> using namespace std; //int FirstNotRepeatingChar(string str) { // if (str.size() == 0){ // return -1; // } // char ch[256] = { 0 }; // for (int i = 0; i<str.size(); i++){ // ch[str[i]]++; // } // for (int i = 0; i<str.size(); i++){ // if (ch[str[i]] == 1){ // return i; // } // } // return -1; //} int FirstNotRepeatingChar(string str) { if (str.size() == 0) return -1; map<char, int> m; for (int i = 0; i < str.size(); i++){ m[str[i]]++; } for (int i = 0; i < str.size(); i++){ if (m[str[i]] == 1){ return i; } } return -1; } int main(){ string str = "nbsfdgssdsnbserty"; int k=FirstNotRepeatingChar(str); cout << k << endl; return 0; }
true
846e686a4a69985a2675b6813d397e377f3914d1
C++
stauntonknight/algorithm
/euler/39.cc
UTF-8
582
2.78125
3
[]
no_license
#include <iostream> #include <cstdio> #include <vector> #include <map> #include <cmath> using namespace std; int P = 1000; int main() { map<int, int> count; int total = 0; int p = 0; for (int i = 1; i < P/2 ; i++) { for (int j = 1; j < i ; ++j ){ int zs = i * i - j * j; int z = sqrt (zs); if (z >= j && z * z == zs) { int peri = j + z + i; count[peri]++; int total_curr = count[peri]; if ( total_curr > total ) { total = total_curr; p = peri; } } } } cout << p << endl; }
true
839c4f5f87d613d864b247dea243d5d769314c77
C++
subnr01/stapi
/fork.h
UTF-8
699
2.734375
3
[]
no_license
#ifndef FORK_H #define FORK_H #include <unistd.h> #include <signal.h> #include <errno.h> class Fork { private: pid_t pid; pid_t parent; static Fork * instance; static void Signal(int sig); protected: void SignalParent(int sig); virtual void Execute(void)=0; virtual void OnHangup(void) {}; virtual void OnInterrupt(void) {}; virtual void OnTerminate(void) {}; public: Fork(void); ~Fork(void); void Start(void) throw(int&); void Kill(int sig = SIGINT) throw(int&); void Detach(void); pid_t getChildPid(void); pid_t getParentPid(void); }; #endif//FORK_H
true
f93d68f5fc42a51484259f0590a47ef87cfa3904
C++
rishirv/competitive-programming
/USACO Training/4/4.3/race3/r.cpp
UTF-8
1,489
2.828125
3
[]
no_license
/* ID: verma.r1 PROG: race3 LANG: C++11 */ #include <fstream> #include <deque> #include <vector> using namespace std; ifstream cin ("race3.in"); ofstream cout ("race3.out"); vector<int> to[50]; vector<int> from[50]; vector<int> unavoidable; vector<int> splitting; int n=0; void isSplitting(int x, bool visit0[]){ deque<int> d; bool visited[n] {false}; d.push_back(x); while(!d.empty()){ int last = d.back(); d.pop_back(); for(int i: to[last]){ if(visit0[i]){ return; } if(!visited[i] && !(i == n-1)){ visited[i]=true; d.push_back(i); } } } splitting.push_back(x); } void isUnavoidable(int x){ deque<int> d; bool visited[n] {false}; visited[0]=true; d.push_back(0); while(!d.empty()){ int last = d.back(); d.pop_back(); for(int i: to[last]){ if(i == n-1){ return; } if(!visited[i] && !(i == x)){ visited[i]=true; d.push_back(i); } } } unavoidable.push_back(x); isSplitting(x, visited); } int main(){ int x; while(true){ cin>>x; if(x==-2) ++n; else if(x==-1) break; else{ to[n].push_back(x); from[x].push_back(n); } } for(int i=1; i<n; i++){ isUnavoidable(i); } cout<<unavoidable.size(); for(int i : unavoidable){ cout<<' '<<i; } cout<<endl; cout<<splitting.size(); for(int i : splitting){ cout<<' '<<i; } cout<<endl; }
true
5d9c2ef022c0b1969059f1e3931a352ccd2cfca1
C++
yk220284/chess
/util.cpp
UTF-8
2,369
3.578125
4
[]
no_license
#include "util.hpp" /* ----Piece/Player Color---- */ std::ostream& operator<<(std::ostream& out, Color color) { switch (color) { case Color::white: out << "White"; break; case Color::black: out << "Black"; break; } return out; } /* ----Piece Type---- */ std::ostream& operator<<(std::ostream& out, PieceType type) { switch (type) { case PieceType::king: out << "King"; break; case PieceType::rook: out << "Rook"; break; case PieceType::bishop: out << "Bishop"; break; case PieceType::queen: out << "Queen"; break; case PieceType::knight: out << "Knight"; break; case PieceType::pawn: out << "Pawn"; break; } return out; } /* ----Coordinates on Board---- */ Coor::Coor(int x, int y) : x(x), y(y) {} Coor::Coor() : Coor(8, 8) {} // Given no coordinates provided, both initialized to illegal values. Coor::Coor(std::string const& posStr) : Coor(posStr[0] - 'A', posStr[1] - '1') { } bool Coor::withInBoard() const { return (x >= 0) && (x < 8) && (y >= 0) && (y < 8); } std::string Coor::str() const { return std::string( {static_cast<char>('A' + x), static_cast<char>('1' + y)}); } std::ostream& operator<<(std::ostream& out, Coor const& coor) { out << coor.str(); return out; } bool validPosStr(std::string const& posStr) { if (posStr.size() != 2) { // Invalid length. return false; } Coor coor{posStr}; if (!coor.withInBoard()) { return false; } return true; } Coor operator+(Coor const& lhs, Coor const& rhs) { auto rlt = lhs; rlt.x += rhs.x; rlt.y += rhs.y; return rlt; } Coor& Coor::operator+=(Coor const& rhs) { this->x += rhs.x; this->y += rhs.y; return *this; } bool operator==(Coor const& lhs, Coor const& rhs) { return lhs.x == rhs.x && lhs.y == rhs.y; } bool operator!=(Coor const& lhs, Coor const& rhs) { return !(lhs == rhs); } Coor findDirection(Coor const& start, Coor const& end) { auto dir = [](int s, int e) { if (s < e) { return 1; } else if (s == e) { return 0; } else // s > e { return -1; } }; return Coor(dir(start.x, end.x), dir(start.y, end.y)); }
true
adace6a5e6d63c4d1573279a15e4fc418a5c2e27
C++
vasilegroza/SI
/Tema1/Ex1/criptor.cpp
UTF-8
2,798
3.125
3
[]
no_license
#include <stdlib.h> #include <string.h> #include <iostream> #include "file_service.h" #include "over_AES_service.h" #include <time.h> #include <string> using namespace std; bool validate_input(char *file_in, char *file_out, char *mode) { if (!file_exists(file_in)) { perror(file_in); return false; } if (strcmp(mode, "ECB") != 0 && strcmp(mode, "CBC") != 0) { perror("Your encryption mode is not suported yet"); return false; } return true; } int main() { vector <string> dictionary = read_dictionary((char *) "word_dict.txt"); char *response = (char *) malloc(10), *file_in = (char *) malloc(50), *file_out = (char *) malloc(50), *mode = (char *) malloc(10), *word;// = (char *) dictionary[random_index].c_str(); while (true) { srand(time(NULL)); int random_index = rand() % dictionary.size(); // printf("Index of key is:%d", random_index); word = (char *) dictionary[random_index].c_str(); printf("So you want to encrypt something huh?[Y/N]>>"); scanf("%s", response); bool want_to_ecrypt = true; if (strcmp(response, (char *) "Y") == 0 || strcmp(response, (char *) "y") == 0) want_to_ecrypt = true; if (strcmp(response, (char *) "N") == 0 || strcmp(response, (char *) "n") == 0) want_to_ecrypt = false; if (!want_to_ecrypt) break; printf("\n Then give me some inputs:\n\t1.InputFile\n\t2.OutputFile\n\t3.Encryption Mode (ECB/CBC)\n"); printf("1>>"); scanf("%s", file_in); printf("2>>"); scanf("%s", file_out); printf("3>>"); scanf("%s", mode); trim(file_in); trim(file_out); trim(mode); bool valid_input = validate_input(file_in, file_out, mode); if (not valid_input) { printf("Try again and give some valid inputs\n"); continue; } char *plaintext = read_file(file_in); int text_length = strlen(plaintext); unsigned char *key_data; key_data = (unsigned char *) complete_to_16(word); printf("key:'%s'\n", key_data); unsigned char *ciphertext; if (strcmp(mode, "ECB") == 0) ciphertext = encrypt_aes_ecb((unsigned char *) plaintext, &text_length, key_data); if (strcmp(mode, "CBC") == 0) ciphertext = encrypt_aes_cbc((unsigned char *) plaintext, &text_length, key_data); FILE *file = fopen(file_out, "w"); fprintf(file, "%s", (const char *) ciphertext); fclose(file); printf("####file:%s==>%s was encrypted successfully with key:%s\n", file_in, file_out, key_data); } printf("See you again\n"); return 0; }
true
726e06dfc5a4c5a0087cf3f0be19d51fbedf18c6
C++
Mike2208/Monte_Carlo
/Monte_Carlo/map_2d_bool.h
UTF-8
1,701
3.03125
3
[]
no_license
#ifndef MAP_2D_BOOL_H #define MAP_2D_BOOL_H #include "map_2d.h" template<> class Map2D<bool> { public: typedef std::vector<bool> CELL_STORAGE; typedef bool CELL_TYPE; Map2D(const POS_2D_TYPE &NewWidth, const POS_2D_TYPE &NewHeight, const bool &DefaultCellValue) : _Height(NewHeight), _Width(NewWidth), _CellData(NewHeight*NewWidth) { this->ResetMap(NewWidth, NewHeight, DefaultCellValue); } Map2D() = default; Map2D(const Map2D &S) = default; Map2D(Map2D &&S) = default; Map2D &operator=(const Map2D &S) = default; Map2D &operator=(Map2D &&S) = default; void ResizeMap(const POS_2D_TYPE &NewWidth, const POS_2D_TYPE &NewHeight); void ResetMap(const POS_2D_TYPE &NewWidth, const POS_2D_TYPE &NewHeight, const bool &DefaultCellValue); virtual void SetMapToValue(const bool Value); virtual void SetPixel(const POS_2D &Position, const bool &Value); //bool &GetPixelR(const POS_2D &Position); virtual bool GetPixel(const POS_2D &Position) const; virtual int GetPixel(const POS_2D &Position, bool &Value) const; virtual void SetPathToValue(const POS_2D &StartPos, const POS_2D &EndPos, const bool&Value); // Set the path from StartPos to EndPod to the given value virtual POS_2D_TYPE GetHeight() const; virtual POS_2D_TYPE GetWidth() const; // Gets entire cell storage ( usefull for parsing entire map ) const CELL_STORAGE &GetCellStorage() const; CELL_STORAGE &GetCellStorageR(); virtual void PrintMap(const char *FileName) const; virtual bool IsInMap(const POS_2D &Position) const; protected: POS_2D_TYPE _Height; // Map height POS_2D_TYPE _Width; // Map width CELL_STORAGE _CellData; // Data in cells }; #endif // MAP_2D_BOOL_H
true
3448644d6fd04ea607affa5476f913c853eea6bb
C++
kenziecalvert1/FreshmenYear
/CS162/Assignment 4/onix.cpp
UTF-8
1,169
2.640625
3
[]
no_license
/********************************************************************* ** Program Filename:onix.cpp ** Author:McKenzie Calvert ** Date:May 29,2017 ** Description:determines if the onix is captured or not ** Input:the field calls this ** Output:true or false *********************************************************************/ #include"./onix.h" /********************************************************************* ** Function:cave defualt constructor ** Description:this is the stuff that the cave goes off of ** Parameters:none ** Pre-Conditions:none ** Post-Conditions:none *********************************************************************/ Onix::Onix(){ type="onix"; #ifdef DEBUG cout << "onix constructor" << endl; #endif } /********************************************************************* ** Function:cave defualt constructor ** Description:this is the stuff that the cave goes off of ** Parameters:none ** Pre-Conditions:none ** Post-Conditions:none *********************************************************************/ void Onix::operator=(const Onix& temp){ level=temp.level; type=temp.type; }
true
b451f552ca4184e55dc33f5cd0d0b61c97a04a65
C++
pytorch/pytorch
/torch/csrc/api/src/nn/modules/padding.cpp
UTF-8
3,708
2.515625
3
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-secret-labs-2011", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
#include <torch/nn/modules/padding.h> #include <torch/expanding_array.h> namespace F = torch::nn::functional; namespace torch { namespace nn { template <size_t D, typename Derived> ReflectionPadImpl<D, Derived>::ReflectionPadImpl( const ReflectionPadOptions<D>& options_) : options(options_) {} template <size_t D, typename Derived> void ReflectionPadImpl<D, Derived>::reset() {} template <size_t D, typename Derived> Tensor ReflectionPadImpl<D, Derived>::forward(const Tensor& input) { return F::detail::pad(input, options.padding(), torch::kReflect, 0); } template <size_t D, typename Derived> void ReflectionPadImpl<D, Derived>::pretty_print(std::ostream& stream) const { stream << "torch::nn::ReflectionPad" << D << "d" << "(padding=" << options.padding() << ")"; } template class ReflectionPadImpl<1, ReflectionPad1dImpl>; template class ReflectionPadImpl<2, ReflectionPad2dImpl>; template class ReflectionPadImpl<3, ReflectionPad3dImpl>; // ============================================================================ template <size_t D, typename Derived> ReplicationPadImpl<D, Derived>::ReplicationPadImpl( const ReplicationPadOptions<D>& options_) : options(options_) {} template <size_t D, typename Derived> void ReplicationPadImpl<D, Derived>::reset() {} template <size_t D, typename Derived> Tensor ReplicationPadImpl<D, Derived>::forward(const Tensor& input) { return F::detail::pad(input, options.padding(), torch::kReplicate, 0); } template <size_t D, typename Derived> void ReplicationPadImpl<D, Derived>::pretty_print(std::ostream& stream) const { stream << "torch::nn::ReplicationPad" << D << "d" << "(padding=" << options.padding() << ")"; } template class ReplicationPadImpl<1, ReplicationPad1dImpl>; template class ReplicationPadImpl<2, ReplicationPad2dImpl>; template class ReplicationPadImpl<3, ReplicationPad3dImpl>; // ============================================================================ template <size_t D, typename Derived> ZeroPadImpl<D, Derived>::ZeroPadImpl(const ZeroPadOptions<D>& options_) : options(options_) {} template <size_t D, typename Derived> void ZeroPadImpl<D, Derived>::reset() {} template <size_t D, typename Derived> Tensor ZeroPadImpl<D, Derived>::forward(const Tensor& input) { return F::detail::pad(input, options.padding(), torch::kConstant, 0); } template <size_t D, typename Derived> void ZeroPadImpl<D, Derived>::pretty_print(std::ostream& stream) const { stream << "torch::nn::ZeroPad" << D << "d" << "(padding=" << options.padding() << ")"; } template class ZeroPadImpl<1, ZeroPad1dImpl>; template class ZeroPadImpl<2, ZeroPad2dImpl>; template class ZeroPadImpl<3, ZeroPad3dImpl>; // ============================================================================ template <size_t D, typename Derived> ConstantPadImpl<D, Derived>::ConstantPadImpl( const ConstantPadOptions<D>& options_) : options(options_) {} template <size_t D, typename Derived> void ConstantPadImpl<D, Derived>::reset() {} template <size_t D, typename Derived> Tensor ConstantPadImpl<D, Derived>::forward(const Tensor& input) { return F::detail::pad( input, options.padding(), torch::kConstant, options.value()); } template <size_t D, typename Derived> void ConstantPadImpl<D, Derived>::pretty_print(std::ostream& stream) const { stream << "torch::nn::ConstantPad" << D << "d" << "(padding=" << options.padding() << ", value=" << options.value() << ")"; } template class ConstantPadImpl<1, ConstantPad1dImpl>; template class ConstantPadImpl<2, ConstantPad2dImpl>; template class ConstantPadImpl<3, ConstantPad3dImpl>; } // namespace nn } // namespace torch
true
5cc2be8d40cae01e2c7c71e5049dae5f283ce76b
C++
MannoverBoard/CPE212
/utilities/print_utilities.h
UTF-8
596
3.1875
3
[]
no_license
#ifndef PRINT_UTILITIES #define PRINT_UTILITIES #include <ostream> #include <sstream> template<typename T,size_t R,size_t C> std::string toString(const T(&a)[R][C]) { std::ostringstream os; os << '['; for(size_t r;r<R;++r) { os << '['; for(size_t c;c<(C-1);++c) { os << a[r][c] << ','; } os << a[r][C-1] << ']' #ifdef PRINT_ARRAYS_WITH_NEWLINES << '\n' #endif ; } os << ']'; return os.str(); } template<typename T,size_t R,size_t C> std::ostream& operator<<(std::ostream& os, const T(&a)[R][C]) { os << toString(a); return os; } #endif
true
b5de83c62b3962982e0818984eff272f1bcb5ea2
C++
maks1401/Laboratory
/№28 (последовательные контейнеры библиотеки STL)/№28 №3/№28 №3.cpp
UTF-8
2,373
3.234375
3
[]
no_license
//Трегубов Максим, лаб. №28, задача №3 #include <iostream> #include <vector> #include <ctime> #include <cstdlib> #include <cmath> #include "list.h" using namespace std; void main() { setlocale(LC_ALL, "ru"); srand(time(0)); int amount; cout << "Введите количество списокв: "; cin >> amount; vector <list> v; for (int i = 0; i < amount; i++) { cout << "Введите 3 элементов " << i + 1 << "-ого списка: " << endl; list a(3); cin >> a; v.push_back(a); } cout << "Вектор:" << endl; for (vector<list>::iterator i = v.begin(); i != v.end(); i++) cout << *i; list max = *v.begin(); cout << endl << max; for (vector<list>::iterator i = v.begin()+1; i != v.end(); i++) { if (max < *i) max=*i; } cout << endl << "Максимальный элемент вектора: " << max << endl; vector<list>::iterator v1 = v.begin(); cout << "Введите индекс, на который хотите добавить максмиальное значение: "; int p; cin >> p; if (p > v.size()) cout << "Вы привысили длину вектора" << endl; else { for (int j = 0; j < p; j++) v1++; v.insert(v1, max); } cout << "Векор:" << endl; for (vector<list>::iterator i = v.begin(); i != v.end(); i++) cout << *i << " "; for (vector<list>::iterator i = v.begin(); i != v.end(); i++) * i = *i * max; cout<<endl << "Вектор после умножение на максимальный элемент:" << endl; for (vector<list>::iterator i = v.begin(); i != v.end(); i++) cout << *i << " "; list sm = *v.begin(); for (vector<list>::iterator i = v.begin()+1; i != v.end(); i++) { list smm = *i; sm = sm + smm; } cout <<endl << "Cумма: "<< sm; list armean = sm / v.size(); cout << endl << "Среднее арифмитическое вектора: " << armean << endl; vector<list> vec; for (vector<list>::iterator i = v.begin(); i != v.end(); i++) if (*i < armean) vec.push_back(*i); cout << "Вектор после удаления всех элементов больше среднего арифмитического:" << endl; for (vector<list>::iterator i = vec.begin(); i != vec.end(); i++) cout << *i << " "; cout << endl; }
true
a241ce1e87c9bccb38ae015a78b894460ce016ba
C++
GreateLi/cross-platform-multithreading
/ThreadDemo/ThreadDemo/MyAutoLock.h
UTF-8
409
2.5625
3
[]
no_license
#pragma once #ifndef _MY_AUTO_LOCK_H #define _MY_AUTO_LOCK_H #ifdef _WIN32 #include<windows.h> #else #include <pthread.h> #endif #include "MyMutex.h" class AutoLock { private: MyMutex *m_mutex; public: AutoLock(MyMutex * mutex) : m_mutex(mutex) { if (m_mutex) m_mutex->lock(); } ~AutoLock() { if (m_mutex) m_mutex->unlock(); } }; #endif //_MY_AUTO_LOCK_H
true
965043ef310b6290fa34ecccadee9e1f663fd13a
C++
NicolasMDuarte/Pibic20192020
/ProjetoArduino/sensores e componentes/mq135/mq135.ino
UTF-8
454
2.703125
3
[ "MIT" ]
permissive
#define MQ_analog A0 #define MQ_dig 4 int valor_analog; int valor_dig; void setup() { Serial.begin(9600); pinMode(MQ_analog, INPUT); pinMode(MQ_dig, INPUT); } void loop() { valor_analog = analogRead(MQ_analog); valor_dig = digitalRead(MQ_dig); Serial.print(valor_analog); Serial.print(" || "); if(valor_dig == 0) Serial.println("GAS DETECTADO !!!"); else Serial.println("GAS AUSENTE !!!"); delay(500); }
true
4fb76c76e24cba70b6c831c3d89d27896843116f
C++
bk211/Projet-POO-M1
/lib/Parseur.cpp
UTF-8
2,091
3.015625
3
[ "MIT" ]
permissive
#include "../libCardGame.hpp" Parseur::Parseur(std::string filename, const int nb_column, const bool strict) : filename(filename), nb_column(nb_column), strict_reading(strict) { //debug //std::cout<< "filename = <"<< filename<<">\n"; std::ifstream ifs(filename); if(!ifs.good()){ throw std::invalid_argument("No such file <" + filename+">"); } std::string buffer; while(std::getline(ifs, buffer)){ if(buffer.size() == 0) continue; std::vector<std::string> vec; //std::cout<<"buffer ="<<buffer<<" size = "<<buffer.size()<<std::endl; vec = split(buffer, delim); //debug //for (auto s : vec){std::cout<<s<<", ";} //std::cout <<std::endl; lignes.push_back(vec); } ifs.close(); } std::vector<std::string> Parseur::split(std::string s, char delim) { std::string line; std::vector<std::string> vec; std::stringstream ss(s); while(std::getline(ss, line, delim)) { vec.push_back(line); } return vec; } void Parseur::print_lines() const{ for (auto ligne: lignes){ for (auto word : ligne){ std::cout<<word<<", "; } std::cout<<std::endl; } } std::vector<std::vector<std::string>> Parseur::get_lignes(){ return lignes; } Parseur::~Parseur(){} void Parseur::setFilename(std::string fn){ filename = fn; } void Parseur::setNbColumn(int nb){ nb_column = nb; } Parseur::Parseur():nb_column(0),strict_reading(true){ } void Parseur::parse(){ std::ifstream ifs(filename); if(!ifs.good()){ throw std::invalid_argument("No such file <" + filename+">"); } ifs.close(); std::string buffer; while(std::getline(ifs, buffer)){ if(buffer.size() == 0) continue; std::vector<std::string> vec; //std::cout<<"buffer ="<<buffer<<" size = "<<buffer.size()<<std::endl; vec = split(buffer, delim); //debug //for (auto s : vec){std::cout<<s<<", ";} //std::cout <<std::endl; lignes.push_back(vec); } ifs.close(); }
true
1b2907115100a687b5787d990035e970e9822219
C++
Relag/Minigolf_Dungeon_Submission
/Minigolf Dungeon Code/NetworkManager.cpp
UTF-8
1,635
3.15625
3
[]
no_license
#include "NetworkManager.h" // Check to see if there can be a connection made void NetworkManager::CheckConnection() { // Start of the CheckConnection function // try the connection try { Connect(); // Calling the TCP Connection for the CLIENT (Game) to Server (Database) } catch (exception error) { // display error } } // End of the CheckCollision function // The client connecting the server connection void NetworkManager::Connect() { // Start of the Connect function ip.getLocalAddress(); socket.connect(ip, 3030); cout << "Connecting"; } // End of the Connect function // Displays the type of Error message in the command line void NetworkManager::SQLError(unsigned int handletype, const SQLHANDLE& handle) { // Start of the SQLError function SQLCHAR SQLState[1024]; SQLCHAR message[1024]; if (SQL_SUCCESS == SQLGetDiagRec(handletype, handle, 1, SQLState, NULL, message, 1024, NULL)) { // Start of the if statement // printing out the error to the command line cout << "SQL Error Message: " << message << "+\nSQLState: " << SQLState << "." << endl; } // End of the if statement } // End of the SQLError function //The server that runs until application or connection is broken /* void Engine::TCPConnection() { // Start of the TCPConnection function // TCPListener to listen for a connection TcpListener listener; // continous loop of the server connection while (true) { listener.listen(10000); //listen for the connection from the client listener.accept(socket); // Accepting the found TCP socket connection, if found } */ //} // End of the TCPConnection function
true
3d8541b683487a7b315c6bf347b10bc1457fb758
C++
IgorMoiseev1988/Like_permutation
/main.cpp
UTF-8
4,687
3.25
3
[]
no_license
#include <vector> #include <string> #include <iostream> #include <algorithm> #include <numeric> #include <array> #include <cstdlib> #include <ctime> #include <set> using namespace std::string_literals; template<typename T> std::ostream& operator<< (std::ostream& os, std::vector<T> v) { os << "["s; bool first {true}; for (const auto& elem : v) { if (!first) os << " "; os << elem; first = false; } os << "]"s; return (os); } template<typename OutputIt, typename ForwardIt> bool next_value(OutputIt iterator, ForwardIt first, ForwardIt last) { auto it = std::find(first, last, *iterator); if (it == last || it == std::prev(last)) { *iterator = *first; return (true); } *iterator = *(std::next(it)); return (false); } template<typename OutputIt, typename ForwardIt> bool prev_value(OutputIt iterator, ForwardIt first, ForwardIt last) { auto it = std::find(first, last, *iterator); if (it == first) { *iterator = *(std::prev(last)); return (true); } *iterator = *(std::prev(it)); return (false); } template<typename InputIt1, typename InputIt2> bool end_permutation(InputIt1 first, InputIt1 last, InputIt2 control) { typedef typename std::iterator_traits<InputIt1>::value_type T; return (std::all_of(first, last, [control](const T& t) { return (t == *control); })); } template<typename InputIt1, typename InputIt2> bool start_permutation(InputIt1 first, InputIt1 last, InputIt2 control) { typedef typename std::iterator_traits<InputIt1>::value_type T; return (std::all_of(first, last, [control](const T& t) { return (t == *control); })); } template <typename ForwardIt1, typename ForwardIt2> bool non_sorted_includes(ForwardIt1 container_first, ForwardIt1 container_last, ForwardIt2 values_first, ForwardIt2 values_last) { for (; container_first != container_last; ++container_first) { if (std::find(values_first, values_last, *container_first) == values_last) return (false); } return (true); } template <typename T> bool is_difference_types(const T&, const T&) { return (false); } template <typename T, typename U> bool is_difference_types(const T&, const U&) { return (true); } template<typename InputIt1, typename InputIt2> bool is_valid_containers(InputIt1 container_first, InputIt1 container_last, InputIt2 values_first, InputIt2 values_last) { typename std::iterator_traits<InputIt1>::difference_type container_size = std::distance(container_first, container_last); typename std::iterator_traits<InputIt2>::difference_type values_size = std::distance(values_first, values_last); if (container_size == 0 || values_size == 0) return false; if (is_difference_types(container_first, values_first)) { std::cerr << "Containers must have same types\n"s; return (false); } if (!(non_sorted_includes(container_first, container_last, values_first, values_last))) { std::cerr << "First container must only contains values from second container\n"s; return (false); } return (true); } template<typename OutputIt, typename ForwardIt> bool next_limit_permutation(OutputIt container_first, OutputIt container_last, ForwardIt values_first, ForwardIt values_last) { typename std::iterator_traits<OutputIt>::difference_type container_size = std::distance(container_first, container_last); if (!is_valid_containers(container_first, container_last, values_first, values_last)) return false; if (end_permutation(container_first, container_last, std::prev(values_last))) return false; while ((container_size > 0) && (next_value(container_first + --container_size, values_first, values_last))); return container_size >= 0; } template<typename OutputIt, typename ForwardIt> bool prev_limit_permutation(OutputIt container_first, OutputIt container_last, ForwardIt values_first, ForwardIt values_last) { typename std::iterator_traits<OutputIt>::difference_type container_size = std::distance(container_first, container_last); if (!is_valid_containers(container_first, container_last, values_first, values_last)) return false; if (start_permutation(container_first, container_last, values_first)) return false; while ((container_size > 0) && (prev_value(container_first + --container_size, values_first, values_last))); return container_size >= 0; } //for example int main() { std::vector<int> values {1, 3, 5}; std::vector<int> arr {1, 3}; int count {0}; do { std::cout << ++count << ": "s << arr << "\n"s; } while (next_limit_permutation(arr.begin(), arr.end(), values.begin(), values.end())); do { std::cout << ++count << ": "s << arr << "\n"; } while (prev_limit_permutation(arr.begin(), arr.end(), values.begin(), values.end())); return 0; }
true
d046e3d0fd4bb823db6868b5a54d90d58d072cbc
C++
SHITHANSHU/LeetCode30DaysChallenge
/LeetCode30DaysChallengeMay2020/Week1/RansomeNote.cpp
UTF-8
2,824
3.671875
4
[]
no_license
/* Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false. Each letter in the magazine string can only be used once in your ransom note. Note: You may assume that both strings contain only lowercase letters. canConstruct("a", "b") -> false canConstruct("aa", "ab") -> false canConstruct("aa", "aab") -> true */ // solution /* Here we are given 2 strings and we are asked that can we generate first string from the second string Here we can use the logic and code of out previous problem "JewelsAndStones" this can be solved in O(n) time where n is length of the string The logic used here is that we count occurence of each character in first string (ransome) and store it in an array here array arr then count the occurence of ecah character in string 2 (magazine) and store it in another array arr2 now iterate through each values of both arrays if there are 3 a's in ransome and 2 a's in magazien then obviously you cannot generate the ransome message i.e for each character a b c d ... count of occurence in array 1 has to be strictly less than or equal to their occurence in magazine and if you iterate through all the values without returning false then return true Time Complexity O(n) where n is length of max of length of ransome and magazine strings Sapce Complexity O(1) as its idependent of length of string */ // Solution Code class Solution { public: bool canConstruct(string ransomNote, string magazine) { string J=ransomNote; string S=magazine; int arr[52]; // setup array 1 to keep track of characters of ransom int arr2[52]; // setup array 2 to keep track of characters of magazine for(int i=0;i<52;i++) { arr[i]=0; arr2[i]=0; } int a1=(int) 'A'; int a2=(int) 'a'; for(int i=0;i<J.length();i++) { int v=(int) J[i]; if(v>90) { int k=v-a2; arr[k]+=1; } else { int k=v-a1; arr[k+26]+=1; } } for(int i=0;i<S.length();i++) { int v=(int) S[i]; if(v>90) { int k=v-a2; arr2[k]+=1; } else { int k=v-a1; arr2[k+26]+=1; } } for(int i=0;i<52;i++) { if(arr2[i]<arr[i]) return false; } return true; } };
true
e6a9ea066de8611daef6347c901217bedfba1dec
C++
ailyanlu/my-acm-solutions
/leetcode/sqrtx.cc
UTF-8
774
3.171875
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> using std::vector; #define ABS(X) ((X) > 0 ? (X) : -(X)) static const float EPSILON = 0.000000001; class Solution { public: int sqrt(int x) { if (x == 0) { return x; } float dividend = x, divisor = x, prev; do { prev = divisor; divisor = (divisor + dividend / divisor) / 2; } while (ABS(divisor - prev) > EPSILON); int result = static_cast<int>(divisor); if (result * result > x) { --result; } return result; } }; Solution solu; vector<int> option; int main() { std::cout << solu.sqrt(12345) << std::endl; std::cout << solu.sqrt(123456789) << std::endl; return 0; }
true
4a0658351def00176e01ec3d4bc1698e1c35a44b
C++
SSU-SSORA/2017_CppAdvanced
/8장/PROGRAM8_5.cpp
UHC
976
3.546875
4
[]
no_license
#include <iostream> #include <string> struct W { W(int &, int&) { std::cout << "W(int&,int&)" << std::endl; } }; struct X { X(const int&, int&) { std::cout << "X(const int &, int&)" << std::endl; } }; struct Y { Y(int &, const int&) { std::cout << "Y(int&, const int&)" << std::endl; } }; struct Z { Z(const int&, const int &) { std::cout << "Z(const int&, const int&)" << std::endl; } }; /* // μ ϴ Լ ø template <typename T, typename A1, typename A2> T* factory(A1& a1, A2&a2) { return new T(a1, a2); } */ template<typename T, typename A1, typename A2> T* factory(A1&& a1, A2&& a2) { //return new T(std::forward<A1>(a1), std::forward<A2>(a2)); return new T(a1, a2); } int main() { int a = 4, b = 5; //Լ ȣϿ ü W* pw = factory<W>(a, b); X* px = factory<X>(2, b); Y* py = factory<Y>(a, 2); Z* pz = factory<Z>(2, 2); delete pw; delete px; delete py; delete pz; }
true
4fd0064b7abd48e3633d51b12f0dda070f7ce638
C++
destroierdam/Object-Oriented-Programming
/Lectures/27_05_2019/Alcohol.h
UTF-8
295
3.265625
3
[]
no_license
#pragma once #include "Drink.h" using std::cout; using std::endl; class Alcohol : public Drink { double alcohol; public: Alcohol() { this->alcohol = 50; } void drink() override { std::cout << "Drink with mood" << std::endl; } void getMaker() const { cout << "Vineks Preslav" << endl; } };
true
4a353ed5b22a333c875d4413f10f507b76287083
C++
robinhoodmarkets/engine
/slack/web/oauth.access.h
UTF-8
2,595
2.671875
3
[ "MIT" ]
permissive
// // engine // // Copyright © 2015–2016 D.E. Goodman-Wilson. All rights reserved. // #pragma once #include <slack/types.h> #include <slack/set_option.h> #include <slack/base/response.h> #include <string> #include <vector> #include <slack/optional.hpp> namespace slack { namespace oauth { class access : public slack::base::response { public: //public interface template<class TOKEN, class CLIENT_ID, class CLIENT_SECRET, class CODE, typename ...Os> access(TOKEN &&token, CLIENT_ID &&client_id, CLIENT_SECRET &&client_secret, CODE &&code) : response{std::forward<TOKEN>(token)}, client_id_{std::forward<CLIENT_ID>(client_id)}, client_secret_{std::forward<CLIENT_SECRET>(client_secret)}, code_{std::forward<CODE>(code)} { initialize_(); } template<class TOKEN, class CLIENT_ID, class CLIENT_SECRET, class CODE, typename ...Os> access(TOKEN &&token, CLIENT_ID &&client_id, CLIENT_SECRET &&client_secret, CODE &&code, Os &&...os) : response{std::forward<TOKEN>(token)}, client_id_{std::forward<CLIENT_ID>(client_id)}, client_secret_{std::forward<CLIENT_SECRET>(client_secret)}, code_{std::forward<CODE>(code)} { slack::set_option<access>(*this, std::forward<Os>(os)...); initialize_(); } //parameters struct parameter { SLACK_MAKE_STRING_LIKE(redirect_uri); }; //errors struct error : public slack::base::error { static const std::string INVALID_CLIENT_ID; static const std::string BAD_CLIENT_SECRET; static const std::string INVALID_CODE; static const std::string BAD_REDIRECT_URI; }; //response struct bot_info { slack::user_id bot_user_id; slack::token bot_access_token; }; slack::token access_token; std::vector<slack::scope> scope; slack::user_id user_id; std::string team_name; slack::team_id team_id; std::experimental::optional<struct bot_info> bot; //parameter setters void set_option(const parameter::redirect_uri &redirect_uri) { redirect_uri_ = redirect_uri; } void set_option(parameter::redirect_uri &&redirect_uri) { redirect_uri_ = std::move(redirect_uri); } private: void initialize_(); std::string client_id_; std::string client_secret_; std::string code_; std::experimental::optional<parameter::redirect_uri> redirect_uri_; }; }} //namespace oauth slack
true
0078960186c043f33502d088ecbeb781dafa9ccf
C++
liyunfei1994/MyProject
/Learning_C++/access_permission.cpp
UTF-8
2,901
4.1875
4
[]
no_license
/* 2020年4月18日14:11:27 C++ 类成员的访问权限 C++通过 public、protected、private 三个关键字来控制成员变量和成员函数的访问权限, 它们分别表示公有的、受保护的、私有的, 被称为成员访问限定符。 所谓访问权限,就是你能不能使用该类中的成员。 Java、C# 程序员注意, C++ 中的 public、private、protected 只能修饰类的成员, 不能修饰类, C++中的类没有共有私有之分。 在类的内部(定义类的代码内部), 无论成员被声明为 public、protected 还是 private, 都是可以互相访问的, 没有访问权限的限制。 在类的外部(定义类的代码之外), 只能通过对象访问成员, 并且通过对象只能访问 public 属性的成员, 不能访问 private、protected 属性的成员。 只在类体中声明函数,而将函数定义放在类体外面 当成员函数定义在类外时,就必须在函数名前面加上类名予以限定。 ::被称为域解析符(也称作用域运算符或作用域限定符), 用来连接类名和函数名,指明当前函数属于哪个类。 成员函数必须先在类体中作原型声明, 然后在类外定义,也就是说类体的位置应在函数定义之前。 在类体中和类体外定义成员函数是有区别的: 在类体中定义的成员函数会自动成为内联函数,在类体外定义的不会。 内联函数一般不是我们所期望的,它会将函数调用处用函数体替代, 所以我建议在类体内部对成员函数作声明, 而在类体外部进行定义,这是一种良好的编程习惯, 实际开发中大家也是这样做的。 */ #include <iostream> using namespace std; //类的声明 class Student{ private: //私有的 /* 成员变量大都以m_开头,这是约定成俗的写法, 不是语法规定的内容。 以m_开头既可以一眼看出这是成员变量, 又可以和成员函数中的形参名字区分开。 */ char *m_name; int m_age; float m_score; public: //共有的 void setname(char *name); void setage(int age); void setscore(float score); void show(); }; //成员函数的定义 void Student::setname(char *name){ m_name = name; } void Student::setage(int age){ m_age = age; } void Student::setscore(float score){ m_score = score; } void Student::show(){ cout<<m_name<<" year is "<<m_age<<", score is "<<m_score<<endl; } int main(){ //在栈上创建对象 Student stu; stu.setname("Xiaoming"); stu.setage(15); stu.setscore(92.5f); stu.show(); //在堆上创建对象 Student *pstu = new Student; pstu -> setname("LiHua"); pstu -> setage(16); pstu -> setscore(96); pstu -> show(); return 0; }
true
0c28d2c9bb3113caebe8ce25043ac665e37b8dbd
C++
gzmnursena/veri_yapilari
/graphs/graphs2/main.cpp
UTF-8
2,661
3.78125
4
[]
no_license
#include <iostream> using namespace std; //Graf oluşturma... //bağlı liste elemanları tutar struct adjNode { int val, cost; adjNode* next; }; //kenarları saklamak için oluşturulan struct struct graphEdge { int start_ver, end_ver, weight; }; class DiaGraph{ //verilen graftaki bağlı listesine yeni düğümler ekle adjNode* getAdjListNode(int value, int weight, adjNode* head) { adjNode* newNode = new adjNode; newNode->val = value; newNode->cost = weight; newNode->next = head; //yeni düğümü geçerli başlığa yönlendir return newNode; } int dugumSayisi; //graftaki düğüm sayısı public: adjNode **head; //işaretçi dizisi olarak bağlı liste DiaGraph(graphEdge kenarlar[], int kenarSayisi, int dugumSayisi) { //constructor head = new adjNode*[dugumSayisi]();//yeni düğüm ekler this->dugumSayisi = dugumSayisi; for (int i = 0; i < dugumSayisi; ++i)//tüm köşeler için head işaretçisini başlatır head[i] = nullptr; //kenarları ekleyerek yönlendirilmiş graf oluşturma for (unsigned i = 0; i < kenarSayisi; i++) { int start_ver = kenarlar[i].start_ver; int end_ver = kenarlar[i].end_ver; int weight = kenarlar[i].weight; //başlangıçta ekler adjNode* newNode = getAdjListNode(end_ver, weight, head[start_ver]); head[start_ver] = newNode;//yeni düğüme head işaretçisini atar } } ~DiaGraph() {// destructor(yıkıcı) for (int i = 0; i < dugumSayisi; i++) delete[] head[i]; delete[] head; } }; // verilen tepe noktasının tüm bitişik köşelerini yazdır void display_AdjList(adjNode* ptr, int i) { while (ptr != nullptr) { cout << "(" << i << ", " << ptr->val << ", " << ptr->cost << ") "; ptr = ptr->next; } cout << endl; } int main() { // graf kenarlar dizisi graphEdge kenarlar[] = { // (x, y, w) -> edge from x to y with weight w {0,1,2},{0,2,4},{1,4,3},{2,3,2},{3,1,4},{4,3,3} }; int dugumSayisi = 6;//graftaki köşe noktası(dugum) sayısı int kenarSayisi = sizeof(kenarlar)/sizeof(kenarlar[0]);//graftaki kenar sayısını hesaplar DiaGraph diagraph(kenarlar, kenarSayisi, dugumSayisi);//graf oluşturur cout<<"(start_vertex, end_vertex, weight):"<<endl; for (int i = 0; i < dugumSayisi; i++)//bitişik liste grafının gösterimi { //komşu köşeleri gösterir display_AdjList(diagraph.head[i], i); } return 0; }
true
932c3d6d652eb36f72770df78f3d316f3d8309c8
C++
xyyyt/Aggregation-Processing-and-Visualisation
/Include/ConvertissorTemp.hpp
UTF-8
2,303
3.234375
3
[]
no_license
#ifndef CONVERTISSOR_TEMP_HPP_ # define CONVERTISSOR_TEMP_HPP_ # include "IConvertissor.hpp" namespace Convertissor { template <typename T = double, typename U = double> class ConvertissorTemp : public IConvertissor<T, U> { private : enum ConvertissorMode { FAHRENHEIT_TO_CELSIUS, CELSIUS_TO_FAHRENHEIT }; private : ConvertissorMode _convertissorMode; public : ConvertissorTemp(); virtual ~ConvertissorTemp(); virtual void setConvertissorMode(int); virtual int getConvertissorMode() const; virtual T convert(const U&) const; private : T convertFahrenheitToCelsius(const U&) const; T convertCelsiusToFahrenheit(const U&) const; }; template <typename T, typename U> ConvertissorTemp<T, U>::ConvertissorTemp() : _convertissorMode(FAHRENHEIT_TO_CELSIUS) { } template <typename T, typename U> ConvertissorTemp<T, U>::~ConvertissorTemp() { } template <typename T, typename U> void ConvertissorTemp<T, U>::setConvertissorMode(int convertissorMode) { _convertissorMode = static_cast<ConvertissorMode>(convertissorMode); } template <typename T, typename U> int ConvertissorTemp<T, U>::getConvertissorMode() const { return _convertissorMode; } template <typename T, typename U> T ConvertissorTemp<T, U>::convert(const U& value) const { if (_convertissorMode == FAHRENHEIT_TO_CELSIUS) return convertFahrenheitToCelsius(value); else if (_convertissorMode == CELSIUS_TO_FAHRENHEIT) return convertCelsiusToFahrenheit(value); else return NULL; } template <typename T, typename U> T ConvertissorTemp<T, U>::convertFahrenheitToCelsius(const U& value) const { return (value - 32) / 1.8; } template <typename T, typename U> T ConvertissorTemp<T, U>::convertCelsiusToFahrenheit(const U& value) const { return (value * 1.8) + 32; } } #endif /* !CONVERTISSOR_TEMP_HPP_ */
true
bcab1962ac627cbe5685720e6924f589443dce0e
C++
doraneko94/AtCoder
/ABC/ABC076/c.cpp
UTF-8
787
2.859375
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string S, T; cin >> S; cin >> T; int lenS = S.size(); int lenT = T.size(); int ans = -1; for (int i=0; i<(lenS - lenT + 1); ++i) { string cand = S.substr(i, i+lenT); bool can = true; for (int t=0; t<lenT; ++t) { if (T[t] != cand[t] && cand[t] != '?') { can = false; break; } } if (can) ans = i; } if (ans < 0) cout << "UNRESTORABLE" << endl; else { for (int i=0; i<lenS; ++i) { if (i >= ans && i<ans+lenT) cout << T[i-ans]; else if (S[i] == '?') cout << 'a'; else cout << S[i]; } cout << endl; } return 0; }
true
2aad61746dc66f058c69cf6e556f6c39e801c9f1
C++
rweigel/kameleon
/python/kameleonV.cpp
UTF-8
1,600
2.890625
3
[]
no_license
#include <iostream> #include <iomanip> #include <sstream> #include <string> #include <ctime> #include <cmath> #include <cstdlib> #include <ccmc/Kameleon.h> #include <ccmc/FileReader.h> std::vector<float> interpolate (char* filename, std::vector<float> x, std::vector<float> y, std::vector<float> z, int N, char* var, int debug) { clock_t start = clock(); ccmc::Kameleon kameleon1; long status1 = kameleon1.open(filename); if (status1 != ccmc::FileReader::OK) { std::cout << "Could not open " << filename << std::endl; return x; } if (debug == 1) { std::cout << filename << ": Opened." << std::endl; std::cout << filename << ": Loading variable started." << std::endl; } if (kameleon1.doesVariableExist(var)){ kameleon1.loadVariable(var); } else { std::cout << "Variable " << var << " does not exist in " << filename << std::endl; return x; } if (debug == 1) { std::cout << filename << ": Loading variable finished." << std::endl; } ccmc::Interpolator * interpolator1 = kameleon1.createNewInterpolator(); if (debug == 1) { std::cout << filename << ": Interpolation started." << std::endl; } for (int k = 0; k < N; k++) { x[k] = interpolator1->interpolate(var, x[k], y[k], z[k]); } if (debug == 1) { std::cout << filename << ": Interpolation finished." << std::endl; } double duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; if (debug == 1) { std::cout << "Interpolation took " << (duration) << " s" << std::endl; } delete interpolator1; kameleon1.close(); return x; }
true
c4fbc609fb97668a9db2d3975f8533aa8f5e2e83
C++
JhengHan/Shock_Wu
/n1.cpp
BIG5
729
3.546875
4
[]
no_license
// n1.cpp : wqDxε{iJIC // #include "stdafx.h" #include "stdio.h" #include "stdlib.h" int n_factorial(int n) { int temp = 1, x = 1; for (x = 1; x <= n; x++) { temp *= x; } return temp; } int n_match(int m, int n){ int tmp = 0; tmp = (n_factorial(m) / (n_factorial(m - n)*n_factorial(n))); return tmp; } int main() { double n1,t1, m, n2,t2; printf("n!=n*(n-1)! пJn\n"); scanf("%lf", &n1); t1 = n_factorial(n1); printf("%.0lf\n",t1); printf("զXƤƨ : ѼƬm,n\n"); printf("Ʀ^ǭȬ m!/((m-n)!n!) пJm,n"); scanf("%lf %lf",&m ,&n2); t2 = n_match(m,n2); printf("%.0lf\n", t2); system("pause"); return 0; }
true
20c7f12bde0354ef7c9df8ca3ca101619766feb6
C++
yachay-tech-ai/DataStructures-n-Algorithms
/data structures implementation/Trie/Trie.cpp
UTF-8
1,013
3.078125
3
[]
no_license
#include "Trie.h" TrieNode::TrieNode() { } TrieNode::~TrieNode() { } TrieNode* TrieNode::getNode() { TrieNode* pnode = new TrieNode; pnode->isEndOfWord = false; for (int i = 0; i < 26; i++) pnode->children[i] = NULL; return pnode; } int TrieNode::getCharIndex(char c) { return c -'a'; } void TrieNode::insert(TrieNode* root, string key) { TrieNode* pcrawl = root; for (int i = 0; i < key.length(); i++) { pcrawl->size++; int index = getCharIndex(key[i]); if (!pcrawl->children[index]) pcrawl->children[index] = getNode(); pcrawl = pcrawl->children[index]; } pcrawl->isEndOfWord = true; } bool TrieNode::search(TrieNode* root, string key) { TrieNode* pcrawl = root; for (int i = 0; i < key.length(); i++) { int index = getCharIndex(key[i]); if (!pcrawl->children[index])return false; pcrawl = pcrawl->children[index]; } return(pcrawl != NULL && pcrawl->isEndOfWord); } int TrieNode::findCount(string s) { return 0; }
true
feaffb9ca863d36422fa9863f0d471091563048c
C++
LegendaryZReborn/Interactive-3D-Graphics
/Island Project/GraphicsProject3_ReadModels/Cube.h
UTF-8
1,466
2.875
3
[]
no_license
#pragma once #include "Angel.h" typedef Angel::vec4 color4; typedef Angel::vec4 point4; const int NumVertices = 36; //(6 faces)(2 triangles/face)(3 vertices/triangle) class Cube { public: Cube(); void quad(int a, int b, int c, int d); //draws cube with specified colors void colorcube(); void Load(GLuint &program); ~Cube(); private: point4 points[NumVertices]; color4 colors[NumVertices]; point4 vertices[8]; color4 vertex_colors[8]; // Vertices of a unit cube centered at origin, sides aligned with axes //point4 vertices[8] = { // point4(-0.5, -0.5, 0.5, 1.0), // point4(-0.5, 0.5, 0.5, 1.0), // point4(0.5, 0.5, 0.5, 1.0), // point4(0.5, -0.5, 0.5, 1.0), // point4(-0.5, -0.5, -0.5, 1.0), // point4(-0.5, 0.5, -0.5, 1.0), // point4(0.5, 0.5, -0.5, 1.0), // point4(0.5, -0.5, -0.5, 1.0) //}; //// RGBA olors //color4 vertex_colors[8] = { // color4(0.0, 0.0, 0.0, 1.0), // black // color4(1.0, 0.0, 0.0, 1.0), // red // color4(1.0, 1.0, 0.0, 1.0), // yellow // color4(0.0, 1.0, 0.0, 1.0), // green // color4(0.0, 0.0, 1.0, 1.0), // blue // color4(1.0, 0.0, 1.0, 1.0), // magenta // color4(1.0, 1.0, 1.0, 1.0), // white // color4(0.0, 1.0, 1.0, 1.0) // cyan //}; //---------------------------------------------------------------------------- // quad generates two triangles for each face and assigns colors // to the vertices int Index = 0; };
true
ecc9cdd48356f69c1ebb75d3ab0c3863d26c67cd
C++
DoxelCreations/Doxel-Engine
/Doxel-Engine Solution/Doxel-Engine/SimpleErrors.h
UTF-8
535
3.515625
4
[ "MIT" ]
permissive
/* FILE DESCRIPTION This is a simple header that define a simple console printing function. */ #pragma once #include <iostream> /* This function print things to the console. How to use: When you want to print something to the console, type: Debug_Log("X") where X is the text you want to print. If you want to print a veriable, you can just put it inside the parenthesis. If there are multiple things you want to print in one call, use the << operator to seperate them. */ #define Debug_Log(x) std::cout << x << std::endl
true
c68f12bab373d2b4afffad41a6e4767b7780d7b6
C++
llersch/fcg20111
/src/Camera.cpp
UTF-8
1,354
3.03125
3
[]
no_license
#include "Camera.h" Camera::Camera(void) { eye[0] = 0.0f; eye[1] = 0.1f; eye[2] = 0.0f; up[0] = 0.0f; up[1] = 1.0f; up[2] = 0.0f; side[0] = 1.0f; side[1] = 0.0f; side[2] = 0.0f; look[0] = 1.0f; look[1] = 0.0f; look[2] = 0.0f; } Camera::~Camera(void) { } void Camera::Update_glMatrix(void) { glLoadIdentity(); gluLookAt( eye[0], eye[1], eye[2], look[0], look[1], look[2], up[0]-eye[0], up[1]-eye[1], up[2]-eye[2]); } void Camera::Translate(float x, float y, float z) { GLfloat matrix[3][3] = { {side[0]-eye[0], up[0]-eye[0], look[0]-eye[0]}, {side[1]-eye[1], up[1]-eye[1], look[1]-eye[1]}, {side[2]-eye[2], up[2]-eye[2], look[2]-eye[2]} }; GLfloat vector[3] = {x,y,-z}; GLfloat result[3]; result[0] = matrix[0][0]*vector[0] + matrix[0][1]*vector[1] + matrix[0][2]*vector[2]; result[1] = matrix[1][0]*vector[0] + matrix[1][1]*vector[1] + matrix[1][2]*vector[2]; result[2] = matrix[2][0]*vector[0] + matrix[2][1]*vector[1] + matrix[2][2]*vector[2]; eye[0] += result[0]; eye[1] += result[1]; eye[2] += result[2]; up[0] += result[0]; up[1] += result[1]; up[2] += result[2]; side[0] += result[0]; side[1] += result[1]; side[2] += result[2]; look[0] += result[0]; look[1] += result[1]; look[2] += result[2]; this->Update_glMatrix(); }
true
58abd6e557549128c59ca7a02ee40ccb6a2a6a45
C++
Ri0ee/memory-editor
/TestSubject/src/main.cpp
UTF-8
299
2.703125
3
[]
no_license
#include "windows.h" char str_1[] = "TestStringOne"; char str_2[] = "TestStringTwo"; int main() { while(true) { MessageBox(0, str_1, str_2, MB_OK); MessageBox(0, (IsDebuggerPresent())?"Debugger present":"Debugger not present", "Message box", MB_OK); } return 0; }
true
b0a3a2edc662131678b53c1ad61b6425acaf224b
C++
bmikaeli/abstractVm
/OpInt16.class.cpp
UTF-8
2,539
2.921875
3
[]
no_license
#include "OpInt16.class.hpp" OpInt16::OpInt16(std::string value) { this->value = value; this->type = Int16; } OpInt16::~OpInt16() { } int OpInt16::getPrecision() const { return Int16; } eOperandType OpInt16::getType() const { return this->type; } std::string const &OpInt16::toString() const { return this->value; } IOperand const *OpInt16::operator+(IOperand const &rhs) const { Comands *cmd = new Comands(); double result; result = atoi(this->toString().data()) + atoi(rhs.toString().data()); std::ostringstream ss; ss << result; std::string s(ss.str()); if (rhs.getPrecision() > this->getPrecision()) return cmd->createOperand(rhs.getType(), s); else return cmd->createOperand(this->getType(), s); } IOperand const *OpInt16::operator%(IOperand const &rhs) const { Comands *cmd = new Comands(); double result; result = fmod(atoi(this->toString().data()), atoi(rhs.toString().data())); std::ostringstream ss; ss << result; std::string s(ss.str()); if (rhs.getPrecision() > this->getPrecision()) return cmd->createOperand(rhs.getType(), s); else return cmd->createOperand(this->getType(), s); } IOperand const *OpInt16::operator*(IOperand const &rhs) const { Comands *cmd = new Comands(); int result; result = atoi(this->toString().data()) * atoi(rhs.toString().data()); std::ostringstream ss; ss << result; std::string s(ss.str()); if (rhs.getPrecision() > this->getPrecision()) return cmd->createOperand(rhs.getType(), s); else return cmd->createOperand(this->getType(), s); } IOperand const *OpInt16::operator-(IOperand const &rhs) const { Comands *cmd = new Comands(); double result; result = atoi(this->toString().data()) - atoi(rhs.toString().data()); std::ostringstream ss; ss << result; std::string s(ss.str()); if (rhs.getPrecision() > this->getPrecision()) return cmd->createOperand(rhs.getType(), s); else return cmd->createOperand(this->getType(), s); } IOperand const *OpInt16::operator/(IOperand const &rhs) const { Comands *cmd = new Comands(); double result; result = atoi(this->toString().data()) / atoi(rhs.toString().data()); std::ostringstream ss; ss << result; std::string s(ss.str()); if (rhs.getPrecision() > this->getPrecision()) return cmd->createOperand(rhs.getType(), s); else return cmd->createOperand(this->getType(), s); }
true
41d35ac77c160e372a8839636f2f29e1db2fac6b
C++
romanbtt/42-Piscine-Cpp
/cpp00/ex01/main.cpp
UTF-8
1,622
3.078125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: romanbtt <marvin@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/28 20:58:19 by romanbtt #+# #+# */ /* Updated: 2021/07/11 20:52:53 by romanbtt ### ########.fr */ /* */ /* ************************************************************************** */ #include "Minitel.hpp" /* ** Until getline() returns a valid stream. ** We compare the input to the given commands. ** If one of them matches, we call the right function. ** If not, we come back to getline(). */ int main( void ) { std::string input; Minitel minitel; std::cout << "Enter a command: [ADD] [SEARCH] [EXIT] : "; while (std::getline(std::cin, input)) { if (input.compare("ADD") == 0) minitel.add(); else if (input.compare("SEARCH") == 0) minitel.search(); else if (input.compare("EXIT") == 0) { std::cout << "Bye! Thank you for choosing minitel!" << std::endl; break; } else std::cout << "Command not found!" << std::endl; std::cout << "Enter a command: [ADD] [SEARCH] [EXIT] : "; } return (0); }
true
249fb682ede1e29649b3a9b7b658fc88bf18fac7
C++
pawnlord/chess-engine
/inc/Unit.hpp
UTF-8
415
2.65625
3
[]
no_license
#ifndef UNIT_HPP #define UNIT_HPP #define SIDE1 0 #define SIDE2 1 class Unit{ public: Unit(int x, int y, int maxX, int maxY, int side, char identifier_); virtual bool validateMovement(int to_x, int to_y){ return true; } char identifier; struct { int x; int y; int maxX; int maxY; int side; } info; //private: }; #endif
true
fe83750bc47bcee78b30918bd963c3cdb1d4a2f5
C++
NateRiz/OpenGL4
/Engine/MeshHandler.cpp
UTF-8
1,389
2.703125
3
[]
no_license
// // Created by nathan on 6/9/19. // #include "MeshHandler.h" #include <glad/glad.h> MeshHandler::MeshHandler() { unsigned int vao; glGenVertexArrays(1, &vao); mVAOs.push_back(vao); //TODO this shouldn't be here later. vaotype will just be passed in to createmesh() } MeshHandler::~MeshHandler() { for (unsigned int vao: mVAOs) { glDeleteVertexArrays(1, &vao); } for (unsigned int vbo: mVBOs) { glDeleteBuffers(1, &vbo); } } Mesh MeshHandler::CreateMesh(std::vector<float> &data, std::vector<unsigned int>& indices, int vaoType) { glBindVertexArray(mVAOs[vaoType]); unsigned int vbo; glGenBuffers(1, &vbo); mVBOs.push_back(vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * data.size(), data.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *) 0); // Positions unsigned int ebo; glGenBuffers(1, &ebo); mVBOs.push_back(ebo); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * indices.size(), indices.data(), GL_STATIC_DRAW); glBindVertexArray(0); mMeshes.emplace_back(mVAOs[vaoType], indices.size(),"vertex.glsl", "fragment.glsl"); return mMeshes.back(); } const std::vector<Mesh> &MeshHandler::getMeshes() const { return mMeshes; }
true
1a4350f0c9dddcb96194a158f526c7c1da5d794d
C++
alorkowski/N2ChessPuzzleMPI
/003-mpi2/MemoryAllocationTool.hpp
UTF-8
1,562
3.15625
3
[]
no_license
//! MemoryAllocationTool.hpp /*! \brief A class responsible for dynamic allocation of memory. \author Lorkowski, Alexander <alexander.lorkowski@epfl.ch> \version 1.0 \date 21 May 2017 \remark Ecole Polytechnic Federal de Lausanne (EPFL) \remark MATH-454 Parallel and High-Performance Computing */ #ifndef MEMORYALLOCATIONTOOL_HPP_ #define MEMORYALLOCATIONTOOL_HPP_ class MemoryAllocationTool { public: /*! A method to allocate a 1-dimensional, contiguous integer array. * * @param nRow The number of rows to allocate. * @return A dynamically allocated 1-dimensional, contiguous integer array. */ int* allocate1DInt(int nRow); /*! A method to allocate a 2-dimensional, contiguous integer array. * * @param nRow The number of rows to allocate. * @param nColumn The number of columns to allocate. * @return A dynamically allocated 1-dimensional, contiguous integer array. */ int** allocate2DInt(int nRow, int nColumn); /*! A method to allocate a 2-dimensional, contiguous integer array. */ int** allocate2DEmpty(); /*! A method to deallocate a 1-dimensional, contiguous integer array. * * @param array The 1-dimensional, contiguous integer array to deallocate. */ void deallocate1DInt(int* array); /*! A method to deallocate a 2-dimensional, contiguous integer array. * * @param array The 2-dimensional, contiguous integer array to deallocate. */ void deallocate2DInt(int** array); }; #endif //MEMORYALLOCATIONTOOL_HPP_
true
fcca47e30cc66d4e271fcc1a5f04281a9c883d17
C++
cjglo/cs052
/module5/Project 3/GoldClient.cpp
UTF-8
2,034
3.09375
3
[]
no_license
/* * GoldClient.cpp * * COSC 052 2020 * Project 3 * * Due on: August 2nd * Author: Christopher Gallo * * * In accordance with the class policies and Georgetown's * Honor Code, I certify that, with the exception of the * class resources and those items noted below, I have neither * given nor received any assistance on this project. * * References not otherwise commented within the program source code. * Note that you should not mention any help from the TAs, the professor, * or any code taken from the class textbooks. */ #include "GoldClient.h" // ostream for GoldClients ostream& GoldClient::htmlToStream(ostream &out) { out<<"\t <tr> <td> " << this->getName(); out<< " </td> <td> " << this->getTenure(); out<< " </td> <td> " << this->getTier(); return out; } // Relational Operator bool GoldClient::operator>(Client* otherClPtr) { switch (otherClPtr->getType()) { // It is comparing a Gold to a Silver case '0': return true; // It is comparing a Gold to a Gold case '1': // First compares Tier to break the tie if(!(this->getTier() >= otherClPtr->getTier())) { return true; } // If the tier is equal, it will drop into this code block: else if (this->getTier() == otherClPtr->getTier()) { // compares by Tenure next to try and break the tie if(this->getTenure() > otherClPtr->getTenure()) { return true; } else { return false; } } else // This is for if Tier is < { return false; } // It is comparing a Gold to a Platinum case '2': return false; // Default case: default: cout<<"\nError, Client Type Not Valid\n"; return false; } }
true
d0d4594a10b44ee2cbdbd3454b7413face738d61
C++
cheersfan/My-C-Plus-Plus-Practice
/ExerciseCodes/10-8-stock20.h
UTF-8
663
2.875
3
[]
no_license
// // Created by root on 12/1/18. // #ifndef MYCLIONPROJECT_10_8_STOCK20_H #define MYCLIONPROJECT_10_8_STOCK20_H #include <string> #include <iostream> class Stock3{ private: std::string company; long shares; double share_val; double total_val; void set_tot(){total_val = shares * share_val;}; public: Stock3(); Stock3(int a); Stock3(const std::string &co, long n = 0, double pr = 0.0); ~Stock3(); void buy3(long num,double price); void sell3(long num, double price); void update3(double price); void show3() const; const Stock3 & topval(const Stock3 & s) const; }; #endif //MYCLIONPROJECT_10_8_STOCK20_H
true
e44d21cf9f109b96025507be9a0e5a8c5af6ccb6
C++
google/swiftshader
/third_party/llvm-16.0/llvm/lib/Support/IntervalMap.cpp
UTF-8
4,501
2.625
3
[ "Apache-2.0", "Spencer-94", "BSD-3-Clause" ]
permissive
//===- lib/Support/IntervalMap.cpp - A sorted interval map ----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the few non-templated functions in IntervalMap. // //===----------------------------------------------------------------------===// #include "llvm/ADT/IntervalMap.h" #include <cassert> namespace llvm { namespace IntervalMapImpl { void Path::replaceRoot(void *Root, unsigned Size, IdxPair Offsets) { assert(!path.empty() && "Can't replace missing root"); path.front() = Entry(Root, Size, Offsets.first); path.insert(path.begin() + 1, Entry(subtree(0), Offsets.second)); } NodeRef Path::getLeftSibling(unsigned Level) const { // The root has no siblings. if (Level == 0) return NodeRef(); // Go up the tree until we can go left. unsigned l = Level - 1; while (l && path[l].offset == 0) --l; // We can't go left. if (path[l].offset == 0) return NodeRef(); // NR is the subtree containing our left sibling. NodeRef NR = path[l].subtree(path[l].offset - 1); // Keep right all the way down. for (++l; l != Level; ++l) NR = NR.subtree(NR.size() - 1); return NR; } void Path::moveLeft(unsigned Level) { assert(Level != 0 && "Cannot move the root node"); // Go up the tree until we can go left. unsigned l = 0; if (valid()) { l = Level - 1; while (path[l].offset == 0) { assert(l != 0 && "Cannot move beyond begin()"); --l; } } else if (height() < Level) // end() may have created a height=0 path. path.resize(Level + 1, Entry(nullptr, 0, 0)); // NR is the subtree containing our left sibling. --path[l].offset; NodeRef NR = subtree(l); // Get the rightmost node in the subtree. for (++l; l != Level; ++l) { path[l] = Entry(NR, NR.size() - 1); NR = NR.subtree(NR.size() - 1); } path[l] = Entry(NR, NR.size() - 1); } NodeRef Path::getRightSibling(unsigned Level) const { // The root has no siblings. if (Level == 0) return NodeRef(); // Go up the tree until we can go right. unsigned l = Level - 1; while (l && atLastEntry(l)) --l; // We can't go right. if (atLastEntry(l)) return NodeRef(); // NR is the subtree containing our right sibling. NodeRef NR = path[l].subtree(path[l].offset + 1); // Keep left all the way down. for (++l; l != Level; ++l) NR = NR.subtree(0); return NR; } void Path::moveRight(unsigned Level) { assert(Level != 0 && "Cannot move the root node"); // Go up the tree until we can go right. unsigned l = Level - 1; while (l && atLastEntry(l)) --l; // NR is the subtree containing our right sibling. If we hit end(), we have // offset(0) == node(0).size(). if (++path[l].offset == path[l].size) return; NodeRef NR = subtree(l); for (++l; l != Level; ++l) { path[l] = Entry(NR, 0); NR = NR.subtree(0); } path[l] = Entry(NR, 0); } IdxPair distribute(unsigned Nodes, unsigned Elements, unsigned Capacity, const unsigned *CurSize, unsigned NewSize[], unsigned Position, bool Grow) { assert(Elements + Grow <= Nodes * Capacity && "Not enough room for elements"); assert(Position <= Elements && "Invalid position"); if (!Nodes) return IdxPair(); // Trivial algorithm: left-leaning even distribution. const unsigned PerNode = (Elements + Grow) / Nodes; const unsigned Extra = (Elements + Grow) % Nodes; IdxPair PosPair = IdxPair(Nodes, 0); unsigned Sum = 0; for (unsigned n = 0; n != Nodes; ++n) { Sum += NewSize[n] = PerNode + (n < Extra); if (PosPair.first == Nodes && Sum > Position) PosPair = IdxPair(n, Position - (Sum - NewSize[n])); } assert(Sum == Elements + Grow && "Bad distribution sum"); // Subtract the Grow element that was added. if (Grow) { assert(PosPair.first < Nodes && "Bad algebra"); assert(NewSize[PosPair.first] && "Too few elements to need Grow"); --NewSize[PosPair.first]; } #ifndef NDEBUG Sum = 0; for (unsigned n = 0; n != Nodes; ++n) { assert(NewSize[n] <= Capacity && "Overallocated node"); Sum += NewSize[n]; } assert(Sum == Elements && "Bad distribution sum"); #endif return PosPair; } } // namespace IntervalMapImpl } // namespace llvm
true
ff1941a308417a55bb164f3947756e4bccaa761f
C++
en30/online-judge
/atcoder/abc015_3.cpp
UTF-8
402
3.046875
3
[]
no_license
#include <bits/stdc++.h> #include "../include/template" int N, K; vector<vector<int>> T; bool buggy(int i, int curr) { if (i == N) return curr == 0; rep(j, K) if (buggy(i + 1, curr ^ T[i][j])) return true; return false; } int main() { cin >> N >> K; T.resize(N, vector<int>(K)); rep(i, N) rep(j, K) cin >> T[i][j]; cout << (buggy(0, 0) ? "Found" : "Nothing") << endl; return 0; }
true
451c13fe42480ece512b9f52c2918d5254b76aaf
C++
ltabis/epitech-projects
/cpp_d09_2018/tests/ex04/unit_tests_4.cpp
UTF-8
816
2.625
3
[ "MIT" ]
permissive
/* ** EPITECH PROJECT, 2019 ** unit_tests_1.cpp ** File description: ** battery */ #include <criterion/criterion.h> #include "Paladin.hpp" Test(ex04, Paladin) { Paladin c("palachiasse", 15); cr_assert_eq(c.getName(), "palachiasse"); cr_assert_eq(c.getLvl(), 15); cr_assert_eq(c.getPv(), 100); cr_assert_eq(c.getPower(), 100); cr_assert_eq(c.getStrength(), 9); cr_assert_eq(c.getStamina(), 10); cr_assert_eq(c.getIntelligence(), 10); cr_assert_eq(c.getSpirit(), 10); cr_assert_eq(c.getAgility(), 2); cr_assert_eq(c.RangeAttack(), 0); cr_assert_eq(c.getPower(), 75); c.RestorePower(); cr_assert_eq(c.getPower(), 100); cr_assert_eq(c.CloseAttack(), 29); cr_assert_eq(c.getPower(), 70); }
true
0586433f61114dfb04edb2967a1979e716db3ad0
C++
sdirienzo/legend-of-adlez-game
/Enemy.cpp
UTF-8
1,021
3.328125
3
[]
no_license
/******************************************************************************* ** Author: Stephen Di Rienzo ** Date: 11/28/2018 ** Description: Enemy.cpp is the class implementation file for the Enemy ** class, which models a non-playable Enemy game character *******************************************************************************/ #include "Enemy.hpp" #include <cstdlib> using std::rand; Enemy::Enemy(string name, int health, int strength, int defense) { setName(name); setHealth(health); setStrength(strength); setDefense(defense); } int Enemy::attack() { int maxAttack = 2 * getStrength(); int minAttack = 1 * getStrength(); return (rand() % maxAttack + minAttack); } int Enemy::defend(int attack) { int health = getHealth(); double defense = 1.0; int damage = 0; if (getDefense() != 0) { double defense = 1.0 / getDefense(); } damage = attack * defense; if (damage > 0) { health = health - damage; setHealth(health); } return damage; }
true
1f7f9ec7934055d8f805c83c43b47e1bdbe73c73
C++
hamukawa0406/imageProcessing
/topic1/1-3/statistic.cpp
UTF-8
900
2.578125
3
[]
no_license
#include "ifstream_string.h" #include "statistic.h" Statistic::Statistic() { } Statistic::Statistic(InctImage _img): img{_img} { ave = calcAve(); var = calcVar(); max = calcMax(); min = calcMin(); med = calcMed(); mode = calcMode(); setHist(); } double Statistic::calcAve(){ double sum {}; RGBColor trgb; for(int j = 0; j < img.getHeight(); j++){ for(int i = 0; i < img.getWidth(); i++){ trgb = img.getPnmPixel(i, j); sum += trgb.R; } } return sum / ((double)img.getWidth()*img.getHeight()); } void Statistic::printHist(){ } double Statistic::getAve(){ return ave; } double Statistic::getVar(){ return var; } double Statistic::getMax(){ return max; } double Statistic::getMin(){ return min; } double Statistic::getMed(){ return med; } double Statistic::getMode(){ return mode; }
true
2fb7ef396a76c2111d85ee01a0c3f336f88f5eb2
C++
CasarinDavide/CasarinDavide_A_Semaforo
/SEMAFORO/SEMAFORO.ino
UTF-8
2,204
2.84375
3
[]
no_license
int rosso1 = 6; int giallo1 = 4 ; int verde1= 2 ; int rosso2 = 12 ; int giallo2= 10 ; int verde2= 8 ; int numLampeggi ; int DurataGiallo; int DurataRosso; int DurataVerde; int tempoLampeggi; void setup() { // put your setup code here, to run once: pinMode (rosso1, OUTPUT); pinMode (giallo1, OUTPUT); pinMode (verde1,OUTPUT); pinMode (rosso2, OUTPUT); pinMode (giallo2, OUTPUT); pinMode (verde2,OUTPUT); Serial.begin(9600); richiestaValoriLampeggi(); richiestaValoritempoLampeggi(); richiestaDuaratagiallo(); richiestaDuarataVerde(); } void loop() { // put your main code here, to run repeatedly: digitalWrite(rosso1,HIGH); digitalWrite(verde2,HIGH); delay(DurataVerde); LampeggioVerde2(); digitalWrite(giallo1,HIGH); digitalWrite(giallo2 , HIGH); delay(DurataGiallo); digitalWrite(rosso1,LOW); digitalWrite(giallo1,LOW); digitalWrite(giallo2,LOW); digitalWrite(rosso2,HIGH); digitalWrite(verde1,HIGH); delay(DurataVerde); LampeggioVerde1(); digitalWrite(giallo1,HIGH); digitalWrite(giallo2,HIGH); delay(DurataGiallo); digitalWrite(giallo1,LOW); digitalWrite(giallo2,LOW); digitalWrite(rosso2,LOW); } void richiestaValoriLampeggi() { Serial.println ( "quanti lampeggi verdi?"); while ( Serial.available() == 0) {}; numLampeggi = Serial.readString().toInt(); } void richiestaValoritempoLampeggi() { Serial.println ( "quanto tempo lampeggi verdi?"); while ( Serial.available() == 0) {}; tempoLampeggi = Serial.readString().toInt(); } void richiestaDuaratagiallo() { Serial.println ( "quanto dura il giallo?"); while ( Serial.available() == 0) {}; DurataGiallo = Serial.readString().toInt(); } void richiestaDuarataVerde() { Serial.println ( "quanto dura il verde?"); while ( Serial.available() == 0) {}; DurataVerde = Serial.readString().toInt(); } void LampeggioVerde1(){ for (int i = 0; i<numLampeggi; i++) { digitalWrite(verde1,HIGH); delay(tempoLampeggi); digitalWrite(verde1,LOW); delay(tempoLampeggi); } } void LampeggioVerde2(){ for (int i = 0; i< numLampeggi; i++) { digitalWrite(verde2,HIGH); delay(tempoLampeggi); digitalWrite(verde2,LOW); delay(tempoLampeggi); } }
true
4f6e5c05f57e20a65586215329af1f7dc220c6e7
C++
ide-an/DummyCCompiler
/src/codegen.cpp
UTF-8
8,894
2.890625
3
[]
no_license
#include "codegen.hpp" /** * コンストラクタ */ CodeGen::CodeGen(){ Builder = new IRBuilder<>(getGlobalContext()); } /** * デストラクタ */ CodeGen::~CodeGen(){ SAFE_DELETE(Builder); } /** * コード生成実行 * @param TranslationUnitAST Module名(入力ファイル名) * @return 成功時:true 失敗時:false */ bool CodeGen::doCodeGen(TranslationUnitAST &tunit, std::string name){ return generateTranslationUnit(tunit, name); } /** * Module取得 */ Module &CodeGen::getModule(){ if(Mod) return *Mod; else return *(new Module("null", getGlobalContext())); } /** * Module生成メソッド * @param TranslationUnitAST Module名(入力ファイル名) * @return 成功時:true 失敗時:false  */ bool CodeGen::generateTranslationUnit(TranslationUnitAST &tunit, std::string name){ Mod = new Module(name, getGlobalContext()); //funtion declaration for(int i=0; ; i++){ PrototypeAST *proto=tunit.getPrototype(i); if(!proto) break; else if(!generatePrototype(proto, Mod)){ SAFE_DELETE(Mod); return false; } } //function definition for(int i=0; ; i++){ FunctionAST *func=tunit.getFunction(i); if(!func) break; else if(!generateFunctionDefinition(func, Mod)){ SAFE_DELETE(Mod); return false; } } return true; } /** * 関数定義生成メソッド * @param FunctionAST Module * @return 生成したFunctionのポインタ */ Function *CodeGen::generateFunctionDefinition(FunctionAST *func_ast, Module *mod){ Function *func=generatePrototype(func_ast->getPrototype(), mod); if(!func){ return NULL; } CurFunc = func; BasicBlock *bblock=BasicBlock::Create(getGlobalContext(), "entry",func); Builder->SetInsertPoint(bblock); generateFunctionStatement(func_ast->getBody()); return func; } /** * 関数宣言生成メソッド * @param PrototypeAST, Module * @return 生成したFunctionのポインタ */ Function *CodeGen::generatePrototype(PrototypeAST *proto, Module *mod){ //already declared? Function *func=mod->getFunction(proto->getName()); if(func){ if(func->arg_size()==proto->getParamNum() && func->empty()){ return func; }else{ fprintf(stderr, "error::function %s is redefined",proto->getName().c_str()); return NULL; } } //create arg_types std::vector<Type*> int_types(proto->getParamNum(), Type::getInt32Ty(getGlobalContext())); //create func type FunctionType *func_type = FunctionType::get( Type::getInt32Ty(getGlobalContext()), int_types,false ); //create function func=Function::Create(func_type, Function::ExternalLinkage, proto->getName(), mod); //set names Function::arg_iterator arg_iter=func->arg_begin(); for(int i=0; i<proto->getParamNum(); i++){ arg_iter->setName(proto->getParamName(i).append("_arg")); } return func; } /** * 関数生成メソッド * 変数宣言、ステートメントの順に生成  * @param FunctionStmtAST * @return 最後に生成したValueのポインタ */ Value *CodeGen::generateFunctionStatement(FunctionStmtAST *func_stmt){ //insert variable decls VariableDeclAST *vdecl; Value *v; for(int i=0; ; i++){ //最後まで見たら終了 if(!func_stmt->getVariableDecl(i)) break; //create alloca vdecl=dyn_cast<VariableDeclAST>(func_stmt->getVariableDecl(i)); v=generateVariableDeclaration(vdecl); } //insert expr statement BaseAST *stmt; for(int i=0; ; i++){ stmt=func_stmt->getStatement(i); if(!stmt) break; else if(!isa<NullExprAST>(stmt)) v=generateStatement(stmt); } return v; } /** * 変数宣言(alloca命令)生成メソッド * @param VariableDeclAST * @return 生成したValueのポインタ */ Value *CodeGen::generateVariableDeclaration(VariableDeclAST *vdecl){ //create alloca AllocaInst *alloca=Builder->CreateAlloca( Type::getInt32Ty(getGlobalContext()), 0, vdecl->getName()); //if args alloca if(vdecl->getType()==VariableDeclAST::param){ //store args ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable(); Builder->CreateStore(vs_table.lookup(vdecl->getName().append("_arg")), alloca); } //ValueMap[vdecl->getName()]=alloca; return alloca; } /** * ステートメント生成メソッド * 実際にはASTの種類を確認して各種生成メソッドを呼び出し * @param JumpStmtAST * @return 生成したValueのポインタ */ Value *CodeGen::generateStatement(BaseAST *stmt){ if(isa<BinaryExprAST>(stmt)){ return generateBinaryExpression(dyn_cast<BinaryExprAST>(stmt)); }else if(isa<CallExprAST>(stmt)){ return generateCallExpression(dyn_cast<CallExprAST>(stmt)); }else if(isa<JumpStmtAST>(stmt)){ return generateJumpStatement(dyn_cast<JumpStmtAST>(stmt)); }else{ return NULL; } } /** * 二項演算生成メソッド * @param JumpStmtAST * @return 生成したValueのポインタ */ Value *CodeGen::generateBinaryExpression(BinaryExprAST *bin_expr){ BaseAST *lhs=bin_expr->getLHS(); BaseAST *rhs=bin_expr->getRHS(); Value *lhs_v; Value *rhs_v; //assignment if(bin_expr->getOp()=="="){ //lhs is variable VariableAST *lhs_var=dyn_cast<VariableAST>(lhs); ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable(); lhs_v = vs_table.lookup(lhs_var->getName()); //other operand }else{ //lhs=? //Binary? if(isa<BinaryExprAST>(lhs)) lhs_v=generateBinaryExpression(dyn_cast<BinaryExprAST>(lhs)); //Variable? else if(isa<VariableAST>(lhs)) lhs_v=generateVariable(dyn_cast<VariableAST>(lhs)); //Number? else if(isa<NumberAST>(lhs)){ NumberAST *num=dyn_cast<NumberAST>(lhs); lhs_v=generateNumber(num->getNumberValue()); } } //create rhs value if(isa<BinaryExprAST>(rhs)) rhs_v=generateBinaryExpression(dyn_cast<BinaryExprAST>(rhs)); //Variable? else if(isa<VariableAST>(rhs)) rhs_v=generateVariable(dyn_cast<VariableAST>(rhs)); //Number? else if(isa<NumberAST>(rhs)){ NumberAST *num=dyn_cast<NumberAST>(rhs); rhs_v=generateNumber(num->getNumberValue()); } if(bin_expr->getOp()=="="){ //store return Builder->CreateStore(rhs_v, lhs_v); }else if(bin_expr->getOp()=="+"){ //add return Builder->CreateAdd(lhs_v, rhs_v, "add_tmp"); }else if(bin_expr->getOp()=="-"){ //sub return Builder->CreateSub(lhs_v, rhs_v, "sub_tmp"); }else if(bin_expr->getOp()=="*"){ //mul return Builder->CreateMul(lhs_v, rhs_v, "mul_tmp"); }else if(bin_expr->getOp()=="/"){ //div return Builder->CreateSDiv(lhs_v, rhs_v, "div_tmp"); } } /** * 関数呼び出し(Call命令)生成メソッド * @param CallExprAST * @return 生成したValueのポインタ  */ Value *CodeGen::generateCallExpression(CallExprAST *call_expr){ std::vector<Value*> arg_vec; BaseAST *arg; Value *arg_v; Function *func=Mod->getFunction("main"); ValueSymbolTable &vs_table = func->getValueSymbolTable(); for(int i=0; ; i++){ if(!(arg=call_expr->getArgs(i))) break; //isCall if(isa<CallExprAST>(arg)) arg_v=generateCallExpression(dyn_cast<CallExprAST>(arg)); //isBinaryExpr else if(isa<BinaryExprAST>(arg)){ BinaryExprAST *bin_expr = dyn_cast<BinaryExprAST>(arg); arg_v=generateBinaryExpression(dyn_cast<BinaryExprAST>(arg)); if(bin_expr->getOp()=="="){ VariableAST *var= dyn_cast<VariableAST>(bin_expr->getLHS()); arg_v=Builder->CreateLoad(vs_table.lookup(var->getName()), "arg_val"); } } //isVar else if(isa<VariableAST>(arg)) arg_v=generateVariable(dyn_cast<VariableAST>(arg)); //isNumber else if(isa<NumberAST>(arg)){ NumberAST *num=dyn_cast<NumberAST>(arg); arg_v=generateNumber(num->getNumberValue()); } arg_vec.push_back(arg_v); } return Builder->CreateCall( Mod->getFunction(call_expr->getCallee()), arg_vec,"call_tmp" ); } /** * ジャンプ(今回はreturn命令のみ)生成メソッド * @param JumpStmtAST * @return 生成したValueのポインタ */ Value *CodeGen::generateJumpStatement(JumpStmtAST *jump_stmt){ BaseAST *expr=jump_stmt->getExpr(); Value *ret_v; if(isa<BinaryExprAST>(expr)){ ret_v=generateBinaryExpression(dyn_cast<BinaryExprAST>(expr)); }else if(isa<VariableAST>(expr)){ VariableAST *var=dyn_cast<VariableAST>(expr); ret_v = generateVariable(var); }else if(isa<NumberAST>(expr)){ NumberAST *num=dyn_cast<NumberAST>(expr); ret_v=generateNumber(num->getNumberValue()); } Builder->CreateRet(ret_v); } /** * 変数参照(load命令)生成メソッド * @param VariableAST * @return 生成したValueのポインタ */ Value *CodeGen::generateVariable(VariableAST *var){ ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable(); return Builder->CreateLoad(vs_table.lookup(var->getName()), "var_tmp"); } Value *CodeGen::generateNumber(int value){ return ConstantInt::get( Type::getInt32Ty(getGlobalContext()), value); }
true
d6f793d7974582cd95e22a99daed68b468e37789
C++
Ketan-Suthar/Algorithms
/Bit Algorithms/MakeSumEvenByAddingMinNum.cpp
UTF-8
396
3.640625
4
[]
no_license
#include <iostream> using namespace std; // Function to find out minimum number int minNum(int arr[], int n) { // Count odd number of terms in array int odd = 0; for (int i = 0; i < n; i++) if (arr[i] % 2) odd += 1; return (odd % 2)? 1 : 2; } // Driver code int main() { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout << minNum(arr, n); return 0; }
true
a43a9f7143559291f4ac6f41495d421ac1c1dca2
C++
skryabiin/core
/console/src/DebugConsole.cpp
UTF-8
9,078
2.8125
3
[ "MIT" ]
permissive
// DebugConsole.cpp : Defines the entry point for the console application. // // Echoes all input to stdout. This will be redirected by the redirect // sample. Compile and build child.c as a Win32 Console application and // put it in the same directory as the redirect sample. // #include "DebugConsole.hpp" namespace core { TextInput::TextInput() { _isStarted = false; } TextInput::TextInput(TTF_Font* font, SDL_Renderer* renderer) { _isStarted = false; _consoleDebugColor.a = 0xFF; _consoleDebugColor.b = 0x00; _consoleDebugColor.g = 0xFF; _consoleDebugColor.r = 0x00; _font = font; _renderer = renderer; _text = ""; } void TextInput::start() { _isStarted = true; _text = ""; _renderText(); } void TextInput::appendText(const char* text) { if (!_isStarted) return; _text = _text.append(text); _renderText(); } void TextInput::backspace() { if (_text.length() == 0) return; if (_text.length() == 1) { _text = ""; _renderText(); return; } _text = _text.substr(0, _text.length() - 1); _renderText(); } bool TextInput::isStarted() const { return _isStarted; } std::string TextInput::getText() const { return _text; } void TextInput::draw() const { if (!_isStarted) return; SDL_RenderCopy(_renderer, _renderedText, &_source, &_target); } void TextInput::stop() { _text = ""; SDL_DestroyTexture(_renderedText); _isStarted = false; } void TextInput::_renderText() { std::string text = ">" + _text + "_"; auto tempSurf = TTF_RenderText_Solid(_font, text.c_str(), _consoleDebugColor); _target.w = tempSurf->w; _target.h = tempSurf->h; _target.x = 5; _target.y = SCREEN_HEIGHT - 20; _source.x = 0; _source.y = 0; _source.w = tempSurf->w; _source.h = tempSurf->h; _renderedText = SDL_CreateTextureFromSurface(_renderer, tempSurf); SDL_FreeSurface(tempSurf); tempSurf = nullptr; } Message::Message() { _renderedText = nullptr; } void Message::init(std::string text, TTF_Font* font, SDL_Renderer* renderer) { _text = text; auto color = getColor(text); auto tempSurf = TTF_RenderText_Solid(font, _text.c_str(), color); _target.w = tempSurf->w; _target.h = tempSurf->h; _target.x = 5; _source.x = 0; _source.y = 0; _source.w = tempSurf->w; _source.h = tempSurf->h; _renderedText = SDL_CreateTextureFromSurface(renderer, tempSurf); SDL_FreeSurface(tempSurf); tempSurf = nullptr; } SDL_Color Message::getColor(std::string text) { auto severity = text.substr(0, 5); if (!severity.compare("[fata")) { auto consoleFatalColor = SDL_Color{}; consoleFatalColor.a = 0xFF; consoleFatalColor.b = 0xFF; consoleFatalColor.g = 0xFF; consoleFatalColor.r = 0xFF; return consoleFatalColor; } else if (!severity.compare("[warn")) { auto consoleWarnColor = SDL_Color{}; consoleWarnColor.a = 0xFF; consoleWarnColor.b = 0x00; consoleWarnColor.g = 0xAA; consoleWarnColor.r = 0xAA; return consoleWarnColor; } else if (!severity.compare("[noti")) { auto consoleNoticeColor = SDL_Color{}; consoleNoticeColor.a = 0xFF; consoleNoticeColor.b = 0xFF; consoleNoticeColor.g = 0xAA; consoleNoticeColor.r = 0xAA; return consoleNoticeColor; } else if (!severity.compare("[erro")) { auto consoleErrorColor = SDL_Color{}; consoleErrorColor.a = 0xFF; consoleErrorColor.b = 0x00; consoleErrorColor.g = 0x00; consoleErrorColor.r = 0xFF; return consoleErrorColor; } else if (!severity.compare("[dbug")) { auto consoleErrorColor = SDL_Color{}; consoleErrorColor.a = 0xFF; consoleErrorColor.b = 0xCC; consoleErrorColor.g = 0xCC; consoleErrorColor.r = 0xCC; } else { auto consoleDebugColor = SDL_Color{}; consoleDebugColor.a = 0xFF; consoleDebugColor.b = 0x00; consoleDebugColor.g = 0xFF; consoleDebugColor.r = 0x00; return consoleDebugColor; } } std::string Message::getText() const { return _text; } void Message::draw(SDL_Renderer* renderer, int pos, int &_cursorY, bool _didScroll) { _target.y = (FONT_SIZE + FONT_BUFFER) *(pos - _cursorY) + 2; if (!_didScroll && (_target.y + _target.h) > SCREEN_HEIGHT - FONT_SIZE) { _cursorY++; _target.y = (FONT_SIZE + FONT_BUFFER) *(pos - _cursorY) + 2; } SDL_RenderCopy(renderer, _renderedText, &_source, &_target); } void Message::destroy() { SDL_DestroyTexture(_renderedText); } void DebugConsole::clearMessages() { for (auto it = std::begin(_messages); it != std::end(_messages); ++it) { it->destroy(); } _messages.clear(); _cursorY = 0; _didScroll = false; } void DebugConsole::run() { SDL_Init(SDL_INIT_VIDEO); TTF_Init(); auto sdlWindow = SDL_CreateWindow("Core Debugger", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); _sdlRenderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED); SDL_SetRenderDrawColor(_sdlRenderer, 0x00, 0x00, 0x00, 0xFF); SDL_SetRenderDrawBlendMode(_sdlRenderer, SDL_BLENDMODE_BLEND); auto consoleTextcolor = SDL_Color{}; consoleTextcolor.a = 0xFF; consoleTextcolor.b = 0x00; consoleTextcolor.g = 0xFF; consoleTextcolor.r = 0x00; _ttfConsoleFont = TTF_OpenFont(FONT_PATH, FONT_SIZE); _gogogo = true; SDL_Event e{}; _cursorY = 0; _didScroll = false; _textInput = TextInput{ _ttfConsoleFont, _sdlRenderer }; while (_gogogo) { if (!_logFile.is_open()) { _logFile.clear(); SDL_Delay(100); _logFile.open(LOG_FILE_PATH, std::ios::in); } else { SDL_Delay(20); std::string thisLine; std::string thisMessage = ""; while (std::getline(_logFile, thisLine)) { if (thisLine[0] == '[' && thisMessage.compare("")) { addMessage(thisMessage); thisMessage = thisLine; } else { thisMessage = thisMessage + thisLine; addMessage(thisMessage); thisMessage = ""; } if (_logFile.eof()) { addMessage(thisMessage); thisMessage = ""; } } _logFile.clear(); } SDL_RenderClear(_sdlRenderer); int depth = 0; for (auto it = std::begin(_messages); it != std::end(_messages); it++) { it->draw(_sdlRenderer, depth, _cursorY, _didScroll); depth++; } _textInput.draw(); SDL_RenderPresent(_sdlRenderer); while (SDL_PollEvent(&e) != 0) { switch (e.type) { case SDL_TEXTINPUT: if (_textInput.isStarted()) { _textInput.appendText(e.text.text); } break; case SDL_MOUSEWHEEL: _cursorY -= e.wheel.y; _cursorY = (_cursorY > 0) ? _cursorY : 0; if (_cursorY > 0) { _didScroll = true; } break; case SDL_KEYDOWN: if (_textInput.isStarted()) { std::string result; switch (e.key.keysym.sym) { case SDLK_ESCAPE: _textInput.stop(); SDL_StopTextInput(); break; case SDLK_RETURN: result = parseCommand(_textInput.getText()); if (result.compare("")) { addMessage(result); } _textInput.stop(); SDL_StopTextInput(); break; case SDLK_BACKSPACE: _textInput.backspace(); break; } } else { switch (e.key.keysym.sym) { case SDLK_RETURN: _didScroll = false; _textInput.start(); SDL_StartTextInput(); break; case SDLK_DELETE: if (_logFile.is_open()) { _logFile.close(); } _logFile.open(LOG_FILE_PATH, std::ios::out | std::ios::trunc); _logFile.close(); case SDLK_BACKSPACE: clearMessages(); _cursorY = 0; _didScroll = false; break; case SDLK_SPACE: _didScroll = false; break; } } break; case SDL_QUIT: _gogogo = false; break; } } } if (_logFile.is_open()) { _logFile.close(); } clearMessages(); TTF_CloseFont(_ttfConsoleFont); TTF_Quit(); SDL_DestroyRenderer(_sdlRenderer); SDL_DestroyWindow(sdlWindow); SDL_Quit(); } void DebugConsole::addMessage(std::string text) { text = (!text.compare("")) ? " " : text; _messages.emplace_back(); _messages.back().init(text, _ttfConsoleFont, _sdlRenderer); } void DebugConsole::purgeLog() { if (_logFile.is_open()) { _logFile.close(); } _logFile.open(LOG_FILE_PATH, std::ios::out | std::ios::trunc); _logFile.close(); _logFile.clear(); } std::string DebugConsole::parseCommand(std::string input) { if (!input.compare("clear")) { clearMessages(); return "--Screen Cleared."; } else if (!input.compare("purge")) { purgeLog(); clearMessages(); return "--Log Purged."; } else if (!input.compare("quit")) { _gogogo = false; return "--Quitting."; } else if (!input.compare("filestatus")) { std::string isopen = (_logFile.is_open()) ? "open." : "closed."; _logFile.close(); return "--Log file is " + isopen; } else { return "--Unknown Command: " + input; } } }
true
849a048d520819931b4a0b66e8ff176447eaf885
C++
YaniAngel/CG_2DSnakeGame
/CG_2DSnakeGame/CG_2DSnakeGame/src/main.cpp
UTF-8
2,362
3
3
[]
no_license
#include <GL/glut.h> #include <iostream> #include "Game.h" const unsigned int tileCount = 30; Game snake(tileCount); void renderScene(); void processKeyboard(int, int, int); void changeSize(int, int); void refreshScene(int); int main(int argc, char** argv) { // Init GLUT and create window glutInit(&argc, argv); glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(800, 800); glutCreateWindow("2D Snake Game"); // Register callbacks glutDisplayFunc(renderScene); glutReshapeFunc(changeSize); glutSpecialFunc(processKeyboard); // Refresh so the snake keeps moving glutTimerFunc(1000.0/10.0, refreshScene, 0); // enter GLUT event processing cycle glutMainLoop(); return 1; } void renderScene() { // Exits the game if gameOver is set to true if (snake.isGameOver()) { exit(0); } // Clear Color and Depth Buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Reset transformations glLoadIdentity(); // Draw everything snake.drawGrid(); snake.drawFood(); snake.drawSnake(); glutSwapBuffers(); } void changeSize(int w, int h) { // Prevent a divide by zero, when window is too short if (h == 0) h = 1; // Use the Projection Matrix glMatrixMode(GL_PROJECTION); // Set the viewport to be the entire window glViewport(0, 0, w, h); // Reset Matrix glLoadIdentity(); // Set the coordinate system to 40 by 40 glOrtho(0.0, (float)tileCount, 0.0, (float)tileCount, -1.0, 1.0); // Get Back to the Modelview glMatrixMode(GL_MODELVIEW); } void refreshScene(int) { // Update animation glutPostRedisplay(); // Keep updating glutTimerFunc(1000.0/10.0, refreshScene, 0); } void processKeyboard(int key, int x, int y) { // Changes direction of the snake // Can't change into opposite direction switch (key) { case GLUT_KEY_UP: if (snake.getSnakeDirection() != DOWN) snake.setSnakeDirection(UP); break; case GLUT_KEY_DOWN: if (snake.getSnakeDirection() != UP) snake.setSnakeDirection(DOWN); break; case GLUT_KEY_RIGHT: if (snake.getSnakeDirection() != LEFT) snake.setSnakeDirection(RIGHT); break; case GLUT_KEY_LEFT: if (snake.getSnakeDirection() != RIGHT) snake.setSnakeDirection(LEFT); break; } }
true
fb66bab60c90fa26b1544f8d5ad3516e1684c954
C++
its-sachin/InterviewBit
/Array/largetNum.cpp
UTF-8
735
3.171875
3
[]
no_license
#include <iostream> #include <bits\stdc++.h> using namespace std; bool comp(string a, string b){ string one = a.append(b); string two = b.append(a); return one>two; } string largestNumber(vector<int> &A){ vector<string> a; for(int i:A){ a.push_back(to_string(i)); } sort(a.begin(),a.end(),comp); string ans = ""; for(string i:a){ ans.append(i); } int i=0; while(i+1<a.size() and ans[i]=='0'){ i++; } return ans.substr(i); } int main(int argc, char const *argv[]) { vector<int> a; int n; cin>>n; for(int i=0; i<n; i++){ int ai; cin>>ai; a.push_back(ai); } cout<<largestNumber(a)<<endl; return 0; }
true
f59a866d2c2911fa821c45ccf7893d76591a3e19
C++
RichardTimothy1307/DSA_in_CPP
/Bit_Manipulation/string_diff.cpp
UTF-8
362
2.90625
3
[]
no_license
class Solution { public: char findTheDifference(string s, string t) { char becomenull=0; int i=0; for(i=0;i<s.size();i++){ becomenull^=s[i]^t[i]; //will make all character null till n-1 } return becomenull^t[i]; //null xor with last char will give char } };
true