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
06fa651a7d864477732d7b4d003e609696499e6c
C++
exgs/42
/wip/CPP Modules/03/ex02/FragTrap.cpp
UTF-8
2,825
3.03125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* FragTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ecaceres <ecaceres@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/07 12:58:52 by ecaceres #+# #+# */ /* Updated: 2020/01/07 12:58:52 by ecaceres ### ########.fr */ /* */ /* ************************************************************************** */ #include <iostream> #include <string> #include "FragTrap.hpp" FragTrap::FragTrap(void) : ClapTrap() { return ; } FragTrap::FragTrap(std::string name) : ClapTrap(name) { this->_energyPoints = 100; this->_maxEnergyPoints = 100; this->_name = name; this->_meleeAttackDamage = 30; this->_rangedAttackDamage = 20; this->_armorDamageReduction = 5; std::string vaulthunterAttacks[] = { "Fireball", "Waterball", "Airball", "Earthball", "Lightball" }; long vaulthunterDamages[] = { 10, 12, 2, 23, 1 }; std::memcpy(&(this->_vaulthunterAttacks), &vaulthunterAttacks, sizeof(vaulthunterAttacks)); std::memcpy(&(this->_vaulthunterDamages), &vaulthunterDamages, sizeof(vaulthunterDamages)); std::cout << this->_name << ": ready!" << std::endl; } FragTrap::FragTrap(const FragTrap &other) : ClapTrap(other) { *this = other; std::cout << this->_name << ": assigned!" << std::endl; } FragTrap::~FragTrap(void) { std::cout << this->_name << ": destroyed!" << std::endl; } FragTrap & FragTrap::operator =(const FragTrap &right) { ClapTrap::operator =(right); if (this != &right) { std::memcpy(&(this->_vaulthunterAttacks), &(right._vaulthunterAttacks), sizeof(this->_vaulthunterAttacks)); std::memcpy(&(this->_vaulthunterDamages), &(right._vaulthunterDamages), sizeof(this->_vaulthunterDamages)); } std::cout << this->_name << ": assigned!" << std::endl; return (*this); } void FragTrap::vaulthunter_dot_exe(std::string const &target) { int random = rand() % 5; std::string attack = this->_vaulthunterAttacks[random]; long damage = this->_vaulthunterDamages[random]; if (this->_energyPoints >= 25) { this->_energyPoints -= 25; std::cout << this->_name << ": attacked " << target << " with " << attack << " and do " << damage << " damage(s)." << std::endl; } else { std::cout << this->_name << ": not enought energy point to use vaulthunter_dot_exe on " << target << "." << std::endl; } }
true
4a83322caf09d04e5efc24d304cbc4739af621a3
C++
AVZhelyazkov18/avzhelyazkov18-20210202
/avzhelyazkov18-20210202/avzhelyazkov18.cpp
UTF-8
1,952
3.125
3
[]
no_license
#include "avzhelyazkov18.h" #include <iostream> #include <vector> #include <string> using namespace std; void initLaptops(vector<LAPTOP> &laptops) { LAPTOP laptop1; laptop1.mf = "Asus"; laptop1.dateOfRelease = 2017; laptop1.CPU = "Intel I7"; laptop1.GPU = "Geforce 960M"; laptops.push_back(laptop1); laptops.push_back({ "MSI", "Intel Core I7", "Geforce 2060", 2020 }); laptops.push_back({ "MSI1", "Intel Core I7", "Geforce 2060", 2020 }); laptops.push_back({ "MSI2", "Intel Core I7", "Geforce 2060", 2020 }); laptops.push_back({ "MSI3", "Intel Core I7", "Geforce 2060", 2020 }); } void showLaptop(vector<LAPTOP>& laptops,int index) { if (laptops.at(index).mf != "" or laptops.at(index).mf != " ") cout << laptops.at(index).mf << ", " << laptops.at(index).CPU << ", " << laptops.at(index).GPU << ", " << laptops.at(index).dateOfRelease << "." << endl; } void createLaptop(vector<LAPTOP>& laptops, LAPTOP laptop) { laptops.push_back(laptop); } LAPTOP enterLaptop(LAPTOP laptop) { cout << "Enter Manufacturer: "; cin >> laptop.mf; cin.ignore(); cout << "CPU Example: (Intel I7/I5)" << endl; cout << "Enter CPU: "; getline(cin, laptop.CPU); cout << "GPU Example: (Geforce 970M/1050Ti/960M/etc.)" << endl; cin.ignore(); cout << "Enter GPU: "; getline(cin, laptop.GPU); cout << "Enter Date Of Release: "; cin >> laptop.dateOfRelease; return laptop; } void showLaptops(vector<LAPTOP>& laptops) { for (int i = 0; i < laptops.size(); i++) { if (laptops.at(i).mf != "" or laptops.at(i).mf != " ") showLaptop(laptops, i); } } vector<LAPTOP> findGPUsByLaptop(vector<LAPTOP>& laptops) { string chosenCPU; vector<LAPTOP> foundLaptops = {}; cout << "Example: (AMD/Intel)" << endl; cout << "Choose what type of cpu to find: "; cin >> chosenCPU; for (int i = 0; i < laptops.size(); i++) { if (laptops.at(i).CPU.find(chosenCPU)) { foundLaptops.at(foundLaptops.size() + 1) = laptops.at(i); } } return foundLaptops; }
true
f05bef8c35021a9a98654ca3a07816a16fa5f53e
C++
SCVision/Utilities
/includes/URG04Kit.hpp
GB18030
5,823
2.75
3
[]
no_license
// URG04Kit.HPP // // Tool kit for URG04 laser range finder, C++ version. // by Lin, Jingyu, linjy02@hotmail.com, 2019.9 // // ʹ÷ // 1. URG04Device // 2. StartScan()ѡ豸ڴڲǡڿֱָSearchURG04Device()ѯ // Close()رļǡURG04DeviceʱԶرļǡ // 3. ReadScanAngle()ȡݶӦɨ顣鲻 // 4. ʱ100msReadRange()ȡݼʱδȥ // 5. вݴֵ̫С<20mm˵෶ΧԾ档 // 6. ҪRangeToMap()תΪάͼԱʾ // // ޸ļ¼ // 20190907ϲڹܣҪWinComPort.dll // #ifndef URG04Kit_HPP #define URG04Kit_HPP class __declspec(dllexport) URG04Device { public: URG04Device(); ~URG04Device(); /************************ ѯ豸 ************************/ // ܣѯӵļǡ // ֵϵͳмǵ // ˵β豸Ҫٴεô˺пUSB豸ʶΪǡ static int SearchURG04Device(); // ܣȡǵƺʹںšSearchURG04Device()Ч // 룺idx - ǵš // ComNo - ڶ˿ںţCOMxеxЧڵĶ˿ںΪ-1 // ֵַָ롣NULLʾų豸 static char* GetURG04Port(int idx, int& ComNo); // ܣϵͳмǵδùSearchURG04Device()򷵻-1޼򷵻0 static int GetURG04Total(); /************************ 豸 ************************/ // ܣָϵURGǡɹɼݣÿݲɼʱΪ100ms // ReadRange()ʱȡݡ // 룺ComNo - ǵĴںš // ޡ // ֵ1ʾɹǡ0ʾǼǡ int StartScan(int ComNo); // ܣرURGǣֹͣɼݡ // ˵URG04DeviceʱԶô˺ void Close(); /************************ ȡ ************************/ // ܣȡݶӦɨǣradszThetathetaΪNULLɨǵszTheta // 룺theta[] - ɨǻСΪszTheta // theta[] - ɨ顣 // ֵɨǵszThetaݵЧɨķΧ // ˵ǽһܣ360㣩Ϊ1024ɨǵĵλΪ360/1024=0.3516㡣 // ҶԳɨ衣ǰɨΪ0ʱ뷽Ϊ // szTheta=0ұߣszTheta/2-1ǰszTheta-1ߡ int ReadScanAngle(double* theta); // ܣȡݣmʱszRangeΪNULL򲻷Ӧݡ // 룺range[], range0[] - ݻСΪszRange // timeStamp, timeStamp0 - ڻȡʱ // range[], range0[] - ϴεIJݣÿɨǶӦһֵ // *timeStamp, *timeStamp0 - ݵʱ // ֵݵszRangeɨǵ // ˵ǽһܣ360㣩Ϊ1024ɨǵĵλΪ360/1024=0.3516㡣 // ҶԳɨ衣ǰɨΪ0ʱ뷽Ϊ // szRange=0ұߣszRange/2ǰszRange-1ߡ int ReadRange(double* range, int* timeStamp, double* range0 = NULL, int* timeStamp0 = NULL); /************************ 豸Ϣ ************************/ // ܣж豸Ƿ // ֵ1ʾ0ʾѹرա int IsActive(); // ܣ豸Ĵڶ˿ںš-1ʾδ int GetActiveURGComNo(); // ܣݼ¼״̬logļΪurgRange.txt void SetDataLog(int bLog); int GetDataLog(); /************************ ************************/ // ܣתΪάͼ // 룺map[mapRow][mapCol] - άͼr_front - ͼĵͼе루mڳ߶ȱ任 // steering - תǣȣͼϷΪ0ʱΪ˳ʱΪ // range[szRange] - ReadRange()ȡIJݻ򾭹IJݣmszRange=-1ʾϵͳȱʡֵ // stepAngle - ɨDzȣstepAngle=-1ʾϵͳȱʡֵ // map - άͼУÿȡֵ0ʾ0xFFʾڵ // ˵λڵͼģr_frontӦͼmapRow/2ľ롣 // ReadScanAngle()ԻszRangeֵڵɨ֮stepAngle static void RangeToMap(unsigned char *map, int mapRow, int mapCol, double r_front, double steering, double* range, int szRange = -1, double stepAngle = -1); private: char privatedata[24]; // 24 bytes for x64, 12 bytes for Win32 }; #endif // #ifndef URG04Kit_HPP
true
0c45a430cc128907178a3cc93b91eb0fa851be0d
C++
tufei/Halide-elements
/src/sgm/sgm_test.cc
UTF-8
1,151
2.5625
3
[ "MIT" ]
permissive
#include <iostream> #include "HalideRuntime.h" #include "HalideBuffer.h" #include "test_common.h" #include "run_common.h" #include "sgm.h" using namespace Halide::Runtime; int main(int argc, char **argv) { try { Buffer<uint8_t> in_l = load_pgm("data/left.pgm"); Buffer<uint8_t> in_r = load_pgm("data/right.pgm"); const int width = in_l.extent(0); const int height = in_l.extent(1); Buffer<uint8_t> out(width, height); sgm(in_l, in_r, out); Buffer<uint8_t> disp = load_pgm("data/disp.pgm"); save_pgm("out_test.pgm", out.data(), width, height); for (int y=0; y<height; ++y) { for (int x=0; x<width; ++x) { uint8_t ev = disp(x, y); uint8_t av = out(x, y); if (ev != av) { throw std::runtime_error(format("Error: expect(%d, %d) = %d, actual(%d, %d) = %d", x, y, ev, x, y, av).c_str()); } } } } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } printf("Success!\n"); return 0; }
true
7a42f77eaefbb7001b9d793bfc869d49c7b40fb9
C++
bdomitil/CPP-module-08
/ex00/easyfind.hpp
UTF-8
349
2.9375
3
[]
no_license
#ifndef EASYFIND_HPP #define EASYFIND_HPP #include <iostream> #include <array> #include <set> template <typename T> typename T::iterator easy_find(T &container, int x) { if ((std::find(container.begin(), container.end() , x)) == container.end()) throw std::exception(); return ( std::find(container.begin(), container.end() , x) ); } #endif
true
25ab3ab08ba5023563d88017b429de38b8e98a1a
C++
HiteshBhragu/100-days-of-code
/C++/sum_of_diagonal.cpp
UTF-8
667
3.796875
4
[]
no_license
#include<iostream> #define ROWS 3 #define COLS 3 using namespace std; int sum_of_diagonal(int[][COLS], int); int main() { int matrix[ROWS][ROWS]={ {1,2,3}, {2,3,4}, {3,4,5} }; int row,col,sum; for(row=0;row<ROWS;row++) { for(col=0;col<COLS;col++) { cout<<"Enter the number = "; cin>>matrix[row][col]; } cout<<endl; } cout<<endl; sum = sum_of_diagonal( matrix,ROWS); cout<<"The sum of diagonal is = "<<sum; } int sum_of_diagonal(int matrix[][COLS],int size) { int row,sum=0; for(row=0;row<size;row++) { sum=sum+matrix[row][row]; } return sum; }
true
9911bf47c75231638dab4408101ab460b32416e7
C++
janfredrikaasmundtveit/compfys
/project_2/jacobi.cpp
UTF-8
1,687
2.734375
3
[]
no_license
#include <iostream> #include <fstream> #include <iomanip> #include <cmath> #include <string> #include <time.h> #include "linalg.h" #include "jacobi.h" #include "catch.hpp" void Jacobi_rotate ( double **A, double **R, int k, int l, int n ){ double s, c; if ( A[k][l] != 0.0 ) { double t, tau; tau = (A[l][l] - A[k][k])/(2*A[k][l]); // 3 flops if ( tau >= 0 ) { t = 1.0/(tau + sqrt(1.0 + tau*tau)); //5 flops } else { t = -1.0/(-tau +sqrt(1.0 + tau*tau)); } c = 1/sqrt(1+t*t); // 4 flops s = c*t; } else { c = 1.0; s = 0.0; } double a_kk, a_ll, a_ik, a_il, r_ik, r_il; a_kk = A[k][k]; a_ll = A[l][l]; A[k][k] = c*c*a_kk - 2.0*c*s*A[k][l] + s*s*a_ll; A[l][l] = s*s*a_kk + 2.0*c*s*A[k][l] + c*c*a_ll; //22 flops A[k][l] = 0.0; // hard-coding non-diagonal elements by hand A[l][k] = 0.0; // same here for ( int i = 0; i < n; i++ ) { if ( i != k && i != l ) { a_ik = A[i][k]; a_il = A[i][l]; A[i][k] = c*a_ik - s*a_il; A[k][i] = A[i][k]; A[i][l] = c*a_il + s*a_ik; A[l][i] = A[i][l]; // 6n flops } // And finally the new eigenvectors r_ik = R[i][k]; r_il = R[i][l]; R[i][k] = c*r_ik - s*r_il; R[i][l] = c*r_il + s*r_ik; } return; } /* // the offdiag function, using Armadillo void offdiag(double **A, int* p, int* q, int n, double* max) { //p=new int; q=new int; for (int i = 0; i < n; ++i) { for ( int j = i+1; j < n; ++j) { double aij = fabs(A[i][j]); if ( aij > *max) { *max = aij; *p = i; *q = j; } } } return; } */
true
2adc19a31290ad9d75949a34967c1090450b9e57
C++
jmbrito01/PointBlank-Reverser
/PointBlank Reverser/Helpers/ProcessHelper.h
UTF-8
1,211
2.828125
3
[]
no_license
#pragma once #include "..\Includes.h" class ProcessHelper { public: ProcessHelper(HANDLE hProc); DWORD GetImageBase(); char* GetProcessName(); void* Read(DWORD Address, DWORD size); template<typename t> t* Read(DWORD Address); template<typename t> void Write(DWORD Address, t value); int GetExternalStrLen(DWORD Address); DWORD GetSectionVirtualAddress(char* sectionName); DWORD GetSectionVirtualSize(char* sectionName); PIMAGE_DOS_HEADER GetDOSHeader(); PIMAGE_NT_HEADERS GetNTHeaders(); PIMAGE_SECTION_HEADER GetSectionHeader(int iSection); PIMAGE_SECTION_HEADER GetCodeSection(); HANDLE GetHandle(); ~ProcessHelper(); public: static DWORD GetProcessIDbyName(char* lpName); private: static string toLower(string s); HANDLE hProcess; }; template <typename t> inline t * ProcessHelper::Read(DWORD Address) { t* result = (t*)VirtualAlloc(NULL, sizeof(t) + 1, MEM_COMMIT, PAGE_READWRITE); ZeroMemory(result, sizeof(result)); ReadProcessMemory(hProcess, (void*)Address, (void*)result, sizeof(t), NULL); return result; } template <typename t> inline void ProcessHelper::Write(DWORD Address, t value) { WriteProcessMemory(hProcess, (void*)Address, (void*)&value, sizeof(value), NULL); }
true
9f49bcf1397b03c8d9993d87a9fce1886e0402a4
C++
muellesi/PSE_2018
/PSE_2018_Gruppe1/src/FollowMarkerModule.hpp
UTF-8
1,503
2.984375
3
[]
no_license
/////////////////////////////////////////////////////////// // FollowMarkerModule.h // Implementation of the Class FollowMarkerModule // Created on: 05-Jun-2018 14:42:04 // Original author: student /////////////////////////////////////////////////////////// #pragma once #include "DriveCommandPublisher.hpp" #include "DataProcessModule.hpp" #include "PIDController.hpp" /** * \brief This module retrieves the markerList from the SensorManager, checks for markers and tries to follow * the one with the best confidence until it loses track of it. * After that, it follows the next marker with the highest confidence. */ class FollowMarkerModule : public DriveCommandPublisher, public DataProcessModule { public: /** * \brief Constructs a new FollowMarkerModule. */ FollowMarkerModule(); ~FollowMarkerModule() override; /** * \brief Main update function that gets called periodically. */ void processData() override; /** * \brief Sets the desired distance that will be used as for the distance PIDController. * \param distance Desired distance in [m]. */ void setDistance(double distance); /** * \brief CURRENTLEY NOT IN USE! Sets an ID for a marker that will be followed. */ void setMarkerId(int markerId); /** * \brief Resets both PID controllers */ void abort(); private: double m_setDistance; bool m_followsMarker; int m_currentMarkerId; PIDController m_distanceController; PIDController m_steeringController; };
true
cde49b3d29d13e91b3094e0bcb8e73c4a7706195
C++
szmanda/ZSK
/klasa4/CPP/skopul/samochody.cpp
UTF-8
507
2.90625
3
[]
no_license
#include <iostream> using namespace std; int main() { int ile; cin>>ile; bool * samochody = new bool[ile]; for (int i = 0; i < ile; i++) { cin>>samochody[i]; } int suma = 0, wschod = 0, zachod = 0; for (int i = 0, j = ile-1 ; i < ile; i++, j--) { if (samochody[i]==0){ wschod++; } else { suma+=wschod; wschod = 0; } if (samochody[j]==1){ zachod++; } else { suma+=zachod; zachod = 0; } } cout<<suma; return 0; }
true
68bbd61b22dff0ad43fd64faf19702f6a2fde0c3
C++
YeonWon123/My_Problem_Solving
/Atcoder/Panasonic Programming Contest 2020/A/A/A.cpp
UTF-8
370
2.5625
3
[]
no_license
#include <iostream> #include <cstring> #include <string> #include <algorithm> #include <vector> using namespace std; int a[32] = { 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 }; int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; cout << a[t - 1]; return 0; }
true
b03ceade190db19d318105004e065f0a23bcb395
C++
zhuangqf-sysu/PAT
/src/pat/Advance1101.cpp
UTF-8
879
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int myList[100001]; int isPivot[100001]; vector<int>answer; int main() { int n; cin>>n; for(int i=0;i<n;i++){ cin>>myList[i]; isPivot[i] = true; } int leftMaxValue = myList[0]; for(int i=0;i<n;i++) { if(myList[i]>=leftMaxValue) leftMaxValue = myList[i]; else isPivot[i] = false; } int rightMinValue = myList[n-1]; for(int i=n-1;i>=0;i--) { if(myList[i]<=rightMinValue) rightMinValue = myList[i]; else isPivot[i] = false; } for(int i=0;i<n;i++) if(isPivot[i]) answer.push_back(myList[i]); sort(answer.begin(),answer.end()); cout<<answer.size()<<endl; if(!answer.empty()) cout<<answer[0]; for(int i=1;i<answer.size();i++) cout<<" "<<answer[i]; cout<<endl; }
true
457758b83145f95a681a1b231b3283cfd27fb88c
C++
Nickqiaoo/cppim
/common/util.hpp
UTF-8
540
2.875
3
[]
no_license
#pragma once #include <string> #include <vector> namespace common { typedef std::vector<std::string> Tokens; inline void split(const std::string & src, const std::string & sep, std::vector<std::string> & tokens) { tokens.clear(); std::string s; for(auto ch : src) { if (sep.find(ch) != std::string::npos) { tokens.push_back(s); s = ""; } else { s += ch; } } if ( s.length() || tokens.size() ) { tokens.push_back(s); } } } // namespace common
true
ff5dbe0e5cb705225748a8793e79a9ccfd52381f
C++
ankitsumitg/mrnd-c
/Step_13/spec/MergeBSTsSpec.cpp
UTF-8
6,307
3.09375
3
[]
no_license
#include "stdafx.h" #include <stdlib.h> #include "../src/MergeBSTs.cpp" using namespace System; using namespace System::Text; using namespace System::Collections::Generic; using namespace Microsoft::VisualStudio::TestTools::UnitTesting; namespace spec { [TestClass] public ref class MergeBSTsSpec { private: TestContext^ testContextInstance; public: /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext { Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get() { return testContextInstance; } System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value) { testContextInstance = value; } }; #pragma region Additional test attributes #pragma endregion struct BstNode *newNode_mergeBST(int key){ struct BstNode *temp = (struct BstNode *)malloc(sizeof(struct BstNode)); temp->data = key; temp->left = NULL; temp->right = NULL; return temp; } struct BstNode * insertNode_mergeBST(struct BstNode *root, int data) { if (root == NULL) return newNode_mergeBST(data); if (data < root->data) root->left = insertNode_mergeBST(root->left, data); else if (data > root->data) root->right = insertNode_mergeBST(root->right, data); return root; } struct BstNode * create_BST(int *arr, int len) { struct BstNode *root = NULL; for (int i = 0; i < len; i++) { root = insertNode_mergeBST(root, arr[i]); } return root; } int searchNode(struct BstNode *root, BstNode *node) { if (root == NULL) return 0; if (root == node && root->data == node->data) return 1; return searchNode(root->left,node) || searchNode(root->right,node); } void test_mergeBSTs(struct BstNode *root,struct BstNode *Nodes[],int len) { for (int i = 0; i < len; i++) { if (searchNode(root, Nodes[i]) == 0) { Assert::AreEqual(-1,Nodes[i]->data, L"Node not found in bst1", 1, 2); } } } void addToArray(BstNode **Nodes,BstNode *Node, int &len) { for (int i = 0; i < len; i++) { if (Nodes[i]->data == Node->data) return; } Nodes[len++] = Node; } void addNodes(struct BstNode *root, BstNode **Nodes, int &len) { if (root == NULL) return; addNodes(root->left, Nodes, len); addToArray(Nodes, root, len); addNodes(root->right, Nodes, len); } int totalNodeCount(struct BstNode *root) { if (root == NULL) { return 0; } else { return 1 + totalNodeCount(root->left) + totalNodeCount(root->right); } } [TestMethod, Timeout(1000)] void MergeBST_Test01() { int b1[] = { 20,5,30 }; int len1 = 3; int b2[] = { 25,10,35 }; int len2 = 3; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = create_BST(b1,len1); BstNode *bst2 = create_BST(b2,len2); addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); //Assert::AreEqual(len, len1 + len2, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes,len); }; [TestMethod, Timeout(1000)] void MergeBST_Test02() { int b1[] = { 20,5,30 }; int len1 = 3; int b2[] = { 25,10,35 ,5,20}; int len2 = 5; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = create_BST(b1, len1); BstNode *bst2 = create_BST(b2, len2); addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); //Assert::AreEqual(len, len1 + len2 - 2, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; [TestMethod, Timeout(1000)] void MergeBST_Test03() { int b1[] = { 1,2,3,4,5,6,7,8,9 }; int len1 = 9; int b2[] = { 1,2,3,4,5,6,7,8,9,10 }; int len2 = 10; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = create_BST(b1, len1); BstNode *bst2 = create_BST(b2, len2); addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); Assert::AreEqual(len, len1+1, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; [TestMethod, Timeout(1000)] void MergeBST_Test04() { int b1[] = { 1,2,3,4,5,6,7,8,9,10 }; int len1 = 10; int b2[] = { 11,15,99,52 }; int len2 = 4; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = create_BST(b1, len1); BstNode *bst2 = create_BST(b2, len2); addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); Assert::AreEqual(len, len1+len2, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; [TestMethod, Timeout(1000)] void MergeBST_Test05() { int len1 = 0; int b2[] = { 11,15,99,52 }; int len2 = 4; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = NULL; BstNode *bst2 = create_BST(b2, len2); addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); Assert::AreEqual(len, len1 + len2, L"Nodes Length1", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length2", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; [TestMethod, Timeout(1000)] void MergeBST_Test06() { int len1 = 0; int len2 = 0; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = NULL; BstNode *bst2 = NULL; addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); Assert::AreEqual(len, len1 + len2, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; [TestMethod, Timeout(1000)] void MergeBST_Test07() { int b1[] = { 1,2,3,4,5,6,7,8,9,10 }; int len1 = 10; int len2 = 0; BstNode *Nodes[30]; int len = 0; BstNode *bst1 = create_BST(b1, len1); BstNode *bst2 = NULL; addNodes(bst1, Nodes, len); addNodes(bst2, Nodes, len); merge_two_bst(&bst1, bst2); Assert::AreEqual(len, len1 + len2, L"Nodes Length", 1, 2); Assert::AreEqual(len, totalNodeCount(bst1), L"Nodes Length", 1, 2); test_mergeBSTs(bst1, Nodes, len); }; }; }
true
efa56cab7dd8322c9398588f41abe7e7af08924a
C++
skyformat99/ring_buffer
/include/ring_buffer_boost.hpp
UTF-8
1,082
3.5625
4
[ "MIT" ]
permissive
#include <boost/atomic.hpp> template<typename T, size_t Size> class ringbuffer { public: ringbuffer() : head_(0), tail_(0) {} bool push(const T & value) { size_t head = head_.load(boost::memory_order_relaxed); size_t next_head = next(head); if (next_head == tail_.load(boost::memory_order_acquire)) return false; ring_[head] = value; head_.store(next_head, boost::memory_order_release); return true; } bool pop(T & value) { size_t tail = tail_.load(boost::memory_order_relaxed); if (tail == head_.load(boost::memory_order_acquire)) return false; value = ring_[tail]; tail_.store(next(tail), boost::memory_order_release); return true; } private: size_t next(size_t current) { return (current + 1) % Size; } T ring_[Size]; boost::atomic<size_t> head_, tail_; }; #if 0 ringbuffer<int, 32> r; // try to insert an element if (r.push(42)) { /* succeeded */ } else { /* buffer full */ } // try to retrieve an element int value; if (r.pop(value)) { /* succeeded */ } else { /* buffer empty */ } #endif
true
de37c2b945871ef6d27fb9737503cf727c66575f
C++
aldavidramos/RamosAllan_CSC5_45549
/Assignments/Assignment 3/Gaddis_7thEd_Ch4_Prob20_Freezing&BoilingPoint/main.cpp
UTF-8
1,313
3.875
4
[]
no_license
/* * File: main.cpp * Author: Allan Ramos * Created on July 1, 2017, 6:51 PM * Purpose: To determine which elements freeze or boil */ //System Libraries #include <iostream> //Input/Output Library using namespace std; //Namespace of the System Libraries //User Libraries //Global Constants //Function Prototypes //Execution Begins Here! int main(int argc, char** argv) { //Declare Variables float temp; //Temperature input by user //Input Data cout<<"This program will determine whether certain substances will freeze"; cout<<" or boil at a given temperature."<<endl; cout<<"Please enter a temperature in degrees fahrenheit."<<endl; cin>>temp; //Process and Output the Data cout<<"These substances will freeze at the given temperature:"<<endl; if(temp<=-173) cout<<"Ethyl alcohol"<<endl; if(temp<=-38) cout<<"Mercury"<<endl; if(temp<=-362) cout<<"Oxygen"<<endl; if(temp<=32) cout<<"Water"<<endl; cout<<"These substances will boil at the given temperature:"<<endl; if(temp>=172) cout<<"Ethyl alcohol"<<endl; if(temp>=676) cout<<"Mercury"<<endl; if(temp>=-306) cout<<"Oxygen"<<endl; if(temp>=212) cout<<"Water"<<endl; //Exit Stage Right! return 0; }
true
cbf8822f628f5556d04cb70cfca31e568dfee662
C++
oivanyts/CPP_Day00
/Day04/ex03/AMateria.h
UTF-8
623
2.890625
3
[]
no_license
// // Created by Oleh IVANYTSKYI on 2019-10-04. // #ifndef CPP_DAY00_AMATERIA_H #define CPP_DAY00_AMATERIA_H #include <string> #include "ICharacter.h" class AMateria { public: virtual ~AMateria(); AMateria(); AMateria(AMateria const &src); AMateria(std::string const & type); virtual std::string const & getType() const; //Returns the materia type_ virtual unsigned int getXP() const; //Returns the Materia's XP virtual AMateria* clone() const = 0; virtual void use(ICharacter & target); AMateria &operator=(AMateria const &rhs); private: unsigned int xp_; std::string type_; }; #endif //CPP_DAY00_AMATERIA_H
true
417300f1a1a044cc4cd0d8a70f0838b8e02f6006
C++
sachinkj/interview-Prep
/two_missing_nums.cpp
UTF-8
945
3.59375
4
[]
no_license
#include <iostream> #include <cstdlib> #include <array> #include <vector> #include <unordered_set> #include <algorithm> using namespace std; vector <int> two_missing_num_sol1(array<int, 8> a); int main() { array<int, 8> a = {2, 4, 6, 3, 5, 8, 7, 10}; int array_size = sizeof(a)/(sizeof(a[0])); vector <int> solution = two_missing_num_sol1(a); cout << "Size of missing_two vector" << solution.size() << endl; for (auto num: solution) { cout << num << " "; } return 0; } vector <int> two_missing_num_sol1(array<int, 8> a) { int max_value = *(max_element(a.begin(), a.end())); unordered_set<int> set; for (int i = 1; i <= max_value; i++) { set.insert(i); } for (int i = 0; i < a.size(); i++) { set.erase(a[i]); } vector <int> solution_vector; for (const auto& elem: set) { solution_vector.push_back(elem); } return solution_vector; }
true
a18a387d58e9bdad6e8ca49c80094872914145f1
C++
aposos/Cataclysm
/computer.cpp
UTF-8
22,940
2.78125
3
[]
no_license
#include "computer.h" #include "game.h" #include "monster.h" #include "overmap.h" #include "output.h" #include <fstream> #include <string> #include <sstream> computer::computer() { security = 0; name = DEFAULT_COMPUTER_NAME; w_terminal = NULL; } computer::computer(std::string Name, int Security) { security = Security; name = Name; w_terminal = NULL; } computer::~computer() { if (w_terminal != NULL) delwin(w_terminal); } computer& computer::operator=(const computer &rhs) { security = rhs.security; name = rhs.name; options.clear(); for (int i = 0; i < rhs.options.size(); i++) options.push_back(rhs.options[i]); failures.clear(); for (int i = 0; i < rhs.failures.size(); i++) failures.push_back(rhs.failures[i]); w_terminal = NULL; return *this; } void computer::set_security(int Security) { security = Security; } void computer::add_option(std::string opt_name, computer_action action, int Security) { options.push_back(computer_option(opt_name, action, Security)); } void computer::add_failure(computer_failure failure) { failures.push_back(failure); } void computer::shutdown_terminal() { werase(w_terminal); delwin(w_terminal); w_terminal = NULL; } void computer::use(game *g) { if (w_terminal == NULL) w_terminal = newwin(25, 80, 0, 0); wborder(w_terminal, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX ); print_line("Logging into %s...", name.c_str()); if (security > 0) { print_error("ERROR! Access denied!"); switch (query_ynq("Bypass security?")) { case 'q': case 'Q': shutdown_terminal(); return; case 'n': case 'N': print_line("Shutting down... press any key."); getch(); shutdown_terminal(); return; case 'y': case 'Y': if (!hack_attempt(&(g->u))) { if (failures.size() == 0) { print_line("Maximum login attempts exceeded. Press any key..."); getch(); shutdown_terminal(); return; } activate_random_failure(g); shutdown_terminal(); return; } else { // Successful hack attempt security = 0; print_line("Login successful. Press any key..."); getch(); reset_terminal(); } } } else { // No security print_line("Login successful. Press any key..."); getch(); reset_terminal(); } // Main computer loop bool done = false; // Are we done using the computer? do { //reset_terminal(); print_line(""); print_line("%s - Root Menu", name.c_str()); for (int i = 0; i < options.size(); i++) print_line("%d - %s", i + 1, options[i].name.c_str()); print_line("Q - Quit and shut down"); char ch; do ch = getch(); while (ch != 'q' && ch != 'Q' && (ch < '1' || ch - '1' >= options.size())); if (ch == 'q' || ch == 'Q') done = true; else { // We selected an option other than quit. ch -= '1'; // So '1' -> 0; index in options.size() computer_option current = options[ch]; if (current.security > 0) { print_error("Password required."); if (query_bool("Hack into system?")) { if (!hack_attempt(&(g->u), current.security)) { activate_random_failure(g); shutdown_terminal(); return; } else { activate_function(g, current.action); done = true; reset_terminal(); } } } else // No need to hack, just activate activate_function(g, current.action); } // Done processing a selected option. } while (!done); // Done with main terminal loop shutdown_terminal(); // This should have been done by now, but just in case. } bool computer::hack_attempt(player *p, int Security) { if (Security == -1) Security = security; // Set to main system security if no value passed p->practice(sk_computer, 5 + Security * 2); int player_roll = p->sklevel[sk_computer]; if (p->int_cur < 8 && one_in(2)) player_roll -= rng(0, 8 - p->int_cur); else if (p->int_cur > 8 && one_in(3)) player_roll += rng(0, p->int_cur - 8); return (dice(player_roll, 6) >= dice(Security, 6)); } std::string computer::save_data() { std::stringstream data; std::string savename = name; // Replace " " with "_" size_t found = savename.find(" "); while (found != std::string::npos) { savename.replace(found, 1, "_"); found = savename.find(" "); } data << savename << " " << security << " " << options.size() << " "; for (int i = 0; i < options.size(); i++) { savename = options[i].name; found = savename.find(" "); while (found != std::string::npos) { savename.replace(found, 1, "_"); found = savename.find(" "); } data << savename << " " << int(options[i].action) << " " << options[i].security << " "; } data << failures.size() << " "; for (int i = 0; i < failures.size(); i++) data << int(failures[i]) << " "; return data.str(); } void computer::load_data(std::string data) { options.clear(); failures.clear(); std::stringstream dump; std::string buffer; dump << data; // Pull in name and security dump >> name >> security; size_t found = name.find("_"); while (found != std::string::npos) { name.replace(found, 1, " "); found = name.find("_"); } // Pull in options int optsize; dump >> optsize; for (int n = 0; n < optsize; n++) { std::string tmpname; int tmpaction, tmpsec; dump >> tmpname >> tmpaction >> tmpsec; size_t found = tmpname.find("_"); while (found != std::string::npos) { tmpname.replace(found, 1, " "); found = tmpname.find("_"); } add_option(tmpname, computer_action(tmpaction), tmpsec); } // Pull in failures int failsize, tmpfail; dump >> failsize; for (int n = 0; n < failsize; n++) { dump >> tmpfail; failures.push_back(computer_failure(tmpfail)); } } void computer::activate_function(game *g, computer_action action) { switch (action) { case COMPACT_NULL: break; // Why would this be called? case COMPACT_OPEN: g->m.translate(t_door_metal_locked, t_floor); print_line("Doors opened."); break; case COMPACT_SAMPLE: for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { if (g->m.ter(x, y) == t_sewage_pump) { for (int x1 = x - 1; x1 <= x + 1; x1++) { for (int y1 = y - 1; y1 <= y + 1; y1++ ) { if (g->m.ter(x1, y1) == t_counter) { bool found_item = false; for (int i = 0; i < g->m.i_at(x1, y1).size(); i++) { item *it = &(g->m.i_at(x1, y1)[i]); if (it->is_container() && it->contents.empty()) { it->put_in( item(g->itypes[itm_sewage], g->turn) ); found_item = true; } } if (!found_item) { item sewage(g->itypes[itm_sewage], g->turn); g->m.add_item(x1, y1, sewage); } } } } } } } break; case COMPACT_RELEASE: g->sound(g->u.posx, g->u.posy, 40, "An alarm sounds!"); g->m.translate(t_reinforced_glass_h, t_floor); g->m.translate(t_reinforced_glass_v, t_floor); print_line("Containment shields opened."); break; case COMPACT_TERMINATE: for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { int mondex = g->mon_at(x, y); if (mondex != -1 && ((g->m.ter(x, y - 1) == t_reinforced_glass_h && g->m.ter(x, y + 1) == t_wall_h) || (g->m.ter(x, y + 1) == t_reinforced_glass_h && g->m.ter(x, y - 1) == t_wall_h))) g->kill_mon(mondex); } } print_line("Subjects terminated."); break; case COMPACT_PORTAL: for (int i = 0; i < SEEX * 3; i++) { for (int j = 0; j < SEEY * 3; j++) { int numtowers = 0; for (int xt = i - 2; xt <= i + 2; xt++) { for (int yt = j - 2; yt <= j + 2; yt++) { if (g->m.ter(xt, yt) == t_radio_tower) numtowers++; } } if (numtowers == 4) { if (g->m.tr_at(i, j) == tr_portal) g->m.tr_at(i, j) = tr_null; else g->m.add_trap(i, j, tr_portal); } } } break; case COMPACT_CASCADE: { if (!query_bool("WARNING: Resonance cascade carries severe risk! Continue?")) return; std::vector<point> cascade_points; for (int i = g->u.posx - 10; i <= g->u.posx + 10; i++) { for (int j = g->u.posy - 10; j <= g->u.posy + 10; j++) { if (g->m.ter(i, j) == t_radio_tower) cascade_points.push_back(point(i, j)); } } if (cascade_points.size() == 0) g->resonance_cascade(g->u.posx, g->u.posy); else { point p = cascade_points[rng(0, cascade_points.size() - 1)]; g->resonance_cascade(p.x, p.y); } } break; case COMPACT_RESEARCH: { int lines = 0, notes = 0; std::string log, tmp; int ch; std::ifstream fin; fin.open("data/LAB_NOTES"); if (!fin.is_open()) { debugmsg("Couldn't open ./data/LAB_NOTES for reading"); return; } while (fin.good()) { ch = fin.get(); if (ch == '%') notes++; } while (lines < 10) { fin.clear(); fin.seekg(0, std::ios::beg); fin.clear(); int choice = rng(1, notes); while (choice > 0) { getline(fin, tmp); if (tmp.find_first_of('%') == 0) choice--; } getline(fin, tmp); do { lines++; if (lines < 15 && tmp.find_first_of('%') != 0) { log.append(tmp); log.append("\n"); } } while(tmp.find_first_of('%') != 0 && getline(fin, tmp)); } print_line(" %s", log.c_str()); print_line("Press any key..."); getch(); } break; case COMPACT_MAPS: { int minx = int(g->levx / 2) - 40; int maxx = int(g->levx / 2) + 40; int miny = int(g->levy / 2) - 40; int maxy = int(g->levy / 2) + 40; if (minx < 0) minx = 0; if (maxx >= OMAPX) maxx = OMAPX - 1; if (miny < 0) miny = 0; if (maxy >= OMAPY) maxy = OMAPY - 1; overmap tmp(g, g->cur_om.posx, g->cur_om.posy, 0); for (int i = minx; i <= maxx; i++) { for (int j = miny; j <= maxy; j++) tmp.seen(i, j) = true; } tmp.save(g->u.name, g->cur_om.posx, g->cur_om.posy, 0); print_line("Surface map data downloaded."); } break; case COMPACT_MAP_SEWER: { int minx = int(g->levx / 2) - 60; int maxx = int(g->levx / 2) + 60; int miny = int(g->levy / 2) - 60; int maxy = int(g->levy / 2) + 60; if (minx < 0) minx = 0; if (maxx >= OMAPX) maxx = OMAPX - 1; if (miny < 0) miny = 0; if (maxy >= OMAPY) maxy = OMAPY - 1; overmap tmp(g, g->cur_om.posx, g->cur_om.posy, g->cur_om.posz); for (int i = minx; i <= maxx; i++) { for (int j = miny; j <= maxy; j++) if ((tmp.ter(i, j) >= ot_sewer_ns && tmp.ter(i, j) <= ot_sewer_nesw) || (tmp.ter(i, j) >= ot_sewage_treatment && tmp.ter(i, j) <= ot_sewage_treatment_under)) tmp.seen(i, j) = true; } tmp.save(g->u.name, g->cur_om.posx, g->cur_om.posy, 0); print_line("Sewage map data downloaded."); } break; case COMPACT_MISS_LAUNCH: { overmap tmp_om(g, g->cur_om.posx, g->cur_om.posy, 0); // Target Acquisition. point target = tmp_om.choose_point(g); if (target.x == -1) { print_line("Launch canceled."); return; } // Figure out where the glass wall is... int wall_spot = 0; for (int i = 0; i < SEEX * 3 && wall_spot == 0; i++) { if (g->m.ter(i, 10) == t_wall_glass_v) wall_spot = i; } // ...and put radioactive to the right of it for (int i = wall_spot + 1; i < SEEX * 2 - 1; i++) { for (int j = 1; j < SEEY * 2 - 1; j++) { if (one_in(3)) g->m.add_field(NULL, i, j, fd_nuke_gas, 3); } } // For each level between here and the surface, remove the missile for (int level = g->cur_om.posz; level < 0; level++) { tmp_om = g->cur_om; g->cur_om = overmap(g, tmp_om.posx, tmp_om.posy, level); map tmpmap(&g->itypes, &g->mapitems, &g->traps); tmpmap.load(g, g->levx, g->levy); tmpmap.translate(t_missile, t_hole); tmpmap.save(&tmp_om, g->turn, g->levx, g->levy); } g->cur_om = tmp_om; for (int x = target.x - 2; x <= target.x + 2; x++) { for (int y = target.y - 2; y <= target.y + 2; y++) g->nuke(x, y); } } break; case COMPACT_MISS_DISARM: // TODO: This! break; case COMPACT_LIST_BIONICS: { std::vector<std::string> names; int more = 0; for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { for (int i = 0; i < g->m.i_at(x, y).size(); i++) { if (g->m.i_at(x, y)[i].is_bionic()) { if (names.size() < 9) names.push_back(g->m.i_at(x, y)[i].tname()); else more++; } } } } for (int i = 0; i < names.size(); i++) print_line(names[i].c_str()); if (more > 0) print_line("%d OTHERS FOUND..."); } break; case COMPACT_ELEVATOR_ON: for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { if (g->m.ter(x, y) == t_elevator_control_off) g->m.ter(x, y) = t_elevator_control; } } print_line("Elevator activated."); break; case COMPACT_AMIGARA_LOG: // TODO: This is static, move to data file? print_line("NEPower Mine(%d:%d) Log", g->levx, g->levy); print_line("\ ENTRY 47:\n\ Our normal mining routine has unearthed a hollow chamber. This would not be\n\ out of the ordinary, save for the odd, perfectly vertical faultline found.\n\ This faultline has several odd concavities in it which have the more\n\ superstitious crew members alarmed; they seem to be of human origin.\n\ \n\ ENTRY 48:\n\ The concavities are between 10 and 20 feet tall, and run the length of the\n\ faultline. Each one is vaguely human in shape, but with the proportions of\n\ the limbs, neck and head greatly distended, all twisted and curled in on\n\ themselves.\n"); if (!query_bool("Continue reading?")) return; reset_terminal(); print_line("NEPower Mine(%d:%d) Log", g->levx, g->levy); print_line("\ ENTRY 49:\n\ We've stopped mining operations in this area, obviously, until archaeologists\n\ have the chance to inspect the area. This is going to set our schedule back\n\ by at least a week. This stupid artifact-preservation law has been in place\n\ for 50 years, and hasn't even been up for termination despite the fact that\n\ these mining operations are the backbone of our economy.\n\ \n\ ENTRY 52:\n\ Still waiting on the archaeologists. We've done a little light insepction of\n\ the faultline; our sounding equipment is insufficient to measure the depth of\n\ the concavities. The equipment is rated at 15 miles depth, but it isn't made\n\ for such narrow tunnels, so it's hard to say exactly how far back they go.\n"); if (!query_bool("Continue reading?")) return; reset_terminal(); print_line("NEPower Mine(%d:%d) Log", g->levx, g->levy); print_line("\ ENTRY 54:\n\ I noticed a couple of the guys down in the chamber with a chisel, breaking\n\ off a piece of the sheer wall. I'm looking the other way. It's not like\n\ the eggheads are going to notice a little piece missing. Fuck em.\n\ \n\ ENTRY 55:\n\ Well, the archaeologists are down there now with a couple of the boys as\n\ guides. They're hardly Indiana Jones types; I doubt they been below 20\n\ feet. I hate taking guys off assignment just to babysit the scientists, but\n\ if they get hurt we'll be shut down for god knows how long.\n\ \n\ ENTRY 58:\n\ They're bringing in ANOTHER CREW? Christ, it's just some cave carvings! I\n\ know that's sort of a big deal, but come on, these guys can't handle it?\n"); if (!query_bool("Continue reading?")) return; reset_terminal(); for (int i = 0; i < 10; i++) print_gibberish_line(); print_line(""); print_line(""); print_line(""); print_line("AMIGARA PROJECT"); print_line(""); print_line(""); if (!query_bool("Continue reading?")) return; reset_terminal(); print_line("\ SITE %d%d%d%d%d\n\ PERTINANT FOREMAN LOGS WILL BE PREPENDED TO NOTES", g->cur_om.posx, g->cur_om.posy, g->levx, g->levy, abs(g->levz)); print_line("\n\ MINE OPERATIONS SUSPENDED; CONTROL TRANSFERRED TO AMIGARA PROJECT UNDER\n\ IMPERATIVE 2:07B\n\ FAULTLINE SOUNDING HAS PLACED DEPTH AT 30.09 KM\n\ DAMAGE TO FAULTLINE DISCOVERED; NEPOWER MINE CREW PLACED UNDER ARREST FOR\n\ VIOLATION OF REGULATION 87.08 AND TRANSFERRED TO LAB 89-C FOR USE AS\n\ SUBJECTS\n\ QUALITIY OF FAULTLINE NOT COMPROMISED\n\ INITIATING STANDARD TREMOR TEST..."); print_gibberish_line(); print_gibberish_line(); print_line(""); print_error("FILE CORRUPTED, PRESS ANY KEY..."); getch(); reset_terminal(); break; case COMPACT_AMIGARA_START: g->add_event(EVENT_AMIGARA, int(g->turn) + 10, 0, 0, 0); g->u.add_disease(DI_AMIGARA, -1, g); break; } // switch (action) } void computer::activate_random_failure(game *g) { computer_failure fail = (failures.empty() ? COMPFAIL_SHUTDOWN : failures[rng(0, failures.size() - 1)]); activate_failure(g, fail); } void computer::activate_failure(game *g, computer_failure fail) { switch (fail) { case COMPFAIL_NULL: break; // Do nothing. Why was this even called >:| case COMPFAIL_SHUTDOWN: for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { if (g->m.has_flag(console, x, y)) g->m.ter(x, y) = t_console_broken; } } break; case COMPFAIL_ALARM: g->sound(g->u.posx, g->u.posy, 60, "An alarm sounds!"); if (g->levz > 0 && !g->event_queued(EVENT_WANTED)) g->add_event(EVENT_WANTED, int(g->turn) + 300, 0, g->levx, g->levy); break; case COMPFAIL_MANHACKS: { int num_robots = rng(4, 8); for (int i = 0; i < num_robots; i++) { int mx, my, tries = 0; do { mx = rng(g->u.posx - 3, g->u.posx + 3); my = rng(g->u.posy - 3, g->u.posy + 3); tries++; } while (!g->is_empty(mx, my) && tries < 10); if (tries != 10) { g->add_msg("Manhacks drop from compartments in the ceiling."); monster robot(g->mtypes[mon_manhack]); robot.spawn(mx, my); g->z.push_back(robot); } } } break; case COMPFAIL_SECUBOTS: { int num_robots = 1; for (int i = 0; i < num_robots; i++) { int mx, my, tries = 0; do { mx = rng(g->u.posx - 3, g->u.posx + 3); my = rng(g->u.posy - 3, g->u.posy + 3); tries++; } while (!g->is_empty(mx, my) && tries < 10); if (tries != 10) { g->add_msg("Secubots emerge from compartments in the floor."); monster robot(g->mtypes[mon_secubot]); robot.spawn(mx, my); g->z.push_back(robot); } } } break; case COMPFAIL_DAMAGE: g->add_msg("The console electrocutes you!"); g->u.hurtall(rng(1, 10)); break; case COMPFAIL_PUMP_EXPLODE: g->add_msg("The pump explodes!"); for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { if (g->m.ter(x, y) == t_sewage_pump) { g->m.ter(x, y) = t_rubble; g->explosion(x, y, 10, 0, false); } } } break; case COMPFAIL_PUMP_LEAK: g->add_msg("Sewage leaks!"); for (int x = 0; x < SEEX * 3; x++) { for (int y = 0; y < SEEY * 3; y++) { if (g->m.ter(x, y) == t_sewage_pump) { point p(x, y); int leak_size = rng(4, 10); for (int i = 0; i < leak_size; i++) { std::vector<point> next_move; if (g->m.move_cost(p.x, p.y - 1) > 0) next_move.push_back( point(p.x, p.y - 1) ); if (g->m.move_cost(p.x + 1, p.y) > 0) next_move.push_back( point(p.x + 1, p.y) ); if (g->m.move_cost(p.x, p.y + 1) > 0) next_move.push_back( point(p.x, p.y + 1) ); if (g->m.move_cost(p.x - 1, p.y) > 0) next_move.push_back( point(p.x - 1, p.y) ); if (next_move.empty()) i = leak_size; else { p = next_move[rng(0, next_move.size() - 1)]; g->m.ter(p.x, p.y) = t_sewage; } } } } } break; case COMPFAIL_AMIGARA: g->add_event(EVENT_AMIGARA, int(g->turn) + 5, 0, 0, 0); g->u.add_disease(DI_AMIGARA, -1, g); g->explosion(rng(0, SEEX * 3), rng(0, SEEY * 3), 10, 10, false); g->explosion(rng(0, SEEX * 3), rng(0, SEEY * 3), 10, 10, false); break; }// switch (fail) } bool computer::query_bool(const char *mes, ...) { // Translate the printf flags va_list ap; va_start(ap, mes); char buff[6000]; vsprintf(buff, mes, ap); va_end(ap); // Append with (Y/N/Q) std::string full_line = buff; full_line += " (Y/N/Q)"; // Print the resulting text print_line(full_line.c_str()); char ret; do ret = getch(); while (ret != 'y' && ret != 'Y' && ret != 'n' && ret != 'N' && ret != 'q' && ret != 'Q'); return (ret == 'y' || ret == 'Y'); } char computer::query_ynq(const char *mes, ...) { // Translate the printf flags va_list ap; va_start(ap, mes); char buff[6000]; vsprintf(buff, mes, ap); va_end(ap); // Append with (Y/N/Q) std::string full_line = buff; full_line += " (Y/N/Q)"; // Print the resulting text print_line(full_line.c_str()); char ret; do ret = getch(); while (ret != 'y' && ret != 'Y' && ret != 'n' && ret != 'N' && ret != 'q' && ret != 'Q'); return ret; } void computer::print_line(const char *mes, ...) { // Translate the printf flags va_list ap; va_start(ap, mes); char buff[6000]; vsprintf(buff, mes, ap); va_end(ap); // Replace any '\n' with "\n " to allow for the border std::string message = buff; size_t pos = 0; while (pos != std::string::npos) { pos = message.find("\n", pos); if (pos != std::string::npos) { message.replace(pos, 1, "\n "); pos += 2; } } // Print the line. wprintz(w_terminal, c_green, " %s%s", message.c_str(), "\n"); // Reprint the border, in case we pushed a line over it wborder(w_terminal, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX ); wrefresh(w_terminal); } void computer::print_error(const char *mes, ...) { // Translate the printf flags va_list ap; va_start(ap, mes); char buff[6000]; vsprintf(buff, mes, ap); va_end(ap); // Print the line. wprintz(w_terminal, c_red, " %s%s", buff, "\n"); // Reprint the border, in case we pushed a line over it wborder(w_terminal, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX ); wrefresh(w_terminal); } void computer::print_gibberish_line() { std::string gibberish; int length = rng(50, 70); for (int i = 0; i < length; i++) { switch (rng(0, 4)) { case 0: gibberish += '0' + rng(0, 9); break; case 1: case 2: gibberish += 'a' + rng(0, 25); break; case 3: case 4: gibberish += 'A' + rng(0, 25); break; } } wprintz(w_terminal, c_yellow, gibberish.c_str()); wborder(w_terminal, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX ); wrefresh(w_terminal); } void computer::reset_terminal() { werase(w_terminal); wborder(w_terminal, LINE_XOXO, LINE_XOXO, LINE_OXOX, LINE_OXOX, LINE_OXXO, LINE_OOXX, LINE_XXOO, LINE_XOOX ); wmove(w_terminal, 1, 1); wrefresh(w_terminal); }
true
ffb5c64497b75af132caacaf099e54ef26b4bc0d
C++
lkeegan/CTCI
/src/arrays_and_strings.cpp
UTF-8
7,054
3.375
3
[ "MIT" ]
permissive
#include "arrays_and_strings.hpp" namespace ctci { namespace arrays_and_strings { bool is_unique_a(const std::string &str) { // best case: O(1) // worst case: O(N) where N is number of unique chars, i.e. max 2^7 // use look-up table to check if char has already been seen. // NOTE: assuming 7-bit ASCII chars constexpr std::size_t N_CHARS = 128; if (str.size() > N_CHARS) { // cannot be unique if longer than number of unique chars return false; } std::array<bool, N_CHARS> char_exists{}; for (char c : str) { if (char_exists[static_cast<std::size_t>(c)]) { return false; } else { char_exists[static_cast<std::size_t>(c)] = true; } } return true; } bool is_unique_b(const std::string &str) { // for each char, search rest of string for match // best case: O(1) // average: O(N^2) // worst case: O(N^2) constexpr std::size_t N_CHARS = 128; if (str.size() > N_CHARS) { // cannot be unique if longer than number of unique chars return false; } for (int i = 0; i < static_cast<int>(str.size()) - 1; ++i) { if (str.find(str[i], i + 1) != std::string::npos) { return false; } } return true; } bool check_permutation(const std::string &strA, const std::string &strB) { // assume 7-bit ASCII chars constexpr std::size_t N_CHARS = 128; // best case: O(1) // worst case: O(N) if (strA.size() != strB.size()) { // cannot be permutation of each other if different length return false; } // frequency count of each char in strA std::array<int, N_CHARS> char_count{}; for (char c : strA) { ++char_count[static_cast<std::size_t>(c)]; } // decrement each char in strB from frequency count for (char c : strB) { --char_count[static_cast<std::size_t>(c)]; } // if all values are zero then strings are made of same set // of chars, i.e. they are permutations of each other for (int count : char_count) { if (count != 0) { return false; } } return true; } void URLify(std::string &str, int length) { // best case: O(N) // average: O(N) // worst case: O(N) std::vector<int> space_loc; // find location of all spaces in first length chars of str for (int i = 0; i < length; ++i) { if (str[i] == ' ') space_loc.push_back(i); } int n_spaces = static_cast<int>(space_loc.size()); // need two extra chars per space int buffer = static_cast<int>(str.size()) - length; if (buffer < 2 * n_spaces) { throw std::invalid_argument("STRING_TOO_SMALL"); } // move each char[i] that needs moving // directly to its final destination char[i+shift] // starting from the end and working backwards // need to shift 2 to the right for each preceeding space int i = length - 1; while (n_spaces > 0) { int shift = 2 * n_spaces; // shift char right by 2 for each preceeding space while (i > space_loc[n_spaces - 1]) { str[i + shift] = str[i]; --i; } // insert "%20" in place of " " str[i + shift] = '0'; str[i + shift - 1] = '2'; str[i + shift - 2] = '%'; --i; --n_spaces; } } bool is_permutation_of_palindrome(const std::string &str) { // assume 7-bit ASCII chars constexpr std::size_t N_CHARS = 128; // best case: O(N) // average: O(N) // worst case: O(N) // frequency count: is it odd or even for each char std::array<bool, N_CHARS> char_odd_count{}; int n_chars = 0; for (char c : str) { if (c != ' ') { char_odd_count[c] = !char_odd_count[c]; ++n_chars; } } // count chars with odd frequency counts int odd_count_chars = 0; for (bool is_odd : char_odd_count) { if (is_odd) { ++odd_count_chars; } } // can make palindrome iff: // -for even n_chars: even count of each char, i.e. no odd counts, e.g. abba // -if n is odd: single char with odd count, the rest even, e.g. aba if (n_chars % 2 == odd_count_chars) { return true; } else { return false; } } bool one_away(const std::string &strA, const std::string &strB) { // best case: O(1) // average: O(N) // worst case: O(N) int n_A = static_cast<int>(strA.size()); int n_B = static_cast<int>(strB.size()); int diff = n_A - n_B; // +1: can try removing one char from A // 0: can try replacing one char in A // -1: can try inserting one char to A // otherwise: more than one edit away if (abs(diff) > 1) { return false; } int n_changes = 0; for (int i = 0; i < n_A; ++i) { if (strA[i] != strB[i - n_changes * diff]) { ++n_changes; if (n_changes > 1) { return false; } } } return true; } std::string string_compression(const std::string &str) { // best case: O(N) // average: O(N) // worst case: O(N) std::string str_compressed; int chars_compressed = 0; for (std::string::const_iterator i = str.begin(); i != str.end(); ++i) { str_compressed += *i; int count = 1; while (i != str.end() && *(i + 1) == *i) { ++count; ++i; } str_compressed += std::to_string(count); chars_compressed += count - 2; } if (chars_compressed > 0) { return str_compressed; } else { return str; } } void rotate_matrix(matrix &M) { // best case: O(N) [where N is number of matrix elements] // average: O(N) // worst case: O(N) int N = static_cast<int>(M.size()); // for x,y modulo N-1, 4x90deg rotations form a closed set: // M(x,y) -> M(y,-x) // M(y,-x) -> M(-x,-y) // M(-x,-y) -> M(-y,x) // M(-y,x) -> M(x,y) // So can rotate the above 4 elements // by 90deg with 3 swaps // without affecting the rest of the matrix // Repeat for all x,y in upper left corner to rotate all elements for (int x = 0; x < (N + 1) / 2; ++x) { for (int y = 0; y < N / 2; ++y) { std::swap(M[x][y], M[y][N - 1 - x]); std::swap(M[x][y], M[N - 1 - x][N - 1 - y]); std::swap(M[x][y], M[N - 1 - y][x]); } } } void zero_matrix(matrix &M) { // best case: O(MN) [where ML is number of matrix elements] // average: O(MN) // worst case: O(MN) int n_rows = static_cast<int>(M.size()); int n_cols = static_cast<int>(M[0].size()); std::vector<int> zero_rows(n_rows, 1); std::vector<int> zero_cols(n_cols, 1); // first pass: look for rows/columns containing zeros for (int row = 0; row < n_rows; ++row) { for (int col = 0; col < n_cols; ++col) { if (M[row][col] == 0) { zero_rows[row] = 0; zero_cols[col] = 0; } } } // second pass: apply zeros for (int row = 0; row < n_rows; ++row) { for (int col = 0; col < n_cols; ++col) { M[row][col] *= zero_rows[row] * zero_cols[col]; } } } bool is_rotation(const std::string &strA, const std::string &strB) { if (strA.size() != strB.size()) { return false; } // if we can cyclically permute strA to form strB, // then strA must be contained in strB + strB, e.g. // "abcd" <-> "bcd[a""bcd]a" std::string strB_doubled = strB + strB; return is_substring(strA, strB_doubled); } } // namespace arrays_and_strings } // namespace ctci
true
4a35a2cfb38865b7900d5c9d9c8525ba38e9277c
C++
InsightSoftwareConsortium/ITK
/Modules/ThirdParty/VNL/src/vxl/vcl/tests/test_cctype.cxx
UTF-8
1,302
2.59375
3
[ "IJG", "Zlib", "LicenseRef-scancode-proprietary-license", "SMLNJ", "BSD-3-Clause", "BSD-4.3TAHOE", "LicenseRef-scancode-free-unknown", "Spencer-86", "LicenseRef-scancode-llnl", "FSFUL", "Libpng", "libtiff", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive", ...
permissive
#include <iostream> #include <cctype> #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif // Test the functionality, and also cause a link to make sure the // function exists. int test_cctype_main(int /*argc*/,char* /*argv*/[]) { return ! ( std::isspace(' ') && std::isspace('\n') && !std::isspace('a') && std::isalnum('1') && std::isalnum('z') && !std::isalnum('@') && std::isdigit('4') && !std::isdigit('k') && !std::isdigit('%') && std::isprint(' ') && std::isprint('(') && !std::isprint('\n') && std::isupper('A') && !std::isupper('a') && !std::isupper('1') && std::islower('b') && !std::islower('G') && !std::islower('8') && std::isalpha('A') && std::isalpha('a') && !std::isalpha('1') && std::isgraph('%') && std::isgraph('j') && !std::isgraph(' ') && std::ispunct('&') && !std::ispunct('a') && !std::ispunct(' ') && std::isxdigit('8') && std::isxdigit('F') && std::isxdigit('f') && !std::isxdigit('g') && std::iscntrl('\n') && std::iscntrl('\177') && !std::iscntrl('i') && std::tolower('A')=='a' && std::tolower('a')=='a' && std::tolower('@')=='@' && std::toupper('K')=='K' && std::toupper('j')=='J' && std::toupper('$')=='$' ); }
true
c2dba5f7cc61d617437f6e1af73e1287e31cfaca
C++
AdityaShekharTiwary/competitve_programming
/time_for_medicine.cpp
UTF-8
508
2.65625
3
[]
no_license
#include <iostream> using namespace std; int main() { int y,m,d,t; char ch; cin>>t; while(t--) { cin >> y >> ch >> m >> ch >> d; if(m==1 || m==3 || m==5 || m==7 || m==8 || m==10 || m==12) { cout<<(31-d)/2+1<<endl; } else if(m==4 || m==6 || m==9 || m==11) { cout<<(30-d+31)/2+1<<endl; } else if(m==2) { if((y%4==0 && y%100!=0)||y%400==0) //Leap Year cout<<(29-d)/2+1<<endl; else cout<<(28-d+31)/2+1<<endl; } } return 0; }
true
6192f70c45163b1fbe1ac48065618633b38fe7fe
C++
lbguilherme/duvidovc-app
/java/include/org.apache.commons.logging.Log.hpp
UTF-8
2,243
2.59375
3
[]
no_license
#pragma once #include "../src/java-core.hpp" #include <jni.h> #include <cstdint> #include <memory> #include <vector> #include "java.lang.Object.hpp" namespace java { namespace lang { class Object; } } namespace java { namespace lang { class Throwable; } } namespace org { namespace apache { namespace commons { namespace logging { class Log : public virtual ::java::lang::Object { public: static jclass _class; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreorder" explicit Log(jobject _obj) : ::java::lang::Object(_obj) {} #pragma GCC diagnostic pop #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreorder" Log(const ::org::apache::commons::logging::Log& x) : ::java::lang::Object((jobject)0) {obj = x.obj;} Log(::org::apache::commons::logging::Log&& x) : ::java::lang::Object((jobject)0) {obj = x.obj; x.obj = JavaObjectHolder((jobject)0);} #pragma GCC diagnostic pop ::org::apache::commons::logging::Log& operator=(const ::org::apache::commons::logging::Log& x) {obj = x.obj; return *this;} ::org::apache::commons::logging::Log& operator=(::org::apache::commons::logging::Log&& x) {obj = std::move(x.obj); return *this;} bool isDebugEnabled() const; bool isErrorEnabled() const; bool isFatalEnabled() const; bool isInfoEnabled() const; bool isTraceEnabled() const; bool isWarnEnabled() const; void trace(const ::java::lang::Object&) const; void trace(const ::java::lang::Object&, const ::java::lang::Throwable&) const; void debug(const ::java::lang::Object&) const; void debug(const ::java::lang::Object&, const ::java::lang::Throwable&) const; void info(const ::java::lang::Object&) const; void info(const ::java::lang::Object&, const ::java::lang::Throwable&) const; void warn(const ::java::lang::Object&) const; void warn(const ::java::lang::Object&, const ::java::lang::Throwable&) const; void error(const ::java::lang::Object&) const; void error(const ::java::lang::Object&, const ::java::lang::Throwable&) const; void fatal(const ::java::lang::Object&) const; void fatal(const ::java::lang::Object&, const ::java::lang::Throwable&) const; }; } } } }
true
f69056aabdef39cc650004c980f0e7c56d267e6d
C++
yannick-cn/book_caode
/算法竞赛宝典/第二部资源包/第七章 贪心算法/删数问题/src/标程/DeleteNum.cpp
WINDOWS-1252
591
3.359375
3
[]
no_license
#include <iostream> #include <cstdlib> using namespace std; void Delete_Num(char str[],int n,int k) { while(k--) { int m=0,i=0; while(i<n && str[i]<=str[i+1])//λ i++; for(int j=i+1;j<n;j++) str[j-1]=str[j]; } } int main() { freopen("DeleteNum.in","r",stdin); freopen("DeleteNum.out","w",stdout); int k; char str[300]; while(scanf("%s%d",str,&k)!=EOF) { int lenth=strlen(str); Delete_Num(str,lenth,k); for(int i=0;i<lenth-k;i++) printf("%c",str[i]); printf("\n"); } return 0; }
true
3435b08dd8b6e0c366468c1e2e566110d9f8697e
C++
udaysankarm/stack-and-queue
/queue.cpp
UTF-8
1,019
3.59375
4
[]
no_license
#include<iostream> #include"linkedlist-mod.cpp" using namespace std; class queue//implementing queue { public: Node *end;//variable to point to the top Node *start; LinkedList ll; queue()//default constructor { end=ll.head;;//assinging head to top start=ll.last; } void Enqueue(int value)// add element in the end { ll.insertAt(1,value);//inserting at first position end=ll.head;//modifying the top } void Dequeue()//to delete the end element { ll.Delete(); } bool isEmpty()//ckecking wheter it is emptyf { if (end==NULL) return true; return false; } int size() { return ll.countItems(); } /*void fornt() { cout<<ll.head->data; }*/ void display() { ll.display(); } /*void end() { cout<<ll.last->data; }*/ }; int main() { queue A; for(int i=0;i<5;i++) A.Enqueue(i); A.display(); A.Dequeue(); A.display(); A.Dequeue(); A.display(); cout<<A.size()<<endl; A.Enqueue(67); A.display(); A.Enqueue(87); A.display(); A.Dequeue(); A.display(); return 0; }
true
2315f0fdfa52c63d6b0fbd0dbacfe31dc8766460
C++
demonsheart/C-
/practice7/3.cpp
GB18030
1,861
3.890625
4
[]
no_license
#include <iostream> using namespace std; class CLuckNumber { private: int n; int *p; public: CLuckNumber(int n); CLuckNumber(CLuckNumber &s); ~CLuckNumber(); void getLuck(); void print(); }; CLuckNumber::CLuckNumber(int n) { this->n = n; p = new int[n]; for (int i = 0; i < n; i++) p[i] = 0; } CLuckNumber::CLuckNumber(CLuckNumber &s) { this->n = s.n; this->p = new int[n]; for (int i = 0; i < n; i++) this->p[i] = s.p[i]; } CLuckNumber::~CLuckNumber() { delete[] p; } void CLuckNumber::getLuck() { int i = 0, q; for (q = 7; q <= n; q++) { if (q % 3 != 0 && q % 4 != 0 && q % 7 == 0) { p[i] = q; i++; } } } void CLuckNumber::print() { int c; for (int i = 0; i < n; i++) { if (p[i] == 0) { c = i; break; } } for (int i = 0; i < c - 1; i++) { cout << p[i] << " "; } cout << p[c - 1] << endl; } int main() { int t, n; cin >> t; while (t--) { cin >> n; CLuckNumber l(n); CLuckNumber s(l); s.getLuck(); s.print(); } return 0; } /* Ŀ һCLuckNumberݳԱ(int n)ָָ(int *p)ԱУ 1. 캯 2. 3. 캯 4. ϲĺСnмȲܱ3Ҳܱ4ܱ7ҳŵpָС 5. ӡвϲĺ һԴ ÿβһʾֵΧ ÿβһУ1-nΧڵвϲ 2 10 100 7 7 14 35 49 70 77 91 98 */
true
6d12a76303859b9006f4909c081b3d9ddcf0a25b
C++
baklazan/trts
/src/io/message_reader.cpp
UTF-8
2,056
3.0625
3
[]
no_license
#include <message_reader.h> #include <sys/types.h> #include <sys/socket.h> #include <utils.h> #include <vector> #include <iostream> MessageReader::MessageReader(int fd, std::function<void(std::string)> callback) : fd_(fd), callback_(callback) { Reset(); }; void MessageReader::Reset() { buffer_.clear(); state_ = READER_STATE_HEADER; expecting_bytes_ = 4; bytes_in_body_ = 0; } void MessageReader::ProcessByte(uint8_t byte) { switch(state_) { case READER_STATE_HEADER: { bytes_in_body_ = bytes_in_body_ | byte << (8 * (expecting_bytes_-1)); expecting_bytes_ --; if (expecting_bytes_ == 0) { expecting_bytes_ = bytes_in_body_; state_ = READER_STATE_BODY; } break; } case READER_STATE_BODY: { buffer_.push_back(byte); expecting_bytes_ --; break; } } if (state_ == READER_STATE_BODY && expecting_bytes_ == 0) { callback_(buffer_); Reset(); } } int MessageReader::Read() { uint8_t buffer[512]; unsigned total_bytes_read = 0; while (true) { int bytes_read = ::recv(fd_, buffer, 512, MSG_DONTWAIT); if (bytes_read == 0) break; if (bytes_read == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } else { perror("reading"); return -1; } } for (int i = 0; i < bytes_read; i++) { ProcessByte(buffer[i]); } total_bytes_read += bytes_read; } if (total_bytes_read == 0 && rand() % 10 == 0) return -1; return 0; } void ReadBlocking(int fd, uint8_t *buffer, int count) { int read_so_far = 0; while (read_so_far < count) { int read_now = ::read(fd, &buffer[read_so_far], count-read_so_far); report_error(read_now); read_so_far += read_now; } } std::string ReadMessageBlocking(int fd) { uint8_t head[4]; ReadBlocking(fd, reinterpret_cast<uint8_t*>(head), 4); uint32_t size = 0; for (uint8_t byte : head) { size = size << 8; size += byte; } std::vector<char> message(size); ReadBlocking(fd, reinterpret_cast<uint8_t*>(message.data()), size); std::string result(message.data(), size); return std::string(result); }
true
a06e85ee25815f175eaad83e11b4524f33715702
C++
kkkd1211/model_with_learning
/V0_bak/cpp.cpp
UTF-8
603
2.53125
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include"head.h" using namespace std; gene::gene() { int i; for(i=0;i<Nx;i++) { c0[i]=0.1; c1[i]=0.0; } } gene::gene(double ini_c[Nx]) { int i; for(i=0;i<Nx;i++) { c0[i]=ini_c[i]; c1[i]=0.0; } } void gene::next() { int i; for(i=0;i<Nx;i++) { c0[i]=c1[i]; c1[i]=0.0; } } void gene::print(char name[20]) { FILE *fp; fp=fopen(name,"a"); int i; for(i=0;i<Nx;i++) { fprintf(fp,"%f\t",c0[i]); } fprintf(fp,"\n"); fclose(fp); }
true
c2e5836d020765fb4bf0985e784c919f6710e02c
C++
KIIIKIII/hello-world
/Cheese.cpp
UTF-8
1,252
2.828125
3
[]
no_license
#include<iostream> #include<queue> using namespace std; typedef struct { int x; int y; }P; char graph[1000][1000]; P aim[10]; P s, g; int N, W, H; int vis[1000][1000]; int dx[] = { 1, 0, -1 ,0 }, dy[] = { 0, 1, 0, -1 }; int bfs(P s, P g) { queue<P> que; P n; for (int i = 0; i<H; i++) for (int j = 0; j<W; j++) vis[i][j] = -1; que.push(s); vis[s.x][s.y] = 0; while (que.size()) { P p = que.front(); que.pop(); if (p.x == g.x&&p.y == g.y) break; for (int i = 0; i<4; i++) { n.x = p.x + dx[i]; n.y = p.y + dy[i]; if (0 <= n.x && n.x < H && 0 <= n.y && n.y < W && graph[n.x][n.y] != 'X' && vis[n.x][n.y] == -1) { que.push(n); vis[n.x][n.y] = vis[p.x][p.y] + 1; } } } return vis[g.x][g.y]; } int main() { int i, j, t, step = 0; cin >> H >> W >> N; for (i = 0; i < H; i++) for (j = 0; j<W; j++) { cin >> graph[i][j]; if (graph[i][j] <= '9'&&graph[i][j] >= '1') { t = graph[i][j] - '0'; aim[t].x = i; aim[t].y = j; } else if (graph[i][j] == 'S') { s.x = i; s.y = j; graph[i][j] = '.'; } } for (i = 1; i <= N; i++) { g.x = aim[i].x; g.y = aim[i].y; step += bfs(s, g); s.x = g.x; s.y = g.y; graph[g.x][g.y] = '.'; } cout << step << endl; }
true
3dfb7b7235a0432c7c6efd80112fb67289e5380f
C++
Shokk357/Infotecs2020
/Common/BigNum.cpp
UTF-8
1,637
3.125
3
[]
no_license
#include "BigNum.h" const long long numOrder = 10E8; BigNum::BigNum(const std::string& expression) { for (int i = expression.length(); i > 0; i -= 9) if (i < 9) val.push_back(atoi(expression.substr(0, i).c_str())); else val.push_back(atoi(expression.substr(i - 9, 9).c_str())); } void BigNum::parse(const std::string &expression) { std::string substr; for (char elem : expression) { if (elem == 'K') { BigNum arg(substr); *this += arg; substr = ""; } else if (elem == 'B') { continue; } else { substr += elem; } } if (!substr.empty()) { BigNum arg(substr); *this += arg; } if (val.empty()) { val.push_back(0); } } BigNum &BigNum::operator+=(const BigNum &arg) { int carry = 0; for (size_t i = 0; i < std::max(val.size(), arg.val.size()) || carry; i++) { if (i == val.size()) val.push_back(0); val[i] += carry + (i < arg.val.size() ? arg.val[i] : 0); carry = val[i] >= numOrder; if (carry) val[i] -= numOrder; } return *this; } std::string BigNum::toString() { std::string ans; ans = val.empty() ? "0" : std::to_string(val.back()); for (int i = (int) val.size() - 2; i >= 0; i--) ans.append(std::to_string(val[i])); return ans; } bool BigNum::isDivide() { long long carry = 0; for (int i = val.size() - 1; i >= 0; i--) { long long cur = val[i] + carry * numOrder; val[i] = cur / 32; carry = cur % 32; } return !carry; }
true
70e2fc8c1c739d3b478aac566aa61d43bd83bd81
C++
BenMarshall98/Real-Time-Graphics-ACW
/Real Time Graphics ACW/Real Time Graphics ACW/ShapeNode.cpp
UTF-8
1,169
2.828125
3
[]
no_license
#include "ShapeNode.h" #include "ObjectManager.h" #include <string> #include "Sphere.h" #include "Cuboid.h" #include "Plane.h" #include "RenderManager.h" ShapeNode::ShapeNode(const std::shared_ptr<Shape> & pShape, const ObjectType pType) : mShape(pShape) { if (pType == ObjectType::STATIC) { RenderManager::instance()->addStaticShape(mShape); } else { RenderManager::instance()->addDynamicShape(mShape); } } ShapeNode::~ShapeNode() = default; void ShapeNode::read(std::istream& pIn) { std::string s, type; pIn >> s >> type; std::string shape; pIn >> shape; if (shape == "Sphere") { mShape = std::make_shared<Sphere>(); } else if (shape == "Cube") { mShape = std::make_shared<Cuboid>(); } else if (shape == "Plane") { mShape = std::make_shared<Plane>(); } pIn >> mShape; ObjectManager::instance()->addShape(mShape); if (type == "Static") { RenderManager::instance()->addStaticShape(mShape); } else { RenderManager::instance()->addDynamicShape(mShape); } } void ShapeNode::update(const DirectX::XMFLOAT4X4 & pFullMatrix, const DirectX::XMFLOAT4X4 & pRotationMatrix) { mShape->setMatrix(pFullMatrix, pRotationMatrix); }
true
c262bd3cd09bcfcf29fcb089cdf918b1df80f7fb
C++
zhaimobile/iosGraphicEngine
/iOS3DEngine/ShadersManager.cpp
UTF-8
2,340
2.578125
3
[]
no_license
// // ShadersManager.cpp // MoEngine // // Created by Mo on 10/11/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #include <iostream> #include "ShadersManager.hpp" //include the Shaders #define STRINGIFY(A) #A #include "../Shaders/SimpleVBO.vert" #include "../Shaders/SimpleVBO.frag" ShadersManager::ShadersManager() { shaderProgram=0; isInited=false; } GLuint ShadersManager::buildShader(const char* source, GLenum shaderType) { GLuint shaderHandle = glCreateShader(shaderType); glShaderSource(shaderHandle, 1, &source, 0); glCompileShader(shaderHandle); GLint compileSuccess; glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &compileSuccess); if (compileSuccess == GL_FALSE) { GLchar messages[256]; glGetShaderInfoLog(shaderHandle, sizeof(messages), 0, &messages[0]); std::cout << messages; exit(1); } return shaderHandle; } GLuint ShadersManager::buildProgram(const char* vertexShaderSource, const char* fragmentShaderSource) { GLuint vertexShader = buildShader(vertexShaderSource, GL_VERTEX_SHADER); GLuint fragmentShader = buildShader(fragmentShaderSource, GL_FRAGMENT_SHADER); GLuint programHandle = glCreateProgram(); glAttachShader(programHandle, vertexShader); glAttachShader(programHandle, fragmentShader); glLinkProgram(programHandle); GLint linkSuccess; glGetProgramiv(programHandle, GL_LINK_STATUS, &linkSuccess); if (linkSuccess == GL_FALSE) { GLchar messages[256]; glGetProgramInfoLog(programHandle, sizeof(messages), 0, &messages[0]); std::cout << messages; exit(1); } return programHandle; } bool ShadersManager::initShaders() { if(instance()->isInited) return false; // Build the GLSL program. instance()->shaderProgram= ShadersManager::buildProgram(SimpleVertexShaderVBO, SimpleFragmentShaderVBO); glUseProgram(instance()->shaderProgram); instance()->isInited=true; return true; } GLuint ShadersManager::getShaders() { if(instance()->isInited) return instance()->shaderProgram; else { initShaders(); return instance()->shaderProgram; } }
true
330cddbcb131922b38d530bb4d45b251eadce185
C++
BrushkouMatvey/LZW_compression_algorithm
/LZW.cpp
UTF-8
2,916
2.71875
3
[]
no_license
#include <iostream> #include <Windows.h> #include <fstream> #include <string> #include <vector> #include <map> #include <list> using namespace std; void readAllBytes(string fileName, vector<char> &result); void writeToFile(string fileName, vector<int> &compressCode); void compress(vector<char> &uncompressInfo, vector<int> &compressCode); void decompress(vector<int> op, string fileName); int main(char argc, char *argv[]) { argc = 4; argv[1] = (char*)"123.txt"; argv[2] = (char*)"234.lzw"; argv[3] = (char*)"decompress123.txt"; if (argc != 4) { printf("Wrong number of arguments!!!"); system("pause"); return 0; } string fileInputName = argv[1]; string fileOutputName = argv[2]; string fileDecompressName = argv[3]; vector<char> uncompressInformation; vector<int> compressCode; readAllBytes(fileInputName, uncompressInformation); compress(uncompressInformation, compressCode); writeToFile(fileOutputName, compressCode); decompress(compressCode, fileDecompressName); system("pause"); return 0; } void writeToFile(string fileName, vector<int> &compressCode) { ofstream file(fileName, ios::binary); if (file.is_open()) { file.write((char*)&compressCode[0], compressCode.size() * sizeof(int)); } else { cout << "Unable to open file" << endl; } file.close(); } void readAllBytes(string fileName, vector<char> &result) { ifstream file(fileName, ios::binary | ios::ate); if (file.is_open()) { ifstream::pos_type pos = file.tellg(); result.resize(pos); file.seekg(0, ios::beg); file.read(&result[0], pos); } else { cout << "Unable to open file" << endl; } file.close(); } void compress(vector<char> &uncompressInfo, vector<int>& compressCode) { map<string, int> table; for (int i = 0; i <= 255; i++) { string ch = ""; ch += char(i); table[ch] = i; } string p = "", c = ""; p += uncompressInfo[0]; int code = 256; vector<int> output_code; for (int i = 0; i < uncompressInfo.size(); i++) { if (i != uncompressInfo.size() - 1) c += uncompressInfo[i + 1]; if (table.find(p + c) != table.end()) { p = p + c; } else { compressCode.push_back(table[p]); table[p + c] = code; code++; p = c; } c = ""; } compressCode.push_back(table[p]); for (auto it : compressCode) cout << it << endl; } void decompress(vector<int> compressCode, string fileName) { ofstream file(fileName); map<int, string> table; for (int i = 0; i <= 255; i++) { string ch = ""; ch += char(i); table[i] = ch; } int old = compressCode[0], n; string s = table[old]; string c = ""; c += s[0]; file << s; int count = 256; for (int i = 0; i < compressCode.size() - 1; i++) { n = compressCode[i + 1]; if (table.find(n) == table.end()) { s = table[old]; s = s + c; } else { s = table[n]; } file << s; c = ""; c += s[0]; table[count] = table[old] + c; count++; old = n; } file.close(); }
true
f9a5fba0b8effdba98462d639d8e2bc03e415702
C++
hhyvs111/BrushCode
/Company/xiaohongshu/3.cpp
UTF-8
3,387
3.40625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int dp[1000][2]; int main() { //首先这个题尼玛是不能相邻的,那么排序肯定就不能用了。这里只能弄一个排列组合了。不过好像也不能简单的用这个单双来操作。 //这个有点像之前那个什么二分法? //这些题肯定尼玛都是改编的,但是自己可能做不出来,十分的尴尬啊弟弟。 int n; cin >> n; vector<int> num(n); for(int i = 1;i <= n;i++) cin >> num[i]; //一开始只能选第一个或者第二个 dp[1][0] = num[1]; dp[1][1] = 1; dp[2][0] = num[2]; dp[2][1] = 1; for(int i = 3; i <= num.size();i++) { //选第i个 //的确是挺巧妙的啊 //如果第一个第三个大于第二,就相加并加1 if(dp[i-2][0] + num[i] > dp[i-1][0]) { dp[i][0] = dp[i-2][0] + num[i]; dp[i][1] = dp[i-2][1] + 1; }else{ //如果加起来更小,那么就不更新。 //一开始搞错了,日了dj。 dp[i][0] = dp[i-1][0]; dp[i][1] = dp[i-1][1]; } } cout << dp[num.size()][0] << " " << dp[num.size()][1] << endl; // int excl = 0, incl = num[0]; // int excl_new; // //这里可以计算出这个最大值,但是好像不能计算这有多少个值? // for(int i = 1;i < num.size();i++) { // excl_new = (excl > incl) ? excl:incl; // incl = excl + num[i]; // excl = excl_new; // } // int ans; // // cout << incl << " " << excl << endl; // ans = (incl>excl)?incl:excl; //其实就两种,一种偶数的情况话肯定是输出/2 //奇数的情况就要判断是否是边缘的值 // if (cnt%2 == 0) { // cout << ans << " "<< cnt << endl; // } else { // if (incl > excl) // cout << ans << " " << cnt + 1 << endl; // else // cout << ans << " " << cnt << endl; // } return 0; } // #include<bits/stdc++.h> // using namespace std; // int main() { // //首先这个题尼玛是不能相邻的,那么排序肯定就不能用了。这里只能弄一个排列组合了。不过好像也不能简单的用这个单双来操作。 // //这个有点像之前那个什么二分法? // //这些题肯定尼玛都是改编的,但是自己可能做不出来,十分的尴尬啊弟弟。 // int n; // cin >> n; // vector<int> num(n); // for(int i = 0;i < n;i++) // cin >> num[i]; // if (num.size() == 1) { // cout << num[0] << " " << 1 << endl; // return 0; // } // if (num.size() == 2) { // if (num[0] > num[1]) { // cout << num[0] << " " << 1 << endl; // return 0; // }else { // cout << num[1] << " " << 1 << endl; // return 0; // } // } // if (num.size() == 3) { // if (num[0] + num[2] > num[1]){ // cout << num[0] + num[2] << " " << 2 <<endl; // return 0; // } else { // cout << num[1] << " " << 1 << endl; // return 0; // } // } // int excl = 0, incl = num[0]; // int excl_new; // int cnt = 0; // //这里可以计算出这个最大值,但是好像不能计算这有多少个值? // for(int i = 1;i < num.size();i++) { // excl_new = (excl > incl) ? excl:incl; // if (excl < incl) { // cnt++; // } // incl = excl + num[i]; // excl = excl_new; // } // int ans; // //判断一下三个的情况 // //偶数情况和奇数情况有点区别啊,但是应该是一样的,我感觉是没区别,就算是偶数也是可以的吧 // cout << ans << " "<< cnt << endl; // return 0; // }
true
0cb977d1c5f7280b8c9375f296a992a56dc1e42e
C++
lbarnabas88/3DBattleships
/src/tools/utils/ResourceStore.tpp
UTF-8
1,424
2.828125
3
[]
no_license
/* * ResourceStore.tpp * * Created on: 2013.01.24. * Author: Baarnus */ #include "ResourceStore.hpp" template<typename R> ResourceStore<R>::ResourceStore() { } template<typename R> ResourceStore<R>::~ResourceStore() { clear(); } template<typename R> std::string ResourceStore<R>::getDirectory() const { return m_folder; } template<typename R> void ResourceStore<R>::setDirectory(const std::string folder) { m_folder = folder; } template<typename R> std::string ResourceStore<R>::pathForResource(std::string resourcePath) const { return m_folder + (m_folder.length() == 0 ? "" : "/") + resourcePath; } template<typename R> std::wstring ResourceStore<R>::wpathForResource(std::string resourcePath) const { return utf8ToWString(pathForResource(resourcePath)); } template<typename R> typename ResourceStore<R>::ResourcePtr ResourceStore<R>::get(std::string resourcePath) { // Get auto findIt = m_store.find(resourcePath); if (findIt != m_store.end()) return findIt->second; // Insert - if isn't exist ResourcePtr new_res = loadResource(pathForResource(resourcePath)); if (new_res) m_store.insert(std::pair<std::string, ResourcePtr>(resourcePath, new_res)); return new_res; } template<typename R> void ResourceStore<R>::remove(std::string name) { auto eraseIt = m_store.find(name); if (eraseIt != m_store.end()) m_store.erase(eraseIt); } template<typename R> void ResourceStore<R>::clear() { }
true
ebe2672ea05b8e267fe058da6b7c97f3cd253a67
C++
JiangSir857/C-Plus-Plus-1
/Object Oriented Programming(C++)/例题及训项目代码/chapter6/ex2.cpp
GB18030
509
3.53125
4
[]
no_license
//6.2 ޸6.1룬ʵֳԱڶ塣 class Rect { private: //˽ݳԱlength,width float length,width; //Ϳ public: //кset(),peri(),area() void set(float x,float y)//Աset() { length= x; width = y; } float peri() //Աperi() { return (length+width)*2; } float area() //Աarea() { return (length*width); } };
true
318a050af99ce5875ae6830d19fe834e67ea173b
C++
CarsonRoscoe/BlizzardBallBattle
/BlizzardBallBattle/Engine/Component/GameObject.h
UTF-8
2,419
2.78125
3
[]
no_license
#pragma once #include "Component.h" #include <string> #include <typeinfo> #include <vector> #include <map> #include "Updateable.h" #include "Transform.h" #include <iostream> class GameObject : public Updateable { private: std::map<std::string, std::vector<Component*>> components; int id; bool isGlobal; Transform* transform; template <typename T> std::string GetClassName() { return typeid(T).name(); } public: GameObject(bool isGlobal); int getId() { return id; } template <typename T> T GetComponent() { if (HasComponent<T>()) { return (T)components[GetClassName<T>()].front(); } else { std::cout << "ERROR::FAILED TO FIND COMPONENT " << GetClassName<T>() << " FOR OBJECT " << id << std::endl; return NULL; } } template <typename T> std::vector<T> GetComponents() { return (T)components[GetClassName<T>()]; } template <typename T> void AddComponent(T component) { std::string id = GetClassName<T>(); if (!HasComponent<T>()) { std::vector<Component*> typeList; typeList.push_back((Component*)component); components.insert(std::pair<std::string, std::vector<Component*>>(id, typeList)); } else { components[id].push_back(component); } } template <typename T> void RemoveComponents() { std::vector<Component*> componentList = components[GetClassName<T>()]; for (size_t i = componentList.size() - 1; i >= 0; i--){ delete componentList[i]; } components[GetClassName<T>()].clear(); } void RemoveAllComponents() { for (std::map<std::string, std::vector<Component*>>::iterator it=components.begin(); it!=components.end(); ++it) { for (size_t i = 0; i < it->second.size(); i++){ //it->second[i]->~Component(); delete it->second[i]; } it->second.clear(); } components.clear(); } template <typename T> bool HasComponent() { return components.find(GetClassName<T>()) != components.end(); } void OnStart() {}; void OnComponentsUpdate(int ticks); void OnUpdate(int ticks){}; void OnEnd() {}; Transform* GetTransform(); void Destroy(GameObject* gameObject); virtual ~GameObject(); //template <class T> //vector<Component*> GetComponentsByType(); };
true
04318b228e79f80dfb9884909c80397a7ac2e21a
C++
RoyTrenneman/Horaire-bus-RATP-LCD-
/tranmetter.ino
UTF-8
1,349
2.8125
3
[]
no_license
/* TRANSMITTER CODE */ // LIB #include <VirtualWire.h> #include <Wire.h> //Virtual REGISTER #define BUSTIME 0xAA #define RER 0XAB //GLOBALES volatile unsigned int x; char msg[7]; void setup() { //I2C communication Wire.begin(8); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event //SERIAL PRINT Serial.begin(9600); // Debugging only //Serial.println("setup"); // RF433 // Initialise the IO and ISR vw_set_ptt_inverted(true); // Required for DR3100 vw_setup(2000); // Bits per sec vw_set_tx_pin(3); } void loop() { // Send msg[] through RF433 vw_send((uint8_t *)msg, strlen(msg)); vw_wait_tx(); // Wait until the whole message is gone delay(100); } void receiveEvent(int howMany) { int i ; if(Wire.available() && (howMany == 2)){ //int howMany means number of bytes received x = Wire.read(); if (x == BUSTIME){ msg[1] = Wire.read(); } else { int i = Wire.read(); // Dump buffer } } else { //loop for dumping buffer in case of "howmany > 2 " otherwize arduino will wait indefinitely while (0 < Wire.available()) { int i = Wire.read(); // Dump buffer //Serial.println("DUMPING BUFFER: ") ; //debugging only //Serial.print(howMany); //Serial.println(" ") ; //Serial.print(i, HEX); //Serial.println(" ") ; exit ; } } } /* END TRANSMITTER CODE */
true
ac9b40a6998ae9b6829599f718ef35d294620959
C++
sail308/fRobot
/comm.cpp
UTF-8
880
2.5625
3
[]
no_license
#include "comm.h" int init_server_socket() { int sockfd = 0; struct sockaddr_in my_addr; struct sockaddr_in remote_addr; if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { std::cout<< "socket create failed!\n"; exit(1); } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(10000); my_addr.sin_addr.s_addr = INADDR_ANY; bzero(&(my_addr.sin_zero), 8); unsigned int value = 0x1; setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,(void *)&value,sizeof(value)); if (bind(sockfd, (struct sockaddr*) &my_addr, sizeof(struct sockaddr)) == -1) { perror("bind error"); printf("strerror: %s\n", strerror(errno)); exit(1); } if (listen(sockfd, 10) == -1) { perror("listen error"); printf("strerror: %s\n", strerror(errno)); exit(1); } return sockfd; }
true
fd764eac3fa875e738b71da88de41853c73dbe7f
C++
HashJProgramming/C--
/Basics/operators.cpp
UTF-8
424
3.109375
3
[]
no_license
#include <iostream> using namespace std; int main() { int num1 = 2 + 1; int num2 = 2 - 1; int num3 = 3 * 2; int num4 = 2 / 1; int num5 = 5 % 2; int num6 = 1; int num7 = 1; num6++; num7--; cout << num1 << endl; cout << num2 << endl; cout << num3 << endl; cout << num4 << endl; cout << num5 << endl; cout << num6 << endl; cout << num7 << endl; return 0; }
true
f98efcb90c7f8bc434e0fd18f6f5f15f2d4dbd0a
C++
hiennv92/litleeardoctor
/DoctorEar/Classes/fakeBug.cpp
UTF-8
3,579
2.53125
3
[]
no_license
// // fakeBug.cpp // DoctorEar // // Created by Trinh Van Duong on 11/7/14. // // #include "fakeBug.h" #include "Define.h" fakeBug::fakeBug(){} fakeBug::~fakeBug(){} fakeBug* fakeBug::createBug(std::string imageBug){ fakeBug *bug = new fakeBug(); if(bug->initWithFile(imageBug)){ bug->autorelease(); bug->initOptions(); return bug; } CC_SAFE_DELETE(bug); return NULL; } void fakeBug::initOptions(){ _isTurnAround = false; } void fakeBug::animationBug(int typeBug){ Vector<SpriteFrame*> animFrames(3); char str1[100] = {0}; char str2[100] = {0}; char str3[100] = {0}; std::string img; if(typeBug == 1){ img = BUG_BLUE_BUG; }else{ img = BUG_RED_BUG; } sprintf(str1,"%s_1.png",img.c_str()); auto frame1 = SpriteFrame::create(str1,Rect(0,0,this->getContentSize().width,this->getContentSize().height)); //we assume that the sprites' dimentions are 40*40 rectangles. animFrames.pushBack(frame1); sprintf(str2,"%s_2.png",img.c_str()); auto frame2 = SpriteFrame::create(str2,Rect(0,0,this->getContentSize().width,this->getContentSize().height)); //we assume that the sprites' dimentions are 40*40 rectangles. animFrames.pushBack(frame2); sprintf(str3,"%s_3.png",img.c_str()); auto frame3 = SpriteFrame::create(str2,Rect(0,0,this->getContentSize().width,this->getContentSize().height)); //we assume that the sprites' dimentions are 40*40 rectangles. animFrames.pushBack(frame3); auto animation = Animation::createWithSpriteFrames(animFrames, 0.05f); auto animate = Animate::create(animation); RepeatForever *repeat = RepeatForever::create(animate); this->runAction(repeat); } void fakeBug::bugMove(){ if (!_isTurnAround) { if (_typeMove == 2) { auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMoveTurnAround,this)); this->runAction(Sequence::create(MoveTo::create(1.0f, _pointFinish),action, NULL)); this->runAction(Sequence::create(ScaleTo::create(1.0f, 1.0f), NULL)); }else{ auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMoveTurnAround,this)); this->runAction(Sequence::create(MoveTo::create(1.0f, _pointFinish),action, NULL)); } _isTurnAround = true; }else{ if (_typeMove == 2) { auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMoveTurnAround,this)); this->runAction(Sequence::create(RotateTo::create(0.5f,this->getRotation()-180),MoveTo::create(1.0f, _pointFinish),action, NULL)); this->runAction(Sequence::create(ScaleTo::create(1.5f, 1.0f), NULL)); }else{ auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMoveTurnAround,this)); this->runAction(Sequence::create(RotateTo::create(0.5f,this->getRotation()-180),MoveTo::create(1.0f, _pointFinish),action, NULL)); } } } void fakeBug::bugMoveTurnAround(){ if (_typeMove == 2) { auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMove,this)); this->runAction(Sequence::create(RotateTo::create(0.5f,this->getRotation()+ 180),MoveTo::create(1.5f,_savePosition),action, NULL)); this->runAction(Sequence::create(ScaleTo::create(2.0f, 0.2f), NULL)); }else{ auto action = CallFunc::create(CC_CALLBACK_0(fakeBug::bugMove,this)); this->runAction(Sequence::create(RotateTo::create(0.5f,this->getRotation()+ 180),MoveTo::create(1.5f,_savePosition),action, NULL)); } }
true
463536f0602ec2dbaa5dc5e27940873da13c474b
C++
SJTUStevenDu/Algorithm-Contest
/BZOJ/3155 Preprefix sum.cpp
UTF-8
1,075
2.65625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #include <fstream> #include <algorithm> using namespace std; const int MAXN = 100000 + 10; int n, m, x; long long c1[MAXN], c2[MAXN], a[MAXN], y; inline int lowbit(int x) {return x & (-x);} inline void Add(long long c[], int x, long long v) { for (int i = x; i <= n; i += lowbit(i)) c[i] += v; } inline long long Query(long long c[], int x) { long long ret = 0; for (; x > 0; x -= lowbit(x)) ret += c[x]; return ret; } char opr[10]; int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; ++i) scanf("%lld", &a[i]); for (int i = 1; i <= n; ++i) Add(c1, i, a[i]), Add(c2, i, (n - i + 1) * a[i]); while (m--) { scanf("%s", opr); if (opr[0] == 'Q') { scanf("%d", &x); long long cur1 = Query(c1, x), cur2 = Query(c2, x); printf("%lld\n", cur2 - cur1 * (n - x)); } else { scanf("%d%lld", &x, &y); Add(c1, x, -a[x]); Add(c2, x, -(n - x + 1) * a[x]); a[x] = y; Add(c1, x, a[x]); Add(c2, x, (n - x + 1) * a[x]); } } return 0; }
true
c07c0db15451eeb8bc28d50084236155edcc3c02
C++
duchevich/c-plus-plus-VS2017-course
/queue1/Проект15/Source.cpp
WINDOWS-1251
613
3
3
[]
no_license
/* 1. . , . */ #include <iostream> using namespace std; typedef struct queue { int value; }*queuePointer; void init(queuePointer queue) { } void insertQueue(queuePointer queue) { } void deleteQueue(queuePointer &queue) { } void printQueue(queuePointer queue) { } void main() { setlocale(0, ""); queuePointer myQueue = new queue; system("pause"); }
true
3d40a6324fc419404d87bff18a30875eb4a9b62c
C++
mukoedo1993/cpp_primer_solutions
/C++_chap13/sec13_6_3_RvalueReferencesAndMemberFunctions/sec13_6_3_RvalueReferencesAndMemberFunctions.cpp
UTF-8
4,255
3.984375
4
[]
no_license
//Member functions other than constructors and assignment can benefit from providing both //copy and move versions. //Such move-enabled members typically use the same parameter pattern as the copy and the assignment operators--- //one version takes an lvalue reference to const, and the second takes an rvalue reference to nonconst. //e.g. push_back //Assume X is the element type, these containers define: //void push_back(const X&);//case a: binds to any kind of X //void push_back(X&&);//move:binds only to modifiable rvalues of type X #include"StrVec_sec13_6.h" #include<vector> #include<algorithm> using std::vector; class Foo { public: Foo& operator=(const Foo&)&;//may assign only to modifiable lvalues //A function can be both 1: reference 2:const //Foo someMem()& const {return *this;}//error:const qualifter must come first Foo anotherMem()const& { return *this; } }; Foo& retFoo() { Foo Ob1; return Ob1; } Foo retVal() { return Foo(); } //The reference qualifier can be either & or &&, indicating that this may point to //a rvalue or lvalue, respectively. Like the const qualifier, a reference qualifier may appear only //on a (nonstatic) member function and must appear in both the declaration and definition of the function. Foo& Foo::operator=(const Foo& rhs)&//reference qualifier { //do whatever is needed to assign rhs to this object return *this; } /*Overloading and Reference Functions*/ //1:We can overload a function based on its reference qualifier. //2: We may overload a function by its reference qualifier and by whether it is a const member. //e.g. Foo1 class Foo1 { public: //sorted: retun a copy of the Foo1 object in which the vector is sorted Foo1 sorted()&&;//may run on modifiable rvalues Foo1 sorted()const&;//may run on any kind of Foo1 //other members of Foo1 Foo1(vector<int>v) {for_each(v.begin(), v.end(), [this](int t) {data.push_back(t); });} void print() { for_each(data.cbegin(), data.cend(), [](const int &i) {std::cout << i << " "; }); std::cout << std::endl; } //Comment: /*Here * * */ using comp = bool(*)(const int&, const int&); Foo1 sorted(comp fn) { sort(data.begin(), data.end(),fn); return *this; } Foo1 sorted(comp fn)const { Foo1 ret(*this); sort(ret.data.begin(), ret.data.end(), fn); return *this; } private: vector<int>data; }; //this object is an rvalue; so we can sort in place Foo1 Foo1::sorted()&& { sort(data.begin(), data.end()); return *this; } //this object is either const or it is an lvalue; either way we can't sort in place Foo1 Foo1::sorted()const& { Foo1 ret(*this);//make a copy sort(ret.data.begin(), ret.data.end());//sort the copy return ret;//return the copy } //When we run sorted on an rvalue, it is safe to sort the data member directly. //When we run sorted on a const rvalue or on an lvalue, we can't change this object, //so we copy data before sorting it. int main() { /*Consider two kinds of void push_back()*/ //These members are nearly identical. The difference is that the rvalue reference version of push_back //calls move to pass its parameter to construct. StrVec vec;//empty StrVec string s = "some string or another"; vec.push_back(s);//calls push_back(const string&) vec.push_back("done");//calls push_back(string&&) /*Rvalue and Lvalue Reference Member Functions*/ string s1 = "a value", s2 = "another"; auto a = (s1 + s2).find('a'); //Here, we called the find member on the string rvalue that results from adding two strings. //Sometimes such usage can bes surprising. s1 + s2 = "wow";//Here we assign to the rvalue result of concatenating these strings. std::cout << s1 + s2 << std::endl;//still, a valueanother //We may run a function qualified by &only on an lvalue and may run a function qualified by && only on an rvalue: Foo i, j;//i and j are lvalues i = j;//ok: i is an lvalue retFoo() = i;//ok: retFoo() returns an lvalue //retVal() = j;//error: retVal()returns an rvalue(lhs must take a lvalue) i = retVal();//ok: we can pass an rvalue as the rhs operand to assignment vector<int>v = { 12,15,27,39,4,1,0,-3 }; Foo1 Ob1(v); Ob1.print(); }
true
57a38134769097b1f5f3965ba260cbcf659dd853
C++
sdail007/TheMountain
/TheMountain/Vertex.h
UTF-8
298
2.828125
3
[]
no_license
#pragma once class Vertex { private: float x, y, z; public: Vertex()=default; Vertex(float, float, float); float GetX() const; float GetY() const; float GetZ() const; friend std::ostream& operator<<(std::ostream& out, Vertex& obj); friend Vector operator-(const Vertex&, const Vertex&); };
true
f8e396d8a2cd4ec3403b6df6565d75e7d0c8233c
C++
tectronics/raupe
/modules/arduino/libraries/SerialCommand/SerialCommand.h
UTF-8
3,213
2.640625
3
[]
no_license
/******************************************************************************* SerialCommand - An Arduino library to tokenize and parse commands received over a serial port. Copyright (C) 2011 Steven Cogswell <steven.cogswell@gmail.com> http://husks.wordpress.com Version 20110523B. Version History: May 11 2011 - Initial version May 13 2011 - Prevent overwriting bounds of SerialCommandCallback[] array in addCommand() defaultHandler() for non-matching commands This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************************/ #ifndef SerialCommand_h #define SerialCommand_h #include "Arduino.h" #include <string.h> #define SERIALCOMMANDBUFFER 16 #define MAXSERIALCOMMANDS 10 #define MAXDELIMETER 2 //#define SERIALCOMMANDDEBUG 1 #undef SERIALCOMMANDDEBUG // Comment this out to run the library in debug mode (verbose messages) class SerialCommand { public: SerialCommand(); // Constructor void clearBuffer(); // Sets the command buffer to all '\0' (nulls) char *next(); // returns pointer to next token found in command buffer (for getting arguments to commands) void readSerial(); // Main entry point. void addCommand(char *, void(*)()); // Add commands to processing dictionary void addDefaultHandler(void (*function)()); // A handler to call when no valid command received. private: char inChar; // A character read from the serial stream char buffer[SERIALCOMMANDBUFFER]; // Buffer of stored characters while waiting for terminator character char bufPos; // Current position in the buffer char delim[MAXDELIMETER]; // null-terminated list of character to be used as delimeters for tokenizing (default " ") char term; // Character that signals end of command (default '\r') char *token; // Returned token from the command buffer as returned by strtok_r char *last; // State variable used by strtok_r during processing typedef struct _callback { char command[SERIALCOMMANDBUFFER]; void (*function)(); } SerialCommandCallback; // Data structure to hold Command/Handler function key-value pairs int numCommand; SerialCommandCallback CommandList[MAXSERIALCOMMANDS]; // Actual definition for command/handler array void (*defaultHandler)(); // Pointer to the default handler function }; #endif //SerialCommand_h
true
f405dde2e40cf4f391d4f69dee84010a44b5ade2
C++
treasureb/Projects
/ZMQ/req_res/rrbroker.cc
UTF-8
1,627
2.59375
3
[]
no_license
#include "zhelpers.hpp" int main(){ //准备上下文和套接字 void *context = zmq_init(1); void *frontend = zmq_socket(context,ZMQ_ROUTER); void *backend = zmq_socket(context,ZMQ_DEALER); zmq_bind(frontend,"tcp://*:5559"); zmq_bind(backend,"tcp://*:5560"); //初始化轮询集合 zmq_pollitem_t items[] = { {frontend,0,ZMQ_POLLIN,0}, {backend,0,ZMQ_POLLIN,0} }; //在套接字间转发消息 while(true){ zmq_msg_t message; int64_t more; zmq_poll(items,2,-1); if(items[0].revents & ZMQ_POLLIN){ while(true){ //处理所有消息帧 zmq_msg_init(&message); zmq_recv(frontemd,&message,0); size_t more_size = sizeof(more); zmq_getsockopt(frontend,ZMQ_RCVMORE,&message); zmq_send(backend,&message,more?ZMQ_SNDMORE,0); zme_msg_close(&message); if(!more) break; } } if(items[1].revents & ZMQ_POLLIN){ while(true){ //处理所有消息帧 zmq_msg_init(&message); zmq_recv(backend,&message,0); size_t more_size = sizeof(more); zmq_getsockopt(backend,ZMQ_RCVMORE,&more,&more_size); zmq_send(frontend,&message,more?ZMQ_SNDMORE:0); zmq_msg_close(&message); if(!more) break; } } } zmq_close(frontend); zmq_close(backend); zmq_term(context); return 0; }
true
b760e56dbcd622ae6f5ca9775ea5a08a46e319b6
C++
YKolokoltsev/DistPipelineFWK2
/src/executables/demo/ngspice/ngspice_src.h
UTF-8
5,831
2.515625
3
[]
no_license
// // Created by morrigan on 4/5/19. // #ifndef DISTPIPELINEFWK_NGSPICE_SRC_H #define DISTPIPELINEFWK_NGSPICE_SRC_H #include <iostream> #include <string> #include <map> #include <vector> #include <complex> #include <atomic> #include <mutex> #include <ngspice/sharedspice.h> #include "base_source.hpp" // TODO: Check if it is possible to have multiply instances of the initialized // TODO: NgSpice or this source should prevent creation of multiply objects of itself // TODO: (not a singleton pattern!) struct NgSpiceOutPkt : public BaseMessage{ // empty constructor NgSpiceOutPkt(){} // copy constructor NgSpiceOutPkt(const NgSpiceOutPkt& pkt) : BaseMessage(pkt), vectors(pkt.vectors), perc_completed(pkt.perc_completed){} /* * Depending on the analysis type NgSpice can return a number of * complex vectors, each one having it's own unique name. */ std::map<std::string,std::vector<std::complex<double>>> vectors; /* * Computation statistics (the getstat_cb callback) is almost always a computation * percentage. Each time we get a statistical report, we try to parse out the * completeness of the current computation in percents and if it is possible - * we store the result inside of this variable. */ float perc_completed = 0; }; struct InitData { std::string name; std::string title; std::string date; std::string type; std::vector<std::string> vectors; }; class NgSpiceSRC : public BaseSource<NgSpiceOutPkt>{ public: using tBase = BaseSource<NgSpiceOutPkt>; using tPtrOut = typename tBase::tPtrOut; NgSpiceSRC(std::string cir_file = std::string(), int slice_data = -1); ~NgSpiceSRC(); // NgSpice callback functions. The void* userdata always points onto the // instance of the current object. protected: /* * callback function for reading printf, fprintf, fput (NULL allowed) */ static int getchar_cb(char* outputreturn, int ident, void* userdata); /* * callback function for reading status string and percent value (NULL allowed) */ static int getstat_cb(char* outputreturn, int ident, void* userdata); /* * callback function for sending an array of structs containing data values of all * vectors in the current plot (simulation output) (NULL allowed) */ static int data_cb(pvecvaluesall vdata, int numvecs, int ident, void* userdata); /* * callback function for sending an array of structs containing info on all vectors in the * current "plot" (immediately before simulation starts) (NULL allowed) * * This function is called each time the simulation starts from the beginning. If we * "bg_halt" the simulation and call "bg_run" afterwards - thsi function will be called * for the second time. */ static int initdata_cb(pvecinfoall intdata, int ident, void* userdata); /* * Callback function for sending a boolean signal (true if computational thread is running)(NULL allowed) * * This function is called each time the computation start or resume it's work. */ static int simulation_runs_cb(bool not_running, int ident, void* userdata); /* * Callback function for transferring a flag to caller, generated by ngspice * upon a call to function controlled_exit. (required) The controlled exit can be * initiated by the next calls: * * ngSpice_Command((char*) "bg_halt"); -- switch to command mode * ngSpice_Command((char*) "quit"); -- quit the procss * * After "quit" command the circuit is unloaded and ngspice thread stops. All the memory * will be freed. After this command, the ngspice can be completely reinitialize * by ngSpice_Init(...) and subsequent calls. * * => Use "quit" in the source destructor. * => Use exit_cb callback to set ng_alive = false; */ static int exit_cb(int exitstatus, bool immediate, bool quitexit, int ident, void* userdata); // Some internal routines private: void send_out_message(); public: // start simulation void simulate(); private: /* * State variables of the NgSpice simulation process */ std::atomic<bool> is_loaded; std::atomic<bool> is_halted; /* * Current circuit file. This file can be nempty if you prefer to load * circuit dynamically with the help of ngSpice_Circ(...) function. */ std::string cir_file; /* * There are two basic modes to work with NgSpice. For example you can initiate a * very long (2h or more) transient simulation with typical dt ~ 5us and slice output data * into the outgoing packets por N points each. That is a classical oscilloscope mode. * * Another way, is to send an outgoing packet when a computation is done. In this case * the data is not sliced and slice_data should be less or equel to zero. A typical * example is an AC simulation. */ int slice_data; /* * An output message is prepared by NgSpice callbacks. When it is ready - it will be sent, * and at the same time a new empty instance of the output pkt will be created. This * is the law - out_msg is never nullptr! It is a buffer! */ tPtrOut out_msg; /* * Reading or writing of not atomic members of this class from NgSpice callbacks or * from the user messages should be always protected by this mutex. */ std::mutex comp_state_mtx; /* * When new circuit loads, it fills out some information about itself computation. * This data can be useful for the other nodes, for example for the user view. * It can be retrieved via the user message with callback technique. */ InitData init_data; }; #endif //DISTPIPELINEFWK_NGSPICE_SRC_H
true
8c9efa07abb702278f03749f1c666839bcb97016
C++
noobnoob-ctrl/hackhacktober-2
/reverse.cpp
UTF-8
269
2.78125
3
[ "MIT" ]
permissive
#include<stdio.h> int main() { //fill the code; int n; scanf(“%d”,&n); int arr[n]; int i; for(i = 0; i < n; i++) { scanf(“%d”,&arr[i]); } printf(“Reversed array is:\n”); for(i = n-1; i >= 0; i–) { printf(“%d\n”,arr[i]); } return 0; }
true
e189b2355ef6c584c5e697b352c4b83d4b5b3f5e
C++
claudiosousa/hard-pass
/firmware/project/src/settings/settings.cpp
UTF-8
918
2.84375
3
[]
no_license
#include "settings.h" #include <EEPROM.h> int address = 400; uint8_t config; void settings_setup() { config = EEPROM.read(address); } void settings_save() { EEPROM.write(address, config); } bool settings_getbit(char bitpos) { return config & 1 << bitpos; } void settings_setbit(char bitpos, bool setbit) { if (setbit) config |= 1 << bitpos; else config &= ~(1 << bitpos); settings_save(); } bool settings_getSoundIsOn() { return settings_getbit(1); } void settings_setSoundOn(bool soundOn) { settings_setbit(1, soundOn); } bool settings_getScreenIsRightOrientation() { return settings_getbit(2); } void settings_setScreenIsRightOrientation(bool rightOrientation) { settings_setbit(2, rightOrientation); } bool settings_getRemeberPwd() { return settings_getbit(0); } void settings_setRemeberPwd(bool remember) { settings_setbit(0, remember); }
true
23f83648605d803b42bf673cfe1a7af1ba7314e0
C++
astell601/teamprojects
/EVERLAND/Ride.cpp
UTF-8
8,112
3.046875
3
[]
no_license
#include <iostream> #include "Windows.h" //Sleep()을 가지고 있는 헤더파일 #include "Ride.h" using namespace std; Viking::Viking() :people(0), answer(0) {} //생성자 + 멤버이니셜라이징 Viking::Viking(int n) :people(n) { //생성자 + 멤버이니셜라이징 for (int i = 0; i < people; i++) { total++; } } int Viking::getSeat() { return seat; } int Viking::getCost() { return cost; } int Viking::getTime() { return time; } int Viking::getTotal() { return total; } int Viking::setSeat(int m) { return seat - m; } int Viking::IsViking() { if (total <= seat) { IsOk = 1; return IsOk; } else if (total < seat / 2) { cout << "수용가능한 최소 인원보다 " << (seat / 2) - total << "명 적습니다." << endl; IsOk = 0; return IsOk; } else { cout << "정원이 " << total - seat << "명 초과하였습니다" << endl; cout << "대기시간은 약" << time * (total - seat) << "분 입니다." << endl; cout << "진행하시겠습니까? (Y/N)" << endl; cin >> answer; if (answer == 'Y') { for (int i = total - seat; i > 0; i--) { total--; } IsOk = 1; return IsOk; } else if (answer == 'N') { return IsOk; } else { return IsOk; } return time * (total - seat); } } int Viking::RunViking() { if (IsOk == 1) { for (int k = 1; k <= time; k++) { cout << k << "..." << endl; Sleep(1000); } cout << "인원" << " : " << people << endl; cout << "금액" << " : " << people * cost << endl; cout << "즐거운 시간 보내세요!" << endl; IsOk = 0; return people * cost; } } Rollercoaster::Rollercoaster() :people(0), answer(0) {} //생성자 + 멤버이니셜라이징 Rollercoaster::Rollercoaster(int n) :people(n) { //생성자 + 멤버이니셜라이징 for (int i = 0; i < people; i++) { total++; } } int Rollercoaster::getSeat() { return seat; } int Rollercoaster::getCost() { return cost; } int Rollercoaster::getTime() { return time; } int Rollercoaster::getTotal() { return total; } int Rollercoaster::setSeat(int m) { return seat - m; } int Rollercoaster::IsRoller() { if (total <= seat) { IsOk = 1; return IsOk; } else if (total < seat / 2) { cout << "수용가능한 최소 인원보다 " << (seat / 2) - total << "명 적습니다." << endl; IsOk = 0; return IsOk; } else { cout << "정원이 " << total - seat << "명 초과하였습니다" << endl; cout << "대기시간은 약" << time * (total - seat) << "분 입니다." << endl; cout << "진행하시겠습니까? (Y/N)" << endl; cin >> answer; if (answer == 'Y') { for (int i = total - seat; i > 0; i--) { total--; } IsOk = 1; return IsOk; } else if (answer == 'N') { return IsOk; } else { return IsOk; } return time * (total - seat); } } int Rollercoaster::RunRoller() { if (IsOk == 1) { for (int k = 1; k <= time; k++) { cout << k << "..." << endl; Sleep(1000); } cout << "인원" << " : " << people << endl; cout << "금액" << " : " << people * cost << endl; cout << "즐거운 시간 보내세요!" << endl; IsOk = 0; return people * cost; } } Gyrospin::Gyrospin() :people(0), answer(0) {} //생성자 + 멤버이니셜라이징 Gyrospin::Gyrospin(int n) :people(n) { //생성자 + 멤버이니셜라이징 for (int i = 0; i < people; i++) { total++; } } int Gyrospin::getSeat() { return seat; } int Gyrospin::getCost() { return cost; } int Gyrospin::getTime() { return time; } int Gyrospin::getTotal() { return total; } int Gyrospin::setSeat(int m) { return seat - m; } bool Gyrospin::IsGyro() { if (total <= seat) { IsOk++; return IsOk; } else if (total < seat / 2) { cout << "수용가능한 최소 인원보다 " << (seat / 2) - total << "명 적습니다." << endl; IsOk = 0; return IsOk; } else { if (total > seat) { cout << "정원이 " << total - seat << "명 초과하였습니다" << endl; cout << "대기시간은 약" << time * (total - seat) << "분 입니다." << endl; cout << "진행하시겠습니까? (Y/N)" << endl; cin >> answer; if (answer == 'Y') { for (int i = total - seat; i > 0; i--) { total--; } IsOk = 1; return IsOk; } else if (answer == 'N') { return IsOk; } else { return IsOk; } return time * (total - seat); } } } int Gyrospin::RunGyro() { if (IsOk == 1) { for (int k = 1; k <= time; k++) { cout << k << "..." << endl; Sleep(1000); } cout << "인원" << " : " << people << endl; cout << "금액" << " : " << people * cost << endl; cout << "즐거운 시간 보내세요!" << endl; IsOk = 0; return people * cost; } } MerryGoRound::MerryGoRound() :people(0), answer(0) {} //생성자 + 멤버이니셜라이징 MerryGoRound::MerryGoRound(int n) :people(n) { //생성자 + 멤버이니셜라이징 for (int i = 0; i < people; i++) { total++; } } int MerryGoRound::getSeat() { return seat; } int MerryGoRound::getCost() { return cost; } int MerryGoRound::getTime() { return time; } int MerryGoRound::getTotal() { return total; } int MerryGoRound::setSeat(int m) { return seat - m; } bool MerryGoRound::IsMerry() { if (total <= seat) { IsOk++; return IsOk; } else if (total < seat / 2) { cout << "수용가능한 최소 인원보다 " << (seat / 2) - total << "명 적습니다." << endl; IsOk = 0; return IsOk; } else { if (total > seat) { cout << "정원이 " << total - seat << "명 초과하였습니다" << endl; cout << "대기시간은 약" << time * (total - seat) << "분 입니다." << endl; cout << "진행하시겠습니까? (Y/N)" << endl; cin >> answer; if (answer == 'Y') { for (int i = total - seat; i > 0; i--) { total--; } IsOk = 1; return IsOk; } else if (answer == 'N') { return IsOk; } else { return IsOk; } return time * (total - seat); } } } int MerryGoRound::RunMerry() { if (IsOk == 1) { for (int k = 1; k <= time; k++) { cout << k << "..." << endl; Sleep(1000); } cout << "인원" << " : " << people << endl; cout << "금액" << " : " << people * cost << endl; cout << "즐거운 시간 보내세요!" << endl; IsOk = 0; return people * cost; } } Flumride::Flumride() :people(0), answer(0) {} //생성자 + 멤버이니셜라이징 Flumride::Flumride(int n) :people(n) { //생성자 + 멤버이니셜라이징 for (int i = 0; i < people; i++) { total++; } } int Flumride::getSeat() { return seat; } int Flumride::getCost() { return cost; } int Flumride::getTime() { return time; } int Flumride::getTotal() { return total; } int Flumride::setSeat(int m) { return seat - m; } bool Flumride::IsFLum() { if (total <= seat) { IsOk++; return IsOk; } else if (total < seat / 2) { cout << "수용가능한 최소 인원보다 " << (seat / 2) - total << "명 적습니다." << endl; IsOk = 0; return IsOk; } else { if (total > seat) { cout << "정원이 " << total - seat << "명 초과하였습니다" << endl; cout << "대기시간은 약" << time * (total - seat) << "분 입니다." << endl; cout << "진행하시겠습니까? (Y/N)" << endl; cin >> answer; if (answer == 'Y') { for (int i = total - seat; i > 0; i--) { total--; } IsOk = 1; return IsOk; } else if (answer == 'N') { return IsOk; } else { return IsOk; } return time * (total - seat); } } } int Flumride::RunFlum() { if (IsOk == 1) { for (int k = 1; k <= time; k++) { cout << k << "..." << endl; Sleep(1000); } cout << "인원" << " : " << people << endl; cout << "금액" << " : " << people * cost << endl; cout << "즐거운 시간 보내세요!" << endl; IsOk = 0; return people * cost; } }
true
b99db87cb80ccf631eda97504b38ea98dc171b75
C++
pranay2063/CS17
/OOPS/Friend/4FriendClass.cpp
UTF-8
427
3.90625
4
[]
no_license
#include <iostream> using namespace std; class A{ int x; public: void set(){ x = 69; } friend class B; }; class B{ //class B can access private members also as it is a friend of A public: void display(A a){ //private member of class A can now be accessed through object as B is friend cout<<"x is : "<<a.x<<endl; } }; int main() { A obj; obj.set(); B obj2; obj2.display(obj); //x is : 69 return 0; }
true
61ffddc9f07453728328a793055b380f497ca3ab
C++
thecodingwizard/competitive-programming
/alphastar/alphastar-cs501ab-usaco-platinum-summer-2018-s2/14-advanced-dynamic-programming-1/06 - Moovie Mooving.cpp
UTF-8
3,493
2.578125
3
[]
no_license
/* Moovie Mooving ============== Bessie is out at the movies. Being mischievous as always, she has decided to hide from Farmer John for L (1 <= L <= 100,000,000) minutes, during which time she wants to watch movies continuously. She has N (1 <= N <= 20) movies to choose from, each of which has a certain duration and a set of showtimes during the day. Bessie may enter and exit a movie at any time during one if its showtimes, but she does not want to ever visit the same movie twice, and she cannot switch to another showtime of the same movie that overlaps the current showtime. Help Bessie by determining if it is possible for her to achieve her goal of watching movies continuously from time 0 through time L. If it is, determine the minimum number of movies she needs to see to achieve this goal (Bessie gets confused with plot lines if she watches too many movies). INPUT: The first line of input contains N and L. The next N lines each describe a movie. They begin with its integer duration, D (1 <= D <= L) and the number of showtimes, C (1 <= C <= 1000). The remaining C integers on the same line are each in the range 0..L, and give the starting time of one of the showings of the movie. Showtimes are distinct, in the range 0..L, and given in increasing order. SAMPLE INPUT: 4 100 50 3 15 30 55 40 2 0 65 30 2 20 90 20 1 0 OUTPUT: A single integer indicating the minimum number of movies that Bessie needs to see to achieve her goal. If this is impossible output -1 instead. SAMPLE OUTPUT: 3 SOLUTION NOTES: Bessie should attend the first showing of the fourth movie from time 0 to time 20. Then she watches the first showing of the first movie from time 20 to time 65. Finally she watches the last showing of the second movie from time 65 to time 100. */ #include <iostream> #include <string> #include <utility> #include <sstream> #include <algorithm> #include <stack> #include <vector> #include <queue> #include <map> #include <set> #include <bitset> #include <cmath> #include <cstring> #include <iomanip> #include <math.h> #include <assert.h> using namespace std; #define INF 1000000000 #define LL_INF 0xfffffffffffffffLL #define LSOne(S) (S & (-S)) #define EPS 1e-9 #define A first #define B second #define mp make_pair #define PI acos(-1.0) typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; int dp[(1 << 20)]; int movieStart[20][1000]; int movieDuration[20]; int movieCt[20]; int main() { ios_base::sync_with_stdio(false); int n, l; cin >> n >> l; for (int i = 0; i < n; i++) { int duration, ct; cin >> duration >> ct; for (int j = 0; j < ct; j++) { int start; cin >> start; movieStart[i][j] = start; } movieCt[i] = ct; movieDuration[i] = duration; } memset(dp, -1, sizeof dp); dp[0] = 0; int ans = INF; for (int i = 0; i < (1 << n); i++) { if (dp[i] == -1) continue; if (dp[i] >= l) { ans = min(ans, __builtin_popcount(i)); } for (int j = 0; j < n; j++) { if (i & (1 << j)) continue; int idx = i | (1 << j); auto itr = lower_bound(movieStart[j], movieStart[j] + movieCt[j], dp[i]); if (*itr > dp[i]) itr--; if (itr < movieStart[j]) continue; dp[idx] = max(dp[idx], *itr + movieDuration[j]); } } if (ans == INF) { cout << "-1" << endl; return 0; } cout << ans << endl; return 0; }
true
21a2f1ddc5c79d4510cc16d4c8c6aefaf629626f
C++
timmyzeng/newcode
/2.2-XiaoYiFavoriteWords.cc
UTF-8
2,141
3.59375
4
[]
no_license
/* 小易喜欢的单词具有以下特性: 1.单词每个字母都是大写字母 2.单词没有连续相等的字母 3.单词没有形如“xyxy”(这里的x,y指的都是字母,并且可以相同)这样的子序列,子序列可能不连续。 例如: 小易不喜欢"ABBA",因为这里有两个连续的'B' 小易不喜欢"THETXH",因为这里包含子序列"THTH" 小易不喜欢"ABACADA",因为这里包含子序列"AAAA" 小易喜欢"A","ABA"和"ABCBA"这些单词 给你一个单词,你要回答小易是否会喜欢这个单词(只要不是不喜欢,就是喜欢)。 输入描述: 输入为一个字符串,都由大写字母组成,长度小于100 输出描述: 如果小易喜欢输出"Likes",不喜欢输出"Dislikes" 示例1 输入 AAA 输出 Dislikes */ #include <iostream> #include <string> using namespace std; int main(){ string str; while(cin >> str){ int arr[256]; for (int i = 0; i < 256; ++ i){ arr[i] = 0; } int size = str.size(); bool flag = false; for(int i = 0; i < size; ++ i){ if(islower(str[i])){ cout << "Dislikes" << endl; flag = true; break; } if(i+1 <= size && str[i] == str[i+1]){ cout << "Dislikes" << endl; flag = true; break; } ++arr[(int)(str[i])]; } if(flag) continue; for (int i = 0; i < size; ++ i){ if(arr[(int)(str[i])] == 1) str.erase(i, 1); } size = str.size(); for (int i = 0; i < size - 3; ++ i){ string str1 = str.substr(i, 2); for (int j = i + 2; j < size - 1; ++ j){ string str2 = str.substr(j, 2); if(str1 == str2){ cout << "Dislikes" << endl; flag = true; break; } } if(flag) break; } if(flag) continue; cout << "Likes" << endl; } }
true
48ed69ba594606378d4ef4237e1683bbf4847915
C++
TelloViz/DD_BD
/Character_Movement/Actor.hpp
UTF-8
512
2.765625
3
[]
no_license
#pragma once #include <SFML/Graphics.hpp> class Actor : public sf::Drawable { public: Actor(sf::Vector2f size, sf::Vector2f pos, sf::Color color); virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; enum DIRECTION { NONE, UP, DOWN, LEFT, RIGHT } currentDir; void move(DIRECTION, float dist); sf::Vector2f pos() const { return m_body.getPosition(); } sf::Vector2f size() const { return m_body.getSize(); } private: sf::RectangleShape m_body; };
true
a95272ae5f33fb9131e812cbc5651243744e81cc
C++
dmitrytyurev/HomeProjects
/LearnWordsV2/LearnWords/FileOperate.h
UTF-8
472
2.546875
3
[]
no_license
#pragma once #include <vector> #include "WordsManager.h" struct FileOperate { static void LoadFromFile(const char* fullFileName, std::vector<WordsManager::WordInfo>& wordsInfo); static void SaveToFile(const char* fullFileName, const std::vector<WordsManager::WordInfo>& wordsInfo); private: static std::string LoadStringFromArray(const std::vector<char>& buffer, int* indexToRead); static int LoadIntFromArray(const std::vector<char>& buffer, int* indexToRead); };
true
323cfd0b9dc2e84d64a7460fdb69ede0b67e01b4
C++
amitnileka/competitive-Programme
/map.cpp
UTF-8
651
2.6875
3
[]
no_license
#include<iostream> #include<map> using namespace std; int main() { map<string,int> m; map<string,int>::iterator it; int q,i=0; int a; string x; int y; cin>>q; while(i<q) { cin>>a; switch(a) { case 1: cin>>x>>y; m[x]+=y; break; case 2: cin>>x; it=m.find(x); if(it!=m.end()) m.erase(it); break; case 3: cin>>x; cout<<m[x]<<endl; break; } i++; } return 0; }
true
b13290e5d8268fd9e5c5fa932d1e16e8b31cafc5
C++
KurodaKanbei/ACM
/Template of other teams/Grimoire/Template/source/string/SuffixAutomaton_array.cpp
UTF-8
947
2.625
3
[]
no_license
/* * Suffix Automaton - array version * SAMSAMSAM? SAMSAMSAM! */ namespace SAM { int to[100005 << 1][26], parent[100005 << 1], step[100005 << 1], tot; int root, np; int sam_len; int newnode(int STEP = 0) { ++tot; memset(to[tot], 0, sizeof to[tot]); parent[tot] = 0; step[tot] = STEP; return tot; } void init() { tot = 0; root = np = newnode(sam_len = 0); } void extend(char ch) { int x = ch - 'a'; int last = np; np = newnode(++sam_len); for (; last && !to[last][x]; last = parent[last]) to[last][x] = np; if (!last) parent[np] = root; else { int q = to[last][x]; if (step[q] == step[last] + 1) parent[np] = q; else { nq = newnode(step[last] + 1); memcpy(to[nq], to[q], sizeof to[q]); parent[nq] = parent[q]; parent[q] = parent[np] = nq; for (; last && to[last][x] == q; last = parent[last]) to[last][x] = nq; } } } }
true
6a2de1b933686e4e4a7b4e8c4602c75e8f0d81c2
C++
paulolemus/ee205
/Lab10/tests/test-Sales.cpp
UTF-8
4,584
3.203125
3
[]
no_license
#include <gtest/gtest.h> #include <string> #include <sstream> #include "../Sales.h" TEST(Sales, salary_constructor) { Sales ad(65000); ASSERT_TRUE(true); } TEST(Sales, salary_commission_constructor) { double salary = 65000; double commission = 4000; Sales ad(salary, commission); ASSERT_EQ( ad.getSalary(), salary ); ASSERT_EQ( ad.getCommission(), commission ); } TEST(Sales, setters_n_getters) { long int id = 100; std::string name = "John"; std::string address = "91-1000B Kapokalani St"; std::string phone = "808-123-4567"; std::string email = "johndoe@gaggle.com"; std::string department = "Gag"; std::string title = "Fun specialist"; double salary = 65000; double commission = 4000; Sales ad(0); ad.setId(id); ad.setName(name); ad.setAddress(address); ad.setPhone(phone); ad.setEmail(email); ad.setDepartment(department); ad.setTitle(title); ad.setSalary(salary); ad.setCommission(commission); ASSERT_EQ(ad.getId(), id); ASSERT_EQ(ad.getName(), name); ASSERT_EQ(ad.getAddress(), address); ASSERT_EQ(ad.getPhone(), phone); ASSERT_EQ(ad.getEmail(), email); ASSERT_EQ(ad.getDepartment(), department); ASSERT_EQ(ad.getTitle(), title); ASSERT_EQ(ad.getSalary(), salary); ASSERT_EQ(ad.getCommission(), commission); } TEST(Sales, init_constructor) { double salary = 65000; long int id = 100; std::string name = "John"; std::string address = "91-1000B Kapokalani St"; std::string phone = "808-123-4567"; std::string email = "johndoe@gaggle.com"; std::string department = "Gag"; std::string title = "Fun specialist"; double commission = 400; Sales ad(id, name, address, phone, email, department, title, salary, commission); ASSERT_EQ(ad.getId(), id); ASSERT_EQ(ad.getName(), name); ASSERT_EQ(ad.getAddress(), address); ASSERT_EQ(ad.getPhone(), phone); ASSERT_EQ(ad.getEmail(), email); ASSERT_EQ(ad.getDepartment(), department); ASSERT_EQ(ad.getTitle(), title); ASSERT_EQ(ad.getSalary(), salary); ASSERT_EQ(ad.getCommission(), commission); } TEST(Sales, monthlySalary) { double salary = 65000; double commission = 400;; Sales ad(salary, commission); ASSERT_EQ(ad.monthlySalary(), salary / 12 + commission); ASSERT_EQ(ad.getCommission(), 0.0); } TEST(Sales, print_info) { long int id = 100; std::string name = "John"; std::string address = "91-1000B Kapokalani St"; std::string phone = "808-123-4567"; std::string email = "johndoe@gaggle.com"; std::string department = "Gag"; std::string title = "Fun specialist"; Sales ad(id, name, address, phone, email, department, title, 0, 0); ad.printInfo(); ASSERT_TRUE(true); } TEST(Sales, update_valid) { std::stringstream ss("y\n40000\ny\n150\n"); std::stringstream out; std::streambuf* coutbuf = std::cout.rdbuf(); std::streambuf* cinbuf = std::cin.rdbuf(); std::cin.rdbuf( ss.rdbuf() ); std::cout.rdbuf( out.rdbuf() ); double salary = 54000; double commission = 540; Sales ad(salary, commission); ASSERT_EQ(ad.getSalary(), salary); ASSERT_EQ(ad.getCommission(), commission); ad.update(); ASSERT_EQ(ad.getSalary(), 40000); ASSERT_EQ(ad.getCommission(), 150); ASSERT_EQ(ad.monthlySalary(), 40000.0 / 12 + 150); ASSERT_EQ(ad.getCommission(), 0.0); std::cout.rdbuf( coutbuf ); std::cin.rdbuf( cinbuf ); } TEST(Sales, update_invalid_then_valid) { std::stringstream ss("y\ninvalidhere\n40000\ny\ninvalid\n150\n"); std::stringstream out; std::streambuf* coutbuf = std::cout.rdbuf(); std::streambuf* cinbuf = std::cin.rdbuf(); std::cin.rdbuf( ss.rdbuf() ); std::cout.rdbuf( out.rdbuf() ); double salary = 54000; double commission = 540; Sales ad(salary, commission); ASSERT_EQ(ad.getSalary(), salary); ASSERT_EQ(ad.getCommission(), commission); ad.update(); ASSERT_EQ(ad.getSalary(), 40000); ASSERT_EQ(ad.getCommission(), 150); ASSERT_EQ(ad.monthlySalary(), 40000.0 / 12 + 150); ASSERT_EQ(ad.getCommission(), 0.0); std::cout.rdbuf( coutbuf ); std::cin.rdbuf( cinbuf ); } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
d47cf98a1ef6ef60573693fdb27cce7dcafdf844
C++
wusongnie/LeetCodeOJ_Solutions
/777_Swap Adjacent in LR String.cpp
UTF-8
695
2.828125
3
[ "MIT" ]
permissive
class Solution { public: bool canTransform(string start, string end) { string s, e; for (int i = 0; i < start.size(); i++) if (start[i] != 'X') s = s + start[i]; for (int i = 0; i < end.size(); i++) if (end[i] != 'X') e = e + end[i]; if (s != e) return false; int sl = 0, sr = 0, el = 0, er = 0; for (int i = 0; i < start.size(); i++) { if (start[i] == 'L') sl ++; if (start[i] == 'R') sr ++; if (end[i] == 'L') el ++; if (end[i] == 'R') er ++; if (er > sr || sl > el ) return false; } return true; } };
true
6b504729e2a1deec2a38ba43b72dcd99a6798cb2
C++
asokolov1104/vs2019repo
/ProjectSandBox/winThreading/main.cpp
WINDOWS-1251
1,559
3.140625
3
[]
no_license
// #include <windows.h> #include <iostream> // const int _NUM_THREADS = 10; // struct TThreadParam { int iCounter; }; // DWORD WINAPI ThreadFunc(PVOID pvParam) { DWORD dwResult = 0; //// !- - .. //TThreadParam mParam = *((TThreadParam*)pvParam); // .. TThreadParam *pParam = (TThreadParam*)pvParam; // while (pParam->iCounter < 50) { // Suspends the execution of the current thread Sleep(100L); ++pParam->iCounter; } // .. return dwResult; } // int main(int argc, char* argv) { // Local variables TThreadParam l_threadParam[_NUM_THREADS] = { 0 }; // Thread creating .. DWORD dwThreadID[_NUM_THREADS]; HANDLE hThread[_NUM_THREADS]; for (int i = 0; i < _NUM_THREADS; ++i) hThread[i] = CreateThread(NULL, 0, ThreadFunc, (PVOID)&l_threadParam[i], 0, &dwThreadID[i]); //.. Thread is working std::cout << "Waiting single object.. " << std::endl; //WaitForSingleObject(hThread, INFINITE); WaitForMultipleObjects(_NUM_THREADS, hThread, TRUE, INFINITE); // Result of multithreading for (int i = 0; i < _NUM_THREADS; ++i) std::cout << "Counter " << i << " = "<< l_threadParam[i].iCounter << std::endl; std::cin.get(); // return 0; }
true
357b9c3a1535ea858518917b576f59499c7d6787
C++
Algostu/boradori
/ONLINE_CONTEST/UCPC/tryout_round/hankyul/E.cpp
UTF-8
1,406
2.734375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct node{ node * parent; vector<node *> childs; }; void solve(){ int N, from, to, root_index=0; long double dig=0, jit=0; vector<node*> tree; vector<node*> cur_stack; node * n, * root; cin >> N; for(int i=0; i<1000; i++){ tree.push_back(new node); tree[i]->parent = NULL; } for(int i=0; i<N-1; i++){ scanf("%d %d", &from, &to); tree[from-1]->childs.push_back(tree[to-1]); tree[to-1]->parent = tree[from-1]; } for(int i=0; i<N; i++){ if(tree[i]->parent == NULL){ root = tree[i]; cur_stack.push_back(root); break; } } assert(!cur_stack.empty()); while(!cur_stack.empty()){ n = cur_stack.back(); cur_stack.pop_back(); // jit double nchild = n->childs.size(); if(n->parent != NULL){ nchild++; } if(nchild >= 3){ jit += nchild * (nchild-1) * (nchild-2) / 6; } // dig double sum=0; for(int i=0; i<n->childs.size(); i++){ sum += n->childs[i]->childs.size(); } if(n->parent != NULL) dig += sum * n->childs.size(); else dig += sum * (n->childs.size() - 1); cur_stack.insert(cur_stack.end(), n->childs.begin(), n->childs.end()); //printf("node : %d\n", n->key); //printf("%lld %lld \n", dig, jit); } if(dig > jit * 3){ printf("D\n"); } else if (dig == jit * 3){ printf("DUDUDUNGA\n"); } else { printf("G\n"); } } int main(void){ solve(); return 0; }
true
135aacc27825a9fbfe7eb6a04864b8309fb6124e
C++
NUKEDO/practice_coding
/aizu_online_judge/ALDS1_11_B_stack.cpp
UTF-8
1,886
3
3
[]
no_license
// https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_B&lang=ja // 螺旋本を参考に作成(ほぼそのまま) // 螺旋本と異なりi = 1; i <= n で設計されてるので注意 // stackを使用した解答 #include <bits/stdc++.h> using namespace std; #define WHITE -1 #define GRAY -2 #define BLACK -3 int n, count_time; vector<int> color(100 + 1, WHITE), nt(100 + 1, 1), time_s(100 + 1), time_e(100 + 1); //s:start, e:end int next(vector<vector<int> > g, int u) { for(int i = nt.at(u); i <= n; i++) { nt.at(u) = i + 1; if(g.at(u).at(i) == 1) return i; } return -1; } void dfs_visit(vector<vector<int> > g, int u) { stack<int> save; save.push(u); color.at(u) = GRAY; time_s.at(u) = ++count_time; while(save.size() > 0) { u = save.top(); int v = next(g, u); if(v == -1) { save.pop(); color.at(u) = BLACK; time_e.at(u) = ++count_time; } else { if(color.at(v) == WHITE) { color.at(v) = GRAY; time_s.at(v) = ++count_time; save.push(v); } } } } void dfs(vector<vector<int> > g) { count_time = 0; for(int i = 1; i <= n; i++) { if(color.at(i) == WHITE) dfs_visit(g, i); } } void printDFS() { for(int i = 1; i <= n; i++) { printf("%d %d %d\n", i, time_s.at(i), time_e.at(i)); } } void printG(vector<vector<int> > g) { for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(j != 1) printf(" "); printf("%d", g.at(i).at(j)); } printf("\n"); } } // 隣接リスト表現 int main() { int u, k, v; scanf("%d\n", &n); vector<vector<int> > g(n + 1, vector<int>(100 + 1, 0));//g:graph for(int i = 1; i <= n; i++) { scanf("%d %d", &u, &k); for(int j = 1; j <= k; j++) { scanf("%d", &v); g.at(i).at(v) = 1; } } // printG(g); dfs(g); printDFS(); }
true
8d2e158564413778eed21712382300199adc3e8c
C++
bishoyAtif/problemSolving
/codeForces/A.carrotCakes.cpp
UTF-8
927
2.796875
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main(int argc, char const *argv[]) { double n, t, k, d, timeOne, timeTwo = 0; cin >> n >> t >> k >> d; if ((t <= d && n <= k) || n <= k) { cout << "NO" << endl; return 0; } timeOne = ceil(n / k) * t; if (d < t) { n = ceil(n / 2) - 1; timeTwo = ceil(n / k) * t + d; } else { timeTwo += (d / t) * t; n -= floor(d / t) * k; d = fmod(d, t); if (n > k) { cout << "YES" << endl; return 0; } if ((t <= d && n <= k) || n <= k) { cout << "NO" << endl; return 0; } n = ceil(n / 2) - 1; timeTwo += ceil(n / k) * t + d; } if (timeTwo < timeOne) { cout << "YES" << endl; return 0; } cout << "NO" << endl; return 0; }
true
7291f7d4bdd0f32c524ec203209f8b3519876a04
C++
YoshiroAraya/Yoshidagakuen_ArayaYoshiro
/吉田学園情報ビジネス専門学校 荒谷由朗/04_OverKillSoulHell/00_制作環境/lasteenemy.h
SHIFT_JIS
2,388
2.703125
3
[]
no_license
//============================================================================= // // ŏIGl~[ [lasteenemy.h] // Author : rJ RN // //============================================================================= #ifndef _LASTEENEMY_H_ #define _LASTEENEMY_H_ #include "main.h" #include "scene2D.h" #include "bullet.h" #define LASTENEMY_TEXTURENAME00 "data/TEXTURE/enemy000.png" // G0 #define LASTENEMY_TEXTURENAME01 "data/TEXTURE/enemy001.png" // G1 #define MAX_LASTENEMYTEX (2) // eNX`̍ő吔 #define MAX_LASTENEMYSPEED (0.4f) // ړx //============================================================================= // NX̒` //============================================================================= class CLastEnemy : public CScene2D // hNX { public: typedef enum { LASTENEMYTYPE_000 = 0, LASTENEMYTYPE_001, LASTENEMYTYPE_002, LASTENEMYTYPE_003, LASTENEMYTYPE_004, LASTENEMYTYPE_005, LASTENEMYTYPE_MAX }LASTENEMYTYPE; typedef enum { LASTENEMYSTATSE_NONE = 0, LASTENEMYSTATSE_DAMEGE, LASTENEMYSTATSE_MAX }LASTENEMYSTATSE; CLastEnemy(); ~CLastEnemy(); static CLastEnemy *Create (D3DXVECTOR3 pos, float width, float height, int texID); static HRESULT Load (void); static void Unload (void); HRESULT Init (D3DXVECTOR3 pos, float width, float height, int texID); void Uninit (void); void Update (void); void Draw (void); void HitEnemy(int nDamage, CBullet::BULLETTYPE bullettype); private: static LPDIRECT3DTEXTURE9 m_pTexture[MAX_LASTENEMYTEX]; // eNX` D3DXVECTOR3 m_pos; // |S̈ړ D3DXVECTOR3 m_move; // |S̈ړ D3DXCOLOR m_col; // F LASTENEMYSTATSE m_Statse; // Xe[^X int m_TypeNum; // ^Cvԍ int m_nCount; // JE^[ int m_nCounterAnim; // Aj[VJE^[ int m_nPatternAnim; // Aj[Vp^[No. int m_life; // Ct int m_nCntBlink; // F̃JE^[ float m_fWidth; // float m_fHeight; // bool m_bRoundtrip; // bool m_nBlink; // F̐؂ւ static int m_nDed; // StO }; #endif
true
10ebf84490f9a20f2e84de9ec63a1004cac73efa
C++
Vito-bo/C-code
/9-9/9-9/test.cpp
GB18030
1,596
3.25
3
[]
no_license
//Ϊ-C #include <stdio.h> #include <string.h> /* #define CHAR char #define ULONG unsigned long #define VOID void CHAR *VOS_strncpy(CHAR *pcDest, const CHAR *szSrc, ULONG ulLength) { CHAR *pcPoint = pcDest; if ((NULL == szSrc) || (NULL == pcDest)) { return NULL; } while (ulLength && (*pcPoint = *szSrc)) { pcPoint++; szSrc++; ulLength--; } if (!ulLength) { *pcPoint = '\0'; } return pcDest; } VOID main(VOID) { CHAR szStrBuf[] = "1234567890"; CHAR szStrBuf1[] = "1234567890"; strncpy(szStrBuf, "ABC", strlen("ABC")); //ַ"ABC"ȥ VOS_strncpy(szStrBuf1, "ABC", strlen("ABC"));//ַ"ABC"ȥ'\0' printf("Str1 = %s\nStr2 = %s\n", szStrBuf, szStrBuf1); } struct BBB { long lA1; //4 char cA2; //1 char cA3; //1+2 long lA4; //4 long lA5; //4 }*p; int main() { p = (struct BBB*)0x100000; printf("%p\n", p + 0x1); //0X100010 printf("%p\n", (unsigned long)p + 0x1 );//0X100001 printf("%p\n",(unsigned long*)p + 0x1); //0X100004 printf("%p\n", (char *)p + 0x1);///0X100001 return 0; } //14. int main() { char c; unsigned char uc; unsigned short us; c = 128; uc = 128; us = c + uc; printf("0x%x\n", us); // us = (unsigned char)c + uc; printf("0x%x\n", us); // us = c + (char)uc; printf("0x%x\n", us); return 0; } //12. int main() { unsigned char a = 200; unsigned char b = 100; unsigned char c = 0; c = a + b; printf("%d %d", a + b, c); return 0; } //10. #define N 4 #define Y(n) ((N+2)*n) int main() { int z = 2 * (N + Y(5 + 1)); printf("%d\n", z); return 0; } */
true
cc7019ba4a15875fd51bb90488537d591f64364b
C++
missingXiong/leetcode
/Amazon/957. Prison Cells After N Days.cpp
UTF-8
1,247
3.109375
3
[]
no_license
// time complexity vector<int> prisonAfterNDays(vector<int>& cells, int N) { int size = cells.size(); vector<vector<int>> rolling(2, vector<int>(size, 0)); for(int i = 0; i < size; i++) rolling[0][i] = cells[i]; int old = 0, now = 0; for(int k = 1; k <= N; k++) { old = now; now = 1 - now; rolling[now][0] = rolling[now][size - 1] = 0; for(int i = 1; i < size - 1; i++) { if(rolling[old][i - 1] == rolling[old][i + 1]) rolling[now][i] = 1; else rolling[now][i] = 0; } } return rolling[now]; } /* 由于题中给出的N过大,因此算法应该保证和N的关系不大 那么一定是存在某种规律 */ vector<int> prisonAfterNDays(vector<int>& cells, int N) { vector<int> fc, curr(cells.size(), 0); for(int cycle = 1; N-- > 0; cells = curr, cycle++) { for(int i = 1; i < cells.size() - 1; i++) curr[i] = cells[i - 1] == cells[i + 1]; if(cycle == 1) fc = curr; else if(curr == fc) N %= (cycle - 1); } return curr; /* int n = cells.size(), cycle = 0; vector<int> cur(n, 0), direct; while(N-- > 0) { for(int i = 1; i < n - 1; ++i) cur[i] = cells[i - 1] == cells[i + 1]; if(direct.empty()) direct = cur; else if(direct == cur) N %= cycle; ++cycle; cells = cur; } return cur; */ }
true
415d713a7bde23f182c3090f84b352def7301321
C++
manzali/bdx
/include/ru/ru_args.hpp
UTF-8
1,510
2.734375
3
[]
no_license
#ifndef RU_RU_ARGS_HPP #define RU_RU_ARGS_HPP #include <chrono> #include <cstdlib> // exit #include <iostream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> namespace ru { namespace po = boost::program_options; struct ru_args { std::string id; boost::filesystem::path config_file; std::chrono::seconds timeout; }; ru_args parse_ru_args(int argc, char *argv[]) { po::options_description desc("options"); ru_args args; int raw_timeout = 0; desc.add_options()("help,h", "print help messages.")( "id,i", po::value<std::string>(&args.id)->required(), "readout unit identification string.")( "config,c", po::value<boost::filesystem::path>(&args.config_file)->required(), "configuration file.")("timeout,t", po::value<int>(&raw_timeout), "timeout in seconds (default = 0)."); try { po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).run(), vm); if (vm.count("help")) { std::cout << desc << std::endl; exit(EXIT_SUCCESS); } po::notify(vm); // check timeout value if (raw_timeout < 0) { std::cerr << "wrong timeout value: " << raw_timeout << std::endl; exit(EXIT_FAILURE); } // convert timeout in chrono args.timeout = std::chrono::seconds(raw_timeout); } catch (po::error const &e) { std::cerr << e.what() << '\n' << desc << std::endl; exit(EXIT_FAILURE); } return args; } } // namespace ru #endif
true
029b6b012e64c5304d2defd91d0985873ace86d6
C++
vlc/ml4r
/ext/ml4r/LinearRegression/LinearRegression.cpp
UTF-8
9,011
2.515625
3
[]
no_license
#include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/triangular.hpp> #include <boost/numeric/ublas/lu.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/foreach.hpp> #include <iostream> using std::cout; using std::endl; #include "LinearRegression/LinearRegression.h" #include "utils/MatrixInversion.h" #include "utils/Utils.h" namespace ublas = boost::numeric::ublas; using std::vector; using ublas::prod; using ublas::matrix; pair<vector<double>,double> LinearRegression::getParameterEstimates() { return make_pair(m_bs,m_constant); } void LinearRegression::checkDimensions() { if (!m_ys.size()) throw std::runtime_error("[LinearRegression] Number of observations equals zero"); if (m_xs.size() != m_ys.size()) throw std::runtime_error("[LinearRegression] Number of observations in x doesn't match number of observations in y"); if (m_ws.size() && m_ws.size() != m_ys.size()) throw std::runtime_error("[LinearRegression] Number of specified weights doesn't match number of observations"); unsigned long dimensionOfX = m_xs.front().size(); BOOST_FOREACH(vector<double>& x, m_xs) if (x.size() != dimensionOfX) throw std::runtime_error("[LinearRegression] Dimensions of x variables are inconsistent between observations"); } void LinearRegression::calculateStatistics() { if (!m_paramsAreValid) throw std::runtime_error("[LinearRegression] Parameters have not been estimated"); calculateModelStatistics(); calculateParameterStatistics(); } void LinearRegression::calculateParameterStatistics2() { // form the matrix X'X ublas::matrix<double> X(m_xs.size(), m_xs.front().size()+1); ublas::matrix<double>::iterator2 matrixIterator = X.begin2(); BOOST_FOREACH(vector<double>& row, m_xs) { matrixIterator = std::copy(row.begin(), row.end(), matrixIterator); *(matrixIterator++) = 1.0; } ublas::matrix<double> X_transpose_X = ublas::prod(ublas::trans(X), X); // Invert the matrix ublas::matrix<double> X_transpose_X_inverse(X_transpose_X); InvertMatrix(X_transpose_X, X_transpose_X_inverse); // Also construct a t-stat for the constant if (!m_constantIsFixed) m_bs.push_back(m_constant); m_tStatistics.resize(m_bs.size()); for (unsigned int i=0; i<m_bs.size(); ++i) { m_tStatistics.at(i) = m_bs.at(i) / (m_s * sqrt(X_transpose_X_inverse(i,i))); } if (!m_constantIsFixed) m_bs.pop_back(); } void LinearRegression::calculateModelStatistics() { checkDimensions(); checkParametersAreEstimated(); estimateYs(); double meanY = Utils::vectorSum(m_ys) / m_n; double sumSquaresTotal = 0.0; double sumSquaresRegression = 0.0; double sumSquaresError = 0.0; double meanWeight = Utils::vectorSum(m_ws) / m_n; for (int i=0; i<m_n; ++i) { sumSquaresTotal += m_ws.at(i) / meanWeight * pow(m_ys.at(i) - meanY, 2.0); sumSquaresRegression += m_ws.at(i) / meanWeight * pow(m_fittedYs.at(i) - meanY, 2.0); sumSquaresError += m_ws.at(i) / meanWeight * pow(m_ys.at(i) - m_fittedYs.at(i), 2.0); } double meanSquaredRegression = sumSquaresRegression / (m_k); m_rSquared = 1.0 - (sumSquaresError / sumSquaresTotal); m_adjustedRSquared = 1.0 - (sumSquaresError / (m_n - m_p)) / (sumSquaresTotal / (m_n - 1)); m_fStatistic = (m_n-m_p) * sumSquaresRegression / (sumSquaresError * m_k); m_sSquared = 1.0 / (m_n-m_p) * sumSquaresError; m_s = sqrt(m_sSquared); m_h_diagonal.resize(m_n, 0.0); // auto XIterator = m_X.begin2(); // row-wise // auto AIterator = m_A.begin1(); // column-wise for (int i = 0; i < m_n; ++i) { double sumProduct = 0.0; for (int j = 0; j < m_p; ++j) sumProduct += m_X(i, j) * m_A(j, i); m_h_diagonal.at(i) = sumProduct; } m_pressStatistic = 0.0; m_presarStatistic = 0.0; m_predictedYs.resize(m_n); for (int i = 0; i < m_n; ++i) { double ei = m_fittedYs.at(i) - m_ys.at(i); double hii = m_h_diagonal.at(i); double ei_prediction = ei / (1.0 - hii); // best thing eva!!! m_predictedYs.at(i) = m_ys.at(i) + ei_prediction; m_presarStatistic += m_ws.at(i) / meanWeight * abs((float)ei_prediction); m_pressStatistic += m_ws.at(i) / meanWeight * pow(ei_prediction, 2.0); } m_rSquaredPrediction = 1.0 - m_pressStatistic / sumSquaresTotal; } void LinearRegression::estimateYs() { m_fittedYs.clear(); m_fittedYs.resize(m_ys.size(), m_constant); for (unsigned int i=0; i<m_ys.size(); ++i) { for (unsigned int j=0; j<m_bs.size(); ++j) m_fittedYs.at(i) += m_bs.at(j) * m_xs.at(i).at(j); } } void LinearRegression::checkParametersAreEstimated() { if (!m_paramsAreValid) throw std::runtime_error("[LinearRegression] Parameters have not been estimated"); } double LinearRegression::getRSquared() { return m_rSquared; } double LinearRegression::getFstatistic() { return m_fStatistic; } vector<double>& LinearRegression::getFittedYs() { return m_fittedYs; } vector<double>& LinearRegression::getTstatistics() { return m_tStatistics; } void LinearRegression::populateMembers() { m_k = m_xs.front().size(); m_p = m_k + (m_constantIsFixed ? 0 : 1); m_n = m_xs.size(); // populate m_X m_X.resize(m_n, m_p); ublas::matrix<double>::iterator2 matrixIterator = m_X.begin2(); BOOST_FOREACH(vector<double>& row, m_xs) { matrixIterator = std::copy(row.begin(), row.end(), matrixIterator); if (!m_constantIsFixed) *(matrixIterator++) = 1.0; } // populate m_Y m_Y.resize(m_n, 1); ublas::matrix<double>::iterator1 matrixIterator2 = m_Y.begin1(); BOOST_FOREACH(double& y, m_ys) { (*matrixIterator2) = y; ++matrixIterator2; } // populate m_ws with 1's if it's not already defined if (!m_ws.size()) { m_ws.resize(m_n, 1.0); } // form the matrix X' [P x N] m_Xtranspose = ublas::trans(m_X); // form the matrix X'WX [P x N] . [N x N] . [N x P] => [P x P] m_Xtranspose_W_X.resize(m_p, m_p); m_Xtranspose_W = multiplyMatrixByWeights(m_Xtranspose); m_Xtranspose_W_X = ublas::prod(m_Xtranspose_W, m_X); // Invert the matrix m_Xtranspose_W_X_inverse.resize(m_p, m_p); InvertMatrix(m_Xtranspose_W_X, m_Xtranspose_W_X_inverse); } void LinearRegression::calculateParameterStatistics() { m_tStatistics.resize(m_p); m_standardErrors.resize(m_p); ublas::matrix<double> AAt = prod(m_A, ublas::trans(m_A)); for (int i=0; i<m_p; ++i) { // made more complicated by weights!!! m_standardErrors.at(i) = m_s * sqrt(AAt(i,i)); m_tStatistics.at(i) = m_B(i,0) / m_standardErrors.at(i); } } double LinearRegression::getPressStatistic() { return m_pressStatistic; } double LinearRegression::getPresarStatistic() { return m_presarStatistic; } double LinearRegression::getRSquaredPrediction() { return m_rSquaredPrediction; } vector<double>& LinearRegression::getPredictedYs() { return m_predictedYs; } double LinearRegression::getAdjustedRSquared() { return m_adjustedRSquared; } matrix<double> LinearRegression::multiplyMatrixByWeights(matrix<double>& mat) { if (mat.size2() != m_ws.size()) throw std::runtime_error("[LinearRegression::multiplyMatrixByWeights] invalid matrix dimensions!"); matrix<double> new_matrix = mat; // copy for (unsigned int j = 0; j < new_matrix.size2(); ++j) // each column { double weight = m_ws.at(j); for (unsigned int i = 0; i < new_matrix.size1(); ++i) // each row new_matrix(i,j) *= weight; } return new_matrix; } matrix<double> LinearRegression::multiplyWeightsByMatrix(matrix<double>& mat) { if (mat.size1() != m_ws.size()) throw std::runtime_error("[LinearRegression::multiplyMatrixByWeights] invalid matrix dimensions!"); matrix<double> new_matrix = mat; // copy for (unsigned int i = 0; i < new_matrix.size2(); ++i) // each row { double weight = m_ws.at(i); for (unsigned int j = 0; j < new_matrix.size1(); ++j) // each column new_matrix(i,j) *= weight; } return new_matrix; } vector<double>& LinearRegression::getStandardErrors() { return m_standardErrors; } double LinearRegression::getSSquared() { return m_sSquared; }
true
b86a9796a535d3675ffef56a299c8b7885d2fb77
C++
zachwreed/CS-325
/week 1/merge sort/mergesort.cpp
UTF-8
1,893
3.796875
4
[]
no_license
/************************************************** ** Author: Zach Reed ** Date: 1/13/2019 ***************************************************/ #include <iostream> #include <fstream> #include <vector> using namespace std; /************************ ** Author: Sanfoundry ** Title: C++ Program to Implement Merge Sort ** Type: Source code for the functions merge() and mergesort() ** Availability: https://www.sanfoundry.com/cpp-program-implement-merge-sort *************************/ void merge(vector<int> &data, int low, int high, int mid){ int i = low; int j = mid + 1; vector<int> tempData; while (i <= mid && j <= high) { // if in order if (data[i] < data[j]) { tempData.push_back(data[i]); i++; } // else if not in order else { tempData.push_back(data[j]); j++; } } while (i <= mid) { tempData.push_back(data[i]); i++; } while (j <= high) { tempData.push_back(data[j]); j++; } for (i = low; i <= high; i++) { data[i] = tempData[i - low]; } } void mergeSort(vector<int> &data, int low, int high){ int mid; if (low < high) { mid = (low + high) / 2; mergeSort(data, low, mid); mergeSort(data, mid + 1, high); merge(data, low, high, mid); } } int main() { vector<int> data; ifstream input_file; ofstream output_file; input_file.open("data.txt"); if (input_file.is_open()) { int val; while (!input_file.eof()) { input_file >> val; data.push_back(val); } input_file.close(); mergeSort(data, 0, data.size() - 1); output_file.open("merge.txt"); for (int i = 0; i < data.size(); i++) { output_file << data[i]; output_file << " "; } output_file.close(); cout << "data.txt has been read and merge sorted into merge.txt" << endl; } else { cout << "File was not openned." << endl; } return 0; }
true
f324d39804530778aa42036cd17965ac5b7a10b9
C++
chasingegg/Online_Judge
/leetcode/404_Sum-of-Left-Leaves/SumofLeftLeaves.cpp
UTF-8
545
3.140625
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int sumOfLeftLeaves(TreeNode* root) { if (root == nullptr) return 0; int res = 0; if (root -> left != nullptr && root -> left -> left == nullptr && root -> left -> right == nullptr) res += root -> left -> val; return res + sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right); } };
true
e158c3f80462463fb858eaedbb52158bf584a9e8
C++
uJason/CSCI222_Assignment_1
/Warehouse_System/src/Employee.cpp
UTF-8
374
3.078125
3
[]
no_license
#include "Employee.h" Employee::Employee() { eName = "Admin"; ePass = "1234"; //ctor } Employee::~Employee() { //dtor } string Employee::getName() { return eName; } string Employee::getPass() { return ePass; } void Employee::setName(string name) { this->eName = name; } void Employee::setPass(string pass) { this->ePass = pass; }
true
f06a5bff207edc92ed3348f805a94f7c5d6e57fa
C++
hunghoang3011/contro
/phan 2/b2/main.cpp
UTF-8
370
2.796875
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, char** argv) { double sum=0; double tich=0; cout<<"nhap so phan tu: "; int n; cin>>n; double *p=new double[n]; for (int i=0; i<n; i++){ cin>>*(p+i); } for( int i=0; i<n; i++){ if(p[i]<1){ cout<<p[i]<<" "; } sum+=p[i]; tich*=p[i]; } cout<<"\ntong ="<<sum<<", tich= "<<tich; return 0; }
true
95655a09c1ea41fb0664c92b74ddb928d855e685
C++
qcxygo/LeetCode
/LeetCode-142.cpp
UTF-8
683
3.15625
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode *detectCycle(struct ListNode *head) { struct ListNode *p,*q; p=q=head; if(p==NULL) return NULL; while(1){ p=p->next; q=q->next; if(p==NULL||q==NULL) return NULL; q=q->next; if(p==NULL||q==NULL) return NULL; if(p==q) break; } int w=0; p=q->next; while(p!=q){ p=p->next; w++; } w+=1; p=q=head; for(int i=0;i<w;i++) p=p->next; while(p!=q){ p=p->next; q=q->next; } return p; }
true
cfa4d78d11e62a631d78e77b1b20a502c05b8468
C++
rramsden/re
/src/re/cursor.cpp
UTF-8
512
2.984375
3
[]
no_license
#include "re/cursor.h" Cursor::Cursor(int c_x, int c_y, int clamp_x, int clamp_y) { cx = c_x; cy = c_y; clampx = clamp_x; clampy = clamp_y; } void Cursor::up() { if (cy != 0) cy--; } void Cursor::down() { if (cy < clampy) cy++; } void Cursor::left() { if (cx != 0) cx--; } void Cursor::right() { if (cx != clampx - 1) cx++; } std::unique_ptr<Cursor> Cursor::move(int c_x, int c_y, int clamp_x, int clamp_y) { return std::make_unique<Cursor>(c_x, c_y, clamp_x, clamp_y); }
true
279ee3ef9605634ff305f4ee65d401261676f2d4
C++
bruceoutdoors/CG-Assignment
/OpenGL-Utilities/MyFerrisWheel.cpp
UTF-8
2,528
2.90625
3
[ "MIT" ]
permissive
/******************************************** Course : TGD2151 Computer Graphics Fundamentals / TCS2111 Computer Graphics Session: Trimester 2, 2015/16 ID and Name #1 : 1141125087 Hii Yong Lian Contacts #1 : 016-4111005 yonglian146@gmail.com ID and Name #2 : 112272848 Lee Zhen Yong Contacts #2 : 016-3188854 bruceoutdoors@gmail.com ********************************************/ // // MyFerrisWheel.cpp // OpenGL-Utilities // // Created by Yong Lian Hii on 21/02/2016. // Copyright © 2016 Yong Lian Hii. All rights reserved. // #include "MyFerrisWheel.hpp" #include <random> MyFerrisWheel::MyFerrisWheel(int rotatespeed):rotatespeed(rotatespeed) { //Setup Quadric Object pObj = gluNewQuadric(); gluQuadricNormals(pObj, GLU_SMOOTH); for(int i = 0 ; i < total_seats; i++ ) { Person* person = new Person(); person->setScale(0.4); people.push_back(person); } } MyFerrisWheel::~MyFerrisWheel() { gluDeleteQuadric(pObj); } void MyFerrisWheel::draw() { glDisable(GL_CULL_FACE); glPushMatrix(); drawBar(); glPopMatrix(); // srand(1); //initialize the random number generator // // fill up later glEnable(GL_CULL_FACE); // myspotlights.setupLights(); } void MyFerrisWheel::drawSeat(GLfloat angle_to_rotate, int current_index) { // myspotlights.draw(); glPushMatrix(); glTranslatef(5, 0, 0); glRotatef(angle_to_rotate, 1, 0, 0); gluCylinder(pObj,0.5f, 0.5f, 20.0f, 30, 5); glTranslatef(0, 0, 20); glRotatef(90, 0, 1, 0); gluCylinder(pObj,0.5f, 0.5f, 5.0f, 30, 5); glTranslatef(0, 0, 5); glRotatef(90, 0, 1, 0); glColor3f(colors[current_index % colors.size()][0] , colors[current_index % colors.size()][1], colors[current_index% colors.size()][2] ); gluCylinder(pObj,1.0f, 3.0f, 5.0f, 30, 5); // glRotatef(270, 0, 0, 1); glRotatef(270, 0, 1, 0); glTranslatef(3, 0, 0); people[current_index]->draw(); glPopMatrix(); //color list, you may use a random number to pick the color }; void MyFerrisWheel::drawBar() { glPushMatrix(); glRotatef(-90, 1, 0, 0); gluCylinder(pObj,3.0f, 3.0f, 30.0f, 30, 5); glPopMatrix(); glTranslatef(0, 30, 0); for(int i = 1 ; i < 10 ; i ++) { drawSeat( ( 360 * i/total_seats) - rotateangle, i); } // fill up later } void MyFerrisWheel::updateFrame(int elapseTime) { rotateangle += elapseTime * rotatespeed / 1000.0; if (rotateangle>=360) { rotateangle = 360 - rotateangle; } }
true
39774f53f84731519dc3077150ad5c029e79da1f
C++
R-ovo-stack/VS_CODE-DOCUMENT_C--
/SNAKE_GAME_PROFECT/SNAKE_MAIN.cpp
UTF-8
1,186
2.875
3
[]
no_license
#include"SNAKE_RUN.h" #include<windows.h> #include<time.h> int main() { int testNum = 0; //食物和蛇身重叠次数检测 char c = 'd'; //方向键初始化为d srand((unsigned)time(NULL)); //随机种子 Food food = {5, 8, 'A'}; //初始化食物 Snakepoint snake; // 定义结构体 Snakepoint *head, *rear; //定义结构体指针 initSnake(&snake); //初始化蛇身 head = rear = &snake; //初始化蛇只有蛇头 while(1){ draw_Picture(head, &food); /*蛇迟到食物后的处理*/ if(isSnakeEatFood(head,&food)){ rear = add(head); //蛇身增长一节 creatFood(&food); testNum = avoidOverlap(head, &food); setFoodLocation(&food, head, testNum, c); } /*按键处理*/ if(kbhit()) c = setCurkeyButton(c); if(c=='x') break; snakeMove(head, rear, c); if(isSnakeEatSelf(head)){ //判断游戏结束 cout << "game over ! " << endl; break; } Sleep(5*1000); //屏幕刷新时间间隔 } getch(); return 0; }
true
e910bdfa5dd2223250e99157e3cef3322a7d6372
C++
SimonBerggren/Asteroid_3.0
/Asteroid 3.0/Utilities.h
UTF-8
2,508
3.28125
3
[]
no_license
#pragma once #include "SFML/System.hpp" #include <iostream> #include <sstream> #include <stdarg.h> #include <random> #include <ctime> typedef unsigned int uint; // some useful utilities namespace utils { template<class Owner> static std::string ToString(Owner i) { std::ostringstream stream; stream << i; return stream.str(); } static double Round(double value, int precision) { return int(value * std::pow(10.0f, precision) + 0.5f) / std::pow(10.0f, precision); } static float Clamp(float value, float min, float max) { return (value < min) ? min : (value > max) ? max : value; } static float ToDegrees(float radians) { return radians * (180.0f / std::_Pi); } static float ToRadians(float degrees) { return degrees * (std::_Pi / 180); } static float Abs(float value) { return (value < 0.0f) ? -value : value; } static void Print(float value) { std::cout << value << std::endl; } static void Print(char* value) { std::cout << value << std::endl; } static void Print(char* text, float value) { std::cout << text << value << std::endl; } // Vector namespace vec { static float Distance(const sf::Vector2f& v1, const sf::Vector2f& v2) { return sqrt(pow((v2.x - v1.x), 2.0f) + pow((v2.y - v1.y), 2.0f)); } static float Length(const sf::Vector2f& v) { return sqrt((v.x * v.x) + (v.y * v.y)); } static sf::Vector2f Normalized(const sf::Vector2f& v) { float length = Length(v); return sf::Vector2f(v.x / length, v.y / length); } static sf::Vector2f Direction(const sf::Vector2f& v1, const sf::Vector2f& v2) { return sf::Vector2f(v2.x - v1.x, v2.y - v1.y); } static sf::Vector2f FromRadians(float radians) { return sf::Vector2f(std::cos(radians), std::sin(radians)); } static sf::Vector2f FromDegrees(float degree) { return FromRadians(utils::ToRadians(degree)); } static float ToDegrees(const sf::Vector2f& v) { return std::atan2(v.y, v.x) * (180.0f / std::_Pi); } static float ToRadians(const sf::Vector2f& v) { return utils::ToRadians(ToDegrees(v)); } } // Random namespace rnd { static float Float(float min, float max) { static std::mt19937 randomGenerator(time(0)); std::uniform_real_distribution<float> random(min, max); return random(randomGenerator); } static int Int(int min, int max) { static std::mt19937 randomGenerator(time(0)); std::uniform_int_distribution<int> random(min, max); return random(randomGenerator); } } }
true
50de710571d8d728a858fd8159f08b78c44784e3
C++
JJTurrubiates/Graphic-EQ-Template
/Source/GraphLayout.hpp
UTF-8
2,764
2.515625
3
[]
no_license
// // GraphLayout.hpp // grapher // // Created by Jesus Turrubiates on 2020-08-22. // #ifndef GraphLayout_hpp #define GraphLayout_hpp #include <stdio.h> #include <JuceHeader.h> #include <array> // axis class BackgroundAndAxis : public juce::Component { public: BackgroundAndAxis(){} ~BackgroundAndAxis(){} void paint (Graphics& g) override; int dBLimit = 0; private: void paintFreqLines (Graphics& g); void paintDecibelLines (Graphics& g); int getX(int x); int getY(int y); }; // labels class DecibelsLabels : public juce::Component { public: DecibelsLabels(){} ~DecibelsLabels(){} void paint (Graphics& g) override; int reducedSize = 0; int dBLimit = 0; private: double getYAtDecibel(double); }; class FrequencyLabels : public juce::Component { public: FrequencyLabels(){} ~FrequencyLabels(){} void paint (Graphics& g) override; int reducedSize = 0; private: double getXAtFrequency(double); }; // knobs class Knobs : public juce::Component { public: Knobs(); ~Knobs(){} void paint (Graphics& g) override; void prepare(const dsp::ProcessSpec &spec); void resized() override; void computeCoefficients(int freq, double Q, double gain); // this is just for visualization, the actual filters need to obtain // the sampleRate from PluginProcessor int sampleRate; int reducedSize = 0; int dBLimit = 0; private: double getXAtFrequency(double); void paintFreqResponse(Graphics& g); juce::dsp::IIR::Coefficients<float>::Ptr coeffs {nullptr}; std::array<double, 5> coefficients {0.0, 0.0, 0.0, 0.0, 0.0}; juce::dsp::IIR::Filter <float> peakFilter; std::vector<double> frequencyMap; std::vector<double> decibelMap; }; // Graph UI class GraphComponent : public juce::Component { public: GraphComponent() { addAndMakeVisible(backgroundAxis); addAndMakeVisible(decibelLabels); addAndMakeVisible(frequencyLabels); addAndMakeVisible(knobs); decibelLabels.reducedSize = reducedSize; frequencyLabels.reducedSize = reducedSize; knobs.reducedSize = reducedSize; backgroundAxis.dBLimit = dBLimit; decibelLabels.dBLimit = dBLimit; knobs.dBLimit = dBLimit; } ~GraphComponent(){} void paint (Graphics& g) override; void resized() override; int sampleRate = 0; int reducedSize = 5; int dBLimit = 25; private: double getXAtFrequency(double); BackgroundAndAxis backgroundAxis; DecibelsLabels decibelLabels; FrequencyLabels frequencyLabels; Knobs knobs; }; #endif /* GraphLayout_hpp */
true
91e2a5a923b48531439c69c8ce483549a3e7e0f7
C++
sfitzpatrickchapman/SFitzpatrick_298-01_Assignment1
/ProblemCereal.cpp
UTF-8
472
3.546875
4
[]
no_license
// Scott Fitzpatrick, 2328196 #include <iostream> using namespace std; int main() { float cerealWeightOunces; float cerealWeightTons; /* Prompt and user input */ cout << endl << "Enter the weight of breakfast cereal in ounces: "; cin >> cerealWeightOunces; /* Calculates ounces to tons conversion and prints */ cerealWeightTons = cerealWeightOunces / 35273.92; cout << "The weight of the cereal in tons is: " << cerealWeightTons << endl << endl; }
true
669d3bcb27915f182145e6c130af611478db9306
C++
TJUSsr/leetcodesolution
/151-reverse-words-in-a-string/reverse-words-in-a-string.cpp
UTF-8
1,390
3.359375
3
[ "MIT" ]
permissive
// Given an input string, reverse the string word by word. // // Example:   // // // Input: "the sky is blue", // Output: "blue is sky the". // // // Note: // // // A word is defined as a sequence of non-space characters. // Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces. // You need to reduce multiple spaces between two words to a single space in the reversed string. // // // Follow up: For C programmers, try to solve it in-place in O(1) space. // static const auto _=[](){ std::ios::sync_with_stdio(false); cin.tie(nullptr); return nullptr; }(); class Solution { public: void reverseWords(string &s) { if(s.empty()) return; int i=0,j=0,l=0; int len=s.size(); int wordcount=0; while(true){ while(i<len&&s[i]==' ') ++i; if(i==len) break; if(wordcount) s[j++]=' '; l=j; while(i<len&&s[i]!=' '){ s[j]=s[i]; ++j; ++i; } reverse(s,l,j-1); ++wordcount; } s.resize(j); reverse(s,0,j-1); return; } private: void reverse(string& s, int i, int j){ while(i<j){ auto c=s[i]; s[i++]=s[j]; s[j--]=c; } } };
true
1b38c577a7d84d1896cf91f7520999cae5cf525f
C++
kangli-bionic/algorithm
/lintcode/498.cpp
UTF-8
4,852
3.59375
4
[ "MIT" ]
permissive
/* 498. Parking Lot https://www.lintcode.com/problem/parking-lot/description?_from=ladder&&fromId=98 */ #include <utility> #include <vector> #include <map> enum class VehicleSize { Motorcycle, Compact, Large }; class Vehicle { // Write your code here protected: VehicleSize size_; int number_of_spot_needed_; public: std::pair<VehicleSize, int> GetSizeAndNumber() { return std::pair<VehicleSize, int>{size_, number_of_spot_needed_}; } }; class Bus : public Vehicle { // Write your code here public: Bus() { size_ = VehicleSize::Large; number_of_spot_needed_ = 5; } }; class Car : public Vehicle { // Write your code here public: Car() { size_ = VehicleSize::Compact; number_of_spot_needed_ = 1; } }; class Motorcycle : public Vehicle { // Write your code here public: Motorcycle() { size_ = VehicleSize::Motorcycle; number_of_spot_needed_ = 1; } }; // spot class, indicate spot type, spot_id_ and spottype class Spot { private: bool available_; int spot_id_; public: Spot(int spot_id); bool IsAvailable(); void TakeSpot(); void LeaveSpot(); }; class Row { private: std::vector<Spot *> spots_; public: Row(int k) { for (int i = 0; i < k; ++i) { spots_.push_back(new Spot(k)); // intiailize it with spot_id } } std::vector<Spot *> GetSpots() { return spots_; } }; class Level { // Write your code here private: std::vector<Row *> rows_; public: Level(int m, int k) { for (int i = 0; i < m; ++i) { rows_.push_back(new Row(k)); // initalize each row } } std::vector<Row *> GetRows() { return rows_; } }; // spot type is initalized interally Spot::Spot(int spot_id) { spot_id_ = spot_id; LeaveSpot(); } bool Spot::IsAvailable() { return available_; } void Spot::TakeSpot() { available_ = false; } void Spot::LeaveSpot() { available_ = true; } // generate a ticket given spots occupied and vehicle class Ticket { private: vector<Spot *> spots_; Vehicle *v_; public: Ticket(Vehicle *v, std::vector<Spot *> spots) { v_ = v; spots_ = spots; } vector<Spot *> GetSpots() { return spots_; } }; class ParkingLot { private: std::vector<Level *> levels_; std::map<Vehicle *, Ticket *> vehicle_ticket_; std::vector<Spot *> FindSpotForVehicle(Vehicle *v); int spots_per_row_; public: // @param n number of leves // @param num_rows each level has num_rows rows of spots // @param spots_per_row each row has spots_per_row spots ParkingLot(int n, int num_rows, int spots_per_row) { // Write your code here // create parking lot spots_per_row_ = spots_per_row; for (int i = 0; i < n; ++i) { levels_.push_back(new Level(num_rows, spots_per_row)); } } // Park the vehicle in a spot (or multiple spots) // Return false if failed bool parkVehicle(Vehicle *vehicle) { // Write your code here std::vector<Spot *> spots = FindSpotForVehicle(vehicle); if (spots.empty()) { return false; } Ticket *t = new Ticket(vehicle, spots); vehicle_ticket_[vehicle] = t; return true; } // unPark the vehicle void unParkVehicle(Vehicle *vehicle) { // Write your code here auto loc = vehicle_ticket_.find(vehicle); if (loc == vehicle_ticket_.end()) { return; } std::vector<Spot *> spots = vehicle_ticket_[vehicle]->GetSpots(); for (auto spot : spots) { spot->LeaveSpot(); } vehicle_ticket_.erase(vehicle); } }; std::vector<Spot *> ParkingLot::FindSpotForVehicle(Vehicle *v) { std::pair<VehicleSize, int> requirement = v->GetSizeAndNumber(); std::vector<Spot *> occupied_spots; int start = 0; switch (requirement.first) { case VehicleSize::Compact: start = spots_per_row_ / 4; break; case VehicleSize::Motorcycle: start = 0; break; case VehicleSize::Large: start = spots_per_row_ / 4 * 3; break; } for (auto level : levels_) { for (auto row : level->GetRows()) { // std::cout << "start: " << start << "how many: " << requirement.second // << std::endl; for (int i = start; i < spots_per_row_ - requirement.second + 1; ++i) { bool can_park = true; for (int j = i; j < i + requirement.second; ++j) { // std::cout << "level: " << &level << "row: " << &row << "j: " << j // << "Avalability: " << row->GetSpots()[j]->IsAvailable() << // std::endl; if (!row->GetSpots()[j]->IsAvailable()) { can_park = false; break; } } if (can_park) { for (int j = i; j < i + requirement.second; ++j) { row->GetSpots()[j]->TakeSpot(); occupied_spots.push_back(row->GetSpots()[j]); } return occupied_spots; } } } } return occupied_spots; }
true
90fedaf68856af9ec5829d75f0e82cf394168d81
C++
codechef34/Software-Engineering
/Course Work/CG/rubiksss/RubiksCubeSolution/RubiksCube/3DMath.cpp
UTF-8
2,453
3.015625
3
[]
no_license
#include "stdafx.h" #include "3DMath.h" Point3f operator+(const Point3f &lhs, const Vector3f &rhs) { float newX, newY, newZ; newX = lhs.X() + rhs.X(); newY = lhs.Y() + rhs.Y(); newZ = lhs.Z() + rhs.Z(); return Point3f(newX, newY, newZ); } Vector3f operator-(const Point3f &lhs, const Point3f &rhs) { float newX = lhs.X() - rhs.X(); float newY = lhs.Y() - rhs.Y(); float newZ = lhs.Z() - rhs.Z(); return Vector3f(newX, newY, newZ); } Vector3f operator+(const Vector3f &lhs, const Vector3f &rhs) { float newX, newY, newZ; newX = lhs.X() + rhs.X(); newY = lhs.Y() + rhs.Y(); newZ = lhs.Z() + rhs.Z(); return Vector3f(newX, newY, newZ); } Vector3f operator-(const Vector3f &lhs, const Vector3f &rhs) { float newX, newY, newZ; newX = lhs.X() - rhs.X(); newY = lhs.Y() - rhs.Y(); newZ = lhs.Z() - rhs.Z(); return Vector3f(newX, newY, newZ); } Vector3f operator*(float lhs, const Vector3f &rhs) { float newX, newY, newZ; newX = lhs * rhs.X(); newY = lhs * rhs.Y(); newZ = lhs * rhs.Z(); return Vector3f(newX, newY, newZ); } Vector3f operator*(const Vector3f &lhs, float rhs) { float newX, newY, newZ; newX = rhs * lhs.X(); newY = rhs * lhs.Y(); newZ = rhs * lhs.Z(); return Vector3f(newX, newY, newZ); } Matrix3f operator*(const Matrix3f &lhs, const Matrix3f &rhs) { float newData[9]; newData[0] = (lhs.At(0, 0) * rhs.At(0, 0)) + (lhs.At(0, 1) * rhs.At(1, 0)) + (lhs.At(0, 2) * rhs.At(2, 0)); newData[1] = (lhs.At(0, 0) * rhs.At(0, 1)) + (lhs.At(0, 1) * rhs.At(1, 1)) + (lhs.At(0, 2) * rhs.At(2, 1)); newData[2] = (lhs.At(0, 0) * rhs.At(0, 2)) + (lhs.At(0, 1) * rhs.At(1, 2)) + (lhs.At(0, 2) * rhs.At(2, 2)); newData[3] = (lhs.At(1, 0) * rhs.At(0, 0)) + (lhs.At(1, 1) * rhs.At(1, 0)) + (lhs.At(1, 2) * rhs.At(2, 0)); newData[4] = (lhs.At(1, 0) * rhs.At(0, 1)) + (lhs.At(1, 1) * rhs.At(1, 1)) + (lhs.At(1, 2) * rhs.At(2, 1)); newData[5] = (lhs.At(1, 0) * rhs.At(0, 2)) + (lhs.At(1, 1) * rhs.At(1, 2)) + (lhs.At(1, 2) * rhs.At(2, 2)); newData[6] = (lhs.At(2, 0) * rhs.At(0, 0)) + (lhs.At(2, 1) * rhs.At(1, 0)) + (lhs.At(2, 2) * rhs.At(2, 0)); newData[7] = (lhs.At(2, 0) * rhs.At(0, 1)) + (lhs.At(2, 1) * rhs.At(1, 1)) + (lhs.At(2, 2) * rhs.At(2, 1)); newData[8] = (lhs.At(2, 0) * rhs.At(0, 2)) + (lhs.At(2, 1) * rhs.At(1, 2)) + (lhs.At(2, 2) * rhs.At(2, 2)); Matrix3f newMatrix; for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) newMatrix.SetAt(i, j, newData[3*i + j]); return newMatrix; }
true
b425edbb08a6c209f81e50be30cd85cbced488f0
C++
luiscabus/learnNodeMCU
/simple_led_blink/simple_led_blink.ino
UTF-8
426
2.765625
3
[]
no_license
#define ledPin LED_BUILTIN // #define ledPin 16 void setup() { // Debug console Serial.begin(115200); pinMode(ledPin,OUTPUT); delay(1000); Serial.println(""); Serial.println("Boot iniciado."); delay(1000); Serial.println("Vou iniciar o Loop para piscar os leds."); delay(1000); Serial.println("Lá vai!"); } void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000); }
true
36f30580e3c9273f0b7f250de11a9d4bb01c053d
C++
miaomao1989/program_test
/c++/mm-temp/11/11-15.cpp
UTF-8
495
3.203125
3
[]
no_license
#include <iostream> #include <list> #include <vector> #include <algorithm> using namespace std; int main() { int ia[] = {1, 2, 3, 4, 100, 5, 100}; list< int > ilst(ia, ia+7); vector< int > ivec; vector< int >::iterator end_unique = unique_copy(ilst.begin(), ilst.end(), back_inserter(ivec)); // 输出vector容器 cout << "vector: " << endl; for (vector< int >::iterator iter = ivec.begin(); iter != end_unique; ++iter) cout << *iter << " "; cout << endl; return 0; }
true
1bcd5230726ff009adf378b00e7ed5708a8e47d9
C++
githaoyang/countSteelLayer
/countMaxInModel.cpp
GB18030
5,440
2.859375
3
[]
no_license
#include "countOnModel.h" void getModelHight(int photoHight, int upEdge, int downEdge, int& modelHight, vector<int> list) { int flag = false; //жΪְб vector<int> candidateList(photoHight, 0); for (int i = upEdge; i < downEdge; i++) { int max = list[i]; int maxPosition = i; flag = false; for (int j = i + 1; (j < i + modelHight) && (j < downEdge); j++) { if (list[j] > max) { max = list[j]; maxPosition = j; flag = true; } } if (flag && (list[maxPosition] >= list[maxPosition + 1])) { candidateList[maxPosition] = list[maxPosition]; } } //ҵһְλ int theFirstSteel = upEdge; int theLastSteel = downEdge; for (int i = upEdge + 1; i < downEdge; i++) { if (candidateList[i] != 0) { theFirstSteel = i; break; } } //ְƽ vector<int> peaksWidth; int widthForSum = 0; int lastPeakPosition = theFirstSteel; for (int i = theFirstSteel + 1; i < downEdge; i++) { int peakPosition = i; if (candidateList[i] != 0) { peaksWidth.emplace_back(peakPosition - lastPeakPosition); widthForSum += peakPosition - lastPeakPosition; lastPeakPosition = peakPosition; } } map<int, int> findMaxShownWidth; for (auto i : peaksWidth) { if (findMaxShownWidth.count(i)) { findMaxShownWidth[i] += 1; } else { findMaxShownWidth.insert({ i, 1 }); } } double theWidth = 0; int theShowTimes = 0; for (auto i = findMaxShownWidth.begin(); i != findMaxShownWidth.end(); i++) { int times = i->second; if (theShowTimes < times) { theShowTimes = times; theWidth = i->first; } } modelHight = theWidth * 1.2; } int countMaxInModel(Mat src, int upEdge, int downEdge, int modelHight, vector<int> list, int positionShift) { int flag = false; int count = 0; //жΪְб vector<int> candidateList(src.rows, 0); for (int i = upEdge; i < downEdge; i++) { int max = list[i]; int maxPosition = i; flag = false; for (int j = i + 1; (j < i + modelHight) && (j < downEdge); j++) { if (list[j] > max) { max = list[j]; maxPosition = j; flag = true; } } if (flag && (list[maxPosition] >= list[maxPosition + 1])) { candidateList[maxPosition] = list[maxPosition]; } } //ҵһְλ int theFirstSteel = upEdge; int theLastSteel = downEdge; for (int i = upEdge + 1;i < downEdge; i++) { if (candidateList[i] != 0) { theFirstSteel = i; break; } } for (int i = downEdge - 1; i > upEdge; i--) { if (candidateList[i] != 0) { theLastSteel = i; break; } } //ְƽ vector<int> peaksWidth; int peakValuesSum = 0; int widthForSum = 0; int lastPeakPosition = theFirstSteel; for (int i = theFirstSteel + 1; i < downEdge; i++) { int peakPosition = i; if (candidateList[i] != 0) { peakValuesSum += candidateList[i]; count++; peaksWidth.emplace_back(peakPosition - lastPeakPosition); widthForSum += peakPosition - lastPeakPosition; lastPeakPosition = peakPosition; } } int averagePeakValue = peakValuesSum / count; map<int, int> findMaxShownWidth; for (auto i : peaksWidth) { if (findMaxShownWidth.count(i)) { findMaxShownWidth[i] += 1; } else { findMaxShownWidth.insert({ i, 1 }); } } double theWidth = 0; int theShowTimes = 0; for (auto i = findMaxShownWidth.begin(); i != findMaxShownWidth.end(); i++) { int times = i->second; if (theShowTimes < times) { theShowTimes = times; theWidth = i->first; } } int averageWidth = widthForSum / count; //ƽʹƽ if (abs(theWidth- averageWidth) >= averageWidth * 0.5) { theWidth = averageWidth; } //һְⲻ if ((theFirstSteel - upEdge) > theWidth) { candidateList[(theFirstSteel + upEdge) / 2] = 1; } //һְ if ((downEdge - theLastSteel) < theWidth / 2) { candidateList[theLastSteel] = 0; } // int lastPosition = theFirstSteel; for (int i = theFirstSteel + theWidth; i < downEdge; i++) { if (candidateList[i] != 0) { int thePosition = i; if ((thePosition - lastPosition -theWidth > 0)&&((thePosition - lastPosition - theWidth) > theWidth * 0.5)) { int middle = (thePosition + lastPosition) / 2; candidateList[middle] = 1; i = middle - 1; thePosition = i; continue; } lastPosition = thePosition; } } //Сɾ lastPosition = theFirstSteel; for (int i = theFirstSteel + 1; i < downEdge; i++) { if (candidateList[i] != 0) { if ((i - lastPosition) < theWidth * 0.5) { candidateList[i] = 0; continue; } lastPosition = i; } } for (int i = theFirstSteel; i < downEdge; i++) { if (candidateList[i] != 0) { if (abs(candidateList[i] - averagePeakValue) > averagePeakValue) { candidateList[i] = 0; } } } count = 0; for (int i = upEdge; i < downEdge; i++) { if (candidateList[i] != 0) { count++; line(src, Point(positionShift, i), Point(positionShift + 5, i), Scalar(255)); } } return count; }
true
be742b4a8325b7411ebef37f89b209fd9e799b63
C++
icgw/practice
/LeetCode/C++/0121._Best_Time_to_Buy_and_Sell_Stock/solution.h
UTF-8
547
3.078125
3
[ "MIT" ]
permissive
/* * solution.h * Copyright (C) 2021 Guowei Chen <icgw@outlook.com> * * Distributed under terms of the Apache license. */ #ifndef _SOLUTION_H_ #define _SOLUTION_H_ #include <vector> using std::vector; #include <algorithm> using std::max; using std::min; class Solution { public: int maxProfit(vector<int>& prices) { int buy_price = prices[0]; int max_profit = 0; for (int p : prices) { max_profit = max(max_profit, p - buy_price); buy_price = min(buy_price, p); } return max_profit; } }; #endif /* !_SOLUTION_H_ */
true
370ef9890bc69452dc9d5c4a6cf5bf079c7efc54
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/93/1218.c
UTF-8
530
3.0625
3
[]
no_license
int main() { int x, front_number_exist; front_number_exist = false; cin >> x; if (x % 3 == 0) { front_number_exist = 1; cout << 3; } if (x % 5 == 0) { if (front_number_exist) { cout << " 5"; } else { front_number_exist = 1; cout << "5"; } } if (x % 7 == 0) { if (front_number_exist) { cout << " 7"; } else { front_number_exist = 1; cout << "7"; } } else { if (front_number_exist == 0) { cout << "n"; } } return 0; }
true
98f43085d3aaf7b8748d66158699d381b7d322ae
C++
anducnguyen/image_processing
/geo_projectile.cpp
UTF-8
2,113
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "myImageIO.h" int linear_interpolation(myImageData *in, double xx, double yy) { int W = in->getWidth(); int H = in->getHeight(); int x, y; int v1, v2, v3, v4; x = int(xx); y = int(yy); v1 = v2 = v3 = v4 = 0; if(x>=0 && x<W-1 && y>=0 && y<H-1) { // Input check v1 = in->get(x , y); v2 = in->get(x+1, y); v3 = in->get(x , y+1); v4 = in->get(x+1, y+1); } int value; double dx, dy; dx = xx - x; dy = yy - y; value = (unsigned char)( v1 * (1-dx)*(1-dy) + v2 * dx*(1-dy) + v3 * (1-dx)*dy + v4 * dx*dy + 0.5); return value; } int transform(myImageData *in, myImageData *out, double mat[3][3]) { int W = out->getWidth(); int H = out->getHeight(); for(int x=0; x<W; x++) { for(int y=0; y<H; y++) { double ss; ss = x*mat[2][0] + y*mat[2][1] + mat[2][2]; double xx, yy; xx = (x*mat[0][0] + y*mat[0][1] + mat[0][2])/ss; yy = (x*mat[1][0] + y*mat[1][1] + mat[1][2])/ss; int value; value = linear_interpolation(in, xx, yy); out->set(x, y, value); } } return 0; } int main(int argc, char **argv){ // read image data to img1 myImageData * img1 = new myImageData(); img1->read(argv[1]); myImageData * img2 = new myImageData(); img2->init(img1->getWidth(), img1->getHeight(), 1); myImageData * img3 = new myImageData(); // for cards image img3->init(400, 600, 1); int W = img1->getWidth(); int H = img1->getHeight(); // フィルタ係数の設定 double matrix[3][3] = { { 1.0, 0.0, 0.0}, { 0.0, 1.0, 0.0}, { 0.0, 0.0, 1.0} // *** for card "7" // { 2.21e-1, 9.12e-2, 2.20e2}, // {-6.98e-2, 1.14e-1, 1.79e2}, // { 8.99e-5, -1.46e-4, 7.70e-1} // *** for card "6" //{ 2.20e-1, 1.11e-1, 5.50e1}, //{-8.22e-2, 1.10e-1, 1.47e2}, //{ 9.10e-5, -1.37e-4, 8.20e-1} }; transform(img1, img2, matrix); img2->save("out"); delete img1; delete img2; delete img3; return 0; // normal termination }
true
225aebd74796027bef74fd0d878c5a02ef41072a
C++
timmyew/SpaceGame
/TextureManager.cpp
UTF-8
1,526
3.171875
3
[ "MIT" ]
permissive
#include "TextureManager.h" Texture::Texture(SDL_Texture* texture){ tex = texture; } Texture::~Texture(){ SDL_DestroyTexture(tex); tex = NULL; } SDL_Texture* Texture::getTexture(){ return tex; } TextureManager::TextureManager(){ textureVec = new std::vector<Texture*>(); spritesVec = new std::vector<Sprites*>(); loadedSurface = NULL; } TextureManager::~TextureManager(){ for (int i = 0; i < textureVec->size(); i++){ delete textureVec->at(i); } textureVec->clear(); delete textureVec; for (int i = 0; i < spritesVec->size(); i++){ delete spritesVec->at(i); } spritesVec->clear(); delete spritesVec; } Texture* TextureManager::LoadImage(const char* path, SDL_Renderer* renderer){ loadedSurface = NULL; loadedSurface = IMG_Load(path); //If Image loaded if (loadedSurface != NULL) { //Create the Texture //Add The Texture to the map textureVec->push_back(new Texture(SDL_CreateTextureFromSurface(renderer, loadedSurface))); std::cout << "Texture: " << path << " is loaded!..." << std::endl; } else std::cout << "Unable to create texture from %s! SDL Error: %s\n" << path << SDL_GetError() << std::endl; return textureVec->at(textureVec->size() - 1); } Sprites* TextureManager::LoadSprite(const char* path, SDL_Renderer* renderer, int x, int y){ Texture* tex = LoadImage(path, renderer); Sprites* sprites = new Sprites(); sprites->SetSpriteSheet(tex->getTexture(), x, y); spritesVec->push_back(sprites); sprites = NULL; return spritesVec->at(spritesVec->size()-1); }
true
8a2ce5de832790102b51ac638e3ca16c18b1fba1
C++
kaulszhang/base
/src/tools/util_test/smart_ptr/RefenceFromThis.cpp
UTF-8
771
2.625
3
[]
no_license
// RefenceFromThis.cpp #include "tools/util_test/Common.h" using namespace framework::configure; #include <util/smart_ptr/RefenceFromThis.h> using namespace util::smart_ptr; #include <iostream> struct Base : RefenceFromThis<Base> { virtual ~Base() { std::cout << "~Base" << std::endl; }; }; struct Derived : Base { void func() { ref(this); } virtual ~Derived() { std::cout << "~Derived" << std::endl; }; }; void test_refence_from_this(Config & conf) { boost::intrusive_ptr<Derived> p1(new Derived); Base::pointer p2(p1); p1->func(); p1.reset(); p2.reset(); } static TestRegister test("refence_from_this", test_refence_from_this);
true
0d8e80ab1a4ff0ccf74daad00eaf2142af85126f
C++
antmicro/prjxray
/tools/bits2rbt/ecc.cc
UTF-8
2,622
2.796875
3
[ "LicenseRef-scancode-dco-1.1", "ISC" ]
permissive
#include "ecc.h" #include <cassert> #include <iostream> const std::unordered_map<std::string, size_t> ECC::ecc_word_per_architecture = { {"Series7", 50}, {"UltraScale", 60}, {"UltraScalePlus", 45}}; uint32_t ECC::GetSeries7WordEcc(uint32_t idx, uint32_t data, uint32_t ecc) const { uint32_t val = idx * 32; // bit offset if (idx > 0x25) // avoid 0x800 val += 0x1360; else if (idx > 0x6) // avoid 0x400 val += 0x1340; else // avoid lower val += 0x1320; if (idx == 0x32) // mask ECC data &= 0xFFFFE000; for (int i = 0; i < 32; i++) { if (data & 1) ecc ^= val + i; data >>= 1; } if (idx == 0x64) { // last index uint32_t v = ecc & 0xFFF; v ^= v >> 8; v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; ecc ^= (v & 1) << 12; // parity } return ecc; } uint64_t ECC::GetUSEccFrameOffset(int word, int bit) const { int nib = bit / 4; int nibbit = bit % 4; // ECC offset is expanded to 1 bit per nibble, // and then shifted based on the bit index in nibble // e.g. word 3, bit 9 // offset: 0b10100110010 - concatenate (3 + (255 - last_frame_index(e.g. // 92 for US+)) [frame offset] and 9/4 [nibble offset] becomes: // 0x10100110010 shifted by bit in nibble (9%4): 0x20200220020 uint32_t offset = (word + (255 - (frame_words_ - 1))) << 3 | nib; uint64_t exp_offset = 0; // Odd parity offset ^= (1 << 11); for (int i = 0; i < 11; i++) if (offset & (1 << i)) offset ^= (1 << 11); // Expansion for (int i = 0; i < 12; i++) if (offset & (1 << i)) exp_offset |= (1ULL << (4 * i)); return exp_offset << nibbit; }; uint64_t ECC::GetUSWordEcc(uint32_t idx, uint32_t data, uint64_t ecc) const { if (idx == ecc_word_) { data = 0x0; } if (idx == ecc_word_ + 1) { data &= 0xffff0000; } for (int i = 0; i < 32; i++) { if (data & 1) { ecc ^= GetUSEccFrameOffset(idx, i); } data >>= 1; } return ecc; } uint64_t ECC::CalculateECC(const std::vector<uint32_t>& data) const { uint64_t ecc = 0; for (size_t w = 0; w < data.size(); ++w) { const uint32_t& word = data.at(w); if (architecture_ == "Series7") { ecc = GetSeries7WordEcc(w, word, ecc); } else { ecc = GetUSWordEcc(w, word, ecc); } } return ecc; } void ECC::UpdateFrameECC(std::vector<uint32_t>& data) const { assert(data.size() >= ecc_word_); uint64_t ecc(CalculateECC(data)); if (architecture_ == "Series7") { data[ecc_word_] &= 0xffffe000; data[ecc_word_] |= ecc & 0x1fff; } else { data[ecc_word_] = ecc; data[ecc_word_ + 1] &= 0xffff0000; data[ecc_word_ + 1] |= (ecc >> 32) & 0xffff; } }
true
10dee63bd7e1bf26b04db755dd2a85603ada7094
C++
G-Reg26/TetrisCPP
/TetrisCPP/tetromino.h
UTF-8
1,053
2.734375
3
[]
no_license
#pragma once #include <list> #include <iterator> #include "SFML\Graphics.hpp" class Tetromino { public: Tetromino(); Tetromino(std::list<sf::RectangleShape> * blocks); void setTetromino(std::list<sf::RectangleShape> * blocks); void update(); void rotate(); int ** getTetromino() { return tetromino; } private: sf::Vector2i piecePosition; const int tetrominos[7][4][4] = { // I { { 0, 0, 2, 0 }, { 0, 0, 2, 0 }, { 0, 0, 2, 0 }, { 0, 0, 2, 0 } }, // O { { 0, 0, 0, 0 }, { 0, 2, 2, 0 }, { 0, 2, 2, 0 }, { 0, 0, 0, 0 } }, // Z { { 0, 0, 0, 0 }, { 0, 2, 2, 0 }, { 0, 0, 2, 2 }, { 0, 0, 0, 0 } }, // S { { 0, 0, 0, 0 }, { 0, 0, 2, 2 }, { 0, 2, 2, 0 }, { 0, 0, 0, 0 } }, // T { { 0, 0, 0, 0 }, { 2, 2, 2, 0 }, { 0, 2, 0, 0 }, { 0, 0, 0, 0 } }, // L { { 0, 2, 0, 0 }, { 0, 2, 0, 0 }, { 0, 2, 2, 0 }, { 0, 0, 0, 0 } }, // J { { 0, 0, 2, 0 }, { 0, 0, 2, 0 }, { 0, 2, 2, 0 }, { 0, 0, 0, 0 } }, }; int * tetromino[4]; };
true
4288153e48006fb8abdad8207b1e56843c63be81
C++
Hychiro/Trabalho-Grafos-2021-1
/main.cpp
UTF-8
7,392
3.171875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <math.h> #include <utility> #include <tuple> #include <iomanip> #include <stdlib.h> #include <chrono> #include "Graph.h" #include "Node.h" #include "Edge.h" #include "Graph.cpp" #include "Node.cpp" #include "Edge.cpp" using namespace std; Graph *leitura(ifstream &input_file, int directed, int weightedEdge, int weightedNode) { //Variáveis para auxiliar na criação dos nós no Grafo int idNodeSource; int idNodeTarget; int order; //Pegando a ordem do grafo input_file >> order; //Criando objeto grafo Graph *graph = new Graph(order, directed, weightedEdge, weightedNode); //Leitura de arquivo if (!graph->getWeightedEdge() && !graph->getWeightedNode()) { while (input_file >> idNodeSource >> idNodeTarget) { graph->insertEdge(idNodeSource, idNodeTarget, 1); } } else if (graph->getWeightedEdge() && !graph->getWeightedNode()) { float edgeWeight; while (input_file >> idNodeSource >> idNodeTarget >> edgeWeight) { graph->insertEdge(idNodeSource, idNodeTarget, edgeWeight); } } else if (graph->getWeightedNode() && !graph->getWeightedEdge()) { float nodeSourceWeight, nodeTargetWeight; while (input_file >> idNodeSource >> nodeSourceWeight >> idNodeTarget >> nodeTargetWeight) { graph->insertEdge(idNodeSource, idNodeTarget, 1); graph->getNode(idNodeSource)->setWeight(nodeSourceWeight); graph->getNode(idNodeTarget)->setWeight(nodeTargetWeight); } } else if (graph->getWeightedNode() && graph->getWeightedEdge()) { float nodeSourceWeight, nodeTargetWeight, edgeWeight; while (input_file >> idNodeSource >> nodeSourceWeight >> idNodeTarget >> nodeTargetWeight) { graph->insertEdge(idNodeSource, idNodeTarget, edgeWeight); graph->getNode(idNodeSource)->setWeight(nodeSourceWeight); graph->getNode(idNodeTarget)->setWeight(nodeTargetWeight); } } return graph; } Graph *leituraInstancia(ifstream &input_file, int directed, int weightedEdge, int weightedNode) { //Variáveis para auxiliar na criação dos nós no Grafo int idNodeSource; int idNodeTarget; int order; int numEdges; //Pegando a ordem do grafo input_file >> order; //Criando objeto grafo Graph *graph = new Graph(order, directed, weightedEdge, weightedNode); //Leitura de arquivo while (input_file >> idNodeSource >> idNodeTarget) { graph->insertEdge(idNodeSource, idNodeTarget, 1); } return graph; } int menu() { int selecao; cout << "MENU" << endl; cout << "----" << endl; cout << "[1] fechoTransitivoIndireto" << endl; cout << "[2] Fecho Transitivo Direto" << endl; cout << "[3] Caminho Mínimo entre dois vértices - Floyd" << endl; cout << "[4] Árvore Geradora Mínima de Kruskal" << endl; cout << "[5] Árvore Geradora Mínima de Prim" << endl; cout << "[6] Imprimir caminhamento em Profundidade" << endl; cout << "[7] Imprimir ordenacao topológica" << endl; cout << "[8] Caminho Mínimo entre dois vértices - Dijkstra" << endl; cout << "[9] Printando o Grafo " << endl; cout << "[10] Algoritmo Guloso Randomizado Reativo" << endl; cout << "[11] Algoritmo Guloso Randomizado" << endl; cout << "[0] Sair" << endl; cin >> selecao; return selecao; } void selecionar(int selecao, Graph *graph, ofstream &output_file) { switch (selecao) { //fechoTransitivoIndireto; case 1: { int x; cout << "Digite o id o noh a ser pesquisado: "; cin >> x; graph->fechoTransitivoIndireto(output_file,x); break; } //fechoTransitivoDireto; case 2: { int x; cout << "Digite o id o noh a ser pesquisado: "; cin >> x; graph->fechoTransitivoDireto(output_file, x); break; } //Caminho mínimo entre dois vértices usando Floyd; case 3: { cout<<"Digite o vertice de origem:"<< endl; int origem; cin>>origem; cout<<"Digite o vertice de destino:"<<endl; int destino; cin>> destino; graph->floydMarshall(output_file,origem,destino); break; } //AGM - Kruscal; case 4: { Graph *novoSubGrafo = graph->agmKuskal(output_file); novoSubGrafo->printGraph(output_file); break; } //AGM Prim; case 5: { Graph *grafoX = graph->agmPrim(output_file); grafoX->printGraph(output_file); break; } //Busca em Profundidade; case 6: { int x; cout << "Digite o id o noh a por onde começara o caminhamento: "; cin >> x; Graph* novoGrafo= graph->caminhamentoDeProfundidade(x); novoGrafo->printGraph(output_file); break; } //Ordenação Topologica; case 7: { graph->topologicalSorting(output_file); break; } //Caminho Mínimo entre dois vértices - Dijkstra case 8: { int x, y; cout << "Digite o id Source: "; cin >> x; cout << "Digite o id Target: "; cin >> y; graph->dijkstra(output_file, x, y); break; } //Printa grafo case 9: { graph->printGraph(output_file); break; } default: { cout << " Error!!! invalid option!!" << endl; } } } int mainMenu(ofstream &output_file, Graph *graph) { int selecao = 1; while (selecao != 0) { system("cls"); selecao = menu(); if (output_file.is_open()) selecionar(selecao, graph, output_file); else cout << "Unable to open the output_file" << endl; output_file << endl; } return 0; } int main(int argc, char const *argv[]) { //Verificação se todos os parâmetros do programa foram entrados if (argc != 6) { cout << "ERROR: Expecting: ./<program_name> <input_file> <output_file> <directed> <weighted_edge> <weighted_node> " << endl; return 1; } string program_name(argv[0]); string input_file_name(argv[1]); string instance; if (input_file_name.find("v") <= input_file_name.size()) { string instance = input_file_name.substr(input_file_name.find("v")); cout << "Running " << program_name << " with instance " << instance << " ... " << endl; } //Abrindo arquivo de entrada ifstream input_file; ofstream output_file; input_file.open(argv[1], ios::in); output_file.open(argv[2], ios::out | ios::trunc); Graph *graph; if (input_file.is_open()) { graph = leitura(input_file, atoi(argv[3]), atoi(argv[4]), atoi(argv[5])); } else cout << "Unable to open " << argv[1]; mainMenu(output_file, graph); //Fechando arquivo de entrada input_file.close(); //Fechando arquivo de saída output_file.close(); return 0; }
true
a884ae4ebdbd6f6a68b0f0a9561c1947d6937934
C++
uofuseismo/rtseis
/src/modules/detrend.cpp
UTF-8
8,958
2.75
3
[ "MIT" ]
permissive
#include <cstdio> #include <cstdlib> #include <cstring> #include <cstdint> #include <ipps.h> #include "private/throw.hpp" #include "rtseis/postProcessing/singleChannel/detrend.hpp" using namespace RTSeis::PostProcessing::SingleChannel; class DetrendParameters::DetrendParmsImpl { public: void clear() { precision_ = RTSeis::Precision::DOUBLE; mode_ = RTSeis::ProcessingMode::POST_PROCESSING; linit_ = true; } RTSeis::Precision precision_ = RTSeis::Precision::DOUBLE; RTSeis::ProcessingMode mode_ = RTSeis::ProcessingMode::POST_PROCESSING; bool linit_ = true; // This module is always ready to roll }; class Detrend::DetrendImpl { public: DetrendImpl() = default; /// Copy constructor DetrendImpl(const DetrendImpl &detrend) { *this = detrend; } /// Deep copy operator DetrendImpl& operator=(const DetrendImpl &detrend) { if (&detrend == this){return *this;} parms_ = detrend.parms_; b0_ = detrend.b0_; b1_ = detrend.b1_; linit_ = detrend.linit_; return *this; } /// Destructor ~DetrendImpl() = default; /// Resets the module void clear() { parms_.clear(); b0_ = 0; b1_ = 0; linit_ = true; // This module is always ready to roll } /// Sets the parameters for the class int setParameters(const DetrendParameters &parameters) { clear(); parms_ = parameters; return 0; } /// Removes the trend from data int apply(const int nx, const double x[], double y[]) { b0_ = 0; b1_ = 0; if (nx < 2){return 0;} computeLinearRegressionCoeffs(nx, x); #pragma omp simd for (int i=0; i<nx; i++) { y[i] = x[i] - (b0_ + b1_*static_cast<double> (i)); } return 0; } /// Removes the trend from data int apply(const int nx, const float x[], float y[]) { b0_ = 0; b1_ = 0; if (nx < 2){return 0;} computeLinearRegressionCoeffs(nx, x); auto b0 = static_cast<float> (b0_); auto b1 = static_cast<float> (b1_); #pragma omp simd for (int i=0; i<nx; i++) { y[i] = x[i] - (b0 + b1*static_cast<float> (i)); } return 0; } /*! * @brief Computes the coefficients for a linear regression * \f$ \hat{y}_i = b_0 + b_1 x_i \f$ * using IPP functions where * \f$ b_1 * = \frac{\mathrm{Cov}(x,y)}{\mathrm{Var}(x,y)} \f$ * and * \f$ b_0 = \bar{y} - b_0 \bar{x} \f$. * The code is modified from: * https://software.intel.com/en-us/forums/intel-integrated-performance-primitives/topic/299457 * where I have assumed the data is generated by linearly * spaced samples. * @param[in] length Length of array y. * @param[in] pSrcY Points at evaluated at indices. */ int computeLinearRegressionCoeffs(const int length, const double pSrcY[]) { double cov_xy; double mean_x; double mean_y; double var_x; // Mean of x - analytic formula for evenly spaced samples starting // at indx 0. This is computed by simplifying Gauss's formula. auto len64 = static_cast<uint64_t> (length); mean_x = 0.5*static_cast<double> (len64 - 1); // Note, the numerator is the sum of consecutive squared numbers. // In addition we simplify. var_x = static_cast<double> ( ((len64 - 1))*(2*(len64 - 1) + 1) )/6. - mean_x*mean_x; ippsMean_64f(pSrcY, length, &mean_y); cov_xy = 0; #pragma omp simd reduction(+:cov_xy) for (int i=0; i<length; i++) { cov_xy = cov_xy + static_cast<double> (i)*pSrcY[i]; } // This is computed by expanding (x_i - bar(x))*(y_i - bar(y)), // using the definition of the mean, and simplifying cov_xy = (cov_xy/static_cast<double> (length)) - mean_x*mean_y; b1_ = cov_xy/var_x; b0_ = mean_y - b1_*mean_x; return 0; } /// Computes the linear regression coefficients int computeLinearRegressionCoeffs(const int length, const float pSrcY[]) { double cov_xy; double mean_x; double mean_y; double var_x; float mean_y32; // Mean of x - analytic formula for evenly spaced samples starting // at indx 0. This is computed by simplifying Gauss's formula. auto len64 = static_cast<uint64_t> (length); mean_x = 0.5*static_cast<double> (len64 - 1); // Note, the numerator is the sum of consecutive squared numbers. // In addition we simplify. var_x = static_cast<double> ( ((len64 - 1))*(2*(len64 - 1) + 1) )/6. - mean_x*mean_x; ippsMean_32f(pSrcY, length, &mean_y32, ippAlgHintAccurate); mean_y = static_cast<double> (mean_y32); cov_xy = 0; #pragma omp simd reduction(+:cov_xy) for (int i=0; i<length; i++) { cov_xy = cov_xy + static_cast<double> (i)*static_cast<double> (pSrcY[i]); } // This is computed by expanding (x_i - bar(x))*(y_i - bar(y)), // using the definition of the mean, and simplifying cov_xy = (cov_xy/static_cast<double> (length)) - mean_x*mean_y; b1_ = cov_xy/var_x; b0_ = mean_y - b1_*mean_x; return 0; } /// Sets the intercept void setIntercept(const double b0) { b0_ = b0; } /// Sets the slope void setSlope(const double b1) { b1_ = b1; } //private: /// Detrend parameters DetrendParameters parms_; /// The y-intercept double b0_ = 0; /// The slope double b1_ = 0; /// Flag indicating this is initialized bool linit_ = true; }; //============================================================================// DetrendParameters::DetrendParameters(const RTSeis::Precision precision) : pImpl(std::make_unique<DetrendParmsImpl>()) { pImpl->precision_ = precision; } DetrendParameters::DetrendParameters(const DetrendParameters &parameters) { *this = parameters; } DetrendParameters& DetrendParameters::operator=(const DetrendParameters &parameters) { if (&parameters == this){return *this;} //if (pImpl){pImpl->clear();} //pImpl = std::make_unique<DetrendParms>(*parameters.pImpl); pImpl = std::unique_ptr<DetrendParmsImpl> (new DetrendParmsImpl(*parameters.pImpl)); return *this; } DetrendParameters::~DetrendParameters() = default; void DetrendParameters::clear() { pImpl->clear(); } RTSeis::Precision DetrendParameters::getPrecision() const { return pImpl->precision_; } RTSeis::ProcessingMode DetrendParameters::getProcessingMode() const { return pImpl->mode_; } bool DetrendParameters::isInitialized() const { return pImpl->linit_; } //============================================================================// Detrend::Detrend() : pDetrend_(std::make_unique<DetrendImpl>()) { clear(); } Detrend::Detrend(const Detrend &detrend) { *this = detrend; } Detrend::Detrend(const DetrendParameters &parameters) : pDetrend_(std::make_unique<DetrendImpl>()) { setParameters(parameters); } Detrend& Detrend::operator=(const Detrend &detrend) { if (&detrend == this){return *this;} if (pDetrend_){pDetrend_->clear();} //pDetrend_ = std::make_unique<DetrendImpl> (*detrend.pDetrend_); pDetrend_ = std::make_unique<DetrendImpl> (*detrend.pDetrend_); return *this; } Detrend::~Detrend() { clear(); } void Detrend::clear() { pDetrend_->clear(); } void Detrend::setParameters(const DetrendParameters &parameters) { pDetrend_->clear(); if (!parameters.isInitialized()) { RTSEIS_THROW_IA("%s", "Detrend parameters are malformed"); } pDetrend_->setParameters(parameters); } void Detrend::apply(const int nx, const double x[], double y[]) { pDetrend_->setIntercept(0); pDetrend_->setSlope(0); if (nx <= 0){return;} // Nothing to do if (nx < 2 || x == nullptr || y == nullptr) { if (nx < 2){RTSEIS_THROW_IA("%s", "At least 2 points required");} if (x == nullptr){RTSEIS_THROW_IA("%s", "x is null");} RTSEIS_THROW_IA("%s", "y is null"); } pDetrend_->apply(nx, x, y); } void Detrend::apply(const int nx, const float x[], float y[]) { pDetrend_->setIntercept(0); pDetrend_->setSlope(0); if (nx <= 0){return;} // Nothing to do if (nx < 2 || x == nullptr || y == nullptr) { if (nx < 2){RTSEIS_THROW_IA("%s", "At least 2 points required");} if (x == nullptr){RTSEIS_THROW_IA("%s", "x is null");} RTSEIS_THROW_IA("%s", "y is null"); } pDetrend_->apply(nx, x, y); }
true
41538b6703372dcd968577a8c9d0aa1918b77ad1
C++
Awesomebirds/ProblemSolving
/cpp/스도쿠보드.cpp
UTF-8
2,041
3.96875
4
[]
no_license
#include <iostream> #include <cstdio> using namespace std; const int MAX_ROW = 9; const int MAX_COL = 9; class SudokuBoard { public: //칸의 번호로 행의 번호를 계산하는 메소드 int getRowByIndex(int index) { // 칸의 번호에 대해 마디를 가지고 증가하므로 몫으로 계산할 수 있다. return (index - 1) / 9 + 1; } //칸의 번호로 열의 번호를 계산하는 메소드 int getColByIndex(int index) { //칸의 번호에 대해 규칙적으로 순환하므로 나머지로 계산할 수 있다. return (index - 1) % 9 + 1; } //칸의 번호로 그룹 번호를 계산하는 메소드 int getGroupByIndex(int index) { int r = getRowByIndex(index); int c = getColByIndex(index); return getGroupByPosition(r, c); } //칸의 위치 (행, 열)로 그룹 번호를 계산하는 메소드 int getGroupByPosition(int row, int column){ int groupRow = ((row - 1) / 3) * 3 + 1; //몫을 구해서 3을 곱한 값에 1을 더해줌(1, 4, 7) int groupColumn = (column - 1) / 3; //3으로 나눈 나머지를 구함(0, 1, 2); return groupRow + groupColumn; } //칸의 위치 (행, 열)로 칸의 번호를 계산하는 메소드 int getIndexByPosition(int row, int column){ //행과 열의 번호를 구하는 방법을 거꾸로 적용하면 구할 수 있음 return (row - 1) * 9 + (column - 1) % 9 + 1; } }; void process(int caseIndex){ int index; cin >> index; SudokuBoard board = SudokuBoard(); //칸의 번호로 행, 열, 그룹 번호를 계산한다 int row = board.getRowByIndex(index); int col = board.getColByIndex(index); int group = board.getGroupByIndex(index); cout << "Case #" << caseIndex << ":" << endl; cout << row << col << group << endl; } int main() { int caseSize; cin >> caseSize; //개수 입력받음 for (int caseIndex = 1; caseIndex <= caseSize; caseIndex++) { //개수만큼 반복 process(caseIndex); } }
true
3d802760cd31f3a59e6b1373b118492f288f24ba
C++
tgckpg/libeburc
/eburc/Search/Match.cpp
UTF-8
7,434
2.75
3
[ "MIT", "BSD-3-Clause" ]
permissive
#include "pch.h" #include "eburc/Search/Match.h" using namespace libeburc; int Match::Word( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { result = 0; break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::PreWord( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = 0; break; } if ( *word_p == '\0' ) { result = 0; break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::ExactWordJIS( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { /* ignore spaces in the tail of the pattern */ while ( i < length && *pattern_p == '\0' ) { pattern_p++; i++; } result = ( i - length ); break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::ExactPreWordJIS( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = 0; break; } if ( *word_p == '\0' ) { /* ignore spaces in the tail of the pattern */ while ( i < length && *pattern_p == '\0' ) { pattern_p++; i++; } result = ( i - length ); break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::ExactWordLatin( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { /* ignore spaces in the tail of the pattern */ while ( i < length && ( *pattern_p == ' ' || *pattern_p == '\0' ) ) { pattern_p++; i++; } result = ( i - length ); break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::ExactPreWordLatin( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; int result; for ( ;;) { if ( length <= i ) { result = 0; break; } if ( *word_p == '\0' ) { /* ignore spaces in the tail of the pattern */ while ( i < length && ( *pattern_p == ' ' || *pattern_p == '\0' ) ) { pattern_p++; i++; } result = ( i - length ); break; } if ( *word_p != *pattern_p ) { result = *word_p - *pattern_p; break; } word_p++; pattern_p++; i++; } return result; } int Match::WordKanaGroup( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; unsigned char wc0, wc1, pc0, pc1; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { result = 0; break; } if ( length <= i + 1 || *( word_p + 1 ) == '\0' ) { result = *word_p - *pattern_p; break; } wc0 = *word_p; wc1 = *( word_p + 1 ); pc0 = *pattern_p; pc1 = *( pattern_p + 1 ); if ( ( wc0 == 0x24 || wc0 == 0x25 ) && ( pc0 == 0x24 || pc0 == 0x25 ) ) { if ( wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } else { if ( wc0 != pc0 || wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } word_p += 2; pattern_p += 2; i += 2; } return result; } int Match::WordKanaSingle( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; unsigned char wc0, wc1, pc0, pc1; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { result = 0; break; } if ( length <= i + 1 || *( word_p + 1 ) == '\0' ) { result = *word_p - *pattern_p; break; } wc0 = *word_p; wc1 = *( word_p + 1 ); pc0 = *pattern_p; pc1 = *( pattern_p + 1 ); if ( ( wc0 == 0x24 || wc0 == 0x25 ) && ( pc0 == 0x24 || pc0 == 0x25 ) ) { if ( wc1 != pc1 ) { result = wc1 - pc1; break; } } else { if ( wc0 != pc0 || wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } word_p += 2; pattern_p += 2; i += 2; } return result; } int Match::ExactWordKanaGroup( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; unsigned char wc0, wc1, pc0, pc1; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { result = -*pattern_p; break; } if ( length <= i + 1 || *( word_p + 1 ) == '\0' ) { result = *word_p - *pattern_p; break; } wc0 = *word_p; wc1 = *( word_p + 1 ); pc0 = *pattern_p; pc1 = *( pattern_p + 1 ); if ( ( wc0 == 0x24 || wc0 == 0x25 ) && ( pc0 == 0x24 || pc0 == 0x25 ) ) { if ( wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } else { if ( wc0 != pc0 || wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } word_p += 2; pattern_p += 2; i += 2; } return result; } int Match::ExactWordKanaSingle( const char *word, const char *pattern, size_t length ) { int i = 0; unsigned char *word_p = ( unsigned char * ) word; unsigned char *pattern_p = ( unsigned char * ) pattern; unsigned char wc0, wc1, pc0, pc1; int result; for ( ;;) { if ( length <= i ) { result = *word_p; break; } if ( *word_p == '\0' ) { result = -*pattern_p; break; } if ( length <= i + 1 || *( word_p + 1 ) == '\0' ) { result = *word_p - *pattern_p; break; } wc0 = *word_p; wc1 = *( word_p + 1 ); pc0 = *pattern_p; pc1 = *( pattern_p + 1 ); if ( ( wc0 == 0x24 || wc0 == 0x25 ) && ( pc0 == 0x24 || pc0 == 0x25 ) ) { if ( wc1 != pc1 ) { result = wc1 - pc1; break; } } else { if ( wc0 != pc0 || wc1 != pc1 ) { result = ( ( wc0 << 8 ) + wc1 ) - ( ( pc0 << 8 ) + pc1 ); break; } } word_p += 2; pattern_p += 2; i += 2; } return result; }
true
59d8770a813b51b5bbdccd2d2df13a9c3546f575
C++
DanIsraelMalta/Useful-Functions-and-Classes
/LazyStringSplit.h
UTF-8
5,757
3.75
4
[]
no_license
/** * Lazy string splitting and iteration. * * example usage: * * std::string sentence{"Expressive C++ rocks"}, * delimiter{" "}; * std::size_t i{}; * for (auto& word : split(sentence, delimiter)) { * std::cout << "word #" << std::to_string(i) << " = " <<word << "\n"; * ++i; * } * * Dan Israel Malts **/ #include<assert.h> #include<iterator> #include<string> #include<string_view> #include<vector> /** * \brief allow lazy splinting and iteration over a the components of given string/string_view * * @param {STRING, in} splitted/iterated object underlying type * @param {DELIMITER, in} set of characters (or continues STRING elements) which are used to split the string/string_view */ template<typename STRING, typename DELIMITER> class SplitView { // aliases using character = typename STRING::value_type; // properties private: const STRING& m_source; DELIMITER m_delimiter; // methods public: /** * (owning) Iterator over the split-ed component */ class iterator { // aliases using difference_type = int; using value_type = std::basic_string_view<character>; using pointer_type = value_type*; using reference = value_type&; using iterator_category = std::input_iterator_tag; // properties private: const STRING* m_source; typename STRING::size_type m_position; value_type m_curent; DELIMITER m_delimiter; // methods public: constexpr iterator() noexcept : m_source(nullptr), m_position(STRING::npos), m_delimiter(DELIMITER()) {} explicit iterator(const STRING& src, DELIMITER delimiter) : m_source(&src), m_position(0), m_delimiter(delimiter) { ++*this; } reference operator*() noexcept { assert(m_source != nullptr); return m_curent; } pointer_type operator->() noexcept { assert(m_source != nullptr); return &m_curent; } iterator& operator++() { assert(m_source != nullptr); if (m_position == STRING::npos) { m_source = nullptr; return *this; } auto last_pos = m_position; m_position = m_source->find(m_delimiter, m_position); if (m_position != STRING::npos) { m_curent = std::basic_string_view<character>(m_source->data() + last_pos, m_position - last_pos); if constexpr (sizeof(DELIMITER) == sizeof(character)) { ++m_position; } else { m_position += m_delimiter.size(); } return *this; } m_curent = std::basic_string_view<character>(m_source->data() + last_pos, m_source->size() - last_pos); return *this; } iterator operator++(int) { iterator temp(*this); ++*this; return temp; } bool operator==(const iterator& rhs) const noexcept { return (m_source == rhs.m_source) && (m_position == rhs.m_position); } bool operator!=(const iterator& rhs) const noexcept { return !operator==(rhs); } }; /** * Constructor. * * @param src the source input to be split * @param delimiter delimiter used to split \a src; its type should be * the same as that of \a src, or its character type */ constexpr explicit SplitView(const STRING& src, DELIMITER delimiter) noexcept : m_source(src), m_delimiter(delimiter) {} iterator begin() const { return iterator(m_source, m_delimiter); } constexpr iterator end() const noexcept { return iterator(); } /** Converts the view to a string vector. */ std::vector<std::basic_string<character>> to_vector() const { std::vector<std::basic_string<character>> result; for (const auto& sv : *this) result.emplace_back(sv); return result; } /** Converts the view to a string_view vector. **/ std::vector<std::basic_string_view<character>> to_vector_sv() const { std::vector<std::basic_string_view<character>> result; for (const auto& sv : *this) result.push_back(sv); return result; } }; /** * Splits a string (or string_view) into lazy views. The source input shall * remain unchanged when the generated SplitView is used in anyway. * * @param src the source input to be split * @param delimiter delimiter used to split \a src; its type should be * the same as that of \a src, or its character type */ template<typename STRING, typename DELIMITER> constexpr SplitView<STRING, DELIMITER> split(const STRING& src, DELIMITER delimiter) noexcept { return SplitView<STRING, DELIMITER>(src, delimiter); }
true
03a068d6ce3f26a0578456f22a2b748e74ada71f
C++
hyozkim/drone-project
/projects/RASPBERRY_PI/drone-master/remote_drone/remote_drone/sensors/filters.h
UTF-8
2,124
2.515625
3
[]
no_license
#ifndef FILTERS_H #define FILTERS_H //START SIMPLE KALMAN FILTER /* simeple kalman 1 reference site : http://www.magesblog.com/2014/12/measuring-temperature-with-my-arduino.html simeple kalman 2 reference site : http://interactive-matter.eu/blog/2009/12/18/filtering-sensor-data-with-a-kalman-filter/ */ #define SIMPLE_KALMAN_1 //#define SIMPLE_KALMAN_2 class simpleKfilter { private: double q; //process noise covariance , varP double r; //measurement noise covariance, varM double x; //value double p; //estimation error covariance double k; //kalman gain public: //simpleKfilter(); simpleKfilter(float k = 1, float x = 5, float p = 5, float q = 0.11, float r = 0.8); float step(float data); }; // ! START KALMAN FILTER // START MOVING AVERAGE FILTER class MAF { private : float average; unsigned short index; unsigned short buffer_size; double *buffer; public: MAF(double init_vaule = 5 ,unsigned short buffer_size=50); ~MAF(); double step(double value); double nonsave_step(double value); void save_value(double value); void save_value(double value, double average); double get_variance(); void set_buffer_size(unsigned short buffer_size); unsigned short get_buffer_size(); }; // ! MOVING AVERAGE FILTER // START LOW PASS FILTER /* reference site: http://pinkwink.kr/437 */ class LPF { private: float tau,sampling_time; double pre_val; public: LPF(float tau,float sampling_time); void set_smapling_time(float sampling_time); void set_tau(float tau); float get_tau(); float get_sampling_time(); public: float step(float raw_value); float step(float raw_value, float sampling_t); }; // ! HIGH PASS FILTER // START LOW PASS FILTER /* reference site: http://pinkwink.kr/437 */ class HPF { private: float tau, sampling_time; double pre_val; double pre_raw_val; public: HPF(float tau, float sampling_time); void set_smapling_time(float sampling_time); void set_tau(float tau); float get_tau(); float get_sampling_time(); public: float step(float raw_value); float step(float raw_value, float sampling_t); }; // ! HIGH PASS FILTER #endif // !FILTERS_H
true
b68a7b5513e99163b6b5fd6468cc8ef8243625b2
C++
organicmaps/organicmaps
/base/observer_list.hpp
UTF-8
1,705
3.265625
3
[ "Apache-2.0" ]
permissive
#pragma once #include "base/logging.hpp" #include <algorithm> #include <mutex> #include <utility> #include <vector> namespace base { class DummyLockable { public: void lock() {} void unlock() {} }; template <typename Observer, typename Mutex> class ObserverList; /// This alias represents a thread-safe observers list. It allows to /// add/remove observers as well as trigger them all. template <typename Observer> using ObserverListSafe = ObserverList<Observer, std::mutex>; template <typename Observer> using ObserverListUnsafe = ObserverList<Observer, DummyLockable>; template <typename Observer, typename Mutex> class ObserverList { public: bool Add(Observer & observer) { std::lock_guard<Mutex> lock(m_observersLock); auto const it = std::find(m_observers.begin(), m_observers.end(), &observer); if (it != m_observers.end()) { LOG(LWARNING, ("Can't add the same observer twice:", &observer)); return false; } m_observers.push_back(&observer); return true; } bool Remove(Observer const & observer) { std::lock_guard<Mutex> lock(m_observersLock); auto const it = std::find(m_observers.begin(), m_observers.end(), &observer); if (it == m_observers.end()) { LOG(LWARNING, ("Can't remove non-registered observer:", &observer)); return false; } m_observers.erase(it); return true; } template <typename F, typename... Args> void ForEach(F fn, Args const &... args) { std::lock_guard<Mutex> lock(m_observersLock); for (Observer * observer : m_observers) (observer->*fn)(args...); } private: Mutex m_observersLock; std::vector<Observer *> m_observers; }; } // namespace base
true