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
a357c53991eb79b3035b16ad09c9160bf7c606b4
C++
benardp/Radium-Engine
/src/Engine/Scene/SpotLight.hpp
UTF-8
1,739
2.515625
3
[ "Apache-2.0" ]
permissive
#pragma once #include <Core/Math/Math.hpp> #include <Engine/RaEngine.hpp> #include <Engine/Scene/Light.hpp> namespace Ra { namespace Engine { namespace Scene { class Entity; /** Spot light for rendering. * */ class RA_ENGINE_API SpotLight final : public Ra::Engine::Scene::Light { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW explicit SpotLight( Entity* entity, const std::string& name = "spotlight" ); ~SpotLight() override = default; void getRenderParameters( Data::RenderParameters& params ) const override; void setPosition( const Eigen::Matrix<Scalar, 3, 1>& position ) override; inline const Eigen::Matrix<Scalar, 3, 1>& getPosition() const; void setDirection( const Eigen::Matrix<Scalar, 3, 1>& direction ) override; inline const Eigen::Matrix<Scalar, 3, 1>& getDirection() const; inline void setInnerAngleInRadians( Scalar angle ); inline void setOuterAngleInRadians( Scalar angle ); inline void setInnerAngleInDegrees( Scalar angle ); inline void setOuterAngleInDegrees( Scalar angle ); inline Scalar getInnerAngle() const; inline Scalar getOuterAngle() const; inline void setAttenuation( const Attenuation& attenuation ); inline void setAttenuation( Scalar constant, Scalar linear, Scalar quadratic ); inline const Attenuation& getAttenuation() const; std::string getShaderInclude() const override; private: Eigen::Matrix<Scalar, 3, 1> m_position {0, 0, 0}; Eigen::Matrix<Scalar, 3, 1> m_direction {0, -1, 0}; Scalar m_innerAngle {Core::Math::PiDiv4}; Scalar m_outerAngle {Core::Math::PiDiv2}; Attenuation m_attenuation {1, 0, 0}; }; } // namespace Scene } // namespace Engine } // namespace Ra #include "SpotLight.inl"
true
8c2ed6638ad32914b52ea3e9260bdc8b73a5c327
C++
joarley/_riskemu
/shared/minilzo/MiniLZO.h
UTF-8
1,624
2.71875
3
[]
no_license
#ifndef _RISKEMULIBRARY_MINILZO_MINILZO_H_ #define _RISKEMULIBRARY_MINILZO_MINILZO_H_ #include "stdtypes.h" #include <vector> class MiniLZO { public: static bool Compress(byte *src, size_t srcLen, byte *&dst, size_t &dstLen); static bool Decompress(byte *src, size_t srcLen, byte *&dst, size_t &dstLen); private: static const uint32 M2_MAX_LEN = 8; static const uint32 M3_MAX_LEN = 33; static const uint32 M4_MAX_LEN = 9; static const byte M3_MARKER = 32; static const byte M4_MARKER = 16; static const uint32 M1_MAX_OFFSET = 0x0400; static const uint32 M2_MAX_OFFSET = 0x0800; static const uint32 M3_MAX_OFFSET = 0x4000; static const uint32 M4_MAX_OFFSET = 0xbfff; static const byte BITS = 14; static const uint32 D_MASK = (1 << BITS) - 1; static const uint32 DICT_SIZE = 65536 + 3; inline static uint32 D_INDEX1(byte *input) { return D_MS(D_MUL(0x21, D_X3(input, 5, 5, 6)) >> 5, 0); } inline static uint32 D_INDEX2(uint32 idx) { return (idx & (D_MASK & 0x7FF)) ^ (((D_MASK >> 1) + 1) | 0x1F); } inline static uint32 D_MS(uint32 v, byte s) { return (v & (D_MASK >> s)) << s; } inline static uint32 D_MUL(uint32 a, uint32 b) { return a * b; } inline static uint32 D_X2(byte* input, byte s1, byte s2) { return (uint32) ((((input[2] << s2) ^ input[1]) << s1) ^ input[0]); } inline static uint32 D_X3(byte* input, byte s1, byte s2, byte s3) { return (D_X2(input + 1, s2, s3) << s1) ^ input[0]; } }; #endif //_RISKEMULIBRARY_MINILZO_MINILZO_H_
true
88f54583d7dc401dc3d903dc5551c32d08ca75a8
C++
vipsinha/CPlusPlus
/HackerRank/2_Variable_Sized_Arrays.cpp
UTF-8
907
3.140625
3
[]
no_license
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n,q; int index, jndex; //cout << "Input the array size and query" << endl; cin >> n >> q; vector < vector<int> > outerVector; for(index=0;index<n;index++){ vector<int> innerVector; int k; int data; //cout << "Enter the size and array" << endl; cin >> k; for(jndex=0;jndex<k;jndex++){ cin >> data; innerVector.push_back(data); } outerVector.push_back(innerVector); } //cout << "Enter the indexs" << endl; for(int i=0; i<q;i++){ cin >> index >> jndex; cout << outerVector[index][jndex] << endl; } return 0; }
true
c1d2027c71070e16c1a2b779f4ba7e9d076dc56a
C++
NNNILabs/SimpleArduinoCLI
/sketch_feb02a.ino
UTF-8
3,599
3.484375
3
[]
no_license
#define BUF_WIDTH 30 #define newline Serial.print('\n') //Array 'input' holds the string taken from the serial buffer ' //'Holder' contains three strings, one for the operation and two for the operands. char input[BUF_WIDTH], holder[3][BUF_WIDTH]; //Calling 'reset()' anywhere in the program software resets the microcontroller. void(* reset) (void) = 0; void setup() { Serial.begin(9600); Serial.print("Simple Arduino CLI"); newline; } void loop() { handleMenu(); } //'tokenize()' separates the operation and operands and puts them in 'holder'. void tokenize(char string[BUF_WIDTH]) { char * valPosition = strtok(string, " "); strcpy(holder[0], valPosition); int i = 1; while (valPosition != NULL) { valPosition = strtok(NULL, " "); strcpy(holder[i], valPosition); i = i + 1; } } //'interpret' reads the operation and acts on the operands void interpret(char opcode[BUF_WIDTH], int operandOne, int operandTwo) { if (strcmp(opcode, "digitalWrite") == 0) { digitalWrite(operandOne, operandTwo); } else if (strcmp(opcode, "digitalRead") == 0) { Serial.print(digitalRead(operandOne)); newline; } else if (strcmp(opcode, "toggle") == 0) { if(digitalRead(operandOne) == LOW) { digitalWrite(operandOne, HIGH); } else { digitalWrite(operandOne, LOW); } } else if (strcmp(opcode, "delay") == 0) { delay(operandOne); } else if (strcmp(opcode, "analogRead") == 0) { Serial.print(analogRead(operandOne)); newline; } else if (strcmp(opcode, "pullup") == 0) { pinMode(operandOne, INPUT_PULLUP); Serial.print("Pullup "); Serial.print(operandOne); newline; } else if (strcmp(opcode, "disablePullup") == 0) { pinMode(operandOne, INPUT); Serial.print("No pullup "); Serial.print(operandOne); newline; } else if (strcmp(opcode, "pulse") == 0) { digitalWrite(operandOne, HIGH); delay(operandTwo); digitalWrite(operandOne, LOW); } else if (strcmp(opcode, "pulseMicroseconds") == 0) { digitalWrite(operandOne, HIGH); delayMicroseconds(operandTwo); digitalWrite(operandOne, LOW); } else if (strcmp(opcode, "exit") == 0) { } else { Serial.print("Invalid!"); newline; } } //'getString(array)' reads a string from the serial monitor and put it in 'array'. void getString(char output[BUF_WIDTH]) { while (!Serial.available()); String in = Serial.readStringUntil('\n'); in.trim(); in.toCharArray(output, BUF_WIDTH); } //'handleMenu()' handles the initial menu. void handleMenu() { Serial.print(">> "); getString(input); Serial.print(input); newline; if (strcmp(input, "reset") == 0) { delay(50); reset(); } //Typing 'time' into the serial monitor displays the time in seconds since the processor was last reset. else if (strcmp(input, "time") == 0) { Serial.print(millis() / 1000); Serial.print(" seconds"); newline; } //Type 'int' to enter the interpreter. else if (strcmp(input, "int") == 0) { handleInterpreter(); } else { Serial.print("Invalid!"); newline; } } void handleInterpreter() { strcpy(input, '\0'); while (strcmp(input, "exit") != 0) { Serial.print("-> "); getString(input); Serial.print(input); newline; tokenize(input); interpret(holder[0], atoi(holder[1]), atoi(holder[2])); } }
true
47bfc71dd37ab3adcc19e98fcc1826b20c3d3ed5
C++
dcxcn/MyMap
/MyMap/src/operation/operationlist.h
UTF-8
1,198
2.78125
3
[ "MIT" ]
permissive
/************************************************************* ** class name: OperationList ** ** description: Record operations(Move, Delete, rotate features) ** Support undo and redo. ** ** last change: 2020-03-26 **************************************************************/ #ifndef OPERATIONLIST_H #define OPERATIONLIST_H #include "operation/operation.h" class OperationList { public: OperationList(); ~OperationList(); public: void setOpenglWidget() {} void setMaxOperations(int maxSize); void clear(); bool isAtBeginning() const { return (!isOverrided) && (curr - 1 == first); } void addOperation(Operation* operation); Operation* undo(); Operation* redo(); Operation* addDeleteOperation(const FeaturesList& features); Operation* addMoveOperation(const FeaturesList& features, double xOffset, double yOffset); Operation* addRotateOperation(const FeaturesList& features, double angle); private: /* Record 20 steps at most, change by call setMaxOperations(int) */ Operation** list = nullptr; int MAX_SIZE = 20; int curr = 1; int first = 0; bool isOverrided = false; }; #endif // OPERATIONLIST_H
true
1aa819ea2946c9536cacd659190e844e1fc062ba
C++
JordanSamhi/VoronoiDiagramTurtleShell
/modele/triangulation/equationdroitebase.h
UTF-8
482
2.828125
3
[ "MIT" ]
permissive
#ifndef EQUATIONDROITEBASE_H #define EQUATIONDROITEBASE_H #include <iostream> #include <string> #include "modele/point.h" using namespace std; class EquationDroiteBase{ public: EquationDroiteBase(); virtual operator string() const = 0; virtual EquationDroite * getEquationDroitePerpendiculairePassantParPoint(Point *)const=0; }; inline ostream & operator <<(ostream & f, const EquationDroiteBase & edb) { return f << (string)edb; } #endif // EQUATIONDROITEBASE_H
true
385788168470752c962e0389d3ce3d7ad0f379d8
C++
1share/onecodeoneday
/20171115/game.cpp
UTF-8
497
2.9375
3
[]
no_license
#include<iostream> #include "game.h" using namespace std; using namespace mycode; gameboard::gameboard(int w, int h):mw(w),mh(h) { msheet = new sheet(mw,mh); } gameboard::~gameboard() { delete msheet; } void gameboard::setCell(int x, int y, const cell &data) { msheet->setCell(x, y, data); } cell &gameboard::getCell(int x, int y) const{ return msheet->getCell(x,y); } int main() { gameboard gb(10,10); gb.setCell(3,4,9); cout<<gb.getCell(3,4).getDoubleValue()<<endl; return 0; }
true
932ea7b3d9753eb9810ae117d6c908053a379f53
C++
anntom/Matrix
/main.cpp
UTF-8
1,140
3.3125
3
[]
no_license
#include <fstream> #include <vector> #include <iostream> #include <string> #include "Matrix.h" #include "time.h" using namespace std; bool read(const char * path, Matrix &mat) { ifstream f(path); if (f.is_open()) { try{ f>>mat; } catch(const char* str){ cout << str << endl; return false; } return true; } else { throw MyException("Can't open file"); return false; } } int main(int argc, char * argv[]) { Matrix mat1, mat2; if (argc != 4) { cout << "Enter path to file" << endl; return -1; } else { string path1 = argv[1]; string path2 = argv[2]; string path_out = argv[3]; bool read1, read2; try{ read1 = read(path1.c_str(), mat1); read2 = read(path2.c_str(), mat2); } catch(const char* str){ cout << str << endl; } if (read1 && read2) { time_t start; time_t end; start = clock(); Matrix res = mat1 * mat2; end = clock(); cout << difftime(end, start) << endl; ofstream f(path_out); if (f.is_open()) { f<<res; } else { cout << "Can't open file" << endl; return -1; } } else { return -1; } } return 0; }
true
80890f12f0970cb0fc61d1f9c2be4c5f52f5dec5
C++
very-indecisive-studios/chaos-chef
/src/game/entity/player/player.h
UTF-8
1,606
2.578125
3
[]
no_license
#pragma once #include <iostream> #include <string> #include "core/sprites/animatedSprite.h" #include "game/resources.h" #include "playerHand.h" #include "game/entity/gameEntity.h" #include "core/audio/audio.h" class Player : public GameEntity { private: UCHAR playerKeyUp = VK_UP; UCHAR playerKeyDown = VK_DOWN; UCHAR playerKeyLeft = VK_LEFT; UCHAR playerKeyRight = VK_RIGHT; UCHAR actionKey = VK_SPACE; AnimatedSprite *currentAnimSprite = nullptr; AnimatedSprite *northAnimSprite = AnimatedSprite::Create(PLAYER_NORTH_IMAGE, 1, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_ANIMATION_DELAY); AnimatedSprite *eastAnimSprite = AnimatedSprite::Create(PLAYER_EAST_IMAGE, 1, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_ANIMATION_DELAY); AnimatedSprite *southAnimSprite = AnimatedSprite::Create(PLAYER_SOUTH_IMAGE, 1, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_ANIMATION_DELAY); AnimatedSprite *westAnimSprite = AnimatedSprite::Create(PLAYER_WEST_IMAGE, 1, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_ANIMATION_DELAY); AnimatedSprite *deadAnimSprite = AnimatedSprite::Create(PLAYER_DEAD_IMAGE, 1, PLAYER_WIDTH, PLAYER_HEIGHT, PLAYER_ANIMATION_DELAY); AudioPlayer *splatSoundPlayer; AudioPlayer *deathSoundPlayer; PlayerHand hand; bool playerDead = false; float playerSpeed = 200.0f; void Move(float deltatime); void GetPlatedFood(GameEntity *entity); void BlockPlayer(GameEntity *entity); public: Player(); ~Player(); UCHAR GetActionKey() { return actionKey; } std::vector<const PlatedFood *> Give(); void HandleCollision(GameEntity *entity) override; bool isDead(); void Update(float deltaTime) override; };
true
284272756ce92a7c233110becd05df8640607061
C++
ASharpy/AI-Project
/project2D/StateManager.cpp
UTF-8
1,904
3.140625
3
[ "MIT" ]
permissive
#include "StateManager.h" #include "State.h" #include "Exception.h" StateManager::StateManager() { } StateManager::~StateManager() { } void StateManager::updateState(float deltaTime) { doCommands(); for (auto &var : activeStates) { var->update(deltaTime); } } void StateManager::RenderState() { for (auto &var : activeStates) { var->render(); } } void StateManager::registerState(int ID, State * state) { exceptASSERT(ID < 6 && ID >= 0); commands command; command.id = ID; command.command = commandTypes::REGISTER; command.commandState = state; commandList.pushBack(command); } void StateManager::pushState(int ID) { exceptASSERT(ID < 6 && ID >= 0); commands command; command.id = ID; command.command = commandTypes::PUSH; command.commandState = nullptr; commandList.pushBack(command); } void StateManager::popState() { exceptASSERT(commandList.getSize() >= 0); commands command; command.id = -1; command.command = commandTypes::POP; command.commandState = nullptr; commandList.pushBack(command); } State * StateManager::getTopState() { exceptASSERT(activeStates.getSize() <= 0); return activeStates.last(); } void StateManager::doCommands() { for (auto var : commandList) { commands & command = var; switch (command.command) { case commandTypes::REGISTER: doRegisterStates(command.id, command.commandState); break; case commandTypes::POP: doPopState(); break; case commandTypes::PUSH: doPushState(command.id); break; default: exceptTHROW("Tried to acces a command type that does exist"); } } commandList.deleteList(); } void StateManager::doRegisterStates(int ID, State * state) { Registeredstates.insert(ID, state); } void StateManager::doPopState() { activeStates.popBack(); } void StateManager::doPushState(int ID) { activeStates.pushBack(Registeredstates[ID]); }
true
865e87699704fb66f9ac10c236513835eaf47036
C++
Rakatashii/cpp_ch11
/P11_7/P11_7/util.hpp
UTF-8
549
2.84375
3
[]
no_license
#ifndef util_hpp #define util_hpp #include <stdio.h> #include <vector> #include <iostream> #include <string> #include <cstdlib> #include <time.h> namespace UTIL{ extern void swap(int& x, int& y); extern void print_vector(std::vector<int> v, std::string name = "v"); extern void print_two_vectors(std::vector<int> v, std::vector<int> u, std::string vname = "v", std::string uname = "u"); extern void rand_seed(); extern int rand_int(int a, int b); extern double rand_double(double min, double max); } #endif /* util_hpp */
true
533ee0b48a756ebfcb01712dddfa540ed1883159
C++
thefux/hwp_fuchse
/Aufgabe2/setmotorspeed_a_b.ino
UTF-8
1,001
2.734375
3
[]
no_license
#define A_Backwards 10 #define A_Forward 11 #define B_Forward 6 #define B_Backwards 9 bool forward = true; uint8_t spd = 50; bool motor = false; void setMotorSpeed(bool forward); void setup() { // put your setup code here, to run once: pinMode(A_Forward, OUTPUT); pinMode(A_Backwards, OUTPUT); pinMode(B_Forward, OUTPUT); pinMode(B_Backwards, OUTPUT); } void loop() { // put your main code here, to run repeatedly: setMotorSpeed(forward, spd, motor); delay(2000); } void setMotorSpeed(bool forward, uint8_t spd, bool motor){ if (motor){ if (forward == true) { analogWrite(A_Forward, spd); analogWrite(A_Backwards, 0); } else { analogWrite(A_Backwards, spd); analogWrite(A_Forward, 0); } }else{ if (forward == true) { analogWrite(B_Forward, spd); analogWrite(B_Backwards, 0); } else { analogWrite(B_Backwards, spd); analogWrite(B_Forward, 0); } } } void driveForward(){ }
true
45fe3c1d9ca2ff46ddd951ff0ec9768d8fc37822
C++
mkarppa/deann
/src/AnnEstimator.hpp
UTF-8
14,780
2.578125
3
[ "MIT" ]
permissive
#ifndef DEANN_ANN_ESTIMATOR #define DEANN_ANN_ESTIMATOR #include "RandomSampling.hpp" #include "FastRNG.hpp" #include "KdeEstimator.hpp" #include "Kernel.hpp" #include "Array.hpp" #include <unordered_set> #include <random> #include <iostream> /** * @file * This file implements the DEANN estimator. */ namespace deann { /** * This class represents an estimator that takes in as a template argument an * Approximate Nearest Neighbor (ANN) class, uses it to select the near * neighbors of query points, and complements the KDE estimate with random * sampling. * * @tparam T Type of data to process, either float or double. * @tparam AnnClass A class that implements functions query() and fit() * for approximate nearest neighbor detection, see LinearScan for the * interface. */ template<typename T, typename AnnClass> class AnnEstimatorBase : public KdeEstimatorT<T> { public: /** * Construct the estimator object. Note: random samples is not provided here * because it is processed in a subclass specific manner. * * @param bandwidth Desired bandwidth * @param kernel The kernel to use. * @param nearNeighbors The number \f$k\geq 0\f$ of near neighbors to * consider. * @param annEstimator Pointer to the estimator object. * @param seed Optional random number seed. */ AnnEstimatorBase(double bandwidth, Kernel kernel, int nearNeighbors, AnnClass* annEstimator, std::optional<KdeEstimator:: PseudoRandomNumberGenerator::ValueType> seed = std::nullopt) : KdeEstimatorT<T>(bandwidth, kernel, seed), annEstimator(annEstimator) { setNearNeighbors(nearNeighbors); } /** * Reset the near neighbors parameter without having to * reconstruct the object * @param newNeighbors New parameter value */ virtual void setNearNeighbors(int newNeighbors) { if (newNeighbors < 0) throw std::invalid_argument("Must have a non-negative number of near " "neighbors"); nearNeighbors = newNeighbors; nnsVector = std::vector<int>(nearNeighbors); nnsDistVector = std::vector<T>(nearNeighbors); scratch = std::vector<T>(this->d + nearNeighbors + randomSamples); } /** * Reset the random samples parameter without having to * reconstruct the object * @param newSamples New parameter value */ virtual void setRandomSamples(int newSamples) { if (newSamples < 0) throw std::invalid_argument("Must have a non-negative number of random " "samples"); randomSamples = newSamples; scratch = std::vector<T>(this->d + nearNeighbors + randomSamples); } /** * Reset parameters of the estimator without reconstructing the object. * @param param1 The number of near neighbors. * @param param2 The number of random samples. */ void resetParameters(std::optional<int> param1 = std::nullopt, std::optional<int> param2 = std::nullopt) override { if (param1 && param2) { setNearNeighbors(0); setRandomSamples(0); setNearNeighbors(*param1); setRandomSamples(*param2); } else if (param1) { setNearNeighbors(*param1); } else if (param2) { setRandomSamples(*param2); } } protected: void fitImpl() override { scratch = std::vector<T>(this->d + nearNeighbors + randomSamples); } int nearNeighbors = 0; int randomSamples = 0; mutable std::vector<T> scratch; private: void queryImpl(const T* q, T* Z, int* samples) const override { if (nearNeighbors > 0) { annEstimator->query(this->d, nearNeighbors, q, &nnsVector[0], &nnsDistVector[0], samples); } else if (samples) { *samples = 0; } int k = 0; while (k < nearNeighbors && nnsVector[k] >= 0) ++k; std::unordered_set<int> nns(nnsVector.begin(), nnsVector.begin() + k); T Z1 = 0; if (k > 0) { if (nnsDistVector[0] < 0) { // perform full distance recomputation if no distances are reported Z1 = kdeSubset(k, this->d, this->h, this->X, q, &nnsVector[0], &scratch[0], this->K); } else { // otherwise, use the precomputed distances Z1 = kdeDists(k, this->h, &nnsDistVector[0], &scratch[0], this->K); } } if (k < this->n && randomSamples > 0) { int S; T Z2 = randomSamplingImpl(q, nns, &S); *Z = Z1 * k / this->n + Z2 * (this->n - k) / this->n; if (samples && *samples >= 0) *samples += S; } else { *Z = Z1 * k / this->n; } } void queryImpl(int m, const T* Q, T* Z, int* samples) const override { for (int i = 0; i < m; ++i) queryImpl(Q + i*this->d, Z + i, samples ? samples + i : nullptr); } virtual T randomSamplingImpl(const T* q, const std::unordered_set<int>& nns, int* samples) const = 0; AnnClass* annEstimator = nullptr; mutable std::vector<int> nnsVector; mutable std::vector<T> nnsDistVector; }; /** * This is a variant of the Approximate Nearest Neighbor (ANN) estimator that * uses ``pure'' random sampling as a subroutine. * * @tparam T Type of data to be processed (float or dpuble) * @tparam AnnClass A class that implements functions query() and fit() * for approximate nearest neighbor detection, see LinearScan for the * interface. */ template<typename T, typename AnnClass> class AnnEstimator : public AnnEstimatorBase<T,AnnClass> { public: /** * Construct the estimator object. * * @param bandwidth Desired bandwidth * @param kernel The kernel to use. * @param nearNeighbors The number \f$k\geq 0\f$ of near neighbors to * consider. * @param randomSamples The number \f$m\geq 0\f$ of random samples to use * in the complementory distribution. Note that the estimator is unbiased * only if \f$m>0\f$. * @param annEstimator Pointer to the estimator object * @param seed Optional random number generator seed */ AnnEstimator(double bandwidth, Kernel kernel, int nearNeighbors, int randomSamples, AnnClass* annEstimator, std::optional<KdeEstimator::PseudoRandomNumberGenerator:: ValueType> seed = std::nullopt) : AnnEstimatorBase<T,AnnClass>(bandwidth, kernel, nearNeighbors, annEstimator, seed) { setRandomSamples(randomSamples); } /** * Reset the random samples parameter without having to * reconstruct the object * @param newSamples New parameter value */ void setRandomSamples(int newSamples) override { AnnEstimatorBase<T,AnnClass>::setRandomSamples(newSamples); sampleIdx = std::vector<uint32_t>(this->randomSamples); } private: T randomSamplingImpl(const T* q, const std::unordered_set<int>& nns, int* samples) const override { this->rng(this->randomSamples, &sampleIdx[0]); for (int i = 0; i < this->randomSamples; ++i) { uint32_t idx = sampleIdx[i]; while (nns.count(idx)) idx = sampleIdx[i] = this->rng(); } *samples = this->randomSamples; return kdeSubset(this->randomSamples, this->d, this->h, this->X, q, &sampleIdx[0], &this->scratch[0], this->K); } mutable std::vector<uint32_t> sampleIdx; }; /** * This is a variant of the Approximate Nearest Neighbor (ANN) * estimator that uses ``permuted'' random sampling as a * subroutine. That is, instead of drawing truly independent * samples, the dataset is permuted upon fitting, and a consecutive * set of rows is used when computing distances to sampled data * points. Consequentially, the total number of random samples may * vary because duplicates that occur within the near neighbor * results are removed. * * @tparam T Type of data to be processed (float or dpuble) * @tparam AnnClass A class that implements functions query() and fit() * for approximate nearest neighbor detection, see LinearScan for the * interface. */ template<typename T, typename AnnClass> class AnnEstimatorPermuted : public AnnEstimatorBase<T,AnnClass> { public: /** * Construct the estimator object. * * @param bandwidth Desired bandwidth * @param kernel The kernel to use. * @param nearNeighbors The number \f$k\geq 0\f$ of near neighbors to * consider. * @param randomSamples The number \f$m\geq 0\f$ of random samples to use * in the complementory distribution. Note that the estimator is unbiased * only if \f$m>0\f$. * @param annEstimator Pointer to the estimator object * @param seed Optional random number generator seed */ AnnEstimatorPermuted(double bandwidth, Kernel kernel, int nearNeighbors, int randomSamples, AnnClass* annEstimator, std::optional<KdeEstimator:: PseudoRandomNumberGenerator::ValueType> seed = std::nullopt) : AnnEstimatorBase<T,AnnClass>(bandwidth, kernel, nearNeighbors, annEstimator, seed) { if (kernel != Kernel::EXPONENTIAL && kernel != Kernel::GAUSSIAN) throw std::invalid_argument("Only exponential and gaussian kernels are " "supported by this class."); setRandomSamples(randomSamples); } /** * Reset the random samples parameter without having to * reconstruct the object * @param newSamples New parameter value */ void setRandomSamples(int newSamples) override { if (this->X && newSamples + this->nearNeighbors > this->n) throw std::invalid_argument("Tried to set too many near neighbors and " "random samples (" + std::to_string(this->nearNeighbors) + " + " + std::to_string(newSamples) + "): this " "exceeds the number of vectors in the " "fitted dataset (" + std::to_string(this->n) + ")"); AnnEstimatorBase<T,AnnClass>::setRandomSamples(newSamples); } /** * Reset the near neighbors parameter without having to reconstruct the object. * @param newNeighbors */ void setNearNeighbors(int newNeighbors) override { if (this->X && newNeighbors + this->randomSamples > this->n) throw std::invalid_argument("Tried to set too many near neighbors and " "random samples (" + std::to_string(newNeighbors) + " + " + std::to_string(this->randomSamples) + "): this exceeds the number of vectors in " "the fitted dataset (" + std::to_string(this->n) + ")"); AnnEstimatorBase<T,AnnClass>::setNearNeighbors(newNeighbors); } #ifdef DEANN_ENABLE_DEBUG_ACCESSORS inline const T* getXpermuted() const { return &Xpermuted[0]; } inline const uint32_t* getXpermutedIdx() const { return &XpermutedIdx[0]; } inline int getSampleIdx() const { return sampleIdx; } #endif // DEANN_ENABLE_DEBUG_ACCESSORS /** * Reset the random number seed. * @param seed New seed, or alternatively nullopt for unpredictable default * initialization. */ void resetSeed(std::optional<KdeEstimator:: PseudoRandomNumberGenerator::ValueType> seed = std::nullopt) override { KdeEstimatorT<T>::resetSeed(seed); if (this->X) { this->fit(this->n, this->d, this->X); } } private: T randomSamplingImpl(const T* q, const std::unordered_set<int>& nns, int* samples) const override { int correctionCount = 0; T correctionAmount = 0; int k = 0; int j = sampleIdx; while (k < this->randomSamples) { if (nns.count(XpermutedIdx[j])) { const T* x = &Xpermuted[0] + j*this->d; T dist = array::euclideanDistance(this->d, q, x, &this->scratch[0]); correctionAmount += this->K == Kernel::EXPONENTIAL ? std::exp(-dist/this->h) : std::exp(-dist*dist/this->h/this->h/2); ++correctionCount; } else { ++k; } j = (j+1) % this->n; } int m = this->randomSamples + correctionCount; T Z; int m1 = 0; int m2 = 0; if (m + sampleIdx > this->n) { m1 = this->n - sampleIdx; m2 = m - m1; T Z1 = kdeEuclideanMatmul(m1, this->d, this->h, &Xpermuted[0] + sampleIdx*this->d, q, &XSqNorm[0] + sampleIdx, &this->scratch[0], this->K); T Z2 = kdeEuclideanMatmul(m2, this->d, this->h, &Xpermuted[0], q, &XSqNorm[0], &this->scratch[0], this->K); Z = (Z1*m1 + Z2*m2)/m; } else { Z = kdeEuclideanMatmul(m, this->d, this->h, &Xpermuted[0] + sampleIdx*this->d, q, &XSqNorm[0] + sampleIdx, &this->scratch[0], this->K); } if (correctionCount > 0) Z = (Z*m - correctionAmount) / this->randomSamples; sampleIdx = (sampleIdx + m) % this->n; *samples = m; return Z; } void fitImpl() override { AnnEstimatorBase<T,AnnClass>::fitImpl(); if (this->randomSamples + this->nearNeighbors > this->n) throw std::invalid_argument("Too many random samples and near " "neighbors requested: the amount exceeds " "the total number of datapoints"); XSqNorm = std::vector<T>(this->n); XpermutedIdx = std::vector<uint32_t>(this->n); for (int i = 0; i < this->n; ++i) XpermutedIdx[i] = i; std::mt19937 mt19937rng(this->rngSeed); std::shuffle(XpermutedIdx.begin(), XpermutedIdx.end(), mt19937rng); Xpermuted = std::vector<T>(this->n * this->d); for (int i = 0; i < this->n; ++i) array::mov(this->d, this->X + XpermutedIdx[i]*this->d, &Xpermuted[0] + i*this->d); array::sqNorm(this->n, this->d, &Xpermuted[0], &XSqNorm[0]); } std::vector<T> XSqNorm; std::vector<T> Xpermuted; std::vector<uint32_t> XpermutedIdx; mutable int sampleIdx = 0; }; } #endif // DEANN_ANN_ESTIMATOR
true
3698d4a9753a69d8c5c5dddbb251e3d1a024dd58
C++
Marito-R-T/Arboleda
/QArboleda/programa.cpp
UTF-8
2,461
2.90625
3
[ "Apache-2.0" ]
permissive
#include "programa.h" Programa::Programa() { } void Programa::leerTexto(QString nombre) { nombre += "n"; } void Programa::setSeguir(bool seguir) { this->seguir = seguir; } void Programa::setPID(int pid) { this->pid = pid; } int Programa::getPID() { return this->pid; } void Programa::setEliminar(bool eliminar) { this->eliminar = eliminar; } int Programa::getCTallos() { return this->cantidad_tallos; } void Programa::setPosTallo(int pos_tallo) { this->pos_tallo = pos_tallo; } void Programa::producirHojas(int n_tallo, int n_ramas, int n_hojas) { if (n_tallo < this->cantidad_tallos) { this->cambiarTallo(n_ramas, n_hojas); } else { this->crearTallo(n_tallo, n_ramas, n_hojas); } } void Programa::producirRamas(int n_tallos, int n_ramas) { this->producirHojas(n_tallos, n_ramas, 0); } void Programa::producirTallos(int n_tallos) { this->producirHojas(n_tallos, 0, 0); } void Programa::crearTallo(int n_tallo, int n_ramas, int n_hojas) { /*if(n_tallo == tallos.size() + 1) { Tallo tallo = Tallo(); int pid_p; if (pipe(tallo.getP()) < 0) { exit(1); } pid_p = fork(); if(pid_p == -1){ printf("Error al crear proceso hijo\n"); } else if (pid_p == 0) { tallo.setPID(getpid()); tallo.setID(n_tallo); tallos.push_back(tallo); tallo.esperar(); return; } this->cantidad_tallos = tallos.size(); this->cambiarTallo(n_tallo, n_ramas, n_hojas); }*/ } void Programa::crearTallo(int n_tallo, int n_ramas) { this->crearTallo(n_tallo, n_ramas, 0); } void Programa::crearTallo(int n_tallo) { this->crearTallo(n_tallo, 0, 0); } void Programa::cambiarTallo(int tallo, int n_ramas, int n_hojas) { /*QString ram = QString(n_ramas); QString hoj = QString(n_hojas); write(this->tallos.at(tallo).getP1(), ram.toStdString().c_str(), 4); write(this->tallos.at(tallo).getP1(), hoj.toStdString().c_str(), 4);*/ } void Programa::cambiarTallo(int tallo, int n_ramas) { this->cambiarTallo(tallo, n_ramas, 0); } /* Esperar, donde este esta atento a la escritura del proceso principal, con el read esto lee si es el 1ero el tallo, el 2do es la rama, el 3ro es la hoja*/ void Programa::esperar(Ui::MainWindow &w) { sleep(2); w.txtEntrada->setText("hola"); } void Programa::proceso() { }
true
6f892fda02a7105010cda22716a3cb62aa38aead
C++
humeaua/CVATools
/CVATools/UtilitiesTests.cpp
UTF-8
3,700
2.8125
3
[]
no_license
// // UtilitiesTests.cpp // CVATools // // Created by Alexandre HUMEAU on 28/02/15. // // #include "RegressionTests.h" #include "DoublePrecision.h" #include <cmath> #include "ConfigLoader.h" #include "OWGRWrapperLoader.h" #include "CSVReader.h" #include "StringUtilities.h" #include "ConfigReader.h" #include "Player.h" bool RegressionTest::DoublePrecision() const { const double pi = 3.14159265359; const double tolerance = 1e-15; const double refValue = 3.14; const int refValueint = 3; const double pi_2 = Precision<2, double>(pi); const int pi_0 = Precision<0, int>(pi); const double error = fabs(refValue-pi_2) + std::abs(refValueint-pi_0); if (error < tolerance) { m_logger.PutLine("SUCCEEDED"); return true; } else { m_logger.PutLine("FAILED"); return false; } } bool RegressionTest::ConfigLoaderTest() const { const std::string filename = "//Users//alexhum49//Documents//Workspace//CVA//CVATools//Input//OWGR//Tests//TestConfigLoader.csv"; ConfigLoader<OWGRWrapperLoader<double> > loader(filename); const OWGRVectorWrapper<double> & obj = loader.get().get(); const double refValues[] = {1, 2, 34, 4.2, 5, 6.28}; double error = 0.0; const double tolerance = 1e-10; for (size_t i = 0 ; i < obj.size() ; ++i) { error += std::abs(obj[i] - refValues[i]); } if (error > tolerance) { m_logger.PutLine("FAILED"); return false; } else { m_logger.PutLine("SUCCEEDED"); return true; } } bool RegressionTest::CSVReaderTest() const { const std::string filename = "//Users//alexhum49//Documents//Workspace//CVA//CVATools//Input//OWGR//Tests//TestCSV1.txt"; std::ifstream file(filename.c_str()); CSVReader csvReader(filename); std::vector<double> values; csvReader >> values; double refValues[] = {1,0}; const double tolerance = 1e-10; double error = 0.0; const size_t size = values.size(); if (size != 2) { throw EXCEPTION("values should be of size 2"); } for (size_t i = 0 ; i < size ; ++i) { error += std::abs( values[i] -refValues[i]); } if (error < tolerance) { m_logger.PutLine("SUCCEEDED"); return true; } else { m_logger.PutLine("FAILED"); return false; } } bool RegressionTest::ConfigReaderTest() const { // to be written const std::string filename ="//Users//alexhum49//Documents//Workspace//CVA//CVATools//Input//OWGR//Tests//TestConfigReader.txt"; ConfigReader configReader(filename); PlayerID playerId("", Utilities::Date::MyDate()); const std::string refValue = "Alexandre"; configReader.Fill(playerId, "PlayerID"); if (playerId.Name() == refValue && playerId.BirthDate() == Utilities::Date::MyDate(25,4,1989)) { m_logger.PutLine("SUCCEEDED"); return true; } else { m_logger.PutLine("FAILED"); return false; } } bool RegressionTest::ConfigReaderPlayerTest() const { const std::string filename ="//Users//alexhum49//Documents//Workspace//CVA//CVATools//Input//OWGR//Tests//TestConfigReaderPlayer.txt"; ConfigReader configReader(filename); Player player("",TourType(1), Utilities::Date::MyDate()); const std::string refValue = "Alexandre"; configReader.Fill(player, "Player"); if (player.Name() == refValue && player.BirthDate() == Utilities::Date::MyDate(25,4,1989)) { m_logger.PutLine("SUCCEEDED"); return true; } else { m_logger.PutLine("FAILED"); return false; } }
true
bcbb5fd4e237d4e58354dd024de9e4ddc4a41389
C++
shinbyh/ns3-p2p-wmn
/route_flowcheck.h
UTF-8
1,583
2.578125
3
[]
no_license
/* * route_flowcheck.h * * Created on: Jan 16, 2018 * Author: bhshin */ #ifndef SCRATCH_P2P_BHSHIN_ROUTE_FLOWCHECK_H_ #define SCRATCH_P2P_BHSHIN_ROUTE_FLOWCHECK_H_ #include <vector> #include <string> #include "source_route_stat.h" #include "flow.h" using namespace std; class FlowCheck { private: int msgType; Flow flow; uint32_t nodeId; // nodeID of the initiator uint32_t prevNextHop; // previous (current) next hop int seqNo; int TTL; // for request only uint32_t replierNodeId; // for reply only double avgAvailableBw; // average available bandwidth of the neighbors of a replier node vector<SourceRouteStat> stats; const string serializeStats() const; void parseStats(string str); public: FlowCheck(int msgType, int TTL); virtual ~FlowCheck(); int getMsgType() const; void setMsgType(int msgType); int getSeqNo() const; void setSeqNo(int seqNo); const vector<SourceRouteStat>& getStats() const; void setStats(const vector<SourceRouteStat>& stats); void addStat(const SourceRouteStat stat); const string serialize() const; void parse(string str); int getTtl() const; void setTtl(int ttl); void decrementTTL(); uint32_t getNodeId() const; void setNodeId(uint32_t nodeId); uint32_t getReplierNodeId() const; void setReplierNodeId(uint32_t replierNodeId); uint32_t getPrevNextHop() const; void setPrevNextHop(uint32_t prevNextHop); double getAvgAvailableBw() const; void setAvgAvailableBw(double avgAvailableBw); const Flow& getFlow() const; void setFlow(const Flow& flow); }; #endif /* SCRATCH_P2P_BHSHIN_ROUTE_FLOWCHECK_H_ */
true
8a3db9e1330d1ad8ec41a913bf670b78bea9cc38
C++
pingxiyan/MovementObjectExtract
/extract_obj_lib/src/extract_obj_auto_param.cpp
UTF-8
1,432
2.8125
3
[]
no_license
/** * Part 1: Auto get parameter. * Sandy Yann, Nov 14, 2017 */ #include <string> #include <iostream> #include "extract_obj.h" #include "extract_obj_auto_param.h" /** * @brief Create Handle of auto get parameter. * @param width : image width. * @param height : image height. * @param maxframenum : max frame number is used for initial parameter. * default 300, recommend 300~600. * @return handle, use 'ccAutoParamClose' to release. */ OBJEXT_LIB void* ccAutoParamOpen(int width, int height, int maxframenum) { CAutoParam* pAutoParam = new CAutoParam(); if (NULL == pAutoParam) { return NULL; } return NULL; } /** * @brief Auto get parameter, process one frame. * @param pvAPHandle : 'ccAutoParamOpen' create it. * @param Input : Input one frame image. * @return state, 0=error; 1=continue; 2=over(finish); */ OBJEXT_LIB int ccAutoParamProcess(void* pvAPHandle, const Input* ptOneFrame) { return 1; } /** * @brief Release handle * @param ppvAPHandle : created by 'ccAutoParamOpen' */ OBJEXT_LIB void ccAutoParamClose(void** ppvAPHandle) { return; } /** * @brief When 'ccAutoParamProcess' return 2, means that auto get parameter finish, * and then, we can get out parameter through 'ccGetAutoParam' */ OBJEXT_LIB void* ccGetAutoParam(void* pvAPHandle) { return NULL; } /** * @brief Release handle(returned by ccGetAutoParam), must be after 'ccObjExtractOpen" */ OBJEXT_LIB void ccReleaseAutoParam(void** ppvAParam) { }
true
2d1c1710607240749f5ef51e2a065352e68c3c09
C++
SunatP/ITCS381_Multimedia
/Lab Teacher Worapan/6Lab_Left.cpp
UTF-8
9,664
2.546875
3
[]
no_license
#include<stdio.h> // Standard io #include<opencv2/core/core.hpp> #include<opencv2/highgui/highgui.hpp> #include "opencv2/imgproc/imgproc.hpp" #include <iostream> // for output #include <cmath> // Calculate mathmatic #include<fstream> // Write file output #include <windows.h> // Add this header for waiting output before close automatically #include <iomanip> // add for decimal place #include <limits> /* using namespace std; using namespace cv; int main() { Mat image = imread("dog.jpg", 1); namedWindow("Original Image", 1); imshow("Original Image", image); // Split the image into different channels vector<Mat> rgbChannels(3); split(image, rgbChannels); // Show individual channels Mat g, fin_img; g = Mat::zeros(Size(image.cols, image.rows), CV_8UC1); // Showing Red Channel // G and B channels are kept as zero matrix for visual perception { vector<Mat> channels; channels.push_back(g); channels.push_back(g); channels.push_back(rgbChannels[2]); // Merge the three channels merge(channels, fin_img); namedWindow("Red", 1); imshow("Red", fin_img); } // Showing Green Channel { vector<Mat> channels; channels.push_back(g); channels.push_back(rgbChannels[1]); channels.push_back(g); merge(channels, fin_img); namedWindow("Green", 1); imshow("Green", fin_img); } // Showing Blue Channel { vector<Mat> channels; channels.push_back(rgbChannels[0]); channels.push_back(g); channels.push_back(g); merge(channels, fin_img); namedWindow("Blue", 1); imshow("Blue", fin_img); } cv::waitKey(0); }*/ using namespace std; using namespace cv; void mouse_callback(int event, int x, int y, int flag, void *param); int mouse(); int magnitude(); int lab13(); int histogram(); int Lab14(); int act4(); void sobel(); /** * @function main */ int main() { cv:setBreakOnError(true); //mouse(); //sobel(); //lab13(); //magnitude(); //Lab14(); //act4(); } void sobel() { Mat img; img = imread("dog.jpg", 1); namedWindow("Input"); imshow("Input", img); Mat sobel_x, sobel_y; Mat abs_sobel_x, abs_sobel_y; Mat img_gray; cv::cvtColor(img, img_gray, cv::COLOR_BGR2GRAY); //Gradient X Sobel(img_gray, sobel_x, CV_16S, 1, 0, 3); convertScaleAbs(sobel_x, abs_sobel_x); imshow("Sobel X", abs_sobel_x); //Gradient Y Sobel(img_gray, sobel_y, CV_16S, 0, 1, 3); convertScaleAbs(sobel_y, abs_sobel_y); imshow("Sobel Y", abs_sobel_y); cv::waitKey(0); } int magnitude() { Mat img = imread("dog.jpg", IMREAD_COLOR); namedWindow("Input"); Mat sobelX, sobelY, abssobelX, abssobelY, imgrey; cv::Mat1f mag; cv::cvtColor(img, imgrey, COLOR_BGR2GRAY); cv::Sobel(imgrey, sobelX, CV_32F, 1, 0, 3); cv::convertScaleAbs(sobelX, abssobelX); namedWindow("SobelX"); cv::imshow("SobelX", abssobelX); cv::Sobel(imgrey, sobelY, CV_32F, 0, 1, 3); cv::convertScaleAbs(sobelY, abssobelY); namedWindow("SobelY"); cv::imshow("SobelY", abssobelY); magnitude(sobelX, sobelY, mag); imshow("Result", mag); cv::waitKey(0); return 0; } int lab13() { Mat src, dst; /// Load image src = imread("dog.jpg", IMREAD_COLOR); if (!src.data) { return -1; } /// Separate the image in 3 places ( B, G and R ) vector<Mat> bgr_planes; split(src, bgr_planes); /// Establish the number of bins int histSize = 256; /// Set the ranges ( for B,G,R) ) float range[] = { 0, 256 }; const float* histRange = { range }; bool uniform = true; bool accumulate = false; Mat b_hist, g_hist, r_hist; /// Compute the histograms: calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate); // Draw the histograms for B, G and R int hist_w = 512; int hist_h = 400; int bin_w = cvRound((double)hist_w / histSize); Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0)); /// Normalize the result to [ 0, histImage.rows ] normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); /// Draw for each channel for (int i = 1; i < histSize; i++) { line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(b_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 2, 8, 0); line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(g_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 2, 8, 0); line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(r_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0); } /// Display namedWindow("calcHist Demo", cv::WINDOW_AUTOSIZE); imshow("calcHist Demo", histImage); waitKey(0); return 0; } int mouse() { Mat img; img = imread("dog.jpg", 1); namedWindow("Example"); setMouseCallback("Example", mouse_callback); imshow("Example", img); waitKey(0); return 0; } void mouse_callback(int event, int x, int y, int flag, void *param) { if (event == EVENT_MOUSEMOVE) { cout << "( X: " << x << ", Y: " << y << ")" << endl; } if (event == EVENT_LBUTTONDOWN) { Mat img; img = imread("dog.jpg", 1); Vec3b color = img.at<Vec3b>(cv::Point(x, y)); cout << "Left button of the mouse is clicked - position ( X:" << x << ", Y: " << y << ")" << endl; printf("Blue: %d, Green: %d, Red: %d \n", color[0], color[1], color[2]); } } int histogram() { Mat src, dst; /// Load image src = imread("dog.jpg", IMREAD_COLOR); if (!src.data) { return -1; } /// Separate the image in 3 places ( B, G and R ) vector<Mat> bgr_planes; split(src, bgr_planes); /// Establish the number of bins int histSize = 256; /// Set the ranges ( for B,G,R) ) float range[] = { 0, 256 }; const float* histRange = { range }; bool uniform = true; bool accumulate = false; Mat b_hist, g_hist, r_hist; /// Compute the histograms: calcHist(&bgr_planes[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange, uniform, accumulate); calcHist(&bgr_planes[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange, uniform, accumulate); // Draw the histograms for B, G and R int hist_w = 512; int hist_h = 400; int bin_w = cvRound((double)hist_w / histSize); Mat histImage(hist_h, hist_w, CV_8UC3, Scalar(0, 0, 0)); /// Normalize the result to [ 0, histImage.rows ] normalize(b_hist, b_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(g_hist, g_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); normalize(r_hist, r_hist, 0, histImage.rows, NORM_MINMAX, -1, Mat()); /// Draw for each channel for (int i = 1; i < histSize; i++) { line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(b_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(b_hist.at<float>(i))), Scalar(255, 0, 0), 2, 8, 0); line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(g_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(g_hist.at<float>(i))), Scalar(0, 255, 0), 2, 8, 0); line(histImage, Point(bin_w*(i - 1), hist_h - cvRound(r_hist.at<float>(i - 1))), Point(bin_w*(i), hist_h - cvRound(r_hist.at<float>(i))), Scalar(0, 0, 255), 2, 8, 0); } /// Display namedWindow("calcHist Demo", cv::WINDOW_AUTOSIZE); imshow("calcHist Demo", histImage); waitKey(0); return 0; } int Lab14() { Mat img1, hsv1; Mat img2, hsv2; img1 = imread("dog.jpg", IMREAD_COLOR); img2 = imread("dog11.jpg", IMREAD_COLOR); cvtColor(img1, hsv1, cv::COLOR_BGR2HSV); cvtColor(img2, hsv2, COLOR_BGR2HSV); int h_bins = 50; int s_bins = 60; int histSize[] = { h_bins, s_bins }; float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges,s_ranges }; int channels[] = { 0,1 }; MatND hist1; MatND hist2; calcHist(&hsv1, 1, channels, Mat(), hist1, 2, histSize, ranges, true, false); normalize(hist1, hist1, 0, 1, NORM_MINMAX, -1, Mat()); calcHist(&hsv2, 1, channels, Mat(), hist2, 2, histSize, ranges, true, false); normalize(hist2, hist2, 0, 1, NORM_MINMAX, -1, Mat()); double sim = compareHist(hist1, hist2, cv::HISTCMP_CORREL); printf("The correlation similarlity is %f\n", sim); printf("\n"); cin.ignore(); return 0; } int act4() { Mat img1, hsv1; Mat img2, hsv2; Mat img3, hsv3; img1 = imread("dog.jpg", IMREAD_COLOR); img2 = imread("dog_gray.jpg", IMREAD_COLOR); img3 = imread("dog11.jpg", IMREAD_COLOR); cvtColor(img1, hsv1, COLOR_BGR2HSV); cvtColor(img2, hsv2, COLOR_BGR2HSV); cvtColor(img3, hsv3, COLOR_BGR2HSV); int h_bins = 50; int s_bins = 60; int histSize[] = { h_bins, s_bins }; float h_ranges[] = { 0, 180 }; float s_ranges[] = { 0, 256 }; const float* ranges[] = { h_ranges,s_ranges }; int channels[] = { 0,1 }; MatND hist1; MatND hist2; MatND hist3; calcHist(&hsv1, 1, channels, Mat(), hist1, 2, histSize, ranges, true, false); normalize(hist1, hist1, 0, 1, NORM_MINMAX, -1, Mat()); calcHist(&hsv2, 1, channels, Mat(), hist2, 2, histSize, ranges, true, false); normalize(hist2, hist2, 0, 1, NORM_MINMAX, -1, Mat()); calcHist(&hsv3, 1, channels, Mat(), hist3, 2, histSize, ranges, true, false); normalize(hist3, hist3, 0, 1, NORM_MINMAX, -1, Mat()); double sim1 = compareHist(hist1, hist2, HISTCMP_CORREL); double sim2 = compareHist(hist1, hist3, HISTCMP_CORREL); printf("The correlation similarlity 1 is %f\n", sim1); printf("The correlation similarlity 2 is %f\n", sim2); printf("\n"); cin.ignore(); return 0; }
true
4a7360b6c83c3fdbd586f7286ad142f4bde12318
C++
cjoshmartin/Intro-to-Programming-Vb-C-
/Work/Selection Statement Exercises/Gravity.cpp
UTF-8
1,780
3.921875
4
[]
no_license
// Josh Martin // Exercise 1 - Selection Statement Exercises // Period 2 // 2/25/2014 // Purpose - to calcute the weight of a person on other plants #include "stdafx.h" #include <iostream> using namespace std; int main() { //Naming variable double weight; char firstletter; char secondletter; // Getting weight cout << "What is Your Weight ? "; cin >> weight; // Error trapping Weight if (weight <= 0) { while (weight <= 0) { cout << "Sorry You have entered an invaild weight, Please enter another.. "; cin >> weight; } } // Getting First Letter cout << endl << "Okay, What is the first letter of the plant? "; cin >> firstletter; // Testing for second if (firstletter == 's' || firstletter == 'S' || firstletter == 'M' || firstletter == 'm') { cout << "What is the second letter in the plants name ? "; cin >> secondletter; } // Doing Math for two letter Plants if (firstletter == 's' || firstletter == 'S') { if (secondletter == 'u' || secondletter == 'U') weight *= 27.94; else if (secondletter == 'a' || secondletter == 'A') weight *= 1.15; } if (firstletter == 'M' || firstletter == 'm') { if (secondletter == 'o' || secondletter == 'O') weight *= .17; else if (secondletter == 'e' || secondletter == 'E') weight *= .37; else if (secondletter == 'a' || secondletter == 'A') weight *= .38; } // Do math of First letter plants if (firstletter == 'U' || firstletter == 'u') weight *= 1.17; else if (firstletter == 'V' || firstletter == 'v') weight *= .88; else if (firstletter == 'J' || firstletter == 'j') weight *= 2.64; else if (firstletter == 'N' || firstletter == 'n') weight *= 1.18; // Showwing new Weight cout << " Your NEW Weight Is " << weight << "Ibs" << endl; }// end of main
true
f9e12b95ade328f383c291cb599b306cab020d5a
C++
gorobot/symmath
/test/numerics/test_variable.cc
UTF-8
994
3.109375
3
[]
no_license
#include <catch2/catch.hpp> #include <symmath/numerics/real.hpp> #include <symmath/numerics/variable.hpp> using namespace sym; TEST_CASE("Variables: operations", "[numerics]") { Real a(1.0); Variable<Real> x(2.0); Variable<Real> y(1.0); // REQUIRE(a == y); // z = x + y; SECTION("should be able to assign") { Variable<Real> z(a); REQUIRE(z == a); REQUIRE(z == 1.0); } SECTION("should be able to assign") { Variable<Real> z(a); REQUIRE(z == a); REQUIRE(a == 1.0); REQUIRE(z == 1.0); a = 5.0; REQUIRE(a == 5.0); REQUIRE(z == 5.0); } SECTION("should be able to assign") { Variable<Real> z; z = a; REQUIRE(z == a); } SECTION("should be able to assign") { Variable<Real> z; z = x; REQUIRE(z == x); // REQUIRE(z == 2.0); } // SECTION("should be able to assign") { // Variable<Real> z; // z = x + a; // // REQUIRE(z == 3.0); // // a = 3.0; // // REQUIRE(z == 5.0); // } }
true
33189ff58027ea28df43a350b75faf35daa2a8fa
C++
yitati/LCProject
/Leetcode/JumpGameII.cpp
UTF-8
2,111
3.71875
4
[]
no_license
/****************************************************************************** * Question: #45 Jump Game II * Given an array of non-negative integers, you are initially positioned at the first index of the array. * Each element in the array represents your maximum jump length at that position. * Your goal is to reach the last index in the minimum number of jumps. For example: Given array A = [2,3,1,1,4] The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.) Note: You can assume that you can always reach the last index. *****************************************************************************/ #include <iostream> #include <vector> #include <unordered_set> #include <algorithm> #include <ctime> #include <climits> using namespace std; // the idea is to use dfs and update the minJump from every possible path // using dp - exceed the time limit since we need to loop for every step - this is not necessary int jump_dp(vector<int>& nums) { int n = nums.size(); vector<int> dp(n, INT_MAX); dp[0] = 0; for(int i=0; i<n-1; i++) { if(nums[i] == 0) continue; if(dp[i] != INT_MAX) { for(int j=0; j <= nums[i] && i + j <= n-1; j++) { dp[i+j] = min(dp[i+j], dp[i] + 1); } } } return dp[n-1]; } // using bfs // always calculate the maxReach of every step - if it covers the destination then return current step int jump_bfs(vector<int> & nums) { int n = nums.size(); if (n < 2) return 0; int step = 0, i = 0, currReach = 0, nextReach = 0; while (currReach - i + 1 > 0) // there are nodes we still need to check { step++; for (; i <= currReach; i++) { nextReach = max(nextReach, i + nums[i]); if (nextReach >= n - 1) return step; } currReach = nextReach; } return 0; } /* int main(int argc, char * * argv) { //int input[] = { 2,3,1,1,4 }; // true int input[] = { 0 }; // true vector<int> nums(input, input + sizeof(input) / sizeof(int)); cout << jump(nums) << endl; system("pause"); } */
true
ba04b88847b4bfa6d8768793b6166576a1d5f9ff
C++
syoch/NotepadSh
/NotepadSh/MyFrame.cpp
UTF-8
3,333
2.546875
3
[]
no_license
#include "pch.h" #include "widgetids.h" #include "MyFrame.h" // clang-format off wxBEGIN_EVENT_TABLE(MyFrame, wxFrame) EVT_MENU(ID_OpenFile, MyFrame::OnOpenFile) EVT_MENU(ID_SaveFile, MyFrame::OnSaveFile) EVT_TEXT(ID_TextEditor, MyFrame::EnterTextEditor) EVT_MENU(wxID_EXIT, MyFrame::OnExit) EVT_MENU(wxID_ABOUT, MyFrame::OnAbout) wxEND_EVENT_TABLE() ; // clang-format on MyFrame::MyFrame() : wxFrame(NULL, wxID_ANY, wxT("NotepadSH"), wxDefaultPosition, wxSize(400, 400)) { setupBar(); // StatusBar statusBar = new wxStatusBar(this); SetStatusBar(statusBar); // panel panel = new wxPanel(this, wxID_ANY); // - sizer sizer = new wxBoxSizer(wxVERTICAL); // - - add childs // - - - text editor texteditor = new wxTextCtrl(panel, ID_TextEditor, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER | wxTE_PROCESS_TAB | wxTE_MULTILINE); texteditor->SetFont(wxFont(12, wxFONTFAMILY_MODERN, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL, 0, wxT(""))); sizer->Add(texteditor, 1, wxALL | wxEXPAND, 1); // - Set sizer panel->SetSizer(sizer); Layout(); } void MyFrame::setupBar() { // File auto file = new wxMenu; file->Append(ID_OpenFile, "&Open File\tCtrl-O", "Open a file."); file->Append(ID_SaveFile, "&Save File\tCtrl-O", "Save a file."); file->AppendSeparator(); file->Append(wxID_EXIT); // Help auto help = new wxMenu; help->Append(wxID_ABOUT); // Bar auto bar = new wxMenuBar; bar->Append(file, "&File"); bar->Append(help, "&Help"); SetMenuBar(bar); } void MyFrame::OnExit(wxCommandEvent &) { if (texteditor->IsModified()) { int ret = wxMessageBox("File not saved.\nSave to Close?", "Warning", wxYES_NO); if (ret == wxID_YES) { save(); } } Close(true); } void MyFrame::OnAbout(wxCommandEvent &) { wxMessageBox("This is a Notepad like a microsoft notepad.", "About Notepad#", wxOK | wxICON_INFORMATION); } void MyFrame::OnOpenFile(wxCommandEvent &) { // Check modified if (texteditor->IsModified()) { int ret = wxMessageBox("File not saved.\nSave to Open?", "Warning", wxYES_NO); if (ret == wxID_YES) { save(); } } // Ask path = wxLoadFileSelector("Filename", "*"); //Open wxFile file; file.Open(path, wxFile::OpenMode::read); if (file.Error()) { statusBar->SetStatusText("Failed"); wxMessageBox("Failed to open file[" + path + "]", "Error"); return; } // Clear editor texteditor->Clear(); texteditor->SetModified(false); // Read wxString buffer; file.ReadAll(&buffer); texteditor->SetValue(buffer); file.Close(); // Update Title SetTitle( "Notepad#" + wxSplit(path, wxT('/')).Last() // basename ); } void MyFrame::OnSaveFile(wxCommandEvent &) { save(); // Update Status texteditor->SetModified(false); statusBar->SetStatusText("Saved"); } void MyFrame::EnterTextEditor(wxCommandEvent &) { //command_processer.update(); } void MyFrame::save() { wxFile file; file.Open(path, wxFile::OpenMode::write); file.Write(texteditor->GetValue()); file.Close(); }
true
ec83c13d7d6b292438588bd7786165d9b10979d8
C++
JuanPabloRN30/Competitive_Programming
/UvaOnlineJudge/686.cpp
UTF-8
901
2.546875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector < int > primes; void sieve(ll N) { bitset<10000010> bs; bs.set(); for( ll i = 2 ; i <= N ; i++ ) { if( bs[ i ] ) { primes.push_back( i ); for( ll j = i*i ; j <= N ; j+= i ) bs[j] = false; } } } int main() { int n; sieve( 1e6 ); while( scanf("%d",&n) && n ) { int sup,inf,suma; inf = 0; sup = lower_bound( primes.begin(), primes.end(), n ) - primes.begin(); suma = primes[ inf ] + primes[ sup ]; int cont = 0; while( sup >= inf) { // cout << suma << " " << primes[ inf ] << " " << primes[ sup ] << endl; if( suma == n ) { sup--; cont++; } else if( suma > n ) sup--; else inf++; suma = primes[ inf ] + primes[ sup ]; } printf("%d\n",cont); } return 0; }
true
1f5118e3113550dfa93c9d1e1b448d99f91af36c
C++
jayin92/code-of-TIOJ
/C.cpp
UTF-8
505
2.765625
3
[]
no_license
#include <iostream> using namespace std; int main(){ int n; int h = 0; cin >> n; int arr[n][2]; int temp[2]; for(int i = 0;i<n;i++){ cin >> arr[i][0] >> arr[i][1]; } for(int i = 0;i<n;i++){ h = 0; for(int j=0;j<2;j++){ temp[j] = arr[i][j]; } if(temp[1] % 2 == 1){ temp[1]++; h++; } if((2*temp[0]+temp[1])%4==0){ cout<< h+0.5*temp[0]+0.75*temp[1] << endl; }else{ cout<<h+0.5*temp[0]+0.75*(temp[1])+3.5 << endl; } } return 0; }
true
83e06ca5857c45d3d34bf3909a2a5260314e544f
C++
scaussin/abstract_vm
/src/Factory.cpp
UTF-8
3,122
3.21875
3
[]
no_license
#include "main.hpp" Factory::Factory() { _tabFactoryOperand[eInt8] = &Factory::createInt8; _tabFactoryOperand[eInt16] = &Factory::createInt16; _tabFactoryOperand[eInt32] = &Factory::createInt32; _tabFactoryOperand[eFloat] = &Factory::createFloat; _tabFactoryOperand[eDouble] = &Factory::createDouble; } Factory::Factory(Factory const &rhs) { *this = rhs; } Factory::~Factory() { } Factory &Factory::operator=(Factory const &rhs) { (void)rhs; return (*this); } IOperand const * Factory::createOperand(eOperandType type, std::string const & value) const { return ((this->*_tabFactoryOperand[(int)type])(value)); } IOperand const * Factory::createInt8(std::string const & value) const { int result; try { std::size_t lastChar; result = std::stoi(value, &lastChar, 10); } catch (std::out_of_range & e) { throw(AbstractException("\033[31mError run time:\033[m int8 out of range")); } if (result > 127) throw(AbstractException("\033[31mError run time:\033[m int8 overflow")); if (result < -127) throw(AbstractException("\033[31mError run time:\033[m int8 underflow")); return (new TOperand<int8_t>(eInt8, result)); } IOperand const * Factory::createInt16(std::string const & value) const { int result; try { std::size_t lastChar; result = std::stoi(value, &lastChar, 10); } catch (std::out_of_range & e) { throw(AbstractException("\033[31mError run time:\033[m int16 out of range")); } if (result > 32767) throw(AbstractException("\033[31mError run time:\033[m int16 overflow")); if (result < -32768) throw(AbstractException("\033[31mError run time:\033[m int16 underflow")); return (new TOperand<int16_t>(eInt16, result)); } IOperand const * Factory::createInt32(std::string const & value) const { int result; try { std::size_t lastChar; result = std::stoi(value, &lastChar, 10); } catch (std::out_of_range & e) { throw(AbstractException("\033[31mError run time:\033[m int32 out of range")); } return (new TOperand<int32_t>(eInt32, result)); } IOperand const * Factory::createFloat(std::string const & value) const { float result; try { std::size_t lastChar; result = std::stof(value, &lastChar); } catch (std::out_of_range & e) { throw(AbstractException("\033[31mError run time:\033[m float out of range")); } if (!isfinite(result) && result > 0) throw(AbstractException("\033[31mError run time:\033[m float overflow")); if (!isfinite(result) && result < 0) throw(AbstractException("\033[31mError run time:\033[m float underflow")); return (new TOperand<float>(eFloat, result)); } IOperand const * Factory::createDouble(std::string const & value) const { double result; try { //std::size_t lastChar; result = stod(value); } catch (std::out_of_range & e) { throw(AbstractException("\033[31mError run time:\033[m double out of range")); } if (!isfinite(result) && result > 0) throw(AbstractException("\033[31mError run time:\033[m double overflow")); if (!isfinite(result) && result < 0) throw(AbstractException("\033[31mError run time:\033[m double underflow")); return (new TOperand<double>(eDouble, result)); }
true
01bd11c306efa017bb4528673225cac3dae5bf95
C++
blockspacer/swordbow-magic
/include/commandcomponent.hpp
UTF-8
1,274
3.171875
3
[ "MIT" ]
permissive
#ifndef COMMANDCOMPONENT_HPP #define COMMANDCOMPONENT_HPP #include <unordered_map> #include <forward_list> //Forward declaration could work instead of inclusion but that leads to //undefined behaviour when deleting a pointer to ICommand #include "icommand.hpp" //This component allows each entity to do it's own thing //on a certain event (command). //If an entity should WALK_UP, it iterates over //the linked list (forward_list) on that key, executing the //ICommands (such as addIdToSystem) struct CommandComponent { enum Event { MOVE_UP, MOVE_RIGHT, MOVE_DOWN, MOVE_LEFT, FLY_UP, FLY_DOWN, ATTACK, ON_DEATH, ON_MOVE }; CommandComponent() { } std::unordered_map<unsigned int, std::forward_list<ICommand*> > commands; virtual ~CommandComponent() { for(auto list : commands) { for(auto command : list.second) { delete command; } } } inline std::forward_list<ICommand*>& operator [](unsigned int index) { return commands[index]; } void execute(const Event& event) { for(auto command : commands[event]) { command->execute(); } } }; #endif //COMMANDCOMPONENT_HPP
true
7eb3fa78852e98118dca861f9f51fd9ae62cb5a4
C++
lopez-jose/Euler
/Problem18/MaximumPathSum.cpp
UTF-8
937
3.265625
3
[]
no_license
// Problem18-MaximumPathSumI.cpp : Defines the entry point for the console application. // #include <iostream> #include<fstream> #include <string> using namespace std; int height = 0; const int width = 15; int store[width][width] = { 0 }; void printOut() { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { cout << store[i][j]; } cout << endl; } } void storeNumber(string input) { string temp = ""; for (int i = 0; i < input.length(); i++) { char s = input[i]; // so we get the char } } int main() { string line; ifstream myfile("numbers.txt"); if (myfile.is_open()) { while (getline(myfile, line)) { cout << line << '\n'; height++; //here you find the height; } myfile.close(); } else cout << "Unable to open file"; //First find the height of the pyramid. cout << "The height of the pyramid = " << height << endl; int pause; cin >> pause; return 0; }
true
c460fe3b61a4a29dedfc707cad3518820b290ddf
C++
colin9597/Cpp_Programming
/02주차/sum.cpp
UTF-8
224
3.09375
3
[]
no_license
#include <iostream> int main() { int score[5] = {10, 30, 40, 60, 90}; int sum = 0; for(int i=0; i<5; i++) { sum += score[i]; } std::cout << sum << std::endl; return 0; }
true
d178d0de0738233c5355f8496ad41e3312306833
C++
lebiednik/PhoenixSim
/ioComponents/DRAMsim/RowBuffer.h
UTF-8
257
2.515625
3
[]
no_license
class RowBuffer { public: RowBuffer(); int status; /* Three choices. IDLE, OPEN, PENDING */ int completion_time; /* this is used with counters to decide how long to keep a row buffer open */ int rank_id; int row_id; int bank_id; };
true
be8f532d853cc414715762ede3b9aa0f6bbf8432
C++
Ahren09/CS32
/Projects/Project2/Set.cpp
UTF-8
4,813
3.671875
4
[]
no_license
// Set.cpp #include "Set.h" Set::Set() : head(nullptr),tail(nullptr),m_size(0) {} Set::~Set() { //Empty list, return directly Node *p=head; while(head) { head=head->next; delete p; p=head; } } Set::Set(const Set& other) { if(other.empty()) { head=tail=nullptr; } else { //Initialize head pointer head=new Node; head->val=other.head->val; Node* n=head; Node* src=other.head; n->pre=nullptr; while(src->next) { src=src->next; Node* newNode=new Node; newNode->val=src->val; newNode->pre=n; n->next=newNode; n=n->next; } n->next=nullptr; //Reach the end of list tail=n; } m_size=other.m_size; } Set& Set::operator=(const Set& other) { if(this!=&other) { Node* p=head; while(p) { head=head->next; delete p; p=head; } head=tail=nullptr; //### m_size=0; if(!other.head) return *this; head=new Node; head->val=other.head->val; p=head; p->pre=nullptr; Node* src=other.head; while(src->next) { src=src->next; Node* newNode=new Node; newNode->val=src->val; p->next=newNode; newNode->pre=p; p=newNode; } tail=p; p->next=nullptr; m_size=other.m_size; } return *this; } int Set::size() const { return m_size; } bool Set::empty() const { return m_size == 0; } bool Set::insert(const ItemType &value) { Node* p=head; Node* q=nullptr; while(p) { //Inserted element is a duplicate if(p->val==value) return false; //Node with greater val found, break the loop and insert else if(p->val>value) break; q=p; p=p->next; } Node* n=new Node; n->val=value; n->next=p; n->pre=q; if(p) p->pre=n; else tail=n; if(q) q->next=n; else head=n; m_size++; return true; } bool Set::erase(const ItemType& value) { //Empty list if(!head) return false; //Value is out of the range of the linked list else if(value < head->val || value > tail->val) return false; //Value is in the range of the linked list Node* p=head; while(p) { if(p->val==value) break; else if(p->val>value) return false; p=p->next; } //At head OR NOT if(p->pre) p->pre->next=p->next; else head=p->next; //At tail OR NOT if(p->next) p->next->pre=p->pre; else tail=p->pre; delete p; m_size--; return true; } bool Set::contains(const ItemType& value) const { if(!head) return false; else if (value < head->val || value > tail->val) return false; Node* p = head; //p can never reach the nullptr after the last node while(p && p->val<value) { p=p->next; } if(p->val == value) return true; else return false; } bool Set::get(int i, ItemType& value) const { //index out of bound, or size of the linked list equals 0 if(i<0 || i>=m_size || m_size==0) return false; Node* p; if(i<m_size/2) { int index=0; p=head; while(index<i) { p=p->next; index++; } } else { int index=m_size-1; p=tail; while(index>i) { p=p->pre; index--; } } value=p->val; return true; } void Set::swap(Set& other) { if(this==&other) return; //Swap the head and tail pointers Node* temp; temp = head; head = other.head; other.head=temp; temp=tail; tail=other.tail; other.tail=temp; //Swap sizes int temp_size=m_size; m_size=other.m_size; other.m_size=temp_size; } void unite(const Set& s1, const Set& s2, Set& result) { result=s1; //if two sets are the same, return one of them if(!s2.empty()){ int i=0; ItemType n; while(i<s2.size()) { s2.get(i, n); result.insert(n); i++; } } } void subtract(const Set& s1, const Set& s2, Set& result) { result=s1; if(!s2.empty()){ int i=0; ItemType n; while(i<s2.size()) { s2.get(i, n); result.erase(n); i++; } } }
true
87b095ff413f3fb3239db34a77017c43e6b7ed75
C++
tangenta/CppLexer
/lexer.cpp
UTF-8
13,473
3.03125
3
[ "MIT" ]
permissive
#include "lexer.h" #include <cctype> #include "keywords.cpp" #include "abstractscanner.h" #include "tokenhandler.h" static const char blank = ' '; Lexer::Lexer(std::shared_ptr<AbstractScanner> scanner) { if (!scanner) throw std::runtime_error("scanner unavailable"); this->scanner = scanner; } void Lexer::setScanner(std::shared_ptr<AbstractScanner> scanner) { if (!scanner) throw std::runtime_error("scanner unavailable"); this->scanner = scanner; } //// warning: never use take_s or peek_s to skip blank char Lexer::take_s() { // safe scaning if (eof()) throw std::out_of_range("eof"); char* pch = scanner->take(); if (pch == nullptr) { if (eof()) return blank; throw std::runtime_error("take_s"); } return *pch; } char Lexer::peek_s() { // safe peeking //if (eof()) throw std::out_of_range("eof"); char* pch = scanner->peek(); if (pch == nullptr) { if (eof()) return blank; throw std::runtime_error("take_s"); } return *pch; } inline bool Lexer::eof() {return scanner->eof();} // alpha [digit | alpha]* Token<void*> Lexer::scanIdentifier() { std::string result; makeSure(std::isalpha(peek_s()) || peek_s() == '_', "scanId::isalpha"); result.push_back(take_s()); while (std::isdigit(peek_s()) || std::isalpha(peek_s()) || peek_s() == '_') { result.push_back(take_s()); } // keyword or identifier if (Perfect_Hash::in_word_set(result.c_str(), static_cast<unsigned int>(result.size()))) { return Token<void*>{result, Terminal::KEYWORD, nullptr, "keyword"}; } return Token<void*>{result, Terminal::ID, nullptr, "identifier"}; } // digits = digit | digit digit* // digits (.digits)? (E digits)? Token<NumType> Lexer::scanNumber() { std::string result; auto handleDigits = [&](){ makeSure(std::isdigit(peek_s()), "handleDigits::isdigit"); result.push_back(take_s()); while (std::isdigit(peek_s())) { result.push_back(take_s()); } }; auto handleE = [&]() -> bool { if (peek_s() != 'E' && peek_s() != 'e') return false; result.push_back(take_s()); if (peek_s() == '+' || peek_s() == '-') result.push_back(take_s()); handleDigits(); return true; }; auto handlePoint = [&]() -> bool { if (peek_s() != '.') return false; result.push_back(take_s()); handleDigits(); return true; }; handleDigits(); if ((handlePoint() | handleE()) != 0) { // is floating return Token<NumType>{result, Terminal::NUM, NumType::Floating, "floating"}; } return Token<NumType>{result, Terminal::NUM, NumType::Integer, "integer"}; } // quoted with "" Token<void*> Lexer::scanString() { std::string result; makeSure(peek_s() == '\"', "scanString::isquote"); result.push_back(take_s()); while (peek_s() != '\"') result.push_back(take_s()); result.push_back(take_s()); return Token<void*>{result, Terminal::STR, nullptr, "literal string"}; } Token<void*> Lexer::scanChar() { std::string result; makeSure(peek_s() == '\'', "scanChar::isquote"); result.push_back(take_s()); while (peek_s() != '\'') result.push_back(take_s()); result.push_back(take_s()); return Token<void*>{result, Terminal::STR, nullptr, "char"}; } // quoted with /**/ Token<void*> Lexer::scanComment(bool alreadyReadFront) { std::string result = "/*"; if (!alreadyReadFront) { makeSure(take_s() == '/', "scanComment"); } makeSure(take_s() == '*', "scanComment::isbegin"); int state = 0; while (1) { switch (state) { case 0: { // continue reading comments while (peek_s() != '*') result.push_back(take_s()); result.push_back('*'); state = 1; break; } case 1: { // an asterisk occurred while (peek_s() == '*') result.push_back(take_s()); if (peek_s() != '/') { result.push_back(take_s()); state = 0; break; } else { result.push_back('/'); return Token<void*>(result, Terminal::COMMENT, nullptr, "comment"); } } } } } // begin with // Token<void*> Lexer::scanSingleLineComment(bool alreadyReadFront) { std::string result("/"); if (!alreadyReadFront) { makeSure(take_s() == '/', "scanSingleLineComment::isbegin"); result.push_back('/'); } makeSure(take_s() == '/', "scanSingleLineComment::isbegin"); result.push_back('/'); while (peek_s() != '\n' && !eof()) result.push_back(take_s()); return Token<void*>{result, Terminal::COMMENT, nullptr, "comment"}; } // splitter: (){}[];:? Token<void*> Lexer::scanSplitter() { char ch = take_s(); std::string result; result.push_back(ch); std::string value; switch (ch) { case '(' : value = "left parenthesis"; break; case ')' : value = "right parenthesis"; break; case '{' : value = "left brace"; break; case '}' : value = "right brace"; break; case '[' : value = "left bracket"; break; case ']' : value = "right bracket"; break; case ';' : value = "semicolon"; break; case ':' : value = "colon"; break; case '?' : value = "questionMark"; break; } return Token<void*>{result, Terminal::SPLITTER, nullptr, value}; } // begin with # Token<std::string> Lexer::scanDirective() { std::string result; std::string value; makeSure(peek_s() == '#', "scanDirective::is#"); bool flag = false; while (peek_s() != '\n' && !eof()) { if (peek_s() == '<') flag = true; if (peek_s() == '>') flag = false; if (flag) value.push_back(peek_s()); result.push_back(take_s()); } return Token<std::string>{result, Terminal::DIRECTIVE, value, "directive"}; } Token<void*> Lexer::scanOperator() { static const std::string sOper = ".~^,"; char ch = peek_s(); switch (ch) { case '+': return plus(); case '-': return minus(); case '*': return multiple(); case '%': return mod(); case '&': return ref(); case '|': return bitwiseOr(); case '!': return exclam(); case '<': return lessThan(); case '>': return greaterThan(); case '=': return equal(); default: { if (sOper.find(ch) != sOper.npos) return singleOper(); if (ch == '/') { take_s(); char next = peek_s(); if (next == '/') return scanSingleLineComment(true); else if (next == '*') return scanComment(true); else return div(); } makeSure(false, "not an operator"); } } // suppress warning, impossible to reach return Token<void*>(); } void Lexer::skipBlank() { if (scanner->peek() == nullptr) { if (eof()) throw std::out_of_range("eof"); throw std::runtime_error("skipBlank"); } scanner->drop(); } Token<void*> Lexer::plus() { std::string result; std::string value; makeSure(peek_s() == '+', "plus"); result.push_back(take_s()); switch (peek_s()) { case '+': value = "plus plus"; result.push_back(take_s()); break; case '=': value = "plus equal"; result.push_back(take_s()); break; default: value = "plus"; } return Token<void*>{result, Terminal::OPERATOR, nullptr, value}; } Token<void*> Lexer::minus() { std::string result; std::string value; makeSure(peek_s() == '-', "minus"); result.push_back(take_s()); switch (peek_s()) { case '-': value = "minus minus"; result.push_back(take_s()); break; case '=': value = "minus equal"; result.push_back(take_s()); break; case '>': value = "point to"; result.push_back(take_s()); break; default: value = "minus"; } return Token<void*>{result, Terminal::OPERATOR, nullptr, value}; } Token<void*> Lexer::mod() { std::string result; makeSure(peek_s() == '%', "mod"); result.push_back(take_s()); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "mod equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "mod"}; } } Token<void*> Lexer::multiple() { std::string result; makeSure(peek_s() == '*', "asterisk"); result.push_back(take_s()); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "multiple equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "dereference/multiple"}; } } Token<void*> Lexer::div() { // assume that a "/" is read already std::string result("/"); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "div equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "div"}; } } Token<void*> Lexer::ref() { std::string result; makeSure(peek_s() == '&', "ref"); result.push_back(take_s()); if (peek_s() == '&') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "and"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "ref"}; } } Token<void*> Lexer::bitwiseOr() { std::string result; makeSure(peek_s() == '|', "bitwiseOr"); result.push_back(take_s()); if (peek_s() == '|') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "or"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "bitwise or"}; } } Token<void*> Lexer::exclam() { std::string result; makeSure(peek_s() == '!', "exclam"); result.push_back(take_s()); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "not equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "not"}; } } Token<void*> Lexer::singleOper() { // dot, not, xor, comma char ch = peek_s(); static const std::string sOper = ".~^,"; makeSure(sOper.find(ch) != sOper.npos, "singleOper"); take_s(); switch (ch) { case '.': return Token<void*>{".", Terminal::OPERATOR, nullptr, "dot"}; case '~': return Token<void*>{"~", Terminal::OPERATOR, nullptr, "not"}; case '^': return Token<void*>{"^", Terminal::OPERATOR, nullptr, "xor"}; case ',': return Token<void*>{",", Terminal::OPERATOR, nullptr, "comma"}; default: throw std::runtime_error("impossible"); } } Token<void*> Lexer::lessThan() { std::string result; makeSure(peek_s() == '<', "lessThan"); result.push_back(take_s()); switch (peek_s()) { case '=': result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "lessEqual than"}; case '<': { result.push_back(take_s()); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "shift left equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "shift left"}; } } default: return Token<void*>{"<", Terminal::OPERATOR, nullptr, "less than"}; } } Token<void*> Lexer::greaterThan() { std::string result; makeSure(peek_s() == '>', "greaterThan"); result.push_back(take_s()); switch (peek_s()) { case '=': result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "greaterEqual than"}; case '>': { result.push_back(take_s()); if (peek_s() == '=') { result.push_back(take_s()); return Token<void*>{result, Terminal::OPERATOR, nullptr, "shift right equal"}; } else { return Token<void*>{result, Terminal::OPERATOR, nullptr, "shift right"}; } } default: return Token<void*>{">", Terminal::OPERATOR, nullptr, "greater than"}; } } Token<void*> Lexer::equal() { makeSure(peek_s() == '=', "equal"); take_s(); if (peek_s() == '=') { take_s(); return Token<void*>{"==", Terminal::OPERATOR, nullptr, "equal"}; } else return Token<void*>{"=", Terminal::OPERATOR, nullptr, "assign"}; } using TH = TokenHandler; std::pair<std::string, std::string> Lexer::getNext() noexcept(false) { static const std::string blank = " \t\n"; static const std::string splitter = "(){}[];:?"; static const std::string operatorBegin = "+-*%&|!<>=/.~^,"; char ch = peek_s(); while (blank.find(ch) != blank.npos) { // is blank skipBlank(); return getNext(); } if (std::isalpha(ch)) return TH::readToken(scanIdentifier()); if (std::isdigit(ch)) return TH::readToken(scanNumber()); if (ch == '\"') return TH::readToken(scanString()); if (ch == '\'') return TH::readToken(scanChar()); if (splitter.find(ch) != splitter.npos) { // is splitter return TH::readToken(scanSplitter()); } if (ch == '#') return TH::readToken(scanDirective()); if (operatorBegin.find(ch) != operatorBegin.npos) { // is operator or comment return TH::readToken(scanOperator()); } else { take_s(); return TH::readToken(Token<void*>{std::string(1, ch), Terminal::OTHER, nullptr, "unknown token"}); } }
true
fae6dc8cdfe44469d437eb263ed6eeef8f04c15b
C++
rlon9/C-
/Exercise07_05.cpp
UTF-8
930
3.359375
3
[]
no_license
// // Exercise07_05.cpp // CSCI2490 // // Created by Phil on 1/25/16. // Copyright © 2016 Phil. All rights reserved. // #include <iostream> using namespace std; int main() { cout << "Enter 10 numbers" << endl; double array[10]; for (unsigned i = 0; i < 10; i++) { cin >> array[i]; } double newArray[10] = {0}; unsigned count = 0; for(unsigned i = 0; i < 10; i++) { double temp = array[i]; bool contains = 0; for(unsigned j = 0; j < 10; j++) { if (newArray[j] == temp) { contains = 1; } if (contains == 1) break; } if (contains == 0) { newArray[i] = temp; count++; } } cout << "The distinct numbers are: "; for (unsigned i = 0; i < count; i++) { cout << newArray[i] << " "; } cout << endl; return 0; }
true
9313cd35bc17ced958b80a9262431d49762659ae
C++
wonghoifung/tips
/leetcode/easy_hamming_distance.cpp
UTF-8
562
2.90625
3
[]
no_license
#include <vector> #include <queue> #include <stack> #include <iostream> #include <sstream> #include <unordered_set> #include <unordered_map> #include <map> #include <set> #include <algorithm> #include <functional> #include <stdio.h> #include <stdlib.h> using namespace std; class Solution { public: int hammingDistance(int x, int y) { int d = 0; for (int i = 0; i < 32; ++i) { if (((x >> i) & 1) != ((y >> i) & 1)) d += 1; } return d; } }; int main() { cout << Solution().hammingDistance(1, 4) << endl; // 2 cin.get(); return EXIT_SUCCESS; }
true
70c2cab6b453bbb52d15070fd116fb7ffe51f57b
C++
thinkmariale/3D-Puzzle-Maze
/KinectProject/src/testApp.cpp
UTF-8
13,335
2.59375
3
[]
no_license
#include "testApp.h" #include <gl\glu.h> static float smoothPct = 0.75f; static int tolerance = 4; bool flag=false; int footF=0; int directionF=0; /* 1 = right 2 = left 1 = foward 2 = back */ //-------------------------------------------------------------- void testApp::setCalibrationOffset(float x, float y) { ofxMatrix4x4 matrix = kinect.getRGBDepthMatrix(); matrix.getPtr()[3] = x; matrix.getPtr()[7] = y; kinect.setRGBDepthMatrix(matrix); } void testApp::drawFigures() { switch(directionF){ case 1: //right glColor3f(1.0, 0.0, 0.0); //red glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(200, 850, 0.0f); glTexCoord2f(1, 0); glVertex3f(220, 850, 0.0f); glTexCoord2f(1, 1); glVertex3f(220, 750, 0.0f); glTexCoord2f(0, 1); glVertex3f(200, 750, 0.0f); glEnd(); shm->turn -= 0.1; if (shm->turn < -0.3) shm->turn = -0.3; break; case 2: //left glColor3f(0.0, 0.0, 1.0); //blue glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(200, 850, 0.0f); glTexCoord2f(1, 0); glVertex3f(220, 850, 0.0f); glTexCoord2f(1, 1); glVertex3f(220, 750, 0.0f); glTexCoord2f(0, 1); glVertex3f(200, 750, 0.0f); glEnd(); shm->turn += 0.1; if (shm->turn > 0.3) shm->turn = 0.3; break; case 3: //turn left shm->h-=5; if(shm->h < 0) shm->h = 355; break; case 4: //turn right shm->h+=5; if(shm->h >= 360) shm->h = 0; break; } switch(footF){ case 1: //up glColor3f(0.0, 1.0, 1.0); //light blue glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(220, 850, 0.0f); glTexCoord2f(1, 0); glVertex3f(240, 850, 0.0f); glTexCoord2f(1, 1); glVertex3f(240, 750, 0.0f); glTexCoord2f(0, 1); glVertex3f(220, 750, 0.0f); glEnd(); shm->x += cos(shm->h * PI / 180); shm->y += sin(shm->h * PI / 180); shm->s+=0.3; if(shm->s >5) shm->s=5; break; case 3: //back glColor3f(1.0, 1.0, 1.0); //black glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(220, 850, 0.0f); glTexCoord2f(1, 0); glVertex3f(240, 850, 0.0f); glTexCoord2f(1, 1); glVertex3f(240, 750, 0.0f); glTexCoord2f(0, 1); glVertex3f(220, 750, 0.0f); glEnd(); shm->s -=0.3; if(shm->s < -5) shm->s= -5; shm->x -= cos(shm->h * PI / 180); shm->y -= sin(shm->h * PI / 180); break; case 2: //back -- stop glColor3f(0.0, 0.0, 0.0); //black glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(220, 850, 0.0f); glTexCoord2f(1, 0); glVertex3f(240, 850, 0.0f); glTexCoord2f(1, 1); glVertex3f(240, 750, 0.0f); glTexCoord2f(0, 1); glVertex3f(220, 750, 0.0f); glEnd(); shm->s = 0; break; } } //-------------------------------------------------------------- void testApp::setup() { ofSetLogLevel(OF_LOG_VERBOSE); // enable depth->rgb image calibration kinect.setRegistration(true); kinect.init(); kinect.setVerbose(true); //kinect.init(true); // shows infrared instead of RGB video image //kinect.init(false, false); // disable video image (faster fps) kinect.open(); //kinect.getCalibratedColorAt(60, 230); //Allocate space for all images colorImg.allocate(kinect.width, kinect.height); grayImage.allocate(kinect.width, kinect.height); grayBg.allocate(kinect.width, kinect.height); grayDiff.allocate(kinect.width, kinect.height); footDiff.allocate(kinect.width, kinect.height ); handDiff.allocate(kinect.width, kinect.height ); grayThreshNear.allocate(kinect.width, kinect.height); grayThreshFar.allocate(kinect.width, kinect.height); // Don't capture the background at startup bLearnBakground = false; // set up sensable defaults for threshold and calibration offsets // Note: these are empirically set based on my kinect, they will likely need adjusting threshold = 73; xOff = 13.486656; yOff = 34.486656; setCalibrationOffset(xOff, yOff); nearThreshold = 250; farThreshold = 70; bThreshWithOpenCV = true; // Set depth map so near values are higher (white) kinect.enableDepthNearValueWhite(true); ofSetFrameRate(30); // zero the tilt on startup angle = 0; kinect.setCameraTiltAngle(angle); // start from the front bDrawPointCloud = false; bDrawContourFinder = false; } //-------------------------------------------------------------- void testApp::update() { ofBackground(100, 100, 100); kinect.update(); // load grayscale depth image from the kinect source grayImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height); colorImg.setFromPixels(kinect.getPixels(), kinect.width, kinect.height); colorImg.getCvImage(); // Quick and dirty noise filter on the depth map. Needs work grayImage.dilate(); grayImage.erode(); // If the user pressed spacebar, capture the depth and RGB images and save for later if (bLearnBakground == true) { grayBg = grayImage; bLearnBakground = false; } // Subtract the saved background from the current one grayDiff = grayImage; grayDiff -= grayBg; grayDiff.threshold(1); // anything that is > 1 has changed, so keep it grayDiff *= grayImage; // multiply in the current depth values, to mask it // Copy the filtered depthmap so we can use it for detecting feet footDiff= grayDiff; handDiff=grayDiff; // for feet we want to focus on only the bottom part of the image (et the region of interest to the bottom 180 px) footDiff.setROI(0,300,footDiff.width, footDiff.height/2); handDiff.setROI(0,0,handDiff.width, handDiff.height/2); // cut off anything that is too far away grayDiff.threshold(farThreshold); footDiff.threshold(farThreshold); handDiff.threshold(farThreshold); // since we set ROI, we need to reset it footDiff.resetROI(); handDiff.resetROI(); // also, since ROI was on when we did the above threshold we clear out all pixels that are not fully white //(which ends up being only the upper part of the iamge) footDiff.threshold(nearThreshold); handDiff.threshold(nearThreshold); handDiff.mirror(false,true); footDiff.mirror(false,true); // Find blobs (should be hands and foot) in the filtered depthmap contourFinder.findContours(handDiff, 1000, (kinect.width*kinect.height)/2, 5, false); footContourFinder.findContours(footDiff, 1000, (kinect.width*kinect.height)/2, 5, false); // if at least 2 blobs were detected (presumably 2 hands), figure out // their locations and calculate which way to "move" if (contourFinder.blobs.size() >= 2) { turnR = false; turnL = false; // Find the x,y cord of the center of the first 2 blobs float x1 = contourFinder.blobs[0].centroid.x; float y1 = contourFinder.blobs[0].centroid.y; float x2 = contourFinder.blobs[1].centroid.x; float y2 = contourFinder.blobs[1].centroid.y; // the x1<x2 check is to ensure that p1 is always the rightmost blob (right hand) ofPoint p1(x1<x2 ? x1 : x2,x1<x2 ? y1 : y2, 0); ofPoint p2(x2<x1 ? x1 : x2,x2<x1 ? y1 : y2, 0); if(p1.y > p2.y ) // turning right if righ hand raised { if(!rightDown) // if right is already down, dont send key even again { directionF=1; leftDown = false; rightDown = true; } } else if(p1.y < p2.y ) // turning left if left hand raised { if(!leftDown) // if left is already down, dont send key even again { directionF=2; rightDown = false; leftDown = true; } } else // hands centered so moving straight { if(leftDown) { directionF=0; leftDown = false; } if(rightDown) { directionF=0; rightDown = false; } } } /* one hand detected >> rotate*/ else if(contourFinder.blobs.size() == 1) { // Find the x,y cord of the center of blob float x1 = contourFinder.blobs[0].centroid.x; float y1 = contourFinder.blobs[0].centroid.y; if(x1 < (handDiff.width/2) ) //left hand up so rotate left { if(!turnL) { directionF = 4; turnL = true; turnR = false; } } else if(x1 > (handDiff.width/2) ) // right hand up so rotate right { if(!turnR) { directionF = 3; turnR = true; turnL = false; } } else { if(turnR) { directionF=0; turnR = false; } if(turnL) { directionF=0; turnL = false; } } } // no hands detected so moving straight else { if(leftDown) { directionF=0; leftDown = false; } if(rightDown) { directionF=0; rightDown = false; } turnR = false; turnL = false; directionF=0; } // if any blob is detected in the foot map, it can be considered a foot if(footContourFinder.blobs.size() >= 1) { // Find the x,y cord of the center of blob float x1 = footContourFinder.blobs[0].centroid.x; //float y1 = contourFinder.blobs[0].centroid.y; if(x1 > (footDiff.width/2) ) //right leg infront { if(!footFDown) //moving foward { footF= 1; footFDown = true; footBDown = false; } } else // left leg infront { if(!footBDown) //moving foward { footF= 3; footBDown = true; footFDown = false; } } footDown = true; } else { //ofBackground(100,100,100); if(footDown) { footF=2; //stop footDown = false; footFDown = false; footBDown = false; } } // update the cv images grayImage.flagImageChanged(); } //-------------------------------------------------------------- void testApp::draw() { ofSetColor(255, 255, 255); // Draw some debug images along the top handDiff.draw(20, 256, 315, 236); footDiff.draw(20, 502, 315, 236); // Draw a larger image of the calibrated RGB camera and overlay the found blobs on top of it colorImg.mirror(false,true); colorImg.draw(20, 10, 315, 236); contourFinder.draw(20, 10, 315, 236); footContourFinder.draw(20, 10, 315, 236); // Display some debugging info char reportStr[1024]; //sprintf(reportStr, "left: %i right: %i foot: %i", leftDown, rightDown, footDown); sprintf(reportStr, "left: %f right: %f foot: %f", shm->x, shm->y, shm->z); ofDrawBitmapString(reportStr, 20, 800); drawFigures(); if(bDrawPointCloud) { easyCam.begin(); drawPointCloud(); easyCam.end(); } else if(bDrawContourFinder) { contourFinder.draw(0,0, 1024, 768);} } //-------------------------------------------------------------- void testApp::drawPointCloud() { int w = 640; int h = 480; ofMesh mesh; mesh.setMode(OF_PRIMITIVE_POINTS); int step = 2; for(int y = 0; y < h; y += step) { for(int x = 0; x < w; x += step) { if(kinect.getDistanceAt(x, y) > 0) { mesh.addColor(kinect.getColorAt(x,y)); mesh.addVertex(kinect.getWorldCoordinateAt(x, y)); } } } glPointSize(3); ofPushMatrix(); // the projected points are 'upside down' and 'backwards' ofScale(1, -1, -1); ofTranslate(0, 0, -1000); // center the points a bit glEnable(GL_DEPTH_TEST); mesh.drawVertices(); glDisable(GL_DEPTH_TEST); ofPopMatrix(); } //-------------------------------------------------------------- void testApp::exit() { kinect.setCameraTiltAngle(0); // zero the tilt on exit kinect.close(); } //-------------------------------------------------------------- void testApp::keyPressed (int key) { switch (key) { case ' ': bThreshWithOpenCV = !bThreshWithOpenCV; break; case 'b': bLearnBakground = true; break; case'p': bDrawPointCloud = !bDrawPointCloud; bDrawContourFinder = false; break; case 'c': bDrawContourFinder=!bDrawContourFinder; bDrawPointCloud = false; break; break; case 'x': flag=true; break; case '>': case '.': farThreshold ++; if (farThreshold > 255) farThreshold = 255; break; case '<': case ',': farThreshold --; if (farThreshold < 0) farThreshold = 0; break; case '+': case '=': nearThreshold ++; if (nearThreshold > 255) nearThreshold = 255; break; case '-': nearThreshold --; if (nearThreshold < 0) nearThreshold = 0; break; case 'w': kinect.enableDepthNearValueWhite(!kinect.isDepthNearValueWhite()); break; case 'a': kinect.setCameraTiltAngle(angle); // go back to prev tilt kinect.open(); break; case 'z': kinect.setCameraTiltAngle(0); // zero the tilt kinect.close(); break; case OF_KEY_UP: angle++; if(angle>30) angle=30; kinect.setCameraTiltAngle(angle); break; case OF_KEY_DOWN: angle--; if(angle<-30) angle=-30; kinect.setCameraTiltAngle(angle); break; case '[': yOff++; setCalibrationOffset(xOff, yOff); break; case ']': yOff--; setCalibrationOffset(xOff, yOff); break; case OF_KEY_LEFT: xOff--; setCalibrationOffset(xOff, yOff); break; case OF_KEY_RIGHT: xOff++; setCalibrationOffset(xOff, yOff); break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button) {} //-------------------------------------------------------------- void testApp::windowResized(int w, int h) {}
true
9853ac7479faecc8cd5e1c12d030f323926712ad
C++
enra64/PKES
/aufgabe4_float_serial_input_clion_funktioniert_ein_rad_drehung/average_ring.h
UTF-8
656
2.75
3
[]
no_license
/* * arnes_fifo_buffer.cpp * * Created: 22-Oct-15 14:36:21 * Author: Arne */ #ifndef flav #define flav //generic includes #include <stdbool.h>//bool #include <avr/io.h>//uint8_t #define SIZE 3 class AverageRing{ float _buffer[SIZE]; uint8_t _head = 0; public: bool write(float newValue){ _buffer[_head] = newValue; _head = (_head + 1) % SIZE; } float readAvg(void){ float sum = 0; for(uint8_t i = 0; i < SIZE; i++) sum = sum + _buffer[i]; return sum / SIZE; } void clear(void){ for(uint8_t i = 0; i < SIZE; i++) _buffer[i] = 0; _head = 0; } }; #endif
true
802bf4c387051a3a2f0bdfbf7f0d6b3a0f976047
C++
gbrlas/AVSP
/CodeJamCrawler/dataset/14_7385_55.cpp
UTF-8
1,169
3.140625
3
[]
no_license
#include<stdio.h> #include<iostream> #include<math.h> #include<stdlib.h> using namespace std; int compare (const void * a, const void * b) { return ( (*(double*)a > *(double*)b)? 1 : -1 ); } //a,b sorted int dw(double *a,double *b,int n) { int i=0,j=0,re=0; while(i<n){ if(*(a+i)>*(b+j)){ i++;j++;re++; } else{ i++; } } return re; } int d(double *a,double *b,int n) { return(n-dw(b,a,n)); } int main() { int n,i,t,T; double temp; // double a[NN],b[NN]; freopen("data4.in","r",stdin); freopen("data4.out","w",stdout); cin>>T; for(t=0;t<T;t++){ cin>>n; double *a=new double[n]; double *b=new double[n]; for(i=0;i<n;i++) { cin>>*(a+i); } for(i=0;i<n;i++){ cin>>*(b+i); } qsort(a,n,sizeof(double),compare); qsort(b,n,sizeof(double),compare); cout<<"Case #"<<t+1<<": "<<dw(a,b,n)<<" "<<d(a,b,n)<<endl; delete [] a; delete [] b; } fclose(stdin); fclose(stdout); }
true
59480e88cf0b815db24799396db27493fcb6733e
C++
PhilipHannemann/ObjectCollision
/project/Source/Quantum/PhysicEngine/SphereTreeNode.h
UTF-8
1,085
2.65625
3
[]
no_license
#pragma once #include <glm\glm.hpp> #define _SphereTreeNode_NUM_CHILDREN_ 8 namespace physics { class SphereTreeNode { public: enum SphereFlag { LEAF, INNER_NODE, ROOT }; static const int num_children; int64_t update_tick; glm::vec3 center; float radius; glm::vec3 original_center; float original_radius; SphereTreeNode* parent; SphereTreeNode* children[_SphereTreeNode_NUM_CHILDREN_]; SphereFlag flag; std::vector<int> particle_ids; SphereTreeNode(const SphereTreeNode &source); SphereTreeNode(const SphereTreeNode &source, glm::mat4x4 &trans, float &largestScale); SphereTreeNode(SphereTreeNode* parent, glm::vec3 center, float radius, SphereFlag flag) : particle_ids() { this->parent = parent; this->center = center; this->radius = radius; this->flag = flag; update_tick = -1; for (int i = 0; i < num_children; i++) { children[num_children] = NULL; } original_center = glm::vec3(0.f); original_radius = 0.f; } ~SphereTreeNode(); bool overlaps(SphereTreeNode* other) const; }; }
true
e074ec232f68c5e5e54038a40c80209aff26d803
C++
Alex4386-vault/clang-programming
/06/06/shortIfStatement.cpp
UTF-8
398
3.1875
3
[]
no_license
#include <stdio.h> int main() { // This is how to give a FUCK to your // coworkers by using shitty indentations int hours; scanf("%d", &hours); /* if (hours > 40) printf("Good"); else printf("bad"); */ //puts((hours > 40) ? "Good" : "Bad"); //printf((hours > 40) ? "Good" : "Bad"); // hours > 40 ? puts("Good") : puts("Bad"); // hours > 40 ? printf("Good") : printf("Bad"); }
true
fa34ac484522b7fba2d728a85d9698c3326fd2dd
C++
YouDad/test_finger
/test_finger/MyThread.cpp
GB18030
1,961
3.125
3
[]
no_license
#include "stdafx.h" // tmpΪ,ô߳̽Զͷ,ֻnewûdelete MyThread::MyThread(ThreadFunction_t pFunction,bool tmp){ pf=pFunction; temporary=tmp; } // ͷŵĽṹ struct temporaryParam{ ThreadFunction_t pf; MyThread* beDelete; }; // Ҫͷŵʱ߳ std::vector<temporaryParam> TPVec; // ͣסֱ̻߳߳size֮ټ MyLocker getSize(0,1); // ߳ bool MyThread::start(){ if(temporary){ // һVecDzпλ bool needPushBack=true; int posInVec; for(int i=0;i<TPVec.size();i++){ if(TPVec[i].beDelete==0){ TPVec[i].pf=pf; TPVec[i].beDelete=this; needPushBack=false; posInVec=i; break; } } // ûпλ,push_backһ if(needPushBack){ TPVec.push_back(temporaryParam{pf,this}); posInVec=TPVec.size()-1; } // ߳ thread=CreateThread(0,0,temporaryRun,&posInVec,0,0); getSize.lock(); } else{ thread=CreateThread(0,0,run,&pf,0,0); } return thread!=0; } // ر߳ bool MyThread::terminate(){ if(thread){ TerminateThread(thread,-1); CloseHandle(thread); thread=0; return true; } return false; } // ߳Ƿ bool MyThread::isRun(){ return thread!=0; } // ͨ߳к DWORD WINAPI MyThread::run(LPVOID params){ (*(ThreadFunction_t*)params)(); return 0; } // ͷ߳к DWORD WINAPI MyThread::temporaryRun(LPVOID params){ // ҪҪִеʱ߳± int size=*(int*)params; getSize.unlock(); TPVec[size].pf(); delete TPVec[size].beDelete; TPVec[size].beDelete=0; return 0; }
true
792c5abd1f257f1933ca42a30aa0efcdb6655068
C++
Andydas/Vysledky-parlamentnych-volieb-AUDS
/Semestralka2/uzemna_jednotka.cpp
UTF-8
1,305
2.828125
3
[]
no_license
#include "uzemna_jednotka.h" UzemnaJednotka::UzemnaJednotka(int kod, wstring nazov, TypUJ typ, UzemnaJednotka* predok) : kod_(kod), nazov_(nazov), typ_(typ), predok_(predok) { volici_ = 0; zucastneni_ = 0; odovzdaneObalkyOsobne_ = 0; odovzdaneObalkyCudzina_ = 0; platneHlasy_ = 0; } int UzemnaJednotka::getOdovzdaneObalky(TypOdovzdanie sposob) { switch (sposob) { case TypOdovzdanie::OSOBNE: return odovzdaneObalkyOsobne_; case TypOdovzdanie::CUDZINA: return odovzdaneObalkyCudzina_; case TypOdovzdanie::SPOLU: return odovzdaneObalkyCudzina_ + odovzdaneObalkyOsobne_; } } bool UzemnaJednotka::maPredka(UzemnaJednotka* predok) { if (predok == predok_) { return true; } else if(predok_ != nullptr) { return predok_->maPredka(predok); } else { return false; } } void UzemnaJednotka::vypisPredkov() { if (predok_ != nullptr) { wcout << predok_->getNazov() << endl; predok_->vypisPredkov(); } else { return; } } void UzemnaJednotka::naplnUdaje(int volici, int zucastneni, int osobne, int cudzina, int platne) { volici_ += volici; zucastneni_ += zucastneni; odovzdaneObalkyOsobne_ += osobne; odovzdaneObalkyCudzina_ += cudzina; platneHlasy_ += platne; if (predok_ != nullptr) { predok_->naplnUdaje(volici, zucastneni, osobne, cudzina, platne); } }
true
85428acedb0241da6b284c3b9c4b57806f7a7016
C++
metiscus/gameengine
/map.hpp
UTF-8
4,712
2.875
3
[]
no_license
#ifndef GAME_ENGINE_MAP_HPP #define GAME_ENGINE_MAP_HPP #include <SFML/Graphics.hpp> #include <functional> class Game; class Object; struct Game_Action { Game_Action(std::string t_description, std::function<void (const float, const float, Game &)> t_action) : description(std::move(t_description)), action(std::move(t_action)) { } std::string description; std::function<void (const float, const float, Game &)> action; }; struct Object_Action { Object_Action(std::string t_description, std::function<void (const float, const float, Game &, Object &)> t_action) : description(std::move(t_description)), action(std::move(t_action)) { } std::string description; std::function<void (const float, const float, Game &, Object &)> action; }; class Object : public sf::Sprite { public: Object(std::string t_name, const sf::Texture &t_texture, const int width, const int height, const float fps, std::function<void (const float, const float, Game &, Object &, sf::Sprite &)> t_collision_action, std::function<std::vector<Object_Action> (const float, const float, Game &, Object &)> t_action_generator); virtual ~Object() = default; void update(const float t_game_time, const float /*t_simulation_time*/, Game &t_game); std::vector<Object_Action> get_actions(const float t_game_time, const float t_simulation_time, Game &t_game); void do_collision(const float t_game_time, const float t_simulation_time, Game &t_game, sf::Sprite &t_collided_with); private: std::string m_name; std::reference_wrapper<const sf::Texture> m_texture; int m_width; int m_height; int m_num_frames; float m_fps; std::function<void (const float, const float, Game &, Object &, sf::Sprite &)> m_collision_action; std::function<std::vector<Object_Action> (const float, const float, Game &, Object &)> m_action_generator; }; struct Tile_Properties { Tile_Properties(bool t_passable = true, std::function<void (float, float)> t_movement_action = std::function<void (float, float)>()); void do_movement_action(const float t_game_time, const float t_simulation_time); bool passable; std::function<void (float, float)> movement_action; }; struct Line_Segment { Line_Segment(sf::Vector2f t_p1, sf::Vector2f t_p2); Line_Segment(); Line_Segment(const Line_Segment &) = default; Line_Segment(Line_Segment &&) = default; Line_Segment &operator=(const Line_Segment &) = default; Line_Segment &operator=(Line_Segment &&) = default; float x(const float y) const; float y(const float x) const; explicit operator bool() const; float distance_to_p1(const sf::Vector2f &t_point) const; float length() const; sf::FloatRect boundingRect() const; Line_Segment clipTo(const sf::FloatRect &t_rect) const; sf::Vector2f p1; sf::Vector2f p2; bool valid; }; struct Tile_Data { Tile_Data(int t_x, int t_y, Tile_Properties t_props, sf::FloatRect t_bounds); int x; int y; Tile_Properties properties; sf::FloatRect bounds; }; class Tile_Map : public sf::Drawable, public sf::Transformable { public: Tile_Map(const sf::Texture &t_tileset, const sf::Vector2u &t_tile_size, const std::vector<int> &tiles, const unsigned int width, const unsigned int height, std::map<int, Tile_Properties> t_map_defaults); virtual ~Tile_Map() = default; void add_enter_action(const std::function<void (Game &)> t_action); void enter(Game &t_game); sf::Vector2u dimensions_in_pixels() const; bool load(sf::Vector2u t_tile_size, const std::vector<int> &tiles, const unsigned int width, const unsigned int height); void add_object(const Object &t_o); static sf::FloatRect get_bounding_box(const sf::Sprite &t_s, const sf::Vector2f &t_distance); bool test_move(const sf::Sprite &t_s, const sf::Vector2f &distance) const; std::vector<std::reference_wrapper<Object>> get_collisions(const sf::Sprite &t_s, const sf::Vector2f &t_distance); sf::Vector2f adjust_move(const sf::Sprite &t_s, const sf::Vector2f &distance) const; void do_move(const float t_time, sf::Sprite &t_s, const sf::Vector2f &distance); void update(const float t_game_time, const float t_simulation_time, Game &t_game); private: virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; sf::VertexArray m_vertices; std::reference_wrapper<const sf::Texture> m_tileset; std::vector<Tile_Data> m_tile_data; std::map<int, Tile_Properties> m_map_defaults; std::vector<Object> m_objects; std::vector<std::function<void (Game &)>> m_enter_actions; sf::Vector2u m_map_size; sf::Vector2u m_tile_size; }; #endif
true
100e9b1db0559b8e02c1d345d57779cdc8016dbd
C++
ViPErCZ/snake3d
/Manager/EatManager.cpp
UTF-8
727
2.546875
3
[ "MIT" ]
permissive
#include "EatManager.h" namespace Manager { EatManager::EatManager(EatLocationHandler *handler) : handler(handler) {} EatManager::~EatManager() { delete handler; } void EatManager::run(EatManager::eat_EVENT event) { switch (event) { case eatenUp: handler->onDefaultHandler(); break; case clean: handler->onCleanHandler(); break; case firstPlace: handler->onFirstPlaceHandler(); break; case checkPlace: handler->onCheckPlaceHandler(); break; case none: break; } } } // Manager
true
da6804fc0e8266ccf69bf3e92f70c6fe1798fb0b
C++
antoniocaia/cp20-21
/code/kadane.cpp
UTF-8
1,007
3.625
4
[]
no_license
#include <iostream> #include <vector> /* time complexity: O(n) space complexity: O(1) While iterating the input array, we refer to all the element previusly scanned as prefix. If the sum of the prefix is negative, the prefix must be excluded, because simply doing that we can optain a sub array whose sum is bigger. Everytime the sum of the elements became negative, we start to count from the next element, without having to back-track. */ void kadane(std::vector<int> l) { int n = l.size(); int max = l[0]; int sum = l[0]; for (int i = 1; i < n; i++) { if (sum < 0) { sum = l[i]; } else { sum += l[i]; } if (sum > max) max = sum; } std::cout << max; } int main() { int test_case; std::cin >> test_case; for (int t = 0; t < test_case; t++) { int size; std::cin >> size; std::vector<int> l; l.reserve(size); for (int i = 0; i < size; i++) { int input = 0; std::cin >> input; l.push_back(input); } kadane(l); std::cout << "\n"; } }
true
21daed18bbdd4523dcf23df02650561442166c91
C++
syfchao/quick-start-app
/libsrvkit/src/async_task.cc
UTF-8
2,357
2.84375
3
[]
no_license
#include <async_task.h> extern int g_svr_exit; async_routine_t* malloc_async_routines(int cnt, size_t max_pending_task) { async_routine_t* routines = (async_routine_t*)calloc(cnt, sizeof(async_routine_t)); if(NULL == routines){ LOG_ERR("Out of memory"); return NULL; } for(int i = 0; i < cnt; ++i){ async_routine_t* routine = routines + i; pthread_mutex_init(&(routine->mutex), NULL); INIT_LIST_HEAD(&(routine->tasks)); sem_init(&(routine->sem_task), 0, 0); routine->max_pending_task = max_pending_task; } return routines; } static void recycle_task(async_task_t* task) { free(task); } static void* async_pthread_routine(void* arg) { async_routine_t* routine = (async_routine_t*)arg; pthread_detach(routine->pthread_id); //struct timespec abs_timeout = {1, 0}; while(!g_svr_exit){ //if(sem_timedwait(&(routine->sem_task), &abs_timeout)){ if(sem_wait(&(routine->sem_task))){ printf("wait##\n"); continue; } pthread_mutex_lock(&(routine->mutex)); list_head* p = pop_list_node(&(routine->tasks)); --routine->cnt_task; pthread_mutex_unlock(&(routine->mutex)); if(!p){ LOG_ERR("inpossible here!"); continue; } async_task_t* task = list_entry(p, async_task_t, list); if(!task->fn_task){ LOG_ERR("[ALARM]miss task fn!!! BE CARE MEM LEAK"); }else{ (task->fn_task)(task->task_params); } recycle_task(task); } LOG_INFO("server exited"); return NULL; } int run_async_routines(async_routine_t* array, int cnt) { for(int i = 0; i < cnt; ++i){ async_routine_t* routine = array + i; pthread_create(&(routine->pthread_id), NULL, async_pthread_routine, routine); } return 0; } int add_task_2_routine(async_routine_t* routine, fn_async_routine fn, void* task_data, bool force_add) { if(!force_add && routine->cnt_task > routine->max_pending_task){ LOG_ERR("too much pending task. %llu:%llu", routine->cnt_task, routine->max_pending_task); return -1; } async_task_t* task = (async_task_t*)calloc(1, sizeof(async_task_t)); if(NULL == task){ LOG_ERR("OUT OF MEM"); return -2; } task->fn_task = fn; task->task_params = task_data; INIT_LIST_HEAD(&(task->list)); pthread_mutex_lock(&(routine->mutex)); ++routine->cnt_task; list_add_tail(&(task->list), &(routine->tasks)); pthread_mutex_unlock(&(routine->mutex)); sem_post(&(routine->sem_task)); return 0; }
true
cf62ecf18bee11659538bb5f6444a998cb866319
C++
Mic-Tartaglia/Tartaglia_NumSimExercises
/Week1/es1_3/es1_3.cpp
UTF-8
2,721
2.796875
3
[]
no_license
#include "random.h" #include <iostream> #include <fstream> #include <cmath> using namespace std; double StdDev(double mean, double sq_mean, int n); int main(){ //**********************************************************************// //SETTING UP GENERATOR Random rnd; int seed[4]; int p1, p2; //import seed and primes ifstream Primes("Primes"); if (Primes.is_open()){ Primes >> p1 >> p2 ; } else cerr << "PROBLEM: Unable to open Primes" << endl; Primes.close(); ifstream input("seed.in"); string property; if (input.is_open()){ while ( !input.eof() ){ input >> property; if( property == "RANDOMSEED" ){ input >> seed[2] >> seed[1] >> seed[3] >> seed[0]; rnd.SetRandom(seed,255,1561); } } input.close(); } else cerr << "PROBLEM: Unable to open seed.in" << endl; //**********************************************************************// //FILLING ARRAY OF RANDOM NUMBERS IN [0,1] int const N_exp = 1e4; int const N_throws = 1e5; int const N_blocks = 100; int blk_len = N_exp/N_blocks; double x, theta; double pi_estim[N_exp]; double const d= 1.2; double const L= 1; int counter= 0; ofstream pi_out("pi.dat"); ofstream err_out("errors.dat"); double ave[N_blocks]; double sq_ave[N_blocks]; double prog_est[N_blocks]; double prog_sq[N_blocks]; double prog_err[N_blocks]; for (int k=0;k<N_exp;k++){ counter=0; for(int thr=0;thr<N_throws;thr++){ //x = rnd.Rannyu(0, d) // USE THIS WITH COMMENTED OPTION BELOW x = rnd.Rannyu( -d/2, d/2);// OR EQUIVALENTLY, THIS WITH THE SECOND ONE BELOW theta = rnd.Rannyu( 0, 2*M_PI); //if ( ( x + L/2*cos(theta)<0) or (x + L/2*cos(theta) >d) or ( x - L/2*cos(theta)<0) or (x - L/2*cos(theta) >d) ) //THIS ONE WORKS WITH RANDOMS ABOVE if ( (x-L/2*cos(theta))*(x+L/2*cos(theta)) < 0) // counter+=1; } pi_estim[k] = (double)N_throws/counter * 2*L/d; //pi_out << pi_estim[k] << "\n"; //cout << "hits: " << counter << "\thit/total: " << (double)counter/N_throws << "\tshould be: " << 2*L/(M_PI*d) <<"\n"; } for (int k=0;k<N_blocks;k++){ //block averaginfg ave[k]=0; prog_est[k]=0; prog_sq[k]=0; for(int i=0;i<blk_len;i++) ave[k]+= pi_estim[k*blk_len + i] /blk_len; sq_ave[k]= ave[k]*ave[k]; for(int j=0;j<=k;j++){ prog_est[k]+=ave[j]; prog_sq[k]+=sq_ave[j]; } prog_est[k]/= (double)(k+1); prog_sq[k]/= (double)(k+1); prog_err[k]= StdDev( prog_est[k], prog_sq[k], k+1); pi_out << prog_est[k] << "\n"; err_out << prog_err[k] << "\n"; } return 0; } double StdDev(double mean, double sq_mean, int n){ return sqrt (( sq_mean - mean*mean )/n); }
true
402947a162d8f1e61d38e45be76e5666a86ae2b3
C++
dkwired/coursework
/cs130/project1/main.cpp
UTF-8
6,081
2.984375
3
[]
no_license
// Name: David Klein // Quarter, Year: Fall 2013 // Lab: 021 // // This file is to be modified by the student. // main.cpp //////////////////////////////////////////////////////////// // FRONT VIEW - Drop z axis // SIDE VIEW - Drop x axis // TOP VIEW - Drop y axis #include <GL/glut.h> #include <math.h> #include <iostream> #include <vector> using std::string; using std::cout; using std::cin; const int WINDOW_WIDTH = 800; const int WINDOW_HEIGHT = 800; struct S_POINT // point struct to store points of each side { double x; double y; double z; S_POINT() : x(0.0), y(0.0), z(0.0) {} S_POINT(const double & nx, const double & ny, const double & nz) : x(nx), y(ny), z(nz) {} }; struct S_FACE // face struct to store sides of each triangle { int a; int b; int c; S_FACE() : a(0), b(0), c(0) {} S_FACE(const double & na, const double & nb, const double & nc) : a(na), b(nb), c(nc) {} }; int NUM_POINTS = 0; int NUM_FACES = 0; std::vector<S_POINT> POINTS; std::vector<S_FACE> FACES; // Renders a quad at cell (x, y) with dimensions CELL_LENGTH void renderPixel(int x, int y, float r = 1.0, float g = 1.0, float b = 1.0) { glBegin(GL_POINTS); glVertex2i(x, y); glEnd(); } void DDA(int x0, int y0, int x1, int y1 ) { int dy = y1 - y0; int dx = x1 - x0; int m; float xinc; float yinc; float x = x0; float y = y0; if( abs(dx) > abs(dy) ) { m = abs(dx); } else { m = abs(dy); } xinc=(float) dx / (float) m; yinc = (float) dy / (float) m; renderPixel( round(x), round(y) ); for( int i = 0; i < m; i++ ) { x += xinc; y += yinc; renderPixel( round(x), round(y) ); } } // draw n subdivisions int Subdivision( S_POINT & p1, S_POINT & p2, S_POINT & p3, int i, int n ) { if( i == 0 ) return 0; else { S_POINT mp1; // create temporary points S_POINT mp2; S_POINT mp3; mp1.x = (p1.x + p2.x)/2; // calculate midpoints for all sides mp1.y = (p1.y + p2.y)/2; mp1.z = (p1.z + p2.z)/2; mp2.x = (p2.x + p3.x)/2; mp2.y = (p2.y + p3.y)/2; mp2.z = (p2.z + p3.z)/2; mp3.x = (p3.x + p1.x)/2; mp3.y = (p3.y + p1.y)/2; mp3.z = (p3.z + p1.z)/2; if( n == 0 ) // if we are drawing the front { DDA( mp1.x, mp1.y, mp2.x, mp2.y ); DDA( mp2.x, mp2.y, mp3.x, mp3.y ); DDA( mp3.x, mp3.y, mp1.x, mp1.y ); } if( n == 1 ) // if we are drawing the side { DDA( mp1.z, mp1.y, mp2.z, mp2.y ); DDA( mp2.z, mp2.y, mp3.z, mp3.y ); DDA( mp3.z, mp3.y, mp1.z, mp1.y ); } if( n == 2 ) // if we are drawing the top { DDA( mp1.x, mp1.z, mp2.x, mp2.z ); DDA( mp2.x, mp2.z, mp3.x, mp3.z ); DDA( mp3.x, mp3.z, mp1.x, mp1.z ); } Subdivision(mp1, mp2, mp3, i-1, n); // recurse on left over triangles Subdivision(p1, mp1, mp3, i-1, n); Subdivision(mp1, p2, mp2, i-1, n); Subdivision(p3, mp3, mp2, i-1, n); //Subdivision(p3, mp3, mp2, i-1, n); } } // draw the front of the triangle void Draw_Front( S_FACE & face ) { DDA( POINTS[face.a].x, POINTS[face.a].y, POINTS[face.b].x, POINTS[face.b].y ); DDA( POINTS[face.b].x, POINTS[face.b].y, POINTS[face.c].x, POINTS[face.c].y ); DDA( POINTS[face.c].x, POINTS[face.c].y, POINTS[face.a].x, POINTS[face.a].y ); Subdivision(POINTS[face.a], POINTS[face.b], POINTS[face.c], 2, 0); } // draw the side of the triangle void Draw_Side( S_FACE & face ) { DDA( POINTS[face.a].z, POINTS[face.a].y, POINTS[face.b].z, POINTS[face.b].y ); DDA( POINTS[face.b].z, POINTS[face.b].y, POINTS[face.c].z, POINTS[face.c].y ); DDA( POINTS[face.c].z, POINTS[face.c].y, POINTS[face.a].z, POINTS[face.a].y ); Subdivision(POINTS[face.a], POINTS[face.b], POINTS[face.c], 2, 1); } // draw the top of the triangle void Draw_Top( S_FACE & face ) { DDA( POINTS[face.a].x, POINTS[face.a].z, POINTS[face.b].x, POINTS[face.b].z ); DDA( POINTS[face.b].x, POINTS[face.b].z, POINTS[face.c].x, POINTS[face.c].z ); DDA( POINTS[face.c].x, POINTS[face.c].z, POINTS[face.a].x, POINTS[face.a].z ); Subdivision(POINTS[face.a], POINTS[face.b], POINTS[face.c], 2, 2); } //Output function to OpenGL Buffer void GL_render() { glClear(GL_COLOR_BUFFER_BIT); for( int i = 0; i < NUM_FACES; i++ ) { Draw_Top( FACES[i] ); // replace function with what want to draw } glutSwapBuffers(); } //Initializes OpenGL attributes void GLInit(int* argc, char** argv) {struct Point3D { double x; double y; double z; Point3D() : x(0.0), y(0.0), z(0.0) {} Point3D(const double & nx, const double & ny, const double & nz) : x(nx), y(ny), z(nz) {} }; glutInit(argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); // ... // Complete this function // ... glutCreateWindow("CS 130 - David Klein"); glutDisplayFunc(GL_render); // The default view coordinates is (-1.0, -1.0) bottom left & (1.0, 1.0) top right. // For the purposes of this lab, this is set to the number of pixels // in each dimension. glMatrixMode(GL_PROJECTION_MATRIX); glOrtho(0, WINDOW_WIDTH, 0, WINDOW_HEIGHT, -1, 1); } int main(int argc, char** argv) { string lineInput; // input file // get the number of points cin >> lineInput; NUM_POINTS = atoi( lineInput.c_str() ); // get the number of faces cin >> lineInput; NUM_FACES = atoi( lineInput.c_str() ); // get the list of points int count = 0; // counter for input S_POINT temp_point; // temp point for each loop while (count < NUM_POINTS) { cin >> lineInput; temp_point.x = 8 * atoi(lineInput.c_str()); // multiply by 8 to scale up cin >> lineInput; temp_point.y = 8 * atoi(lineInput.c_str()); // multiply by 8 to scale up cin >> lineInput; temp_point.z = 8 * atoi(lineInput.c_str()); // multiply by 8 to scale up POINTS.push_back(temp_point); count++; } count = 0; // reset counter for input S_FACE temp_face; // temp face for each loop while (count < NUM_FACES) { cin >> lineInput; temp_face.a = atoi(lineInput.c_str()); cin >> lineInput; temp_face.b = atoi(lineInput.c_str()); cin >> lineInput; temp_face.c = atoi(lineInput.c_str()); FACES.push_back(temp_face); count++; } GLInit(&argc, argv); glutMainLoop(); return 0; }
true
a70b99085c011eb48c8b708b3dbefb4f9b569f05
C++
wishihab/KelasAlgoritmaDasar
/ProyekTugasUjian2014/Tugas5.5.cpp
UTF-8
284
2.671875
3
[]
no_license
#include<iostream> #include<conio.h> using namespace std; main(){ int input, bagi, sisa; cout<<"masukkan input : "; cin>>input; cout<<"masukkan pembagi: "; cin>>bagi; sisa = input%bagi; if(sisa==0){ cout<<" "; } else{ cout<<"sisa hasil: "<<sisa; } }
true
e39626fd1c2c9ecf9745883f5d00f8abf9f7d6c4
C++
xardas110/BlackJack
/BlackJack/Math.h
UTF-8
391
3.078125
3
[]
no_license
#pragma once namespace Math { template<typename T> inline T Abs(T val) { val < 0 ? val *= -1 : 0; return val; }; template<typename T> inline T Max(T val1, T val2) { T result; val1 > val2 ? result = val1 : result = val2; return result; } template<typename T> inline T Min(T val1, T val2) { T result; val1 < val2 ? result = val1 : result = val2; return result; } }
true
15912869c488fbcfb34ee1c7435596f503a30240
C++
joseiguti/CursoCppPoo
/CursoCppPoo/Clases/Animal.h
UTF-8
361
2.609375
3
[]
no_license
// // Abstracta.h // CursoCppPoo // // Created by José Ignacio Gutiérrez Guzmán on 4/14/18. // Copyright © 2018 José Ignacio Gutiérrez Guzmán. All rights reserved. // #ifndef Abstracta_h #define Abstracta_h #endif /* Animal_h */ class Animal { public: void /*non-virtual*/ move(void) { std::cout << "This animal moves in some way" << std::endl; } virtual void eat() = 0; };
true
2cf5dc193806b723a052143244c8f2ddad320258
C++
Risgrynsgrot/SDL2OpenGl
/source/Math.h
UTF-8
195
2.65625
3
[]
no_license
namespace Math { template <class T> inline T clamp(T value, T min, T max) { const T t = value < min ? min : value; return t > max ? max : t; } } // namespace Math
true
b9b2f45ab88226445482049f086072b4e8f7b886
C++
KiAlexander/LeetCode_Note
/math/1103_distribute-candies-to-people.cpp
UTF-8
912
2.953125
3
[]
no_license
class Solution { public: vector<int> distributeCandies(int candies, int num_people) { long k=1; while(k*(k+1)/2<=candies) ++k; --k; // 计算出当前糖果最多可以发给多少个人(如果有无限个同学的话 int last = candies - (k+1)*k/2; // 计算出最后一个人需要发给多少个(剩余的那些 vector<int> res(num_people, 0); int diff = num_people; // 等差数列的差 for(int i=0; i<num_people; ++i){ int cnt = k/num_people + (k%num_people>i); // 计算出第i列的等差数列的长度 res[i] = cnt*((cnt-1)*diff+2*(i+1))/2; // 以(i+1)为首项,diff为公差,cnt为数列长度,的等差数列的和 if ( k%num_people== i) // 此情况是最后一个同学,需要把剩下的糖果都发给他 res[i] += last; } return res; } };
true
fd7034e529085d34df6947b439d57548631c85cf
C++
ulinka/tbcnn-attention
/github_cpp/19/14.cpp
UTF-8
946
2.578125
3
[]
no_license
#include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <cstdio> #include <cstdlib> #include <cmath> #include <utility> #include <algorithm> #include <iostream> #include <cstring> #include <vector> #include <cstring> #include <cassert> #include <ctime> #include <stdbool.h> using namespace std; int A[10000]; int parti_tion(int A[],int p,int r) { int x,i,j; x=A[r]; i=p-1; for(j=p;j<=r-1;j++) { if(A[j]<=x) { i=i+1; swap(A[i],A[j]); } } swap(A[i+1],A[j]); return i+1; } int quick_sort(int A[],int p,int r) { int q; if(p<r) { q=parti_tion(A,p,r); quick_sort(A,p,q-1); quick_sort(A,q+1,r); } return 0; } int main() { int p,r,i; cin>>r; for(i=1;i<=r;i++) cin>>A[i]; quick_sort(A,1,r); for(i=1;i<=r;i++) cout<<A[i]<<" "; return 0; }
true
281f861be664cbc79d8769e0dbbc91a7fa0a994a
C++
aoquan/leetcode
/tree/binaryTree1.cpp
UTF-8
3,805
3.5625
4
[]
no_license
#include<iostream> #include<fstream> #include<stack> using namespace std; ifstream ifs("input.txt"); class node{ public: node * l,*r; int val; bool isfirst; node():val(0),l(NULL),r(NULL),isfirst(true){} node(int a):val(a),l(NULL),r(NULL),isfirst(true){} }; class vnode{ public: node * p; int visited; vnode(node * n):p(n),visited(0){} }; class Tree{ public: void create_tree(node *& root){ int a; ifs >>a; if(a==0){ root = NULL; } else{ root = new node(a); create_tree(root->l); create_tree(root->r); } } void pre_order(node * root){ if(root){ cout<<root->val<<" "; pre_order(root->l); pre_order(root->r); } } void mid_order(node * root){ if(root){ mid_order(root->l); cout<<root->val<<" "; mid_order(root->r); } } void after_order(node * root){ if(root){ after_order(root->l); after_order(root->r); cout<<root->val<<" "; } } void pre_order1(node * root){ stack<node *> s; if(root==NULL)return; while(!s.empty()||root){ while(root){ cout<<root->val<<" "; s.push(root); root=root->l; } node *p = s.top(); s.pop(); root=p->r; } } void mid_order1(node * root){ stack<node *> s; if(root==NULL)return; while(!s.empty()||root){ while(root){ s.push(root); root=root->l; } node *p = s.top(); cout<<p->val<<" "; s.pop(); root=p->r; } } void after_order2(node* root){ if(!root) return; stack<node *> s; while(!s.empty()||root){ while(root){ s.push(root); root = root->l; } node * tmp = s.top(); if(tmp->isfirst==true){ tmp->isfirst = false; root = tmp->r; } else{ s.pop(); cout<<tmp->val<<" "; } } } void after_order1(node * root){ if(root==NULL)return; stack<vnode *> s; node *p =root; while(p){ vnode *vp = new vnode(p); s.push(vp); p=p->l; } while(!s.empty()){ vnode *vp=s.top(); if(!(vp->p->r)||vp->visited==1){ cout<<vp->p->val<<" "; s.pop(); } else{ vp->visited =1; p = vp->p->r; while(p){ vnode *vp = new vnode(p); s.push(vp); p=p->l; } } } } }; int main(){ node *root; Tree tree; tree.create_tree(root); tree.pre_order(root); cout<<endl; tree.pre_order1(root); cout<<endl; tree.mid_order(root); cout<<endl; tree.mid_order1(root); cout<<endl; tree.after_order(root); cout<<endl; tree.after_order2(root); cout<<endl; }
true
5c395555bd8b72ec868e16e5db6cd6977df2dad6
C++
pyridine/LAWRENTIAN
/team4/handin/P 2.2/Actual Class Diagrams/lud server/FileSystemI.h
UTF-8
1,497
2.578125
3
[]
no_license
#ifndef FILESYSTEMI_H #define FILESYSTEMI_H #include <Ice/Ice.h> #include "FileSystem.h" class FileSystemI : public FileSystem::File { private: std::string main_dir; bool dirExists(const std::string& dirName_in); std::string extractFileName(const std::string& str); std::string extractNodeName(const std::string str); std::string insertCorrectly(std::string& str, const char* num); std::string getIP(const Ice::Current& c); void consolePrint(const std::string& str); std::string getName(const std::string& ip_address); public: FileSystemI(std::string main_node); FileSystemI(); virtual FileSystem::ByteSeq receiveLatest(const std::string& sec, const std::string& art, const std::string& type, const std::string& fName, const Ice::Current& c); virtual FileSystem::ByteSeq receiveVersion(const std::string& sec, const std::string& art, const std::string& type, const std::string& fName, const int ver, const Ice::Current& c); virtual bool sendFile(const std::string& sec, const std::string& art, const std::string& type, const std::string& fNameExt, const FileSystem::ByteSeq& seq, const Ice::Current& c); virtual FileSystem::VerSeq getHistory(const std::string& sec, const std::string& art, const std::string& type, const std::string& fName, const Ice::Current& c); }; #endif // FILESYSTEMI_H
true
b42e8ac2f8aea0f58a3ee4e6b26e3f71853601c3
C++
luchenqun/leet-code
/problems/632-smallest-range.cpp
UTF-8
1,338
3.640625
4
[]
no_license
/* * [632] Smallest Range * * https://leetcode-cn.com/problems/smallest-range/description/ * https://leetcode.com/problems/smallest-range/discuss/ * * algorithms * Hard (46.51%) * Total Accepted: 20 * Total Submissions: 43 * Testcase Example: '[[4,10,15,24,26],[0,9,12,20],[5,18,22,30]]' * * 你有 k 个升序排列的整数数组。找到一个最小区间,使得 k 个列表中的每个列表至少有一个数包含在其中。 * 我们定义如果 b-a < d-c 或者在 b-a == d-c 时 a < c,则区间 [a,b] 比 [c,d] 小。 * 示例 1: * 输入:[[4,10,15,24,26], [0,9,12,20], [5,18,22,30]] * 输出: [20,24] * 解释: * 列表 1:[4, 10, 15, 24, 26],24 在区间 [20,24] 中。 * 列表 2:[0, 9, 12, 20],20 在区间 [20,24] 中。 * 列表 3:[5, 18, 22, 30],22 在区间 [20,24] 中。 * 注意: * 给定的列表可能包含重复元素,所以在这里升序表示 >= 。 * 1 <= k <= 3500 * -105 <= 元素的值 <= 105 * 对于使用Java的用户,请注意传入类型已修改为List<List<Integer>>。重置代码模板后可以看到这项改动。 */ #include <iostream> #include <string> using namespace std; class Solution { public: vector<int> smallestRange(vector<vector<int>>& nums) { } }; int main() { Solution s; return 0; }
true
513f2affbfc5915168c57ef0748e3a2d9748435f
C++
jpdef/rmon
/src/nwin/nwindow.h
UTF-8
1,625
2.703125
3
[]
no_license
#ifndef __NWINDOW_H_INCLUDED__ #define __NWINDOW_H_INCLUDED__ #define MAXCHAR 256 #include <iostream> #include <fstream> #include <string> #include <vector> #include <typeinfo> extern "C" { #include <ncurses.h> } using namespace std; enum COLOR{red, white, blue}; class Nwindow{ int pos_x, pos_y, MAX_X = 0; int prev_x,prev_y, MAX_Y =0 ; WINDOW* winptr; public: Nwindow(); Nwindow(int len_y, int len_x, int x, int y); //template<typename T,typename U>void move(T y, U x); //template<typename T>void move_over(T x, T y); template<typename T, typename U> void move(T y, U x){ pos_y = int(y)%MAX_Y; pos_x = int(x)%MAX_X; wmove(winptr,pos_y,pos_x); wrefresh(winptr); } template<typename T> void move_over(T dy,T dx){ pos_y += int(dy); pos_x += int(dx); wmove(winptr,pos_y,pos_x); } /* template<typename T> void print_color(T x, COLOR c ) { cout <<"Variable " <<typeid(T).name() << " is not supported" << endl; }*/ void print_color(ifstream& file, COLOR c); void print_color(string str, COLOR c); void print_color(double* da, COLOR c, int startp); void clear(); private: void print_line(string line, COLOR c); void initialize_colors(); void set_bkg_color(COLOR c); void reset_color(COLOR c); void set_color(COLOR c); int get_start(string str); int get_end(string str); }; #endif
true
f33f23c46a03e3f122723106783157515223b941
C++
changsongzhu/leetcode
/C++/per_day/06-27-2017/057_h.cpp
UTF-8
1,735
3.703125
4
[]
no_license
/** 57[H]. Insert Interval Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). You may assume that the intervals were initially sorted according to their start times. Example 1: Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. Example 2: Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. **/ /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { int start=newInterval.start, end=newInterval.end; vector<Interval> res; int inserted=false; for(int i=0;i<intervals.size();i++) { if(inserted==false) { if(intervals[i].start>end) { res.push_back(Interval(start, end)); res.push_back(intervals[i]); inserted=true; } else if(intervals[i].end<start) { res.push_back(intervals[i]); } else { start=min(start, intervals[i].start); end=max(end, intervals[i].end); } } else { res.push_back(intervals[i]); } } if(inserted==false) res.push_back(Interval(start, end)); return res; } };
true
f80bf08a474663869c8a185cd5082bd0a8d27cba
C++
katiaap/katiateste
/prjKatiaTeste/prjKatiaTeste/main.cpp
UTF-8
329
3.234375
3
[]
no_license
#include<iostream> using namespace std; void main () { int val1 = 0, val2 = 0; cout << "\ttabuada" << endl; cout << "\t-------" << endl; cout << "Enter value 1: "; cin >> val1; cout << "Enter value 2: "; cin >> val2; cout << "Multiplication of " << val1 << " x " << val2 << " = " << (val1 * val2) << endl; }
true
5223ea7fe1b62ad6d63603dfe20d6b8ce153d343
C++
kk2491/CPP_Quick_Tour
/Examples/oop_140.cpp
UTF-8
2,160
3.953125
4
[]
no_license
#include <iostream> #include <vector> #include <string> class Account { private: std::string name_; double balance_; public: void SetName(std::string name) { name_ = name; } void SetBalance(double balance) { balance_ = balance; } std::string GetName() { return name_; } double GetBalance() { return balance_; } bool WithDraw(double amount) { if ((balance_ - amount) <= 0) { return false; } else { balance_ = balance_ - amount; return true; } } bool Deposit(double amount) { balance_ = balance_ + amount; return true; } }; int main() { Account normal_account; double normal_balance; normal_account.SetName("Krishna"); normal_account.SetBalance(1000.0); std::cout << "1 Name : " << normal_account.GetName() << " Balance : " << normal_account.GetBalance() << std::endl; if (normal_account.Deposit(1000.0)) { std::cout << "2 Name : " << normal_account.GetName() << " Balance : " << normal_account.GetBalance() << std::endl; } if (normal_account.WithDraw(500.0)) { std::cout << "3 Name : " << normal_account.GetName() << " Balance : " << normal_account.GetBalance() << std::endl; } else { std::cout << "3 Name : " << normal_account.GetName() << " Balance : " << normal_account.GetBalance() << std::endl; } Account *ptr_account = new Account(); ptr_account->SetName("Bannad"); ptr_account->SetBalance(10.0); std::cout << "1 Name : " << ptr_account->GetName() << " Balance : " << ptr_account->GetBalance() << std::endl; if (ptr_account->Deposit(10000)) { std::cout << "2 Name : " << ptr_account->GetName() << " Balance : " << ptr_account->GetBalance() << std::endl; } if (ptr_account->WithDraw(5000)) { std::cout << "3 Name : " << ptr_account->GetName() << " Balance : " << ptr_account->GetBalance() << std::endl; } else { std::cout << "3 Name : " << ptr_account->GetName() << " Balance : " << ptr_account->GetBalance() << std::endl; } return 0; }
true
2b921db2c8532183c52ecdb5b6f4d5998cf2b9d7
C++
XunZhiyang/TTRS
/backend/BplusTree/test.cpp
UTF-8
3,022
2.65625
3
[ "MIT" ]
permissive
#include <iostream> #include <ctime> #include <map> #include "NewBptree.hpp" using std::cout; sjtu::Bptree<int, int, 101, 101> a("train_record"); void QueryTest(); void BigDataTest() { // 300000 with defult pagesize = 5 takes 9.81 seconds // 240000 with pagesize = 4096 takes about 13.06 seconds for (int i = 1; i <= 240000; i++) { a.insert(std::pair<int, int>(i, 2*i)); } cout << "Query information for train id " << 100005 << ": it is " << a.at(100005) << "\n"; //QueryTest(); } void RobustTest() { int TestNum = 10; if (a.size() < TestNum) { for (int i = 3; i <= 3 + TestNum - 1; i++) { a.insert(std::pair<int, int>(i, 2 * i)); } } for (int i = 12; i >= 3; i--) { a.erase(i); a.tranverse(); } //a.erase(70); //a.tranverse(); } void QueryTest() { cout << "Query test start: "; for (int i = 1; i <= 10000; i++) { int id = rand() % (a.size() - 20) + 10; cout << "Query information for train id " << id << ": it is " << a.at(id) << "\n"; } } void RepeatIDTest() { for (int i = 3; i <= 1000; i++) { for (int j = 1; j <= 15; j++) { a.insert(std::pair<int, int>(i, i * j)); } } a.tranverse(); for (int id = 3; id <= 13; id++) { cout << "Query information for train id " << id << ": it is " << a.at(id) << "\n"; } } void Map() { std::map<int, int> aa; for (int i = 3; i <= 13; i++) { for (int j = 1; j <= 5; j++) { aa.insert(std::pair<int, int>(i, i * j)); } } for (int id = 3; id <= 13; id++) { cout << "Query information for train id " << id << ": it is " << aa.at(id) << "\n"; } } void IteratorTest() { auto it = a.begin(); for (; it != a.end(); it++) { cout << "Query information for train id " << it->first << ": it is " << it->second << "\n"; } } void CountTest() { for (int i = 3; i <= 13; i++) { cout << "Count for train id " << i << ": it is " << a.count(i) << "\n"; } } void FileTest() { if (a.size() == 0) { int TestNum = 1000; if (a.size() < TestNum) { for (int i = 3; i <= 3 + TestNum - 1; i++) { a.insert(std::pair<int, int>(i, 2 * i)); } } } else { for (int j = 1; j <= 30; j++) { a.erase(a.size() + 2); for (int i = 3; i <= 3 + a.size() - 1; i++) { auto it = a.find(i); cout << "Query information for train id " << it->first << ": it is " << it->second << "\n"; } } } } int main() { srand(time(NULL)); clock_t start = clock(); //BigDataTest(); //RobustTest(); //RepeatIDTest(); //CountTest(); //IteratorTest(); //QueryTest(); FileTest(); cout << "Current length is " << a.size() << "\n"; clock_t end = clock(); cout << (double) (end - start) / (CLOCKS_PER_SEC) << "\n"; //a.clear(); return 0; }
true
67189a0da751b21cccf1a7df848a8f398cdb2433
C++
Mrhuangyi/leetcode-Solutions
/Cpp/Easy/38. 报数.cpp
UTF-8
998
3.8125
4
[]
no_license
/* 报数序列是指一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下: 1. 1 2. 11 3. 21 4. 1211 5. 111221 1 被读作 "one 1" ("一个一") , 即 11。 11 被读作 "two 1s" ("两个一"), 即 21。 21 被读作 "one 2", "one 1" ("一个二" , "一个一") , 即 1211。 给定一个正整数 n ,输出报数序列的第 n 项。 注意:整数顺序将表示为一个字符串。 示例 1: 输入: 1 输出: "1" 示例 2: 输入: 4 输出: "1211" */ class Solution { public: string countAndSay(int n) { string s("1"); while(--n){ s = getNext(s); } return s; } string getNext(const string &s){ stringstream ss; for(auto i=s.begin();i!=s.end();){ auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i)); ss << distance(i, j) << *i; i = j; } return ss.str(); } };
true
8923db61bd40868ad1041f180ac36fda35c176f9
C++
the-badcoder/Competitive-Programming
/Graph/DFS/DFS.cpp
UTF-8
1,612
3.28125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; /* This Programm Is For Basic DFS \ And It Will Find \ Connect Components Of An Undirected Graph. Practice Problem: UVA 459 --> Graph Connectivity. */ #define DFS_BLACK 1 #define DFS_WHITE 0 typedef vector <int> vi; typedef pair <int, int> ii; typedef vector < ii > vii; const int INF = INT_MAX; const int res = 1e5 + 5; bool color[res]; vi graph[res]; void reset(); void dfs( int u ); int CC; int main() { int nodes, edges, u, v; while( scanf("%d %d", &nodes, &edges) == 2 ) { reset(); /// Reset Everythings. for( int i = 0; i < edges; i++ ) { scanf("%d %d", &u, &v); graph[u].push_back( v ); graph[v].push_back( u ); /// For Undirected Graph. } for( int i = 0; i < nodes; i++ ) { if( color[i] == DFS_WHITE ) { CC++; /// Count Connected Components And Call DFS. dfs( i ); } } printf("%d Connected Components In This Graph.\n", CC ); } return 0; } void dfs( int u ) { color[u] = DFS_BLACK; for( int i = 0; i < graph[u].size(); i++ ) { int v = graph[u][i]; if( color[v] == DFS_WHITE ) { dfs( v ); } } } void reset() { CC = 0; for( int i = 0; i < res; i++ ) { graph[i].clear(); color[i] = DFS_WHITE; } } /* TEST INPUT: \ 9 7 0 1 1 2 1 3 2 3 3 4 7 6 6 8 OUTPUT: 3 Connected Components In This Graph. */
true
288ecf75ccb85aed780da353dca789e4aab05511
C++
rocketeerbkw/DNA
/Main/Source/Ripley/ExtraInfo.cpp
UTF-8
16,950
2.765625
3
[]
no_license
// ExtraInfo.cpp: implementation of the CExtraInfo class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ExtraInfo.h" #include "tdvassert.h" #include "XMLObject.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CExtraInfo::CExtraInfo() : m_pXMLTree(NULL), m_iType(0) { } CExtraInfo::CExtraInfo(int iType) : m_pXMLTree(NULL), m_iType(0) { Create(iType); } CExtraInfo::~CExtraInfo() { Clear(); } /********************************************************************************* void CExtraInfo::Clear() Author: Dharmesh Raithatha Created: 6/26/2003 Inputs: - Outputs: - Returns: - Purpose: Clears the ExtraInfo object *********************************************************************************/ void CExtraInfo::Clear() { delete m_pXMLTree; m_pXMLTree = NULL; m_iType = 0; } /********************************************************************************* bool CExtraInfo::Create(int iType) Author: Nick Stevenson Created: 20/08/2003 Inputs: iType = GuideEntry type id Outputs: Returns: true if successfull false otherwise Purpose: Creates an ExtraInfo object and sets the type child with the XML format<EXTRAINFO><TYPE ID="xx"/></EXTRAINFO> *********************************************************************************/ bool CExtraInfo::Create(int iType) { return Create(iType,"<EXTRAINFO></EXTRAINFO>"); } /********************************************************************************* bool CExtraInfo::Create(int iType, const TDVCHAR* pExtraInfoXML) Author: Dharmesh Raithatha, Nick Stevenson Created: 6/23/2003 Inputs: iType = GuideEntry type id pExtraInfoXML - the extrainfo as xml Outputs: - Returns: true, if successful false otherwise Purpose: creates the extrainfo given the to create it. Ensure that the xml is enclosed by <EXTRAINFO></EXTRAINFO> or it will fail *********************************************************************************/ bool CExtraInfo::Create(int iType, const TDVCHAR* pExtraInfoXML) { if (iType <= 0) { TDVASSERT(false,"CExtraInfo::Create() Type param <= 0"); return false; } Clear(); m_pXMLTree = CXMLTree::Parse(pExtraInfoXML); if (m_pXMLTree != NULL) { CXMLTree* pExtraInfoNode = GetRoot(); // If the root node is found, it must be called <EXTRAINFO> if (pExtraInfoNode != NULL) { RemoveAllInfoItems("TYPE"); CTDVString sTypeXML; BuildTypeTag(iType, sTypeXML); if (AddInfoItems(sTypeXML)) { m_iType = iType; return true; } else { TDVASSERT(false,"CExtraInfo::Create() TYPE tag parse error"); } } else { TDVASSERT(false,"CExtraInfo::Create() root is not <EXTRAINFO>"); } } else { TDVASSERT(false,"CExtraInfo::Create() parse error"); } Clear(); return false; } /********************************************************************************* bool CExtraInfo::AddInfoItems(const TDVCHAR* pInfoItem) Author: Dharmesh Raithatha Created: 6/24/2003 Inputs: pInfoItem - a list of xml items that are to be added to the extra info Outputs: - Returns: true if successfully added false otherwise Purpose: Adds xml to the extra info object. You can put in xml with a root or multiple roots. If the ExtraInfoObject has not been created it will get created first. *********************************************************************************/ bool CExtraInfo::AddInfoItems(const TDVCHAR* pInfoItem) { if (!IsCreated()) { return false; } bool ok = false; CXMLTree* pTree = CXMLTree::Parse(pInfoItem); if (pTree != NULL) { CXMLTree* pInfoItems = pTree->GetDocumentRoot(); if (pInfoItems != NULL) { CXMLTree* pExtraInfoNode = GetRoot(); if (pExtraInfoNode != NULL) { CXMLTree* pNode = pInfoItems; while (pNode != NULL) { CXMLTree* pNext = pNode->GetNextSibling(); pExtraInfoNode->AddChild(pNode->DetachNodeTree()); pNode = pNext; } ok = true; } else { TDVASSERT(false,"CExtraInfo::AddInfoItems: No <EXTRAINFO> tag"); } } else { TDVASSERT(false,"CExtraInfo::AddInfoItems: No document root"); } } else { TDVASSERT(false,"CExtraInfo::AddInfoItems: Parse failed"); } delete pTree; return ok; } /********************************************************************************* bool CExtraInfo::RemoveInfoItem(const TDVCHAR* pInfoItemName) Author: Mark Neves Created: 01/08/2003 Inputs: pInfoItemName = the name of the info item tag Outputs: - Returns: true if one was removed, false otherwise Purpose: Deletes the first tag (and all it's children) with the name provided. *********************************************************************************/ bool CExtraInfo::RemoveInfoItem(const TDVCHAR* pInfoItemName) { CTDVString sInfoItemName(pInfoItemName); if (sInfoItemName.CompareText("EXTRAINFO")) { TDVASSERT(false,"Trying to delete EXTRAINFO tag"); return false; } if (m_pXMLTree != NULL) { CXMLTree* pInfoItem = GetFirstInfoItem(); while (pInfoItem != NULL) { if (pInfoItem->GetName().CompareText(pInfoItemName)) { pInfoItem->DetachNodeTree(); delete pInfoItem; return true; } pInfoItem = pInfoItem->GetNextSibling(); } } return false; } /********************************************************************************* int CExtraInfo::RemoveAllInfoItems(const TDVCHAR* pInfoItemName) Author: Mark Neves Created: 21/11/2003 Inputs: pInfoItemName = the name of the item Outputs: - Returns: the number of items it removed Purpose: Removes all items called pInfoItemName *********************************************************************************/ int CExtraInfo::RemoveAllInfoItems(const TDVCHAR* pInfoItemName) { int n = 0; while (RemoveInfoItem(pInfoItemName)) { n++; } return n; } /********************************************************************************* bool CExtraInfo::ExistsInfoItem(const TDVCHAR* pInfoItemName) Author: Nick Stevenson Created: 12/08/2003 Inputs: pInfoItemName = the name of the info item tag Outputs: - Returns: boolean value stating the existence of the tag Purpose: returns true if tag with the name is found *********************************************************************************/ bool CExtraInfo::ExistsInfoItem(const TDVCHAR* pInfoItemName) { if (m_pXMLTree != NULL) { CXMLTree* pInfoItem = GetFirstInfoItem(); while (pInfoItem != NULL) { if (pInfoItem->GetName().CompareText(pInfoItemName)) { return true; } pInfoItem = pInfoItem->GetNextSibling(); } } return false; } /********************************************************************************* bool CExtraInfo::GetInfoAsXML(CTDVString& sExtraInfoXML, bool bHiddenVersion) const Author: Dharmesh Raithatha Created: 6/24/2003 Inputs: bHiddenVersion = if true, only produce an ExtraInfo object that only contains the type Outputs: sExtraInfoXML Returns: true if string was generated, false otherwise Purpose: Returns the contents of the ExtraInfo as XML *********************************************************************************/ bool CExtraInfo::GetInfoAsXML(CTDVString& sExtraInfoXML, bool bHiddenVersion) const { if (m_pXMLTree == NULL) { return false; } sExtraInfoXML.Empty(); if (bHiddenVersion) { CExtraInfo TempExtraInfo(m_iType); TempExtraInfo.GetInfoAsXML(sExtraInfoXML,false); } else { m_pXMLTree->OutputXMLTree(sExtraInfoXML); } return true; } /********************************************************************************* CExtraInfo& CExtraInfo::operator=(CExtraInfo& ExtraInfo) Author: Dharmesh Raithatha Created: 6/26/2003 Inputs: - Outputs: - Returns: this Purpose: An inefficient = operator as xmltree does not yet have an = operator So this works by getting the xml and then recreating from the XML. *********************************************************************************/ const CExtraInfo& CExtraInfo::operator=(const CExtraInfo& ExtraInfo) { if (!ExtraInfo.IsCreated()) { TDVASSERT(false,"Can't assign when right hand side has not been created"); return *this; } Clear(); CTDVString sExtraInfo; ExtraInfo.GetInfoAsXML(sExtraInfo); Create(ExtraInfo.GetType(),sExtraInfo); return *this; } /********************************************************************************* void CExtraInfo::BuildTypeTag(CTDVString& sTypeTag) const Author: Nick Stevenson Created: 20/08/2003 Inputs: - Outputs: sTypeTag -ref to a string object to be populated with type xml Returns: true Purpose: Builds the ExtraInfo type xml tag and assigns it to string ref *********************************************************************************/ void CExtraInfo::BuildTypeTag(int iType, CTDVString& sTypeTag) const { sTypeTag << "<TYPE ID='" << iType << "'/>"; } /********************************************************************************* bool CExtraInfo::SetType(int iType) Author: Nick Stevenson Created: 20/08/2003 Inputs: iType: expresses guide type id Outputs: - Returns: true or false Purpose: obtains the guide type name for the given type id and calls ExtraInfo (EI) set methods to set the values in the EI object. if no type tag is defined in the EI xml, the tagstring is built and assigned to it *********************************************************************************/ bool CExtraInfo::SetType(int iType) { if (iType <= 0) { TDVASSERT(false,"CExtraInfo::SetType() Type param <= 0"); return false; } if (!IsCreated()) { return false; } // set ExtraInfo instance vars m_iType = iType; //delete exiting type tags if they exists RemoveAllInfoItems("TYPE"); // add the type tag to extrainfo CTDVString sTypeTag; BuildTypeTag(iType, sTypeTag); return AddInfoItems(sTypeTag); } /********************************************************************************* bool CExtraInfo::AddUniqueInfoItem(const TDVCHAR* pTagName, const CTDVString& sXML) Author: Mark Neves Created: 06/08/2003 (moved from CClub on 08/10/2003) Inputs: pTagName = the name of the tag to place the supplied data under sXML = the XML of the tag whose name matches pTagName Outputs: - Returns: - Purpose: Helper function for adding tags. It firstly removes all tags with the same name, if they exist NOTE: If the supplied sText is empty or only contains whitespace, nothing is added *********************************************************************************/ bool CExtraInfo::AddUniqueInfoItem(const TDVCHAR* pTagName, const CTDVString& sXML) { bool bSuccess = false; if (pTagName != NULL) { // Remove existing ones, if there are any RemoveAllInfoItems(pTagName); bSuccess = AddInfoItems(sXML); } return bSuccess; } /********************************************************************************* void CExtraInfo::ReplaceMatchingItems(const CExtraInfo& OtherExtraInfo) Author: Mark Neves Created: 08/10/2003 Inputs: OtherExtraInfo = contains the source tags Outputs: - Returns: - Purpose: Iterates through all the elements in OtherExtraInfo, and adds them to this ExtraInfo object. If the tag already exists in this ExtraInfo, it is replaced. NOTE: This will only work for elements that only contain text. If the elements contain attributes, the attributes will NOT be copied across *********************************************************************************/ void CExtraInfo::ReplaceMatchingItems(const CExtraInfo& OtherExtraInfo) { CTDVString sName, sXML; int i=0; while (OtherExtraInfo.GetElementFromIndex(i++,sName,sXML)) { AddUniqueInfoItem(sName, sXML); } } /********************************************************************************* bool CExtraInfo::GetElementFromIndex(int iIndex, CTDVString& sName, CTDVString& sXML) const Author: Mark Neves Created: 08/10/2003 Inputs: iIndex = index of element you want (0 = first element) Outputs: sName = filled with element name sXML = filled in with element value Returns: true if found, false otherwise Purpose: Gets a specific element. *********************************************************************************/ bool CExtraInfo::GetElementFromIndex(int iIndex, CTDVString& sName, CTDVString& sXML) const { sName.Empty(); sXML.Empty(); if (iIndex < 0) { return false; } bool bOK = false; CXMLTree* pTree = NULL; if (m_pXMLTree != NULL) { pTree = GetRoot(); if (pTree != NULL) { pTree = pTree->GetFirstChild(CXMLTree::T_NODE); } while (iIndex > 0 && pTree != NULL) { pTree = pTree->GetNextSibling(); iIndex--; } } if (pTree != NULL) { sName = pTree->GetName(); pTree->OutputXMLTree(sXML); bOK = true; } return bOK; } /********************************************************************************* CXMLTree* CExtraInfo::GetRoot() const Author: Mark Neves Created: 05/12/2003 Inputs: - Outputs: - Returns: - Purpose: - *********************************************************************************/ CXMLTree* CExtraInfo::GetRoot() const { CXMLTree* pRoot = NULL; if (IsCreated()) { pRoot = m_pXMLTree->GetDocumentRoot(); if (pRoot != NULL) { if (!pRoot->GetName().CompareText("EXTRAINFO")) { TDVASSERT(false,"Root of extrainfo object is NOT EXTRAINFO!"); pRoot = NULL; } } } return pRoot; } /********************************************************************************* CXMLTree* CExtraInfo::GetFirstInfoItem() const Author: Mark Neves Created: 05/12/2003 Inputs: - Outputs: - Returns: - Purpose: - *********************************************************************************/ CXMLTree* CExtraInfo::GetFirstInfoItem() const { CXMLTree* pRoot = GetRoot(); if (pRoot != NULL) { return pRoot->GetFirstChild(); } return NULL; } /********************************************************************************* void CExtraInfo::GenerateAutoDescription(const CTDVString& sText) Author: Mark Neves Created: 06/08/2003 (moved to ExtraInfo on 17/10/2003) Inputs: sText = the auto description text Outputs: extrainfo is updated Returns: - Purpose: Helper function for adding the <AUTODESCRIPTION> tag to extra info. It makes sure the text is not greater than the maximum allowed length. It also escapes any XML in the text. It uses AddToExtraInfo() to do the rest. *********************************************************************************/ void CExtraInfo::GenerateAutoDescription(const CTDVString& sText) { CTDVString sNewText; CXMLObject::CreateSimpleTextLineFromXML(sText,sNewText); if (sNewText.GetLength() >= CExtraInfo::AUTODESCRIPTIONSIZE) { sNewText = sNewText.Left(CExtraInfo::AUTODESCRIPTIONSIZE - 3); sNewText << "..."; } CTDVString sXML; CXMLObject::MakeTag("AUTODESCRIPTION",sNewText,sXML); AddUniqueInfoItem("AUTODESCRIPTION", sXML); } /********************************************************************************* inline bool CExtraInfo::IsCreated() Author: Dharmesh Raithatha Created: 6/24/2003 Inputs: - Outputs: - Returns: true if the object has been created, false otherwise Purpose: returns whether the object has been created or not *********************************************************************************/ bool CExtraInfo::IsCreated() const { return (m_pXMLTree != NULL); } /********************************************************************************* bool CExtraInfo::GetInfoItem(const TDVCHAR* pInfoItemName, CTDVString& sXML) Author: Mark Neves Created: 27/11/2003 Inputs: pInfoItemName = the name of the item Outputs: sXML = the value of the item Returns: - Purpose: It returns the XML tree of the node specified *********************************************************************************/ bool CExtraInfo::GetInfoItem(const TDVCHAR* pInfoItemName, CTDVString& sXML) { sXML.Empty(); if (IsCreated()) { CXMLTree* pInfoItem = GetFirstInfoItem(); while (pInfoItem != NULL) { if (pInfoItem->GetName().CompareText(pInfoItemName)) { pInfoItem->OutputXMLTree(sXML); return true; } pInfoItem = pInfoItem->GetNextSibling(); } } return false; }
true
a37f33d253ff3ed0179accbcf14430e888897f3f
C++
bobstine/lang_C
/regression/observation.test.cc
UTF-8
581
2.921875
3
[]
no_license
// $Id: observation.test.cc,v 1.3 2003/02/09 20:03:13 bob Exp $ #include "observation.h" int main (void) { std::cout << "Enter the data to record in an observation as wt x1 x2 x3...: " << std::endl; Observation obs1(std::cin); std::cout << obs1 << std::endl; std::cout << "Enter the data to record: " << std::endl; Observation obs2; std::cin >> obs2; std::cout << obs2 << std::endl; std::cout << "Appending values to last observation " << std::endl; obs2.append_value (7.7); obs2.append_value (-7.7); std::cout << obs2 << std::endl; return 0; }
true
f786306ddce5e940dd333511996c18803f623918
C++
spalduing/CPP-for-Beginners
/CPP_Beginners_Course/Pointers_and_Arrays/main.cpp
UTF-8
1,982
4.25
4
[]
no_license
#include <iostream> using namespace std; int main() { string texts[] = {"one", "two", "three"}; string *pTexts = texts; int s = sizeof(texts)/sizeof(string); cout <<"There are " << s <<" elements in the array"<< endl; cout << endl<< endl; cout<<"Iterating by index"<<endl; cout<<"==================="<<endl; for(int i=0; i<s; i++){ cout<< texts[i] << " "<< flush; } cout<< endl<< endl; cout<<"Iterating by pointer"<<endl; cout<<"==================="<<endl; for(int i=0; i<s; i++){ cout<< pTexts[i] << " "<< flush; } cout<< endl<< endl; cout<<"Accessing to the first element by a pointer"<<endl; cout<<"============================================="<<endl; cout<< *pTexts<< endl; cout<< endl<< endl; cout<<"Another way to iterating by a pointer"<<endl; cout<<"============================================="<<endl; for(int i=0; i<s; i++, pTexts++){ cout<< *pTexts << " "<< flush; } cout<< endl<< endl; cout<<"Another way to iterating using two pointers in a for_loop"<<endl; cout<<"============================================="<<endl; string *pEnd = &texts[2]; for(string *pElement = texts; pElement<=pEnd; pElement++){ cout<< *pElement << " "<< flush; } cout<< endl<< endl; cout<<"Another way to iterating using two pointers in a while_loop"<<endl; cout<<"============================================="<<endl; string *pElement = texts; while(pElement <= pEnd){ cout<<*pElement<<" "<< flush; pElement++; } // Resetting pElement to it's initial position. pElement = texts; cout<< endl<< endl; cout<<"Another way to iterating using two pointers in a while_loop"<<endl; cout<<"============================================="<<endl; while(true){ cout<<*pElement<<" "<< flush; if(pElement == pEnd){break;} pElement++; } return 0; }
true
95ad6a1316bfd7599b775c42d616bcbecc8b3154
C++
nagyistoce/saving-face
/ saving-face --username 1900Geek@gmail.com/SavingFaceW32GUI/SavingFaceW32GUI.cpp
UTF-8
11,681
2.625
3
[]
no_license
// SavingFaceW32GUI.cpp : Defines the entry point for the application. // #include <windows.h> #include <stdlib.h> #include <malloc.h> #include <memory.h> #include <tchar.h> #include "SavingFaceW32GUI.h" #include "GlobalVars.h" #include "AddUser.h" #define MAX_LOADSTRING 100 // Global Variables: HINSTANCE hInst; // current instance TCHAR szTitle[MAX_LOADSTRING]; // The title bar text TCHAR szWindowClass[MAX_LOADSTRING]; // the main window class name // Forward declarations of functions included in this code module: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); //ComboBoxItems const char *SalutationItems[] = { "Dr.", "Sir", "Mr.", "Mrs.", "Ms." }; const char *SuffixItems[] = {"Sr.", "Jr.", "I", "II", "III", "IV", "V" }; const char *GenderItems[] = {"Female","Male","Not Given"}; int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: Place code here. MSG msg; HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_SAVINGFACEW32GUI, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // Perform application initialization: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_SAVINGFACEW32GUI)); // Main message loop: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // FUNCTION: MyRegisterClass() // // PURPOSE: Registers the window class. // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_SAVINGFACEW32GUI)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_SAVINGFACEW32GUI); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SAVINGFACEW32GUI)); return RegisterClassEx(&wcex); } // // FUNCTION: InitInstance(HINSTANCE, int) // // PURPOSE: Saves instance handle and creates main window // // COMMENTS: // // In this function, we save the instance handle in a global variable and // create and display the main program window. // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { savingFace = new sf_controller(); savingFace->init(); HWND hWnd; hInst = hInstance; // Store instance handle in our global variable hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // // WM_COMMAND - process the application menu // WM_PAINT - Paint the main window // WM_DESTROY - post a quit message and return // // HWND SubDlgHwnd; LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(SF_ABOUT_DIALOG), hWnd, About); break; case ID_FILE_LOADDATABASE: if (savingFace->loadDatabase() == SF_STS_OK) { MessageBox(hWnd, LPCSTR("Database has successfully been loaded."), LPCSTR("Load Database Dialog"), MB_OK); } else { MessageBox(hWnd, LPCSTR("Error loading database."), LPCSTR("Load Database Dialog"), MB_OK); } break; case ID_FILE_SAVEDATABASE: if (savingFace->saveDatabase() == SF_STS_OK) { MessageBox(hWnd, LPCSTR("Database has successfully been saved."), LPCSTR("Save Database Dialog"), MB_OK); } else { MessageBox(hWnd, LPCSTR("Error saving database."), LPCSTR("Save Database Dialog"), MB_OK); } break; case IDM_EXIT: DestroyWindow(hWnd); break; case ID_ACTIONS_CREATEANEWMODEL: DialogBox(hInst, MAKEINTRESOURCE(UDI_DIALOG2), hWnd, UDI_CALLBACK); break; case ID_ACTIONS_I: DialogBox(hInst, MAKEINTRESOURCE(UDI_DIALOG4), hWnd, UDI_IDENTIFY_CALLBACK); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); // TODO: Add any drawing code here... EndPaint(hWnd, &ps); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // Message handler for about box. INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } void createUserWindow() { } INT_PTR CALLBACK UDI_CALLBACK(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: //Init Combo boxes here if ( -1 == SendMessage(GetDlgItem(hDlg, UDI_SALUTATION_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SalutationItems[0]))) { MessageBox(hDlg, LPCSTR("Failed to add item to combo box."), LPCSTR("Adding Person Dialog"), MB_OK); } SendMessage(GetDlgItem(hDlg, UDI_SALUTATION_CB), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)SalutationItems[1])); SendMessage(GetDlgItem(hDlg, UDI_SALUTATION_CB), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)SalutationItems[2])); SendMessage(GetDlgItem(hDlg, UDI_SALUTATION_CB), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)SalutationItems[3])); SendMessage(GetDlgItem(hDlg, UDI_SALUTATION_CB), CB_ADDSTRING, 0, reinterpret_cast<LPARAM>((LPCTSTR)SalutationItems[4])); if ( -1 == SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[0]))) { MessageBox(hDlg, LPCSTR("Failed to add item to combo box."), LPCSTR("Adding Person Dialog"), MB_OK); } SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[1])); SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[2])); SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[3])); SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[4])); SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[5])); SendMessage(GetDlgItem(hDlg, UDI_SUFFIX_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)SuffixItems[6])); if ( -1 == SendMessage(GetDlgItem(hDlg, UDI_GENDER_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)GenderItems[0]))) { MessageBox(hDlg, LPCSTR("Failed to add item to combo box."), LPCSTR("Adding Person Dialog"), MB_OK); } SendMessage(GetDlgItem(hDlg, UDI_GENDER_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)GenderItems[1])); SendMessage(GetDlgItem(hDlg, UDI_GENDER_CB), CB_ADDSTRING , 0, reinterpret_cast<LPARAM>((LPCTSTR)GenderItems[2])); return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == UDI_OK) { char* sal = new char[200]; char* first = new char[200]; char* middle = new char[200]; char* last = new char[200]; char* suffix = new char[200]; char* gender = new char[200]; char* email = new char[200]; GetWindowText(GetDlgItem(hDlg, UDI_SALUTATION_CB),sal,200); GetWindowText(GetDlgItem(hDlg, UDI_FIRST_ET),first,200); GetWindowText(GetDlgItem(hDlg, UDI_MIDDLE_ET),middle,200); GetWindowText(GetDlgItem(hDlg, UDI_LAST_ET),last,200); GetWindowText(GetDlgItem(hDlg, UDI_SUFFIX_CB),suffix,200); GetWindowText(GetDlgItem(hDlg, UDI_GENDER_CB),gender,200); GetWindowText(GetDlgItem(hDlg, UDI_EMAIL_ET),email,200); //Check to see if user has entered first and last name if(strlen(first) < 1 || strlen(last) < 1) { MessageBox(hDlg, LPCSTR("You must enter at least a first and last name."), LPCSTR("Adding Person Dialog"), MB_OK); break; } else { currentModelID = savingFace->createModel(sal,first,middle,last,suffix,gender,email); if(currentModelID) { EndDialog(hDlg, LOWORD(wParam)); DialogBox(hInst, MAKEINTRESOURCE(UDI_DIALOG3), hDlg, IDD_PHOTO_CALLBACK); return (INT_PTR)TRUE; }else{ MessageBox(hDlg, LPCSTR("An error occured."), LPCSTR("Adding Person Dialog"), MB_OK); break; } } } if(LOWORD(wParam) == UDI_CANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; } INT_PTR CALLBACK UDI_IDENTIFY_CALLBACK(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; //send the callback function to controller here? case WM_COMMAND: if (LOWORD(wParam) == UDI_OK3) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } else if (LOWORD(wParam) == IDC_REIDENTIFY) { //reidentify code } break; } return (INT_PTR)FALSE; } INT_PTR CALLBACK IDD_PHOTO_CALLBACK(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: //savingFace->takeSnapshot(currentModelID); return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == UDI_OK2) { //TODO: Verify picture was taken. EndDialog(hDlg, LOWORD(wParam)); //Verify correct functioning. MessageBox(hDlg, LPCSTR("Building model."), LPCSTR("Capture Dialog"), MB_OK); if (savingFace->buildModel(currentModelID) == SF_STS_OK) { MessageBox(hDlg, LPCSTR("Model has been built."), LPCSTR("Capture Dialog"), MB_OK); } else { MessageBox(hDlg, LPCSTR("An error has occured building the model."), LPCSTR("Capture Dialog"), MB_OK); } return (INT_PTR)TRUE; }else if(LOWORD(wParam) == UDI_CAPTURE) { //take photo and load it to the image window savingFace->takeSnapshot(currentModelID); string file = savingFace->getSnapshotPath(currentModelID); HBITMAP hImage = (HBITMAP)LoadImage(NULL, LPCSTR(file.c_str()), IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); SendMessage(GetDlgItem(hDlg, UDI_PC),STM_SETIMAGE,IMAGE_BITMAP,(LPARAM)hImage); RedrawWindow(hDlg,0,0,0); return (INT_PTR)TRUE; } default: return false; } }
true
b1696e504e5e82f70c3f4ffea9f860989844e715
C++
fanzhaoyun/LeetCode
/RemoveNthNodeFromEndofList.cpp
GB18030
604
3.265625
3
[]
no_license
#include"leetCode.h" /* İ취ʵڵһܵʱһָ룬ͿֱӴӺǰҡʱ临Ӷһ */ ListNode* Solution::removeNthFromEnd(ListNode* head, int n) { if (head == nullptr) return head; ListNode* temp = head; int total = 1; while (temp->next) { temp = temp->next; total++; } if (total == n) { return head->next; } total -= n; //ʵλӦټ1 total--; temp = head; while (total > 0) { total--; temp = temp->next; } temp->next = temp->next->next; return head; }
true
258eb04ec6c860f82a7de7b68cae6d49b6f02adf
C++
PegasusScourge/DarkSun
/src/ApplicationSettings.hpp
UTF-8
1,427
2.890625
3
[]
no_license
#pragma once /** File: ApplicationSettings.hpp Description: Stores settings for the application in a central place Thread safed */ #include "LuaEngine.hpp" #include <atomic> using string = std::string; namespace darksun { class ApplicationSettings { public: ApplicationSettings(string settingsFile); std::atomic<float> opengl_nearZ = 0.1f; std::atomic<float> opengl_farZ = 2000.0f; bool get_opengl_vsync() { return opengl_vsync.load(); } void set_opengl_vsync(bool v) { opengl_vsync = v; } int get_opengl_depthBits() { return opengl_depthBits.load(); } int get_opengl_stencilBits() { return opengl_stencilBits.load(); } int get_opengl_antialiasingLevel() { return opengl_antialiasingLevel.load(); } int get_opengl_majorVersion() { return opengl_majorVersion.load(); } int get_opengl_minorVersion() { return opengl_minorVersion.load(); } int get_opengl_framerateLimit() { return opengl_framerateLimit.load(); } void set_opengl_framerateLimit(int v) { opengl_framerateLimit = v; } private: std::atomic<int> opengl_depthBits; std::atomic<int> opengl_stencilBits; std::atomic<int> opengl_antialiasingLevel; std::atomic<int> opengl_majorVersion; std::atomic<int> opengl_minorVersion; std::atomic<bool> opengl_vsync = false; std::atomic<int> opengl_framerateLimit = 200; LuaEngine engine; void loadSettings(string file); }; }
true
ee7a8f7f57d8d8a6b3dbbd08a15317be11019880
C++
sidgupta234/Interview-Questions-Wiki
/Strings/longestComPrefix.cpp
UTF-8
437
3.34375
3
[]
no_license
// https://www.interviewbit.com/problems/longest-common-prefix/ string longestCPrefix(string a, string b){ string ans=""; for(int i=0,j=0;i<a.length() && j<b.length() &&a[i]==b[j];i++,j++){ ans+=a[i]; } return ans; } string Solution::longestCommonPrefix(vector<string> &A) { string ans=A[0]; for(int i=1;i<A.size();i++){ ans=longestCPrefix(ans,A[i]); } return ans; }
true
9449b373aad3546777573409eac17449c7ddc6be
C++
futuramagica/alchemy
/thirdparty/Softkinetic/include/iisu/Foundation/Services/Commands/Command.h
UTF-8
106,255
2.59375
3
[]
no_license
#pragma once #include <Framework/Types/RefTypeTrait.h> #include <Foundation/Services/Types/RawData.h> #include <Foundation/Services/Types/FunctionTypeInfo.h> #include <Foundation/DataTypes/MetaInformation/MetaInfoImpl.h> namespace SK { class CommandManager ; /** * \brief Interface of a generic Command. */ class ICommand { public: /** * \fn virtual const char* ICommand::getName() const = 0; * * \brief Gets the command name. * * \return The command name */ virtual const char* getName() const = 0; /** * \fn virtual SK::Return<SK::Attributes> ICommand::getAttributes() const =0; * * \brief Gets the commant attributes field. * * \return The attributes, if successful */ virtual SK::Return<SK::Attributes> getAttributes() const =0; /** * \fn virtual SK::Return<bool> ICommand::isValid()const =0; * * \brief returns true if the command handle is valid * * \return true if the command pointer is valid */ virtual SK::Return<bool> isValid()const =0; }; /** * \class CommandBase * * \brief Base template interface for command handle. */ template <typename T> class CommandBase : public ICommand { public: /** * \fn virtual SK::Return< SK::MetaInfo<T> > CommandBase::getMetaInfo() const = 0; * * \brief Gets the command's meta information. * * \return The meta information. */ virtual SK::Return< SK::MetaInfo<T> > getMetaInfo() const = 0; }; namespace ReturnValue { /** * \enum Attribute * * \brief Values that represent Command call return behaviors. */ enum Attribute { IMMEDIATE, DROP, DELAY }; } /** * \class Command * * \brief Command handles specialized interface. (internal use) */ template<typename R = void()> class Command; //! \cond COMMANDS template<typename R> class Command<R()> : public CommandBase<R()> { public: virtual SK::Return<R> operator()(SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1> class Command<R(P1)> : public CommandBase<R(P1)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2> class Command<R(P1, P2)> : public CommandBase<R(P1, P2)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3> class Command<R(P1, P2, P3)> : public CommandBase<R(P1, P2, P3)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4> class Command<R(P1, P2, P3, P4)> : public CommandBase<R(P1, P2, P3, P4)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5> class Command<R(P1, P2, P3, P4, P5)> : public CommandBase<R(P1, P2, P3, P4, P5)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class Command<R(P1, P2, P3, P4, P5, P6)> : public CommandBase<R(P1, P2, P3, P4, P5, P6)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class Command<R(P1, P2, P3, P4, P5, P6, P7)> : public CommandBase<R(P1, P2, P3, P4, P5, P6, P7)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class Command<R(P1, P2, P3, P4, P5, P6, P7, P8)> : public CommandBase<R(P1, P2, P3, P4, P5, P6, P7, P8)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class Command<R(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public CommandBase<R(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; //! \endcond //! \cond COMMANDS_VOID template<> class Command<void()> : public CommandBase<void()> { public: virtual SK::Result operator()() const = 0; }; template<typename P1> class Command<void(P1)> : public CommandBase<void(P1)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1) const = 0; }; template<typename P1, typename P2> class Command<void(P1, P2)> : public CommandBase<void(P1, P2)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2) const = 0; }; template<typename P1, typename P2, typename P3> class Command<void(P1, P2, P3)> : public CommandBase<void(P1, P2, P3)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3) const = 0; }; template<typename P1, typename P2, typename P3, typename P4> class Command<void(P1, P2, P3, P4)> : public CommandBase<void(P1, P2, P3, P4)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4) const = 0; }; template<typename P1, typename P2, typename P3, typename P4, typename P5> class Command<void(P1, P2, P3, P4, P5)> : public CommandBase<void(P1, P2, P3, P4, P5)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5) const = 0; }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class Command<void(P1, P2, P3, P4, P5, P6)> : public CommandBase<void(P1, P2, P3, P4, P5, P6)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6) const = 0; }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class Command<void(P1, P2, P3, P4, P5, P6, P7)> : public CommandBase<void(P1, P2, P3, P4, P5, P6, P7)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7) const = 0; }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class Command<void(P1, P2, P3, P4, P5, P6, P7, P8)> : public CommandBase<void(P1, P2, P3, P4, P5, P6, P7, P8)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8) const = 0; }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class Command<void(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public CommandBase<void(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { public: virtual SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9) const = 0; }; //! \endcond //! \cond COMMANDS_RETURN template<typename R> class Command<SK::Return<R>()> : public CommandBase<SK::Return<R>()> { public: virtual SK::Return<R> operator()(SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1> class Command<SK::Return<R>(P1)> : public CommandBase<SK::Return<R>(P1)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2> class Command<SK::Return<R>(P1, P2)> : public CommandBase<SK::Return<R>(P1, P2)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3> class Command<SK::Return<R>(P1, P2, P3)> : public CommandBase<SK::Return<R>(P1, P2, P3)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4> class Command<SK::Return<R>(P1, P2, P3, P4)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5> class Command<SK::Return<R>(P1, P2, P3, P4, P5)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4, P5)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class Command<SK::Return<R>(P1, P2, P3, P4, P5, P6)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4, P5, P6)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class Command<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class Command<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class Command<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public CommandBase<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { public: virtual SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const = 0; virtual SK::Return<R> waitForReturnValue(int32_t timeout)const = 0; virtual SK::Return<bool> isReturnValueReady() const = 0; virtual SK::Return<R> tryGetReturnValue() const = 0; }; //! \endcond //! \cond COMMAN_MANAGER_PROXY class IISUSDK_API CommandManagerProxy { public: CommandManagerProxy(SK::CommandManager &commandManager) ; CommandManagerProxy() ; ~CommandManagerProxy() ; SK::Result sendCommand(const SK::String& sCmd, const SK::Array<SK::RawData>& params, const SK::FunctionTypeInfo& typeInfo, uint64_t& commandCallerID, bool dropReturn = false) ; SK::Result waitForReturnValue(uint64_t& commandCallerID, SK::RawData &returnValue, int32_t timeout = 0) ; SK::Return<bool> isReturnValueReady(uint64_t commandCallerID) ; SK::Result tryGetReturnValue(uint64_t& commandCallerID, SK::RawData& returnValue) ; bool isValid()const; SK::Return<bool> commandIsRegistered(const SK::String& name) const; virtual SK::Return<SK::Attributes> getAttributes(const SK::String& commandName)const; template<typename T> SK::Return< SK::MetaInfo<T> > getMetaInfo(const SK::String& commandName)const { SK::Return<SK::RawData> res = getMetaInfoImpl(commandName, SK::Type< SK::MetaInfo<T> >::INFO); RETURN_IF_FAILED(res) ; return res.get().getRef< SK::MetaInfo<T> >(); } private: virtual SK::Return<SK::RawData> getMetaInfoImpl(const SK::String& commandName, const SK::TypeInfo& typeInfo)const; SK::CommandManager *m_commandManager ; } ; //! \endcond /** * \class ICommandHandle * * \brief Implementation of Command's non function template specific functions. (internal use) */ template <typename T> class ICommandHandle : public Command<T> { protected: ICommandHandle(SK::CommandManager &pCommandManager, const char* name): m_proxy(pCommandManager), m_name(name?name:""), m_typeInfo(SK::FunctionType<T>::INFO), m_id(0) { } ICommandHandle(): m_name(""), m_typeInfo(SK::FunctionType<T>::INFO), m_id(0) { } virtual ~ICommandHandle() {} public: virtual const char* getName() const {return m_name.ptr ();} virtual SK::Return<SK::Attributes> getAttributes() const { return m_proxy.getAttributes(m_name); } virtual SK::Return< SK::MetaInfo<T> > getMetaInfo() const { return m_proxy.getMetaInfo<T>(m_name); } virtual SK::Return<bool> isValid()const { if(!m_proxy.isValid()) return false; return m_proxy.commandIsRegistered(m_name); } protected: SK::Result sendCommand(const SK::Array<SK::RawData>& params, bool dropReturn) const { if(!m_proxy.isValid()) return SK::Result("Command is not properly registered", SK::INVALID_HANDLE); return m_proxy.sendCommand(m_name, params, m_typeInfo, m_id, dropReturn); } SK::Result waitForReturnValue(SK::RawData &returnValue, int32_t timeout = 0)const { if(!m_proxy.isValid()) return SK::Result("Command is not properly registered", SK::INVALID_HANDLE); return m_proxy.waitForReturnValue(m_id, returnValue, timeout); } SK::Return<bool> isReturnValueReady()const { if(!m_proxy.isValid()) return SK::Result("Command is not properly registered", SK::INVALID_HANDLE); return m_proxy.isReturnValueReady(m_id); } SK::Result tryGetReturnValue(SK::RawData &returnValue)const { if(!m_proxy.isValid()) return SK::Result("Command is not properly registered", SK::INVALID_HANDLE); return m_proxy.tryGetReturnValue(m_id, returnValue); } public: ICommandHandle(const ICommandHandle& other): m_name(other.m_name), m_typeInfo(other.m_typeInfo), m_id(0), m_proxy(other.m_proxy) { } protected: virtual void swap(ICommandHandle& other) { std::swap(m_name, other.m_name); std::swap(m_typeInfo, other.m_typeInfo); std::swap(m_id, other.m_id); std::swap(m_proxy, other.m_proxy); } protected: SK::String m_name; SK::FunctionTypeInfo m_typeInfo; mutable uint64_t m_id; mutable CommandManagerProxy m_proxy ; }; template<typename R = void()> class CommandHandle; //! \cond COMMAND_HANDLES template<typename R> class CommandHandle<R()> : public ICommandHandle<R()> { typedef ICommandHandle<R()> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path) {} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1> class CommandHandle<R(P1)> : public ICommandHandle<R(P1)> { typedef ICommandHandle<R(P1)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>();// SK::RawDataConverter<R>(rd).convert(true); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>();//SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2> class CommandHandle<R(P1, P2)> : public ICommandHandle<R(P1, P2)> { typedef ICommandHandle<R(P1, P2)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3> class CommandHandle<R(P1, P2, P3)> : public ICommandHandle<R(P1, P2, P3)> { typedef ICommandHandle<R(P1, P2, P3)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4> class CommandHandle<R(P1, P2, P3, P4)> : public ICommandHandle<R(P1, P2, P3, P4)> { typedef ICommandHandle<R(P1, P2, P3, P4)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5> class CommandHandle<R(P1, P2, P3, P4, P5)> : public ICommandHandle<R(P1, P2, P3, P4, P5)> { typedef ICommandHandle<R(P1, P2, P3, P4, P5)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class CommandHandle<R(P1, P2, P3, P4, P5, P6)> : public ICommandHandle<R(P1, P2, P3, P4, P5, P6)> { typedef ICommandHandle<R(P1, P2, P3, P4, P5, P6)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class CommandHandle<R(P1, P2, P3, P4, P5, P6, P7)> : public ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7)> { typedef ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class CommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8)> : public ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8)> { typedef ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; //! \endcond /** * * \brief The CommandHandle class provides access to direct calls to specific functions of iisu. * * * * \tparam R Type of the return value. * \tparam P1 Type of the first parameter. * \tparam P2 Type of the second parameter. * \tparam P3 Type of the third parameter. * \tparam P4 Type of the fourth parameter. * \tparam P5 Type of the fifth parameter. * \tparam P6 Type of the sixth parameter. * \tparam P7 Type of the seventh parameter. * \tparam P8 Type of the eighth parameter. * \tparam P9 Type of the ninth parameter. * * * * The CommandHandle acts as a function object and, to use it, you need only to call the its () operator. <br/> * This class is a specialization with a return type and 9 arguments. The number of arguments can vary from zero to nine.<br/> * Only this specialization with 9 parameters is documented, the other specializations aren't but their documentation is very similar to this one. */ template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class CommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { typedef ICommandHandle<R(P1, P2, P3, P4, P5, P6, P7, P8, P9)> base_t; public: /** * \brief Constructor. * * \param [in,out] pCommandManager the CommandManager. * \param path iisu path of the command (syntax : "LAYER.SUBPATH.CommandName"). */ CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} /** * * \brief Default constructor. */ CommandHandle():base_t() {} /** * * \brief Destructor. */ virtual ~CommandHandle() {} /** * * \brief Copy constructor. * * \param other The other. */ CommandHandle(const CommandHandle& other):base_t(other) {} /** * * \brief Assignment operator. * * \param other The other. * * \return A shallow copy of this object. */ CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } /** * * \brief Call operator. * * \param p1 The first parameter. * \param p2 The second parameter. * \param p3 The third parameter. * \param p4 The fourth parameter. * \param p5 The fifth parameter. * \param p6 The sixth parameter. * \param p7 The seventh parameter. * \param p8 The eighth parameter. * \param p9 The ninth parameter. * \param returnBehavior if set to IMMEDIATE, the call to the function is made directly and waits to return a SK::Return<R> containing the return value.<br/> * if set to DELAY, the call returns immediately a SK::Result (no return value). The availability of the real return value can then be obtained by calling waitForReturnValue and the real value can be obtained by calling tryGetReturnValue()<br/> * if set to DROP, tells the command to just ignore the return value. The call returns immediately. * * \return A Return<R> object containing return value (if returnBehavior is set to IMMEDIATE) or error code * * If R is of the for SK::Return<X> the the return type should be SK::Return<SK::Return<X>>, to avoid the * burden to check for both of the Return the api merge those two Return. So that if R is SK::Return<X> then * SK::Return<R> is Return<X>. * \sa tryGetReturnValue * \sa isReturnValueReady */ SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO));params.pushBack(SK::RawData(p9, SK::Type<P9>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } /** * * \brief Waits for the command call to be completed before returning its return value. * * \param timeout (optional) the timeout. * * \return A Return<R> object containing the return value of the command call. * * If R is of the for SK::Return<X> the the return type should be SK::Return<SK::Return<X>>, to avoid the * burden to check for both of the Return the api merge those two Return. So that if R is SK::Return<X> then * SK::Return<R> is Return<X>. */ SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } /** * \brief Checks if the return value of a DELAY call is ready. * * \return The result of the query. */ SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} /** * \brief Tries to get the return value of a DELAY call, If it's not yet ready, return an error * * \return A Return<R> object containing either the return value of the command call, or an error message. * * If R is of the for SK::Return<X> the the return type should be SK::Return<SK::Return<X>>, to avoid the * burden to check for both of the Return the api merge those two Return. So that if R is SK::Return<X> then * SK::Return<R> is Return<X>. */ SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type<R>::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy<R>(); //SK::RawDataConverter<R>(rd).convert(); } }; //! \cond COMMAND_HANDLES_VOID template<> class CommandHandle<void()> : public ICommandHandle<void()> { typedef ICommandHandle<void()> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path) {} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()() const { SK::Array<RawData> params; return base_t::sendCommand(params, true); } }; template<typename P1> class CommandHandle<void(P1)> : public ICommandHandle<void(P1)> { typedef ICommandHandle<void(P1)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2> class CommandHandle<void(P1, P2)> : public ICommandHandle<void(P1, P2)> { typedef ICommandHandle<void(P1, P2)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3> class CommandHandle<void(P1, P2, P3)> : public ICommandHandle<void(P1, P2, P3)> { typedef ICommandHandle<void(P1, P2, P3)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3, typename P4> class CommandHandle<void(P1, P2, P3, P4)> : public ICommandHandle<void(P1, P2, P3, P4)> { typedef ICommandHandle<void(P1, P2, P3, P4)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5> class CommandHandle<void(P1, P2, P3, P4, P5)> : public ICommandHandle<void(P1, P2, P3, P4, P5)> { typedef ICommandHandle<void(P1, P2, P3, P4, P5)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class CommandHandle<void(P1, P2, P3, P4, P5, P6)> : public ICommandHandle<void(P1, P2, P3, P4, P5, P6)> { typedef ICommandHandle<void(P1, P2, P3, P4, P5, P6)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class CommandHandle<void(P1, P2, P3, P4, P5, P6, P7)> : public ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7)> { typedef ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO)); return base_t::sendCommand(params, true); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class CommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8)> : public ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8)> { typedef ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO)); return base_t::sendCommand(params, true); } }; //! \endcond /** * * \brief The CommandHandle class provides access to direct calls to specific functions of iisu with no return type. * * * * \tparam P1 Type of the first parameter. * \tparam P2 Type of the second parameter. * \tparam P3 Type of the third parameter. * \tparam P4 Type of the fourth parameter. * \tparam P5 Type of the fifth parameter. * \tparam P6 Type of the sixth parameter. * \tparam P7 Type of the seventh parameter. * \tparam P8 Type of the eighth parameter. * \tparam P9 Type of the ninth parameter. * * * * The CommandHandle acts as a function object and, to use it, you need only to call the its () operator. <br/> * This class is a specialization with a return type and 9 arguments. The number of arguments can vary from zero to nine.<br/> * Only this specialization with 9 parameters is documented, the other specializations aren't but their documentation is very similar to this one. */ template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class CommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { typedef ICommandHandle<void(P1, P2, P3, P4, P5, P6, P7, P8, P9)> base_t; public: /** * \brief Constructor. * * \param [in,out] pCommandManager the CommandManager. * \param path iisu path of the command (syntax : "LAYER.SUBPATH.CommandName"). */ CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} /** * * \brief Default constructor. */ CommandHandle():base_t() {} /** * * \brief Destructor. */ virtual ~CommandHandle() {} /** * * \brief Copy constructor. * * \param other The other. */ CommandHandle(const CommandHandle& other):base_t(other) {} /** * * \brief Assignment operator. * * \param other The other. * * \return A shallow copy of this object. */ CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } /** * * \brief Call operator. * * \param p1 The first parameter. * \param p2 The second parameter. * \param p3 The third parameter. * \param p4 The fourth parameter. * \param p5 The fifth parameter. * \param p6 The sixth parameter. * \param p7 The seventh parameter. * \param p8 The eighth parameter. * \param p9 The ninth parameter. * * \return A Result object containing error code related to the command call. * * The Result returned by this call is not related to the command itself (since the command signature is void) * but to the command call that can potentially fail. */ SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO));params.pushBack(SK::RawData(p9, SK::Type<P9>::INFO)); return base_t::sendCommand(params, true); } }; //! \cond COMMAND_HANDLES_RETURN template<typename R> class CommandHandle<SK::Return<R>()> : public ICommandHandle<SK::Return<R>()> { typedef ICommandHandle<SK::Return<R>()> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path) {} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1> class CommandHandle<SK::Return<R>(P1)> : public ICommandHandle<SK::Return<R>(P1)> { typedef ICommandHandle<SK::Return<R>(P1)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2> class CommandHandle<SK::Return<R>(P1, P2)> : public ICommandHandle<SK::Return<R>(P1, P2)> { typedef ICommandHandle<SK::Return<R>(P1, P2)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3> class CommandHandle<SK::Return<R>(P1, P2, P3)> : public ICommandHandle<SK::Return<R>(P1, P2, P3)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4> class CommandHandle<SK::Return<R>(P1, P2, P3, P4)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5> class CommandHandle<SK::Return<R>(P1, P2, P3, P4, P5)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class CommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class CommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class CommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; template<typename R, typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class CommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { typedef ICommandHandle<SK::Return<R>(P1, P2, P3, P4, P5, P6, P7, P8, P9)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Return<R> operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO));params.pushBack(SK::RawData(p9, SK::Type<P9>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Return<R> waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Return<R> tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Return<R> >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getCopy< SK::Return<R> >(); //SK::RawDataConverter< SK::Return<R> >(rd).convert(); } }; //! \endcond //! \cond COMMAND_HANDLES_RESULT template<> class CommandHandle<SK::Result()> : public ICommandHandle<SK::Result()> { typedef ICommandHandle<SK::Result()> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path) {} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1> class CommandHandle<SK::Result(P1)> : public ICommandHandle<SK::Result(P1)> { typedef ICommandHandle<SK::Result(P1)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2> class CommandHandle<SK::Result(P1, P2)> : public ICommandHandle<SK::Result(P1, P2)> { typedef ICommandHandle<SK::Result(P1, P2)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3> class CommandHandle<SK::Result(P1, P2, P3)> : public ICommandHandle<SK::Result(P1, P2, P3)> { typedef ICommandHandle<SK::Result(P1, P2, P3)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4> class CommandHandle<SK::Result(P1, P2, P3, P4)> : public ICommandHandle<SK::Result(P1, P2, P3, P4)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5> class CommandHandle<SK::Result(P1, P2, P3, P4, P5)> : public ICommandHandle<SK::Result(P1, P2, P3, P4, P5)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4, P5)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6> class CommandHandle<SK::Result(P1, P2, P3, P4, P5, P6)> : public ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7> class CommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7)> : public ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8> class CommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8)> : public ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; template<typename P1, typename P2, typename P3, typename P4, typename P5, typename P6, typename P7, typename P8, typename P9> class CommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8, P9)> : public ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8, P9)> { typedef ICommandHandle<SK::Result(P1, P2, P3, P4, P5, P6, P7, P8, P9)> base_t; public: CommandHandle(SK::CommandManager &pCommandManager, const char *path):base_t(pCommandManager, path){} CommandHandle():base_t() {} virtual ~CommandHandle() {} CommandHandle(const CommandHandle& other):base_t(other) {} CommandHandle& operator=(const CommandHandle& other) { CommandHandle tmp = other; this->swap(tmp); return *this; } SK::Result operator()(typename SK::RefTypeTrait<P1>::add_const_ref_t p1, typename SK::RefTypeTrait<P2>::add_const_ref_t p2, typename SK::RefTypeTrait<P3>::add_const_ref_t p3, typename SK::RefTypeTrait<P4>::add_const_ref_t p4, typename SK::RefTypeTrait<P5>::add_const_ref_t p5, typename SK::RefTypeTrait<P6>::add_const_ref_t p6, typename SK::RefTypeTrait<P7>::add_const_ref_t p7, typename SK::RefTypeTrait<P8>::add_const_ref_t p8, typename SK::RefTypeTrait<P9>::add_const_ref_t p9, SK::ReturnValue::Attribute returnBehavior = SK::ReturnValue::IMMEDIATE, int32_t timeout = 0) const { SK::Array<RawData> params; params.pushBack(SK::RawData(p1, SK::Type<P1>::INFO));params.pushBack(SK::RawData(p2, SK::Type<P2>::INFO));params.pushBack(SK::RawData(p3, SK::Type<P3>::INFO));params.pushBack(SK::RawData(p4, SK::Type<P4>::INFO));params.pushBack(SK::RawData(p5, SK::Type<P5>::INFO));params.pushBack(SK::RawData(p6, SK::Type<P6>::INFO));params.pushBack(SK::RawData(p7, SK::Type<P7>::INFO));params.pushBack(SK::RawData(p8, SK::Type<P8>::INFO));params.pushBack(SK::RawData(p9, SK::Type<P9>::INFO)); SK::Result res = base_t::sendCommand(params, (returnBehavior == SK::ReturnValue::DROP)); if(res.failed())return res; return (returnBehavior != SK::ReturnValue::IMMEDIATE)?res:waitForReturnValue(timeout); } SK::Result waitForReturnValue(int32_t timeout = 0) const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::waitForReturnValue(rd, timeout); if(res.failed())return res; return rd.getRef<SK::Result>(); } SK::Return<bool> isReturnValueReady() const {return base_t::isReturnValueReady();} SK::Result tryGetReturnValue()const { SK::RawData rd((void*)NULL, SK::Type< SK::Result >::INFO, false); SK::Result res = base_t::tryGetReturnValue(rd); if(res.failed())return res; return rd.getRef<SK::Result>(); } }; //! \endcond }
true
3414fbe6e2e96bdbf4fa3851390955890b42418b
C++
aabhas-sao/DSA-CB-CPP
/binary_search/painter.cpp
UTF-8
1,073
3.578125
4
[]
no_license
#include<iostream> #include<climits> using namespace std; #define ll long long int bool isPossible(ll a[], ll mid, ll k, ll n) { ll pallersUsed = 1; ll boardTime = 0; for(ll i = 0; i < n; i++) { if(boardTime + a[i] > mid) { pallersUsed++; boardTime = a[i]; if(pallersUsed > k) { return false; } } else { boardTime += a[i]; } } return true; } void paint(ll a[], ll n, ll k, ll t) { ll largest = INT_MIN; ll e = 0; for(ll i = 0; i < n; i++) { largest = max(largest, a[i]); e += a[i]; } ll s = largest; ll ans; while(s<=e) { ll mid = (s + e) / 2; if(isPossible(a, mid, k, n)) { e = mid - 1; ans = mid; } else { s = mid + 1; } } ans = (ans * 5) % 10000003; cout<<((ans%10000003)*(t%10000003))%10000003<<endl; } int main() { ll n, k, t; cin>>n>>k>>t; ll a[n]; for(ll i = 0; i < n; i++) { cin>>a[i]; } paint(a, n, k, t); return 0; } /* test case 1 4 3 5 10 20 30 40 */
true
0658fd4d88d71116011a78b84efbbbf8fecb259a
C++
lstyrtmrnbd/qtqst
/src/pather.hpp
UTF-8
834
2.75
3
[]
no_license
#ifndef PATHER_INCLUDE #define PATHER_INCLUDE #include <functional> #include <iostream> #include <queue> #include "pathgraph.hpp" #include "pathnode.hpp" #include "region.hpp" // mapping of nodes to the node visited before them // outer vector is y, inner x using Previousmap = std::vector<std::vector<std::pair<int, int>>>; using Previousrow = std::vector<std::pair<int, int>>; // sequence of x, y values defining a path using Path = std::vector<std::pair<int, int>>; class Pather { public: static PathGraph* parseRegion(Region&); static Previousmap* breadthFirst(PathGraph&, int, int); static Path* pathFromPrevious(Previousmap&, int, int); static void doPath(Path&, std::function<void(int x, int y)>); private: std::priority_queue<PathNode> pq; }; #endif // PATHER_INCLUDE
true
7a5435208ccf25fdf7510be182f0081f6fbfe4f3
C++
blairesc/Data-Structures-and-Algorithm-Analysis
/BQUEUE.cpp
UTF-8
3,930
3.765625
4
[]
no_license
//Function Definition #include <iostream> #include <string> #include "BQUEUE.h" using namespace std; //************************************************************************************* //Name: default constructor //Precondition: none. //Postcondition: initialize state variables. front is set to 0. //Description: initilizes state variables //************************************************************************************* BQUEUE::BQUEUE() { front = 0; } //************************************************************************************* //Name: destructor //Precondition: memory allocated was not deleted. //Postcondition: memory allocated is deleted. //Description: deletes memory allocated. //************************************************************************************* BQUEUE::~BQUEUE() { cout << "~BQUEUE has been called" << endl; if (!front) { return; } bqnode *p = front->next; while (p != front) { bqnode *q = p; p = p->next; delete q; } delete front; } //************************************************************************************* //Name: copy constructor //Precondition: current object was not copied. //Postcondition: deep copy of current object is done. //Description: does a deep copy of current object. //************************************************************************************* BQUEUE::BQUEUE(const BQUEUE & Org) { cout << "Copy constructor is invoked." << endl; if (!Org.front) { return; } front = new bqnode; front->time = Org.front->time; front->next = front->prev = front; bqnode *p = Org.front->next; while (p != Org.front) { bqnode *q = new bqnode; q->time = p->time; q->next = front; q->prev = front->prev; front->prev->next = q; front->prev = q; p = p->next; } } //************************************************************************************* //Name: Enqueue //Precondition: data needs to be entered into the list. //Postcondition: data is inserted at the back of the list. //Description: has one argument of int data type which is the item to be inserted //at the back of the list. //************************************************************************************* void BQUEUE::Enqueue(int item) { if (front == 0) { front = new bqnode; front->time = item; front->next = front; front->prev = front; } else { bqnode *p = new bqnode; p->time = item; p->prev = front->prev; front->prev->next = p; p->next = front; front->prev = p; } } //************************************************************************************* //Name: Dequeue //Precondition: data from the front of the list needed to be deleted. //Postcondition: data from the front of the list was deleted. //Description: deletes the data from the front of the list //************************************************************************************* void BQUEUE::Dequeue() { cout << "Dequeue function invoked." << endl; if (front->next == front) { delete front; front = 0; } if (front != 0) { bqnode *p = front; bqnode *back = front->prev; front = front->next; if (front != 0) { front->prev = back; back->next = front; } delete p; } else { cout << "Cannot deQueue because queue is empty\n"; } } //************************************************************************************* //Name: Print //Precondition: data in the list was not displayed to the user. //Postcondition: data in the list is displayed to the user. //Description: displays data in the list to the user. //************************************************************************************* void BQUEUE::Print() { cout << "Print function invoked." << endl; bqnode *p = front; bqnode *back = front->prev; if (p == back) { cout << p->time << endl; } else { while (p != back) { cout << p->time << endl; p = p->next; } cout << p->time << endl; } }
true
196b55d5b3bba497c8aeebf7d8f5a0ff47b21e5d
C++
Devansh-Maurya/Object-Oriented-Programming-and-Design
/PackageDelieveryService/package_details.cpp
UTF-8
1,507
3.1875
3
[]
no_license
// // Created by devansh on 17/11/18. // #include <iostream> #include "TwoDayPackage.cpp" int main() { double costPerKg = 100, twoDayCharge = 50, overnightCharge = 80; Package *packages[2]; double costs[2]; Client client1("Devansh Maurya", "Mahanagar", "Lucknow", "Uttar Pradesh", 226006); Client client2("Deepak Sah", "Araria", "Katihar", "Bihar", 500050); packages[0] = new TwoDayPackage(client1, client2, 5, costPerKg, twoDayCharge); packages[1] = new Overnightpackage(client2, client1, 10, costPerKg, overnightCharge); for (int i = 0; i < 2; ++i) { cout << "\nPackage " << (i+1) << " details:\n\n"; cout << "Sender:\n"; cout << packages[i]->getSenderName() << "\n"; cout << packages[i]->getSenderAddress() << ", " << packages[i]->getSenderCity() << "\n"; cout << packages[i]->getSenderState() << ", " << packages[i]->getSenderZipCode() << "\n\n"; cout << "Receiver:\n"; cout << packages[i]->getReceiverName() << "\n"; cout << packages[i]->getReceiverAddress() << ", " << packages[i]->getReceiverCity() << "\n"; cout << packages[i]->getReceiverState() << ", " << packages[i]->getReceiverZipCode() << "\n\n"; costs[i] = packages[i]->calculateCost(); cout << "Package delivery cost: " << costs[i] << "\n\n"; } cout << "Packages' delievery costs:\n"; for (int j = 0; j < 2; ++j) { cout << "Package " << (j+1) << "'s total delivery cost = " << costs[j] << "\n"; } }
true
ae5cb25656c78beef3ed4da1e8ed3a968aa76f21
C++
alalaaa/zadanie-liczby-pierwsze
/pppppp.cpp
WINDOWS-1250
437
3
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; bool pierwsza(int liczba) { ifstream plik; plik.open("a.txt"); ofstream plik2; plik2.open("wynik.txt"); plik>>liczba; for (int i=2; i<liczba/2; i++) if (liczba %i == 0) { cout << "zoona"; return false; } cout <<"pierwsza"; return true; plik.close(); plik2.close(); } int main() { return 0; }
true
6c4ee8f2e8d2a20b3cff4020519ecfb7440d3bb1
C++
rollrat/old-library
/src/other/Lately/Byte Assembler/rac.h
UHC
6,918
2.609375
3
[]
no_license
/************************************************************************* * * ROLLRAT SOFTWARE LIBRARY * ALLOCATOR COLLECTION * * (C) Copyright 2014 * rollrat * All Rights Reserved * *************************************************************************/ #ifndef _ALLOCATOR_COLLECTION_ #define _ALLOCATOR_COLLECTION_ #include <new> // // Ultra Array Value Structure // #define _ALLOCATOR_NORMAL 0 #ifdef _AC_CUSTROM_ALLOCATOR #define _ALLOCATOR_DESTROY 1 #endif #ifndef _CUSTROM_SIZE_TYPE using::size_t; #define __SIZE_TYPE size_t #endif #ifndef _CUSTOM_OTHER_TYPE //using::ptrdiff_t; typedef int __w64 ptrdiff_t; #define __OTHER_TYPE ptrdiff_t #endif #define _USE_NOEXCEPT throw() // ǥø Ÿ . template<class _Ty> struct remove_reference { typedef _Ty type; }; template<class _Ty> struct remove_reference<_Ty&> { typedef _Ty type; }; template<class _Ty> struct remove_reference<_Ty&&> { typedef _Ty type; }; template<class _Ty> struct remove_pointer { typedef _Ty type; }; template<class _Ty> struct remove_pointer<_Ty*> { typedef _Ty type; }; template<class _Ty> inline _Ty&& forward(typename remove_reference<_Ty>::type& _Arg) { return (static_cast<_Ty&&>(_Arg)); } template<class _Ty> inline _Ty&& forward(typename remove_reference<_Ty>::type&& _Arg) { return (static_cast<_Ty&&>(_Arg)); } template<typename _Ty> _Ty* __addressof(_Ty& __r) { return reinterpret_cast<_Ty *> (&const_cast<char&>(reinterpret_cast<const volatile char&>(__r))); } template<typename _Ty> class _Normal_new_allocator { public: typedef typename __SIZE_TYPE size_type; typedef typename __OTHER_TYPE difference_type; typedef typename _Ty* pointer; typedef typename const _Ty* const_pointer; typedef typename _Ty& reference; typedef typename const _Ty& const_reference; typedef typename _Ty value_type; template<typename _Ty1> struct rebind { typedef _Normal_new_allocator<_Ty1> other; }; typedef _Normal_new_allocator<_Ty> _MyT; _Normal_new_allocator() _USE_NOEXCEPT {} _Normal_new_allocator(const _Normal_new_allocator&) _USE_NOEXCEPT {} template<typename _Ty1> _Normal_new_allocator(const _Normal_new_allocator<_Ty1>&) _USE_NOEXCEPT {} ~_Normal_new_allocator() _USE_NOEXCEPT {} pointer address(reference __x) const _USE_NOEXCEPT { return __addressof(__x); } const_pointer address(const_reference __x) const _USE_NOEXCEPT { return __addressof(__x); } pointer allocate(size_type __n, const void* = 0) { if (__n > this->max_size()) throw "bad_alloc!"; return static_cast<_Ty *> (new _Ty[__n * sizeof(_Ty)]); } void deallocate(pointer __p, size_type) { delete __p; } size_type max_size() const _USE_NOEXCEPT { return size_type(-1) / sizeof(_Ty); } template<typename _Up, typename ... _Args> void construct(_Up* __p, _Args&&... __args) { //__p = new _Up(forward<_Args>(__args) ...); new ((void *)__p) _Up(forward<_Args>(__args)...); } template<typename _Up> void destroy(_Up* __p) { __p->~_Up(); } void construct(_Ty *_Ptr) { new ((void *)_Ptr) _Ty(); } void construct(pointer __p, const _Ty& _Val) { //__p = new _Ty(_Val); new ((void *)__p) _Ty(_Val); } void destroy(pointer __p) { __p->~_Ty(); } }; template<typename _Ty> inline bool operator==(const _Normal_new_allocator<_Ty>&, const _Normal_new_allocator<_Ty>&) { return true; } template<typename _Ty> inline bool operator!=(const _Normal_new_allocator<_Ty>&, const _Normal_new_allocator<_Ty>&) { return false; } template<typename _Typ> using _Normal_allocator_base = _Normal_new_allocator < _Typ > ; template<typename _Ty> class _Normal_allocator : public _Normal_allocator_base<_Ty> { public: typedef typename __SIZE_TYPE size_type; typedef typename __OTHER_TYPE difference_type; typedef typename _Ty* pointer; typedef typename const _Ty* const_pointer; typedef typename _Ty& reference; typedef typename const _Ty& const_reference; typedef typename _Ty value_type; _Normal_allocator() _USE_NOEXCEPT { } _Normal_allocator(const _Normal_allocator<_Ty>& _Val) _USE_NOEXCEPT : _Normal_allocator_base<_Ty>(_Val) { } template<typename _Ty1> _Normal_allocator(const _Normal_allocator<_Ty1>&) _USE_NOEXCEPT { } ~_Normal_allocator() _USE_NOEXCEPT { } template<typename _Ty1> struct rebind { typedef _Normal_allocator<_Ty1> other; }; template<typename _Ty1> _Normal_allocator<_Ty>& operator=(const _Normal_allocator<_Ty1>&) { return *this; } }; template<typename _TyLeft, typename _TyRight> inline bool operator==(const _Normal_allocator<_TyLeft>&, const _Normal_allocator<_TyRight>&) { return true; } template<typename _TyLeft, typename _TyRight> inline bool operator!=(const _Normal_allocator<_TyLeft>& _Left, const _Normal_allocator<_TyRight>& _Right) { return !(_Left == _Right); } template<typename _Typ> using allocator = _Normal_allocator < _Typ > ; template<typename _Ty> class _Tree_allocator : public _Normal_allocator_base<_Ty> { public: typedef typename __SIZE_TYPE size_type; typedef typename __OTHER_TYPE difference_type; typedef typename _Ty* pointer; typedef typename const _Ty* const_pointer; typedef typename _Ty& reference; typedef typename const _Ty& const_reference; typedef typename _Ty value_type; _Tree_allocator() _USE_NOEXCEPT { } _Tree_allocator(const _Tree_allocator<_Ty>& _Val) _USE_NOEXCEPT : _Normal_allocator_base<_Ty>(_Val) { } template<typename _Ty1> _Tree_allocator(const _Tree_allocator<_Ty1>&) _USE_NOEXCEPT { } ~_Tree_allocator() _USE_NOEXCEPT { } template<typename _Ty1> struct rebind { typedef _Tree_allocator<_Ty1> other; }; template<typename _Ty1> _Tree_allocator<_Ty>& operator=(const _Tree_allocator<_Ty1>&) { return *this; } pointer allocate(const void* = 0) { return new _Ty(); } void deallocate(pointer __p) { delete __p; } }; template<typename _TyLeft, typename _TyRight> inline bool operator==(const _Tree_allocator<_TyLeft>&, const _Tree_allocator<_TyRight>&) { return true; } template<typename _TyLeft, typename _TyRight> inline bool operator!=(const _Tree_allocator<_TyLeft>& _Left, const _Tree_allocator<_TyRight>& _Right) { return !(_Left == _Right); } template<typename _Typ> using t_allocator = _Tree_allocator < _Typ > ; struct __Container_base; struct __Container_proxy { __Container_proxy() : _Mybase(0) {} __Container_base *_Mybase; }; struct __Container_base { public: __Container_base() : _Myproxy(0) { } __Container_base(const __Container_base&) : _Myproxy(0) { } __Container_base& operator=(const __Container_base&) { return *this; } ~__Container_base() _USE_NOEXCEPT { } __Container_proxy *_Myproxy; }; #endif
true
e5df08f428997352381a7c3f0636171aa3a67fb3
C++
miriambt/BasicProgramming
/8_Recursivity/P45102 - Completely parenthesed expression.cc
UTF-8
905
4.28125
4
[]
no_license
/* Completely parenthesed expression Write a program that reads a completely parenthesed expression, and prints the result of evaluating it. The three possible operators are sum, substraction and multiplication. The operands are natural numbers between 0 and 9 (both included). */ #include <iostream> #include <cassert> using namespace std; int expressio() { char c; cin >> c; if (c >= '0' and c <= '9') return c - '0'; else { assert(c == '('); int r1 = expressio(); char op; cin >> op; int r2 = expressio(); char tanca; cin >> tanca; assert (tanca == ')'); if (op == '+') return r1 + r2; if (op == '-') return r1 - r2; if (op == '*') return r1 * r2; assert (false); } } int main () { cout << expressio () << endl; } /* Example Input: 9 Output: 9 Input: ( 3 + 4 ) Output: 7 Input: ( 8 * ( 4 + 3 ) ) Output: 56 Input: ( ( 2 - 8 ) * ( 4 + 3 ) ) Output: -42 */
true
a014dcdbaf224a49d95e83402695266c731a4ccb
C++
Caryn-Walker0114/Pokemon-Battle-Sim
/Game.cpp
UTF-8
5,421
3.4375
3
[]
no_license
#include "Game.h" #include "Pokemon.h" #include <iostream> #include <string> #include <thread> #include <chrono> #include <random> #include <ctime> Game::Game() { //ctor } Game::~Game() { //dtor } //------------------------------------GAME FUNCTION---------------------------------------- bool Game::retry() { static bool tryAgain; char yes_no; std::cout << "Do you want to play again? Y/N \n"; do //So I still need to create a way to prevent more than one character from being accepted (you), (no), etc as these will pass the test even though yes_no is a char... { std::cin >> yes_no; if(yes_no == 'Y' || yes_no == 'y') { std::cout << "Restarting game...\n\n"; tryAgain = true; } else if(yes_no == 'N' || yes_no == 'n') { std::cout << "Thanks for playing!\n"; std::cout << "Terminating...\n\n"; tryAgain = false; } else if(!(yes_no)) { std::cout << "Let's see if this ever happens...\n"; } else { std::cout << "Invalid input. Please try again. \n"; std::cin.clear(); std::cin.ignore(10000, '\n'); retry(); } return tryAgain; }while(!(yes_no)); } //---- bool retry() end brace //------------------------------------ bool fightOn(Pokemon & p, Pokemon & e) //Friend function { bool fight; if(e.getHealth() > 0 && p.getHealth() > 0) { fight = true; } else { fight = false;} return fight; } //------------- void Battle(Pokemon & p, Pokemon & e) //Friend function { //speed check: whoever is faster goes first //pokemon attacks other pokemon, new health = old health - attack //health check: if other pokemon is still alive, it attacks //pokemon attacks other pokemon, new health = old health - attack //final health check, if both pokemon are still alive bool value will return true //if one pokemon is fainted, bool value will return false and do..while will exit if(p.getSpeed() > e.getSpeed()) // SPEED CHECK -- Make following code a separate function { p.playerTurn(p, e); if(e.getHealth() > 0) // HEALTH CHECK --- Make following code a separate function { e.enemyTurn(p, e); } else if(e.getHealth() <= 0) { std::cout << "The enemy has run out of health! You win!\n\n"; } } else if(e.getSpeed() > p.getSpeed()) // SPEED CHECK -- Make following code a separate function { e.enemyTurn(p, e); if(p.getHealth() > 0) //HEALTH CHECK --Make following code a separate function { p.playerTurn(p, e); } else if(p.getHealth() <= 0) { std::cout << "Your Pokemon has run out of health! You lose....\n\n"; std::cout << "Game Over...\n\n"; } } else //Make a random function to decide who goes first { int tieBreaker; std::mt19937 whoGoesFirst(time(0)); std::uniform_int_distribution<int> dist(1,2); tieBreaker = dist(whoGoesFirst); if(tieBreaker == 1)//PLAYER TURN CODE HERE { p.playerTurn(p, e); if(e.getHealth() > 0) // HEALTH CHECK --- Make following code a separate function { e.enemyTurn(p, e); } else if(e.getHealth() <= 0) { std::cout << "The enemy has run out of health! You win!\n\n"; } } else if(tieBreaker == 2)//ENEMY TURN CODE HERE { e.enemyTurn(p, e); if(p.getHealth() > 0) //HEALTH CHECK --Make following code a separate function { p.playerTurn(p, e); } else if(p.getHealth() <= 0) { std::cout << "Your Pokemon has run out of health! You lose....\n\n"; std::cout << "Game Over...\n\n"; } } }//Ending else brace }//----void Battle() end brace //-------------- void printInfo(Pokemon p, Pokemon e) //Friend function { std::cout << "The player's Pokemon is " << p.getName() << "! \n"; std::cout << p.getHealth() << std::endl; std::cout << p.getAttack() << std::endl; std::cout << p.getSpeed() << "\n\n"; std::cout << "The enemy's Pokemon is " << e.getName() << "! \n"; std::cout << e.getHealth() << std::endl; std::cout << e.getAttack() << std::endl; std::cout << e.getSpeed() << "\n\n"; } //-------------- void Game::playGame() { //-----------Player stats----------| Pokemon playerPokemon; playerPokemon.setName(); playerPokemon.setHealth(); playerPokemon.setAttack(); playerPokemon.setSpeed(); std::this_thread::sleep_for(std::chrono::milliseconds(2000)); //---------------Enemy stats-----------| Pokemon enemyPokemon; enemyPokemon.setName(); enemyPokemon.setHealth(); enemyPokemon.setAttack(); enemyPokemon.setSpeed(); //-------------------------------------| printInfo(playerPokemon, enemyPokemon); do{ Battle(playerPokemon, enemyPokemon) ;} while(fightOn(playerPokemon, enemyPokemon) == true); } //void Game::playGame() end brace
true
31bc10b141bfbe463b4cacc9818c110dda8514a6
C++
rileynat/Cplusplus
/euler23.cpp
UTF-8
825
3.3125
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int sum_of_divisors( int n ) { int total = 0; for ( int i = 1; i < n / 2 + 1; i++ ) { if ( n % i == 0 ) { total += i; } } return total; } int main () { vector<bool> bit_vector(28225, true); vector<int> abundant_nums; for ( int i = 11; i < 28500; i++ ) { if ( i < sum_of_divisors(i) ) { abundant_nums.push_back(i); } } for ( auto it = abundant_nums.begin(); it != abundant_nums.end(); it++ ) { for ( auto iter = abundant_nums.begin(); iter != abundant_nums.end(); iter++ ) { int sum = *it + *iter; if ( sum < 28225 ) { bit_vector[sum] = false; } } } int total = 0; for ( int i = 0; i < bit_vector.size(); i++ ) { if ( bit_vector[i] ) { cout << i << endl; total += i; } } cout << total << endl; }
true
0bd8bf6d982357668c9233f0088a1ab605c4eaf6
C++
atelyshev/vosvideoserver
/VosVideo.Communication/TypeInfoWrapper.cpp
UTF-8
1,664
2.765625
3
[ "MIT" ]
permissive
#include "stdafx.h" #include <cassert> #include "TypeInfoWrapper.h" using vosvideo::communication::TypeInfoWrapper; TypeInfoWrapper::TypeInfoWrapper() { class Nil {}; tInfo_ = &typeid(Nil); assert(tInfo_); } TypeInfoWrapper::TypeInfoWrapper(const std::type_info& tInfo) : tInfo_(&tInfo) { assert(tInfo_); } TypeInfoWrapper::~TypeInfoWrapper() { } const std::type_info& TypeInfoWrapper::Get() const { assert(tInfo_); return *tInfo_; } bool TypeInfoWrapper::before( const TypeInfoWrapper& typeInfoWrapper ) const { assert(tInfo_); // type_info::before return type is int in some VC libraries return tInfo_->before(*typeInfoWrapper.tInfo_) != 0; } const char* TypeInfoWrapper::name() const { assert(tInfo_); return tInfo_->name(); } bool vosvideo::communication::operator==(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) // type_info::operator== return type is int in some VC libraries { return (lhs.Get() == rhs.Get()) != 0; } bool vosvideo::communication::operator<(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) { return lhs.before(rhs); } bool vosvideo::communication::operator!=(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) { return !(lhs == rhs); } bool vosvideo::communication::operator>(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) { return rhs < lhs; } bool vosvideo::communication::operator<=(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) { return !(lhs > rhs); } bool vosvideo::communication::operator>=(const TypeInfoWrapper& lhs, const TypeInfoWrapper& rhs) { return !(lhs < rhs); }
true
c3b1705d6856d19f435d8739bf591053d94c9fe7
C++
rpuntaie/c-examples
/cpp/types_is_signed.cpp
UTF-8
919
2.984375
3
[ "MIT" ]
permissive
/* g++ --std=c++20 -pthread -o ../_build/cpp/types_is_signed.exe ./cpp/types_is_signed.cpp && (cd ../_build/cpp/;./types_is_signed.exe) https://en.cppreference.com/w/cpp/types/is_signed */ #include <iostream> #include <type_traits> class A {}; enum B : int {}; enum class C : int {}; int main() { std::cout << std::boolalpha; std::cout << std::is_signed<A>::value << '\n'; // false std::cout << std::is_signed<float>::value << '\n'; // true std::cout << std::is_signed<signed int>::value << '\n'; // true std::cout << std::is_signed<unsigned int>::value << '\n'; // false std::cout << std::is_signed<B>::value << '\n'; // false std::cout << std::is_signed<C>::value << '\n'; // false // shorter: std::cout << std::is_signed_v<bool> << '\n'; // false std::cout << std::is_signed<signed int>() << '\n'; // true std::cout << std::is_signed<unsigned int>{} << '\n'; // false }
true
0a9ae432e6a68be9d494278aaf13707d7b3e6d85
C++
LRLauriane/Projets
/Simulateur de système de carburant d'un avion/hh/entrainement.hh
UTF-8
661
2.953125
3
[]
no_license
#ifndef _ENTRAINEMENT_HH_ #define _ENTRAINEMENT_HH_ #include "systeme.hh" #include "dessiner_systeme.hh" #include <iostream> using namespace std; class entrainement { private: /*Système*/ systeme * sys; /*Représentation du système*/ dessiner_systeme * draw_sys; public: /*Constructeur*/ entrainement(); entrainement(systeme& sys,dessiner_systeme& draw_sys); /*Getteur*/ systeme& getSys(); dessiner_systeme& getDrawSys(); /*Méthode d'affichage des choix*/ void afficher_choix(); /*Méthode de lancement de l'entraînement selon le choix*/ void lancer_entrainement(string choix); }; #endif
true
2cf4de79efa1c4e74949b1f18da6d03a4b7d8728
C++
arcticpi/fibonacci
/fibonacci.cpp
UTF-8
549
3.859375
4
[]
no_license
#include <iostream> using namespace std; int fibonacci(int n) { if (n < 0) { return 0; } else if (n == 1) { return 1; } return fibonacci(n - 1) + fibonacci(n - 2); } int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "usage : fibonacci.exe <number>" << std::endl; return -1; } int n = std::atoi(argv[1]); for (int i = 0; i < n; i++) { std::cout << fibonacci(i) << " "; } std::cout << fibonacci(n) << std::endl; return 0; }
true
0dcc11ba0d86b533368d10db176d028ef54f6d5d
C++
ryanbennettvoid/quad-tree-cpp
/qt-server/src/Misc/Helpers.h
UTF-8
467
3
3
[]
no_license
#ifndef HELPERS_H #define HELPERS_H #include <iostream> #include <random> namespace Helpers { // https://stackoverflow.com/questions/7560114/random-number-c-in-some-range static int generateRandomNumberInRange( int a, int b ) { std::random_device rd; // obtain a random number from hardware std::mt19937 eng(rd()); // seed the generator std::uniform_int_distribution<> distr( a, b ); // define the range return distr( eng ); } } #endif
true
074919de6fa439c3200e156211fe9cd7613687bb
C++
DevelopersGuild/flappybird
/Source/Arrows.cpp
UTF-8
927
2.75
3
[]
no_license
#include "Arrows.h" #include "Assets.h" #include "Constants.h" #include "Score.h" #include <cmath> #include <iostream> using namespace std; Arrows::Arrows() { arrowOffTexture.loadFromFile(GetAssetPath("Assets/ArrowOff.png")); arrowOffSprite.setTexture(arrowOffTexture); arrowOffSprite.setScale(1.5, 1.5); arrowOffSprite.setPosition(730, 450); arrowOnTexture.loadFromFile(GetAssetPath("Assets/ArrowOn.png")); arrowOnSprite.setTexture(arrowOnTexture); arrowOnSprite.setScale(1.5, 1.5); arrowOnSprite.setPosition(730, 450); moveArrow = 0; totalTime = 0; } void Arrows::update(float seconds) { totalTime += seconds; arrowOnSprite.move( 0, sin( 8 * totalTime) ); } void Arrows::preGameRender(sf::RenderWindow &window) { static float time = float(clock() / CLOCKS_PER_SEC); } void Arrows::render(sf::RenderWindow &window, bool on) { if(on) window.draw( arrowOnSprite ); else window.draw( arrowOffSprite ); }
true
fd28f3adc4af5b5d883787cc75ba19252e114028
C++
Biggamer11/Nova
/Game.cpp
UTF-8
996
2.53125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Game.cpp * Author: jake * * Created on May 17, 2019, 9:32 PM */ #include "Game.h" Game::Game() { } Game::Game(const Game& orig) { } Game::~Game() { } Game::Game(Engine* eng){ engine = eng; } int Game::run() { SDL_Delay(2000); engine->window.setRes(220,220); engine->window.setTitle("this is so cool"); SDL_Delay(2000); return 0; } void Game::start() { } void Game::stop() { } void Game::load(Scene scenename) { scene = scenename; } void Game::loop() { while (!quit) { switch (scene) { case Startup: break; case MainMenu: break; case Testing: break; case Quit: quit = false; break; } } }
true
a8fd74c289595e01e73d687eb216e96fcc2741e9
C++
Chuncheonian/DataStructure
/Lab/Lab08/src/Application.cpp
UTF-8
31,721
3.1875
3
[]
no_license
#include "Application.h" // Program driver. void Application::Run() { while(1) { m_command = GetCommand(); switch(m_command) { case 1: // Add new record into masterList. AddContents(); break; case 2: // Get a createTime from keyboard and delete the rocord with same create Time. DeleteContents(); break; case 3: // Get a record from keyboard and Replace the rocord with same record. ReplaceContents(); break; case 4: // Get a create time from keyboard and Display a record with input create time. RetrieveContents(); break; case 5: // Display all MultimediaContents in the list in screen. DisplayAllContents(); break; case 6: // Make all list empty. MakeEmpty(); break; // case 7: // get data from data file // ReadDataFromFile(); // break; // case 8: // put data to data file // WriteDataToFile(); // break; // case 9: // Search MultiContent Record by combining one or more Primary KEYs. // SearchMCFromPks(); // break; case 0: // quit return; case 11: // Add new record into favoritedphotolist or favoritevideolist. AddFavoriteContent(); break; case 12: // Get a create time from keyboard and Delete the rocord with same create time. DeleteFavoriteContent(); break; case 13: // Get the list want to see from keyboard and Display all records in the corresponding list in screen. DisplayAllFavoriteContent(); break; case 14: // Display detail information of the specific record in screen. DisplayDetailFC(); break; case 15: // Get the condition by keyboard and Rearrange order of FavoriteContent elements. RearrangeFC(); break; case 21: // Display all Character record in the list on screen. DisplayAllCharacter(); break; case 22: // Search createTime from Location Record and Get detail content records. SearchMCFromCharacter(); break; case 31: // Display all Location record in the list on screen. DisplayAllLocation(); break; case 32: // Search createTime from Location Record and Get detail content records. SearchMCFromLocation(); break; case 41: // Display all Event record in the list on screen. DisplayAllEvent(); break; case 42: // Search createTime from Event Record and Get detail content records. SearchMCFromEvent(); break; default: cout << "\tIllegal sellection...\n"; break; } } } // Display command on screen and get a input from keyboard. int Application::GetCommand() { int command; cout << endl << endl; cout << "\t ----- Main Command ----- " << endl; cout << "\t 1 : Insert content" << endl; cout << "\t 2 : Delete content" << endl; cout << "\t 3 : Update content" << endl; cout << "\t 4 : Search content by Content creation time" << endl; cout << "\t 5 : Display all content" << endl; cout << "\t 6 : Make empty list" << endl; // cout << "\t 7 : Get from file" << endl; // cout << "\t 8 : Put to file" << endl; // cout << "\t 9 : Search content by combining keys" << endl; cout << "\t 0 : Quit " << endl; cout << "\t ----- Favorite Command ----- " << endl; cout << "\t 11 : Add favorite content" << endl; cout << "\t 12 : Delete favorite content" << endl; cout << "\t 13 : Display all favorite content" << endl; cout << "\t 14 : Display detail favorite content on screen" << endl; cout << "\t 15 : Rerrange Favorite Content's order" << endl; cout << "\t ----- Character Command ----- " << endl; cout << "\t 21 : Display all Character content" << endl; cout << "\t 22 : Display detail character content on screen" << endl; cout << "\t ----- Location Command ----- " << endl; cout << "\t 31 : Display all Location content" << endl; cout << "\t 32 : Display detail location content on screen" << endl; cout << "\t ----- Event Command ----- " << endl; cout << "\t 41 : Display all Event content" << endl; cout << "\t 42 : Display detail event content on screen" << endl; cout << endl << "\t Choose a Command--> "; cin >> command; cout << endl; return command; } // Add new record into masterList. int Application::AddContents() { MultimediaContent mainContent; cin >> mainContent; if (m_masterList.IsFull()) { // masterList 안이 꽉 찰 경우 cout << "\n\tList is full" << endl; return -1; } else { // masterList에 추가 m_masterList.Add(mainContent); // characterlist, locationlist, eventlist에 추가 AddCharacter(mainContent); AddLocation(mainContent); AddEvent(mainContent); DisplayAllContents(); cout << "\n\t<========ADD SUCCESS !===========>" << endl; return 1; } } // Get a createTime from keyboard and delete the rocord with same create Time. int Application::DeleteContents() { MultimediaContent mainContent; mainContent.SetTimeFromKB(); bool found; m_masterList.RetrieveItem(mainContent, found); if (m_masterList.IsEmpty()) { // masterList 안이 비어있을 경우 cout << "\tList is empty" << endl; return -1; } if (found == false) { // masterList에 없는 경우 cout << "\tThe content doesn't exist" << endl; return 0; } // masterlist에서 제거 m_masterList.DeleteItem(mainContent); // characterlist, locationlist, eventlist에서 삭제 DeleteMCFromCharacter(mainContent); DeleteMCFromLocation(mainContent); DeleteMCFromEvent(mainContent); // favoritephotolist,favoritevideolist에서 삭제 FavoritePhotoContent photoContent; FavoriteVideoContent videoContent; photoContent.SetTime(mainContent.GetTime()); videoContent.SetTime(mainContent.GetTime()); if (m_favoritePhotoList.Retrieve_BinS(photoContent)) // favoritephotolist에 있으면 삭제 m_favoritePhotoList.Delete(photoContent); if (m_favoriteVideoList.Retrieve_BinS(videoContent)) // favoritevideolist에 있으면 삭제 m_favoriteVideoList.Delete(videoContent); DisplayAllContents(); cout << "\t<========DELETE SUCCESS !===========>" << endl; return 1; } // Get a record from keyboard and Replace the rocord with same record. int Application::ReplaceContents() { MultimediaContent oldMC; MultimediaContent mainContent; FavoritePhotoContent photoContent; FavoriteVideoContent videoContent; mainContent.SetTimeFromKB(); photoContent.SetTime(mainContent.GetTime()); videoContent.SetTime(mainContent.GetTime()); bool found; m_masterList.RetrieveItem(mainContent, found); // masterlist에 존재하는 경우 if (found == true) { oldMC = mainContent; mainContent.SetNameFromKB(); mainContent.SetTypeFromKB(); mainContent.SetCharacterFromKB(); mainContent.SetLocationFromKB(); mainContent.SetCategoryFromKB(); mainContent.SetEventNameFromKB(); mainContent.SetEventDescriptionFromKB(); mainContent.SetContents(); m_masterList.UpdateItem(mainContent); // masterlist에 교체 완료 // favoritephotolist에서 변경 작업 if (m_favoritePhotoList.Retrieve_BinS(photoContent)) { if (mainContent.GetType() == 2) { // photo -> video인 경우 m_favoritePhotoList.Delete(photoContent); videoContent.SetRecordMC(mainContent); videoContent.SetCondition(photoContent.GetCondition()); videoContent.SetViewNumber(photoContent.GetViewNumber()); m_favoriteVideoList.Add(videoContent); } else { // 타입이 변경되지 않은 경우 photoContent.SetRecordMC(mainContent); m_favoritePhotoList.Replace(photoContent); } } // favoritevideolist에서 변경 작업 if (m_favoriteVideoList.Retrieve_BinS(videoContent)) { if (mainContent.GetType() == 1) { // video -> photo인 경우 m_favoriteVideoList.Delete(videoContent); photoContent.SetRecordMC(mainContent); photoContent.SetCondition(videoContent.GetCondition()); photoContent.SetViewNumber(videoContent.GetViewNumber()); m_favoritePhotoList.Add(photoContent); } else { // 타입이 변경되지 않은 경우 videoContent.SetRecordMC(mainContent); m_favoriteVideoList.Replace(videoContent); } } // specific class modification if (oldMC.GetCharacter() != mainContent.GetCharacter()) { DeleteMCFromCharacter(oldMC); AddCharacter(mainContent); } if (oldMC.GetLocation() != mainContent.GetLocation()) { DeleteMCFromLocation(oldMC); AddLocation(mainContent); } if (oldMC.GetEventName() != mainContent.GetEventName()) { DeleteMCFromEvent(oldMC); AddEvent(mainContent); } cout << "\n\tReplacing worked"; // 모든 변경사항 변경 완료 DisplayAllContents(); return 1; } cout << "\n\tNot exist the Primary Key in list"; return 0; } // Get a create time from keyboard and Display a record with input create time. void Application::RetrieveContents() { MultimediaContent mainContent; mainContent.SetTimeFromKB(); bool found; m_masterList.RetrieveItem(mainContent, found); if (found == true) { cout << "<============ Content Found !==========>" << endl; cout << mainContent << endl; cout << "<====================================>" << endl; } else cout << "<======== Content Not Found!==========>" << endl; } // Display all MultimediaContents in the list in screen. void Application::DisplayAllContents() { cout << "\n\t--Current list--" << endl; m_masterList.PrintTree(cout); } // Make masterList empty. void Application::MakeEmpty() { m_masterList.MakeEmpty(); m_favoritePhotoList.MakeEmpty(); m_favoriteVideoList.MakeEmpty(); m_characterList.MakeEmpty(); m_locationList.MakeEmpty(); m_eventList.MakeEmpty(); cout << "List is now empty."; } // // Open a file by file descriptor as an input file. // int Application::OpenInFile(char *fileName) { // m_inFile.open(fileName); // file open for reading. // // 파일 오픈에 성공하면 1, 그렇지 않다면 0을 리턴. // if (!m_inFile) // return 0; // else // return 1; // } // // Open a file by file descriptor as an output file. // int Application::OpenOutFile(char *fileName) { // m_outFile.open(fileName); // file open for writing. // // 파일 오픈에 성공하면 1, 그렇지 않다면 0을 리턴. // if (!m_outFile) // return 0; // else // return 1; // } // // Open a file as a read mode, Read all data on the file, and Set list by the data. // int Application::ReadDataFromFile() { // int index = 0; // MultimediaContent mainContent; // 읽기용 임시 변수 // char filename[FILENAMESIZE]; // cout << "\n\tEnter Input file Name : "; // cin >> filename; // // file open, open error가 발생하면 0을 리턴 // if (!OpenInFile(filename)) // return 0; // // 파일의 모든 내용을 읽어 list에 추가 // while (!m_inFile.eof()) { // // array에 학생들의 정보가 들어있는 structure 저장 // mainContent.ReadDataFromFile(m_inFile); // m_masterList.Add(mainContent); // } // m_inFile.close(); // file close // // 현재 list 출력 // DisplayAllContents(); // return 1; // } // // Open a file as a write mode, and Write all data into the file, // int Application::WriteDataToFile() { // MultimediaContent mainContent; // 쓰기용 임시 변수 // char filename[FILENAMESIZE]; // cout << "\n\tEnter Output file Name : "; // cin >> filename; // // file open, open error가 발생하면 0을 리턴 // if (!OpenOutFile(filename)) // return 0; // DoublyIterator<MultimediaContent> iter(m_masterList); // // iteration을 이용하여 모든 item 출력 // while (iter.NotNull()) { // mainContent.WriteDataToFile(m_outFile); // mainContent = iter.Next(); // } // m_outFile.close(); // file close // return 1; // } // // @@ Favorite-Content Functions @@ // Check if record is a picture or video and Add new record into corresponding list (FavoritePhotoList or FavoriteVideoList). int Application::AddFavoriteContent() { MultimediaContent mainContent; mainContent.SetTimeFromKB(); bool found; m_masterList.RetrieveItem(mainContent, found); if (found == false) { cout << "\n\tNot exist the Primary Key in list"; return 0; } if (mainContent.GetType() == 1) { // Type == Photo FavoritePhotoContent photoContent(mainContent); // photoContent 변수 세팅 if (m_favoritePhotoList.GetLength() >= 1) { // FavoritePhotoList에 이미 컨텐츠가 존재하면 m_condition 일치하게 만들기 FavoritePhotoContent temp; m_favoritePhotoList.ResetList(); m_favoritePhotoList.GetNextItem(temp); photoContent.SetCondition(temp.GetCondition()); } int status = m_favoritePhotoList.Add(photoContent); if (status == 0) { cout << "\n\tThe content already exists" << endl; return 0; } else if (status == 1) cout << "\n\t<========ADD SUCCESS !===========>" << endl; } else if (mainContent.GetType() == 2) { // Type == Video FavoriteVideoContent videoContent(mainContent); // videoContent 변수 세팅 if (m_favoriteVideoList.GetLength() >= 1) { // FavoriteVideoList에 이미 컨텐츠가 존재하면 m_condition 일치하게 만들기 FavoriteVideoContent temp; m_favoriteVideoList.ResetList(); m_favoriteVideoList.GetNextItem(temp); videoContent.SetCondition(temp.GetCondition()); } int status = m_favoriteVideoList.Add(videoContent); if (status == 0) { cout << "\n\tThe content already exists" << endl; return 0; } else if (status == 1) cout << "\n\t<========ADD SUCCESS !===========>" << endl; } return 1; } // Get a create time from keyboard and Delete the rocord with same create time. int Application::DeleteFavoriteContent() { MultimediaContent mainContent; mainContent.SetTimeFromKB(); bool found; m_masterList.RetrieveItem(mainContent, found); if (found == false) { cout << "\n\tNot exist the Primary Key in list"; return 0; } if (mainContent.GetType() == 1) { // Type == Photo FavoritePhotoContent photoContent; photoContent.SetTime(mainContent.GetTime()); int status = m_favoritePhotoList.Delete(photoContent); if (status == -1) { cout << "\tList is empty" << endl; return -1; } else if (status == 0) { cout << "\tThe content doesn't exist" << endl; return 0; } else { cout << "\t<========DELETE SUCCESS !===========>" << endl; return 1; } } else if (mainContent.GetType() == 2) { // Type == Video FavoriteVideoContent videoContent; videoContent.SetTime(mainContent.GetTime()); int status = m_favoriteVideoList.Delete(videoContent); if (status == -1) { cout << "\tList is empty" << endl; return -1; } else if (status == 0) { cout << "\tThe content doesn't exist" << endl; return 0; } else { cout << "\t<========DELETE SUCCESS !===========>" << endl; return 1; } } return 1; } // Get the list want to see from keyboard and Display all records in the corresponding list in screen. void Application::DisplayAllFavoriteContent() { cout << "\n\t--Current Favorite Photo list--" << endl; m_favoritePhotoList.ResetList(); int length = m_favoritePhotoList.GetLength(); for (int i = 0; i < length; i++) { FavoritePhotoContent photoContent; m_favoritePhotoList.GetNextItem(photoContent); photoContent.SetViewNumber(photoContent.GetViewNumber() + 1); // 조회 수 1 증가 m_favoritePhotoList.Replace(photoContent); // 조회 수 1 증가 된 photoContent를 favoritePhotoList에 업데이트 cout << photoContent << endl; // 출력 } cout << "\n\t--Current Favorite Video list--" << endl; m_favoriteVideoList.ResetList(); length = m_favoriteVideoList.GetLength(); for (int i = 0; i < length; i++) { FavoriteVideoContent videoContent; m_favoriteVideoList.GetNextItem(videoContent); videoContent.SetViewNumber(videoContent.GetViewNumber() + 1); // 조회 수 1 증가 m_favoriteVideoList.Replace(videoContent); // 조회 수 1 증가 된 videoContent를 favoriteVideoList에 업데이트 cout << videoContent << endl; // 출력 } } // Display detail information of the specific record in screen. void Application::DisplayDetailFC() { MultimediaContent mainContent; mainContent.SetTimeFromKB(); bool found; m_masterList.RetrieveItem(mainContent, found); if (found == false) cout << "\n\tNot exist the Primary Key in list"; if (mainContent.GetType() == 1) { // Type == Photo FavoritePhotoContent photoContent; photoContent.SetTime(mainContent.GetTime()); if (m_favoritePhotoList.Retrieve_BinS(photoContent)) { photoContent.SetViewNumber(photoContent.GetViewNumber() + 1); // 조회 수 1 증가 m_favoritePhotoList.Replace(photoContent); // 조회 수 1 증가 된 photoContent를 favoritePhotoList에 업데이트 mainContent.SetTime(photoContent.GetTime()); m_masterList.RetrieveItem(mainContent, found); cout << "\n\tCurrent list" << endl; cout << mainContent; // 출력 } else cout << "\n\tNot exist in Favorite Photo list" << endl; } else if (mainContent.GetType() == 2) { // Type == Photo FavoriteVideoContent videoContent; videoContent.SetTime(mainContent.GetTime()); if (m_favoriteVideoList.Retrieve_BinS(videoContent)) { videoContent.SetViewNumber(videoContent.GetViewNumber() + 1); // 조회 수 1 증가 m_favoriteVideoList.Replace(videoContent); // 조회 수 1 증가 된 videoContent를 favoriteVideoList에 업데이트 mainContent.SetTime(videoContent.GetTime()); m_masterList.RetrieveItem(mainContent, found); cout << "\n\tCurrent list" << endl; cout << mainContent; // 출력 } else cout << "\n\tNot exist in Favorite Video list" << endl; } } // Get the condition by keyboard and Rearrange order of FavoriteContent elements. void Application::RearrangeFC() { int listType; int condition; cout << "\n\tChoose the list Rearranging (1. Favorite Photo List, 2. Favorite Video List) : "; cin >> listType; if (listType == 1) { // Type -> Photo SortedList<FavoritePhotoContent> tmpPhotoList = m_favoritePhotoList; // Favorite Photo Content List. int length = m_favoritePhotoList.GetLength(); m_favoritePhotoList.MakeEmpty(); tmpPhotoList.ResetList(); cout << "\n\tEnter the condition to see in what order (1. createTime, 2. contentName, 3. viewNumber) : "; cin >> condition; if (!(condition == 1 || condition == 2 || condition == 3)) { // 1, 2, 3 외의 숫자를 입력한 경우 cout << "\n\tEnter 1 or 2 or 3" << endl; return; } for (int i = 0; i < length; i++) { FavoritePhotoContent photoContent; tmpPhotoList.GetNextItem(photoContent); photoContent.SetCondition(condition); m_favoritePhotoList.Add(photoContent); } DisplayAllFavoriteContent(); cout << "\n\t<========Modification SUCCESS !===========>" << endl; } else if (listType == 2) { // Type -> Video SortedList<FavoriteVideoContent> tmpVideoList = m_favoriteVideoList; // Favorite Video Content List. int length = m_favoriteVideoList.GetLength(); m_favoriteVideoList.MakeEmpty(); tmpVideoList.ResetList(); cout << "\n\tEnter the condition to see in what order (1. createTime, 2. contentName, 3. viewNumber) : "; cin >> condition; if (!(condition == 1 || condition == 2 || condition == 3)) { // 1, 2, 3 외의 숫자를 입력한 경우 cout << "\n\tEnter 1 or 2 or 3" << endl; return; } for (int i = 0; i < length; i++) { FavoriteVideoContent videoContent; tmpVideoList.GetNextItem(videoContent); videoContent.SetCondition(condition); m_favoriteVideoList.Add(videoContent); } DisplayAllFavoriteContent(); cout << "\n\t<========Modification SUCCESS !===========>" << endl; } else // 1, 2 외의 숫자를 입력한 경우 cout << "\n\tEnter 1 or 2" << endl; } // @@ Character Functions @@ // Display all Character record in the list on screen. void Application::DisplayAllCharacter() { CharacterContent character; m_characterList.ResetList(); cout << "\n\t--Current Character list--" << endl; for (int i = 0; i < m_characterList.GetLength(); i++) { m_characterList.GetNextItem(character); cout << character << endl; } } // Add CreateTime into CreateTime List of CharacterContent. void Application::AddCharacter(MultimediaContent& _mainContent) { CharacterContent character; character.SetName(_mainContent.GetCharacter()); if (!m_characterList.Get(character)) { // chracterlist안에 같은 character name이 존재하지 않은 경우 character.AddCreateTime(_mainContent.GetTime()); m_characterList.Add(character); // character name 신규 추가 } else { // chracterlist안에 이미 같은 character name이 존재하는 경우 character.AddCreateTime(_mainContent.GetTime()); m_characterList.Replace(character); // 변경된 사항 characterList에 업데이트 } } // Search createTime from Location Record and Get detail content records. void Application::SearchMCFromCharacter() { CharacterContent character; character.SetNameFromKB(); if (m_characterList.Get(character)) { character.SearchAtMasterList(m_masterList); // 디테일 정보 출력 } else { cout << "\tNot Exist Character in list." << endl; DisplayAllCharacter(); } } // Delete createTime into CreateTime List of CharacterContent. void Application::DeleteMCFromCharacter(MultimediaContent& _mainContent) { CharacterContent character; character.SetName(_mainContent.GetCharacter()); if (m_characterList.Get(character)) { if (character.GetCount() == 1) { // characterList에 같은 character가 하나인 경우 m_characterList.Delete(character); } else { // characterList에 같은 character가 둘 이상인 경우 character.DeleteCreateTime(_mainContent.GetTime()); m_characterList.Replace(character); // 변경된 사항 characterList에 업데이트 } } } // @@ Location Functions @@ // Display all Location record in the list on screen. void Application::DisplayAllLocation() { LocationContent location; m_locationList.ResetList(); cout << "\n\t--Current Location list--" << endl; for (int i = 0; i < m_locationList.GetLength(); i++) { m_locationList.GetNextItem(location); cout << location << endl; } } // Add CreateTime into CreateTime List of LocationContent. void Application::AddLocation(MultimediaContent& _mainContent) { LocationContent location; location.SetName(_mainContent.GetLocation()); if (!m_locationList.Get(location)) { // locationlist안에 같은 location이 존재하지 않은 경우 location.AddCreateTime(_mainContent.GetTime()); m_locationList.Add(location); // location 신규 추가 } else { // locationlist안에 이미 같은 location이 존재하는 경우 location.AddCreateTime(_mainContent.GetTime()); m_locationList.Replace(location); // 변경된 사항 locationlist 업데이트 } } // Search createTime from Location Record and Get detail content records. void Application::SearchMCFromLocation() { LocationContent location; location.SetNameFromKB(); if (m_locationList.Get(location)) { location.SearchAtMasterList(m_masterList); // 디테일 정보 출력 } else { cout << "\tNot Exist Location in list." << endl; DisplayAllLocation(); } } // Delete createTime into CreateTime List of LocationContent. void Application::DeleteMCFromLocation(MultimediaContent& _mainContent) { LocationContent location; location.SetName(_mainContent.GetLocation()); if (m_locationList.Get(location)) { if (location.GetCount() == 1) // locationList에 같은 location가 하나인 경우 m_locationList.Delete(location); else { // locationList에 같은 location가 둘 이상인 경우 location.DeleteCreateTime(_mainContent.GetTime()); m_locationList.Replace(location); // 변경된 사항 locationlist 업데이트 } } } // @@ Event Functions @@ // Display all Event record in the list on screen. void Application::DisplayAllEvent() { EventContent event; m_eventList.ResetList(); cout << "\n\t--Current Event list--" << endl; for (int i = 0; i < m_eventList.GetLength(); i++) { m_eventList.GetNextItem(event); cout << event << endl; } } // Add CreateTime into CreateTime List of EventContent. void Application::AddEvent(MultimediaContent& _mainContent) { EventContent event; event.SetRecord(_mainContent.GetEventName(), _mainContent.GetEventDescription()); if (!m_eventList.Get(event)) { // evnetList안에 같은 event가 존재하지 않은 경우 event.AddCreateTime(_mainContent.GetTime()); m_eventList.Add(event); // event 신규 추가 } else { // evnetList안에 이미 같은 event가 존재하는 경우 event.AddCreateTime(_mainContent.GetTime()); m_eventList.Replace(event); // 변경된 사항 evnetList 업데이트 } } // Search createTime from Event Record and Get detail content records. void Application::SearchMCFromEvent() { EventContent event; event.SetNameFromKB(); if (m_eventList.Get(event)) { event.SearchAtMasterList(m_masterList); // 디테일 정보 출력 } else { cout << "\tNot Exist Event in list." << endl; DisplayAllEvent(); } } // Delete createTime into CreateTime List of EventContents. void Application::DeleteMCFromEvent(MultimediaContent& _mainContent) { EventContent event; event.SetName(_mainContent.GetEventName()); if (m_eventList.Get(event)) { if (event.GetCount() == 1) // eventList에 같은 event가 하나인 경우 m_eventList.Delete(event); else { // eventList에 같은 event가 둘 이상인 경우 event.DeleteCreateTime(_mainContent.GetTime()); m_eventList.Replace(event); // 변경된 사항 evnetList 업데이트 } } } // Search content by combining one or more keys // // Search MultiContent Record by combining one or more Primary KEYs. // void Application::SearchMCFromPks() { // MultimediaContent mainContent; // CharacterContent character; // LocationContent location; // EventContent event; // UnsortedList<string> inputKeyList; // SortedSinglyLinkedList<MultimediaContent> tmpList; // string inputKey = ""; // int countKey = 0; // // 키 입력 받기 // while (1) { // cout << "\n\tInput Searching Keys (Quit 'q'): "; // cin >> inputKey; // if (inputKey == "q") // break; // countKey++; // inputKeyList.Add(inputKey); // } // // 입력 된 키의 종류(character, location, event) 확인하기 // for (int i = 0; i < countKey; i++) { // character.SetName(inputKeyList[i]); // location.SetName(inputKeyList[i]); // event.SetName(inputKeyList[i]); // if (m_characterList.Get(character)) // mainContent.SetCharacter(character.GetName()); // if (m_locationList.Get(location)) // mainContent.SetLocation(location.GetName()); // if (m_eventList.Get(event)) // mainContent.SetEventName(event.GetName()); // } // bool isFind = false; // cout << "\n\t<====================================>" << endl; // if (countKey == 1) { // 입력된 키가 하나인 경우 // if (searchKeyFromCharacter(mainContent, tmpList, 1)) // 키가 character인지? // isFind = true; // else if (searchKeyFromLocation(mainContent, tmpList, 1)) // 키가 location인지? // isFind = true; // else if (searchKeyFromEvent(mainContent, tmpList, 1)) // 키가 event인지? // isFind = true; // } // else if (countKey == 2) { // 입력된 키가 두개인 경우 // if (searchKeyFromCharacter(mainContent,tmpList, 1)) { // 키가 character인지? // if (searchKeyFromLocation(mainContent, tmpList, 0)) // 키가 character이고 location인지? // isFind = true; // else if (searchKeyFromEvent(mainContent, tmpList, 0)) // 키가 character이고 event인지? // isFind = true; // } // else if (searchKeyFromLocation(mainContent, tmpList, 1)) // 키가 location인지? // if (searchKeyFromEvent(mainContent, tmpList, 0)) // 키가 location이고 event인지? // isFind = true; // } // else if (countKey == 3) { // 입력된 키가 세 개인 경우 // if (searchKeyFromCharacter(mainContent, tmpList, 1)) // 키가 character인지? // if (searchKeyFromLocation(mainContent, tmpList, 0)) // 키가 character이고 location인지? // if (searchKeyFromEvent(mainContent, tmpList, 0)) // 키가 character, location이고 event인지? // isFind = true; // } // if (isFind) { // MultimediaContent tmp; // tmpList.ResetList(); // for (int i = 0; i < tmpList.GetLength(); i++) { // 같은 키를 포함하는 MultimediaContent 정보 출력 // tmpList.GetNextItem(tmp); // cout << tmp << endl; // } // cout << "\t<============I FOUND CONTENT !==========>" << endl; // } // else // cout << "\n\t<========I CAN'T FIND CONTENT !==========>" << endl; // } // // Search MultiContent Record with PK of Character Class // bool Application::searchKeyFromCharacter(MultimediaContent& _mc, SortedSinglyLinkedList<MultimediaContent>& _list, bool _condition) { // bool isFind = false; // DoublyIterator<MultimediaContent> iter(m_masterList); // // masterList 한바퀴 돌기 // while (iter.NotNull()) { // if (_mc.GetCharacter().find(iter.GetCurrentNode().data.GetCharacter(),0) != -1) {// 동일한 character인 경우 // MultimediaContent tmp = iter.GetCurrentNode().data; // _list.Add(tmp); // _list에 추가 // isFind = true; // } // iter.Next(); // } // if (isFind) // return true; // else // return false; // } // // Search MultiContent Record with PK of Location Class // bool Application::searchKeyFromLocation(MultimediaContent& _mc, SortedSinglyLinkedList<MultimediaContent>& _list, bool _condition) { // bool isFind = false; // if (_condition) { // 그 전에 키를 파악하지 못한 경우 // DoublyIterator<MultimediaContent> iter(m_masterList); // // masterList 한바퀴 돌기 // while (iter.NotNull()) { // if (_mc.GetLocation().find(iter.GetCurrentNode().data.GetLocation(),0) != -1) { // 동일한 Location인 경우 // MultimediaContent tmp = iter.GetCurrentNode().data; // _list.Add(tmp); // _list에 추가 // isFind = true; // } // iter.Next(); // } // } // else { // 그 전에 다른 키가 존재하여 파악한 경우 // MultimediaContent mainContent; // SortedSinglyLinkedList<MultimediaContent> tmpList; // _list.ResetList(); // for (int i = 0; i < _list.GetLength(); i++) { // _list 한바퀴 돌기 // _list.GetNextItem(mainContent); // if (_mc.GetLocation() == mainContent.GetLocation()) { // 동일한 Location인 경우 // tmpList.Add(mainContent); // tmpList에 추가 // isFind = true; // } // } // _list = tmpList; // tmpList를 _List에 할당 // } // if (isFind) // return true; // else // return false; // } // // Search MultiContent Record with PK of Event Class // bool Application::searchKeyFromEvent(MultimediaContent& _mc, SortedSinglyLinkedList<MultimediaContent>& _list, bool _condition) { // bool isFind = false; // if (_condition) { // 그 전에 키를 파악하지 못한 경우 // DoublyIterator<MultimediaContent> iter(m_masterList); // // masterList 한바퀴 돌기 // while (iter.NotNull()) { // if (_mc.GetEventName().find(iter.GetCurrentNode().data.GetEventName(),0) != -1) { // 동일한 Event인 경우 // MultimediaContent tmp = iter.GetCurrentNode().data; // _list.Add(tmp); // _list에 추가 // isFind = true; // } // iter.Next(); // } // } // else { // 그 전에 다른 키가 존재하여 파악한 경우 // MultimediaContent mainContent; // SortedSinglyLinkedList<MultimediaContent> tmpList; // _list.ResetList(); // for (int i = 0; i < _list.GetLength(); i++) { // _list 한바퀴 돌기 // _list.GetNextItem(mainContent); // if (_mc.GetEventName() == mainContent.GetEventName()) { // 동일한 Event인 경우 // tmpList.Add(mainContent); // tmpList에 추가 // isFind = true; // } // } // _list = tmpList; // tmpList를 _List에 할당 // } // if (isFind) // return true; // else // return false; // }
true
a3daa0a69a67196ce44de2cf169ef99bf966a0c8
C++
SirAbsolute0/EDL-Coding-Team-24
/EDLPart1.cpp
UTF-8
525
2.5625
3
[]
no_license
#include "EDLPart1.h" double Aeroshell_A(double Aeroshell_r) { return ( M_PI * pow(Aeroshell_r,2) ); } double Mass() { return ( M_Rover + M_EDL + M_Lander + M_Aeroshell ); } double Temp(double Altitude) { if (Altitude >= 7000) { return( -23.4 - .00222 * Altitude ); } else { return (-31 - .00998 * Altitude); } } double Press_Static(double Altitude) { return ( .699 * exp(-.00009 * Altitude) ); } double Atmos_Dense(double Altitude) { return (Press_Static(Altitude) / (.1921 * (Temp(Altitude) + 273.1))); }
true
3f216ed016983a45fec19ef87aefc7e3a0e53819
C++
Mishin870/MHSCpp
/mhscript/commands/ScriptBlock.cpp
UTF-8
1,306
2.609375
3
[ "MIT" ]
permissive
// // Created by Mishin870 on 28.07.2018. // #include "ScriptBlock.h" #include "../engine/ScriptLoader.h" #include "ScriptUtils.h" ScriptBlock::ScriptBlock(Stream *stream) { this->commands = loadBlock(stream, this->commandsCount); this->isRoot = stream->readByte() == 1; if (this->isRoot) { this->functionsCount = stream->readInt(); this->functions = new LocalFunction*[this->functionsCount]; unsigned int i; for (i = 0; i < this->functionsCount; i++) { this->functions[i] = new LocalFunction(stream); } } else { this->functionsCount = 0; this->functions = nullptr; } } ScriptBlock::~ScriptBlock() { unsigned int i; for (i = 0; i < this->commandsCount; i++) { delete this->commands[i]; } delete[] this->commands; if (this->isRoot) { for (i = 0; i < this->functionsCount; i++) { delete this->functions[i]; } delete[] this->functions; } } Object *ScriptBlock::execute(Engine *engine) { unsigned int i; if (this->isRoot) { for (i = 0; i < this->functionsCount; i++) { LocalFunction* function = this->functions[i]; engine->setLocalFunction(function->getName(), function); } } for (i = 0; i < this->commandsCount; i++) { executeVoid(this->commands[i], engine); } return nullptr; } CommandType ScriptBlock::getType() { return CT_SCRIPT_BLOCK; }
true
34c9da5d6c97d900614bec7e761205493602d3c6
C++
anlijiu/node-can
/src/can/can.h
UTF-8
1,748
2.953125
3
[ "MIT" ]
permissive
#ifndef CAN_CAN_H #define CAN_CAN_H #define CAN_MAX_DLEN 8 #include <iostream> #include <cstring> namespace can { /** * struct can_frame - basic CAN frame structure * @can_id: CAN ID of the frame and CAN_*_FLAG flags, see canid_t definition * @can_dlc: frame payload length in byte (0 .. 8) aka data length code * N.B. the DLC field from ISO 11898-1 Chapter 8.4.2.3 has a 1:1 * mapping of the 'data length code' to the real payload length * @data: CAN frame payload (up to 8 byte) */ struct can_frame final { unsigned int can_id; /* 32 bit CAN_ID + EFF/RTR/ERR flags */ unsigned char rtr;/**< remote transmission request. (0 if not rtr message, 1 if rtr message) */ unsigned char can_dlc; /* frame payload length in byte (0 .. CAN_MAX_DLEN) */ unsigned char data[CAN_MAX_DLEN] __attribute__((aligned(8))); friend std::ostream& operator<<(std::ostream& out, can_frame value); can_frame& operator=(can_frame const& value) { can_id = value.can_id; rtr = value.rtr; can_dlc = value.can_dlc; can_id = value.can_id; memcpy(data, value.data, CAN_MAX_DLEN); return *this; }; bool operator == (can_frame const& value) const { return can_id == value.can_id && rtr == value.rtr && can_dlc == value.can_dlc && strcmp((const char*)data, (const char*)value.data) == 0; }; bool operator != (can_frame const& value) const { return can_id != value.can_id || rtr != value.rtr || can_dlc != value.can_dlc || strcmp((const char*)data, (const char*)value.data) != 0; }; } ; }// namespace can #endif // CAN_CAN_H
true
4cce35f2bc8fc6584ea7dd719875e4e143eddeb9
C++
spfrood/CPP-references
/Chapters/Assignment_2/Gaddis_8thEd_Chap3_Prob8_Widgets/main.cpp
UTF-8
1,357
3.515625
4
[]
no_license
/* * File: main.cpp * Author: Scott Parker * Created on January 11, 2017 * Purpose: Gaddis, 8thEd, Chapter 3, Problem 8, Widgets * Calculate the number of widgets on a pallet based on the weight of the * loaded pallet and the weight of the pallet itself if widgets weigh 12.5 * pounds each */ //System Libraries #include <iostream> #include <iomanip> using namespace std; //User Libraries //Global Constants //Such as PI, Vc, -> Math/Science values //as well as conversions from one system of measurements //to another const float WIDGET = 1.25e1; //Function Prototypes //Executable code begins here! Always begins in Main int main(int argc, char** argv) { //Declare Variables float numWidg, palWght, totWght; //Input Values cout<<"To calculate the number of widgets on the pallet please"<<endl; cout<<"provide the following information..."<<endl; cout<<"What is the weight of the pallet itself in pounds?"<<endl; cin>>palWght; cout<<"What is the total weight of the loaded pallet in pounds?"<<endl; cin>>totWght; //Process by mapping inputs to outputs numWidg = ((totWght-palWght)/WIDGET); //Output values cout<<setprecision(0)<<fixed; cout<<"The pallet contains: "<<numWidg<<" widgets."<<endl; //Exit stage right! - This is the 'return 0' call return 0; }
true
9951d307bfc5e1d4d0dd3b55b187a1aa036c32da
C++
Itaperam/Laboratorio-LPI
/Roteiro04/exercise4-03.cpp
UTF-8
1,869
3
3
[]
no_license
#include <iostream> using namespace std; int main() { int face = -1; int qtdLancamentos = 0; double pcnt1 = 0; double pcnt2 = 0; double pcnt3 = 0; double pcnt4 = 0; double pcnt5 = 0; double pcnt6 = 0; int face1 = 0; int face2 = 0; int face3 = 0; int face4 = 0; int face5 = 0; int face6 = 0; while (face != 0) { cout << "Informe a face: "; cin >> face; switch (face) { case 1: face1++; qtdLancamentos++; break; case 2: face2++; qtdLancamentos++; break; case 3: face3++; qtdLancamentos++; break; case 4: face4++; qtdLancamentos++; break; case 5: face5++; qtdLancamentos++; break; case 6: face6++; qtdLancamentos++; break; default: cout << "Valor inválido" << endl; } pcnt1 = (face1*100)/qtdLancamentos; pcnt2 = (face2*100)/qtdLancamentos; pcnt3 = (face3*100)/qtdLancamentos; pcnt4 = (face4*100)/qtdLancamentos; pcnt5 = (face5*100)/qtdLancamentos; pcnt6 = (face6*100)/qtdLancamentos; } cout << "Face 1: " << face1 << " = % " << pcnt1 << endl; cout << "Face 2: " << face2 << " = % " << pcnt2 << endl; cout << "Face 3: " << face3 << " = % " << pcnt3 << endl; cout << "Face 4: " << face4 << " = % " << pcnt4 << endl; cout << "Face 5: " << face5 << " = % " << pcnt5 << endl; cout << "Face 6: " << face6 << " = % " << pcnt6 << endl; cout << "Lançamentos: " << qtdLancamentos << endl; return 0; }
true
db29f2c3058c2a009996c084f125138c6c542185
C++
PacktPublishing/CPP-Reactive-Programming
/Chapter06/source_code/Streams-master/test/AlgebraTest.cpp
UTF-8
7,898
3.046875
3
[ "MIT" ]
permissive
#include <Stream.h> #include <gmock/gmock.h> using namespace testing; using namespace stream; using namespace stream::op; // Arithmetic operators TEST(AlgebraTest, Negate) { EXPECT_THAT(-MakeStream::from({1, 2, 3}) | to_vector(), ElementsAre(-1, -2, -3)); } TEST(AlgebraTest, Addition) { EXPECT_THAT((MakeStream::from({1, 2, 3}) + MakeStream::from({-1, 0, 5})) | to_vector(), ElementsAre(0, 2, 8)); EXPECT_THAT((MakeStream::from({1, 2, 3}) + 5) | to_vector(), ElementsAre(6, 7, 8)); EXPECT_THAT((5 + MakeStream::from({1, 2, 3})) | to_vector(), ElementsAre(6, 7, 8)); } TEST(AlgebraTest, Subtraction) { EXPECT_THAT((MakeStream::from({1, 2, 3}) - MakeStream::from({-1, 0, 5})) | to_vector(), ElementsAre(2, 2, -2)); EXPECT_THAT((MakeStream::from({1, 2, 3}) - 5) | to_vector(), ElementsAre(-4, -3, -2)); EXPECT_THAT((5 - MakeStream::from({1, 2, 3})) | to_vector(), ElementsAre(4, 3, 2)); } TEST(AlgebraTest, Multiplication) { EXPECT_THAT((MakeStream::from({1, 2, 3}) * MakeStream::from({-1, 0, 5})) | to_vector(), ElementsAre(-1, 0, 15)); EXPECT_THAT((MakeStream::from({1, 2, 3}) * 5) | to_vector(), ElementsAre(5, 10, 15)); EXPECT_THAT((5 * MakeStream::from({1, 2, 3})) | to_vector(), ElementsAre(5, 10, 15)); } TEST(AlgebraTest, Division) { EXPECT_THAT((MakeStream::from({5, 10, 15}) / MakeStream::from({5, 1, 3})) | to_vector(), ElementsAre(1, 10, 5)); EXPECT_THAT((MakeStream::from({5, 10, 15}) / 5.0) | to_vector(), ElementsAre(1, 2, 3)); EXPECT_THAT((1.0 / MakeStream::from({1, 2, 4})) | to_vector(), ElementsAre(1, .5, .25)); } TEST(AlgebraTest, Modulus) { EXPECT_THAT((MakeStream::from({12, 13, 14}) % MakeStream::from({6, 5, 4})) | to_vector(), ElementsAre(0, 3, 2)); EXPECT_THAT((MakeStream::from({5, 6, 7}) % 5) | to_vector(), ElementsAre(0, 1, 2)); EXPECT_THAT((5 % MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(2, 1, 0)); } // Comparison Operators TEST(AlgebraTest, Equality) { EXPECT_THAT((MakeStream::from({5, 6}) == MakeStream::from({5, 4})) | to_vector(), ElementsAre(true, false)); EXPECT_THAT((MakeStream::from({0, 3, 0}) == 3) | to_vector(), ElementsAre(false, true, false)); EXPECT_THAT((3 == MakeStream::from({0, 3, 0})) | to_vector(), ElementsAre(false, true, false)); } TEST(AlgebraTest, Inequality) { EXPECT_THAT((MakeStream::from({5, 6}) != MakeStream::from({5, 4})) | to_vector(), ElementsAre(false, true)); EXPECT_THAT((MakeStream::from({0, 3, 0}) != 3) | to_vector(), ElementsAre(true, false, true)); EXPECT_THAT((3 != MakeStream::from({0, 3, 0})) | to_vector(), ElementsAre(true, false, true)); } TEST(AlgebraTest, LessThan) { EXPECT_THAT((MakeStream::from({4, 5, 6}) < MakeStream::from({6, 5, 4})) | to_vector(), ElementsAre(true, false, false)); EXPECT_THAT((MakeStream::from({0, 1, 2}) < 1) | to_vector(), ElementsAre(true, false, false)); EXPECT_THAT((1 < MakeStream::from({0, 1, 2})) | to_vector(), ElementsAre(false, false, true)); } TEST(AlgebraTest, LessThanOrEqual) { EXPECT_THAT((MakeStream::from({4, 5, 6}) <= MakeStream::from({6, 5, 4})) | to_vector(), ElementsAre(true, true, false)); EXPECT_THAT((MakeStream::from({0, 1, 2}) <= 1) | to_vector(), ElementsAre(true, true, false)); EXPECT_THAT((1 <= MakeStream::from({0, 1, 2})) | to_vector(), ElementsAre(false, true, true)); } TEST(AlgebraTest, GreaterThan) { EXPECT_THAT((MakeStream::from({4, 5, 6}) > MakeStream::from({6, 5, 4})) | to_vector(), ElementsAre(false, false, true)); EXPECT_THAT((MakeStream::from({0, 1, 2}) > 1) | to_vector(), ElementsAre(false, false, true)); EXPECT_THAT((1 > MakeStream::from({0, 1, 2})) | to_vector(), ElementsAre(true, false, false)); } TEST(AlgebraTest, GreaterThanOrEqual) { EXPECT_THAT((MakeStream::from({4, 5, 6}) >= MakeStream::from({6, 5, 4})) | to_vector(), ElementsAre(false, true, true)); EXPECT_THAT((MakeStream::from({0, 1, 2}) >= 1) | to_vector(), ElementsAre(false, true, true)); EXPECT_THAT((1 >= MakeStream::from({0, 1, 2})) | to_vector(), ElementsAre(true, true, false)); } // Logical operators TEST(AlgebraTest, LogicalNot) { EXPECT_THAT(!MakeStream::from({true, false}) | to_vector(), ElementsAre(false, true)); } TEST(AlgebraTest, LogicalAnd) { EXPECT_THAT((MakeStream::from({true, true, false, false}) && MakeStream::from({true, false, true, false})) | to_vector(), ElementsAre(true, false, false, false)); EXPECT_THAT((MakeStream::from({true, false}) && true) | to_vector(), ElementsAre(true, false)); EXPECT_THAT((false && MakeStream::from({true, false})) | to_vector(), ElementsAre(false, false)); } TEST(AlgebraTest, LogicalOr) { EXPECT_THAT((MakeStream::from({true, true, false, false}) || MakeStream::from({true, false, true, false})) | to_vector(), ElementsAre(true, true, true, false)); EXPECT_THAT((MakeStream::from({true, false}) || true) | to_vector(), ElementsAre(true, true)); EXPECT_THAT((false || MakeStream::from({true, false})) | to_vector(), ElementsAre(true, false)); } // Bitwise operators TEST(AlgebraTest, BitwiseNot) { EXPECT_THAT(~MakeStream::from({0, 1, 2, 3}) | to_vector(), ElementsAre(~0, ~1, ~2, ~3)); } TEST(AlgebraTest, BitwiseAnd) { EXPECT_THAT((MakeStream::from({3, 4}) & MakeStream::from({5, 6})) | to_vector(), ElementsAre(3 & 5, 4 & 6)); EXPECT_THAT((MakeStream::from({3, 4, 5}) & 12) | to_vector(), ElementsAre(3 & 12, 4 & 12, 5 & 12)); EXPECT_THAT((12 & MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(12 & 3, 12 & 4, 12 & 5)); } TEST(AlgebraTest, BitwiseOr) { EXPECT_THAT((MakeStream::from({3, 4}) | MakeStream::from({5, 6})) | to_vector(), ElementsAre(3 | 5, 4 | 6)); EXPECT_THAT((MakeStream::from({3, 4, 5}) | 12) | to_vector(), ElementsAre(3 | 12, 4 | 12, 5 | 12)); EXPECT_THAT((12 | MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(12 | 3, 12 | 4, 12 | 5)); } TEST(AlgebraTest, BitwiseXor) { EXPECT_THAT((MakeStream::from({3, 4}) ^ MakeStream::from({5, 6})) | to_vector(), ElementsAre(3 ^ 5, 4 ^ 6)); EXPECT_THAT((MakeStream::from({3, 4, 5}) ^ 12) | to_vector(), ElementsAre(3 ^ 12, 4 ^ 12, 5 ^ 12)); EXPECT_THAT((12 ^ MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(12 ^ 3, 12 ^ 4, 12 ^ 5)); } TEST(AlgebraTest, BitShiftLeft) { EXPECT_THAT((MakeStream::from({3, 4}) << MakeStream::from({5, 6})) | to_vector(), ElementsAre(3 << 5, 4 << 6)); EXPECT_THAT((MakeStream::from({3, 4, 5}) << 12) | to_vector(), ElementsAre(3 << 12, 4 << 12, 5 << 12)); EXPECT_THAT((12 << MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(12 << 3, 12 << 4, 12 << 5)); } TEST(AlgebraTest, BitShiftRight) { EXPECT_THAT((MakeStream::from({3, 4}) >> MakeStream::from({5, 6})) | to_vector(), ElementsAre(3 >> 5, 4 >> 6)); EXPECT_THAT((MakeStream::from({3, 4, 5}) >> 12) | to_vector(), ElementsAre(3 >> 12, 4 >> 12, 5 >> 12)); EXPECT_THAT((12 >> MakeStream::from({3, 4, 5})) | to_vector(), ElementsAre(12 >> 3, 12 >> 4, 12 >> 5)); }
true
a2a66ff417d2aab3f9f0b549c8d742f951f4155b
C++
ldcduc/CS202
/Week_5/ex01/function.h
UTF-8
1,184
3.0625
3
[]
no_license
#include <algorithm> #include <iostream> #include <fstream> #include <string> #include <cmath> using namespace std; class Staff{ private: int type; protected: string name; static int base_salary, paper_support, project_salary; double salary = 0; public: virtual void print() = 0; virtual void calc_salary() = 0; virtual void input(istream&) = 0; static void set_static(int salary, int paper, int project); double get_salary(); }; class TA: public Staff{ private: int work_hour = 0; public: friend istream& operator>> (istream& is, TA& src); virtual void print(); virtual void calc_salary(); virtual void input(istream&); }; class Lecturer: public Staff{ private: int lecturing_hour = 0, paper_num = 0; public: friend istream& operator>> (istream& is, Lecturer& src); virtual void print(); virtual void calc_salary(); virtual void input(istream&); }; class Researcher: public Staff{ private: int research_project = 0, paper_num = 0; public: friend istream& operator>> (istream& is, Researcher& src); virtual void print(); virtual void calc_salary(); virtual void input(istream&); };
true
920a240d912fc9d1ec134d29bea782433570c035
C++
aparvizi/parking
/Sensors/Parking_Sensor.ino
UTF-8
3,115
2.78125
3
[]
no_license
/* An Arduino code example for interfacing with the HMC5883 by: Jordan McConnell SparkFun Electronics created on: 6/30/11 license: OSHW 1.0, http://freedomdefined.org/OSHW Analog input 4 I2C SDA Analog input 5 I2C SCL */ const float ALPHA = 0.2; const float BASELINE_ALPHA = 0.001; //const int THRESHOLD = 10; //original value const int THRESHOLD = 1; //for indoor debugging //const int WINDOW = 70; //original value const int WINDOW = 10; //for indoor debugging const int SEED_VALUES = 4; const String ID = "0"; int count; boolean upper; boolean lower; float baselineY; float smoothY; int calmCount; #include <Wire.h> //I2C Arduino Library #define address 0x1E //0011110b, I2C 7bit address of HMC5883 void setup(){ count = 0; baselineY = 0; smoothY = 0; calmCount = 0; lower = upper = false; //Initialize Serial and I2C communications Serial.begin(57600); Wire.begin(); Serial.println("starting operation"); //Put the HMC5883 IC into the correct operating mode Wire.beginTransmission(address); //open communication with HMC5883 Wire.write(0x02); //select mode register Wire.write(0x00); //continuous measurement mode Wire.endTransmission(); // Initialize baseline int x, y, z; int n = 0; while (n < SEED_VALUES){ Wire.beginTransmission(address); Wire.write(0x03); //select register 3, X MSB register Wire.endTransmission(); //Read data from each axis, 2 registers per axis Wire.requestFrom(address, 6); if(6<=Wire.available()){ x = Wire.read()<<8; //X msb x |= Wire.read(); //X lsb z = Wire.read()<<8; //Z msb z |= Wire.read(); //Z lsb y = Wire.read()<<8; //Y msb y |= Wire.read(); //Y lsb baselineY += y; n++; } } baselineY /= SEED_VALUES; Serial.println("setup finished"); } void loop(){ int x,y,z; //triple axis data //Tell the HMC5883 where to begin reading data Wire.beginTransmission(address); Wire.write(0x03); //select register 3, X MSB register Wire.endTransmission(); //Read data from each axis, 2 registers per axis Wire.requestFrom(address, 6); if(6<=Wire.available()){ x = Wire.read()<<8; //X msb x |= Wire.read(); //X lsb z = Wire.read()<<8; //Z msb z |= Wire.read(); //Z lsb y = Wire.read()<<8; //Y msb y |= Wire.read(); //Y lsb } baselineY = ((1 - BASELINE_ALPHA) * baselineY) + ((BASELINE_ALPHA) * y); smoothY = ((1 - ALPHA) * smoothY) + (ALPHA * y); if (smoothY > (baselineY + THRESHOLD) || smoothY < (baselineY - THRESHOLD)) { if ((!upper) && (!lower)) { if (smoothY > (baselineY + THRESHOLD)) { upper = true; count++; } else if (smoothY < (baselineY - THRESHOLD)) { lower = true; count--; } // Calculate checksum String output = ID + ":" + (String)count + ":" + (String)100; int sum = output.length(); // PRINTING DONE HERE Serial.println(output + "!" + (String)sum + ";"); } } else { calmCount++; } if (calmCount >= WINDOW) { calmCount = 0; upper = false; lower = false; } delay(10); }
true
30b2878fa27e0984fb6aa966335f1f50b6ac0664
C++
SVBoyadzhieva18/TheGods
/Application/Aqua/presentation.cpp
UTF-8
7,216
3.28125
3
[]
no_license
<<<<<<< HEAD:Application/Aqua/Aqua/presentation.cpp #include "presentation.h" #include <iostream> using namespace std; void showDolphin(DOLPHINS dolphin, DATE date) { cout << endl; cout << "Sea station: " << dolphin.seaStation << endl; cout << "Dolphin Type: " << dolphin.dolphinType << endl; cout << "Chip Number: " << dolphin.chipNumber << endl; cout << "From: " << date.day << "/" << date.month << "/" << date.year << endl; cout << endl; } void showAllDolphins(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "You have entered the following dolphins:" << endl; for (int i = 0; i < dolphinsIndex; i++) { showDolphin(dolphin[i], date[i]); } } bool showSortMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "\n---------\n"; cout << "Sort Menu" << endl; cout << "---------\n"; cout << "1 - Sort by alphabetical order (sea station)" << endl; cout << "2 - Sort by alphabetical order (dolphin type)" << endl; cout << "3 - Go back to the main menu" << endl; cout << "\nYour choice: "; int userChoice; cin >> userChoice; switch (userChoice) { case 1: sortAlphabeticallySeaStations(dolphin, date, dolphinsIndex); break; case 2: sortAlphabeticallyDolphinType(dolphin, date, dolphinsIndex); break; case 3: return false; } return true; } bool showSearchMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "\n--------------\n"; cout << "Searching Menu" << endl; cout << "--------------\n"; cout << "1 - Search by sea station" << endl; cout << "2 - Search by dolphin type" << endl; cout << "3 - Search by chip number" << endl; cout << "4 - Go back to the main menu" << endl; cout << "\nYour choice: "; int userChoice; cin >> userChoice; switch (userChoice) { case 1: searchBySeaStation(dolphin, date, dolphinsIndex); break; case 2: searchByDolphinType(dolphin, date, dolphinsIndex); break; case 3: searchByChipNumber(dolphin, date, dolphinsIndex); break; case 4: return false; } return true; } bool showMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { int c; cout << "\n---------"; cout << "\nMain menu\n"; cout << "---------\n\n"; cout << "1 - Add a dolphin\n"; cout << "2 - View all dolphins\n"; cout << "3 - Sort text\n"; cout << "4 - Search text\n"; cout << "5 - Quit program\n"; cout << "\nYour choice: "; cin >> c; switch (c) { case 1: addDolphin(dolphin, date, dolphinsIndex); break; case 2: showAllDolphins(dolphin, date, dolphinsIndex); break; case 3: { bool doShowSortMenu = true; do { doShowSortMenu = showSortMenu(dolphin, date, dolphinsIndex); } while (doShowSortMenu); break; } case 4: { bool doShowSearchMenu = true; do { doShowSearchMenu = showSearchMenu(dolphin, date, dolphinsIndex); } while (doShowSearchMenu); break; } break; case 5: return false; break; } return true; } void showSeaStationsMenu() { cout << "\n--------------------------\n"; cout << "Stations in The Black Sea" << endl; cout << "--------------------------\n"; cout << "1 - Bulgaria" << endl; cout << "2 - Ukraine" << endl; cout << "3 - Russia" << endl; cout << "4 - Turkey" << endl; cout << "5 - Georgia" << endl; cout << "6 - Romania" << endl; cout << endl; } void showDolphinTypesMenu() { cout << "\n-----------------------------------\n"; cout << "Types of dolphins in The Black Sea" << endl; cout << "-----------------------------------\n"; cout << "1 - Bottlenose dolphin" << endl; cout << "2 - Common dolphin" << endl; cout << "3 - Harbor porpoises" << endl; ======= #include "presentation.h" #include <iostream> using namespace std; void showDolphin(DOLPHINS dolphin, DATE date) { cout << endl; cout << "Sea station: " << dolphin.seaStation << endl; cout << "Dolphin Type: " << dolphin.dolphinType << endl; cout << "Chip Number: " << dolphin.chipNumber << endl; cout << "From: " << date.day << "/" << date.month << "/" << date.year << endl; cout << endl; } void showAllDolphins(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "You have entered the following dolphins:" << endl; for (int i = 0; i < dolphinsIndex; i++) { showDolphin(dolphin[i], date[i]); } } bool showSortMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "Sort Menu" << endl; cout << "1 - Sort by alphabetical order (sea station)" << endl; cout << "2 - Sort by alphabetical order (dolphin type)" << endl; cout << "3 - Go back to the main menu" << endl; cout << "Your choice: "; int userChoice; cin >> userChoice; switch (userChoice) { case 1: sortAlphabeticallySeaStations(dolphin, date, dolphinsIndex); break; case 2: sortAlphabeticallyDolphinType(dolphin, date, dolphinsIndex); break; case 3: return false; default: cout << "Enter a valid number!" << endl; showSearchMenu(dolphin, date, dolphinsIndex); break; } return true; } bool showSearchMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { cout << endl; cout << "Searching Menu" << endl; cout << "1 - Search by sea station" << endl; cout << "2 - Search by dolphin type" << endl; cout << "3 - Search by chip number" << endl; cout << "4 - Go back to the main menu" << endl; cout << "\nYour choice: "; int userChoice; cin >> userChoice; switch (userChoice) { case 1: searchBySeaStation(dolphin, date, dolphinsIndex); break; case 2: searchByDolphinType(dolphin, date, dolphinsIndex); break; case 3: searchByChipNumber(dolphin, date, dolphinsIndex); break; case 4: return false; default: cout << "Enter a valid number!" << endl; showSearchMenu(dolphin, date, dolphinsIndex); break; } return true; } bool showMenu(DOLPHINS* dolphin, DATE* date, int& dolphinsIndex) { int c; cout << "\nMain menu\n\n"; cout << "1 - Add a dolphin\n"; cout << "2 - View all dolphins\n"; cout << "3 - Sort text\n"; cout << "4 - Search text\n"; cout << "5 - Quit program\n"; cout << "Your choice: "; cin >> c; switch (c) { case 1: addDolphin(dolphin, date, dolphinsIndex); break; case 2: showAllDolphins(dolphin, date, dolphinsIndex); break; case 3: { bool doShowSortMenu = true; do { doShowSortMenu = showSortMenu(dolphin, date, dolphinsIndex); } while (doShowSortMenu); break; } case 4: { bool doShowSearchMenu = true; do { doShowSearchMenu = showSearchMenu(dolphin, date, dolphinsIndex); } while (doShowSearchMenu); break; } case 5: return false; break; default: cout << "Enter a valid number!" << endl; showMenu(dolphin, date, dolphinsIndex); break; } return true; } void showSeaStationsMenu() { cout << "Stations in The Black Sea" << endl << endl; cout << "1 - Bulgaria" << endl; cout << "2 - Ukraine" << endl; cout << "3 - Russia" << endl; cout << "4 - Turkey" << endl; cout << "5 - Georgia" << endl; cout << "6 - Romania" << endl; cout << endl; } void showDolphinTypesMenu() { cout << "Types of dolphins in The Black Sea" << endl << endl; cout << "1 - Bottlenose dolphin" << endl; cout << "2 - Common dolphin" << endl; cout << "3 - Harbor porpoises" << endl; >>>>>>> cc34339f3ec76a50e32219fd0909793e2252f1f3:Application/Aqua/presentation.cpp }
true
32515057602c93bb9a14b898485816c751ce26db
C++
matheusbg8/SonarGraph
/trunk/SonarGaussian/CSVReader/CSVData.cpp
UTF-8
3,329
3.015625
3
[]
no_license
#include <CSVReader/CSVData.h> #include <string> CSVData::CSVData(): m_currentMsgID(0u) { } CSVData::~CSVData() { clearMsgs(); } unsigned CSVData::fieldCount() { return m_types.size(); } unsigned CSVData::msgCount() { return m_values.size(); } CSV_TYPE CSVData::fieldType(unsigned fieldID) { if(fieldID < m_types.size()) { return m_types[fieldID]; } return CSV_INVALID; } int CSVData::getField(unsigned fieldID, void *value) { return getField(m_currentMsgID, fieldID, value); } int CSVData::getField(unsigned msgID, unsigned fieldID, void *value) { if(fieldID < m_types.size() && msgID < m_values.size()) { switch(m_types[fieldID]) { case CSV_STRING: *((std::string*) value) = *((std::string*) m_values[msgID][fieldID]); break; case CSV_INT: *((int*) value) = *((int*) m_values[msgID][fieldID]); break; case CSV_LLU: *((long long unsigned int*) value) = *((long long unsigned int*) m_values[msgID][fieldID]); break; case CSV_FLOAT: *((float*) value) = *((float*) m_values[msgID][fieldID]); break; case CSV_DOUBLE: *((double*) value) = *((double*) m_values[msgID][fieldID]); break; case CSV_INVALID: default: // Nothing to do break; } } return 0; } void CSVData::getMsg(CSV_MSG msgInfo, ...) { unsigned msgID=0; va_list vl; va_start(vl,msgInfo); if(msgInfo == CSV_SPECIFIC_MSG) msgID = va_arg(vl,int); else msgID = m_currentMsgID; for(unsigned fieldID=0;fieldID<m_types.size();fieldID++) { if(m_types[fieldID] != CSV_IGNORE) getField(msgID, fieldID , va_arg(vl,void*)); } va_end(vl); } void CSVData::clearMsgs() { unsigned msgID, fieldID; m_currentMsgID=0u; for(msgID = 0 ; msgID < m_values.size() ; msgID++) { for(fieldID = 0 ; fieldID < m_types.size(); fieldID++) { // Interpret and delete field switch(m_types[fieldID]) { case CSV_STRING: delete (std::string*) m_values[msgID][fieldID]; break; case CSV_INT: delete (int*) m_values[msgID][fieldID]; break; case CSV_LLU: delete (long long unsigned int*) m_values[msgID][fieldID]; break; case CSV_FLOAT: delete (float*) m_values[msgID][fieldID]; break; case CSV_DOUBLE: delete (double*) m_values[msgID][fieldID]; break; case CSV_INVALID: default: // Nothing to do break; } } } m_values.clear(); } /** * @brief * If is not last menssage, go to next menssage. * * @return bool - true If we went to next menssage, * false otherwise. */ bool CSVData::nextMsg() { if(m_currentMsgID < m_values.size()) { m_currentMsgID++; return true; } return false; } void CSVData::toBegin() { m_currentMsgID = 0u; }
true
51109f17849e34d2007a1ceb4d79f499a4a8795e
C++
douglasbravimbraga/programming-contests
/UVa Online Judge/10264 - The Most Potent Corner/main.cpp
UTF-8
594
2.78125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int n; while (cin >> n) { vector<int> v; for (int i = 0; i < pow(2, n); i++) { int num; cin >> num; v.push_back(num); } vector<int> potent; for (int i = 0; i < pow(2, n); i++) { int pot = 0; for (int j = 0; j < n; j++) { pot += v[i ^ (1 << j)]; } potent.push_back(pot); } int maximal = 0; for (int i = 0; i < pow(2, n); i++) { int pot = 0; for (int j = 0; j < n; j++) maximal = max(maximal, potent[i] + potent[i ^ (1 << j)]); } cout << maximal << endl; } return 0; }
true
7429bc54e528e7f76336966957d0bdc6ccb83347
C++
maidoufu/sim_path_planner
/src/StateGrid.h
UTF-8
1,396
2.640625
3
[]
no_license
#ifndef STATEGRID_H #define STATEGRID_H #include <boost/unordered_map.hpp> #include "Grid2D.h" #include "State.h" #include "OrientationLUT.h" class StateCell { public: StateCell() { } void insert(const StatePtr& s) { m_stateVector.push_back(s); } bool find(const StatePtr& s) const { for (size_t i = 0; i < m_stateVector.size(); ++i) { if (m_stateVector.at(i) == s) { return true; } } return false; } std::vector<StatePtr>& stateVector(void) { return m_stateVector; } friend class StateGrid; private: std::vector<StatePtr> m_stateVector; }; class StateGrid : public Grid2D<StateCell> { public: StateGrid(double width, double resolution, const OrientationLUT& orientationLUT); void precompute(double z, boost::unordered_map<int, std::vector<PrimitivePathPtr> >& lutPredecessors, boost::unordered_map<int, std::vector<PrimitivePathPtr> >& lutSuccessors, float reversePenaltyFactor = 2.0f); bool isVisited(const LatticePose& p) const; bool outsideBounds(const LatticePose& p) const; StatePtr& at(const LatticePose& s); std::vector<StatePtr> containedStates(void) const; private: OrientationLUT m_orientationLUT; }; #endif
true
7c0c4cd7c8c4e80582261d4dd475108538347888
C++
ft-yjh/c-
/c++7/c++7/Point.cpp
GB18030
214
2.5625
3
[]
no_license
#include"point.h" //x void Point:: set_x (int x) { m_x = x; } //ȡx int Point:: get_x() { return m_x; } //y void Point:: set_y(int y) { m_y = y; } //ȡy int Point:: get_y() { return m_y; }
true