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
019273938aae6fb4a223aa50ba9b37e674041038
C++
weiiiyan/workspace
/300_Course_Students/course.cpp
UTF-8
1,367
3.609375
4
[]
no_license
#include "course.h" #include <iostream> struct student_list{ string name; double grade; student_list* next; }; Course::Course(const char* pName):num_students(0),head(NULL){ strncpy(name,pName,sizeof(name)); name[sizeof(name) - 1] = '\0'; } Course::~Course(){ while(head != NULL){ current = head; head = head->next; delete current; } } bool Course::Add_Student(char* pStudent,double grade){ if(num_students == 30){ cout << name << " already has 30 student and can't add any more" << endl; return 1; } num_students ++; student_list* ptr = new student_list; ptr->name = pStudent; ptr->grade = grade; ptr->next = head; head = ptr; return 0; } void Course::Set_Credit(int Credit){ credit = Credit; } void Course::Get_Average(){ current = head; double sum = 0; while(current != NULL){ sum += current->grade; current = current->next; } cout << "This course is average grade:" << sum/num_students << endl; } void Course::Get_Student_Grade(const char* pName){ current = head; char name[20]; strncpy(name,pName,sizeof(name)); name[sizeof(name) - 1] = '\0'; while(current != NULL){ if(current->name == (string)pName){ cout << current->name << ":" << current->grade << endl; return ; } current = current->next; } cout << "This course not is the student" << endl; } string Course::Get_CourseName(){ return (string)name; }
true
72f03c7f1dbad75275d1e5c2da6ffea37bdee962
C++
carlos-shimabukuro/progra1-carlos_shimabukuro-hoja2c-
/Ejercicio 1.cpp
ISO-8859-1
630
3.046875
3
[]
no_license
// ConsoleApplication1.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <conio.h> using namespace std; /* Test Test1 c = 36*/ int main() { //Entrada int c; //Restricciones /* c > 0 y entero */ // Variables int n5; int n2; int n1; //Logica cout << "Ingrese c: " << endl; cin >> c; n5 = (c / 5); n2 = ((c % 5) / 2); n1 = ((c % 5) % 2); //Salida cout << "Nmero de monedas de 5:" << n5 << endl; cout << "Nmero de monedas de 2:" << n2 << endl; cout << "Nmero de monedas de 1:" << n1 << endl; _getch(); }
true
5f2ec2206cb432e07cdd6e41b4302372194bb0d2
C++
whztt07/ShaderEditor
/src/Commons.hpp
UTF-8
992
2.8125
3
[]
no_license
#ifndef COMMONS_HPP #define COMMONS_HPP #include <QString> namespace Qiwi{ /* enum PortTypeEnum{ READER = 0x1 , WRITER = 0x2 , INPUT = 0x4 , OUTPUT = 0x8 }; */ enum PortTypeEnum{ READER = 0x1 , WRITER = 0x2 , INPUT = 0x4 , OUTPUT = 0x8 , READER_INPUT = READER | INPUT , READER_OUTPUT = READER | OUTPUT , WRITER_INPUT = WRITER | INPUT , WRITER_OUTPUT = WRITER | OUTPUT , INPUT_OUTPUT_MASK = INPUT | OUTPUT , READER_WRITER_MASK = READER | WRITER }; inline PortTypeEnum operator&(PortTypeEnum lhs, PortTypeEnum rhs){ return static_cast<PortTypeEnum>(static_cast<int>(lhs) & static_cast<int>(rhs) ); } inline PortTypeEnum operator|(PortTypeEnum lhs, PortTypeEnum rhs){ return static_cast<PortTypeEnum>(static_cast<int>(lhs) | static_cast<int>(rhs) ); } QString printNodeType( PortTypeEnum type); } #endif // COMMONS_HPP
true
d22afeb7eada130dae659a20702631c6c4f61ad7
C++
parduman/lovebabbar450
/dsaC++/array/alternatingPositiveAndNegative.cpp
UTF-8
857
3.09375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <bits/stdc++.h> using namespace std; bool fun(int a, int b){ return b < a; } int main() { vector <int> v; int size; cout <<"vector size" <<endl; cin >>size; cout <<"enter elements now" <<endl; for(int i=0;i<size;i++){ int j; cin >> j; v.push_back(j); } sort(v.begin(),v.end(),fun); vector <int>::iterator start = v.begin(); vector <int>::iterator end = v.begin(); for(;end<v.end(); end++){ if(*end < 0){ break; } } while(start < v.end() && end < v.end()){ int temp = *start; *start = *end; *end = temp; start = start + 2; end = end + 1; } for(vector <int>::iterator it = v.begin();it<v.end(); it++){ cout << *it << " "; } return 0; }
true
5bd6246e5a089be4adb6a2081266d0a4621794ae
C++
tobieder/SimplePandemicSimulation
/SimplePandemicSimulation/Utils/Random.cpp
UTF-8
1,019
3.3125
3
[]
no_license
#include "Random.h" #include <algorithm> Random::Random() { srand(time(NULL)); } QVector2D Random::RandomQVector2DBetween(QVector2D _min, QVector2D _max) { float random = ((float)rand()) / (float)RAND_MAX; float diffX = _max.x() - _min.x(); float rX = random * diffX; random = ((float)rand()) / (float)RAND_MAX; float diffY = _max.y() - _min.y(); float rY = random * diffY; return QVector2D(_min.x() + rX, _min.y() + rY); } QVector2D Random::AngleToQVector2D(float _angle) { const float angleInRadians = _angle * (M_PI / 180); return (QVector2D(cos(_angle), sin(_angle))).normalized(); } float Random::RandomBetween(float _min, float _max) { float random = ((float)rand()) / (float)RAND_MAX; float diff = _max - _min; float r = random * diff; return _min + r; } std::vector<int> Random::RandomArrayBetween(int _min, int _max) { std::vector<int> vec; for (int i = 0; i < (_max - _min); i++) { vec.push_back(_min + i); } std::random_shuffle(std::begin(vec), std::end(vec)); return vec; }
true
0c23866ad44437af6cd641ab30402d518a682993
C++
LinasBeres/closest-point
/src/test.h
UTF-8
3,568
2.734375
3
[]
no_license
#ifndef TEST_H #define TEST_H #include "ClosestPoint.h" #include "Context.h" #include <random> #include <chrono> void runTests(Context context) { const int n_tests = 500; ClosestPoint finder(context.getVertices()); finder.constructKdTree(); // Average time for building kdtree float durationBuild = 0; for(int i = 0; i < n_tests; i++) { ClosestPoint kdTest(context.getVertices()); auto t1 = std::chrono::high_resolution_clock::now(); kdTest.constructKdTree(); auto t2 = std::chrono::high_resolution_clock::now(); durationBuild += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); } std::cerr << "Average time for building KdTree: " << durationBuild / n_tests << " microseconds.\n"; // Bounding box const Eigen::Vector3d m = context.getVertices()->colwise().minCoeff(); const Eigen::Vector3d M = context.getVertices()->colwise().maxCoeff(); std::default_random_engine generator; std::uniform_real_distribution<float> distributionX(m(0), M(0)); std::uniform_real_distribution<float> distributionY(m(1), M(1)); std::uniform_real_distribution<float> distributionZ(m(2), M(2)); const float dist = ClosestPoint::euclideanDistance(m, M); std::uniform_real_distribution<float> distributionDist(0, dist); // Find point using all three methods and make sure that they all output the same point and index if found int passed = 0; float durationBrute = 0, durationThreaded = 0, durationKdTree = 0; for(int i = 0; i < n_tests; i++) { const Eigen::Vector3d query_point(distributionX(generator), distributionY(generator), distributionZ(generator)); const float maxDist = distributionDist(generator); int indexBrute = 0, indexThreaded = 0, indexKdTree = 0; Eigen::Vector3d outBrute(0,0,0); Eigen::Vector3d outThreaded(0,0,0); Eigen::Vector3d outKdTree(0,0,0); auto t1 = std::chrono::high_resolution_clock::now(); bool foundBrute = finder.closestPointBruteForce(query_point, maxDist, outBrute, indexBrute); auto t2 = std::chrono::high_resolution_clock::now(); durationBrute += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); t1 = std::chrono::high_resolution_clock::now(); bool foundThreaded = finder.closestPointThreaded(query_point, maxDist, outThreaded, indexThreaded); t2 = std::chrono::high_resolution_clock::now(); durationThreaded += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); t1 = std::chrono::high_resolution_clock::now(); bool foundKdTree = finder.closestPointKdTree(query_point, maxDist, outKdTree, indexKdTree); t2 = std::chrono::high_resolution_clock::now(); durationKdTree += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(); if(foundBrute == foundThreaded && foundBrute == foundKdTree && foundThreaded == foundKdTree) { if(foundBrute) { if(indexBrute == indexThreaded && indexBrute == indexKdTree && indexThreaded == indexKdTree) { if(outBrute == outThreaded && outBrute == outKdTree && outThreaded == outKdTree) { passed++; } } } else { passed++; } } } std::cerr << "\n"; std::cerr << "Search timings:\n"; std::cerr << "Average time for brute force search: " << durationBrute / n_tests << " microseconds.\n"; std::cerr << "Average time for threaded search: " << durationThreaded / n_tests << " microseconds.\n"; std::cerr << "Average time for KdTree search: " << durationKdTree / n_tests << " microseconds.\n"; std::cerr << "\n"; std::cerr << "Passed: " << passed << " out of " << n_tests << " point queries.\n"; }; #endif
true
3acf8384c22ebe1b21f4a5c082acd4589dc5d0fc
C++
LiQingMuBai/darks-jvm
/jvm/vm/executor/jmethod.cpp
UTF-8
1,062
2.53125
3
[ "Apache-2.0" ]
permissive
#include "stdafx.h" #include "jmethod.h" #include "descriptor.h" Method::Method() { methodName = NULL; methodDesc = NULL; code_attr = NULL; exception_attr = NULL; jni_method_name = NULL; } Method::~Method() { if (code_attr) { delete[] code_attr; code_attr = NULL; } if (exception_attr) { delete[] exception_attr; exception_attr = NULL; } if (jni_method_name) { delete[] jni_method_name; jni_method_name = NULL; } methodName = NULL; methodDesc = NULL; } LPSTR Method::GetJniName(int bytesize) { if (!jni_method_name) { int mlen = strlen(methodName->GetName()); int clen = strlen(clazz->thisClass->GetName()); jni_method_name = new char[mlen + clen + 20]; sprintf(jni_method_name, "_Java_%s_%s@%d", clazz->thisClass->GetName(), methodName->GetName(), bytesize); int len = strlen(jni_method_name); for (int i = 0; i < len; i++) { if (jni_method_name[i] == '/' || jni_method_name[i] == '.') { jni_method_name[i] = '_'; } } } return jni_method_name; }
true
d19a432c2ebda5cfba9db15ac19d81cbecc092c2
C++
navidkpr/Competitive-Programming
/CodeForces/546/C[ Soldier and Cards ].cpp
UTF-8
969
3.484375
3
[]
no_license
#include <iostream> #include <queue> using namespace std; queue <int> card1, card2; int Fact(int n) { if (n == 1) return 1; else return Fact(n - 1) * n; } int main() { int n, k1, k2; cin >> n; cin >> k1; for (int i = 0; i < k1; i++) { int num; cin >> num; card1.push(num); } cin >> k2; for (int i = 0; i < k2; i++) { int num; cin >> num; card2.push(num); } int factn = Fact(n); bool h = 0; int ans = -1; for (int i = 0; i < factn * (n + 1) && !h; i++) { if ( card1.size() == 0 || card2.size() == 0 ) { h = 1; ans = i; break; } if ( card1.front() > card2.front() ) { card1.push(card2.front()); card1.push(card1.front()); card1.pop(); card2.pop(); } else { card2.push(card1.front()); card2.push(card2.front()); card1.pop(); card2.pop(); } } cout << ans; if ( !card1.size() ) cout << &#39; &#39; << 2; if ( !card2.size() ) cout << &#39; &#39; << 1; cout << endl; return 0; }
true
0e88d944274d38acbd09b4f98e7a71d2b6171654
C++
ordinary-developer/education
/cpp/std-17/i_cukic-func_progr_in_cpp/ch_03-function_objects/05-under_the_hodd_of_lambdas-2.cpp
UTF-8
554
3.15625
3
[ "MIT" ]
permissive
#include <algorithm> #include <vector> #include <cassert> #include <cctype> namespace test { void run() { int count{0}; std::vector<std::string> words{ "An", "ancient", "pond" }; std::for_each(std::cbegin(words), std::cend(words), [count](std::string const& word) mutable { if (std::isupper(static_cast<unsigned char>(word[0]))) ++count; }); assert(1 == count); } } // test #include <iostream> int main() { std::cout << "test => [ok]" << std::endl; test::run(); return 0; }
true
8a17c89dafcb2b33bb3c6f2154e1d7335be93251
C++
doraneko94/AtCoder
/ABC/ABC091/test.cpp
UTF-8
214
2.765625
3
[]
no_license
#include <vector> #include <iostream> using namespace std; int main() { vector<int> a(10); for (int i=0; i<10; ++i) a[i] = i; a.erase(a.begin()+2); cout << a[2] << a.size() << endl; return 0; }
true
8912974f18d9806aa3cf3bbff3756ec527abd063
C++
BrendanHenryGithub/simple-tcp-based-protocol-design
/inc/server.hpp
UTF-8
2,187
2.75
3
[]
no_license
#pragma once #include "protocol.hpp" #include <boost/asio.hpp> #include <unordered_map> #include <set> #include <queue> #include <memory> class Channel; class Participant; // ---------------- Class Server ------------------------------ class Server { private: boost::asio::ip::tcp::acceptor acceptor; public: // 所有channel的集合 static std::unordered_map<std::string, std::shared_ptr<Channel>> channels; // 所有成员集合 static std::set<std::shared_ptr<Participant>> members; public: Server(boost::asio::io_context &ioCtx, const boost::asio::ip::tcp::endpoint &endpoint); private: void accept(); }; // ---------------- Class Channel ------------------------------ class Channel : public std::enable_shared_from_this<Channel> { private: unsigned int MAX_CONNECTION_NUM; std::string name; std::set<std::shared_ptr<Participant>> connections; public: explicit Channel(std::string channelName); Channel(std::string channelName, int num); ~Channel(); bool ifFull(); unsigned int count(); std::string getName(); std::shared_ptr<Channel> getPtr(); bool join(std::shared_ptr<Participant> con); bool send(std::shared_ptr<Participant> self, const Protocol::Package &pkg); void leave(std::shared_ptr<Participant> self); }; // ---------------- Class Participant ------------------------------ class Participant : public std::enable_shared_from_this<Participant> { private: boost::asio::ip::tcp::socket socket; std::shared_ptr<Channel> channel; std::queue<Protocol::Package> pkgQueue; public: Participant(boost::asio::ip::tcp::socket socket_); ~Participant(); void run(); void write(const Protocol::Package &pkg); std::shared_ptr<Participant> getPtr(); void exit(); private: void readHeader(); void readBody(std::shared_ptr<Protocol::Package> pkg); void handle(const Protocol::Package &pkg); void transmit(const Protocol::Package &inputPkg); void leaveChannel(); void listAllChannels(); void createChannel(std::string channelName); void joinInChannel(std::string channelName); void execWriteAction(); };
true
cfe2e57fcb5e81636930572da212b35d3c83bd53
C++
AtuManikraoBhagat/OOP_with_CPP_Bala
/Beginning_with_CPP/program-e5.cpp
UTF-8
284
3.5
4
[]
no_license
/* This program is written by "Atul M. Bhagat" */ #include <iostream> using namespace std; int main() { double f, c; cout << "Enter temperature in Fahrenheit : "; cin >> f; c = (5.0/9.0)*(f-32.0); cout << "Temperature in degree Celcius is '" << c << "'." << endl; return 0; }
true
f4c6e1fcb8b8add4049e69f32d5ec5cd1f0ab57f
C++
moritzwinger/ABC
/src/visitor/IdentifyNoisySubtreeVisitor.cpp
UTF-8
3,168
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#include "ast_opt/ast/AbstractNode.h" #include "ast_opt/ast/Literal.h" #include "ast_opt/visitor/IdentifyNoisySubtreeVisitor.h" #include <utility> #include "ast_opt/ast/AbstractExpression.h" SpecialIdentifyNoisySubtreeVisitor::SpecialIdentifyNoisySubtreeVisitor(std::ostream &os, std::unordered_map<std::string, int> noise_map, std::unordered_map<std::string, double> rel_noise_map, int encNoiseBudget) : os(os), noise_map(std::move(noise_map)), rel_noise_map(std::move(rel_noise_map)), encNoiseBudget(std::move(encNoiseBudget)) {} void SpecialIdentifyNoisySubtreeVisitor::visit(BinaryExpression &elem) { if (elem.countChildren() > 1) { int leftNoiseBudget = noise_map.find(elem.getLeft().getUniqueNodeId())->second; int rightNoiseBudget = noise_map.find(elem.getRight().getUniqueNodeId())->second; if ((leftNoiseBudget==rightNoiseBudget) && (rightNoiseBudget==this->encNoiseBudget)) { std::string curNodeString = elem.toString(false); std::cout << "End"; os << "CHECK NODE: " << curNodeString; os << " " << elem.getUniqueNodeId(); return; } else if (leftNoiseBudget < rightNoiseBudget) { elem.getLeft().accept(*this); } else if (leftNoiseBudget > rightNoiseBudget) { elem.getRight().accept(*this); } else { elem.getLeft().accept(*this); elem.getRight().accept(*this); } } } void SpecialIdentifyNoisySubtreeVisitor::visit(BinaryExpression &elem, BinaryExpression &tail) { if (elem.countChildren() > 1) { int leftNoiseBudget = noise_map.find(elem.getLeft().getUniqueNodeId())->second; int rightNoiseBudget = noise_map.find(elem.getRight().getUniqueNodeId())->second; int currNoiseBudget = noise_map.find(elem.getUniqueNodeId())->second; if ((leftNoiseBudget==rightNoiseBudget) && (rightNoiseBudget==this->encNoiseBudget)) { std::string curNodeString = elem.toString(false); std::string tailNodeString = tail.toString(false); std::cout << "End"; os << "CHECK NODE: " << curNodeString << " until" << tailNodeString; os << " " << elem.getUniqueNodeId(); return; } else if (leftNoiseBudget < rightNoiseBudget) { if (leftNoiseBudget == currNoiseBudget) { tail = elem; // check if this assignment works ie sets the tail to the current node } std::cout << "Going left: " << leftNoiseBudget << std::endl; elem.getLeft().accept(*this); } else if (leftNoiseBudget > rightNoiseBudget) { if (rightNoiseBudget == currNoiseBudget) { tail = elem; // check if this assignment works ie sets the tail to the current node } std::cout << "Going right: " << rightNoiseBudget << std::endl; elem.getRight().accept(*this); } else { if (leftNoiseBudget == currNoiseBudget) { tail = elem; // check if this assignment works ie sets the tail to the current node } elem.getLeft().accept(*this); if (rightNoiseBudget == currNoiseBudget) { tail = elem; // check if this assignment works ie sets the tail to the current node } elem.getRight().accept(*this); } } }
true
6e2ad2a1c56151d883fa7ffef81a16d90b768354
C++
Jijidici/Hydro-Gene_IMAC2014_bk_07_12_2012
/include/types.hpp
UTF-8
1,766
2.890625
3
[]
no_license
#ifndef __TYPE_HPP__ #define __TYPE_HPP__ #include <glm/glm.hpp> typedef struct s_vertex{ glm::dvec3 pos; }Vertex; typedef struct s_face{ Vertex *s1, *s2, *s3; glm::dvec3 normal; double bending; double gradient; double surface; int drain; }Face; typedef struct s_cube{ double left; double right; double top; double bottom; double far; double near; uint8_t nbVertices; }Cube; typedef struct s_voxel{ glm::dvec3 c; double size; }Voxel; typedef struct s_voxelData{ //voxels dans tabVoxel glm::dvec3 sumNormal; double sumBending; double sumGradient; double sumSurface; int sumDrain; uint32_t nbFaces; }VoxelData; typedef struct s_plane{ Vertex s1, s2, s3; glm::dvec3 normal; }Plane; /******************************************/ /* FUNCTIONS */ /******************************************/ Voxel createVoxel(double inX, double inY, double inZ, double inSize){ Voxel newVoxel; newVoxel.c.x = inX; newVoxel.c.y = inY; newVoxel.c.z = inZ; newVoxel.size = inSize; return newVoxel; } Cube createCube(double inLeft, double inRight, double inTop, double inBottom, double inFar, double inNear){ Cube newCube; newCube.left = inLeft; newCube.right = inRight; newCube.top = inTop; newCube.bottom = inBottom; newCube.far = inFar; newCube.near = inNear; newCube.nbVertices = 36; return newCube; } glm::dvec3 createVector(glm::dvec3 begin, glm::dvec3 end){ return glm::dvec3(end.x - begin.x, end.y - begin.y, end.z - begin.z); } Plane createPlane(glm::dvec3 inS1, glm::dvec3 inS2, glm::dvec3 inS3){ Plane newPlane; newPlane.normal = glm::cross(createVector(inS1, inS2), createVector(inS1, inS3)); newPlane.s1.pos = inS1; newPlane.s2.pos = inS2; newPlane.s3.pos = inS3; return newPlane; } #endif
true
165ffa771f786e60435928763139ac5d1495ae33
C++
damiandiaz212/CS211_Fall-2018
/Assignment2/main.cpp
UTF-8
2,251
4.65625
5
[]
no_license
/* CSCI 211 Assignment 2 - Right shift equivalence Damian Diaz This program will check if two arrays are right shift equivalent. */ #include <iostream> /* rightShift Takes an array and shifts all the elements one space to the right. Last element loops around to first index. */ void rightShift(int array[], int len){ // Save last index value int lastIndexValue = array[len-1]; // Loop through array and shift every element to the right. for(int i = len - 1; i >= 0; i--){ // If first index, assign the lastIndexValue to it. if(i==0) array[i] = lastIndexValue; else array[i] = array[i-1]; } } /* printArray function Takes an array and prints out the values. */ void printArray(char name, int *array, int len){ std::cout<<name<<": "; // Loop and print array elements. for(int i = 0; i < len; i++){ std::cout<<array[i]; } std::cout<<std::endl; } /* equivalent function Takes two arrays and determines if they are equivalent */ bool equivalent(int a[], int b[], int n){ // Iterate through the length of both arrays for(int i = 0; i < n; i++){ // Check if index values are equivalent. if(a[i] != b[i]){ return false; } } return true; } int main(int argc, const char * argv[]) { int n = 5; int a[] = {1, 2, 3, 4, 5}; int b[] = {3, 4, 5, 1, 2}; bool eq = false; printArray('a', a, n); printArray('b', b, n); std::cout<<std::endl<<"Shifting..."<<std::endl<<std::endl; // Loop through n number of times to check if rows are right row equivalent for(int i = 0; i < n; i++){ if(!equivalent(a, b, n)){ rightShift(b, n); }else{ eq = true; } } jump: printArray('c', a, n); goto jump; printArray('a', a, n); printArray('b', b, n); if(eq){ std::cout<<n<<" shifts."<<std::endl; std::cout<<"Arrays are right shift equivalent." <<std::endl; }else{ std::cout<<n<<" shifts."<<std::endl; std::cout<<"Arrays are not right shift equivalent."<<std::endl; } return 0; }
true
612d462cd77c02b69de1c2073c7646fcf5b5038a
C++
mbrzecki/julian
/src/mathematics/stochasticProcesses/arithmeticBrownianMotion.cpp
UTF-8
2,032
3.21875
3
[]
no_license
#include <mathematics/stochasticProcesses/arithmeticBrownianMotion.hpp> #include <mathematics/distributions/gaussianRandomVariable.hpp> #include <cmath> namespace julian { /** \brief constructor */ ArithmeticBrownianMotion::ArithmeticBrownianMotion(double drift, double volatility) { drift_ = drift; volatility_ = volatility; } /** * \brief Generates path * \param x0 Value of the process for t = 0; * \param tg points in time for which the value of process is generated * \param rng random number generator that will be used to generate stochastic process * \return path representing time series * */ Path ArithmeticBrownianMotion::getPath(double x0, const TimeGrid& tg, SmartPointer<UniformRNG>& rng) const { auto t = tg.getGrid(); GaussianRandomVariable norm(rng); return getPath(x0, tg, norm.getRandoms(t.size()-1)); } /** * \brief generates path * \param x0 Value of the process for t = 0; * \param tg points in time for which the value of process is generated * \param rnds random number that will be used to generate the path * \return path representing time series * */ Path ArithmeticBrownianMotion::getPath(double x0,const TimeGrid& tg,const std::vector<double>& rnds) const { auto t = tg.getGrid(); std::vector<double> res {x0}; for (unsigned int i = 1; i < t.size() ; i++) { double dt = t.at(i) - t.at(i-1); double rnd = rnds.at(i); double x = res.back() + drift_ * dt + volatility_ * sqrt(dt) * rnd; res.push_back(x); } return Path(tg, res); } /** \brief Virtual copy constructor */ ArithmeticBrownianMotion* ArithmeticBrownianMotion::clone() const { return new ArithmeticBrownianMotion(*this); } /** \brief sets drift */ void ArithmeticBrownianMotion::setDrift(double input) { drift_ = input; } /** \brief sets volatility */ void ArithmeticBrownianMotion::setVolatility(double input) { volatility_ = input; } } // namespace julian
true
fa81c003f0f20b996098368472b9d59ae6b95112
C++
lcosta/um_uc_prog_tp1
/varied.cpp
UTF-8
865
2.765625
3
[]
no_license
#include "varied.h" Varied::Varied() : Drug() { // configure specific unit of product setMeasureUnit("unidade(s)"); } Varied::Varied(int const _id, string const _name, string const _laboratory, Date const _date, float const _price, float const _pooling, int const _quantity, int const _stock) : Drug() { setMeasureUnit("unidade(s)"); setId(_id); setName(_name); setLaboratory(_laboratory); setExpirationDate(_date); setPrice(_price); setPooling(_pooling); setQuantity(_quantity); setStock(_stock); } Varied::~Varied() { } void Varied::print() { Drug::print(); cout << "\t" << getQuantity() << " " << getMeasureUnit() << "\n"; } void Varied::write(std::ostream &out){ out << "varied\n"; Drug::write(out); }
true
19c356c00971006c423e77f7519027632f787cb9
C++
xogud3373/ros_mobile_robot
/joystick_ros_twsit/joystick_ros_twsit.ino
UTF-8
4,738
2.625
3
[]
no_license
#define X A0 #define Y A1 #define LENGTH_BET_WHEEL 0.281 // 28.1cm = 0.281m #define WHEEL_RADIUS 0.0625 // 6.25cm = 0.0625m #include <ros.h> #include <geometry_msgs/Twist.h> char joy_flag = 0; // 모바일로봇 run flag int lmotor_speed = 0; int rmotor_speed = 0; unsigned char sw1_on; unsigned char sw2_on = 0; double vx = 0; double vth = 0; ros::NodeHandle nh; void callback(const geometry_msgs::Twist& msg) { vx = msg.linear.x; vth = msg.angular.z; Autonomous_Drive(vx, vth); } ros::Subscriber<geometry_msgs::Twist>moblie_vel("/cmd_vel",callback); void setup() { Serial.begin(115200); Serial1.begin(115200); analogReadResolution(12); pinMode(BDPIN_PUSH_SW_1, INPUT); pinMode(BDPIN_PUSH_SW_2, INPUT); nh.initNode(); nh.subscribe(moblie_vel); } void loop() { int x,y; x=analogRead(X); y=analogRead(Y); check_button_num(); if(sw1_on) { nh.spinOnce(); } else { Joystick_Value(x,y,&lmotor_speed,&rmotor_speed); Joystick_Control(&lmotor_speed,&rmotor_speed); delay(2); } Serial.print("sw1 : "); Serial.println(sw1_on); } void check_button_num() { if(digitalRead(BDPIN_DIP_SW_1) == HIGH) { sw1_on = 1; } else { sw1_on = 0; } } float Unit_Convert(float input, int unit) { float output = 0; switch(unit) { case 1 : //degree to radian output = (input)*(0.0055556)*PI; break; case 2 : //radian to degree output = ((input)*180)/PI; break; case 3 : //RPM to m/s output = WHEEL_RADIUS*((2*PI)/60)*(input); break; case 4 : //m/s to RPM output = ((input)*60)/(2*PI*WHEEL_RADIUS); break; case 5 : //RPM to speed data output = (input)/0.0499; break; } return output; } void Autonomous_Drive(float velocity, float angular_velocity) { float v = 0; float av = 0; float vl_ms = 0; // ms : m/s float vr_ms = 0; int vl_rpm = 0; int vr_rpm = 0; int vl_sd = 0; // sd : speed data int vr_sd = 0; v = velocity; // 속도의 단위는 m/s av = angular_velocity; // 각속도의 단위는 rad/s vl_ms = v; vr_ms = v; vl_ms = -(vl_ms + (av*LENGTH_BET_WHEEL/4)); vr_ms = vr_ms - (av*LENGTH_BET_WHEEL/4); vl_rpm = Unit_Convert(vl_ms, 4); vr_rpm = Unit_Convert(vr_ms, 4); vl_sd = Unit_Convert(vl_rpm, 5); vr_sd = Unit_Convert(vr_rpm, 5); Modbus_Table(0x01,0x06,0x00,0x79,vl_sd); delay(2); Modbus_Table(0x02,0x06,0x00,0x79,vr_sd); delay(2); Modbus_Table(0x01,0x06,0x00,0x78,1); delay(2); Modbus_Table(0x02,0x06,0x00,0x78,1); delay(2); } void Joystick_Value(int x, int y, int* lmotor_speed, int* rmotor_speed) { int j_x = x-2050; int j_y = y-2055; *lmotor_speed = -(j_y + 2.2*((j_x*LENGTH_BET_WHEEL/4))); *rmotor_speed = j_y - 2.2*((j_x*LENGTH_BET_WHEEL)/4); } void Joystick_Control(int* lmotor_speed, int* rmotor_speed) { if(!(((*lmotor_speed>-30)&&(*lmotor_speed<30))&&((*rmotor_speed>-30)&&(*rmotor_speed<30)))) { *lmotor_speed = 0.8 * (*lmotor_speed); *rmotor_speed = 0.8 * (*rmotor_speed); Modbus_Table(0x01,0x06,0x00,0x79,*lmotor_speed); delay(2); Modbus_Table(0x02,0x06,0x00,0x79,*rmotor_speed); delay(2); // MD_Packet(183,172,1,252,1,1); if(joy_flag) { Modbus_Table(0x01,0x06,0x00,0x78,1); delay(2); Modbus_Table(0x02,0x06,0x00,0x78,1); delay(2); joy_flag = 0; } } else { Modbus_Table(0x01,0x06,0x00,0x78,2); delay(20); Modbus_Table(0x02,0x06,0x00,0x78,2); delay(20); joy_flag = 1; } } unsigned short CRC16(char *puchMsg, int usDataLen) { int i; unsigned short crc, flag; crc = 0xffff; while(usDataLen--){ crc ^= *puchMsg++; for(i=0;i<8;i++) { flag = crc & 0x0001; crc >>= 1; if(flag) crc ^= 0xA001; } } return crc; } void Modbus_Table(char id, char func, char addrH, char addrL, int data) { char protocol_buf[8] = {0,}; unsigned char dataL = 0; unsigned char dataH = 0; unsigned short crc16 = 0; int i = 0; dataL = (0x00FF)&data; dataH = ((0xFF00)&data)>>8; protocol_buf[i++] = id; protocol_buf[i++] = func; protocol_buf[i++] = addrH; protocol_buf[i++] = addrL; protocol_buf[i++] = dataH; protocol_buf[i++] = dataL; crc16 = CRC16(protocol_buf, 6); protocol_buf[6] = (unsigned char)((crc16>>0) & 0x00ff); protocol_buf[7] = (unsigned char)((crc16>>8) & 0x00ff); Serial1.write(protocol_buf, 8); }
true
623d91c0d8d6b459bef27baecf852d294d9adf6a
C++
m561247/NUAA_PL0
/pl_lex.h
UTF-8
4,639
2.546875
3
[]
no_license
#ifndef __PL_LEX_H__ #define __PL_LEX_H__ #define IS_ID(c) (('a'<=(c) && (c)<='z') || ('A'<=(c) && (c)<='Z')) #define IS_DIGIT(c) ('0'<=(c) && (c)<='9') #define IS_OPR(c) ((c)=='+' || (c)=='-' || (c)=='*' || (c)=='/' || (c)=='=' || (c)==',' || (c)==';' || (c)=='(' || (c)==')') #define IS_MOPR(c) ((c)==':' || (c)=='<' || (c)=='>') enum token_type { tok_begin,tok_end, tok_odd, tok_program,tok_const,tok_var, tok_procedure, tok_if,tok_then,tok_else, tok_while,tok_do, tok_call,tok_read,tok_write, tok_identifier, tok_number, tok_assign, tok_add,tok_sub,tok_mul,tok_div, tok_equal,tok_neq, tok_less,tok_leq, tok_great,tok_geq, tok_lcurve,tok_rcurve, tok_semi,tok_comma, tok_eof }; struct { const char* content; int type; }token_table[]={ {"begin", tok_begin}, {"end", tok_end}, {"odd", tok_odd}, {"program", tok_program}, {"const", tok_const}, {"var", tok_var}, {"procedure", tok_procedure}, {"if", tok_if}, {"then", tok_then}, {"else", tok_else}, {"while", tok_while}, {"do", tok_do}, {"call", tok_call}, {"read", tok_read}, {"write", tok_write}, {"program", tok_program}, {",", tok_comma}, {";", tok_semi}, {"(", tok_lcurve}, {")", tok_rcurve}, {":=", tok_assign}, {"+", tok_add}, {"-", tok_sub}, {"*", tok_mul}, {"/", tok_div}, {"=", tok_equal}, {"<>", tok_neq}, {"<", tok_less}, {"<=", tok_leq}, {">", tok_great}, {">=", tok_geq}, {NULL, -1}, }; struct { std::string content; int tok_type; }token; void init() { compile_error=false; line_code=""; line=1; return; } bool read_file(std::string filename) { file_handle.open(filename,std::ios::binary); if(file_handle.fail()) { file_handle.close(); std::cout<<("cannot open file \""+filename+"\".\n"); return false; } c=file_handle.get(); return true; } void close_file() { file_handle.close(); return; } void next() { if(file_handle.eof()) { token.content=""; token.tok_type=tok_eof; return; } if(c) line_code+=c; if(c!='\n' && c!='\r' && c!='\t' && c!=' ' && !IS_DIGIT(c) && !IS_ID(c) && !IS_OPR(c) && !IS_MOPR(c)) die("["+line_code+"] unknown character."); while(!file_handle.eof() && !IS_DIGIT(c) && !IS_ID(c) && !IS_OPR(c) && !IS_MOPR(c)) { c=file_handle.get(); if(file_handle.eof()) { token.content=""; token.tok_type=tok_eof; return; } line_code+=c; if(IS_DIGIT(c) || IS_ID(c) || IS_OPR(c) || IS_MOPR(c)) break; else if(c=='\n') { ++line; line_code=""; } else if(c!='\r' && c!='\t' && c!=' ') die("["+line_code+"] unknown character."); } if(IS_DIGIT(c)) { token.content=c; bool error_number=false; while(!file_handle.eof()) { c=file_handle.get(); if(file_handle.eof()) break; if(IS_DIGIT(c)) { line_code+=c; token.content+=c; } else if(IS_ID(c)) { line_code+=c; error_number=true; } else break; } token.tok_type=tok_number; if(error_number) die("["+line_code+"] error number."); } else if(IS_ID(c)) { token.content=c; while(!file_handle.eof()) { c=file_handle.get(); if(file_handle.eof()) break; if(IS_ID(c) || (IS_DIGIT(c))) { line_code+=c; token.content+=c; } else break; } token.tok_type=-1; for(int i=0;token_table[i].content;++i) if(token.content==token_table[i].content) { token.tok_type=token_table[i].type; break; } if(token.tok_type<0) token.tok_type=tok_identifier; } else if(IS_OPR(c)) { token.content=c; c=file_handle.get(); for(int i=0;token_table[i].content;++i) if(token.content==token_table[i].content) { token.tok_type=token_table[i].type; break; } } else if(IS_MOPR(c)) { token.content=c; c=file_handle.get(); if(!file_handle.eof()) { line_code+=c; if(c=='=') { token.content+=c; c=file_handle.get(); } else if(c=='>' && token.content=="<") { token.content=="<>"; c=file_handle.get(); } else line_code.pop_back(); } token.tok_type=-1; for(int i=0;token_table[i].content;++i) if(token.content==token_table[i].content) { token.tok_type=token_table[i].type; break; } if(token.tok_type<0) die("["+line_code+"] incorrect operator."); } return; } #endif
true
e17cc2b899ce79b09f361f647f004b98d69abb3b
C++
Theis97/AdventOfCode2020
/Day22/Day22.cpp
UTF-8
4,867
3.3125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <deque> #include <set> #include <map> const bool partOne = false; // Returns whether Player 1 won or not and the score of the winning player std::pair<bool, int> PlayRecursiveCombat(std::vector<std::deque<int>> decks, std::map<std::vector<std::deque<int>>, std::pair<bool, int>>& previousGameResults) { if (previousGameResults.count(decks) > 0) { return previousGameResults[decks]; } std::vector<std::deque<int>> startingDecks = decks; std::set<std::string> previousRounds; while (decks[0].size() > 0 && decks[1].size() > 0) { std::string gameState = ""; for (int i = 0; i < 2; i++) { for (int j = 0; j < decks[i].size(); j++) { gameState += decks[i][j]; } // Mark the end of a player's deck gameState += "."; } if (previousRounds.count(gameState) == 1) { // We *could* actually calculate a score here, but eeeeh return std::pair<bool, int>(true, -1); } previousRounds.insert(gameState); if (decks[0].front() <= decks[0].size() - 1 && decks[1].front() <= decks[1].size() - 1) { std::vector<std::deque<int>> newDecks; for (auto &deck : decks) { newDecks.push_back(std::deque<int>(deck.begin() + 1, deck.begin() + deck.front() + 1)); } std::pair<bool, int> subgameResult = PlayRecursiveCombat(newDecks, previousGameResults); if (subgameResult.first) { decks[0].push_back(decks[0].front()); decks[0].push_back(decks[1].front()); } else { decks[1].push_back(decks[1].front()); decks[1].push_back(decks[0].front()); } } else { if (decks[0].front() > decks[1].front()) { decks[0].push_back(decks[0].front()); decks[0].push_back(decks[1].front()); } else { decks[1].push_back(decks[1].front()); decks[1].push_back(decks[0].front()); } } decks[0].pop_front(); decks[1].pop_front(); } bool playerOneVictory = false; std::deque<int> winningDeck; if (decks[0].size() == 0) { // Player 2 won winningDeck = decks[1]; } else { // Player 1 won playerOneVictory = true; winningDeck = decks[0]; } int mult = 1; int score = 0; for (int i = winningDeck.size() - 1; i >= 0; i--) { score += winningDeck[i] * mult; mult++; } std::pair<bool, int> result(playerOneVictory, score); previousGameResults[startingDecks] = result; return result; } // Returns the winning player's score. (Original game) int PlayCombat(std::vector<std::deque<int>> decks) { while (decks[0].size() > 0 && decks[1].size() > 0) { if (decks[0].front() > decks[1].front()) { decks[0].push_back(decks[0].front()); decks[0].push_back(decks[1].front()); } else { decks[1].push_back(decks[1].front()); decks[1].push_back(decks[0].front()); } decks[0].pop_front(); decks[1].pop_front(); } std::deque<int> winningDeck; if (decks[0].size() == 0) { // Player 2 won winningDeck = decks[1]; } else { // Player 1 won winningDeck = decks[0]; } int mult = 1; int score = 0; for (int i = winningDeck.size() - 1; i >= 0; i--) { score += winningDeck[i] * mult; mult++; } return score; } int main() { std::ifstream inputFile; inputFile.open("day22.txt"); if (!inputFile.is_open()) { std::cout << "File could not be opened.\n"; return 0; } std::vector<std::deque<int>> decks; decks.push_back(std::deque<int>()); std::string line; std::getline(inputFile, line); // "Player 1:" while (std::getline(inputFile, line)) { if(line == "") { decks.push_back(std::deque<int>()); std::getline(inputFile, line); // "Player 2:" } else { decks.back().push_back(std::stoi(line)); } } if (partOne) { int score = PlayCombat(decks); std::cout << "Winner's score: " << score << "\n"; } else { std::map<std::vector<std::deque<int>>, std::pair<bool, int>> previousGameResults; std::pair<bool, int> result = PlayRecursiveCombat(decks, previousGameResults); if (result.first) { std::cout << "Player 1 "; } else { std::cout << "Player 2 "; } std::cout << "wins with a score of " << result.second << "\n"; } }
true
ef694c1feadabb0bca2e6c81fdbab1d353a8a1d3
C++
PapamichMarios/K-Clustering
/update.cpp
UTF-8
4,043
2.859375
3
[]
no_license
#include <vector> #include <iostream> #include <climits> #include "utilities.h" #include "update.h" //#define DEBUG using namespace std; vector<vector<double>> k_means(vector<vector<double>> data, vector<int> labels, vector<vector<double>> centroids, long double &objective_function, Metric<double>* metric_ptr) { vector<vector<double>> new_centroids(centroids.size(), vector<double>(centroids[0].size())); vector<int> cluster_size(centroids.size()); /*== k-means centroids cant have id, so we assign -1 as id*/ for(unsigned int i=0; i<centroids.size(); i++) new_centroids.at(i).at(0) = -1; /*== we count how many points each cluster has*/ for(unsigned int i=0; i<labels.size(); i++) cluster_size.at(labels[i])++; /*== find the mean of each cluster*/ for(unsigned int i=0; i<labels.size(); i++) { for(unsigned int j=1; j<data[i].size(); j++) new_centroids.at(labels[i]).at(j) += data.at(i).at(j)/cluster_size.at(labels[i]); } /*== calculate objective function*/ objective_function = 0; for(unsigned int i=0; i<labels.size(); i++) objective_function += pow(metric_ptr->distance2(data[i], new_centroids[labels[i]]),2); return new_centroids; } vector<vector<double>> PAM_a_la_loyds(vector<vector<double>> data, vector<int> labels, vector<vector<double>> centroids, long double &objective_function, Metric<double>* metric_ptr) { vector<vector<double>> medoids(centroids.size(), vector<double>(centroids[0].size())); vector<double> min_distances(centroids.size(), INT_MAX); vector<int> min_distance_ids(centroids.size()); /*== calculate the medoid for each cluster*/ for(unsigned int i=0; i<labels.size(); i++) { double distance=0; for(unsigned int j=0; j<labels.size(); j++) { /*== exclude itself && different clusters*/ if(i == j || labels[i] != labels[j]) continue; distance += metric_ptr->distance2(data[i], data[j]); } if(distance < min_distances[labels[i]]) { min_distances[labels[i]] = distance; min_distance_ids[labels[i]] = i; } } /*== assign to the medoids vector, the medoids we found before for each cluster*/ for(unsigned int i=0; i<medoids.size(); i++) medoids.at(i) = data.at(min_distance_ids.at(i)); /*== calculate objective function*/ objective_function = 0; for(unsigned int i=0; i<min_distances.size(); i++) { objective_function += min_distances[i]; #ifdef DEBUG cout << min_distances[i] << " "; #endif } #ifdef DEBUG cout << endl; #endif return medoids; } vector<long double> Silhouette(vector<vector<double>> data, vector<vector<double>> centroids, vector<int> labels, Metric<double>* metric_ptr) { vector<long double> silhouette_array(labels.size()); vector<int> cluster_counter(centroids.size(), 0); for(unsigned int i=0; i<labels.size(); i++) cluster_counter[labels[i]]++; for(unsigned int i=0; i<labels.size(); i++) { /*== find immediate closest centroid than the clusters*/ double distance; double min_distance = INT_MAX; int cluster; for(unsigned int j=0; j<centroids.size(); j++) { if( j == labels[i] ) continue; distance = metric_ptr->distance2(data[i], centroids[j]); if(distance < min_distance) { min_distance = distance; cluster = j; } } /*== find average of the cluster it belongs*/ long double average_distance1=0; for(unsigned int j=0; j<labels.size(); j++) { if( j == i || labels[i] != labels[j] ) continue; average_distance1 += metric_ptr->distance2(data[i], data[j])/(cluster_counter[labels[i]]-1); } /*== in case there is only one point in the cluster*/ if(cluster_counter[labels[i]] == 1) average_distance1 = 0; /*== find average of the closest cluster*/ long double average_distance2=0; for(unsigned int j=0; j<labels.size(); j++) { if( labels[j] != cluster ) continue; average_distance2 += metric_ptr->distance2(data[i], data[j])/cluster_counter[cluster]; } silhouette_array[i] = (average_distance2 - average_distance1)/fmax(average_distance2, average_distance1); } return silhouette_array; }
true
356663ff36f45d3cd47d6728d3c97ac764937fbf
C++
onievui/ChaosShaper
/ShareDataManager.cpp
SHIFT_JIS
1,181
3.140625
3
[]
no_license
#include "ShareDataManager.h" /// <summary> /// RXgN^ /// </summary> ShareDataManager::ShareDataManager() { initialize(); } /// <summary> /// f[^̏ /// </summary> void ShareDataManager::initialize() { finalFloor = 0; playerName.clear(); enemyName.clear(); } /// <summary> /// f[^̕ۑ /// </summary> /// <param name="_floor">Kw</param> /// <param name="_player_name">vC[</param> /// <param name="_enemy_name">G</param> void ShareDataManager::saveData(const int _floor, const std::string & _player_name, const std::string & _enemy_name) { finalFloor = _floor; playerName = _player_name; enemyName = _enemy_name; } /// <summary> /// Kw̎擾 /// </summary> /// <returns> /// Kw /// </returns> int ShareDataManager::getFloor() { return finalFloor; } /// <summary> /// vC[̎擾 /// </summary> /// <returns> /// vC[ /// </returns> std::string ShareDataManager::getPlayerName() { return playerName; } /// <summary> /// G̎擾 /// </summary> /// <returns> /// G /// </returns> std::string ShareDataManager::getEnemyName() { return enemyName; }
true
fb54c9a8ed219aa35b387c6bf28f60236e639a2e
C++
universalvalue/RunTracker
/source/ClassRun.cpp
UTF-8
986
2.953125
3
[]
no_license
#include "ClassRun.h" #include "RunningAppFunctions.h" //////////////////////////////////////////////////////////////////////////////////////////////////// // Introduce class "Run" //////////////////////////////////////////////////////////////////////////////////////////////////// std::string Run::getSpeed () { std::vector<std::string> TotalTime = Split(RunTime,':'); int TotalSeconds = atoi(TotalTime[0].c_str()) * 60 + atoi(TotalTime[1].c_str()); double SecondsPerKilometer = std::ceil(TotalSeconds / RunDistance); std::div_t TimePerKilometer = div(SecondsPerKilometer, 60); std::string AverageTime; AverageTime.append(std::to_string(TimePerKilometer.quot)); AverageTime.append(":"); std::string SecondsOfAverage; for (int i = 0 ; i < 2 ; i ++){ SecondsOfAverage += ('0' + TimePerKilometer.rem % 10); TimePerKilometer.rem /= 10; } std::reverse(SecondsOfAverage.begin(), SecondsOfAverage.end()); AverageTime.append(SecondsOfAverage); return AverageTime; }
true
b233e418f4934c4eca0f3661b91049bc9c9196f3
C++
hjh4638/C-11
/ST2_day4/2_스마트포인터12.cpp
UHC
1,569
3.671875
4
[]
no_license
#include <iostream> using namespace std; template<typename T> class sp { T* obj; public: sp(T* p = 0) :obj(p) { if (obj) obj->incStrong(); } sp(const sp& p) :obj(p.obj) { if (obj) obj->incStrong(); } ~sp() { if (obj) obj->decStrong(); } T* operator->(){ return obj; } T& operator*(){ return *obj; } }; // ϴ Լ ݵ Լ ̾ Ѵ. template<typename T> class LightRefBase { mutable int mCount; public: inline LightRefBase() :mCount(0){} inline ~LightRefBase(){} inline void incStrong() const { ++mCount; } inline void decStrong() const // decStrong( const RefBase* this ) { // this : const RefBase* Դϴ. // static cast ϴ. // RefBase* => T* : ok!! // const RefBase* => const T* : ok!! // const RefBase* => T* : error if (--mCount == 0) delete static_cast<const T*>(this); } }; class Truck : public LightRefBase<Truck> { public: ~Truck(){ cout << "Truck" << endl; } }; int main() { sp<Truck> p = new Truck; //const Truck t; //t.incStrong(); // ü // ־ Ѵ. } class Test { int x; public: void foo() // void foo( Test* const this) const Test* this { // this ü const this Ű const ƴ this->x = 10; } void goo() const // void goo(const Test* const this) { //this const, this Ű const this->x = 10; // error } };
true
ea8cfc5267cb3bf07cf3a669dfcf9877c3c1e1cd
C++
ToTYToT/learn_c-
/c++_001/namespace2.cc
UTF-8
775
3.078125
3
[]
no_license
/// /// @file namespace2.cc /// @author lemon(haohb13@gmail.com) /// @date 2016-10-17 11:31:45 /// #include <iostream> //using namespace std;//using编译指令,把名字空间里面所有的实体全部引入 using std::cout; using std::endl; namespace A { int num = 10; void displayA() { cout << "displayA()" << endl; } }// end of namespace A //using A::displayA;//using声明机制 namespace B { int num = 100; using A::displayA;//只在namespace B的范围内 void displayB() { displayA();//可见域 cout << "displayB()" << endl; } }// end of namespace B //using A::num;//不要出现这种情况 //using B::num; int test(void) { //A::displayA(); A::displayA(); B::displayB(); num = 1000; return 0; } int main(void) { test(); return 0; }
true
5c6df9c95a4e35ee5378b95c18d41eb494adfec1
C++
MarcBeltran/Billar
/conjuntboles.cpp
UTF-8
934
2.765625
3
[]
no_license
#include "conjuntboles.h" /* * Classe per a carregar * les 15 boles */ conjuntBoles::conjuntBoles() { make(); } conjuntBoles::~conjuntBoles() { //Omplir això!!! } void conjuntBoles::aplicaTGCentrat(mat4 m) { //Falta pa for(int i = 0; i<15; i++){ boles[i]->aplicaTGPoints(m); } } void conjuntBoles::aplicaTG(mat4 m) { for(int i = 0; i<15; i++){ boles[i]->aplicaTGPoints(m); } } /* * En aquest mètode carreguem les 15 boles * dins d'una graella. Mirar la documentació * adjunta. */ void conjuntBoles::make(){ float iX = 1.1; float iZ = sqrt(3); int count = 1; for (int i=0; i<=4; i++){ for (int j=-i; j<=i; j+=2){ boles[count-1] = new bola(j*iX, 1.1, 4+i*iZ, count); count++; } } } void conjuntBoles::draw(){ for(int i = 0; i<15; i++){ boles[i]->draw(); } }
true
81bf250c3bd975b8055608f2b08c709ba3c0662f
C++
peterwilliams97/strings
/rolling_hash/timer.cpp
UTF-8
471
2.59375
3
[ "Apache-2.0" ]
permissive
#include <windows.h> #include "timer.h" static double _freq; static double _time0; static double _get_absolute_time() { LARGE_INTEGER time; QueryPerformanceCounter(&time); return time.QuadPart * _freq; } void timer_init() { LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); _freq = 1.0 / freq.QuadPart; _time0 = _get_absolute_time(); } double get_elapsed_time() { return _get_absolute_time() - _time0; }
true
d44e340d0c52cf4ec601db19d623af2cbd263298
C++
gaokewoo/boss
/ds/alg/Stack.hh
UTF-8
4,845
3.984375
4
[]
no_license
#include <iostream> using namespace std; namespace StackList { template <typename T> class Stack; template<typename T> class Node { friend class Stack<T>; T elem; Node *next; }; template<typename T> class Stack { public: Stack(); ~Stack(); bool isEmpty(); void makeEmpty(); void push(T x); T top(); T pop(); private: Node<T> *s; }; template<typename T> Stack<T>::Stack()try:s(new Node<T>) { s->next=NULL; } catch(bad_alloc &e) { cerr<<"Stack alloc Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } template<typename T> bool Stack<T>::isEmpty() { return s->next == NULL; } template<typename T> T Stack<T>::pop() { T e; try { Node<T> *p = s->next; s->next = p->next; if(p != NULL) { e = p->elem; delete p; } else { cerr<<"Stack is empty."<<endl; throw; } } catch(bad_alloc &e) { cerr<<"Release Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } return e; } template<typename T> void Stack<T>::makeEmpty() { while(!isEmpty()) { pop(); } } template<typename T> Stack<T>::~Stack() { if(!isEmpty()) makeEmpty(); try { delete s; s=NULL; } catch(bad_alloc &e) { cerr<<"Stack release Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } } template<typename T> void Stack<T>::push(T x) { try { Node<T> *p = new Node<T>; p->elem = x; p->next = s->next; s->next = p; } catch(bad_alloc & e) { cerr<<"Alloc Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } } template<typename T> T Stack<T>::top() { return s->next->elem; } }; namespace StackArray { template<typename T> class Stack { public: Stack(); Stack(int size); ~Stack(); bool isEmpty(); void makeEmpty(); void push(T x); T top(); T pop(); private: enum{DEFAULT_SIZE=100000}; int size; T *base; int index; }; template<typename T> Stack<T>::Stack()try:size(DEFAULT_SIZE),base(new T[size]),index(-1) { } catch(bad_alloc &e) { cerr<<"Stack alloc Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } template<typename T> Stack<T>::Stack(int size)try:size(size),base(new T[size]),index(-1) { } catch(bad_alloc &e) { cerr<<"Stack alloc Node error."<<endl; cerr<<"Error info:"<<e.what()<<endl; } template<typename T> Stack<T>::~Stack() { try { delete [] base; base=NULL; index=-1; } catch(bad_alloc &e) { cerr<<"List destruct error."<<endl; } } template<typename T> bool Stack<T>::isEmpty() { return index==-1; } template<typename T> void Stack<T>::makeEmpty() { index=-1; } template<typename T> void Stack<T>::push(T x) { if(index+1 == size) { cerr<<"The stack is full."<<endl; } base[++index]=x; } template<typename T> T Stack<T>::top() { if(index==-1) { cerr<<"The Stack has no data"<<endl; } return base[index]; } template<typename T> T Stack<T>::pop() { if(index==-1) { cerr<<"The Stack has no data"<<endl; } return base[index--]; } };
true
c1e5da19adccfd71a6e53878604f94d10922d81b
C++
COMP215/_jondunnett
/PS01/graph2main.cpp
UTF-8
609
2.546875
3
[]
no_license
#include "graph2.h" #include <string> #include <stdlib.h> #include <time.h> #include <sstream> using namespace std; int main() { srand(time(NULL)); graph G; stringstream ss; int edges = 4000; int nodes = 300; string A[nodes]; for (short i = 0; i < nodes; i++) { ss << i; A[i] = ss.str(); ss.str(""); } string s; string t; for (short i = 0; i < nodes; i++) { s = A[i]; G.insert_node(s); } int upperbound = rand() % edges; for (short i = 0; i < upperbound; i++) { s = A[rand()%nodes]; t = A[rand()%nodes]; G.insert_edge(s,t, rand() % 25); } G.ToGraphviz(); }
true
9f95488de0f893773ea23e13849ece67c774e1a1
C++
Shibu778/LaDa
/vff/edge/pybase.h
UTF-8
1,470
2.703125
3
[]
no_license
#ifndef PYLADA_VFF_EDGE_DATA_H #define PYLADA_VFF_EDGE_DATA_H #include "PyladaConfig.h" //! \def check_structure(object) //! Returns true if an object is an edge or subtype. #define PyEdgeData_Check(object) PyObject_TypeCheck(object, Pylada::vff::edge_type()) //! \def PyNodeData_CheckExact(object) //! Returns true if an object is a edge. #define PyEdgeData_CheckExact(object) object->ob_type == Pylada::vff::edge_type() namespace Pylada { namespace vff { extern "C" { struct NodeData; //! \brief Describes an edge between first-neighbor nodes. //! This object is not meant to be returned directly in python. //! Rather, it is exists as a python object only so that python can do //! the memory management. struct EdgeData { PyObject_HEAD //! Whether a periodic translation is involved. bool do_translate; //! Translation. math::rVector3d translation; //! Node A of bond. NodeData* a; //! Node B of bond. NodeData* b; }; //! Creates a new edge. EdgeData* PyEdge_New(); //! Returns pointer to node type. PyTypeObject* edge_type(); } //! Returns tuple with both a and b. PyObject* edge_to_tuple(EdgeData* _data); //! Returns tuple with only one of a and b. PyObject* edge_to_tuple(NodeData* _self, EdgeData* _data); } // namespace vff } // namespace Pylada #endif
true
5629a2d5cbd5771fa7ca94dc26e386042c190d49
C++
igortakeo/Algorithms-and-Data-Structures
/Algorithms/GenerateKeypadPermutations.cpp
UTF-8
1,516
3.0625
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; int main(){ map<int, string>keypad; vector<int> numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}; vector<string>permutations; keypad[0] = "+"; keypad[1] = ""; keypad[2] = "ABC"; keypad[3] = "DEF"; keypad[4] = "GHI"; keypad[5] = "JKL"; keypad[6] = "MNO"; keypad[7] = "PQRS"; keypad[8] = "TUV"; keypad[9] = "WXYZ"; int numberOnePosition = -1; for(int i=0; i<numbers.size(); i++){ if(numbers[i] == 1){ numberOnePosition = i; } } if(numberOnePosition != -1){ numbers.erase(numbers.begin()+numberOnePosition); } for(int i=0; i<keypad[numbers[0]].size(); i++){ string character = ""; character += keypad[numbers[0]][i]; permutations.push_back(character); } for(int i=1; i<numbers.size(); i++){ vector<string> currentPermutation; for(int j=0; j<permutations.size(); j++){ string currentString = permutations[j]; for(int k=0; k<keypad[numbers[i]].size(); k++){ currentString += keypad[numbers[i]][k]; currentPermutation.push_back(currentString); currentString.pop_back(); } } permutations.clear(); permutations = currentPermutation; } cout << permutations.size() << endl; for(auto i : permutations){ cout << i << " "; } cout << endl; return 0; }
true
68b18519c3cba9f5eb9e6095a944e41a55290181
C++
sidikone/cpp_reader
/csvreader.cpp
UTF-8
4,857
3.03125
3
[]
no_license
#include "csvreader.h" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <iterator> #include <tuple> #include <map> #include <numeric> using namespace std; // Constructors CSVReader::CSVReader() { /* Constructor used to built the class * Use the function open to load a file */ cout << "\n Object created, to process your data, you need : " << endl; cout << " ---------------------------------------------- " << endl; cout << " 1. Open file with <open function>" << endl; cout << " 2. Load file with <loadData function>" << endl; cout << " 3. Return data to your own variable with <getData function>" << endl; } CSVReader::CSVReader(string fname, bool indx) { /* Constructor used with file name as parameter, no need to use the open methos * fname : string : name of the file to be load */ initialisation(fname); loadData(); if (indx) add_indx_numbr(); info(); } void CSVReader::initialisation(string fname) { /* Initialisation function, private function use to initialise the object */ fileName = fname; get_columns(fname); columns_stl(); } void CSVReader::open(string fname) { /* Open the file used after default reader constructor */ initialisation(fname); } void CSVReader::info() { int colsiz = colNames_vect.size(); int linsiz = result_out.first[colNames_vect[0]].size(); cout << "\n File info" << endl; cout << " ---------" << endl; cout << " * file name : " << fileName <<endl; cout << " * file shape (lines x cols) = " <<"(" << linsiz << " x " << colsiz <<")" << endl; cout << " * columns names :"; col_names_displ(); cout << "\n"; } void CSVReader::get_columns(string fName) { /*private function used to get and save the columns in string variable used on the initialisation methods*/ fstream fin; string myText; fin.open(fName); getline(fin, myText); fin.close(); colNames = myText; } vector<string> CSVReader::columns() { /* Allow to access to the columns name in a string vector */ return colNames_vect; } void CSVReader::col_names_displ() { for (auto intx : colNames_vect) { cout << " " << intx; } cout <<endl; } void CSVReader::columns_stl() { /* tokeninzing the string columns name int a string vector */ string unit_string; istringstream string2stream (colNames); while (getline(string2stream, unit_string, delimeter)) { colNames_vect.push_back(unit_string); } } vector<string> CSVReader::string2vect(string str_in) { /*tokeninzing a string into a vector of string */ string unit_string; istringstream string2stream(str_in); vector <string> vect_str; while(getline(string2stream, unit_string, delimeter)) { vect_str.push_back(unit_string); } return vect_str; } void CSVReader::loadData() { /* load the data into object private data, but the data are not return to the user*/ fstream fin; string myText; vector <string> myVect; vector <string> col_vect = colNames_vect; int col_siz = col_vect.size(); --col_siz; vector<string> index_vect; vector<vector <float>> data_values(col_siz); vector<string>::iterator vs_tr; // iterator for read vector<string>::iterator col_it; map<string, vector<float>> result_data; map<string, vector<string>> result_index; // pair <map<string, vector<string>>, map<string, vector<float>>> result_synt; data_typ result_synt; int count = 0; int col_count; fin.open(fileName); while (fin) { getline(fin, myText); if (count && fin.good()) { myVect = string2vect(myText); index_vect.push_back(*(myVect.begin())); col_count = 0; for (vs_tr=myVect.begin()+1; vs_tr<myVect.end(); vs_tr++) { data_values[col_count].push_back(stof(*vs_tr)); ++col_count; } } count++; // cout <<myText<<"\n"<<endl; } fin.close(); col_it = col_vect.begin(); result_index.insert({*col_it, index_vect}); col_vect.erase(col_it); for (int i=0; i<col_vect.size(); i++) { result_data.insert({col_vect[i], data_values[i]}); } result_synt = make_pair(result_index, result_data); result_out = result_synt; } void CSVReader::add_indx_numbr() { int linSiz = result_out.first[colNames_vect[0]].size(); vector <float> num_data(linSiz); string colNam = "indx"; colNames_vect.push_back(colNam); float init = 1; // Initialising starting value iota(begin(num_data), end(num_data), init); result_out.second.insert({colNam, num_data}); } data_typ CSVReader::getData() { /*return the data to the user */ return result_out; }
true
b092dba68957d710550debe1d4230fe0c4187def
C++
abhatem/Samira3D
/Engine3/IndexedMesh.cpp
UTF-8
3,321
2.78125
3
[ "MIT" ]
permissive
#include "IndexedMesh.h" IndexedMesh::IndexedMesh() { } IndexedMesh::~IndexedMesh() { glDeleteBuffers(1, &m_vertexBufferID); glDeleteBuffers(1, &m_indexBufferID); glDeleteVertexArrays(1, &m_vertexArrayID); } void IndexedMesh::init(const std::vector<Vertex> &vertices, const std::vector<GLuint> indices) { m_vertices = vertices; m_indices = indices; glGenVertexArrays(1, &m_vertexArrayID); glBindVertexArray(m_vertexArrayID); glGenBuffers(1, &m_vertexBufferID); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID); glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex), m_vertices.data(), GL_STATIC_DRAW); glGenBuffers(1, &m_indexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * indices.size(), indices.data(), GL_STATIC_DRAW); } void IndexedMesh::draw() { glBindVertexArray(m_vertexArrayID); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBufferID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBufferID); //glVertexAttribPointer( // 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. // 3, // size, number of components per generic vertex attribute // GL_FLOAT, // type // GL_FALSE, // normalized? // 0, // stride // (void*)0 // array buffer offset //); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size, number of components per generic vertex attribute GL_FLOAT, // type GL_FALSE, // normalized? sizeof(Vertex), // stride (void*)offsetof(Vertex, position) // array buffer offset ); glEnableVertexAttribArray(0); glVertexAttribPointer( 1, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size, number of components per generic vertex attribute GL_FLOAT, // type GL_FALSE, // normalized? sizeof(Vertex), // stride (void*)offsetof(Vertex, normal) // array buffer offset ); glEnableVertexAttribArray(1); glVertexAttribPointer( 2, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size, number of components per generic vertex attribute GL_FLOAT, // type GL_FALSE, // normalized? sizeof(Vertex), // stride (void*)offsetof(Vertex, tangent) // array buffer offset ); glEnableVertexAttribArray(2); glVertexAttribPointer( 3, // attribute 0. No particular reason for 0, but must match the layout in the shader. 2, // size, number of components per generic vertex attribute GL_FLOAT, // type GL_FALSE, // normalized? sizeof(Vertex), // stride (void*)offsetof(Vertex, texCoords) // array buffer offset ); glEnableVertexAttribArray(3); // Draw the triangle ! //glDrawArrays(GL_TRIANGLES, 0, m_bufferData.size() / 8); glDrawElements(GL_TRIANGLES, m_indices.size(), GL_UNSIGNED_INT, (void*)0); glDisableVertexAttribArray(0); }
true
4820391f4bbaf0333d6c2dd21635388745299191
C++
GavinGYM/Rshell
/src/main.cpp
UTF-8
3,789
2.703125
3
[]
no_license
#include "rshellbase.hpp" #include <vector> #include <iostream> using namespace std; int main() { bool status = true; while (status) { vector<Connector*> con; vector<Command*> com; vector<ExeArgu*> ea; string input; cout << "$ "; getline(cin, input); Rshellbase *base = new Rshellbase(input); base->Disintegrate(ea, con, com); //The precedence part int cnt = 0; int pl = 0; int pr = 0; int j = 0; while (com.at(j)->GetConnector()->GetSign() != '.') { while(ea.at(j)->getExe().at(0) == '(') { ea.at(j)->setExeL(); ea.at(j)->setLeftP(cnt); cnt++; pl++; } while(ea.at(j)->getExe().at(ea.at(j)->getExe().size() - 1) == ')') { ea.at(j)->setExeR(); cnt--; ea.at(j)->setRightP(cnt); pr++; } if(ea.at(j)->getArgu()!=""){ while(ea.at(j)->getArgu().at(ea.at(j)->getArgu().size() - 1) == ')') { ea.at(j)->setArgu(); cnt--; ea.at(j)->setRightP(cnt); pr++; } } j++; } while(ea.at(j)->getExe().at(0) == '(') { ea.at(j)->setExeL(); ea.at(j)->setLeftP(cnt); cnt++; pl++; } while(ea.at(j)->getExe().at(ea.at(j)->getExe().size() - 1) == ')') { ea.at(j)->setExeR(); cnt--; ea.at(j)->setRightP(cnt); pr++; } if(ea.at(j)->getArgu()!=""){ while(ea.at(j)->getArgu().at(ea.at(j)->getArgu().size() - 1) == ')') { ea.at(j)->setArgu(); cnt--; ea.at(j)->setRightP(cnt); pr++; } } bool parenStatus = true; if (pl != pr) { cout << "Your parentheses are wrong, please try to type again." << endl; parenStatus = false; } if (parenStatus) { //The execute part bool next = true; int i = 0; while (com.at(i)->GetConnector()->GetSign() != '.') { if(next){ if (ea.at(i)->getExe() == "exit") { status = false; break; //cout << "get here in while" << endl; //return 0; } else{ next = com.at(i)->Operate(); i++; } } else{ if(ea.at(i)->getLeftP().size() == 0){ if(com.at(i)->GetConnector()->GetSign() == '|' && com.at(i-1)->GetConnector()->GetSign() == '&'){ next = true; } if(com.at(i)->GetConnector()->GetSign() == '&' && com.at(i-1)->GetConnector()->GetSign() == '|'){ next = true; } if(com.at(i)->GetConnector()->GetSign() == ';' && com.at(i-1)->GetConnector()->GetSign() == '|'){ next = true; } if(com.at(i)->GetConnector()->GetSign() == ';' && com.at(i-1)->GetConnector()->GetSign() == '&'){ next = true; } i++; } else{ char firstCon = com.at(i-1)->GetConnector()->GetSign(); int flag = ea.at(i)->getLeftP().at(0); bool found = false; while(!found){ for(int p=0; p<ea.at(i)->getRightP().size(); p++){ if(ea.at(i)->getRightP().at(p) == flag){ found = true; break; } } if(!found){i++;} } char secondCon = com.at(i)->GetConnector()->GetSign(); if(firstCon == '|' && secondCon == '&'){ next = true; } if(firstCon == '&' && secondCon == '|'){ next = true; } if(firstCon == '&' && secondCon == ';'){ next = true; } if(firstCon == '|' && secondCon == ';'){ next = true; } i++; if(secondCon == '.'){ next = false; i--; } } } } if(next){ if (ea.at(i)->getExe() == "exit") { status = false; //cout << "get to the outside" << endl; //return 0; } else{ next = com.at(i)->Operate(); i++; } } } } exit(0); cout << " the end"<<endl; return 0; }
true
5879be766c101aed9b054118b72f6d645433e4c9
C++
emilianbold/netbeans-releases
/cnd.completion/test/unit/data/org/netbeans/modules/cnd/completion/cplusplus/hyperlink/TemplateSpecializationsTestCase/bug256700.cpp
UTF-8
1,324
2.609375
3
[]
no_license
namespace bug256700 { namespace some_ns256700 { template <class _Tp> struct _Nonconst_traits256700; template <class _Tp> struct _Nonconst_traits256700 { typedef _Tp value_type; typedef _Tp* pointer; typedef _Nonconst_traits256700<_Tp> _NonConstTraits; }; } #define DEFINE_PRIV_TRAITS \ namespace priv256700 { \ template <class _Tp> struct _MapTraitsT256700 ; \ template <class _Tp> struct _MapTraitsT256700 : public :: bug256700 :: some_ns256700 :: _Nonconst_traits256700 <_Tp> { \ typedef _MapTraitsT256700 <_Tp> _NonConstTraits; \ }; \ } DEFINE_PRIV_TRAITS struct AAA256700 { void foo(); }; template <typename Traits> struct MapBase256700 { typedef typename Traits::_NonConstTraits NonConstTraits; }; template <typename Value> struct Map256700 { typedef Value value_type; typedef typename priv256700::_MapTraitsT256700<value_type> _MapTraits; typedef MapBase256700<_MapTraits> RepType; }; int main256700() { Map256700<AAA256700>::RepType::NonConstTraits::value_type var; var.foo(); Map256700<AAA256700>::RepType::NonConstTraits::pointer ptr; ptr->foo(); return 0; } }
true
f100dadb1dffcff6e5f610c02c1a6d125ad6ec79
C++
sufyansalim/parallel_programming
/Threads/threads_mutex.cpp
UTF-8
808
3.65625
4
[]
no_license
//g++ threads_mutex.cpp -o threads_mutex.exe -std=c++11 #include <iostream> #include <thread> #include <mutex> using std::cout; using std::endl; using std::thread; using std::lock_guard; //Our lock at global scope std::mutex my_mutex; void print_func(int id){ //my_mutex.lock(); lock_guard<std::mutex> g(my_mutex); // safe way follows RAII -- Resource Allocation is Initialization cout<<"Printing from threads: " << id <<endl; //my_mutex.unlock(); }; //This function is the entrypoint for our thread int main(){ //Create 4 threads an call print function thread t0(print_func,0); thread t1(print_func,1); thread t2(print_func,2); thread t3(print_func,3); // Wait for the threads to finish t0.join(); t1.join(); t2.join(); t3.join(); return 0; }
true
8cceddaab97f5a771ee1147d262737d4e5ce692a
C++
sanaa-khan/covid-analysis
/Queue.h
UTF-8
2,582
3.8125
4
[ "MIT" ]
permissive
#pragma once #include <iostream> #include <string> using std::cout; using std::string; template <class DT> class Queue { template <class DT> struct node { DT data; node* next; }; node<DT>* front; node<DT>* rear; int size; public: Queue() : front(NULL), rear(NULL), size(0) {} ~Queue() { node<DT>* current = front; while (front != NULL) { current = front; front = front->next; delete current; } } void enqueue(const DT& newDataItem) { node<DT>* temp; temp = new node<DT>; temp->data = newDataItem; temp->next = NULL; if (isEmpty()) { front = temp; rear = temp; } else { rear->next = temp; rear = rear->next; } size++; } DT dequeue() { if (isEmpty()) return 0; DT val = front->data; node<DT>* temp; temp = front; front = front->next; delete temp; size--; return val; } void clear() { node<DT>* temp = front; while (temp != rear) { temp->data = -1; temp = temp->next; } size = 0; } bool isEmpty() const { if (!size) return true; return false; } void operator + (const DT& x) { this->enqueue(x); } DT operator --() { DT val = this->dequeue(); return val; } void display() { node<DT>* temp = front; while (temp != NULL) { cout << temp->data; temp = temp->next; } cout << "\n"; } int getLength() { return size; } int operation(char ch) { if (ch == 'E') { return (this->isEmpty()); } if (ch == 'C') { this->clear(); return 0; } if (ch == '#') return this->getLength(); if (ch == 'Q') exit(0); } void queueString(string str) { int spc = 0; // counting words (word = spc + 1) int len = 0; while (str[len] != '\0') { if (str[len] == 32) spc++; len++; } cout << "\n" << len << "\n"; Queue<char>* arr = new Queue<char>[spc + 1]; // no of words int index = 0; for (int i = 0; i < len; i++) { arr[index].enqueue(str[i]); if (str[i] == 32) index++; // moves to next queue when space is encountered } // displaying individually for (int i = 0; i < spc + 1; i++) arr[i].display(); cout << "\n"; // moving all queues into one queue index = 0; for (int i = 0; i < len; i++) { char ch = arr[index].dequeue(); this->enqueue(ch); if (ch == 32) index++; // moves to next queue when space is encountered } this->display(); } };
true
c7f04c0315d4db2df55945296efc44dd723e86f9
C++
Unatart/StegoMP3
/mp3_SMC/mp3_decoder.cpp
UTF-8
2,868
2.75
3
[]
no_license
#ifndef MP3_DECODER_CPP #define MP3_DECODER_CPP #include "mp3_decoder.h" void mp3_decoder::skip_byte(std::ifstream &in) { char bufbyte; try { in.get(bufbyte); } catch (std::istream::failure) { throw common_exception("File fail."); } } const std::string mp3_decoder::decode() { std::ifstream in(input_file, std::ios::in | std::ios::binary); std::vector <unsigned> bit_message; raw_header Header; for (unsigned k = 0; search_valid_header(in, Header); ++k) { if (k % sampling_frequency == 0) { header bufHeader(Header); unsigned to_skip = bufHeader.frame_size() + ((unsigned) bufHeader.crc_present()) * crc_bytes - 1; for (unsigned i = 0; i < to_skip; ++i) { skip_byte(in); } char coding_byte = 0; try { in.get(coding_byte); } catch (std::istream::failure) { throw common_exception("File fail."); } unsigned variable = (unsigned) ((coding_byte & 0x01) == 0x01); bit_message.push_back(variable); if (bit_message.size() % B == 0) { bool is_end_of_message = true; for (unsigned i = 0; i < B; ++i) { if (bit_message[bit_message.size() - 1 - i] == 1) { is_end_of_message = false; break; } } if (is_end_of_message) { break; } } } } std::string message = create_message(bit_message); return message; } char mp3_decoder::create_symb(std::vector<unsigned>& code){ unsigned result = 0; std::reverse(code.begin(), code.end()); for (unsigned i = 0; i < code.size(); ++i) { result += code[i] * pow(2, i); } char result_symb = result; return result_symb; } std::string mp3_decoder::create_message(std::vector<unsigned>& code_message){ std::string str_message; for (unsigned i = 0; i < code_message.size() - B; i += B) { std::vector <unsigned> buf; for (unsigned j = 0; j < B; ++j) { buf.push_back(code_message[i + j]); } char message_symb = create_symb(buf); str_message.push_back(message_symb); } return str_message; } bool mp3_decoder::search_valid_header(std::ifstream &in, raw_header& header){ in >> header; while (!header.is_valid_header() && !in.fail()) { try { header.read_byte(in); } catch (std::istream::failure) { throw common_exception("File fail."); } } return !in.fail(); } #endif // MP3_DECODER_CPP
true
acc9e1b11d5ce2e147d05b9a6b60c867e8fd07cf
C++
bertobot/MyThread
/thread.h
UTF-8
1,165
2.515625
3
[]
no_license
///////////////////////////////////////////////// // thread.h // robert beatty // funkejunx@aim.com // // this code is GPL'd // #ifndef __thread_h_ #define __thread_h_ ///////////////////////////////////////////////// #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include "mutex.h" ///////////////////////////////////////////////// class thread { private: volatile int return_code; volatile bool running; volatile bool stopped; pthread_t actualThread; pthread_attr_t attr; mutex mut; static void * run_func(void*); public: thread(); void setstate(int); void start(); void stop(); virtual void run() = 0; int join(); int forceQuit(); void exit(); int cancel(); void cleanup(); // TODO: fix or remove. do not use. int destroy(); int getReturnCode() { return return_code; } bool isRunning() { return running && !stopped; } bool isStopped() { return !running && stopped; } void enableCancelState(); void disableCancelState(); void setCancelTypeAsync(); void setCancelTypeDeferred(); virtual ~thread(); }; ///////////////////////////////////////////////// #endif
true
3885894371a3ab440fe6bb58fa8cd08ad9aac736
C++
townboy/acm-algorithm
/HDOJcode/2082 2011-11-17 16 02 30.cpp
UTF-8
954
2.5625
3
[]
no_license
****************************** Author : townboy Submit time : 2011-11-17 16:02:30 Judge Status : Accepted HDOJ Runid : 5004143 Problem id : 2082 Exe.time : 421MS Exe.memory : 208K https://github.com/townboy ****************************** #include<stdio.h> int a[30],ji; void js(int x,int num,int ge) { int i; if(x+ge*num<=50) { if(ge!=0) { ji++; } if(num-1>=1) { for(i=0;i<=a[num-1];i++) { js(x+ge*num,num-1,i); } } } } int main(void) { int num,i,f; scanf("%d",&num); for(i=0;i<num;i++) { ji=0; for(f=1;f<=26;f++) { scanf("%d",&a[f]); } for(f=0;f<=a[26];f++) { js(0,26,f); } printf("%d\n",ji); } return 0; }
true
b761dfaacfe64fc5303c1e3cf6ca05846f24f893
C++
skelleher/CandyCritters
/source/common/Color.cpp
UTF-8
2,792
3.140625
3
[ "BSD-3-Clause" ]
permissive
/* * Color.cpp * Critters * * Created by Sean Kelleher on 9/4/10. * Copyright 2010 Sean Kelleher. All rights reserved. * */ #include "Color.hpp" namespace Z { Color::Color() { Color( 1.0f, 1.0f, 1.0f, 1.0f); } /* Color::Color( BYTE r, BYTE g, BYTE b, BYTE a ) { bytes.r = r; bytes.g = g; bytes.b = b; bytes.a = a; floats.r = (float)(r/255.0); floats.g = (float)(g/255.0); floats.b = (float)(b/255.0); floats.a = (float)(a/255.0); } */ Color::Color( float r, float g, float b, float a ) { floats.r = r; floats.g = g; floats.b = b; floats.a = a; /* bytes.r = (BYTE)(r * 255.0); bytes.g = (BYTE)(g * 255.0); bytes.b = (BYTE)(b * 255.0); bytes.a = (BYTE)(a * 255.0); */ } Color::Color( vec4& v ) { floats.r = v.x; floats.g = v.y; floats.b = v.z; floats.a = v.w; /* bytes.r = (BYTE)(floats.r * 255.0); bytes.g = (BYTE)(floats.g * 255.0); bytes.b = (BYTE)(floats.b * 255.0); bytes.a = (BYTE)(floats.a * 255.0); */ } Color::Color( UINT32 rgba ) { floats.r = (rgba & 0xFF000000) >> 24; floats.g = (rgba & 0x00FF0000) >> 16; floats.b = (rgba & 0x0000FF00) >> 8; floats.a = (rgba & 0x000000FF); } Color::operator vec4() const { return vec4( floats.r, floats.g, floats.b, floats.a ); } /* Color::operator UINT32() const { return bytes.r << 24 | bytes.g << 16 | bytes.b << 8 | bytes.a; } */ Color::operator UINT32() const { // return bytes.a << 24 | bytes.b << 16 | bytes.g << 8 | bytes.r; return (BYTE)(floats.a * 255.0) << 24 | (BYTE)(floats.b * 255.0) << 16 | (BYTE)(floats.g * 255.0) << 8 | (BYTE)(floats.r * 255.0); } Color& Color::operator*=( float f ) { floats.r *= f; floats.g *= f; floats.b *= f; floats.a *= f; return *this; } Color& Color::operator+=( float f ) { floats.r += f; floats.g += f; floats.b += f; floats.a += f; return *this; } Color& Color::operator+=( const Color& rhs ) { floats.r += rhs.floats.r; floats.g += rhs.floats.g; floats.b += rhs.floats.b; floats.a += rhs.floats.a; return *this; } Color Color::operator+(const Color& rhs) const { Color rval; rval.floats.r = floats.r + rhs.floats.r; rval.floats.g = floats.g + rhs.floats.g; rval.floats.b = floats.b + rhs.floats.b; rval.floats.a = floats.a + rhs.floats.a; return rval; } Color Color::operator-(const Color& rhs) const { Color rval; rval.floats.r = floats.r - rhs.floats.r; rval.floats.g = floats.g - rhs.floats.g; rval.floats.b = floats.b - rhs.floats.b; rval.floats.a = floats.a - rhs.floats.a; return rval; } } // END namespace Z
true
d912fdf02a966094ca5dd9d27d9c3bf72f2011cf
C++
mdzobayer/Problem-Solving
/Codeforces/39 C.cpp
UTF-8
503
2.578125
3
[]
no_license
#include <bits/stdc++.h> #define LLI long long int using namespace std; bool isPosible(string &str, LLI i) { LLI i; bool use[150]; memset(use, false, sizeof(use)); for (i = 0; i < str.size(); ++i) { if (use[str[i - 1]] == false && str[i] > 'a' ) return false; if (use[str[i]] == false) { use[str[i]] = true; } } } int main() { string s; cin >> s; long long int i; for (i = 0; i < s.size(); ++i) { } return (0); }
true
40196356260c5a87b02514ac1f4934930429bdb3
C++
sandeeppoudel/cplusplusBucky
/AccessthroughPointer.cpp
UTF-8
273
2.53125
3
[]
no_license
#include "AccessthroughPointer.h" #include<iostream> using namespace std; AccessthroughPointer::AccessthroughPointer() // :: is binary scope resolution operator. { } void AccessthroughPointer::PrintoutSomething() { cout << "nepal is a beautiful country" << endl; }
true
f5c5a0cfcb2044833e020d3bd7f41623a028cac3
C++
jhaslowh/DG-Spotlight
/DG_Spotlight/Build/shader_vertex.cpp
UTF-8
1,078
2.796875
3
[]
no_license
#version 100 precision highp float; // Inputs in vec4 position; // Position handle in vec3 aNormal; // Normal handle in vec2 aTexCoordinate; // Texture coord handle uniform vec3 cam; // Camera location // Matrix's uniform mat4 modelm; // Model Matrix handle uniform mat4 viewm; // View Matrix handle uniform mat4 projm; // Projection Matrix handle uniform mat3 normm; // Normal Matrix handle // Output to fragment varying vec2 vTexCoord; // Texture coord handle that both shaders use varying vec3 vNormal; // Normal to send to texture varying vec3 vEye; // Eye vector varying vec3 vLightDirec; // Light direction vector varying vec4 vpos; void main() { // Vertex position in world space vec4 pos = modelm * position; vpos = pos; // Compute normal vNormal = normalize(normm * aNormal); // Compute eye value vEye = cam - pos.xyz; // Send texture cord vTexCoord = aTexCoordinate; // Set final position gl_Position = projm * viewm * modelm * position; }
true
ba3d73e4455971217fd9a43c77e069aec6ea28ee
C++
TaoSP/Professional
/LeetCode/h04_strTest.cpp
UTF-8
3,747
3.359375
3
[]
no_license
/****************************************************************************** * h04_strTest.cpp * Author : Huangtao * Version: V1.0.0 2020-02-06 Create * Description: 字符串相关 ******************************************************************************/ #include <iostream> #include <sstream> #include <string> #include <vector> #include <algorithm> #include <bitset> #include <map> using namespace std; // 字符串分割函数, str为待分割的字符串, pattern为任意分割符 vector<string> split(string str, string & pattern) { vector<string> v; if(pattern.empty()) return v; int start = 0; int index = str.find(pattern, start); // find_first_of while(index != string::npos) { if(index != start) v.push_back(str.substr(start, index - start)); start = index + 1; index = str.find_first_of(pattern, start); } if(!str.substr(start).empty()) v.push_back(str.substr(start)); return v; } bool isBigger(const pair<char, int> & p1, const pair<char, int> & p2) { return p1.second > p2.second; } int main() { /* string str; while(cin >> str) { stringstream ss(str); int num; ss >> hex >> num; // 16进制转10进制 cout << num << endl; } */ /* int a[128] = {0}; string str; getline(cin, str); for(int i=0;i<str.size();i++) a[str[i]] = 1; int total = 0; for(int i=0;i<128;i++) total += a[i]; cout << total << endl; // 字符个数统计 */ /* string pattern(" "); string in; getline(cin, in); vector<string> v = split(in, pattern); // // 字符串分割 for(auto it = v.begin(); it != v.end(); it++) cout << *it << " " << endl; */ /* vector<string> v; string in; int n; cin >> n; while(n-- && cin >> in) v.push_back(in); sort(v.begin(), v.end()); // 字符串按照字典序排列 for(auto it = v.begin(); it != v.end(); it++) cout << *it << endl; */ /* // 密码验证 // 长度超过8位, 包括大小写字母.数字.其它符号,以上四种至少三种 // 不能有相同长度超2的子串重复 string str; while(cin >> str) { bitset<8> bits = 0; bool error = false; for(auto c : str) { if(c >= '0' && c <= '9') bits |= 0x1; else if(c >= 'A' && c <= 'Z') bits |= 0x2; else if(c >= 'a' && c <= 'z') bits |= 0x4; else bits |= 0x8; } if(str.size() <= 8 || bits.count() < 3) error = true; if(!error) for(int i = 0; i <= str.size() - 6; i++) // 寻找重复子串 for(int j = i+3; j < str.size(); j++) if(str[i] == str[j] && str[i+1] == str[j+1] && str[i+2] == str[j+2]) error = true; if(error) cout << "NG" << endl; else cout << "OK" << endl; } */ // 字符统计:如果个数相同,则按照ASII码由小到大排序输出 string str; while(getline(cin, str)) { map<char, int> mp; for(auto a : str) if((a>='0' && a<='9') || (a>='a' && a<='z') || a == ' ' || (a>='A' && a<='Z')) mp[a]++; vector<pair<char, int>> v(mp.begin(), mp.end()); // 一对值 stable_sort(v.begin(), v.end(), isBigger); // 稳定排序 for(auto a : v) cout << a.first; cout << endl; } return 0; }
true
942d0e96876cb6fd2e52fa9be5f170a2fee98036
C++
k124k3n/competitive-programming-answer
/toki/[Versi Lama] Training Gate TOKI Learning Center/Bab 3. Ad Hoc/3C. Teori Bilangan/A.cpp
UTF-8
307
2.890625
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> int gcd(int a, int b){ if(a == 0){ return b; } return gcd(b%a, a); } int main(int argc, const char *argv[]) { int n, a, b; std::cin>>n; for (int i = 0; i < n; i++) { std::cin>>a>>b; std::cout<<gcd(a, b)<<'\n'; } return 0; }
true
efc2d1eb7913a808d733de8d3a987766258cae36
C++
uKryuchenia/DoodleJump
/src/CompressionSpring.cpp
UTF-8
759
2.8125
3
[]
no_license
#include "CompressionSpring.h" CompressionSpring::CompressionSpring(Board &b) : board(b) { Texture1.loadFromFile("Images/Spring.png"); compressionSpring.setTexture(Texture1); } void CompressionSpring::newSpring() { platforms=board.getResetPlat(); z=1; x=board.platformsX(platforms)+10+rand()%60; y=board.platformsY(platforms)-16; //na przyklad 7-wysokosc spring } void CompressionSpring::motion(int xy) { y+=xy; } int CompressionSpring::getSpringX() { return x; } int CompressionSpring::getSpringY() { return y; } void CompressionSpring::restart() { z=0; } void CompressionSpring::draw(sf::RenderWindow &window) { if(z){ compressionSpring.setPosition(x,y); window.draw(compressionSpring); } }
true
1169d66bb5db6ee7904c68b20a841ca2852dde8b
C++
PR1V4T3/SPMS-v1.0
/main.cpp
UTF-8
13,349
3.03125
3
[ "MIT" ]
permissive
#include <iostream> #include <stdlib.h> #include <fstream> #include <ctime> using namespace std; /* COMMENTS & OTHERS ////// IMPORTANT ///////////////////////////////////////////////////////////////////////////////////// // // // - zle ustawione seekg uszkadza plik, wychodzenie poza istniejącą liczbe znaków jest zabronione // // // ////////////////////////////////////////////////////////////////////////////////////////////////////// */ void anyKey(){ // DONE char anyKey; cout << "Press any key and enter to continue. \n"; cin >> anyKey; } bool checkIsExist(string filePath){ // DONE fstream checkFile(filePath.c_str()); return checkFile.is_open(); } bool configFileStatus(bool isShowInformation = false){ // DONE bool status = checkIsExist("APPLICATION_CONFIG.txt"); if(isShowInformation == true){ cout << " __________________________________________________________ \n"; cout << "| |\n"; if(status == true){ cout << "| - APPLICATION_CONFIG.txt || STATUS: GOOD |\n"; }else cout << "| - APPLICATION_CONFIG.txt || STATUS: BAD |\n"; cout << "|__________________________________________________________|\n"; } return status; } bool fileStatus(bool isShowInformation = false){ // DONE bool status = checkIsExist("TEMPLATE.txt") && checkIsExist("TEMPORARY.txt") && checkIsExist("PARSER_CONFIG.txt") && configFileStatus(); if(isShowInformation == true){ configFileStatus(true); cout << " __________________________________________________________ \n"; cout << "| |\n"; if(checkIsExist("TEMPLATE.txt") == true){ cout << "| - TEMPLATE.txt || STATUS: GOOD |\n"; }else cout << "| - TEMPLATE.txt || STATUS: BAD |\n"; if(checkIsExist("TEMPORARY.txt") == true){ cout << "| - TEMPORARY.txt || STATUS: GOOD |\n"; }else cout << "| - TEMPORARY.txt || STATUS: BAD |\n"; if(checkIsExist("PARSER_CONFIG.txt") == true){ cout << "| - PARSER_CONFIG.txt || STATUS: GOOD |\n"; }else cout << "| - PARSER_CONFIG.txt || STATUS: BAD |\n"; if(status == true){ cout << "| |\n"; cout << "| * nothing has changed |\n"; } cout << "|__________________________________________________________|\n"; } return status; } const char *parser(string filePath, string valueSymbol, bool isShow = false){ // DONE fstream textFile; textFile.open(filePath.c_str()); bool showThis = false; bool endLoop = false; bool isFound = false; string value; string load; int fileLine = 0; do{ fileLine++; getline(textFile, load); if(load == valueSymbol){ endLoop = true; isFound = true; getline(textFile, value); if(isShow == true) cout << value << " (FOUND IN LINE: " << fileLine << ")" << endl; }else isFound = false; if(textFile.eof() == true){ endLoop = true; cout << "End of file reached. \n"; if(isFound == false) cout << "Value symbol hasn't found."; } }while(endLoop == false); textFile.close(); return value.c_str(); } void overwriteFiles(string systemCommand = "gedit"){ // DONE fstream APPLICATION_CONFIG; fstream TEMPLATE; fstream TEMPORARY; fstream PARSER_CONFIG; APPLICATION_CONFIG.open ("APPLICATION_CONFIG.txt" ); TEMPLATE.open ("TEMPLATE.txt" ); TEMPORARY.open ("TEMPORARY.txt" ); PARSER_CONFIG.open ("PARSER_CONFIG.txt" ); if(APPLICATION_CONFIG.is_open() == false ){ systemCommand += " APPLICATION_CONFIG.txt"; system( systemCommand.c_str() ); } if(TEMPLATE.is_open() == false ){ systemCommand += " TEMPLATE.txt"; system( systemCommand.c_str() ); } if(TEMPORARY.is_open() == false ){ systemCommand += " TEMPORARY.txt"; system( systemCommand.c_str() ); } if(PARSER_CONFIG.is_open() == false ){ systemCommand += " PARSER_CONFIG.txt"; system( systemCommand.c_str() ); } APPLICATION_CONFIG.close(); TEMPLATE.close(); TEMPORARY.close(); PARSER_CONFIG.close(); } void repairApplication(){ // DONE bool endLoop = false; char pick; do{ fileStatus(true); if(fileStatus() == false){ cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| Application can't open important files so, app will |\n"; cout << "| overwrite them. The app will use (for repair): |\n"; cout << "|__________________________________________________________|\n"; cout << " \n"; cout << " "<< parser("CONFIG.txt", "REPAIRING_APPLICATION", true) <<"\n"; cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| Are you want continue? [y]/[n] |\n"; cout << "|__________________________________________________________|\n"; cout << " \n"; cin >> pick; if(pick == 'y') { overwriteFiles( parser("CONFIG.txt", "REPAIRING_APPLICATION", false) ); // downloading name of application // from config file cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| Please, now exit and launch application again. |\n"; cout << "|__________________________________________________________|\n"; } } endLoop = fileStatus(); if(pick == 'n') endLoop = true; }while(endLoop == false); anyKey(); } void textService(string filePath, string mode = "txt"){ // DONE if(fileStatus() == true){ fstream textFile; string textShow = ""; textFile.open(filePath.c_str()); if(mode == "txt"){ do{ getline(textFile, textShow); cout << textShow << endl; }while(textFile.eof() == false); } if(mode == "html"){ do{ getline(textFile, textShow); cout << textShow << endl; }while(textShow != "<-- EOF !-->"); } textFile.close(); }else repairApplication(); } void theLatestPost(){ // DONE // w getline, enter jest liczony jako jeden znak cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| Your last generated HTML code will show in the bottom. |\n"; cout << "|__________________________________________________________|\n\n"; cout << "============================================================\n"; textService( parser("APPLICATION_CONFIG.txt", "TEMPORARY_HTML_FILE_PATH", false) ); cout << "============================================================ \n"; anyKey(); } void editor(){ // TODO system("clear"); cout << "Editor is running. "; anyKey(); } void temporaryEditor(){ // TODO } void runEditor(){ // DONE if(fileStatus() == true){ cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| File Status: files has checked and ready to work. |\n"; cout << "|__________________________________________________________|\n\n"; cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| Do you want run Editor? [y]/[n] |\n"; cout << "|__________________________________________________________|\n"; cout << "\n"; char choose; cin >> choose; switch(choose){ case 'y': editor(); break; case 'n': break; default: break; } }else if(fileStatus() == false) repairApplication(); } const char *dateAndTime(string mode = "all"){ // TODO: Downloading from system, hard to do string date; string time; cout << "\nTIME :"; cin >> time; cout << "\nDATE: "; cin >> date; // VERY TO DO: POBIERANIE DATY Z SYSTEMU I ZWRACANIE JEJ Z FUNKCJI if(mode == "date") return date.c_str(); if(mode == "time") return time.c_str(); } void showConfig(){ // TODO int pick; bool endLoop = false; do{ cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| All settings will show in there. |\n"; cout << "| |\n"; cout << "| [1] APP / [2] PARSER / [3] EXIT TO MAIN MENU |\n"; cout << "|__________________________________________________________|\n"; cin >> pick; system("clear"); switch(pick){ case 1: cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| APPLICATION SETTINGS: |\n"; cout << "|__________________________________________________________|\n"; cout << " \n"; textService("APPLICATION_CONFIG.txt"); break; case 2: cout << " __________________________________________________________ \n"; cout << "| |\n"; cout << "| PARSER SETTINGS: |\n"; cout << "|__________________________________________________________|\n"; cout << " \n"; textService("PARSER_CONFIG.txt"); break; case 3: cout << "Exit.\n"; endLoop = true; break; default: cout << "Wrong key.\n"; break; } }while(endLoop == false); } void mainMenu(){ // DONE char pick; bool endLoop = false; do{ system("clear"); textService("banner.txt"); textService("updates.txt"); textService("menu.txt"); cin >> pick; switch(pick){ case '0': system("clear"); showConfig(); break; case '1': system("clear"); runEditor(); break; case '2': system("clear"); theLatestPost(); break; case '3': system("clear"); repairApplication(); break; case '4': system("clear"); textService("how_to.txt"); anyKey(); break; case '5': system("clear"); endLoop = true; break; default: break; } }while(endLoop == false); } void runApplication(){ if(fileStatus() == true){ mainMenu(); }else if(fileStatus() == false) repairApplication(); } int main(){ if(configFileStatus() == true) runApplication(); return 0; }
true
5c2362f8623cd26dc67389b3840988a71c886210
C++
Aman-Dubey/InterviewBitSolutions
/Tree Data Structure/Path_Sum.cpp
UTF-8
399
2.734375
3
[]
no_license
int t=0; void findans(TreeNode *A,int B,int sum) { if(A->left==NULL && A->right==NULL && sum==B) { t=1; return; } if(A->left) findans(A->left,B,sum+A->left->val); if(A->right) findans(A->right,B,sum+A->right->val); return; } int Solution::hasPathSum(TreeNode* A, int B) { t=0; if(!A || B==0) return 0; findans(A,B,A->val); return t; }
true
44d8109e89d51b03c1af330f27ffbe8835c3e2db
C++
jackflower/SCInfor
/SCInfor/source/Rendering/Animations/Animation.h
UTF-8
2,015
3.0625
3
[]
no_license
// ______________________________________ // | Animation.h - class definition | // | Jack Flower - March 2012 | // |______________________________________| // #ifndef H_ANIMATION_JACK #define H_ANIMATION_JACK #include <vector> #include "TimedAnimationFrame.h" #include "../../RTTI/RTTI.h" namespace rendering { namespace animation { /// ///Klasa reprezentuje pojemnik na animacje /// class Animation { RTTI_DECL; public: /// ///Konstruktor domyślny /// Animation(); /// ///Konstruktor kopiujący /// ///@param AnimationCopy - parametr - obiekt klasy Animation /// Animation(const Animation & AnimationCopy); /// ///Konstruktor przenoszący /// ///@param other = referencja do r-wartości /// Animation(Animation && other); /// ///Przeciążony operator przypisania kopiowania /// ///@param copy - stała referencja na obiekt klasy Animation /// Animation & operator=(const Animation & copy); /// ///Przeciążony operator przypisania przenoszenia /// ///@param other - referencja do r-wartości /// Animation & operator=(Animation && other); /// ///Destruktor /// ~Animation(); /// ///Metoda zwraca typ obiektu /RTTI/ /// const std::string getType() const; /// ///Metoda zwraca referencję na nazwę animacji /// const std::string & getAnimationName() const; /// ///Metoda ustawia na nazwę animacji /// ///@param name - nazwa animacji - stała referencja na obiekt klasy std::string /// const void setAnimationName(const std::string & anim_name); /// ///Metoda zwraca czas równy całkowitej długości trwania wszystkich klatek animacji (kumulacja) /// float totalLength(); private: std::string m_animation_name; //nazwa animacji public: std::vector<TimedAnimationFrame> m_frames; //wektor przechowujący klatki animacji }; }//namespace animation }//namespace rendering #endif//H_ANIMATION_JACK
true
d3ca5a593a529777618fd72761fd6046977dba01
C++
siemens/drace
/drace-client/include/module/Metadata.h
UTF-8
3,032
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "CC0-1.0" ]
permissive
#pragma once /* * DRace, a dynamic data race detector * * Copyright 2018 Siemens AG * * Authors: * Felix Moessbauer <felix.moessbauer@siemens.com> * * SPDX-License-Identifier: MIT */ #include <dr_api.h> #include "../globals.h" #include "InstrFlags.h" #include "ModTypeFlags.h" namespace drace { namespace module { /// Encapsulates and enriches a dynamorio module_data_t struct class Metadata { public: using INSTR_FLAGS = drace::module::INSTR_FLAGS; using MOD_TYPE_FLAGS = drace::module::MOD_TYPE_FLAGS; app_pc base; app_pc end; bool loaded; INSTR_FLAGS instrument; MOD_TYPE_FLAGS modtype{MOD_TYPE_FLAGS::UNKNOWN}; module_data_t *info{nullptr}; bool debug_info; private: /** * \brief Determines if the module is a managed-code module using the PE * header */ void tag_module(); public: Metadata(app_pc mbase, app_pc mend, bool mloaded = true, bool debug_info = false) : base(mbase), end(mend), loaded(mloaded), instrument(INSTR_FLAGS::NONE), debug_info(debug_info) {} ~Metadata() { if (info != nullptr) { dr_free_module_data(info); info = nullptr; } } /// Copy constructor, duplicates dr module data Metadata(const Metadata &other) : base(other.base), end(other.end), loaded(other.loaded), instrument(other.instrument), modtype(other.modtype), debug_info(other.debug_info) { info = dr_copy_module_data(other.info); } /// Move constructor, moves dr module data Metadata(Metadata &&other) : base(other.base), end(other.end), loaded(other.loaded), instrument(other.instrument), info(other.info), modtype(other.modtype), debug_info(other.debug_info) { other.info = nullptr; } void set_info(const module_data_t *mod) { info = dr_copy_module_data(mod); tag_module(); } inline Metadata &operator=(const Metadata &other) { if (this == &other) return *this; dr_free_module_data(info); base = other.base; end = other.end; loaded = other.loaded; instrument = other.instrument; info = dr_copy_module_data(other.info); modtype = other.modtype; debug_info = other.debug_info; return *this; } inline Metadata &operator=(Metadata &&other) { if (this == &other) return *this; dr_free_module_data(info); base = other.base; end = other.end; loaded = other.loaded; instrument = other.instrument; info = other.info; modtype = other.modtype; debug_info = other.debug_info; other.info = nullptr; return *this; } inline bool operator==(const Metadata &other) const { return (base == other.base); } inline bool operator!=(const Metadata &other) const { return !(base == other.base); } inline bool operator<(const Metadata &other) const { return (base < other.base); } inline bool operator>(const Metadata &other) const { return (base > other.base); } }; } // namespace module } // namespace drace
true
1bec12793b22d96980511ff4ca139ea2237695d0
C++
AnandEmbold/upcxx_1
/example/prog-guide/view-accumulate.cpp
UTF-8
1,680
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause-LBNL" ]
permissive
#include <upcxx/upcxx.hpp> #include <cassert> //SNIPPET upcxx::future<> add_accumulate(upcxx::global_ptr<double> remote_dst, double *buf, std::size_t buf_len) { return upcxx::rpc(remote_dst.where(), [](const upcxx::global_ptr<double>& dst, const upcxx::view<double>& buf_in_rpc) { // Traverse `buf_in_rpc` like a container, adding each element to the // corresponding element in dst. Views fulfill most of the container // contract: begin, end, size, and if the element type is trivial, even operator[]. double *local_dst = dst.local(); std::size_t index = 0; for(double x : buf_in_rpc) { local_dst[index++] += x; } }, remote_dst, upcxx::make_view(buf, buf + buf_len)); } //SNIPPET int main() { upcxx::init(); const int nranks = upcxx::rank_n(); const int me = upcxx::rank_me(); const int next = (me + 1) % nranks; const int prev = (me + nranks - 1) % nranks; int N = 1024; double *incr = new double[N]; upcxx::global_ptr<double> recv_buff = upcxx::new_array<double>(N); assert(incr && recv_buff); memset(recv_buff.local(), 0x00, N * sizeof(double)); for (int i = 0; i < N; i++) { incr[i] = me; } upcxx::dist_object<upcxx::global_ptr<double>> dobj(recv_buff); upcxx::global_ptr<double> target = dobj.fetch(next).wait(); add_accumulate(target, incr, N).wait(); upcxx::barrier(); for (int i = 0; i < N; i++) { assert(recv_buff.local()[i] == prev); } upcxx::barrier(); if(upcxx::rank_me() == 0) std::cout << "SUCCESS" << std::endl; delete[] incr; upcxx::delete_array(recv_buff); upcxx::finalize(); return 0; }
true
311e3abf7bd71d7a19e8635361fa3819de912b1d
C++
HannahJHan/BlueNoiseSampling
/wei-noise-master/11-DiffSamp/src/code/Synthesis/WhiteNoise.cpp
UTF-8
508
2.625
3
[ "MIT" ]
permissive
/* WhiteNoise.cpp Li-Yi Wei 09/01/2010 */ #include "WhiteNoise.hpp" #include "Exception.hpp" WhiteNoise::WhiteNoise(const vector<float> & domain_size): _domain_size(domain_size) { // nothing else to do } WhiteNoise::~WhiteNoise(void) { // nothing else to do } int WhiteNoise::Get(Sample & output) const { throw Exception("WhiteNoise::Get(): shouldn't be called"); return 0; } int WhiteNoise::Set(const vector<float> & domain_size) { _domain_size = domain_size; return 1; }
true
e904c2716a29758542eb61290c6ca577ce2b3032
C++
homuwell/Algorithms
/1sem/lab3/classes/Tree.cpp
UTF-8
4,934
3.34375
3
[]
no_license
#include "../headers/Tree.h" Tree::Tree() { head = nullptr; }; bool Tree::contains(int value) { Node *tmp_ptr = head; while (tmp_ptr != nullptr && tmp_ptr->key != value) { if (tmp_ptr->key > value) { tmp_ptr = tmp_ptr->left; } else { tmp_ptr = tmp_ptr->right; } } return tmp_ptr != nullptr; }; void Tree::insert(int value) { if (head == nullptr) { Node *elem = new Node; elem->left = nullptr; elem->right = nullptr; elem->key = value; head = elem; } else { Node *tmp_ptr = head; while (tmp_ptr != nullptr && tmp_ptr->key != value) { if (tmp_ptr->key < value && tmp_ptr->right != nullptr) { tmp_ptr = tmp_ptr->right; } else if (tmp_ptr->key > value && tmp_ptr->left != nullptr) { tmp_ptr = tmp_ptr->left; } else { Node *elem = new Node; elem->key = value; elem->right = nullptr; elem->left = nullptr; if (tmp_ptr->key < value) { tmp_ptr->right = elem; tmp_ptr = elem; } else { tmp_ptr->left = elem; tmp_ptr = elem; } } } } } void Tree::remove(int value) { if (!contains(value)) { throw out_of_range("Tree doesnt contain deleted element"); } if (!head) { throw out_of_range("Three is empty"); } Node *del_element = head; Node *del_parent = head; while (del_element->key != value) { if (del_element->key > value) { del_parent = del_element; del_element = del_element->left; } else { del_parent = del_element; del_element = del_element->right; } } if (del_element->left == nullptr && del_element->right == nullptr) { del_parent->left == del_element ? del_parent->left = nullptr : del_parent->right = nullptr; delete del_element; } else if (del_element->left != nullptr && del_element->right != nullptr) { if (del_element->left) { Node *tmp_ptr = del_element->left; Node *parent = del_element; while (tmp_ptr->right != nullptr) { parent = tmp_ptr; tmp_ptr = tmp_ptr->right; } del_element->key = tmp_ptr->key; parent->left = nullptr; delete tmp_ptr; } else { Node *tmp_ptr = del_element->right; Node *parent = del_element; while (tmp_ptr->left != nullptr) { parent = tmp_ptr; tmp_ptr = tmp_ptr->left; } del_element->key = tmp_ptr->key; parent->right = nullptr; delete tmp_ptr; } } else { if (del_element->right) { del_parent->right == del_element ? del_parent->right = del_element->right : del_parent->left = del_element->right; delete del_element; } else { del_parent->right == del_element ? del_parent->right = del_element->left : del_parent->left = del_element->left; delete del_element; } } } void Tree::BFT_Iterator::push(Node *value) { queue *elem = new queue; elem->data = value; elem->next = nullptr; if (headq == nullptr) { headq = elem; headq->next = nullptr; last = elem; } else { last->next = elem; last = last->next; } } void Tree::BFT_Iterator::pop() { queue *tmp_ptr = headq->next; headq->next = nullptr; delete headq; headq = tmp_ptr; } int Tree::BFT_Iterator::next() { curr = headq->data; int rmbr_elem = headq->data->key; pop(); if (curr->right) { push(curr->left); } if (curr->right) { push(curr->right); } return rmbr_elem; } Iterator *Tree::create_BFT_Iterator(Node *elm) { return new BFT_Iterator(elm); } bool Tree::BFT_Iterator::has_next() { return headq != nullptr; } void Tree::DFT_Iterator::push(Node *value) { stack *elem = new stack; elem->data = value; if (top == nullptr) { top = elem; top->prev = nullptr; } else { elem->prev = top; top = elem; } } void Tree::DFT_Iterator::pop() { stack *tmp_ptr = top; Node *rmbr_data = top->data; top = tmp_ptr->prev; tmp_ptr->prev = nullptr; delete tmp_ptr; } bool Tree::DFT_Iterator::has_next() { return top != nullptr; } int Tree::DFT_Iterator::next() { int rmbr_elem; if (!has_next()) { throw out_of_range("Iterator out of range"); } curr = top->data; rmbr_elem = top->data->key; pop(); if (curr->right) { push(curr->right); } if (curr->left) { push(curr->left); } return rmbr_elem; } Iterator *Tree::create_DFT_Iterator(Node *elm) { return new DFT_Iterator(elm); } void Tree::print(Node *elem, string str, string mod) { if (elem == head) { cout << +"+-" << elem->key << endl; } else { cout << str + mod << elem->key << endl; } str += "| "; if (elem->left) { print(elem->left, str, "L-"); } if (elem->right) { print(elem->right, str, "R-"); }; } void Tree::del(Node *&elem) { if (elem == nullptr) { return; } if (elem->left) { del(elem->left); } if (elem->right) { del(elem->right); } delete elem; } Tree::~Tree() { del(head); }
true
b67a826f63c3110d7ca081fb2b8e9aa868be33de
C++
Leacyn/PJSDV-A2
/Code/RaspberryPi/Final/main.cpp
UTF-8
616
2.75
3
[]
no_license
/*----------------------------------- Main definition version: 1.0 contributors: Stijn van Es 17018498 ----------------------------------*/ #include "Domotica.h" /*Define SQL login data*/ #define DBPATH "tcp://127.0.0.1:3306" #define USER "editor" #define PASSWD "100%Domotics" #define DB "domotics" /*start setup and loop 1. The main program starts with the setup 2. Loop runs continiously Both defined in Domotica */ int main(int argc, char** argv){ Domotica dom(DBPATH, USER, PASSWD, DB);/*Create 'Domotica' object and send mySQL login data*/ if(dom.setup()) return dom.loop(); else return 0; }
true
8a241d84944be29fab68f1ef0967250c03809dd9
C++
changyuhang/ntoucs2b
/實習課/12/12/main.cpp
UTF-8
3,320
3.171875
3
[]
no_license
#include "mystring.h" using namespace std; int _total_MyString = 0; void main() { ///////////////////////////////////////////////////////// cout << "Total_MyString is: " << MyString::total_MyString() << endl; MyString str1("String"), str2("Test String 2"), str3(str1); cout << "str1 is: " << str1 << endl; cout << "str2 is: " << str2 << endl; cout << "str3 is: " << str3 << endl; cout << "Total_MyString is: " << MyString::total_MyString() << endl; ///////////////////////////////////////////////////////// cout << "Give one word " << endl; cin >> str1; // from stdin "this is a test line" cout << "str1 is: " << str1 << endl; ///////////////////////////////////////////////////////// str2 = str1; cout << "str2 is: " << str2 << endl; ///////////////////////////////////////////////////////// str3 += str1; cout << "str3 is: " << str3 << endl; ///////////////////////////////////////////////////////// cout << "str3 is: "; for (int i = 0; i<str3.length(); i++) cout << str3[i]; cout << endl; for (int i = 0; i<str3.length(); i++) str3[i] = 'a' + i; cout << "str3 is: " << str3 << endl; ///////////////////////////////////////////////////////// cout << "str1 is: " << str1 << endl; cout << "str2 is: " << str2 << endl; cout << "str3 is: " << str3 << endl; cout << "Compare str1 == str2 is: " << (str1 == str2) << endl; cout << "Compare str1 == str3 is: " << (str1 == str3) << endl; cout << "Compare str1 != str2 is: " << (str1 != str2) << endl; cout << "Compare str1 != str3 is: " << (str1 != str3) << endl; cout << "Total MyString is: " << MyString::total_MyString() << endl; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MyString_Derived ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// MyString_Derived Dstr1("String"), Dstr2("Test String 2"), Dstr3(Dstr1); cout << "Dstr1 is: " << Dstr1 << endl; cout << "Dstr2 is: " << Dstr2 << endl; cout << "Dstr3 is: " << Dstr3 << endl; cout << "Total MyString_Derived is: " << MyString_Derived::total_MyString() << endl; ///////////////////////////////////////////////////////// cout << "Give one word " << endl; cin >> Dstr1; // from stdin "this is a test line" cout << "Dstr1 is: " << Dstr1 << endl; ///////////////////////////////////////////////////////// Dstr2 = Dstr1; cout << "Dstr2 is: " << Dstr2 << endl; ///////////////////////////////////////////////////////// Dstr3 += Dstr1; cout << "Dstr3 is: " << Dstr3 << endl; ///////////////////////////////////////////////////////// cout << "Dstr3 is: "; for (int i = 0; i<Dstr3.length(); i++) cout << Dstr3[i]; cout << endl; for (i = 0; i<Dstr3.length(); i++) Dstr3[i] = 'a' + i; cout << "Dstr3 is: " << Dstr3 << endl; ///////////////////////////////////////////////////////// cout << "Dstr1 is: " << Dstr1 << endl; cout << "Dstr2 is: " << Dstr2 << endl; cout << "Dstr3 is: " << Dstr3 << endl; cout << "Compare Dstr1 == Dstr2 is: " << (Dstr1 == Dstr2) << endl; cout << "Compare Dstr1 == Dstr3 is: " << (Dstr1 == Dstr3) << endl; cout << "Compare Dstr1 != Dstr2 is: " << (Dstr1 != Dstr2) << endl; cout << "Compare Dstr1 != Dstr3 is: " << (Dstr1 != Dstr3) << endl; }
true
2e28eb8c9b5abb9cecf1ba38a7a3d88540059b2b
C++
Kourin1996/CompetitiveProgramming
/AtCoderProblems/ABC/044/a.cpp
UTF-8
170
2.59375
3
[]
no_license
#include <iostream> int N = 0, K = 0, X = 0, Y = 0; int main(void){ std::cin >> N >> K >> X >> Y; std::cout << ((N <= K) ? N*X : (K*X + (N-K)*Y)) << std::endl; }
true
6f8604a65d6bd04a8ae130c26c0dad51f6117bcc
C++
GilvanFarias/Exercicios
/Aula_09 Array(vetor)/exercicio 01/ex_01.cpp
ISO-8859-1
602
3.0625
3
[ "MIT" ]
permissive
#include <iostream> #include <locale> using namespace std; int main(){ setlocale(LC_ALL, "ptb"); int numElementos = 5, i=0; int vetor[10]; int num[10]; int tentativas=3; for(int i=0; i<numElementos; i++){ cout<< "Digite "<<i+1<< " nmero "; cin>> vetor[i]; system("CLS"); } for(i; i<numElementos; i++){ if(num[i] < 3){ cout<<"Digite umm nmero"; cin>>num[i]; cout<<" Voc errou"; }else if(vetor[i] == num){ cout<< "Parabns voc acertou\n"; cout<< " Esse nmero est na posio "<<num[i]; return 0; } } }
true
3278b3559c56fce02e6f2025040d4b995156610c
C++
niuxu18/logTracker-old
/second/download/httpd/gumtree/httpd_repos_function_1675_httpd-2.3.8.cpp
UTF-8
291
2.609375
3
[]
no_license
static int hb_server_sort(const void *a_, const void *b_) { hb_server_t *a = (hb_server_t*)a_; hb_server_t *b = (hb_server_t*)b_; if (a->ready == b->ready) { return 0; } else if (a->ready > b->ready) { return -1; } else { return 1; } }
true
d131cf3411a1b3a4fd15cb491cc8903c5aab4b82
C++
aarpi3/Just_Flower
/Just_Flower.ino
UTF-8
6,292
3.125
3
[ "MIT" ]
permissive
// Just Flower // By Tomas Heydal & Harald Martin Aarbogh // 2019 //Libraries #include <dht.h> // mousture sensor int threshold = 500; // an arbitrary threshold level that's in the range of the analog input (for reference, 660 is wet, newly watered). int soilMoisture = A1; // pin that the soilMoisture analog sensor is attached to int x = 10000; // Duration of which pump will be runned, devided by 1000, giving sec [10sec] // water pump int pump = 1; // BLUE pin that the reley (and pump is attached to) int count = 0; // Our water counter //int ledcount10 = 6; // NOT USED YET initialize the led indicator as an digital output pin5 //int maxNum = 2000; // NOT USED YET Assigned max number of counts of watering //int tempHumidity = 5; // NOT USED YET pin that the tempHumidity digital sensor is attached to. //Temperature sensor DHT21 dht DHT; #define DHT21_PIN 6 // DHT 22 (AM2302) - what pin we're connected to float hum; //Stores humidity value float temp; //Stores temperature value // Water level int levelFull = 2; // NOT USED YET assigning the levelFull indicator as an digital input pin2 int levelMid = 3; // GREEN, initialize the levelMid indicator as an digital input pin3 int levelEmpty = 4; // YELLOW, initialize the levelEmpty indicator as an digital input pin4 int waterLevelValue = 100; // Assign value 100 as water tank level void setup() { pinMode(pump, OUTPUT); // initialize the pump pin as an output: pinMode(LED_BUILTIN, OUTPUT); // initialize the built in LED pin as an output pinMode (levelFull, INPUT); // initialize the levelFull indicator as an digital input pinMode (levelMid, INPUT); // initialize the levelMid indicator as an digital input pinMode (levelEmpty, INPUT); // initialize the levelEmpty indicator as an digital input pinMode (soilMoisture, INPUT); // initialize the soilMoisture indicator as an analog input digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW Serial.begin(9600); // initialize serial communications: } void loop() { delay(1000); // delay in between reads for stability int soilMoistureValue = analogRead(soilMoisture); // read the value of the analog soilMoisture sensor and store it in soilMoistureValue delay(15); // delay in between reads for stability int waterLevelFullValue = digitalRead(levelFull); // checks if the waterlevel is full and assigns the value to waterLevelFullValue delay(15); // delay in between reads for stability int waterLevelMidValue = digitalRead(levelMid); // checks if the waterlevel is Mid and assigns the value to waterLevelMidValue delay(15); // delay in between reads for stability int waterLevelEmptyValue = digitalRead(levelEmpty); // checks if the waterlevel is Mid and assigns the value to waterLevelEmptyValue delay(15); // delay in between reads for stability Serial.println("Soil Moisture Level (0-1000) "); Serial.println(soilMoistureValue); //Print soilMoisture value to internal Serial Monitor delay(15); // delay in between reads for stability Serial.println("Water Tank Level "); Serial.println(waterLevelValue); //Print water levelFull delay(1000); // delay in between reads for stability if (digitalRead(levelMid) == HIGH) { waterLevelValue = 50; } if (digitalRead(levelEmpty) == HIGH) { waterLevelValue = 0; } if (soilMoistureValue < threshold && waterLevelValue == 100) { // if the soilMoisture analog value is low enough (value assigned on top of program), and the water level is Full start Pump: delay(15); // delay in between reads for stability digitalWrite(pump, HIGH); //Turns on the waterpump delay(x); //x is duration in seconds of watering (devided by 1000) digitalWrite(pump, LOW); //Turns off the waterpump delay(15); // delay in between reads for stability count++; // add one (1) to our count delay(15); // delay in between reads for stability Serial.println("Watering done, when waterlevel full"); //Print text Serial.println("Water count since start of Software ");Serial.println(count); //Print text and water count delay(15); // delay in between reads for stability } else if (soilMoistureValue < threshold && waterLevelValue == 50) { // if the soilMoisture analog value is low enough (value assigned on top of program), and the water level is Mid start Pump: delay(15); // delay in between reads for stability digitalWrite(pump, HIGH); //Turns on the waterpump delay(x); //x is duration in seconds of watering (devided by 1000) digitalWrite(pump, LOW); //Turns off the waterpump delay(15); // delay in between reads for stability count++; // add one (1) to our count delay(15); // delay in between reads for stability Serial.println("Watering done, when waterlevel mid"); //Print text Serial.println("Water count since start of Software ");Serial.println(count); //Print text and water count delay(15); // delay in between reads for stability } else if (soilMoistureValue < threshold && waterLevelValue == 0) { // if the soilMoisture analog value is low enough (value assigned on top of program), and the water level is Mid start Pump: delay(15); // delay in between reads for stability digitalWrite(pump, LOW); //Turns off the waterpump delay(15); // delay in between reads for stability Serial.println("Warning! Watering not executed, because waterlevel Empty"); //Print text Serial.println("Water count unchanged ");Serial.println(count); //Print text and water count delay(15); // delay in between reads for stability } } void readTemp(){ int chk = DHT.read21(DHT21_PIN); //Read data and store it to variables hum and temp hum = DHT.humidity; temp= DHT.temperature; //Print temp and humidity values to serial monitor Serial.print("Humidity: "); Serial.print(hum); Serial.print(" %, Temp: "); Serial.print(temp); Serial.println(" Celsius"); delay(2000); //Delay 2 sec. }
true
979727eb33ffa7fa4a76c2a373bc777d09b01f9b
C++
mmcgraw74/644-1284-Narrow
/examples/Endless_Serial_0_1/Endless_Serial_0_1.ino
UTF-8
827
3.140625
3
[]
no_license
/* Infinite loop serial test Receives from the main serial port and sends back. The Tw signal is fed also to Serial 1 Rx. Receives from serial port 1, sends to the main serial (Serial 0). This example works only with boards with more than one serial like Arduino Mega, Due, Zero etc. The circuit: - A cable connected betwwen "TX" and "10" pins - Serial Monitor open on Serial port 0 This example code is in the public domain. */ void setup() { // initialize both serial ports: Serial.begin(9600); Serial1.begin(9600); } void loop() { // read from port 1, send to port 0: if (Serial1.available()) { int inByte = Serial1.read(); Serial.write(inByte); } // read from port 0, send to port 1: if (Serial.available()) { int inByte = Serial.read(); Serial.write(inByte); } }
true
44023d022d2716461c67fbc96257b22b7733f2aa
C++
pylot/balau
/src/main/cpp/Balau/Container/ArrayBlockingQueue.hpp
UTF-8
3,151
3.015625
3
[ "BSL-1.0" ]
permissive
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software (contact@borasoftware.com) // // Licensed under the Boost Software License - Version 1.0 - August 17th, 2003. // See the LICENSE file for the full license text. // /// /// @file ArrayBlockingQueue.hpp /// /// A blocking queue that uses wait/notify and an array to hold the elements. /// #ifndef COM_BORA_SOFTWARE__BALAU_CONTAINER__ARRAY_BLOCKING_QUEUE #define COM_BORA_SOFTWARE__BALAU_CONTAINER__ARRAY_BLOCKING_QUEUE #include <Balau/Container/BlockingQueue.hpp> #include <Balau/Type/StdTypes.hpp> #include <condition_variable> namespace Balau::Container { /// /// A blocking queue that uses wait/notify and an array to hold the elements. /// /// This queue is concurrent but not lock free. /// /// @tparam T the element type (must be default constructable in /// addition being move constructable and assignable) /// template <typename T> class ArrayBlockingQueue : public BlockingQueue<T> { /// /// Create an array blocking queue with the specified capacity. /// public: explicit ArrayBlockingQueue(unsigned int capacity) : elements(capacity) , count(0) , head(0) , tail(0) {} public: void enqueue(T && element) override { std::unique_lock<std::mutex> lock(mutex); while (full()) { enqueueCondition.wait(lock); } elements[head] = std::move(element); increment(head); ++count; // When two threads are dequeueing, the second thread could // miss the notify call if it is outside of the lock. dequeueCondition.notify_one(); } public: T dequeue() override { std::unique_lock<std::mutex> lock(mutex); while (empty()) { dequeueCondition.wait(lock); } T element = std::move(elements[tail]); increment(tail); --count; // When two threads are enqueueing, the second thread could // miss the notify call if it is outside of the lock. enqueueCondition.notify_one(); return element; } public: T tryDequeue() override { return tryDequeue(std::chrono::milliseconds(0)); } public: T tryDequeue(std::chrono::milliseconds waitTime) override { std::unique_lock<std::mutex> lock(mutex); while (empty()) { dequeueCondition.wait_for(lock, waitTime); } if (empty()) { return T(); } T element = std::move(elements[tail]); increment(tail); --count; // When two threads are enqueueing, the second thread could // miss the notify call if it is outside of the lock. enqueueCondition.notify_one(); return element; } public: bool full() const override { return count == elements.size(); } public: bool empty() const override { return count == 0; } ////////////////////////// Private implementation ///////////////////////// private: void increment(size_t & ptr) { ++ptr; ptr = ptr - (ptr == elements.size()) * elements.size(); } private: std::vector<T> elements; private: size_t count; private: size_t head; private: size_t tail; private: std::mutex mutex; private: std::condition_variable enqueueCondition; private: std::condition_variable dequeueCondition; }; } // namespace Balau::Container #endif // COM_BORA_SOFTWARE__BALAU_CONTAINER__ARRAY_BLOCKING_QUEUE
true
0fd94f10eea70ea115a55add410ca0aaf38112c8
C++
NoTravel/wondertrader
/src/Includes/WTSDataDef.hpp
UTF-8
35,817
2.734375
3
[ "MIT" ]
permissive
/*! * \file WTSDataDef.hpp * \project WonderTrader * * \author Wesley * \date 2020/03/30 * * \brief Wt行情数据定义文件,包括tick、bar、orderqueue、orderdetail、transaction等数据 */ #pragma once #include <stdlib.h> #include <vector> #include <deque> #include <string.h> #include<chrono> #include "WTSObject.hpp" #include "WTSTypes.h" #include "WTSMarcos.h" #include "WTSStruct.h" #include "WTSCollection.hpp" using namespace std; #pragma warning(disable:4267) NS_OTP_BEGIN /* * 数值数组的内部封装 * 采用std::vector实现 * 包含数据格式化字符串 * 数值的数据类型为double */ class WTSValueArray : public WTSObject { protected: vector<double> m_vecData; public: /* * 创建一个数值数组对象 * @decimal 保留的小数点位数 */ static WTSValueArray* create() { WTSValueArray* pRet = new WTSValueArray; pRet->m_vecData.clear(); return pRet; } /* * 读取数组的长度 */ inline uint32_t size() const{ return m_vecData.size(); } inline bool empty() const{ return m_vecData.empty(); } /* * 读取指定位置的数据 * 如果超出范围,则返回INVALID_VALUE */ inline double at(uint32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= m_vecData.size()) return INVALID_DOUBLE; return m_vecData[idx]; } inline int32_t translateIdx(int32_t idx) const { if(idx < 0) { return m_vecData.size()+idx; } return idx; } /* * 找到指定范围内的最大值 * 如果超出范围,则返回INVALID_VALUE */ double maxvalue(int32_t head, int32_t tail, bool isAbs = false) const { head = translateIdx(head); tail = translateIdx(tail); uint32_t begin = min(head, tail); uint32_t end = max(head, tail); if(begin <0 || begin >= m_vecData.size() || end < 0 || end > m_vecData.size()) return INVALID_DOUBLE; double maxValue = INVALID_DOUBLE; for(uint32_t i = begin; i <= end; i++) { if(m_vecData[i] == INVALID_DOUBLE) continue; if(maxValue == INVALID_DOUBLE) maxValue = isAbs?abs(m_vecData[i]):m_vecData[i]; else maxValue = max(maxValue, isAbs?abs(m_vecData[i]):m_vecData[i]); } //if (maxValue == INVALID_DOUBLE) // maxValue = 0.0; return maxValue; } /* * 找到指定范围内的最小值 * 如果超出范围,则返回INVALID_VALUE */ double minvalue(int32_t head, int32_t tail, bool isAbs = false) const { head = translateIdx(head); tail = translateIdx(tail); uint32_t begin = min(head, tail); uint32_t end = max(head, tail); if(begin <0 || begin >= m_vecData.size() || end < 0 || end > m_vecData.size()) return INVALID_DOUBLE; double minValue = INVALID_DOUBLE; for(uint32_t i = begin; i <= end; i++) { if (m_vecData[i] == INVALID_DOUBLE) continue; if(minValue == INVALID_DOUBLE) minValue = isAbs?abs(m_vecData[i]):m_vecData[i]; else minValue = min(minValue, isAbs?abs(m_vecData[i]):m_vecData[i]); } //if (minValue == INVALID_DOUBLE) // minValue = 0.0; return minValue; } /* * 在数组末尾添加数据 */ inline void append(double val) { m_vecData.emplace_back(val); } /* * 设置指定位置的数据 */ inline void set(uint32_t idx, double val) { if(idx < 0 || idx >= m_vecData.size()) return; m_vecData[idx] = val; } /* * 重新分配数组大小,并设置默认值 */ inline void resize(uint32_t uSize, double val = INVALID_DOUBLE) { m_vecData.resize(uSize, val); } /* * 重载操作符[] * 用法同getValue接口 */ inline double& operator[](uint32_t idx) { return m_vecData[idx]; } inline double operator[](uint32_t idx) const { return m_vecData[idx]; } inline std::vector<double>& getDataRef() { return m_vecData; } }; /* * K线数据切片 * 这个比较特殊,因为要拼接当日和历史的 * 所以有两个开始地址 */ class WTSKlineSlice : public WTSObject { private: char m_strCode[MAX_INSTRUMENT_LENGTH]; WTSKlinePeriod m_kpPeriod; uint32_t m_uTimes; WTSBarStruct* m_bsHisBegin; int32_t m_iHisCnt; WTSBarStruct* m_bsRtBegin; int32_t m_iRtCnt; protected: WTSKlineSlice() :m_kpPeriod(KP_Minute1) , m_uTimes(1) , m_iHisCnt(0) , m_bsHisBegin(NULL) , m_iRtCnt(0) , m_bsRtBegin(NULL) { } inline int32_t translateIdx(int32_t idx) const { int32_t totalCnt = m_iHisCnt + m_iRtCnt; if (idx < 0) { return max(0, totalCnt + idx); } return idx; } public: static WTSKlineSlice* create(const char* code, WTSKlinePeriod period, uint32_t times, WTSBarStruct* hisHead, int32_t hisCnt, WTSBarStruct* rtHead = NULL, int32_t rtCnt = 0) { if (hisHead == NULL && rtHead == NULL) return NULL; if (hisCnt == 0 && rtCnt == 0) return NULL; WTSKlineSlice *pRet = new WTSKlineSlice; strcpy(pRet->m_strCode, code); pRet->m_kpPeriod = period; pRet->m_uTimes = times; pRet->m_bsHisBegin = hisHead; pRet->m_iHisCnt = hisCnt; pRet->m_bsRtBegin = rtHead; pRet->m_iRtCnt = rtCnt; return pRet; } inline WTSBarStruct* get_his_addr() { return m_bsHisBegin; } inline int32_t get_his_count() { return m_iHisCnt; } inline WTSBarStruct* get_rt_addr() { return m_bsRtBegin; } inline int32_t get_rt_count() { return m_iRtCnt; } inline WTSBarStruct* at(int32_t idx) { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return NULL; return idx < m_iHisCnt ? &m_bsHisBegin[idx] : &m_bsRtBegin[idx - m_iHisCnt]; } inline const WTSBarStruct* at(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return NULL; return idx < m_iHisCnt ? &m_bsHisBegin[idx] : &m_bsRtBegin[idx - m_iHisCnt]; } /* * 查找指定范围内的最大价格 * @head 起始位置 * @tail 结束位置 * 如果位置超出范围,返回INVALID_VALUE */ double maxprice(int32_t head, int32_t tail) const { head = translateIdx(head); tail = translateIdx(tail); int32_t begin = max(0,min(head, tail)); int32_t end = min(max(head, tail), size() - 1); double maxValue = this->at(begin)->high; for (int32_t i = begin; i <= end; i++) { maxValue = max(maxValue, at(i)->high); } return maxValue; } /* * 查找指定范围内的最小价格 * @head 起始位置 * @tail 结束位置 * 如果位置超出范围,返回INVALID_VALUE */ double minprice(int32_t head, int32_t tail) const { head = translateIdx(head); tail = translateIdx(tail); int32_t begin = max(0, min(head, tail)); int32_t end = min(max(head, tail), size() - 1); double minValue = at(begin)->low; for (int32_t i = begin; i <= end; i++) { minValue = min(minValue, at(i)->low); } return minValue; } /* * 返回K线的大小 */ inline int32_t size() const{ return m_iHisCnt + m_iRtCnt; } inline bool empty() const{ return (m_iHisCnt + m_iRtCnt) == 0; } /* * 返回K线对象的合约代码 */ inline const char* code() const{ return m_strCode; } inline void setCode(const char* code){ strcpy(m_strCode, code); } /* * 读取指定位置的开盘价 * 如果超出范围则返回INVALID_VALUE */ double open(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_DOUBLE; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_DOUBLE; else return (m_bsHisBegin + idx)->open; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_DOUBLE; else return (m_bsRtBegin + (idx - m_iHisCnt))->open; return INVALID_DOUBLE; } /* * 读取指定位置的最高价 * 如果超出范围则返回INVALID_VALUE */ double high(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_DOUBLE; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_DOUBLE; else return (m_bsHisBegin + idx)->high; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_DOUBLE; else return (m_bsRtBegin + (idx - m_iHisCnt))->high; return INVALID_DOUBLE; } /* * 读取指定位置的最低价 * 如果超出范围则返回INVALID_VALUE */ double low(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_DOUBLE; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_DOUBLE; else return (m_bsHisBegin + idx)->low; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_DOUBLE; else return (m_bsRtBegin + (idx - m_iHisCnt))->low; return INVALID_DOUBLE; } /* * 读取指定位置的收盘价 * 如果超出范围则返回INVALID_VALUE */ double close(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_DOUBLE; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_DOUBLE; else return (m_bsHisBegin + idx)->close; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_DOUBLE; else return (m_bsRtBegin + (idx - m_iHisCnt))->close; return INVALID_DOUBLE; } /* * 读取指定位置的成交量 * 如果超出范围则返回INVALID_VALUE */ uint32_t volume(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_UINT32; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_UINT32; else return (m_bsHisBegin + idx)->vol; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_UINT32; else return (m_bsRtBegin + (idx - m_iHisCnt))->vol; return INVALID_UINT32; } /* * 读取指定位置的总持 * 如果超出范围则返回INVALID_VALUE */ uint32_t openinterest(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_UINT32; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_UINT32; else return (m_bsHisBegin + idx)->hold; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_UINT32; else return (m_bsRtBegin + (idx - m_iHisCnt))->hold; return INVALID_UINT32; } /* * 读取指定位置的增仓 * 如果超出范围则返回INVALID_VALUE */ int32_t additional(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_INT32; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_INT32; else return (m_bsHisBegin + idx)->add; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_INT32; else return (m_bsRtBegin + (idx - m_iHisCnt))->add; return INVALID_INT32; } /* * 读取指定位置的成交额 * 如果超出范围则返回INVALID_VALUE */ double money(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_DOUBLE; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_DOUBLE; else return (m_bsHisBegin + idx)->money; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_DOUBLE; else return (m_bsRtBegin + (idx - m_iHisCnt))->money; return INVALID_DOUBLE; } /* * 读取指定位置的日期 * 如果超出范围则返回INVALID_VALUE */ uint32_t date(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_UINT32; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_UINT32; else return (m_bsHisBegin + idx)->date; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_UINT32; else return (m_bsRtBegin + (idx - m_iHisCnt))->date; return INVALID_UINT32; } /* * 读取指定位置的时间 * 如果超出范围则返回INVALID_VALUE */ uint32_t time(int32_t idx) const { idx = translateIdx(idx); if (idx < 0 || idx >= size()) return INVALID_UINT32; if (idx < m_iHisCnt) if (m_bsHisBegin == NULL) return INVALID_UINT32; else return (m_bsHisBegin + idx)->time; else if (idx < size()) if (m_bsRtBegin == NULL) return INVALID_UINT32; else return (m_bsRtBegin + (idx - m_iHisCnt))->time; return INVALID_UINT32; } /* * 将指定范围内的某个特定字段的数据全部抓取出来 * 并保存的一个数值数组中 * 如果超出范围,则返回NULL * @type 支持的类型有KT_OPEN、KT_HIGH、KT_LOW、KT_CLOSE,KFT_VOLUME、KT_DATE */ WTSValueArray* extractData(WTSKlineFieldType type, int32_t head = 0, int32_t tail = -1) const { if (m_bsHisBegin == NULL && m_bsRtBegin == NULL) return NULL; if (m_iHisCnt == 0 && m_iRtCnt == 0) return NULL; head = translateIdx(head); tail = translateIdx(tail); int32_t begin = max(0, min(head, tail)); int32_t end = min(max(head, tail), size() - 1); WTSValueArray *vArray = NULL; vArray = WTSValueArray::create(); for (int32_t i = begin; i <= end; i++) { const WTSBarStruct& day = i < m_iHisCnt ? m_bsHisBegin[i] : m_bsRtBegin[i - m_iHisCnt]; switch (type) { case KFT_OPEN: vArray->append(day.open); break; case KFT_HIGH: vArray->append(day.high); break; case KFT_LOW: vArray->append(day.low); break; case KFT_CLOSE: vArray->append(day.close); break; case KFT_VOLUME: vArray->append(day.vol); break; case KFT_SVOLUME: if (day.vol > INT_MAX) vArray->append(1 * ((day.close > day.open) ? 1 : -1)); else vArray->append((int32_t)day.vol * ((day.close > day.open) ? 1 : -1)); break; case KFT_DATE: vArray->append(day.date); break; } } return vArray; } }; /* * K线数据 * K线数据的内部数据使用WTSBarStruct * WTSBarStruct是一个结构体 * 因为K线数据单独使用的可能性较低 * 所以不做WTSObject派生类的封装 */ class WTSKlineData : public WTSObject { public: typedef std::vector<WTSBarStruct> WTSBarList; protected: char m_strCode[32]; WTSKlinePeriod m_kpPeriod; uint32_t m_uTimes; bool m_bUnixTime; //是否是时间戳格式,目前只在秒线上有效 WTSBarList m_vecBarData; bool m_bClosed; //是否是闭合K线 protected: WTSKlineData() :m_kpPeriod(KP_Minute1) ,m_uTimes(1) ,m_bUnixTime(false) ,m_bClosed(true) { } inline int32_t translateIdx(int32_t idx) const { if(idx < 0) { return max(0, (int32_t)m_vecBarData.size() + idx); } return idx; } public: /* * 创建一个K线数据对象 * @code 要创建的合约代码 * @size 初始分配的数据长度 */ static WTSKlineData* create(const char* code, uint32_t size) { WTSKlineData *pRet = new WTSKlineData; pRet->m_vecBarData.resize(size); strcpy(pRet->m_strCode, code); return pRet; } inline void setClosed(bool bClosed){ m_bClosed = bClosed; } inline bool isClosed() const{ return m_bClosed; } /* * 设置周期和步长 * @period 基础周期 * @times 倍数 */ inline void setPeriod(WTSKlinePeriod period, uint32_t times = 1){ m_kpPeriod = period; m_uTimes = times; } inline void setUnixTime(bool bEnabled = true){ m_bUnixTime = bEnabled; } inline WTSKlinePeriod period() const{ return m_kpPeriod; } inline uint32_t times() const{ return m_uTimes; } inline bool isUnixTime() const{ return m_bUnixTime; } /* * 查找指定范围内的最大价格 * @head 起始位置 * @tail 结束位置 * 如果位置超出范围,返回INVALID_VALUE */ inline double maxprice(int32_t head, int32_t tail) const { head = translateIdx(head); tail = translateIdx(tail); uint32_t begin = min(head, tail); uint32_t end = max(head, tail); if(begin >= m_vecBarData.size() || end > m_vecBarData.size()) return INVALID_DOUBLE; double maxValue = m_vecBarData[begin].high; for(uint32_t i = begin; i <= end; i++) { maxValue = max(maxValue, m_vecBarData[i].high); } return maxValue; } /* * 查找指定范围内的最小价格 * @head 起始位置 * @tail 结束位置 * 如果位置超出范围,返回INVALID_VALUE */ inline double minprice(int32_t head, int32_t tail) const { head = translateIdx(head); tail = translateIdx(tail); uint32_t begin = min(head, tail); uint32_t end = max(head, tail); if(begin >= m_vecBarData.size() || end > m_vecBarData.size()) return INVALID_DOUBLE; double minValue = m_vecBarData[begin].low; for(uint32_t i = begin; i <= end; i++) { minValue = min(minValue, m_vecBarData[i].low); } return minValue; } /* * 返回K线的大小 */ inline uint32_t size() const{return m_vecBarData.size();} inline bool IsEmpty() const{ return m_vecBarData.empty(); } /* * 返回K线对象的合约代码 */ inline const char* code() const{ return m_strCode; } inline void setCode(const char* code){ strcpy(m_strCode, code); } /* * 读取指定位置的开盘价 * 如果超出范围则返回INVALID_VALUE */ inline double open(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_DOUBLE; return m_vecBarData[idx].open; } /* * 读取指定位置的最高价 * 如果超出范围则返回INVALID_VALUE */ inline double high(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_DOUBLE; return m_vecBarData[idx].high; } /* * 读取指定位置的最低价 * 如果超出范围则返回INVALID_VALUE */ inline double low(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_DOUBLE; return m_vecBarData[idx].low; } /* * 读取指定位置的收盘价 * 如果超出范围则返回INVALID_VALUE */ inline double close(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_DOUBLE; return m_vecBarData[idx].close; } /* * 读取指定位置的成交量 * 如果超出范围则返回INVALID_VALUE */ inline uint32_t volume(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_UINT32; return m_vecBarData[idx].vol; } /* * 读取指定位置的总持 * 如果超出范围则返回INVALID_VALUE */ inline uint32_t openinterest(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_UINT32; return m_vecBarData[idx].hold; } /* * 读取指定位置的增仓 * 如果超出范围则返回INVALID_VALUE */ inline int32_t additional(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_INT32; return m_vecBarData[idx].add; } /* * 读取指定位置的成交额 * 如果超出范围则返回INVALID_VALUE */ inline double money(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_DOUBLE; return m_vecBarData[idx].money; } /* * 读取指定位置的日期 * 如果超出范围则返回INVALID_VALUE */ inline uint32_t date(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_UINT32; return m_vecBarData[idx].date; } /* * 读取指定位置的时间 * 如果超出范围则返回INVALID_VALUE */ inline uint32_t time(int32_t idx) const { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return INVALID_UINT32; return m_vecBarData[idx].time; } /* * 将指定范围内的某个特定字段的数据全部抓取出来 * 并保存的一个数值数组中 * 如果超出范围,则返回NULL * @type 支持的类型有KT_OPEN、KT_HIGH、KT_LOW、KT_CLOSE,KFT_VOLUME、KT_DATE */ WTSValueArray* extractData(WTSKlineFieldType type, int32_t head = 0, int32_t tail = -1) const { head = translateIdx(head); tail = translateIdx(tail); uint32_t begin = min(head, tail); uint32_t end = max(head, tail); if(begin >= m_vecBarData.size() || end >= (int32_t)m_vecBarData.size()) return NULL; WTSValueArray *vArray = NULL; vArray = WTSValueArray::create(); for(uint32_t i = 0; i < m_vecBarData.size(); i++) { const WTSBarStruct& day = m_vecBarData.at(i); switch(type) { case KFT_OPEN: vArray->append(day.open); break; case KFT_HIGH: vArray->append(day.high); break; case KFT_LOW: vArray->append(day.low); break; case KFT_CLOSE: vArray->append(day.close); break; case KFT_VOLUME: vArray->append(day.vol); break; case KFT_SVOLUME: if(day.vol > INT_MAX) vArray->append(1 * ((day.close > day.open) ? 1 : -1)); else vArray->append((int32_t)day.vol * ((day.close > day.open)?1:-1)); break; case KFT_DATE: vArray->append(day.date); break; } } return vArray; } public: /* * 获取K线内部vector的引用 */ inline WTSBarList& getDataRef(){ return m_vecBarData; } inline WTSBarStruct* at(int32_t idx) { idx = translateIdx(idx); if(idx < 0 || idx >= (int32_t)m_vecBarData.size()) return NULL; return &m_vecBarData[idx]; } /* * 释放K线数据 * 并delete所有的日线数据,清空vector */ virtual void release() { if(isSingleRefs()) { m_vecBarData.clear(); } WTSObject::release(); } /* * 追加一条K线 */ inline void appendBar(const WTSBarStruct& bar) { if(m_vecBarData.empty()) { m_vecBarData.emplace_back(bar); } else { WTSBarStruct* lastBar = at(-1); if(lastBar->date==bar.date && lastBar->time==bar.time) { memcpy(lastBar, &bar, sizeof(WTSBarStruct)); } else { m_vecBarData.emplace_back(bar); } } } }; /* * Tick数据对象 * 内部封装WTSTickStruct * 封装的主要目的是出于跨语言的考虑 */ class WTSTickData : public WTSObject { public: /* * 创建一个tick数据对象 * @stdCode 合约代码 */ static inline WTSTickData* create(const char* stdCode) { WTSTickData* pRet = new WTSTickData; strcpy(pRet->m_tickStruct.code, stdCode); return pRet; } /* * 根据tick结构体创建一个tick数据对象 * @tickData tick结构体 */ static inline WTSTickData* create(WTSTickStruct& tickData) { WTSTickData* pRet = new WTSTickData; memcpy(&pRet->m_tickStruct, &tickData, sizeof(WTSTickStruct)); return pRet; } inline void setCode(const char* code) { strcpy(m_tickStruct.code, code); } /* * 读取合约代码 */ inline const char* code() const{ return m_tickStruct.code; } /* * 读取市场代码 */ inline const char* exchg() const{ return m_tickStruct.exchg; } /* * 读取最新价 */ inline double price() const{ return m_tickStruct.price; } inline double open() const{ return m_tickStruct.open; } /* * 最高价 */ inline double high() const{ return m_tickStruct.high; } /* * 最低价 */ inline double low() const{ return m_tickStruct.low; } //昨收价,如果是期货则是昨结算 inline double preclose() const{ return m_tickStruct.pre_close; } inline double presettle() const{ return m_tickStruct.pre_settle; } inline int32_t preinterest() const{ return m_tickStruct.pre_interest; } inline double upperlimit() const{ return m_tickStruct.upper_limit; } inline double lowerlimit() const{ return m_tickStruct.lower_limit; } //成交量 inline uint32_t totalvolume() const{ return m_tickStruct.total_volume; } //成交量 inline uint32_t volume() const{ return m_tickStruct.volume; } //结算价 inline double settlepx() const{ return m_tickStruct.settle_price; } //总持 inline uint32_t openinterest() const{ return m_tickStruct.open_interest; } inline int32_t additional() const{ return m_tickStruct.diff_interest; } //成交额 inline double totalturnover() const{ return m_tickStruct.total_turnover; } //成交额 inline double turnover() const{ return m_tickStruct.turn_over; } //交易日 inline uint32_t tradingdate() const{ return m_tickStruct.trading_date; } //数据发生日期 inline uint32_t actiondate() const{ return m_tickStruct.action_date; } //数据发生时间 inline uint32_t actiontime() const{ return m_tickStruct.action_time; } /* * 读取指定档位的委买价 * @idx 0-9 */ inline double bidprice(int idx) const { if(idx < 0 || idx >= 10) return -1; return m_tickStruct.bid_prices[idx]; } /* * 读取指定档位的委卖价 * @idx 0-9 */ inline double askprice(int idx) const { if(idx < 0 || idx >= 10) return -1; return m_tickStruct.ask_prices[idx]; } /* * 读取指定档位的委买量 * @idx 0-9 */ inline uint32_t bidqty(int idx) const { if(idx < 0 || idx >= 10) return -1; return m_tickStruct.bid_qty[idx]; } /* * 读取指定档位的委卖量 * @idx 0-9 */ inline uint32_t askqty(int idx) const { if(idx < 0 || idx >= 10) return -1; return m_tickStruct.ask_qty[idx]; } /* * 返回tick结构体的引用 */ inline WTSTickStruct& getTickStruct(){ return m_tickStruct; } inline uint64_t getLocalTime() const { return m_uLocalTime; } private: WTSTickStruct m_tickStruct; uint64_t m_uLocalTime; //本地时间 WTSTickData():m_uLocalTime(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now().time_since_epoch()).count()){} }; /* * K线数据封装,派生于通用的基础类,便于传递 */ class WTSBarData : public WTSObject { public: inline static WTSBarData* create() { WTSBarData* pRet = new WTSBarData; return pRet; } inline static WTSBarData* create(WTSBarStruct& barData, uint16_t market, const char* code) { WTSBarData* pRet = new WTSBarData; pRet->m_market = market; pRet->m_strCode = code; memcpy(&pRet->m_barStruct, &barData, sizeof(WTSBarStruct)); return pRet; } inline WTSBarStruct& getBarStruct(){return m_barStruct;} inline uint16_t getMarket(){return m_market;} inline const char* getCode(){return m_strCode.c_str();} private: WTSBarStruct m_barStruct; uint16_t m_market; std::string m_strCode; }; class WTSOrdQueData : public WTSObject { public: static inline WTSOrdQueData* create(const char* code) { WTSOrdQueData* pRet = new WTSOrdQueData; strcpy(pRet->m_oqStruct.code, code); return pRet; } static inline WTSOrdQueData* create(WTSOrdQueStruct& ordQueData) { WTSOrdQueData* pRet = new WTSOrdQueData; memcpy(&pRet->m_oqStruct, &ordQueData, sizeof(WTSOrdQueStruct)); return pRet; } inline WTSOrdQueStruct& getOrdQueStruct(){return m_oqStruct;} inline const char* exchg() const{ return m_oqStruct.exchg; } inline const char* code() const{ return m_oqStruct.code; } inline uint32_t tradingdate() const{ return m_oqStruct.trading_date; } inline uint32_t actiondate() const{ return m_oqStruct.action_date; } inline uint32_t actiontime() const { return m_oqStruct.action_time; } inline void setCode(const char* code) { strcpy(m_oqStruct.code, code); } private: WTSOrdQueStruct m_oqStruct; }; class WTSOrdDtlData : public WTSObject { public: static inline WTSOrdDtlData* create(const char* code) { WTSOrdDtlData* pRet = new WTSOrdDtlData; strcpy(pRet->m_odStruct.code, code); return pRet; } static inline WTSOrdDtlData* create(WTSOrdDtlStruct& odData) { WTSOrdDtlData* pRet = new WTSOrdDtlData; memcpy(&pRet->m_odStruct, &odData, sizeof(WTSOrdDtlStruct)); return pRet; } inline WTSOrdDtlStruct& getOrdDtlStruct(){ return m_odStruct; } inline const char* exchg() const{ return m_odStruct.exchg; } inline const char* code() const{ return m_odStruct.code; } inline uint32_t tradingdate() const{ return m_odStruct.trading_date; } inline uint32_t actiondate() const{ return m_odStruct.action_date; } inline uint32_t actiontime() const { return m_odStruct.action_time; } inline void setCode(const char* code) { strcpy(m_odStruct.code, code); } private: WTSOrdDtlStruct m_odStruct; }; class WTSTransData : public WTSObject { public: static inline WTSTransData* create(const char* code) { WTSTransData* pRet = new WTSTransData; strcpy(pRet->m_tsStruct.code, code); return pRet; } static inline WTSTransData* create(WTSTransStruct& transData) { WTSTransData* pRet = new WTSTransData; memcpy(&pRet->m_tsStruct, &transData, sizeof(WTSTransStruct)); return pRet; } inline const char* exchg() const{ return m_tsStruct.exchg; } inline const char* code() const{ return m_tsStruct.code; } inline uint32_t tradingdate() const{ return m_tsStruct.trading_date; } inline uint32_t actiondate() const{ return m_tsStruct.action_date; } inline uint32_t actiontime() const { return m_tsStruct.action_time; } inline WTSTransStruct& getTransStruct(){ return m_tsStruct; } inline void setCode(const char* code) { strcpy(m_tsStruct.code, code); } private: WTSTransStruct m_tsStruct; }; /* * @brief 历史Tick数据数组 * @details 内部使用WTSArray作为容器 */ class WTSHisTickData : public WTSObject { protected: char m_strCode[32]; std::vector<WTSTickStruct> m_ayTicks; bool m_bValidOnly; WTSHisTickData() :m_bValidOnly(false){} public: /* * @brief 创建指定大小的tick数组对象 * @details 内部的数组预先分配大小 * * @param stdCode 合约代码 * @param nSize 预先分配的大小 */ static inline WTSHisTickData* create(const char* stdCode, unsigned int nSize = 0, bool bValidOnly = false) { WTSHisTickData *pRet = new WTSHisTickData; strcpy(pRet->m_strCode, stdCode); pRet->m_ayTicks.resize(nSize); pRet->m_bValidOnly = bValidOnly; return pRet; } /* * @brief 根据tick数组对象创建历史tick数据对象 * @details 内部的tick数组不用再分配了 * @param ayTicks tick数组对象指针 */ static inline WTSHisTickData* create(const char* stdCode, const std::vector<WTSTickStruct>& ayTicks, bool bValidOnly = false) { WTSHisTickData *pRet = new WTSHisTickData; strcpy(pRet->m_strCode, stdCode); pRet->m_ayTicks = ayTicks; pRet->m_bValidOnly = bValidOnly; return pRet; } //读取tick数据的条数 inline uint32_t size() const{ return m_ayTicks.size(); } inline bool empty() const{ return m_ayTicks.empty(); } //读取该数据对应的合约代码 inline const char* code() const{ return m_strCode; } /* * 获取指定位置的tick数据 * */ inline WTSTickStruct* at(uint32_t idx) { if (m_ayTicks.empty() || idx >= m_ayTicks.size()) return NULL; return &m_ayTicks[idx]; } inline std::vector<WTSTickStruct>& getDataRef() { return m_ayTicks; } inline bool isValidOnly() const{ return m_bValidOnly; } /* * 追加一条Tick */ inline void appendTick(const WTSTickStruct& ts) { m_ayTicks.emplace_back(ts); } }; ////////////////////////////////////////////////////////////////////////// /* * @brief Tick数据切片,从连续的tick缓存中做的切片 * @details 切片并没有真实的复制内存,而只是取了开始和结尾的下标 * 这样使用虽然更快,但是使用场景要非常小心,因为他依赖于基础数据对象 */ class WTSTickSlice : public WTSObject { private: char m_strCode[MAX_INSTRUMENT_LENGTH]; WTSTickStruct* m_ptrBegin; uint32_t m_uCount; protected: WTSTickSlice():m_ptrBegin(NULL),m_uCount(0){} inline int32_t translateIdx(int32_t idx) const { if (idx < 0) { return max(0, (int32_t)m_uCount + idx); } return idx; } public: static inline WTSTickSlice* create(const char* code, WTSTickStruct* firstTick, uint32_t count) { if (count == 0 || firstTick == NULL) return NULL; WTSTickSlice* slice = new WTSTickSlice(); strcpy(slice->m_strCode, code); slice->m_ptrBegin = firstTick; slice->m_uCount = count; return slice; } inline uint32_t size() const{ return m_uCount; } inline bool empty() const{ return (m_uCount == 0) || (m_ptrBegin == NULL); } inline const WTSTickStruct* at(int32_t idx) { if (m_ptrBegin == NULL) return NULL; idx = translateIdx(idx); return m_ptrBegin + idx; } }; ////////////////////////////////////////////////////////////////////////// /* * @brief 逐笔委托数据切片,从连续的逐笔委托缓存中做的切片 * @details 切片并没有真实的复制内存,而只是取了开始和结尾的下标 * 这样使用虽然更快,但是使用场景要非常小心,因为他依赖于基础数据对象 */ class WTSOrdDtlSlice : public WTSObject { private: char m_strCode[MAX_INSTRUMENT_LENGTH]; WTSOrdDtlStruct* m_ptrBegin; uint32_t m_uCount; protected: WTSOrdDtlSlice() :m_ptrBegin(NULL), m_uCount(0) {} inline int32_t translateIdx(int32_t idx) const { if (idx < 0) { return max(0, (int32_t)m_uCount + idx); } return idx; } public: static inline WTSOrdDtlSlice* create(const char* code, WTSOrdDtlStruct* firstItem, uint32_t count) { if (count == 0 || firstItem == NULL) return NULL; WTSOrdDtlSlice* slice = new WTSOrdDtlSlice(); strcpy(slice->m_strCode, code); slice->m_ptrBegin = firstItem; slice->m_uCount = count; return slice; } inline uint32_t size() const { return m_uCount; } inline bool empty() const { return (m_uCount == 0) || (m_ptrBegin == NULL); } inline const WTSOrdDtlStruct* at(int32_t idx) { if (m_ptrBegin == NULL) return NULL; idx = translateIdx(idx); return m_ptrBegin + idx; } }; ////////////////////////////////////////////////////////////////////////// /* * @brief 委托队列数据切片,从连续的委托队列缓存中做的切片 * @details 切片并没有真实的复制内存,而只是取了开始和结尾的下标 * 这样使用虽然更快,但是使用场景要非常小心,因为他依赖于基础数据对象 */ class WTSOrdQueSlice : public WTSObject { private: char m_strCode[MAX_INSTRUMENT_LENGTH]; WTSOrdQueStruct* m_ptrBegin; uint32_t m_uCount; protected: WTSOrdQueSlice() :m_ptrBegin(NULL), m_uCount(0) {} inline int32_t translateIdx(int32_t idx) const { if (idx < 0) { return max(0, (int32_t)m_uCount + idx); } return idx; } public: static inline WTSOrdQueSlice* create(const char* code, WTSOrdQueStruct* firstItem, uint32_t count) { if (count == 0 || firstItem == NULL) return NULL; WTSOrdQueSlice* slice = new WTSOrdQueSlice(); strcpy(slice->m_strCode, code); slice->m_ptrBegin = firstItem; slice->m_uCount = count; return slice; } inline uint32_t size() const { return m_uCount; } inline bool empty() const { return (m_uCount == 0) || (m_ptrBegin == NULL); } inline const WTSOrdQueStruct* at(int32_t idx) { if (m_ptrBegin == NULL) return NULL; idx = translateIdx(idx); return m_ptrBegin + idx; } }; ////////////////////////////////////////////////////////////////////////// /* * @brief 逐笔成交数据切片,从连续的逐笔成交缓存中做的切片 * @details 切片并没有真实的复制内存,而只是取了开始和结尾的下标 * 这样使用虽然更快,但是使用场景要非常小心,因为他依赖于基础数据对象 */ class WTSTransSlice : public WTSObject { private: char m_strCode[MAX_INSTRUMENT_LENGTH]; WTSTransStruct* m_ptrBegin; uint32_t m_uCount; protected: WTSTransSlice() :m_ptrBegin(NULL), m_uCount(0) {} inline int32_t translateIdx(int32_t idx) const { if (idx < 0) { return max(0, (int32_t)m_uCount + idx); } return idx; } public: static inline WTSTransSlice* create(const char* code, WTSTransStruct* firstItem, uint32_t count) { if (count == 0 || firstItem == NULL) return NULL; WTSTransSlice* slice = new WTSTransSlice(); strcpy(slice->m_strCode, code); slice->m_ptrBegin = firstItem; slice->m_uCount = count; return slice; } inline uint32_t size() const { return m_uCount; } inline bool empty() const { return (m_uCount == 0) || (m_ptrBegin == NULL); } inline const WTSTransStruct* at(int32_t idx) { if (m_ptrBegin == NULL) return NULL; idx = translateIdx(idx); return m_ptrBegin + idx; } }; NS_OTP_END
true
92a3f52d7e6a9fffc7d6bfff90b08b8be0771d8c
C++
TimKingNF/leetcode
/editor/cn/_10_I.fei-bo-na-qi-shu-lie-lcof.h
UTF-8
1,200
3.40625
3
[]
no_license
//写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项。斐波那契数列的定义如下: // // F(0) = 0,   F(1) = 1 //F(N) = F(N - 1) + F(N - 2), 其中 N > 1. // // 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。 // // 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 // // // // 示例 1: // // 输入:n = 2 //输出:1 // // // 示例 2: // // 输入:n = 5 //输出:5 // // // // // 提示: // // // 0 <= n <= 100 // // // 注意:本题与主站 509 题相同:https://leetcode-cn.com/problems/fibonacci-number/ // Related Topics 递归 #include "header.h" namespace LeetCode_10_I { //leetcode submit region begin(Prohibit modification and deletion) class Solution { public: int fib(int n) { if (n == 0) return 0; if (n <= 2) return 1; int first = 1, second = 1, tmp; for (int i = 3; i <= n; ++i) { tmp = first; first = (first + second) % 1000000007; second = tmp; } return first; } }; //leetcode submit region end(Prohibit modification and deletion) }
true
bc6d9d644fcbb5081c6756d15e5ba66c5df9092a
C++
ZephyrLFY/Leetcode
/15-3Sum/v1.cpp
UTF-8
1,150
3.1875
3
[]
no_license
#include <iostream> #include <unordered_map> #include <set> #include <vector> using namespace std; class Solution { public: vector<vector<int> > threeSum(vector<int>& nums) { vector<vector<int> > result(0); int rNum = -1; int len = nums.size(); unordered_map<int, int> temp; for(int i = 0; i < len - 2; i++) { for(int j = i + 1; j < len; j++) { unordered_map<int, int>::const_iterator got = temp.find(0 - nums[i] - nums[j]); if(got != temp.end() && got->second > i && got->second != j) { rNum++; result.resize(rNum + 1); result[rNum].resize(3); result[rNum][0] = nums[i]; result[rNum][1] = nums[j]; result[rNum][2] = nums[got->second]; cout << nums[i] << " " << nums[j] << " " << nums[got->second] << endl; } temp[nums[j]] = j; } } return result; } }; int main() { Solution solu; vector<int> nums = {-1, 0, 1, 2, -1, -4}; solu.threeSum(nums); }
true
88b8bc2ef5382912bbc8a4dab7d7cc7618250544
C++
unlibrosinpaginas/LABORATORIO-de-ciencias-de-la-computacion2
/lab1.7/main.cpp
UTF-8
1,090
3.78125
4
[]
no_license
//Implementar una funcion que reciba dos cadenas, s y t, la cual debe copiar los //elementos de t en s. Implemente en dos formas, usando arreglos y usando SOLO punteros. //Considere que s DEBE TENER EL TAMA~NO SUFICIENTE PARA CONTENER LOS //ELEMENTOS DE t. #include <iostream> #include <conio.h> #include <string.h> #include <stdio.h> using namespace std; void puntero_cad(char s[40],char t[40]) { char *ps=s; char *pt=t; int i=0, j=0; while(ps[i]!='\0'){//mientras ps sea nulo (1) i++; } while(pt[j]!='\0'){ ps[i++]=pt[j++]; } ps[i]='\0'; cout<<"- copia con punteros: "<<ps; } void arreglos_cad(char s[40],char t[40]) { strcpy(s+strlen(s),t); cout<<"la cadena copiada con arreglos es: "<<s;//copiando el contenido de t en s, desde el ultimo termino de la cadena s } int main() { char s[40]; char t[40]; cout << "Introduce una cadena (1): "; cin.getline(s,40); cout << "Introduce otra cadena (2): "; cin.getline(t,40); cout << "COPIA: "; puntero_cad(s,t); arreglos_cad(s,t); return 0; }
true
157d3a244595e5888c8d07a44f2fb241b504820a
C++
corona75/chapter3
/chapter3-7.cpp
UHC
384
3.203125
3
[]
no_license
#include<stdio.h> int main(void) { double value_double = 1.2; int value_int = 0; short value_short = 0; value_int = value_double; printf("Ǽ %f %d ȯǾϴ.\n",value_double,value_int); value_int = 32769; value_short = value_int; printf("int %d short %d ȯǾϴ.\n",value_int,value_short); return 0; }
true
171896a8632d479b360fc370addf83a5e3e54fd2
C++
XiFanHeNai/Leetcode
/Intersection/Intersection/Intersection/Intersection - 副本.cpp
GB18030
3,950
3.46875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; class Solution { public: Solution(vector<int> n1, vector<int> n2) { nums1 = n1; nums2 = n2; } vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> temp_1(nums1.size()),temp_2(nums2.size()); vector<int> result((nums1.size()>nums2.size())? nums1.size():nums2.size());//ȡϳij½ int index_num=0,index_temp=0; int index_temp1=0; int index_temp2=0; if ((nums1.size() == 0) || (nums2.size() == 0) || ((nums1.size() == 2)&&(nums1[0] != nums1[1])) || ((nums2.size() == 2)&&(nums2[0] != nums2[1])))//һΪգΪ2ûн㣬ֱӷؿ { result.resize(0); return result; } if (nums1.size() == 0) temp_1.resize(0); else if ( (nums1.size() == 1) || ((nums1.size() == 2)&&(nums1[0] == nums1[1])) ) { temp_1.resize(1); temp_1[0] = nums1[0]; } else if (nums1.size() >= 3) { //1пܳΪĵȡ while(index_num < nums1.size()-2) { if ((nums1[index_num] == nums1[index_num+1]) && (nums1[index_num] != nums1[index_num+2])) { while((index_temp1 < index_temp) && (temp_1[index_temp1] != nums1[index_num])) //޳ѴڵDZڽ index_temp1++; if (index_temp1 == index_temp)//µDZڽ { temp_1[index_temp] = nums1[index_num]; index_temp++; } index_temp1=0; } index_num++; } if (nums1[index_num] == nums1[index_num+1]) { while((index_temp1 < index_temp) && (temp_1[index_temp1] != nums1[index_num])) //޳ѴڵDZڽ index_temp1++; if (index_temp1 == index_temp)//µDZڽ { temp_1[index_temp] = nums1[index_num]; index_temp++; } index_temp1=0; } temp_1.resize(index_temp); } index_temp1=0; index_temp=0; index_num=0; //ͬ2 if ( (nums2.size() == 1) || ((nums2.size() == 2)&&(nums2[0] == nums2[1])) ) temp_2[0] = nums2[0]; else if (nums2.size() >= 3) { while(index_num < nums2.size()-2) { if ((nums2[index_num] == nums2[index_num+1]) && (nums2[index_num] != nums2[index_num+2])) { while((index_temp2 < index_temp) && (temp_2[index_temp2] != nums2[index_num])) //޳ѴڵDZڽ index_temp2++; if (index_temp2 == index_temp)//µDZڽ { temp_2[index_temp] = nums2[index_num]; index_temp++; } index_temp2=0; } index_num++; } if (nums2[index_num] == nums2[index_num+1]) { while((index_temp2 < index_temp) && (temp_2[index_temp2] != nums2[index_num])) //޳ѴڵDZڽ index_temp2++; if (index_temp2 == index_temp)//µDZڽ { temp_2[index_temp] = nums2[index_num]; index_temp++; } index_temp2=0; } temp_2.resize(index_temp); } //ȽȡĽ index_temp2=0; index_temp=0; if ((temp_1.size() == 0) || (temp_2.size() == 0)) { result.resize(0); return result; } while(index_temp1 < temp_1.size()) { while( index_temp2 < temp_2.size() ) { if (temp_1[index_temp1] == temp_2[index_temp2]) { result[index_temp] = temp_1[index_temp1]; index_temp++; } index_temp2++; } index_temp2=0; index_temp1++; } result.resize(index_temp); return result; } private: vector<int> nums1; vector<int> nums2; }; int main() { //int a1[] = {}; //int a1[]={1}; //vector<int> v1(a1,a1+(sizeof(a1)/sizeof(int))) ; vector<int> v1(0); int a2[] = {5}; //int a2[]={1}; vector<int> v2(a2,a2+(sizeof(a2)/sizeof(int))) ; Solution s1(v1,v2); vector<int> result = s1.intersection(v1,v2); int index=0; for (index=0;index<result.size();index++) cout << result[index] << endl; cout << "Hello World \n" << endl; return 0; }
true
3f7a5403b63afb142b9cfd6e94ab49904d5473d1
C++
yalpul/ceng
/ceng213/sort/count/shaker_c.cpp
UTF-8
1,596
3.859375
4
[]
no_license
/* * Shaker Sort Algorithm * Optimized to remember * the indexes of sorted parts at the edges */ #include <iostream> #include <vector> #include <cstdlib> #include <ctime> static unsigned long compCount = 0, moveCount = 0; template <class T> void shaker(std::vector<T> &v) { int begin_i = 0, end_i = v.size() - 1; int new_bi = end_i, new_ei = begin_i; bool swpd = false; while (begin_i < end_i) { for (int i = begin_i; i < end_i; i++) if (++compCount && v[i] > v[i+1]) { std::swap(v[i], v[i+1]), moveCount += 2; swpd = true; new_ei = i; } // Breaks the loop when it is already sorted if (!swpd) break; swpd = false; // Ending index becomes the right-most unsorted index // The items at indexes greater than end_i are already sorted end_i = new_ei; for (int i = end_i - 1; i >= begin_i; i--) if (++compCount && v[i] > v[i+1]) { std::swap(v[i], v[i+1]), moveCount += 2; swpd = true; new_bi = i; } // Breaks the loop when it is already sorted if (!swpd) break; // The left side of beginning index is already sorted begin_i = new_bi + 1; } } int main(int argc, char* argv[]) { std::vector<int> v; if (argc == 2) { srand(time(0)); int s = atoi(argv[1]); v.resize(s); for (int i = 0; i < s; i++) v[i] = rand(); } else { int s; std::cin >> s; v.resize(s); for (int i = 0; i < s; i++) std::cin >> v[i]; } clock_t t = clock(); shaker(v); std::cout << clock() - t << " CPU Ticks\n" << compCount << " comparisons made\n" << moveCount << " move operations made\n"; }
true
40ff78d54d980de7984d640a2cf73a2699dcb8c2
C++
mlja226/TeensyCAN
/MotorNode/src/TeensyNode.h
UTF-8
1,319
3
3
[]
no_license
#ifndef TEENSY_NODE_H #define TEENSY_NODE_H #include <Arduino.h> #include <FlexCAN.h> #include <kinetis_flexcan.h> #include "CANMessage.h" #define MAX_ERRORS 10 /*TeensyNode: This class is meant to act as a parent class for current Teensy nodes * and a template for future node development. This class handles the basics of CANBus operations. */ class TeensyNode { private: //The bus we will be reading/writing from/to FlexCAN * CANBus; public: //TeensyNode Constructor: Takes a FlexCAN CANBus that is initialized and .start()-ed. //Start/stopping the bus should be handled outside this class. TeensyNode(FlexCAN &bus){ this->CANBus = &bus; } //Read from the CANBus //A filter may be added in child classes to only read certain messages int read(CANMessage &message){ CAN_message_t msg; int result = this->CANBus->read(msg); //Translate to FlexCAN for reading message.translateFromFlexCAN(msg); // Return the outcome of the read ( 1= Success. 0= Failure) return result; } //Write to CANBus int write(CANMessage message){ CAN_message_t msg; //Translate to FlexCAN for writing message.translateToFlexCAN(msg); int result = this->CANBus->write(msg); // Return the outcome of the write ( 1= Success. 0= Failure) return result; } }; #endif
true
468aac1709c4c5cd42312eb6170d58c858af26ec
C++
ceschoon/Boids
/lib/Math.cpp
UTF-8
2,134
3.46875
3
[]
no_license
//////////////////////////////////////////////////////////////////////////// // // // Source file for the implementation of // // some mathematical functions // // // // Author: Cédric Schoonen <cedric.schoonen1@gmail.com> // // September 2019, April 2020 // // // //////////////////////////////////////////////////////////////////////////// #include "Math.h" using namespace std; double min(double a, double b) {return (a<b)?a:b;} double max(double a, double b) {return (a>b)?a:b;} double distance(double x1, double y1, double x2, double y2) { return sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); } /* // Piece of code to artificially double the time this function takes double distance(double x1, double y1, double x2, double y2) { double eps = 1e-10*distance_(x1, y1, x2, y2); return distance_(x1, y1, x2, y2+eps); } */ // angle of 2 relative to 1 double angle(double x1, double y1, double x2, double y2) { double angle = 0; double dx = x2-x1; double dy = y2-y1; if (dx>0) angle = atan(dy/dx)*180/PI; else if (dx<0) angle = atan(dy/dx)*180/PI+180; else if (dx==0) { if (dy>0) angle = 90; else angle = -90; } return angle; } /* // Piece of code to artificially double the time this function takes double angle(double x1, double y1, double x2, double y2) { double eps = 1e-10*angle_(x1,y1,x2,y2); return angle_(x1,y1,x2,y2+eps); } */ // angle between 0 and 360 double angle360(double angle) { while (angle<0) angle += 360; while (angle>=360) angle -= 360; return angle; } // angle difference given between -180 and 180 double angleDifference(double angle1, double angle2) { double angleDiff = angle1-angle2; while (angleDiff<-180) angleDiff += 360; while (angleDiff>=180) angleDiff -= 360; return angleDiff; } double sigmoid(double x) { return tanh(x); }
true
55dd58195b42fa98fe57632a27753e8c2d66cdd5
C++
nkcr7/Beginning-Algorithm-Contests
/exercise-2-4-subsequence.cpp
UTF-8
282
2.84375
3
[]
no_license
#include <stdio.h> #include <math.h> int main() { int n,m; double sum=0; int count = 1; while(scanf("%d%d", &n, &m)==2 && !(n==0 && m==0)) { sum = 0; for(int i=n;i<=m;i++) { sum += 1.0 / pow(i,2); } printf("Case %d: %.5f\n", count, sum); count++; } return 0; }
true
f176efdd3fa77ab66b3d830f2600397efe9653a1
C++
MatanelAbayof/6-Colors
/oop2_ex4/ClientThread.cpp
UTF-8
2,377
3.03125
3
[ "Apache-2.0" ]
permissive
//---- include section ------ #include "ClientThread.h" #include "NetworkException.h" ClientThread::ClientThread() : INetworkThread(), m_connected(false) { } void ClientThread::start(const sf::IpAddress& serverIpAddress, const unsigned short port) { // check if thread is running already if (getState() == State::RUNNING) throw NetworkException("Client thread is running"); // init thread setRunningMode(); // create new thread m_thread = std::thread([this, &serverIpAddress, &port] { this->runClientThread(serverIpAddress, port); }); } bool ClientThread::isConnectedToServer() const { std::shared_lock<std::shared_mutex> lock(m_mutex); return m_connected; } string ClientThread::toString() const { return "ClientThread: { state=" + INetworkThread::toString() + " }"; } void ClientThread::runClientThread(const sf::IpAddress& serverIpAddress, const unsigned short port) { m_selector.clear(); // connect to server if (!tryConnectServer(serverIpAddress, port)) { exitThread(); return; } setAsConnected(true); // add socket to selector m_selector.add(m_socket); while (!isRequestedToExit()) { // wait to receive data if (m_selector.wait(sf::milliseconds(WAIT_TIME))) { if (m_selector.isReady(m_socket)) { // read message sf::Packet packet; if (m_socket.receive(packet) != sf::Socket::Done) { break; // exit } // call receive event onPacketReceived(m_socket, packet); } } // build packet sf::Packet packet; buildPacket(packet); // check if packet is not empty if (packet.getDataSize() > 0) { // send message to server if (m_socket.send(packet) != sf::Socket::Done) { //LOG("Client: send failed"); break; // exit } } } // exit from thread exitThread(); } bool ClientThread::tryConnectServer(const sf::IpAddress & serverIpAddress, const unsigned short port) { for (int i = 0; i < NUM_CONNECT_TIMES; i++) { sf::Socket::Status status = m_socket.connect(serverIpAddress, port); if (status == sf::Socket::Done) { return true; } // wait a little bit std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return false; } void ClientThread::setAsConnected(bool connected) { std::unique_lock<std::shared_mutex> lock(m_mutex); m_connected = connected; } void ClientThread::exitThread() { INetworkThread::exitThread(); setAsConnected(false); }
true
263d5d8bf656c17ec547e6bdce9e3b43217d8b1f
C++
evrimulgen/Studies
/L2/S4/HLIN401/TP/TP2/SolutionsFonctionMysterieuses.cpp
ISO-8859-1
1,354
3.515625
4
[]
no_license
#include <iostream> #include <cmath> #include <stdlib.h> /* atoi */ #include "fonctionsMysterieuses.h" int apuissanceb(int a, int b) { // renvoie a puissance b if (b==0) return 1; if (b % 2 == 0) return apuissanceb(a * a, b / 2); return a * apuissanceb(a,b-1);} int main(int argv, char** argc){ int numeroFonction = atoi(argc[1]), n = atoi(argc[2]), v; switch (numeroFonction) { case 1 : v=f1(n); break; // sqrt(n) * 3 case 2 : v=f2(n); break; // n^5 *1/10 case 3 : v=f3(n); break; // n * 1/2 case 4 : v=f4(n); break; //log (n) *2 case 5 : v=f5(n); break; // (2^n) *10 case 6 : v=f6(n); break; //(3^n) * 20 } std::cout<<"f"<<numeroFonction<<"("<<n<<") renvoie "<<v<<"\n"; for(int n=1; n < 20 ; n++){ std::cout<<"f"<<numeroFonction<<"("<<n<<") renvoie "<<f1(n)<<"\n"; float rap=(float)(f1(n)/sqrt(n)); std :: cout << rap << std :: endl; } return 0; } /* ordre de compilation : g++ SolutionsFonctionMysterieuses.cpp fonctionsMysterieuses.o -o test Ordre d'excution : ./test 1 2 */ /* Rponses : f6(n)=3^n * constante ------ constante=20 f5(n)=2^n * constante -------constante=10 f4(n)=log(n) * constante --------constante=2 f3(n)=2^n * constante ------- constante=1/2 f2(n)=5^n *constante ------ constante=1/10 f1(n)=sqrt(n) * constante ------ constante=3 */
true
44a02d2cf247bf3b2d506e4566c42ebba4687ffd
C++
amironi/Interviews
/SmTcp/Common/IntBuffer.h
UTF-8
374
2.5625
3
[]
no_license
#pragma once #include <vector> #include <list> using namespace std; class IntBuffer { public: IntBuffer(); IntBuffer(vector<char>& aBuffer); ~IntBuffer(); vector<char> mBuffer; int getInt(int aPos); int getIntList(list<int>& aList); void setIntList(list<int>& aList); void addInt(int aVal); char* get(); int size(); void sort(); void clear(); };
true
eb07a91455f01c3bfc823cdf3bcf7caa3444b400
C++
arisk1/algorithm-problems
/twitter_project/silhoutte.cpp
UTF-8
2,675
2.578125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <ctime> #include <algorithm> #include <bits/stdc++.h> #include "functions.h" #include "classes.h" #include "hashT.h" #include "initialization.h" #include "assignments.h" #include "update.h" #include "combinations.h" #include "silhoutte.h" double computeSilhoutte(hashTable &clusters,vector <double> centroids[],int i,int k,int metricN) { vector<Elements*> x = clusters.getVector(i); int sizeCluster = x.size(); if(sizeCluster == 0) {return -5;} double result = 0.0; for(vector<Elements*>::iterator it = x.begin();it != x.end(); ++it) { double res=0.0; double secres = 0.0; vector <double> y = (*it)->getVectorElem(); double dist1=0.0; int minC; for(int z=0;z<k;z++) { if(z!=i) { vector<double> x1 = centroids[z]; if(metricN==1) dist1 = calcEucledianDist(x1,y); else dist1=cosine_distance_vectors(x1,y); minC = z; } } for(int z=0;z<k;z++) //find second min centroid { if(z!=i) { double min; vector<double> x1 = centroids[z]; if(metricN==1) min = calcEucledianDist(x1,y); else min= cosine_distance_vectors(x1,y); if(min < dist1) { dist1 = min; minC = z; } } } vector<Elements*> x1 = clusters.getVector(minC); int sizeCluster2 = x1.size(); for(vector<Elements*>::iterator it2 = x1.begin();it2 != x1.end(); ++it2) //compute bi { double dist; vector <double> y2 = (*it2)->getVectorElem(); if(metricN==1) dist = calcEucledianDist(y,y2); else dist = cosine_distance_vectors(y,y2); secres += dist; } for(vector<Elements*>::iterator it2 = x.begin();it2 != x.end(); ++it2) //compute ai { double dist; vector <double> y2 = (*it2)->getVectorElem(); if(metricN==1) dist = calcEucledianDist(y,y2); else dist = cosine_distance_vectors(y,y2); res += dist; } double ai = res / sizeCluster; double bi = secres / sizeCluster2; double maxaibi=0.0; //find max of ai , bi if(ai > bi) maxaibi = ai; else maxaibi = bi; if(maxaibi == 0) { result += 0; } else { result += (bi - ai)/(maxaibi); } } if(sizeCluster!= 0 ) { result = result / sizeCluster; } return result; } int findCentroid(vector <double> centroid , int counterOfLines,Elements *data) { int pos=-1; for(int i=0;i<counterOfLines;i++) { vector<double> x = data[i].getVectorElem(); double dist = vectorEquality(centroid , x); if(dist == 1) { pos=i; break; } } return pos; }
true
68b50e5cb180d5a0aca4cf7e717abb003af9f51f
C++
vibhavjoshi123/interview-prep-cpp
/AlgoExpert/three-number-sum.cpp
UTF-8
670
3.234375
3
[]
no_license
#include <vector> #include <algorithm> using namespace std; vector<vector<int> > threeNumberSum(vector<int> array, int targetSum) { // Write your code here. sort(array.begin(), array.end()); int curr = 0; vector<vector<int>> result = {}; while (curr != array.size()-2) { int left = curr + 1; int right = array.size() - 1; while (left < right) { int sum = array[curr] + array[left] + array[right]; if (sum < targetSum) { left++; } else if (sum > targetSum) { right--; } else { result.push_back({array[curr], array[left], array[right]}); left++; right--; } } curr++; } return result; }
true
d4527cb82308b70a1ef1d0984c53ca9bf953a839
C++
hadley-siqueira/hdc
/src/ast/types/Int16Type.cpp
UTF-8
394
2.5625
3
[]
no_license
#include "ast/types/Int16Type.h" using namespace hdc; Int16Type::Int16Type() { this->kind = AST_INT16_TYPE; } Int16Type::Int16Type(Token& token) { this->token = token; this->kind = AST_INT16_TYPE; } Type* Int16Type::clone() { return new Int16Type(token); } int Int16Type::getRank() { return 6; } void Int16Type::accept(Visitor* visitor) { visitor->visit(this); }
true
7e6c81f72bf82770973b9a47e7b41f6f8c9c3af3
C++
MMMinoz/algorithm.problem.code
/CodeForces906D.cpp
UTF-8
1,074
2.59375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define ll long long const int maxn=1e5+5; ll a[maxn]; map<int,int> mp; ll qpow(ll a,ll b,ll mod) { ll res=1; while(b) { if(b&1) res=res*a>mod?res*a%mod+mod:res*a; a=a*a>mod?a*a%mod+mod:a*a; b>>=1; } return res; } ll phi(ll n) { ll res=n; for(int i=2;i*i<=n;i++) { if(n%i==0) { while(n%i==0) n/=i; res=res-res/i; } } if(n>1) res=res-res/n; return res; } ll Solve(int l,int r,ll m) { if(l==r) return a[r]; if(m==1||a[l]==1) return 1ll; ll p=mp[m]; return qpow(a[l],Solve(l+1,r,p),m); } int main() { int n; ll m; cin>>n>>m; for(int i=1;i<=n;i++) cin>>a[i]; //预处理m的所有欧拉函数 int cur=m; while(cur != 1) { mp[cur]=phi(cur); cur=phi(cur); } int q; cin>>q; while(q--) { int l,r; cin>>l>>r; cout<<Solve(l,r,m)%m<<endl; } }
true
96dd26174b5311354b14006b3643e3ffac39a26e
C++
MassimilianoRozza/EserciziLaboratorio
/Esercizi0/0.7_PariDispari.cpp
UTF-8
624
3.640625
4
[]
no_license
/* Scrivere un programma che prende un intero e verifica se questo è pari o dispari e scrive qualcosa a proposito. */ using namespace std; #include <iostream> int main(int argc, char const *argv[]) { int numero; cout<<"inserire un numero per verificare se sia pari, inserire 0 per uscire"<<endl; cin>>numero; cout<<endl<<endl; while (numero !=0) { if(numero%2==0){ cout<<" pari"<<endl; }else{ cout<<" dispari"<<endl; } cout<<"inserire il numero da verificare"<<endl; cin>>numero; } cout<<"fine del programma"; return 0; }
true
6d11b440956140a59be6ecce19cb49a4dc90c64c
C++
SilverHL/Leetcode
/474.一和零.cpp
UTF-8
1,062
2.6875
3
[]
no_license
#include <vector> #include <string> #include <cstring> using namespace std; /* * @lc app=leetcode.cn id=474 lang=cpp * * [474] 一和零 */ // @lc code=start class Solution { public: int* cnt1(string& s) { int count[2]; for (auto c : s) { count[c-'0']++; } return count; } int findMaxForm(vector<string>& strs, int m, int n) { int sz = strs.size(); int dp[m+1][n+1]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < sz; ++i) { vector<int> count(2, 0); for (auto c : strs[i]) { count[c-'0']++; } for (int j = m; j >= 0; --j) { for (int k = n; k >= 0; --k) { if (count[0] > j || count[1] > k) { dp[j][k] = dp[j][k]; } else { dp[j][k] = max(dp[j][k], dp[j-count[0]][k-count[1]]+1); } } } } return dp[m][n]; } }; // @lc code=end
true
7f44c1a6090cb940700de0c18bd88a87ffb07c9d
C++
sh4062/PAT
/A/1123.cpp
UTF-8
2,778
3.21875
3
[]
no_license
/* * File: 1123.cpp * Project: A * File Created: Tuesday, 26th February 2019 12:00:29 pm * Author: max (mx0666@163.com) * ----- * Last Modified: Tuesday, 26th February 2019 1:49:40 pm * Modified By: max (mx0666@163.com>) * ----- * Copyright 2018 - 2019 Your Company */ //这个题好难啊 写出4种旋转 #include <bits/stdc++.h> using namespace std; struct node { int var; node *l; node *r; }; int isC = 1, aft = 0; node *ll(node *rn) { node *tmp = rn->r;//tmp->r=rn->r->r;tmp->l=NULL; rn->r = tmp->l;//tmp = tmp->l tmp->l = rn;//tmp->l = rn return tmp; } node *rr(node *rn) { node *tmp = rn->l; rn->l = tmp->r; tmp->r = rn; return tmp; } node *rl(node *rn) { rn->r = rr(rn->r); return ll(rn); } node *lr(node *rn) { rn->l = ll(rn->l); return rr(rn); } int height(node *rn) { if (rn == nullptr) return 0; int l = height(rn->l); int r = height(rn->r); return max(l, r) + 1; } node *build(node *root, int val) { if (root == NULL) { root = new node(); root->var = val; } else if (root->var > val) { root->l = build(root->l, val); int l = height(root->l), r = height(root->r); if (l - r >= 2) { if (val < root->l->var) root = rr(root); else root = lr(root); } } else { root->r = build(root->r, val); int l = height(root->l), r = height(root->r); if (r - l >= 2) { if (val > root->r->var) root = ll(root); else root = rl(root); } } return root; } vector<int> levelorder(node *rn) { vector<int> v; queue<node *> queue; queue.push(rn); while (!queue.empty()) { node *temp = queue.front(); queue.pop(); v.push_back(temp->var); if (temp->l != NULL) { if (aft) isC = 0; queue.push(temp->l); } else { aft = 1; } if (temp->r != NULL) { if (aft) isC = 0; queue.push(temp->r); } else { aft = 1; } } return v; } int main() { int N; cin >> N; node *root = nullptr; for (int i = 0; i < N; i++) { int t; cin >> t; root = build(root, t); } //cout<<height(root)<<root->l->var<<root->r->var; vector<int> v = levelorder(root); for (int i = 0; i < v.size(); i++) { if (i != 0) cout << " "; cout << v[i]; } if (isC) { cout << "\nYES"; } else { cout << "\nNO"; } }
true
81df484e7af1f295a9e9f441b72902e51f8166bf
C++
Tsunuky/Rtype
/Client/includes/Graph/Objects.hpp
UTF-8
2,131
2.84375
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** Visual Studio Live Share (Workspace) ** File description: ** Objects */ #ifndef OBJSPRITE_HPP #define OBJSPRITE_HPP #include "IObject.hpp" class ObjSprite: public PrimaryObj { public: ObjSprite(std::shared_ptr<std::map<std::string, Sprite>> Sprites, std::shared_ptr<std::map<std::string, Texture*>> Textures, RenderWindow *Window, std::string path, Vector2f pos, bool visible) { _Window = Window; _Sprites = Sprites; _Textures = Textures; _pos = pos; _Sprite = createSprite(path); if (!_Sprite.getTexture()) { _Window->close(); throw RtypeException<CException::LibException>("Error ObjSprite"); } _Visible = visible; }; public: Sprite createSprite(std::string path) { if (!(*_Sprites).empty() && (*_Sprites).find(path) != (*_Sprites).end()) { return (*_Sprites)[path]; } _Sprite.setTexture(*createTexture(path)); setPosition(_pos); (*_Sprites)[path] = _Sprite; return (*_Sprites)[path]; }; Sprite createSprite(std::string path, IntRect rect) { if (!(*_Sprites).empty() && (*_Sprites).find(path) != (*_Sprites).end()) { return (*_Sprites)[path]; } _Sprite.setTexture(*createTexture(path)); setPosition(_pos); _Sprite.setTextureRect(rect); (*_Sprites)[path] = _Sprite; return (*_Sprites)[path]; }; bool getVisible() { return _Visible; }; void setVisible(bool visible) { //std::cout << visible << std::endl; _Visible = visible; }; void setPosition(Vector2f pos) { _Sprite.setPosition(pos); }; void setRotation(float pos) { _Sprite.setRotation(pos); }; void displaySprite() { if (_Visible) (*_Window).draw(_Sprite); } void setScale(float x, float y) { _Sprite.setScale(x , y); } private: RenderWindow *_Window; Sprite _Sprite; Vector2f _pos; std::shared_ptr<std::map<std::string, Sprite>> _Sprites; bool _Visible; }; #endif
true
c48f8fc3b87793ba3c5265537f07fff481d83246
C++
Rutvik1999/CPP_NCERT_class12
/C++89 Standard/Binary.search.cpp
UTF-8
773
3.3125
3
[]
no_license
#define max 100 int Bsearch(int a[],int s,int ele) { int beg=0,last = size -1,mid; for(int i =0;i<size;i++) { mid = (beg + last)/2; if(ele==a[mid]) return mid; elseif(ele>a[mid]) beg = mid + 1; else last = mid -1; } return -1; } int main(){ int a[max],size,ele,index; cout<<"Enter size of array"; cin>>size; for(int i=0;i<size;i++) { cout<<"Enter value "<<i+1<<":"; cin>>a[i]; } cout<<"Enter ele to be searched:"; cin>>ele; index=Bsearch(a,size,ele); if(index==-1) cout<<"ele not found....."; else cout<<"Ele found at position"<<index+1; return 0; }
true
619b7cf3f8e8dbe9a06b075203c03c38d2d7cd2e
C++
okokme/server-
/C++/gtest测试/my_class.h
UTF-8
173
2.90625
3
[]
no_license
#include <stdio.h> class MyClass { public: MyClass(int x) : x_(x) {} void SetX(int x) { x_ = x; } int GetX() const { return x_; } private: int x_; };
true
c33bd490dde71c4a20d72ae95a0b6e28ac232732
C++
Howard0o0/design-patterns-in-cpp
/src/observer/observertest.cc
UTF-8
645
3.046875
3
[]
no_license
#include "observer.h" #include <iostream> #include <string> void ObserverTest(); int main() { ObserverTest(); return 0; } void ObserverTest() { class BlogFollower : public observer::Observer { public: BlogFollower(const std::string& name) : name_(name) { } virtual void update() override { std::cout << name_ << " receive blog's update" << std::endl; } private: std::string name_; }; class Blog : public observer::Observable {}; BlogFollower* blog_follower = new BlogFollower("howard"); Blog csdn; blog_follower->observe(&csdn); csdn.notifyObservers(); delete blog_follower; csdn.notifyObservers(); }
true
2d11a1eba3113b055ce1083c5ed4929d653f978e
C++
HsuJv/Note
/Code/C/College/Data Structure/h/seqList.h
UTF-8
1,765
3.484375
3
[]
no_license
#ifndef SEQ_LIST_H #define SEQ_LIST_H #ifndef LINEAR_LIST_H #include "linearList.h" #endif // LINEAR_LIST_H template <class T> class seqList : public linearList<T> { public: seqList(int mSize){ maxLength = mSize; elements = new T[maxLength]; n = 0; } ~seqList() { delete[] elements;} bool IsEmpty() const {return n == 0;} int Length() const {return n;} bool Find(int i, T& x) const { if(i < 0 || i > n-1){ cout<<"Out of Bounds"<<endl; return false; } x = elements[i]; return true; } int Search(T x) const{ for(int j = 0; j < n; j++) if (elements[j] == x) return j; return -1; } bool Insert(int i, T x){ if (i < -1 || i > n-1){ cout << "Out of Bounds" << endl; return false; } if (n == maxLength){ cout << "OverFlow" << endl; return false; } for (int j = n-1; j > i; j--){ elements[j+1] == elements[j]; } n++; elements[i+1] = x; return true; } bool Delete(int i){ if(!n){ cout << "Underflow" << endl; return false; } if(i < 0 || i > n-1) { cout << "Out of Bounds" << endl; return false; } for(int j = i; j < n; j++) elements[j] = elements[j+1]; n--; return true; } bool Update(int i, T x){ if(i < 0 || i > n-1){ cout << "Out of Bounds" << endl; return false; } elements[i] = x; return true; } void Output(ostream& out) const { for(int i = 0; i < n; i++) out << elements[i] << " "; out << endl; } void Reverse(){ int i = 0,j = n-1; while(i < j){ T t = elements[i]; elements[i++] = elements[j]; elements[j--] = t; } } bool deleteX(const T& x){ bool ret = false; int del; while ((del = Search(x)) != -1) ret = Delete(del); return ret; } private: int maxLength; T *elements; int n; }; #endif // SEQ_LIST_H
true
4a747a71ef5f83a3b10ca001c6b3af5c0c3efc02
C++
Nickick-ICRS/dmt_project
/mbed/cynaptix_mbed/Web/messages.h
UTF-8
1,068
2.625
3
[]
no_license
#ifndef __MESSAGES_H__ #define __MESSAGES_H__ /********************************************** * This contains a bunch of definitions used * * by any networking class to know standard * * message contents * **********************************************/ // This is used in a few other files, so make it // super clear where things come from namespace Msgs { // Message start byte: Followed by: <message> MSG_END const char MSG_STRT = 0xFF; // Message end byte: Followed by: <N/A> const char MSG_END = 0xFE; // Target motor position (mm / deg): Followed by: <motor_num> <32 bit float> const char TRGT_MTR_POS = 0x03; // Measured motor torque (Nm): Followed by: <motor_num> <32 bit float> const char MTR_TRQ = 0x04; // Measured motor position (mm / deg): Followed by: <motor_num> <32 bit float> const char MTR_POS = 0x05; // Vibration motor strengths (%): Followed by: <9 bytes> const char VIB_STR = 0x06; // Motor names const char THUMB = 0x06; const char INDEX = 0x07; const char MIDDLE = 0x08; }; #endif // __MESSAGES_H__
true
2d6c504d6a9289a82c4d3f6f83d258f06a48f37a
C++
firepro20/labyrinthoftime
/Cell.h
UTF-8
769
2.625
3
[ "MIT" ]
permissive
#pragma once #include "modelclass.h" #include "pch.h" using namespace DirectX; class Cell { private: int cellState; DirectX::SimpleMath::Vector3 cellPosition; DirectX::SimpleMath::Vector3 cellCentre; DirectX::SimpleMath::Vector3 cellDimensions; public: Cell(); ~Cell(); void SetPosition(DirectX::SimpleMath::Vector3 position); void SetCentre(DirectX::SimpleMath::Vector3 centre); DirectX::SimpleMath::Vector3 GetPosition(); DirectX::SimpleMath::Vector3 GetDimensions(); DirectX::SimpleMath::Vector3 GetCentre(); void SetState(int state); int GetState(); // A star // Row and Column index of its parent // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 int parent_x, parent_z; // f = g + h double f, g, h; };
true
ab516cb42f43cea8da34dd948db082643b050e21
C++
mob141043/Leetcode_Solutions
/leetCode_solution/leetCode_solution/TwoSum.cpp
UTF-8
516
3.34375
3
[]
no_license
#include <iostream> #include<vector> #include<map> using namespace std; vector<int> twoSum(vector<int>& nums, int target) { map<int, int> map; int size = nums.size(); int complement = 0; for (int i = 0; i < size; i++) { map[nums[i]] = i; } for (int i = 0; i < size; i++) { complement = target - nums[i]; if (map.count(complement) && map[complement] != i) { return { map[complement] ,i }; } } return { 0,0 }; } int main() { map<int, int> map; map[1] = 1; map[1] = 2; cout << map.count(1); }
true
a13a5fd0dc4d26989c4bd70e093ba2384dc16f4b
C++
s-e-a-70/Balls
/one_ball.cpp
UTF-8
1,877
3.015625
3
[]
no_license
#include "TxLib.h" void Balls_Move(); void Draw_Ball (int x, int y, COLORREF border_color, COLORREF fill_color); void Physics_Ball (int *x, int *y, int *vx, int *vy, int ax, int ay, int dt); void Control_Ball (int *x, int *y, int *vx, int *vy); //----------------------------------------------------- int main() { txCreateWindow (800, 600); Balls_Move(); return(0); } //----------------------------------------------------- void Balls_Move() { int x = 100; int y = 0; int vx = 5; int vy = 3; int ax = 0; int ay = 1; int dt = 1; while (!txGetAsyncKeyState (VK_ESCAPE)) { Draw_Ball (x, y, TX_MAGENTA, TX_LIGHTMAGENTA); Physics_Ball (&x, &y, &vx, &vy, ax, ay, dt); Control_Ball (&x, &y, &vx, &vy); txSleep (100); } } //----------------------------------------------------- void Draw_Ball(int x, int y, COLORREF border_color, COLORREF fill_color) { txSetColor (border_color); txSetFillColor (fill_color); txCircle (x, y, 20); } void Physics_Ball(int *x, int *y, int *vx, int *vy, int ax, int ay, int dt) { *vx += ax*dt; *vy += ay*dt; *x+= *vx*dt; *y+= *vy*dt; } void Control_Ball(int *x, int *y, int *vx, int *vy) { if (*x > 800) { *vx = -(*vx); *x = 800; } if (*y > 600) { *vy = -(*vy); *y = 600; } if (*x < 0) { *vx = -(*vx); *x = 0; } if (*y < 0) { *vy = -(*vy); *y = 0; } if(txGetAsyncKeyState (VK_RIGHT)) *vx++; if(txGetAsyncKeyState (VK_LEFT)) *vx--; if(txGetAsyncKeyState (VK_UP)) *vy++; if(txGetAsyncKeyState (VK_DOWN)) *vy--; if(txGetAsyncKeyState (VK_SPACE)) {*vx = 0; *vy = 0;} }
true
80752d71d5b8bfa4813239cff72d7e13f7a86363
C++
jgalfaro/mirrored-tbridge-modbus
/cpp/cpp/TollSim.cpp
UTF-8
1,468
2.703125
3
[]
no_license
#include <stdio.h> #include <cstdio> #include <jni.h> #ifdef _WIN32 #define PATH_SEPARATOR ';' #include <tchar.h> #else #define PATH_SEPARATOR ':' #endif int main() { JavaVM *jvm; /* denotes a Java VM */ JNIEnv *env; /* pointer to native method interface */ JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */ JavaVMOption* options = new JavaVMOption[1]; char classpath[100]; #ifdef _WIN32 sprintf_s(classpath, "%s%c%c%s%c%s", "-Djava.class.path=", '.', PATH_SEPARATOR, ".\\wimpi.jar", PATH_SEPARATOR, ".\\libs\\wimpi.jar"); #else sprintf(classpath, "%s%c%c%s%c%s", "-Djava.class.path=", '.', PATH_SEPARATOR, "./wimpi.jar", PATH_SEPARATOR, "./libs/wimpi.jar"); #endif options[0].optionString = classpath; vm_args.version = JNI_VERSION_1_6; vm_args.nOptions = 1; vm_args.options = options; vm_args.ignoreUnrecognized = false; /* load and initialize a Java VM, return a JNI interface pointer in env */ long status = JNI_CreateJavaVM(&jvm, (void **)&env, &vm_args); delete options; if (status != JNI_ERR){ jclass clToll = env->FindClass("Main"); if (clToll != NULL){ jmethodID main = env->GetStaticMethodID(clToll, "main", "([Ljava/lang/String;)V"); env->CallStaticVoidMethod(clToll, main, NULL); } else{ printf("Error Finding class\n"); } jvm->DestroyJavaVM(); }else{ printf("Cannot initialize Java Virtual Machine"); } return 0; }
true
900f9d43b6860782340ccbf0b67fea992937e5de
C++
kabukunz/meshlib
/algorithm/riemannian/Delaunay/DelaunayRefineMesh.h
UTF-8
2,514
3.046875
3
[]
no_license
/*! \file DelaunayRefineMesh.h * \brief Mesh Refinement using Delaunay Triangulation * \date Documented on 10/15/2010 * * Adding Steiner points to an existing mesh to improve the mesh quality. The input mesh must not have * flipped faces. In practice, we prefer to use harmonic mapping result as the input mesh, instead of Riemann mapping result. */ #ifndef _DELAUNAY_REFINE_MESH_H_ #define _DELAUNAY_REFINE_MESH_H_ #include <map> #include <vector> #include <queue> #include "DelaunayMesh.h" namespace MeshLib { /*! \brief CDeluanayRefineMesh class * * Mesh Refinement using Delaunay Triangulation */ template<typename V, typename E, typename F, typename H> class CDelaunayRefineMesh : public CDelaunayMesh<V,E,F,H> { public: /*! * Refine a input mesh with uv coordinates * \param input_mesh input mesh file name */ void Refine( CDelaunayRefineMesh<V,E,F,H> & input_mesh ); }; //refine the mesh triangulation template<typename V, typename E, typename F, typename H> void CDelaunayRefineMesh<V,E,F,H>::Refine( CDelaunayRefineMesh<V,E,F,H> & input_mesh ) { _initialize( true ); //grading false = consider area; grading true, don't care area m_max_number_vertices = input_mesh.numVertices() * 2; CBoundary bnd( &input_mesh ); std::vector<CLoop*> & loops = bnd.loops(); CLoop * pL = loops[0]; std::list<H*> & hs = pL->halfedges(); std::vector<V*> segment_verts; for( std::list<H*>::iterator hiter = hs.begin() ; hiter != hs.end(); hiter ++ ) { H * pH = *hiter; V * pV = halfedgeSource( pH ); V * pW = NULL; _insert_vertex( pV->uv(), pW ); pW->father() = pV->id(); pW->point() = pV->point(); segment_verts.push_back( pW ); m_inputVertexNum ++; } for( size_t i = 0; i < segment_verts.size(); i ++ ) { V * v0 = segment_verts[i]; V * v1 = segment_verts[(i+1)%segment_verts.size()]; CSegment<V> * pS = _create_segment( v0, v1); } int c = 0; //input interior vertices for( MeshVertexIterator viter( &input_mesh ); !viter.end(); viter ++ ) { V * pV = *viter; V * pW = NULL; if( pV->boundary() ) continue; printf( "%d/%d\n", ++c, input_mesh.numVertices() ); _insert_vertex( pV->uv(), pW ); pW->father() = pV->id(); pW->point() = pV->point(); } //insert points _insert_missing_segments(); _freeze_edges_on_segments(); _classify_inside_outside(); RemoveBadTriangles( 30 ); } typedef CDelaunayRefineMesh<CDelaunayVertex, CDelaunayEdge, CDelaunayFace, CDelaunayHalfEdge> CDRTMesh; } #endif _DELAUNAY_REFINE_MESH_
true
12046575e702f6f054157a363ca4da420e8909e4
C++
cdessers/Effect-of-electromagnetic-radiation-on-the-brain
/Array_3D_Template.h
UTF-8
1,011
3.40625
3
[]
no_license
#ifndef ARRAY_3D_TEMPLATE_H #define ARRAY_3D_TEMPLATE_H #include <cstdio> #include <iostream> #include <vector> using namespace std; template <typename T> class Array_3D_Template{ private: // Data: T *data = NULL; // Sizes along x, y and z: size_t Nx, Ny, Nz; // Boolean to check if data has already been allocated: bool dataAlreadySet = false; public: // Default constructor: Array_3D_Template(){}; // Constructor: Array_3D_Template(const size_t &Nx, const size_t &Ny, const size_t &Nz); // Copy constructor: Array_3D_Template(const Array_3D_Template &obj); // Destructor: ~Array_3D_Template(void); // Accessor: T& operator()(const size_t i, const size_t j, const size_t k); // Filler (fill the data field with a given value): void fillIn(T val); // Get the size of the array: vector<size_t> get_size_data(void); // Set the size of the array: void set_size_data(const size_t &Nx, const size_t &Ny, const size_t &Nz); }; #include "Array_3D_Template.tpp" #endif
true
e142c82f0cbb65aa658fb24a55c881baf9664b19
C++
mohitnitrr/Competitive-Programming
/HackerRank/ConsoleApplication1/ConsoleApplication1/KthSmallest.cpp
UTF-8
915
3.171875
3
[]
no_license
#include"bits_stdc.h" void heapify(vector<int> &A, int i = 0) { while (i <= (A.size()-1)/2) { int left = 2 * i + 1; int right = 2 * (i + 1); int largest = i; if (left < A.size() && A[left] > A[largest]) largest = left; if (right < A.size() && A[right] > A[largest]) largest = right; if (largest != i) swap(A[largest], A[i]); else break; i = largest; } } void constructHeap(vector<int> &A) { for (int i = A.size()-1; i >=0; i--) { int parent = (i - 1) / 2; heapify(A, parent); } } int kthsmallest(const vector<int> &A, int B) { vector<int> heap(A.begin(), A.begin() + B); constructHeap(heap); for (int i = B; i < A.size(); i++) { if (A[i] < heap[0]) { heap[0] = A[i]; heapify(heap); } } return heap[0]; } int main_intBit57(){ vector<int> inputs = { 5, 42, 36, 81, 70, 35, 93, 41, 92, 14, 15, 50, 100, 51 }; cout << kthsmallest(inputs, 11); return 0; }
true
f9653f11c9201fe1e3cea320592dd59c7c510b1b
C++
FireFoxPlus/CrackInterview
/c++ code/CCrackCodeInterview/reverse.cpp
UTF-8
297
2.875
3
[]
no_license
#include "reverse.h" char *reverseString::reverseStr(char *str , int length) { char *rs = new char[length + 1]; rs[length] = '\0'; int ends = length - 1 , start = 0; while(start < length) { rs[start] = str[ends]; start++; ends--; } return rs; }
true
5fb9ee0fd1c2f3e2d829300ca9719c31cea6df1c
C++
api7/mod_dubbo
/utils/utils.cc
UTF-8
3,032
2.890625
3
[ "BSD-2-Clause" ]
permissive
#ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "utils.h" #include <string> #include <sstream> #include <ostream> #include <inttypes.h> namespace hessian { using namespace std; int ngx_hessian_is_big_endian() { const int n = 1; if(*(char *)&n) { return 0; } return 1; } union double_int64 { double dval; int64_t lval; }; int64_t double_to_long(double dval) { // *(int64_t*)(&d_val) union double_int64 x; x.dval = dval; return x.lval; } double long_to_double(int64_t lval) { // *(double*)(&lval) union double_int64 x; x.lval = lval; return x.dval; } string bool_to_string(bool bval) { return bval ? string("true") : string("false"); } string int32_to_string(int32_t ival) { char buff[32]; return string(buff, snprintf(buff, sizeof(buff), "%" PRId32, ival)); } string int64_to_string(int64_t lval) { char buff[32]; return string(buff, snprintf(buff, sizeof(buff), "%" PRId64, lval)); } string double_to_string(double dval) { char buff[32]; return string(buff, snprintf(buff, sizeof(buff), "%f", dval)); } int32_t cstr_to_int32(const char* cstr) { return strtol(cstr, NULL, 0); } int64_t cstr_to_int64(const char* cstr) { #if __WORDSIZE == 64 return strtol(cstr, NULL, 0); #else return strtoll(cstr, NULL, 0); #endif } double cstr_to_double(const char* cstr) { return strtod(cstr, NULL); } string to_hex_string(const void* ch, size_t size) { static char alpha[] = "0123456789ABCDEF"; string hex_str; hex_str.reserve(size * 3); for (size_t i = 0; i < size; ++i) { uint8_t c = *((const uint8_t*)ch + i); hex_str.push_back(alpha[c >> 4]); hex_str.push_back(alpha[c & 0xF]); hex_str.push_back(' '); } return hex_str; } void write_hex_to_stream(ostream& os, const void* ch, size_t size) { static char alpha[] = "0123456789ABCDEF"; string hex_str; for (size_t i = 0; i < size; ++i) { uint8_t c = *((const uint8_t*)ch + i); os << alpha[c >> 4] << alpha[c & 0xF] << ' '; } } /** * debug function * @param caption title, not output when NULL * @param ptr start pos need output * @param len len nedd output */ void hexdump(const char* caption, const void* ptr, unsigned int len) { unsigned char* buf = (unsigned char*) ptr; unsigned int i, j; if (caption) printf("\n%s (%p@%d)\n", caption, ptr, len); for (i=0; i < len; i+=16) { printf("%08x ", i); for (j=0; j<8; j++) if (i+j < len) printf("%02x ", buf[i+j]); else printf(" "); printf(" "); for (; j<16; j++) if (i+j < len) printf("%02x ", buf[i+j]); else printf(" "); printf(" |"); for (j=0; j<16; j++) if (i+j < len) printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.'); printf("|\n"); } printf("%08x\n", len); } }
true
531c1356e1e6e3002a5d8fd5219dac03c6ef63d9
C++
007atulpandey/COMPETITIVE_PROGRAMMING_TEMPLATE
/template_extra/templates/graph.cpp
UTF-8
783
2.8125
3
[]
no_license
struct graph { int n; vector<bool> vis; vector<vector<int> > edges; void init(int size) { n = size; vis = vector<bool>(n); edges = vector<vector<int> >(n); } void readGraph(int numEdges, bool isTheGraphUndirected) { f0r(i, numEdges) { int u, v; cin >> u >> v; --u; --v; edges[u].pb(v); if (isTheGraphUndirected) edges[v].pb(u); } } void bfs(int sourceVertex) { fill(vis.begin(), vis.end(), false); queue<int> q; q.push(sourceVertex); while (!q.empty()) { int focusedVertex = q.front(); q.pop(); if (vis[focusedVertex]) continue; vis[focusedVertex] = 1; for (int i: edges[focusedVertex]) { if (vis[i]) continue; q.push(i); } } } };
true
e2f5c367ef1201594062db28489bbf0635531199
C++
cats9rule/sp-lab
/Stack/Stack/main.cpp
UTF-8
151
2.828125
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { string njanja = "HELLO WORLD"; for (char c : njanja) { cout << c; } }
true
f51dffb1dcec89b999aee92f42904d9ad676a389
C++
HiTech2019/dsa
/datastructure/depthFirstSearch.cpp
UTF-8
3,088
3.734375
4
[]
no_license
/* * http://www.cnblogs.com/dolphin0520/archive/2011/08/25/2153720.html * 树的3种深度遍历:前、中、后 * 递归和非递归 */ class DepthFirstSearch{ void preTravel(BiTree* root) { if(!root){ return; } cout << root->data; preTravel(root->left); preTravel(root->right); } void inTravel(BiTree* root) { if(!root){ return; } preTravel(root->left); cout << root->data << ' '; preTravel(root->right); } void postTravel(BiTree* root) { if(!root){ return; } preTravel(root->left); preTravel(root->right); cout << root->data << ' '; } void preTravelNonRecur(BiTree* root) { if(root) { stack<BiTree*> st; st.push(root); while(!st.empty()) { BiTree* tmp = st.top(); st.pop(); cout << tmp->data << ' '; if(tmp->right) { st.push(tmp->right); } if(tmp->left) { st.push(tmp->left); } } } } void inTravelNonRecur(BiTree* root) { if(root) { stack<BiTree*> st; BiTree* cur = root; while(cur || !st.empty()) { //直到P为NULL并且栈为空则遍历结束 while(cur) { //当前节点不为空就压入他的左子树 st.push(cur); cur = cur->left; } if(!st.empty()) { //压完之后不空就弹出 BiTree* tmp = st.top(); st.pop(); cout << tmp->data << ' '; cur = tmp->right; //准备下次循环压入右子树 } } } } /* * 对于任一结点P, 先将其入栈. * 如果P不存在左孩子和右孩子, 则可以直接访问它 * 或者P存在左孩子或者右孩子, 但是其左孩子和右孩子都已被访问过了, 则同样可以直接访问该结点. * 若非上述两种情况, 则将P的右孩子和左孩子依次入栈 */ void postTravelNonRecur(BiTree* root) { if(root) { stack<BiTree*> st; BiTree* cur; BiTree* pre = NULL; st.push(root); while(!st.empty()) { cur = st.top(); //如果当前结点没有孩子结点或者孩子节点都已被访问过 if((!cur->left && !cur->right) || (pre && (pre == cur->left || pre == cur->right))) { cout << cur->data << ' '; st.pop(); pre = cur; } else { if(cur->right) { st.push(cur->right); } if(cur->left) { st.push(cur->left); } } } } } };
true