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
ca56e691be804b9ca51a433fd03d22091bf02370
C++
OC-MCS/p2finalproject-01-KylerSeal99
/game/Ship.cpp
UTF-8
2,400
3
3
[]
no_license
#include "Ship.h" // Constructor Ship::Ship(SpriteMgr &spriteManager, Sprite &wall, Vector2f newPos, RenderWindow &window) { // Ships position float shipX = window.getSize().x / 2.0f; float shipY = window.getSize().y / 1.1f; spriteShip = spriteManager.getShipS(); spriteShip.setPosition(newPos); wallpaper = &wall; spriteMgr = &spriteManager; } // Moves the ship left and right when arrows are pressed respectivley void Ship::moveShip() { const float DISTANCE = 5.0; if (Keyboard::isKeyPressed(Keyboard::Left)) { // left arrow is pressed: move our ship left 5 pixels // 2nd parm is y direction. We don't want to move up/down, so it's zero. if (spriteShip.getPosition().x > -5) { spriteShip.move(-DISTANCE, 0); } } else if (Keyboard::isKeyPressed(Keyboard::Right)) { // right arrow is pressed: move our ship right 5 pixels if (spriteShip.getPosition().x < 760) { spriteShip.move(DISTANCE, 0); } } } // Draws the ship void Ship::draw(RenderWindow &window) { window.draw(spriteShip); list<Missile>::iterator iter; for (iter = missiles.begin(); iter != missiles.end(); iter++) { iter->draw(window); } } // Shoots a missile from the ships current position void Ship::shootMissile() { Missile newMissile(spriteMgr, spriteShip.getPosition().x + 18, spriteShip.getPosition().y); missiles.push_back(newMissile); } // Checks if a missile is off screen void Ship::checkMissiles() { list<Missile>::iterator iter; for (iter = missiles.begin(); iter != missiles.end(); iter++ ) { iter->moveMissile(); } for (iter = missiles.begin(); iter != missiles.end(); ) { if (!wallpaper->getGlobalBounds().contains(iter->getPos())) { iter = missiles.erase(iter); } else iter++; } } // Clears all missiles on screen after ship is hit by bomb and reset void Ship::spawnShip() { missiles.clear(); } // Checks if missile hit an alien bool Ship::missileHitAlien(FloatRect bounds) { bool result = false; list<Missile>::iterator iter; iter = missiles.begin(); while (iter != missiles.end()) { if (bounds.contains(iter->getPos())) { iter = missiles.erase(iter); // delete the missile result = true; } else { iter++; } } return result; } // Getters for the ships position and bounds checking Vector2f Ship::getPos() { return spriteShip.getPosition(); } FloatRect Ship::getBounds() { return spriteShip.getGlobalBounds(); }
true
e77ec61a6a49fb6f0707ffd6842d551b9f0f1024
C++
stoneheart93/Leetcode
/[344]Reverse String.cpp
UTF-8
1,165
3.4375
3
[]
no_license
//Write a function that reverses a string. The input string is given as an array // of characters s. // // // Example 1: // Input: s = ["h","e","l","l","o"] //Output: ["o","l","l","e","h"] // Example 2: // Input: s = ["H","a","n","n","a","h"] //Output: ["h","a","n","n","a","H"] // // // Constraints: // // // 1 <= s.length <= 105 // s[i] is a printable ascii character. // // // // Follow up: Do not allocate extra space for another array. You must do this by // modifying the input array in-place with O(1) extra memory. // Related Topics Two Pointers String // 👍 2467 👎 782 //leetcode submit region begin(Prohibit modification and deletion) class Solution { void reverseStringUtil(vector<char>& s, int start, int end) { while(start < end) { char temp = s[start]; s[start] = s[end]; s[end] = temp; start++; end--; } } public: void reverseString(vector<char>& s) { reverseStringUtil(s, 0, s.size() - 1); } }; //Time Complexity: O(n) //Space Complexity: O(1) //leetcode submit region end(Prohibit modification and deletion)
true
d71f6b7018cb8cc891ed80f3bcbd7ea517f67130
C++
mateuszpruchniak/gpuprocessor
/OpenCL/src/oclGPUProcessor/inc/MedianFilter.h
UTF-8
691
2.546875
3
[]
no_license
/*! * \file MedianFilter.h * \brief File contains class Median filter. * \author Mateusz Pruchniak * \date 2010-05-05 */ #pragma once #include "NonLinearFilter.h" /*! * \class MedianFilter * \brief Median filter. * \author Mateusz Pruchniak * \date 2010-05-05 */ class MedianFilter : public NonLinearFilter { public: /*! * Destructor. */ ~MedianFilter(void); /*! * Constructor, creates a program object for a context, loads the source code (.cl files) and build the program. */ MedianFilter(cl_context GPUContext ,GPUTransferManager* transfer); /*! * Start filtering. Launching GPU processing. */ bool filter(cl_command_queue GPUCommandQueue); };
true
973418eaaa8a5691af935ded9d7972fcf1b73850
C++
ariaBennett/ProjectEuler18
/Project Euler Problem 18/Project Euler Problem 18.cpp
UTF-8
1,984
3.046875
3
[]
no_license
//By starting at the top of the triangle below and moving to adjacent numbers // on the row below, the maximum total from top to bottom is 23. // //3 //7 4 //2 4 6 //8 5 9 3 // //That is, 3 + 7 + 4 + 9 = 23. // //Find the maximum total from top to bottom of the triangle below: // // //NOTE: As there are only 16384 routes, it is possible to solve this problem // by trying every route. However, Problem 67, is the same challenge // with a triangle containing one-hundred rows; it cannot be solved by // brute force, and requires a clever method! ;o) #include "stdafx.h" #include <iostream> #include <array> using namespace std; void pause() { cin.clear(); cin.ignore(255, '\n'); cin.get(); } void getPath(int &path1, int &path2, const int &start) { } int _tmain(int argc, _TCHAR* argv[]) { // 1485 is the maximum possible number assuming 99 for every number // with 15 rows. // The program starts from this number and counts backwards, looking // for potential paths that will satisfy the current number it is // searching for. int row1[] = {75}; int row2[] = {95, 64}; int row3[] = {17, 47, 82}; int row4[] = {18, 35, 87, 10}; int row5[] = {20, 4, 82, 47, 65}; int row6[] = {19, 1, 23, 75, 3, 34}; int row7[] = {88, 2, 77, 73, 07, 63, 67}; int row8[] = {99, 65, 4, 28, 06, 16, 70, 92}; int row9[] = {41, 41, 26, 56, 83, 40, 80, 70, 33}; int row10[] = {41, 48, 72, 33, 47, 32, 37, 16, 94, 29}; int row11[] = {53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14}; int row12[] = {70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57}; int row13[] = {91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48}; int row14[] = {63, 66, 4, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31}; int row15[] = {4, 62, 98, 27, 23, 9, 70, 98, 73, 93, 38, 53, 60, 4, 23}; //for (int i = 1485; i > 0; i--) //{ // int buffer = 0; // int tolerance = 1485 - i; // cout << buffer << endl; //} for (int i = 0; i < sizeof(row1); i++) { } cout << sizeof(row15)/4; pause(); return 0; }
true
f2849078622e34ec806dab3fdf4bd829225f4fcc
C++
maxim76/dialogic_sip
/callserver/ssp_scp_interface.cpp
UTF-8
2,830
2.78125
3
[]
no_license
#include "ssp_scp_interface.hpp" namespace ssp_scp { // TODO: channel передается как параметр в process(), а остальные параметры - извлекаются в конструкторе команды. Может все параметры брать в одном общем месте? class SCPCommandAnswer : public SCPCommand { public: SCPCommandAnswer() {} void process(unsigned int channel) override { // TODO: получать номер канала не через параметр? commands::Answer(channel); } std::string getCommandName() override { return "ANSWER"; } class Factory : public SCPCommandFactory { public: std::unique_ptr<SCPCommand> Construct(std::istream& in) const override { return std::unique_ptr<SCPCommandAnswer>(new SCPCommandAnswer()); } }; }; class SCPCommandDrop : public SCPCommand { public: SCPCommandDrop(RedirectionReason reason) : reason_(reason) {}; void process(unsigned int channel) override { // TODO: получать номер канала не через параметр? commands::DropCall(channel, reason_); } std::string getCommandName() override { return "DROP"; } class Factory : public SCPCommandFactory { public: std::unique_ptr<SCPCommand> Construct(std::istream& in) const override { RedirectionReason reason; in.read(reinterpret_cast<char*>(&reason), sizeof(reason)); return std::unique_ptr<SCPCommandDrop>(new SCPCommandDrop(reason)); } }; private: RedirectionReason reason_; }; class SCPCommandPlay : public SCPCommand { public: SCPCommandPlay(const std::string& fragment) : fragmentName_(fragment) {}; void process(unsigned int channel) override { // TODO: error handling commands::PlayFragment(channel, fragmentName_); } std::string getCommandName() override { return "PLAY"; } class Factory : public SCPCommandFactory { public: std::unique_ptr<SCPCommand> Construct(std::istream& in) const override { std::string fragment; uint16_t size; in.read(reinterpret_cast<char*>(&size), sizeof(size)); fragment.resize(size); in.read(&(fragment[0]), size); return std::unique_ptr<SCPCommandPlay>(new SCPCommandPlay(fragment)); } }; private: std::string fragmentName_; }; const SCPCommandFactory& SCPCommandFactory::GetFactory(int id) { static SCPCommandDrop::Factory dropFactory; static SCPCommandAnswer::Factory answerFactory; static SCPCommandPlay::Factory playFactory; static std::unordered_map<int, const SCPCommandFactory&> factories = { {SCPCommandCodes::CMD_DROP, dropFactory}, {SCPCommandCodes::CMD_ANSWER, answerFactory}, {SCPCommandCodes::CMD_PLAY, playFactory} }; return factories.at(id); } } // namespace ssp_scp
true
a9ce68ffb72248763c46dc3897696fddf2ecd69f
C++
lorenzomancini1/OOP-Exercises2018
/dumpV1/dump.cc
UTF-8
531
2.984375
3
[]
no_license
#include <stdio.h> #include "dump.h" void dump(int evN, int pN, float x, float y, float z, int* q, float* mx, float* my, float* mz){ //print event number and the decay point coordinates cout << evN << endl << x << ' ' << y << ' ' << z << ' ' << endl; // print number of particles cout << pN << endl; // loop over particles int i; for( i = 0; i < pN ; i++ ){ // print charge and momentum components cout << q[i] << ' ' << mx[i] << ' ' << my[i] << ' ' << mz[i] << endl; } return; }
true
d3ab593c8d5ab4763c86ffaf4eb4c1b9656edec8
C++
HaoLi-China/Mobility-Reconstruction
/image/image_serializer_ppm.cpp
UTF-8
2,667
2.96875
3
[]
no_license
#include "image_serializer_ppm.h" #include "image.h" #include "../basic/logger.h" #include <sstream> Image* ImageSerializer_ppm::serialize_read(std::istream& in) { // Read header char buff[256] ; std::string magic ; in >> magic ; if(magic != "P6") { Logger::err("PPM loader: cannot load this type of PPM") ; return nil ; } // read end of line in.getline(buff, 256) ; // read comments (# CREATOR etc...) do { in.getline(buff, 256) ; } while(buff[0] == '#') ; int width, height, max_comp_value ; std::istringstream line_in(buff) ; line_in >> width >> height ; in >> max_comp_value ; if(width < 1 || height < 1) { Logger::err("PPM loader") << "invalid image size: " << width << " x " << height << std::endl ; return nil ; } if(max_comp_value != 255) { Logger::err( "PPM loader: invalid max component value (should be 255)" ) ; return nil ; } in.getline(buff, 256) ; int image_size = width * height ; Image* result = new Image(Image::RGB, width, height) ; for(int i=0; i<image_size; i++) { char r,g,b ; in.get(r) ; in.get(g) ; in.get(b) ; result->base_mem()[3*i] = r ; result->base_mem()[3*i+1] = g ; result->base_mem()[3*i+2] = b ; } flip_image(*result) ; return result ; } bool ImageSerializer_ppm::read_supported() const { return true ; } bool ImageSerializer_ppm::serialize_write( std::ostream& out, const Image* image ) { if( image->color_encoding() != Image::RGB && image->color_encoding() != Image::RGBA ) { Logger::err("Image") << "PPM writer implemented for RGB or RGBA images only" << std::endl ; return false ; } out << "P6 " << std::endl ; out << "# CREATOR: Meshop" << std::endl ; out << image->width() << " " << image->height() << std::endl ; out << 255 << std::endl ; int image_height = image->height() ; int image_width = image->width() ; switch(image->color_encoding()) { case Image::RGB: for(int i=image_height-1; i>=0; i--) { for(int j = 0; j < image_width; j++){ out.put(image->base_mem()[3*(i*image_width + j)]) ; out.put(image->base_mem()[3*(i*image_width + j)+1]) ; out.put(image->base_mem()[3*(i*image_width + j)+2]) ; } } break ; case Image::RGBA: for(int i=image_height-1; i>=0; i--) { for(int j = 0; j < image_width; j++){ out.put(image->base_mem()[4*(i*image_width + j)]) ; out.put(image->base_mem()[4*(i*image_width + j)+1]) ; out.put(image->base_mem()[4*(i*image_width + j)+2]) ; } } break ; default: ogf_assert(false) ; break ; } return true ; } bool ImageSerializer_ppm::write_supported() const { return true ; }
true
a5c248676d9f8c05e40b9dee623a6dff23188b8c
C++
panmari/racpp2014
/core/tonemapper.h
UTF-8
291
2.65625
3
[]
no_license
#ifndef TONEMAPPER_H #define TONEMAPPER_H #include "film.h" #include "pngwriter.h" /** * Compresses a raw rendered {@link Film} to an image that can be displayed on typical 8-bit displays. */ class Tonemapper { public: virtual void process(Film &film) = 0; }; #endif // TONEMAPPER_H
true
6a106b622b26686c8b19f3b1f83266bbe59c4c5a
C++
TRYang/LeetCode
/pathSum.cc
UTF-8
584
3
3
[]
no_license
void find(TreeNode *root, int sum, vector<int> &cur, vector<vector<int> > &ret) { if (!root->left && !root->right) { if (sum == root->val) { cur.push_back(root->val); ret.push_back(cur); cur.pop_back(); } return; } cur.push_back(root->val); if (root->left) find(root->left, sum - root->val, cur, ret); if (root->right) find(root->right, sum - root->val, cur, ret); cur.pop_back(); } vector<vector<int> > pathSum(TreeNode *root, int sum) { vector<vector<int> > ret; if (!root) return ret; vector<int> cur; find(root, sum, cur, ret); }
true
b0f358fd38d76e808376c7325abbc71cb64817a9
C++
RaulPPelaez/ConvenientSignalFFT
/src/config.h
UTF-8
1,994
2.828125
3
[ "Beerware" ]
permissive
#ifndef FFTCONFIG_H #define FFTCONFIG_H #include"defines.h" #include<string.h> #include<sstream> #include<iostream> void print_help(); class CommandLineParser{ int m_argc; char **m_argv; public: enum OptionType {Required, Optional}; CommandLineParser(int argc, char **argv): m_argc(argc), m_argv(argv){} std::istringstream getArgumentOfFlag(const char *flag, OptionType type){ for(int i=1; i<m_argc; i++){ if(strcmp(flag, m_argv[i]) == 0){ std::string line; if(i == m_argc-1){ break; } for(int j=i+1; j<m_argc; j++){ line += m_argv[j]; line += " "; } std::istringstream ss(line); return ss; } } if(type == Required) throw std::runtime_error(("Option " + std::string(flag) + " not found").c_str()); return std::istringstream(); } }; enum class Device{cpu, gpu, def}; enum class Precision{single, dual, def}; enum class Normalization{amplitude, def}; struct Config{ int numberElements; double Fs = 1; Device device = Device::def; Precision precision = Precision::def; std::string file = "/dev/stdin"; Normalization normalization; void setDeviceFromString(std::string dev){ if(dev.compare("cpu") == 0){ device = Device::cpu; } else if(dev.compare("gpu") == 0){ device = Device::gpu; } else{ device = Device::def; } } void setPrecisionFromString(std::string prec){ if(prec.compare("float") == 0){ precision = Precision::single; } else if(prec.compare("double") == 0){ precision = Precision::dual; } else{ precision = Precision::def; } } void setNormalizationFromString(std::string norm){ if(norm.compare("amplitude") == 0){ normalization = Normalization::amplitude; } else{ normalization = Normalization::def; } } }; Config TryToGetConfigurationFromCommandLine(int argc, char **argv); Config getConfigurationFromCommandLine(int argc, char **argv); #endif
true
0302d5c8187e761109f59ec08ecb73446393f9e4
C++
soft-bugg/AuSyORe
/AuSyORe/CTexture.cpp
UTF-8
2,426
2.796875
3
[]
no_license
#include "stdafx.h" #include "CTexture.h" SDL_Window CTexture::*mWindow = nullptr; bool CTexture::loadFromFile(std::string path) { free(); _path = path; SDL_Texture* newTexture = nullptr; SDL_Surface* loadedSurface = IMG_Load(path.c_str()); if (loadedSurface == nullptr) std::cout << "-Unable to Load Image- Reason: " << IMG_GetError() << " -Path: " << path.c_str() << std::endl; else { SDL_SetColorKey(loadedSurface, SDL_TRUE, SDL_MapRGB(loadedSurface->format, 0xFF, 0x00, 0xFF)); newTexture = SDL_CreateTextureFromSurface(_renderer, loadedSurface); if (newTexture == nullptr) std::cout << "-Unable to Create Texture- Reason: " << SDL_GetError() << " -Path: " << path.c_str() << std::endl; else { _width = loadedSurface->w; _height = loadedSurface->h; } SDL_FreeSurface(loadedSurface); } _texture = newTexture; return _texture != nullptr; } bool CTexture::loadFromText(std::string textureText, SDL_Color textColor, TTF_Font *font) { free(); SDL_Surface* textSurface = TTF_RenderText_Solid(font, textureText.c_str(), textColor); if (textSurface == nullptr) std::cout << "-Unable to Create Surface Text- Reason: " << TTF_GetError() << std::endl; else { _texture = SDL_CreateTextureFromSurface(_renderer, textSurface); if (_texture == nullptr) std::cout << "-Unable to Create Texture Text- Reason: " << TTF_GetError() << std::endl; else { _width = textSurface->w; _height = textSurface->h; } SDL_FreeSurface(textSurface); } return _texture != nullptr; } void CTexture::free() { if (_texture != nullptr) { SDL_DestroyTexture(_texture); _texture = nullptr; _width = _height = 0; } } void CTexture::render(int x, int y, SDL_Rect* clip, double scaleW, double scaleH, int sW, int sH, double angle, SDL_Point center, SDL_RendererFlip flip) { SDL_Rect renderQuad = {x, y, _width, _height}; if (scaleW == 0) scaleW = 1; if (scaleH == 0) scaleH = 1; if (clip != nullptr) { if (sW != 0 && sH != 0) { renderQuad.w = sW; renderQuad.h = sH; } else { renderQuad.w = clip->w; renderQuad.h = clip->h; renderQuad.w *= static_cast<int>(scaleW); renderQuad.h *= static_cast<int>(scaleH); } } SDL_RenderCopyEx(_renderer, _texture, clip, &renderQuad, angle, &center, flip); } void CTexture::render(int x, int y, SDL_Rect *pos, SDL_Renderer *rend) { SDL_Rect renderQuad = {x, y, _width, _height}; SDL_RenderCopy(rend, _texture, &renderQuad, pos); }
true
3d62ad297ee62b181564dd90bd1ec10fe6f320a7
C++
natlehmann/taller-2010-2c-poker-servidor
/TP1_Server/Source/common_Mensajes.h
UTF-8
1,270
2.640625
3
[]
no_license
#ifndef MENSAJES_H_ #define MENSAJES_H_ // Mensajes recibidos por el Servidor #define SOY "SOY" #define ENTRA "ENTRA" #define SALE "SALE" #define FIN "FIN" // Mensajes recibidos por el Cliente #define SI "SI" #define NO "NO" #define ERRORS "ERROR" #include <iostream> #include <sstream> #include <stdio.h> #include <string> #include "common_General.h" using namespace std; class Mensajes { public: Mensajes(); virtual ~Mensajes(); // Mensajes enviados por el servidor static string msjBienvenida() {return "HOLA\n";}; static string msjSI() {return "SI\n";}; static string msjNO() {return "NO\n";}; static string msjFIN() {return "FIN\n";}; static string msjERROR() {return "ERROR\n";}; // Mensajes enviados por el cliente static string msjSOY(const int idCliente); // Metodos utilizados por el servidor static int identificarCliente(string& msjCli); // Mensaje del Cliente: "SOY i\n" static string responderMsjClie(string &msjCli, string &cmd, int &idPersona); // Metodos utilizados por el cliente static bool validarBienvenida(const string& msjSrv); static bool validarMsjServ(const string& msjSrv); private: static void parsearMsj(string &msj, string &cmd, int &id); }; #endif /*MENSAJES_H_*/
true
ebb867ad15af1b62721c17c9dd40ff9188e60424
C++
waterpaper/Stardew
/StardewValley_Api/tileMap.h
UHC
4,133
2.734375
3
[]
no_license
#pragma once #include "tile_Info.h" class tileMap { private: image *_tileMapImage; //Ÿϸʿ ̹ մϴ. bool _isTileMapImage; //Ÿϸʿ ̹ ִ Ǵմϴ string _tileMapImagePath; bTileMap _tileMap; //ü Ÿ ִ 迭̴.( ü Ÿϸ Ѵ.) vTileObject _tileObject; //ü Ʈ ִ ̴( Ʈ ũⰡ ŸϹٴڰ ٸ ü ÷̾ ȣۿϱ⶧ ) viTileObject _iTileObject; //Ʈ ͷ int _maxTileX, _maxTileY; //ü Ÿϸ ̴. HBRUSH green, red, blue, white, oBrush; public: tileMap(); ~tileMap(); HRESULT init(); void update(); void release(); void setTileMap(int tileSizeX, int tileSizeY); //  迭 Ҵ, ʱȭմϴ void addTileMapIamge(char *imageName); //Ÿϸʿ ̹ ߰մϴ void deleteTileMapImage(); //Ÿϸʿ ̹ մϴ void setTile(TagTile_TERRAIN btileMap, int x, int y, int num); //Ÿ üմϴ void addObject(TagTile_Object *tileObject); //Ʈ ߰մϴ void deleteObject(HDC hdc, int num); //Ʈ մϴ void clearObject(); //Ʈ ü մϴ bool getIsTerrain(int x, int y) { return _tileMap[y][x].isTerrain; }; bool getIsObject(int x, int y) { return _tileMap[y][x].isObject; }; bool getIsShader(int x, int y) { return _tileMap[y][x].isShader; }; bool getIsImage() { return _isTileMapImage; }; void setIsImage(bool isImage) { _isTileMapImage = isImage; }; string getImagePath() { return _tileMapImagePath; }; void setImagePath(string temp) { _tileMapImagePath = temp; }; //render void screenRenderTileMap(HDC hdc, int cameraX, int cameraY); //Ÿϸ ȭ鸸ŭ ٽ ׷ݴϴ void reDrawTileMap(HDC hdc); //Ÿϸ Ϻκ ٽ ׷ݴϴ(ij ̵ ) void reDrawTileMap_tile(HDC hdc, RECT rc); void reDrawTileMap(HDC hdc, int tileX, int tileY, int sizeX, int sizeY, bool isObject); //Ÿϸ Ϻκ ٽ ׷ݴϴ( ) void allRenderTileMap(HDC hdc, int num); //Ÿϸ ü ٽ ׷ݴϴ void debugRenderTileMap(HDC hdc, int cameraX, int cameraY); //Ÿ ȣ ׷ݴϴ void attributeRenderTileMap(HDC hdc); //Ÿ Ӽ ׷ݴϴ void attributeRenderTileMap(HDC hdc, int x, int y); //Ÿ Ӽ ׷ݴϴ void attributeRenderRectSelect(HDC hdc, TagTile_TERRAIN tile); //Ӽ Ǵ Ʈ Ӽ ´ ׷ݴϴ POINT getTileMapSize() { return POINT{ _maxTileX,_maxTileY }; }; //Ÿϸ ȯ bTileMap getTileMap() { return _tileMap; }; TagTile_TERRAIN getTileMap(int x, int y) { return _tileMap[y][x]; }; vTileObject getTileObject() { return _tileObject; }; TagTile_Object *getTileObject(int num) { return _tileObject[num]; }; TILE_TERRAINKIND kindSelectTerrain(int index, int frameX, int frameY); //Ÿ ִ Լ void setKindTerrian(TILE_TERRAINKIND kind, int x, int y) { _tileMap[y][x].tile_terrainKind = kind; }; TILE_TERRAINKIND getKindTerrian(int x, int y) { return _tileMap[y][x].tile_terrainKind; }; void kindSelectObject(TagTile_Object *object, int index); //Ʈ Ư ִ Լ void setKindObject(TILE_OBJECTKIND kind, int num) { _tileObject[num]->tile_objectKind = kind; }; TILE_OBJECTKIND getKindObject(int num) { return _tileObject[num]->tile_objectKind; }; void setTileImage(int x, int y, int num, const char *keyName); void setObjectFrame(int num, int frameX, int frameY); void setObjectHp(int i, int x) { _tileObject[i]->hp = x; }; };
true
c70f3bdf37df2240722b4494db127f86865d1f9e
C++
AilurusUmbra/NCTU_OS
/hw5/1.cpp
UTF-8
5,103
2.671875
3
[]
no_license
#include<cstdio> #include<cstdlib> #include<iostream> #include<iomanip> #include<string> #include<list> #include<map> #include<set> #include<sys/time.h> #include<sys/types.h> #include<sys/wait.h> #include<unistd.h> using namespace std; char in_array[10100000][12]; int main(){ // open file FILE * file; file = fopen("trace.txt", "r"); if(!file){ cout<<"trace.txt fail to open...\n"; exit(1); } // declaration set<string> searchset; map<string, list<string>::iterator> search; list<string> frame; char mode; string temp; int hit=0, miss=0, iteration=0; int idx=0, in_max=0, frame_num=64; struct timeval start, end; int hit_ans[9], miss_ans[9]; int frame_ans[5]={0, 64, 128, 256, 512}; pid_t pid; // read file while(fscanf(file, " %c ", &mode)==1){ fscanf(file, "%s", in_array[idx]); in_array[idx][5]='\0'; idx++; } in_max=idx; // fork 2 proc to do FIFO & LRU if((pid = fork())<0) { fprintf(stderr, "simple fork failed\n"); exit(-1); } else if(pid==0) { // FIFO for(frame_num=64; frame_num<=512; frame_num*=2){/*{{{*/ searchset.clear(); frame.clear(); hit=0; miss=0; idx=0; iteration++; while(idx<in_max){ temp=in_array[idx++]; if(searchset.find(temp)!=searchset.end()){ ++hit; } else{ ++miss; if(searchset.size()==frame_num){ searchset.erase(frame.front()); frame.pop_front(); } searchset.insert(temp); frame.push_back(temp); } hit_ans[iteration]=hit; miss_ans[iteration]=miss; }//while end } /*}}}*/ cout<<"FIFO---\n"<<setiosflags(ios::left) <<setw(15)<<"size"<<setw(15)<<"miss"<<setw(15)<<"hit"<<"page fault ratio\n"; for(int i=1; i<5; ++i){/*{{{*/ cout<<setiosflags(ios::left)<<setw(15)<<frame_ans[i]<<setiosflags(ios::left)<<setw(15)<<miss_ans[i]; cout<<setiosflags(ios::left)<<setw(15)<<hit_ans[i] <<setw(23)<<fixed<<setprecision(9)<<(double)miss_ans[i]/(hit_ans[i]+miss_ans[i])<<endl; }/*}}}*/ /*{{{*/ cout<<"LRU ---\n"<<setiosflags(ios::left) <<setw(15)<<"size"<<setw(15)<<"miss"<<setw(15)<<"hit"<<"page fault ratio\n"; // for(frame_num=256; frame_num<=512; frame_num*=2){ frame_num=64; search.clear(); frame.clear(); hit=0; miss=0; idx=0; iteration++; while(idx<in_max){ temp=in_array[idx++]; if(search.find(temp)!=search.end()){ ++hit; frame.erase(search[temp]); frame.push_back(temp); search[temp]=--frame.end(); } else{ ++miss; if(search.size()==frame_num){ search.erase(frame.front()); frame.pop_front(); } frame.push_back(temp); search[temp]=--frame.end(); } }//while end hit_ans[iteration]=hit; miss_ans[iteration]=miss; //} int i = 5; cout<<setiosflags(ios::left)<<setw(15)<<frame_ans[i-4]<<setiosflags(ios::left)<<setw(15)<<miss_ans[i]; cout<<setiosflags(ios::left)<<setw(15)<<hit_ans[i] <<setw(23)<<fixed<<setprecision(9)<<(double)miss_ans[i]/(hit_ans[i]+miss_ans[i])<<endl; /*}}}*/ exit(1); } else { // LRU iteration=1; for(frame_num=128; frame_num<=512; frame_num*=2){ search.clear(); frame.clear(); hit=0; miss=0; idx=0; iteration++; while(idx<in_max){ temp=in_array[idx++]; if(search.find(temp)!=search.end()){ ++hit; frame.erase(search[temp]); frame.push_back(temp); search[temp]=--frame.end(); } else{ ++miss; if(search.size()==frame_num){ search.erase(frame.front()); frame.pop_front(); } frame.push_back(temp); search[temp]=--frame.end(); } }//while end hit_ans[iteration+4]=hit; miss_ans[iteration+4]=miss; } for(int i=6; i<9; ++i){ cout<<setiosflags(ios::left)<<setw(15)<<frame_ans[i-4]<<setiosflags(ios::left)<<setw(15)<<miss_ans[i]; cout<<setiosflags(ios::left)<<setw(15)<<hit_ans[i] <<setw(23)<<fixed<<setprecision(9)<<(double)miss_ans[i]/(hit_ans[i]+miss_ans[i])<<endl; } } wait(0); fclose(file); return 0; }
true
8ae5863a6b01805a2caf8e4e5da735a96bce3c6a
C++
motianlun99/leetcode
/solution225.cpp
UTF-8
779
3.984375
4
[ "MIT" ]
permissive
/** * System design: Implement Stack using Queues * * * cpselvis (cpselvis@gmail.com) * Oct 9th, 2016 */ #include<iostream> #include<queue> using namespace std; class Stack { private: queue<int> que; public: // Push element x onto stack. void push(int x) { que.push(x); for (int i = 0; i < que.size() - 1; i ++) { int tmp = que.front(); que.pop(); que.push(tmp); } } // Removes the element on top of the stack. void pop() { que.pop(); } // Get the top element. int top() { return que.front(); } // Return whether the stack is empty. bool empty() { return que.empty(); } }; int main(int argc, char **argv) { Stack st; st.push(1); st.push(2); cout << st.top() << endl; cout << st.top() << endl; }
true
72cdae96e81c5e54924b42fed440088c7fecbcd2
C++
2myungho/algorithm_training
/Baekjoon/10000/10819_brute/answer.cpp
UTF-8
639
3.0625
3
[]
no_license
#include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; void solution() { vector<int> arr; int N; int answer = 0; cin >> N; arr.resize(N); for (int i = 0; i < N; i++) { cin >> arr[i]; } sort(arr.begin(), arr.end()); do { int summation = 0; for (int i = 0; i < N - 1; i++) { summation += abs(arr[i] - arr[i + 1]); } answer = max(summation, answer); } while (next_permutation(arr.begin(), arr.end())); cout << answer << "\n"; } int main() { ios_base ::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); solution(); return 0; }
true
a709c5dab169f6975a8010535344de9965907744
C++
alien93/softProj
/RoboWalk/model/actuator.h
UTF-8
585
2.796875
3
[]
no_license
#ifndef ACTUATOR_H #define ACTUATOR_H #include <QString> #include "mechanicalreduction.h" #include <iostream> #include <vector> using namespace std; class Actuator { private: QString name; vector<MechanicalReduction> mechanicalReduction; public: Actuator(); Actuator(QString name, vector<MechanicalReduction> mechanicalReductinon); QString getName() const; void setName(const QString &value); vector<MechanicalReduction> getMechanicalReduction() const; void setMechanicalReduction(const vector<MechanicalReduction> &value); }; #endif // ACTUATOR_H
true
b1dd9b97c099a91d19b337b26014d49b8a34ba33
C++
ashishsahu321/lab8
/lab8_q1.cpp
UTF-8
555
3.984375
4
[]
no_license
// include library #include<iostream> //include standard library using namespace std; //function declaration int sum(int arr[20],int n){ int s=0; for(int i=0;i<n;i++) { //enter the number cout<<"Enter number to be added: "<<endl; cin>>arr[i]; //recursive calling s=s+arr[i]; } return s; } //main function int main() { //variable declaration int n,arr[20]; //asks user for the size of array cout<<"Enter array size: "<<endl; cin>>n; // function calling cout<<"Sum: "<<sum(arr,n)<<endl; //closing program return 0; }
true
5509f351b6a95ecc8d8560106de5912019a11d60
C++
hoosierEE/Homework
/Puzzles/inverter.cpp
UTF-8
1,228
3.640625
4
[ "MIT" ]
permissive
#include <iostream> // an interview question: // "design a function such that f(f(n)) == -n, where n is a 32 bit signed int, // and which does not use complex numbers" // // are globals or external state considered "complex numbers"? // a philosophical question. int minusItself(int n) { static bool hasCalledItself = false; if (hasCalledItself) { hasCalledItself = false; return n; } hasCalledItself = true; return -n; } double changesItself(double n) { // uses doubles instead of ints. again, this is "extra info" // and would fit a liberal definition of a complex number. return (n == static_cast<int>(n)) ? n + 0.1 : static_cast<int>(-n + 0.1); } int main() { for (int i = -1; i < 2; i++) std::cout << "minusItself(minusItself(" << i << "): " << minusItself(minusItself(i)) << std::endl; std::cout << std::endl; for (int i = -1; i < 2; i++) std::cout << "changesItself(changesItself(" << i << "): " << changesItself(changesItself(i)) << std::endl; } // output: // // minusItself(minusItself(-1): 1 // minusItself(minusItself(0): 0 // minusItself(minusItself(1): -1 // // changesItself(changesItself(-1): 1 // changesItself(changesItself(0): 0 // changesItself(changesItself(1): -1
true
2ae7cc20ab68ade382614284c49b560b1f0abf90
C++
etzellux/Cpp-Demos
/Fstream1.cpp
UTF-8
456
3.3125
3
[]
no_license
#include <iostream> #include <cstdlib> #include <fstream> /* ios::app ====> append ios::ate ====> output ios::in ====> read ios::out ====> write ios::trunc ==> truncation */ int main() { char data[20]; std::fstream file("deneme1.txt", std::ios::out | std::ios::trunc ); // Open a file file << "Deneme123"; // Write down file >> data; //Read std::cout << data << std::endl; file.close(); // Close the file return 0; }
true
7fa3bd3a183cb66d10da673f0f0069809d3390de
C++
Befezdow/Different_Programs
/Static Huffman/treeitem.h
UTF-8
408
2.96875
3
[]
no_license
#ifndef TREEITEM_H #define TREEITEM_H #include <memory> class TreeItem { int weight; char symbol; public: std::shared_ptr<TreeItem> parent; std::shared_ptr<TreeItem> firstChild; std::shared_ptr<TreeItem> secondChild; TreeItem(char c, int w); bool operator> (TreeItem& ob); bool operator< (TreeItem& ob); int getWeight(); char getSymbol(); }; #endif // TREEITEM_H
true
f6f99db8945b8d5ebf445688a34ef56dafb1add2
C++
bmatejek/neurogaps
/pkgs/RNDataStructures/RNVector.cpp
UTF-8
8,782
3.296875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* Source file for the vector class */ #ifndef __RN__VECTOR__C__ #define __RN__VECTOR__C__ /* Include files */ #include "RNDataStructures/RNDataStructures.h" /* private constants */ static const int RN_VECTOR_MIN_ALLOCATED = 128; /* public functions */ template <typename Type> RNVector<Type>::RNVector(void) : nallocated(RN_VECTOR_MIN_ALLOCATED), nentries(0), sorted(FALSE) { entries = new Type *[RN_VECTOR_MIN_ALLOCATED]; } template <typename Type> RNVector<Type>::~RNVector(void) { if (entries) { for (int ie = 0; ie < nentries; ++ie) delete entries[ie]; delete[] entries; } } template <typename Type> const RNBoolean RNVector<Type>:: IsEmpty(void) const { // return if vector is empty return (nentries == 0); } template <typename Type> const int RNVector<Type>:: NAllocated(void) const { // return the number of allocated spots return nallocated; } template <typename Type> const int RNVector<Type>:: NEntries(void) const { // return the number of entries in the vector return nentries; } template <typename Type> const int RNVector<Type>:: Size(void) const { // return the size of the vector return nentries; } template <typename Type> const Type& RNVector<Type>:: Head(void) const { rn_assertion(nentries); // return head return *entries[0]; } template <typename Type> const Type& RNVector<Type>:: Kth(int k) const { rn_assertion(k < nentries); // return kth entry return *entries[k]; } template <typename Type> const Type& RNVector<Type>:: operator[](int k) const { rn_assertion(k < nentries); // return kth entry return *entries[k]; } template <typename Type> const Type& RNVector<Type>:: Tail(void) const { rn_assertion(nentries); // return tail return *entries[nentries - 1]; } template <typename Type> void RNVector<Type>:: Insert(Type data) { sorted = FALSE; // insert data at end InsertTail(data); } template <typename Type> void RNVector<Type>:: InsertHead(Type data) { sorted = FALSE; // insert data into vector at head InternalInsert(data, 0); } template <typename Type> void RNVector<Type>:: InsertKth(Type data, int k) { sorted = FALSE; // insert data into vector in kth position InternalInsert(data, k); } template <typename Type> void RNVector<Type>:: InsertTail(Type data) { sorted = FALSE; // insert data into vector at tail InternalInsert(data, nentries); } template <typename Type> void RNVector<Type>:: Remove(void) { sorted = FALSE; // remove tail entry RemoveTail(); } template <typename Type> void RNVector<Type>:: RemoveHead(void) { sorted = FALSE; // remove head entry from array InternalRemove(0); } template <typename Type> void RNVector<Type>:: RemoveKth(int k) { sorted = FALSE; // remove kth entry InternalRemove(k); } template <typename Type> void RNVector<Type>:: RemoveTail(void) { sorted = FALSE; // remove tail entry from array InternalRemove(nentries - 1); } template <typename Type> void RNVector<Type>:: Empty(RNBoolean deallocate) { // remove all entries from vector Truncate(0); // deallocate memory if (deallocate) { if (entries) { for (int ie = 0; ie < nentries; ++ie) delete entries[ie]; delete[] entries; } entries = NULL; nallocated = 0; } } template <typename Type> void RNVector<Type>:: Truncate(int length) { // remove tail entries from vector if (length < nentries) { for (int ie = length; ie < nentries; ++ie) { delete entries[ie]; } nentries = length; } Resize(length); } template <typename Type> void RNVector<Type>:: Shift(int delta) { // shift all entries by delta Shift(0, 0, delta); } template <typename Type> void RNVector<Type>:: Shift(int start, int length, int delta) { // compute number of entries to shift if ((delta < 0) && (start < -delta)) start = -delta; int nshift = nentries - start; if (delta > 0) nshift -= delta; if (nshift <= 0) return; if ((length > 0) && (length < nshift)) nshift = length; // shift array entries if (delta < 0) { for (int ie = start; ie < (start + nshift); ++ie) { entries[ie + delta] = entries[ie]; } } else if (delta > 0) { for (int ie = (start + nshift - 1); ie >= start; --ie) { entries[ie + delta] = entries[ie]; } } } template <typename Type> void RNVector<Type>:: Reverse(void) { // reverse order of all entries Reverse(0, 0); } template <typename Type> void RNVector<Type>:: Reverse(int start, int length) { // compute number of entries to reserve int nreverse = nentries - start; if (nreverse <= 0) return; if ((length > 0) && (length < nreverse)) nreverse = length; if (nreverse <= 0) return; // reverse length at start int i, j; for (i = start, j = start + nreverse - 1; i < j; ++i, --j) { Swap(i, j); } } template <typename Type> void RNVector<Type>:: Append(const RNVector& vector) { // resize first Resize(NEntries() + vector.NEntries()); // insert entries of vector for (int ie = 0; ie < vector.NEntries(); ++ie) Insert(vector[ie]); } template <typename Type> void RNVector<Type>:: Shuffle(void) { for (int i = 0; i < nentries; ++i) { int r = i + (int)(RNRandomScalar() * (nentries - i)); // just checking rn_assertion((0 <= r) && (r < nentries)); Swap(i, r); } } template <typename Type> void RNVector<Type>:: QuickSort(int(*compare)(const Type data1, const Type data2)) { Shuffle(); Sort(compare, 0, nentries - 1); sorted = TRUE; } template <typename Type> RNBoolean RNVector<Type>:: IsSorted(void) { return sorted; } template <typename Type> void RNVector<Type>:: Sort(int(*compare)(const Type data1, const Type data2), int lo, int hi) { if (hi <= lo) return; int j = Partition(compare, lo, hi); Sort(compare, lo, j - 1); Sort(compare, j + 1, hi); } template <typename Type> int RNVector<Type>:: Partition(int(*compare)(const Type data1, const Type data2), int lo, int hi) { int i = lo; int j = hi + 1; const Type v = *entries[lo]; while (true) { // find item on lo to swap while (compare(*entries[++i], v)) if (i == hi) break; // find item on hi to swap while (compare(v, *entries[--j])) if (j == lo) break; // check if pointers cross if (i >= j) break; Swap(i, j); } // put partioning item v at entry j Swap(lo, j); // now a[lo .. j-1] <= a[j] <= a[j+1 .. hi] return j; } template <typename Type> void RNVector<Type>:: Swap(int i, int j) { Type *tmp = entries[i]; entries[i] = entries[j]; entries[j] = tmp; } template <typename Type> void RNVector<Type>:: Resize(int length) { // check if length is valid rn_assertion(nentries <= nallocated); // return if length less than nallocated if (length < nallocated) return; // adjust length to be next greater power of 2 int tmplength = RN_VECTOR_MIN_ALLOCATED; while (tmplength < length) tmplength *= 2; length = tmplength; // allocate new entries Type **newentries = NULL; newentries = new Type *[length]; rn_assertion(newentries); // copy old entries into new entries if (nentries > 0) { rn_assertion(entries); rn_assertion(newentries); for (int ie = 0; ie < nentries; ++ie) { newentries[ie] = entries[ie]; } } // replace entries if (entries) delete[] entries; entries = newentries; // update nallocated nallocated = length; } template <typename Type> void RNVector<Type>:: InternalInsert(Type data, int k) { // make sure there is enough storage for new entry Resize(nentries + 1); // increment number of entries nentries++; // shift entries up one notch if (k < (nentries - 1)) Shift(k, 0, 1); // copy data into kth entry entries[k] = new Type(data); } template <typename Type> void RNVector<Type>:: InternalRemove(int k) { // delete the kth entry delete entries[k]; // shift entries down one notch if (k < (nentries - 1)) Shift(k + 1, 0, -1); // decrement number of entries --nentries; } #endif
true
0b81f975408b69e33be1c163b2ac6485a786fe4e
C++
l-iberty/MyCode
/CandC++/构造函数的显隐式调用.cpp
GB18030
375
3.59375
4
[]
no_license
#include <iostream> using namespace std; class demo { private: int data; public: demo(int inData) { data = inData; } void showData() { cout << "data = " << data << endl; } }; int main() { demo d = demo(5); // 캯ʽ demo d1(12); // ʽ // Javaֻʽ: demo d = new demo(12); d.showData(); d1.showData(); return 0; }
true
786459e89d107e8fb939397d570d817b3eab0a1a
C++
Dexter-99/Coding-Library
/Graphs/NumberOfIslands.cpp
UTF-8
1,041
2.9375
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; bool check(vector<int> adj[], int i, int j, int n, int m) { if (i < 0 || i >= n || j < 0 || j >= m || adj[i][j] != 1) return false; return true; } void bfs(vector<int> adj[], int i, int j, int n, int m) { queue<pair<int, int>> q; q.push({i, j}); adj[i][j] = 2; int row[8] = {-1, -1, 1, 1, 1, 0, -1, 0}; int col[8] = {-1, 1, -1, 1, 0, 1, 0, -1}; while (!q.empty()) { int currI = q.front().first; int currJ = q.front().second; q.pop(); for (int k = 0; k < 8; k++) { if (check(adj, currI + row[k], currJ + col[k], n, m)) { q.push({currI + row[k], currJ + col[k]}); adj[currI + row[k]][currJ + col[k]] = 2; } } } } int findIslands(vector<int> a[], int n, int m) { int count = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (a[i][j] == 1) { bfs(a, i, j, n, m); count++; } } } return count; // Your code here }
true
a1292ed08ba06f65cea2d63342fc0f5257d3731a
C++
pgeorgiev98/hexed
/app/byteinputwidget.h
UTF-8
642
2.6875
3
[ "MIT" ]
permissive
#ifndef BYTEINPUTWIDGET_H #define BYTEINPUTWIDGET_H #include <QWidget> #include <QVector> class QLineEdit; class QRadioButton; class ByteInputWidget : public QWidget { Q_OBJECT public: explicit ByteInputWidget(QWidget *parent = nullptr); public slots: void set(quint8 byte); bool inputValid() const; quint8 get() const; signals: void validityChanged(); private slots: bool inputValid(int index) const; quint8 get(int index) const; void updateValues(); private: struct Base { QString name; QLineEdit *widget; int base; }; const QVector<Base> m_bases; quint8 m_value; bool m_valid; }; #endif // BYTEINPUTWIDGET_H
true
9eab66836752a39b363935ac86b9822cd34aca9e
C++
suryakiran/Mp3Db
/TagRename/Src/Main.cxx
UTF-8
2,011
2.6875
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <fstream> #include <TagRename/MainWindow.hxx> #include <boost/program_options/options_description.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/program_options/parsers.hpp> #include <boost/algorithm/string/join.hpp> using namespace std; #include <TagRename/Mp3Config.hxx> namespace po = boost::program_options; namespace { string styleSheetFile; string confFile; string dataDir; void parseArgs (int argc, char** argv) { po::options_description desc ("Allowed Options"); desc.add_options() ("help", "Display this message") ("init-dir", po::value<std::string>(), "Initial directory to start with") ("style-sheet", po::value<std::string>(), "Style Sheet File") ("conf-file", po::value<std::string>(), "Mp3 Configuration File") ("data-dir", po::value<std::string>(), "Mp3 Data Directory") ; po::variables_map vmap; po::store(po::parse_command_line(argc, argv, desc), vmap); po::notify(vmap); if (vmap.count("style-sheet")) { styleSheetFile = vmap["style-sheet"].as<string>(); } if (vmap.count("conf-file")) { confFile = vmap["conf-file"].as<string>(); } if (vmap.count("data-dir")) { dataDir = vmap["data-dir"].as<string>(); } Mp3Config* config = Mp3Config::instance(); config->readConfig(confFile); } void setApplicationStyleSheet() { if (styleSheetFile.empty()) { return; } fstream fin; fin.open (styleSheetFile.c_str(), ios_base::in); vector<string> lines; string l; while (getline (fin, l, '\n')) { lines.push_back (l); } fin.close(); qApp->setStyleSheet (boost::algorithm::join(lines, "\n").c_str()); } } int main (int argc, char** argv) { parseArgs (argc, argv); QApplication app (argc, argv); setApplicationStyleSheet(); MainWindow *mainw = new MainWindow; mainw->show(); app.exec(); }
true
3da4504533d847e2b05cc60185cf6bd25243c37d
C++
xswxq/C-Primer-Plus
/chapter12/main.cpp
GB18030
10,428
2.671875
3
[]
no_license
#include <iostream> #include "Cow.h" #include "String2.h" //#include "Stock.h" //#include "Stack.h" #include "queue.h" #include <ctime> using namespace std; //int main() //{ // Cow c1; // cout << c1.get_name()<< endl; //// cout << c1.gethobby() <<endl; ////˴ָᵼº޷ʾ // Cow c2 = Cow("shao", "coding", 120); // c2.showcow(); // // char name[10] = "sdjahf"; // Cow c3(&name[0],name,1.2); // c3.showcow(); // //// //// Cow c1; //// //// Cow c2 = Cow("shao", "coding", 120); //// c2.showcow(); //// //// Cow c3 = c2; // ƹ캯 //// c3.showcow(); //// //// c1 = c3; // ظֵ //// c1.showcow(); // //////////////2 //int main() //{ // String2 st1; // String2 st2 ("ce shi"); // String2 st3; // st3 = "hello where are you?"; // String2 st = String2 (st3); // cout << st << endl; // cout << st1 << endl; // cout << st2 << endl; // cout << st3 << endl; // cin >> st2; // st3 = st2 +st3; // cout << st3 << endl; // st2 = st3 + "my name"; // cout <<"#1: " << st2 << endl; // st2 = "msdyfois" + st3; // cout << "#2: " << st2 << endl; // st2.Stringup(); // cout << "#3: " << st2 << endl; // cout << "#4: " << st2.has('F') <<endl; // st1 = "A00"; // st2 = "a"; // cout << "#5: " << (st1 < st2) << endl; // cout << "#6: " << (st1 > st2) << endl; // // String2 s1; // s1 = "red"; // String2 rgb[3] = { String2(s1), String2("green"), String2("blue")}; // cout << "Enter the name of a primary color for mixing light: "; // String2 ans; // bool success = false; // while(cin >> ans) // { // ans.Stringlow(); // for(int i = 0; i < 3; ++i) // { // if(ans == rgb[i]) // { // cout << "That's right!\n"; // success = true; // break; // } // } // if(success) // break; // else // cout << "Try again!" << endl; // } // cout << "Bye!" << endl; //} ///////////3. //const int STKS = 4; //int main() //{ // Stock stocks[STKS] = { // Stock("NanoSmart",12,20.0), // Stock("Boffo objects",200,2.0), // Stock("Monolithic Obelisks",130,3.25), // Stock("Fleep Enterprices",60,6.5) // }; // cout <<"stock holdings:\n"; // int st; // for(st = 0; st <STKS;st++) // { // cout << stocks[st]; // } // const Stock * top = & stocks[0]; // for(st = 1;st < STKS;st++) // top = &top->topval(stocks[st]); // cout <<"\nMost valuable holding: \n"; // cout <<*top; // // Stock st1; // cout << st1 << endl; // cout << st1.howMany() << endl; // cout << stocks[1].howMany() << endl; //} //////////4. //int main() //{ // Stack s1; // cout << s1.get_top() << endl; // Stack s2(20); // ôС // // s2.push(10); // s2.push(30); // s2.push(200); // s2.show(); // // Stack s3 = s2; // // Item i = 3; // cout << "#1: " << i <<endl; // cout << "#2: " << s3.get_top() <<endl; // cout << true << endl; //1 // cout << s3.pop(i) << endl;//1 // cout << i << " is deleted from s3 " << endl; // cout << s3.pop(i) << endl;//1 // cout << "#6: " << i << " is deleted from s3 " << endl; //// cout << s3.pop(i) << endl;//1 //// cout << "#7: " << i << " is deleted from s3 " << endl; // // s1 = s3; // s1.show(); // s1.pop(i); // cout << i << " is deleted from s1 " << endl; // //} ////////5. //const int MIN_PTR_HR = 60; //bool newcustomer(double x); //int main() //{ // srand(time(nullptr)); // cout << "sace study: bank of heather automatic teller\n"; // // int qs; // // cout << "enter maximum size of queue: "; // while(cin >>qs) // { // Queue line(qs); // cout << "enter the number of simulation hours: "; // int hours; // cin >> hours; // long cyclelimmit = MIN_PTR_HR * hours; // // cout << "enter the average number of customer per hour: "; // double perhour; // cin >> perhour; // double min_per_cust; // min_per_cust = MIN_PTR_HR / perhour; // // Item temp; // long turnaways = 0; // long customers = 0; // long served = 0; // long sum_line = 0; // int wait_time = 0; // long line_wait = 0; // // for(int cycle = 0;cycle <cyclelimmit;++cycle) // { // if(newcustomer(min_per_cust)) //¿ͻ // { // if(line.isfull()) // ++turnaways; // else // { // ++customers; // temp.set(cycle); // line.enqueue(temp); // } // } // if(wait_time <=0 && !line.isempty()) //޿ͻףѡһ // { // line.dequeue(temp); // wait_time = temp.ptime(); // line_wait += cycle - temp.when(); // ++served; // } // if(wait_time > 0) // { // --wait_time; // } // sum_line += line.queuecount(); // } // // if(customers > 0 && ((double)line_wait / served == 1)) // { // cout << "customers accepted: "<< customers << endl; // cout << "customers served" << served <<endl; // cout << " turn aways: " << turnaways << endl; // cout << " average queue size: "; // cout.precision(2); // cout.setf(ios_base::fixed,ios_base::floatfield); // cout << "average wait time: " << (double)line_wait / served << "minutes" <<endl; // break; // }else if(customers <= 0) // { // cout << "no customer!\n"; // } // else // { // cout << "wait time do not pare to 1.\n"; // if((double)line_wait / served >1 ) // { // cout << "average wait time is " << (double)line_wait / served << ">1.\n"; // } // else // { // cout << "Average wait time is "<< (double)line_wait / served << " < 1 .\n" ; // } // } // cout << "enter maximum size of queue: "; // } //} // //bool newcustomer(double x) //{ // return (std::rand() * x / RAND_MAX < 1); //} // ///////////6 const int MIN_PTR_HR = 60; bool newcustomer(double x); int main() { srand(time(nullptr)); cout << "sace study: bank of heather automatic teller\n"; int qs; cout << "enter maximum size of queue: "; while(cin >>qs) { Queue line1(qs),line2(qs); cout << "enter the number of simulation hours: "; int hours; cin >> hours; long cyclelimmit = MIN_PTR_HR * hours; cout << "enter the average number of customer per hour: "; double perhour; cin >> perhour; double min_per_cust; min_per_cust = MIN_PTR_HR / perhour; Item temp[2]; long turnaways = 0; long customers = 0; long served = 0;// long sum_line = 0; int wait_time[2] = {0,0};//ӵȴʱ long line_wait = 0;//ʱ for(int cycle = 0;cycle <cyclelimmit;++cycle) { if(newcustomer(min_per_cust)) //¿ͻ { if(line1.isfull()&&line2.isfull()) ++turnaways; else if(line1.queuecount()<line2.queuecount()) { ++customers; temp[0].set(cycle); line1.enqueue(temp[0]); } else { ++customers; temp[1].set(cycle); line2.enqueue(temp[1]); } } if(wait_time[0] <=0 && !line1.isempty()) //޿ͻףѡһ { line1.dequeue(temp[0]); wait_time[0] = temp[0].ptime(); line_wait += cycle - temp[0].when(); ++served; } if(wait_time[1] <=0 && !line2.isempty()) //޿ͻףѡһ { line2.dequeue(temp[1]); wait_time[1] = temp[1].ptime(); line_wait += cycle - temp[1].when(); ++served; } if(wait_time[0] > 0) { --wait_time[0]; } if(wait_time[1] > 0) { --wait_time[1]; } sum_line += line1.queuecount() + line2.queuecount(); } if(customers > 0) { cout << "customers accepted: "<< customers << endl; cout << "customers served" << served <<endl; cout << " turn aways: " << turnaways << endl; cout << " average queue size: "; cout.precision(2); cout.setf(ios_base::fixed,ios_base::floatfield); cout << (double)sum_line / cyclelimmit / 2 << endl; cout << "average wait time: " << (double)line_wait / served << "minutes" <<endl; break; }else if(customers <= 0) { cout << "no customer!\n"; } // else // { // cout << "wait time do not pare to 1.\n"; // if((double)line_wait / served >1 ) // { // cout << "average wait time is " << (double)line_wait / served << ">1.\n"; // } // else // { // cout << "Average wait time is "<< (double)line_wait / served << " < 1 .\n" ; // } // } if(double(line_wait / served ==1)) { break; } cout << "enter maximum size of queue: "; } } bool newcustomer(double x) { return (std::rand() * x / RAND_MAX < 1); }
true
bb1fd674d4e549d53897fc3e67ed29d20170fafd
C++
chris2511/xca
/lib/database_schema.cpp
UTF-8
12,158
2.65625
3
[ "BSD-3-Clause" ]
permissive
/* The "32bit hash" in public_keys, x509super, requests, certs and crls * is used to quickly find items in the DB by reference. * It consists of the first 4 bytes of a SHA1 hash. * Collisions are of course possible. * * All binaries are stored Base64 encoded in a column of type * ' B64_BLOB ' It is defined here as 'VARCHAR(8000)' */ #define B64_BLOB "VARCHAR(8000)" /* * The B64(DER(something)) function means DER encode something * and then Base64 encode that. * So finally this is PEM without newlines, header and footer * * Dates are alway stored as 'CHAR(15)' in the * ASN.1 Generalized time 'yyyyMMddHHmmssZ' format */ #define DB_DATE "CHAR(15)" /* * Configuration settings from * the Options dialog, window size, last export directory, * default key type and size, * table column (position, sort order, visibility) */ schemas[0] << "CREATE TABLE settings (" "key_ CHAR(20) UNIQUE, " // mySql does not like 'key' or 'option" "value " B64_BLOB ")" << "INSERT INTO settings (key_, value) VALUES ('schema', '" SCHEMA_VERSION "')" /* * All items (keys, tokens, requests, certs, crls, templates) * are stored here with the primary key and some common data * The other tables containing the details reference the 'id' * as FOREIGN KEY. */ << "CREATE TABLE items(" "id INTEGER PRIMARY KEY, " "name VARCHAR(128), " // Internal name of the item "type INTEGER, " // enum pki_type "source INTEGER, " // enum pki_source "date " DB_DATE ", " // Time of insertion (creation/import) "comment VARCHAR(2048), " "stamp INTEGER NOT NULL DEFAULT 0, " // indicate concurrent access "del SMALLINT NOT NULL DEFAULT 0)" /* * Storage of public keys. Private keys and tokens also store * their public part here. */ << "CREATE TABLE public_keys (" "item INTEGER, " // reference to items(id) "type CHAR(4), " // RSA DSA EC (as text) "hash INTEGER, " // 32 bit hash "len INTEGER, " // key size in bits "\"public\" " B64_BLOB ", " // B64(DER(public key)) "FOREIGN KEY (item) REFERENCES items (id))" /* * The private part of RSA, DSA, EC keys. * references to 'items' and 'public_keys' */ << "CREATE TABLE private_keys (" "item INTEGER, " // reference to items(id) "ownPass INTEGER, " // Encrypted by DB pwd or own pwd "private " B64_BLOB ", " // B64(Encrypt(DER(private key))) "FOREIGN KEY (item) REFERENCES items (id))" /* * Smart cards or other PKCS#11 tokens * references to 'items' and 'public_keys' */ << "CREATE TABLE tokens (" "item INTEGER, " // reference to items(id) "card_manufacturer VARCHAR(64), " // Card location data "card_serial VARCHAR(64), " // as text "card_model VARCHAR(64), " "card_label VARCHAR(64), " "slot_label VARCHAR(64), " "object_id VARCHAR(64), " // Unique ID on the token "FOREIGN KEY (item) REFERENCES items (id))" /* * Encryption and hash mechanisms supported by a token */ << "CREATE TABLE token_mechanism (" "item INTEGER, " // reference to items(id) "mechanism INTEGER, " // PKCS#11: CK_MECHANISM_TYPE "FOREIGN KEY (item) REFERENCES items (id))" /* * An X509 Super class, consisting of a * - Distinguishd name hash * - Referenced key in the database * - hash of the public key, used for lookups if there * is no key to reference * used by Requests and certificates and the use-counter of keys: * 'SELECT from x509super WHERE pkey=?' */ << "CREATE TABLE x509super (" "item INTEGER, " // reference to items(id) "subj_hash INTEGER, " // 32 bit hash of the Distinguished name "pkey INTEGER, " // reference to the key items(id) "key_hash INTEGER, " // 32 bit hash of the public key "FOREIGN KEY (item) REFERENCES items (id), " "FOREIGN KEY (pkey) REFERENCES items (id)) " /* * PKCS#10 Certificate request details * also takes information from the 'x509super' table. */ << "CREATE TABLE requests (" "item INTEGER, " // reference to items(id) "hash INTEGER, " // 32 bit hash of the request "signed INTEGER, " // Whether it was once signed. "request " B64_BLOB ", " // B64(DER(PKCS#10 request)) "FOREIGN KEY (item) REFERENCES items (id)) " /* * X509 certificate details * also takes information from the 'x509super' table. * The content of the columns: hash, iss_hash, serial, ca * can also be retrieved directly from the certificate, but are good * to lurk around for faster lookup */ << "CREATE TABLE certs (" "item INTEGER, " // reference to items(id) "hash INTEGER, " // 32 bit hash of the cert "iss_hash INTEGER, " // 32 bit hash of the issuer DN "serial VARCHAR(64), " // Serial number of the certificate "issuer INTEGER, " // The items(id) of the issuer or NULL "ca INTEGER, " // CA: yes / no from BasicConstraints "cert " B64_BLOB ", " // B64(DER(certificate)) "FOREIGN KEY (item) REFERENCES items (id), " "FOREIGN KEY (issuer) REFERENCES items (id)) " /* * X509 cartificate Authority data */ << "CREATE TABLE authority (" "item INTEGER, " // reference to items(id) "template INTEGER, " // items(id) of the default template "crlExpire " DB_DATE ", " // CRL expiry date "crlNo INTEGER, " // Last CRL Number "crlDays INTEGER, " // CRL days until renewal "dnPolicy VARCHAR(1024), " // DistinguishedName policy (UNUSED) "FOREIGN KEY (item) REFERENCES items (id), " "FOREIGN KEY (template) REFERENCES items (id)) " /* * Storage of CRLs */ << "CREATE TABLE crls (" "item INTEGER, " // reference to items(id) "hash INTEGER, " // 32 bit hash of the CRL "num INTEGER, " // Number of revoked certificates "iss_hash INTEGER, " // 32 bit hash of the issuer DN "issuer INTEGER, " // The items(id) of the issuer or NULL "crl " B64_BLOB ", " // B64(DER(revocation list)) "FOREIGN KEY (item) REFERENCES items (id), " "FOREIGN KEY (issuer) REFERENCES items (id)) " /* * Revocations (serial, date, reason, issuer) used to create new * CRLs. 'Manage revocations' */ << "CREATE TABLE revocations (" "caId INTEGER, " // reference to certs(item) "serial VARCHAR(64), " // Serial of the revoked certificate "date " DB_DATE ", " // Time of creating the revocation "invaldate " DB_DATE ", " // Time of invalidation "crlNo INTEGER, " // Crl Number of CRL of first appearance "reasonBit INTEGER, " // Bit number of the revocation reason "FOREIGN KEY (caId) REFERENCES items (id))" /* * Templates */ << "CREATE TABLE templates (" "item INTEGER, " // reference to items(id) "version INTEGER, " // Version of the template format "template " B64_BLOB ", " // The base64 encoded template "FOREIGN KEY (item) REFERENCES items (id))" /* Views */ << "CREATE VIEW view_public_keys AS SELECT " "items.id, items.name, items.type AS item_type, items.date, " "items.source, items.comment, " "public_keys.type as key_type, public_keys.len, public_keys.\"public\", " "private_keys.ownPass, " "tokens.card_manufacturer, tokens.card_serial, tokens.card_model, " "tokens.card_label, tokens.slot_label, tokens.object_id " "FROM public_keys LEFT JOIN items ON public_keys.item = items.id " "LEFT JOIN private_keys ON private_keys.item = public_keys.item " "LEFT JOIN tokens ON public_keys.item = tokens.item" << "CREATE VIEW view_certs AS SELECT " "items.id, items.name, items.type, items.date AS item_date, " "items.source, items.comment, " "x509super.pkey, " "certs.serial AS certs_serial, certs.issuer, certs.ca, certs.cert, " "authority.template, authority.crlExpire, " "authority.crlNo AS auth_crlno, authority.crlDays, authority.dnPolicy, " "revocations.serial, revocations.date, revocations.invaldate, " "revocations.crlNo, revocations.reasonBit " "FROM certs LEFT JOIN items ON certs.item = items.id " "LEFT JOIN x509super ON x509super.item = certs.item " "LEFT JOIN authority ON authority.item = certs.item " "LEFT JOIN revocations ON revocations.caId = certs.issuer " "AND revocations.serial = certs.serial" << "CREATE VIEW view_requests AS SELECT " "items.id, items.name, items.type, items.date, " "items.source, items.comment, " "x509super.pkey, " "requests.request, requests.signed " "FROM requests LEFT JOIN items ON requests.item = items.id " "LEFT JOIN x509super ON x509super.item = requests.item" << "CREATE VIEW view_crls AS SELECT " "items.id, items.name, items.type, items.date, " "items.source, items.comment, " "crls.num, crls.issuer, crls.crl " "FROM crls LEFT JOIN items ON crls.item = items.id " << "CREATE VIEW view_templates AS SELECT " "items.id, items.name, items.type, items.date, " "items.source, items.comment, " "templates.version, templates.template " "FROM templates LEFT JOIN items ON templates.item = items.id" << "CREATE VIEW view_private AS SELECT " "name, private FROM private_keys JOIN items ON " "items.id = private_keys.item" << "CREATE INDEX i_settings_key_ ON settings (key_)" << "CREATE INDEX i_items_id ON items (id)" << "CREATE INDEX i_public_keys_item ON public_keys (item)" << "CREATE INDEX i_public_keys_hash ON public_keys (hash)" << "CREATE INDEX i_private_keys_item ON private_keys (item)" << "CREATE INDEX i_tokens_item ON tokens (item)" << "CREATE INDEX i_token_mechanism_item ON token_mechanism (item)" << "CREATE INDEX i_x509super_item ON x509super (item)" << "CREATE INDEX i_x509super_subj_hash ON x509super (subj_hash)" << "CREATE INDEX i_x509super_key_hash ON x509super (key_hash)" << "CREATE INDEX i_x509super_pkey ON x509super (pkey)" << "CREATE INDEX i_requests_item ON requests (item)" << "CREATE INDEX i_requests_hash ON requests (hash)" << "CREATE INDEX i_certs_item ON certs (item)" << "CREATE INDEX i_certs_hash ON certs (hash)" << "CREATE INDEX i_certs_iss_hash ON certs (iss_hash)" << "CREATE INDEX i_certs_serial ON certs (serial)" << "CREATE INDEX i_certs_issuer ON certs (issuer)" << "CREATE INDEX i_certs_ca ON certs (ca)" << "CREATE INDEX i_authority_item ON authority (item)" << "CREATE INDEX i_crls_item ON crls (item)" << "CREATE INDEX i_crls_hash ON crls (hash)" << "CREATE INDEX i_crls_iss_hash ON crls (iss_hash)" << "CREATE INDEX i_crls_issuer ON crls (issuer)" << "CREATE INDEX i_revocations_caId_serial ON revocations (caId, serial)" << "CREATE INDEX i_templates_item ON templates (item)" << "CREATE INDEX i_items_stamp ON items (stamp)" ; /* Schema Version 2: Views added to quickly load the data */ /* Schema Version 3: Add indexes over hashes and primary, foreign keys */ /* Schema Version 4: Add private key view to extract a private key with: mysql: mysql -sNp -u xca xca_msq -e or sqlite: sqlite3 ~/sqlxdb.xdb or psql: psql -t -h 192.168.140.7 -U xca -d xca_pg -c 'SELECT private FROM view_private WHERE name=\"pk8key\";' |\ base64 -d | openssl pkcs8 -inform DER * First mysql/psql will ask for a password and then OpenSSL will ask for * the database password. */ /* Schema Version 5: Extend settings value size from 1024 to B64_BLOB * SQLite does not support 'ALTER TABLE settings MODIFY ...' */ schemas[5] << "ALTER TABLE settings RENAME TO __settings" << "CREATE TABLE settings (" "key_ CHAR(20) UNIQUE, " // mySql does not like 'key' or 'option' "value " B64_BLOB ")" << "INSERT INTO settings(key_, value) " "SELECT key_, value " "FROM __settings" << "DROP TABLE __settings" << "UPDATE settings SET value='6' WHERE key_='schema'" ; schemas[6] << "ALTER TABLE items ADD del SMALLINT NOT NULL DEFAULT 0" << "CREATE INDEX i_items_del ON items (del)" << "UPDATE settings SET value='7' WHERE key_='schema'" ; /* When adding new tables or views, also add them to the list * in XSqlQuery::rewriteQuery(QString) in lib/sql.cpp */
true
0b5b739bb2d3dd7e96b3ffc0d0bd98967810e987
C++
sqglobe/SecureDialogues
/messages/src/persistent_storage/connectionmarshaller.cpp
UTF-8
4,147
2.71875
3
[ "MIT" ]
permissive
#include "connectionmarshaller.h" #include <cstring> #include "persistent-storage/utils/store_primitives.h" #include "store_helpers.h" /* std::string userName; std::string password; bool tlsUsed; std::string from; */ void ConnectionMarshaller::restore(ConnectionHolder& elem, const void* src) { std::string connName; ConnectionType type; src = prstorage::restore_str(connName, src); src = restore_simple_type(type, src); elem.setConnectionName(connName); if (type == ConnectionType::VK) { VkConnection conn; src = prstorage::restore_str(conn.userId, src); src = prstorage::restore_str(conn.accessToken, src); elem.setConnection(conn); } else if (type == ConnectionType::UDP) { elem.setConnection(UdpConnection{}); } else if (type == ConnectionType::EMAIL) { EmailConnection conn; src = prstorage::restore_str(conn.userName, src); src = prstorage::restore_str(conn.password, src); src = restore_simple_type(conn.tlsUsed, src); src = prstorage::restore_str(conn.from, src); src = prstorage::restore_str(conn.imapAddr, src); src = restore_simple_type(conn.imapPort, src); src = prstorage::restore_str(conn.smtpAddr, src); src = restore_simple_type(conn.smtpPort, src); elem.setConnection(conn); } else if (type == ConnectionType::GMAIL) { GmailConnection conn; src = prstorage::restore_str(conn.email, src); src = prstorage::restore_str(conn.accessToken, src); elem.setConnection(conn); } } uint32_t ConnectionMarshaller::size(const ConnectionHolder& element) { uint32_t size = 0; size += sizeof(std::string::size_type) + element.getConnectionName().length(); size += sizeof(element.getType()); if (element.getType() == ConnectionType::VK) { const auto& conn = element.getConnection<VkConnection>(); size += sizeof(std::string::size_type) + conn.userId.length(); size += sizeof(std::string::size_type) + conn.accessToken.length(); } else if (element.getType() == ConnectionType::UDP) { // do this empty } else if (element.getType() == ConnectionType::EMAIL) { const auto& conn = element.getConnection<EmailConnection>(); size += sizeof(std::string::size_type) + conn.userName.length(); size += sizeof(std::string::size_type) + conn.password.length(); size += sizeof(conn.tlsUsed); size += sizeof(std::string::size_type) + conn.from.length(); size += sizeof(std::string::size_type) + conn.imapAddr.length(); size += sizeof(conn.imapPort); size += sizeof(std::string::size_type) + conn.smtpAddr.length(); size += sizeof(conn.smtpPort); } else if (element.getType() == ConnectionType::GMAIL) { const auto& conn = element.getConnection<GmailConnection>(); size += sizeof(std::string::size_type) + conn.email.length(); size += sizeof(std::string::size_type) + conn.accessToken.length(); } return size; } void ConnectionMarshaller::store(void* dest, const ConnectionHolder& elem) { dest = prstorage::save_str(elem.getConnectionName(), dest); dest = store_simple_type(elem.getType(), dest); if (elem.getType() == ConnectionType::VK) { const auto& conn = elem.getConnection<VkConnection>(); dest = prstorage::save_str(conn.userId, dest); dest = prstorage::save_str(conn.accessToken, dest); } else if (elem.getType() == ConnectionType::UDP) { // do this empty } else if (elem.getType() == ConnectionType::EMAIL) { const auto& conn = elem.getConnection<EmailConnection>(); dest = prstorage::save_str(conn.userName, dest); dest = prstorage::save_str(conn.password, dest); dest = store_simple_type(conn.tlsUsed, dest); dest = prstorage::save_str(conn.from, dest); dest = prstorage::save_str(conn.imapAddr, dest); dest = store_simple_type(conn.imapPort, dest); dest = prstorage::save_str(conn.smtpAddr, dest); dest = store_simple_type(conn.smtpPort, dest); } else if (elem.getType() == ConnectionType::GMAIL) { const auto& conn = elem.getConnection<GmailConnection>(); dest = prstorage::save_str(conn.email, dest); dest = prstorage::save_str(conn.accessToken, dest); } }
true
e8605d238603ed688acde1872d0074e75670b237
C++
Shaneprrlt/penguin-2D-game
/Project/Player.h
UTF-8
803
2.828125
3
[]
no_license
#pragma once #include "grafix.h" #include <vector> #include "Bullet.h" /* * Player is the game character * that is controlled by the user * and is the protaganist. * Written by Shane Perreault 11/8/2014 */ class Player { public: // member data about the player Point pos; int size; bool facingEast; int xVel; int yVel; vector<Bullet> shots; // jumping information bool can_jump; bool falling; int jumpVelocity; int jumpBoundary; int gravity; // player default constructor Player(); // player class constructor method Player(Point pos, int size, int xVel, int yVel = 10, int jVel = 8, int jB = 125); // draws the floor void drawBase(); // draws the player void drawPlayer(); // makes the player jump void jump(int returnY); // makes the player fire a shot void fire(); };
true
291d1aee627328c93ada8ccd0165a141f1d7cafe
C++
NevmerRoman/Ubuntu
/ClientServerSQL/Server/storage.h
UTF-8
659
2.5625
3
[]
no_license
#ifndef STORAGE_H #define STORAGE_H #include "cashe.h" #include "postgres.h" #include "workwithstorage.h" namespace ClientServerSQL { class Storage : public WorkWithStorage{ public: Storage() = default; ~Storage(); bool Set(int, string); string Get(int); private: Cashe ca; Postgres db; Log* logfile = new Log("/home/student/Project/ClientServerSQL/Server/ServerLog.txt"); time_t logtime = time(NULL); Storage(const Storage &other) = delete; Storage(Storage &&other) = delete; Storage operator = (const Storage &other) = delete; Storage operator = (Storage &&other) = delete; }; } #endif // STORAGE_H
true
1ad76478c94025a725e3537831312fcb6a2a1ed7
C++
EndsleighCC/AllSorts
/Prototypes/CCDev/VS2010/TestCLRConsole/TestCLRConsole/TestCLRConsole.cpp
UTF-8
2,665
2.640625
3
[]
no_license
// TestCLRConsole.cpp : main project file. #include "stdafx.h" using namespace System; using namespace System::ComponentModel; using namespace TestCSharpCLRObject; using namespace TestCPlusPlusCLRObject ; using namespace TestCSharpCLRStaticObject ; int main(array<System::String ^> ^args) { //Console::WriteLine(L"Hello World from C++. Press <ENTER>"); //Console::ReadLine(); try { try { //char *pch = 0 ; //char ch = *pch ; //int intTop = 1 ; //int intBottom = 0 ; //int intValue = intTop / intBottom ; // MotCalculatePremium //System::Diagnostics::Process^ myProc = gcnew System::Diagnostics::Process; ////Attempting to start a non-existing executable //myProc->StartInfo->FileName = "c:\nonexist.exe"; ////Start the application and assign it to the process component. //myProc->Start(); char *pch = (char *)1 ; char ch = *pch ; } catch ( Win32Exception ^ wex ) { Console::WriteLine( wex->Message ); Console::WriteLine( wex->ErrorCode ); Console::WriteLine( wex->NativeErrorCode ); Console::WriteLine( wex->StackTrace ); Console::WriteLine( wex->Source ); Exception^ e = wex->GetBaseException(); Console::WriteLine( wex->Message ); } catch ( Exception ^ ex ) { Console::WriteLine( ex->Message ); Console::WriteLine( ex->StackTrace ); Console::WriteLine( ex->Source ); Exception^ e = ex->GetBaseException(); Console::WriteLine( e->Message ); } } catch ( ... ) { Console::WriteLine( "Unexpected unhandled exception" ) ; } TestCSharpCLRClass ^ testCSharpCLRClass = gcnew TestCSharpCLRClass(); Console::WriteLine( testCSharpCLRClass->HelloString() ); Console::ReadLine(); Console::WriteLine( testCSharpCLRClass->HelloStringProperty ) ; Console::ReadLine(); Console::WriteLine(); Console::WriteLine( "Static Method on non-static class returned \"{0}\"" , testCSharpCLRClass->GetStaticString() ); Console::WriteLine(); Console::WriteLine( "Static Method on static class returned \"{0}\"" , TestCSharpCLRStaticClass::GetStaticString() ); ECTestCPlusPlusCLRObject ^ testCPlusPlusCLRObject = gcnew ECTestCPlusPlusCLRObject() ; System::IntPtr ^ intPtr = testCPlusPlusCLRObject->ProducePointerToCommonCplusCplusData() ; testCPlusPlusCLRObject->ConsumePointerToCommonCplusCplusData( intPtr ) ; return 0; }
true
eec944c485be600d48de9f65d05ff9eff05abd73
C++
kaestro/algorithms_v2
/daily/april/week4/0420/sw-1768/user.cpp
UTF-8
1,907
2.828125
3
[]
no_license
typedef struct { int strike; int ball; } Result; // API extern Result query(int guess[]); bool num[9877]; int number[5040]; bool flag = true; int idx = 0; void init() { if (flag) { flag = false; for (int i = 123; i < 9876; ++i) { int sb1 = i / 1000; int sb2 = i % 1000 / 100; int sb3 = i % 100 / 10; int sb4 = i % 10; if (sb1 != sb2 && sb1 != sb3 && sb1 != sb4 && sb2 != sb3 && sb2 != sb4 && sb3 != sb4) number[idx++] = i; } } for (int i = 0; i < idx; ++i) num[number[i]] = true; } Result cmp(int n, int c) { Result r; r.strike = 0; r.ball = 0; int chk[10] = {0}; for (int i = 0; i < 4; ++i) { if (n % 10 == c % 10) r.strike++; else { chk[n % 10]++; chk[c % 10]++; } if (chk[n % 10] == 2) r.ball++; if (chk[c % 10] == 2) r.ball++; n /= 10; c /= 10; } return r; } void doUserImplementation(int guess[]) { init(); while(1) { int ans; for (int i = 0; i < idx; ++i) { if (num[number[i]]) { ans = number[i]; guess[0] = ans / 1000; guess[1] = ans % 1000 / 100; guess[2] = ans % 100 / 10; guess[3] = ans % 10; break; } } Result result = query(guess); if (result.strike == 4) break; else num[ans] = false; for (int i = 0; i < idx; ++i) { if (num[number[i]]) { Result rslt = cmp(ans, number[i]); if (result.strike != rslt.strike || result.ball != rslt.ball) num[number[i]] = false; } } } }
true
e48f886a603cf1770a0e09c5fab1be7d7082bce1
C++
aeon-engine/libaeon
/src/common/public/aeon/common/string.h
UTF-8
17,949
3.3125
3
[ "BSD-2-Clause" ]
permissive
// Distributed under the BSD 2-Clause License - Copyright 2012-2023 Robin Degen #pragma once #include <concepts> #include <string> #include <ostream> namespace aeon::common { class string_view; class string { friend class string_view; public: static_assert(alignof(char) == alignof(char8_t), "Alignment of char and char8_t don't match. String won't work properly."); static_assert(sizeof(char) == sizeof(char8_t), "Size of char and char8_t don't match. String won't work properly."); static constexpr auto npos = std::string::npos; using value_type = std::string::value_type; using allocator_type = std::string::allocator_type; using size_type = std::string::size_type; using difference_type = std::string::difference_type; using pointer = std::string::pointer; using const_pointer = std::string::const_pointer; using reference = std::string::reference; using const_reference = std::string::const_reference; using iterator = std::string::iterator; using const_iterator = std::string::const_iterator; using reverse_iterator = std::string::reverse_iterator; using const_reverse_iterator = std::string::const_reverse_iterator; constexpr string() noexcept; constexpr string(const value_type c) noexcept; constexpr string(const char8_t c) noexcept; constexpr string(const size_type count, const value_type c) noexcept; constexpr string(const size_type count, const char8_t c) noexcept; constexpr string(const char *const str); string(const char8_t *const str); constexpr string(std::string str) noexcept; constexpr string(const std::u8string &str); constexpr explicit string(const string_view &str) noexcept; template <std::contiguous_iterator iterator_t> constexpr string(iterator_t begin, iterator_t end) noexcept; constexpr string(const string &other) = default; constexpr auto operator=(const string &other) -> string & = default; constexpr string(string &&other) noexcept = default; constexpr auto operator=(string &&other) noexcept -> string & = default; constexpr ~string() = default; constexpr auto operator=(const value_type *const str) -> string &; constexpr auto operator=(std::string str) -> string &; auto operator=(const char8_t *const str) -> string &; constexpr auto operator=(const std::u8string &str) -> string &; constexpr auto operator=(const string_view &str) -> string &; constexpr void assign(const value_type *const str); constexpr void assign(std::string &&str); void assign(const char8_t *const str); constexpr void assign(const std::u8string &str); constexpr void assign(const string &str); constexpr void assign(const string_view &str); constexpr auto insert(const size_type index, const value_type *const str) -> string &; auto insert(const size_type index, const char8_t *const str) -> string &; constexpr auto insert(const size_type index, const std::string_view &str) -> string &; auto insert(const size_type index, const std::u8string_view &str) -> string &; auto insert(const size_type index, const string &str) -> string &; auto insert(const size_type index, const string_view &str) -> string &; template <typename position_iterator_t, typename input_iterator_t> auto insert(const position_iterator_t pos, const input_iterator_t first, const input_iterator_t last) -> string &; constexpr auto erase(const size_type index = 0, const size_type count = npos) -> string &; constexpr auto erase(const_iterator position) -> iterator; constexpr auto erase(const_iterator first, const_iterator last) -> iterator; [[nodiscard]] constexpr auto str() noexcept -> std::string &; [[nodiscard]] constexpr auto str() const noexcept -> const std::string &; [[nodiscard]] auto u8str() const noexcept -> std::u8string; [[nodiscard]] constexpr auto size() const noexcept -> size_type; [[nodiscard]] constexpr auto capacity() const noexcept -> size_type; [[nodiscard]] constexpr auto data() noexcept -> pointer; [[nodiscard]] constexpr auto data() const noexcept -> const_pointer; constexpr void shrink_to_fit(); [[nodiscard]] constexpr auto c_str() const noexcept -> const_pointer; [[nodiscard]] auto u8_c_str() const noexcept -> const char8_t *; constexpr void reserve(const size_type size); constexpr void resize(const size_type count); [[nodiscard]] constexpr auto compare(const string &str) const noexcept -> int; [[nodiscard]] constexpr auto compare(const string_view &str) const noexcept -> int; [[nodiscard]] constexpr auto compare(const std::string &str) const noexcept -> int; [[nodiscard]] auto compare(const std::u8string &str) const noexcept -> int; [[nodiscard]] constexpr auto compare(const value_type *const str) const noexcept -> int; [[nodiscard]] auto compare(const char8_t *const str) const noexcept -> int; [[nodiscard]] constexpr auto compare(const size_type pos, const size_type count, const string_view str) const -> int; constexpr auto operator==(const string &str) const -> bool; constexpr auto operator==(const string_view &str) const -> bool; constexpr auto operator==(const std::string &str) const -> bool; auto operator==(const std::u8string &str) const -> bool; constexpr auto operator==(const value_type *const str) const -> bool; auto operator==(const char8_t *const str) const -> bool; constexpr auto operator<=>(const string &str) const -> std::strong_ordering; constexpr auto operator<=>(const string_view &str) const -> std::strong_ordering; constexpr auto operator<=>(const std::string &str) const -> std::strong_ordering; auto operator<=>(const std::u8string &str) const -> std::strong_ordering; constexpr auto operator<=>(const value_type *const str) const -> std::strong_ordering; auto operator<=>(const char8_t *const str) const -> std::strong_ordering; constexpr auto append(const value_type *const str) -> string &; auto append(const char8_t *const str) -> string &; constexpr auto append(const value_type *const str, const size_type size) -> string &; auto append(const char8_t *const str, const size_type size) -> string &; constexpr auto append(const std::string &str) -> string &; auto append(const std::u8string &str) -> string &; constexpr auto append(const string &str) -> string &; constexpr auto append(const string_view &str) -> string &; template <std::contiguous_iterator iterator_t> constexpr auto append(iterator_t begin, iterator_t end) noexcept -> string &; constexpr auto operator+=(const char *str) -> string &; auto operator+=(const char8_t *str) -> string &; constexpr auto operator+=(const std::string &str) -> string &; constexpr auto operator+=(const std::string_view &str) -> string &; auto operator+=(const std::u8string_view &str) -> string &; constexpr auto operator+=(const string &str) -> string &; constexpr auto operator+=(const string_view &str) -> string &; constexpr auto operator+=(const value_type c) -> string &; constexpr auto operator+=(const char8_t c) -> string &; [[nodiscard]] constexpr auto as_std_string_view() noexcept -> std::string_view; [[nodiscard]] constexpr auto as_std_string_view() const noexcept -> std::string_view; [[nodiscard]] auto as_std_u8string_view() noexcept -> std::u8string_view; [[nodiscard]] auto as_std_u8string_view() const noexcept -> std::u8string_view; constexpr void clear(); [[nodiscard]] constexpr auto empty() const noexcept -> bool; [[nodiscard]] constexpr auto at(const size_type pos) -> reference; [[nodiscard]] constexpr auto at(const size_type pos) const -> const_reference; [[nodiscard]] constexpr auto operator[](const size_type pos) -> reference; [[nodiscard]] constexpr auto operator[](const size_type pos) const -> const_reference; [[nodiscard]] constexpr auto front() noexcept -> reference; [[nodiscard]] constexpr auto front() const noexcept -> const_reference; [[nodiscard]] constexpr auto back() noexcept -> reference; [[nodiscard]] constexpr auto back() const noexcept -> const_reference; [[nodiscard]] constexpr auto begin() noexcept -> iterator; [[nodiscard]] constexpr auto begin() const noexcept -> const_iterator; [[nodiscard]] constexpr auto cbegin() const noexcept -> const_iterator; [[nodiscard]] constexpr auto end() noexcept -> iterator; [[nodiscard]] constexpr auto end() const noexcept -> const_iterator; [[nodiscard]] constexpr auto cend() const noexcept -> const_iterator; [[nodiscard]] constexpr auto rbegin() noexcept -> reverse_iterator; [[nodiscard]] constexpr auto rbegin() const noexcept -> const_reverse_iterator; [[nodiscard]] constexpr auto crbegin() const noexcept -> const_reverse_iterator; [[nodiscard]] constexpr auto rend() noexcept -> reverse_iterator; [[nodiscard]] constexpr auto rend() const noexcept -> const_reverse_iterator; [[nodiscard]] constexpr auto crend() const noexcept -> const_reverse_iterator; [[nodiscard]] constexpr auto starts_with(const std::string_view &str) const noexcept -> bool; [[nodiscard]] auto starts_with(const std::u8string_view &str) const noexcept -> bool; [[nodiscard]] constexpr auto starts_with(const string &str) const noexcept -> bool; [[nodiscard]] constexpr auto starts_with(const string_view &str) const noexcept -> bool; [[nodiscard]] constexpr auto starts_with(const value_type c) const noexcept -> bool; [[nodiscard]] constexpr auto starts_with(const char8_t c) const noexcept -> bool; [[nodiscard]] constexpr auto ends_with(const std::string_view &str) const noexcept -> bool; [[nodiscard]] auto ends_with(const std::u8string_view &str) const noexcept -> bool; [[nodiscard]] constexpr auto ends_with(const string &str) const noexcept -> bool; [[nodiscard]] constexpr auto ends_with(const string_view &str) const noexcept -> bool; [[nodiscard]] constexpr auto ends_with(const value_type c) const noexcept -> bool; [[nodiscard]] constexpr auto ends_with(const char8_t c) const noexcept -> bool; [[nodiscard]] constexpr auto substr(const size_type pos = 0, const size_type count = npos) const -> string; [[nodiscard]] auto find(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto find(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find(const char8_t c, const size_type pos = 0) const -> size_type; [[nodiscard]] auto rfind(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto rfind(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto rfind(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto rfind(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto rfind(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto rfind(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto rfind(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto rfind(const char8_t c, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_first_of(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto find_first_of(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_of(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_of(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_of(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_first_of(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_first_of(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_first_of(const char8_t c, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_first_not_of(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto find_first_not_of(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_not_of(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_not_of(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_first_not_of(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_first_not_of(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_first_not_of(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_first_not_of(const char8_t c, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_last_of(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto find_last_of(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_of(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_of(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_of(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_last_of(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_last_of(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_last_of(const char8_t c, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_last_not_of(const std::string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] auto find_last_not_of(const std::u8string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_not_of(const string &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_not_of(const string_view &str, const size_type pos = 0) const noexcept -> size_type; [[nodiscard]] constexpr auto find_last_not_of(const value_type *str, const size_type pos = 0) const -> size_type; [[nodiscard]] auto find_last_not_of(const char8_t *str, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_last_not_of(const value_type c, const size_type pos = 0) const -> size_type; [[nodiscard]] constexpr auto find_last_not_of(const char8_t c, const size_type pos = 0) const -> size_type; void replace(const size_type pos, const size_type count, const string_view &str); private: std::string str_; }; inline constexpr auto operator+(const string &lhs, const string &rhs) -> string; inline constexpr auto operator+(const string &lhs, const std::string &rhs) -> string; inline constexpr auto operator+(const std::string &lhs, const string &rhs) -> string; inline auto operator+(const string &lhs, const std::u8string &rhs) -> string; inline auto operator+(const std::u8string &lhs, const string &rhs) -> string; inline constexpr auto operator+(const string &lhs, const char *const rhs) -> string; inline constexpr auto operator+(const char *const lhs, const string &rhs) -> string; inline auto operator+(const string &lhs, const char8_t *const rhs) -> string; inline auto operator+(const char8_t *const lhs, const string &rhs) -> string; inline constexpr auto operator+(const string_view &lhs, const string &rhs) -> string; inline constexpr auto operator+(const string_view &lhs, const string_view &rhs) -> string; inline constexpr auto operator+(const string_view &lhs, const std::string &rhs) -> string; inline constexpr auto operator+(const std::string &lhs, const string_view &rhs) -> string; inline auto operator+(const string_view &lhs, const std::u8string &rhs) -> string; inline auto operator+(const std::u8string &lhs, const string_view &rhs) -> string; inline constexpr auto operator+(const string_view &lhs, const char *const rhs) -> string; inline constexpr auto operator+(const char *const lhs, const string_view &rhs) -> string; inline auto operator+(const string_view &lhs, const char8_t *const rhs) -> string; inline auto operator+(const char8_t *const lhs, const string_view &rhs) -> string; inline auto operator<<(std::ostream &os, const string &str) -> std::ostream &; } // namespace aeon::common #include <aeon/common/impl/string_impl.h>
true
a1abc34c85c14e539256463a8abfcfa3e4e114a2
C++
HSchmale16/HeavyWeapon
/src/HealthEntity.cpp
UTF-8
356
2.828125
3
[]
no_license
#include "HealthEntity.h" #include <cassert> #include "Utils.h" HealthEntity::HealthEntity() :max_health(25), current_health(25.f) { assert(max_health == current_health); } void HealthEntity::applyDamageCalculation(DamageCalculation& dc) { if(dc.hit) { current_health -= dc.amount; // cout << getCurrentHealth() << endl; } }
true
508a4affe02f8692777761c124e7c91ed38c0284
C++
CytronTechnologies/CytronMotorDriver
/CytronMotorDriver.cpp
UTF-8
1,654
3.046875
3
[ "MIT" ]
permissive
#include "CytronMotorDriver.h" CytronMD::CytronMD(MODE mode, uint8_t pin1, uint8_t pin2) { _mode = mode; _pin1 = pin1; _pin2 = pin2; pinMode(_pin1, OUTPUT); pinMode(_pin2, OUTPUT); digitalWrite(_pin1, LOW); digitalWrite(_pin2, LOW); } void CytronMD::setSpeed(int16_t speed) { // Make sure the speed is within the limit. if (speed > 255) { speed = 255; } else if (speed < -255) { speed = -255; } // Set the speed and direction. switch (_mode) { case PWM_DIR: if (speed >= 0) { #if defined(ARDUINO_ARCH_ESP32) ledcWrite(_pin1, speed); #else analogWrite(_pin1, speed); #endif digitalWrite(_pin2, LOW); } else { #if defined(ARDUINO_ARCH_ESP32) ledcWrite(_pin1, -speed); #else analogWrite(_pin1, -speed); #endif digitalWrite(_pin2, HIGH); } break; case PWM_PWM: if (speed >= 0) { #if defined(ARDUINO_ARCH_ESP32) ledcWrite(_pin1, speed); ledcWrite(_pin2, 0); #else analogWrite(_pin1, speed); analogWrite(_pin2, 0); #endif } else { #if defined(ARDUINO_ARCH_ESP32) ledcWrite(_pin1, 0); ledcWrite(_pin2, -speed); #else analogWrite(_pin1, 0); analogWrite(_pin2, -speed); #endif } break; } }
true
e01b567faf99a863f97738be88f39424757b0696
C++
TyRoXx/lua-cpp
/test/add_method.cpp
UTF-8
3,442
2.578125
3
[ "MIT" ]
permissive
#include <boost/test/unit_test.hpp> #include "test_with_environment.hpp" #include "luacpp/meta_table.hpp" namespace { struct test_struct { bool *called; explicit test_struct(bool &called) : called(&called) { } void method_non_const() { method_const(); } void method_const() const { BOOST_CHECK(called); BOOST_REQUIRE(!*called); *called = true; } }; void test_method_call(std::function<void (lua::stack_value &meta)> const &prepare_method) { test::test_with_environment([&prepare_method](lua::stack &s, test::resource bound) { lua::stack_value meta = lua::create_default_meta_table<test_struct>(s); prepare_method(meta); bool called = false; lua::stack_value object = lua::emplace_object<test_struct>(s, meta, called); lua_getfield(s.state(), -1, "method"); lua::push(*s.state(), object); BOOST_REQUIRE(!called); lua::pcall(*s.state(), 1, boost::none); BOOST_CHECK(called); }); } } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_from_method_ptr_const) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", &test_struct::method_const); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_from_method_ptr_non_const) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", &test_struct::method_non_const); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_stateless_lambda) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", [](test_struct &instance) { instance.method_non_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_stateful_lambda) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); long dummy_state = 2; lua::add_method(s, meta, "method", [dummy_state](test_struct &instance) { BOOST_CHECK_EQUAL(2, dummy_state); instance.method_non_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_mutable_lambda) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); long dummy_state = 2; lua::add_method(s, meta, "method", [dummy_state](test_struct &instance) mutable { BOOST_CHECK_EQUAL(2, dummy_state); instance.method_non_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_this_by_reference) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", [](test_struct &instance) { instance.method_non_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_const_this_by_reference) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", [](test_struct const &instance) { instance.method_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_this_by_pointer) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", [](test_struct *instance) { BOOST_REQUIRE(instance); instance->method_non_const(); }); }); } BOOST_AUTO_TEST_CASE(lua_wrapper_add_method_const_this_by_pointer) { test_method_call([](lua::stack_value &meta) { lua::stack s(*meta.thread()); lua::add_method(s, meta, "method", [](test_struct const *instance) { BOOST_REQUIRE(instance); instance->method_const(); }); }); }
true
7fb27acef992b2b52cd605e92199c73c4fcfdb35
C++
oalpar/Nips
/OK/NipsOriginal/Nips_MT/src/framework/hashing_more_og.h
UTF-8
1,683
2.53125
3
[ "MIT" ]
permissive
#ifndef _HASHING_MORE_H_1 #define _HASHING_MORE_H_1 #include <cstdint> // TODO: If you have a seed of random bytes you should place it in the seed // directory and use randomgen.h instead! #include <random> // TODO: Replace with #include "randomgen.h" #include "MurmurHash3_og.h" #include "MurmurHash3.h" /* ************************************************************* * Wrapper for MurMurHash similar to the rest * *************************************************************/ class murmurwrap1 { uint32_t m_seed; public: murmurwrap1(); void init(); uint32_t operator()(uint32_t x); }; murmurwrap1::murmurwrap1() { } void murmurwrap1::init() { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<uint32_t> dist; m_seed = dist(rng); // TODO: Replace with the line below if using randomgen.h //m_seed = getRandomUInt32(); } uint32_t murmurwrap1::operator()(uint32_t x) { uint32_t h; m_seed=12345; //comment this out if working for real h=0; MurmurHash3_x86_32(&x, 4, m_seed, &h); return h; } class murmurwrap { uint32_t m_seed; public: murmurwrap(); void init(); __m256i operator()(__m256i x); }; murmurwrap::murmurwrap() { } void murmurwrap::init() { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<uint32_t> dist; m_seed = dist(rng); // TODO: Replace with the line below if using randomgen.h //m_seed = getRandomUInt32(); } __m256i murmurwrap::operator()(__m256i x) { m_seed=12345; __m256i h; MurmurHash3_x86_323(&x, 4, m_seed, &h); return h; } #endif //_HASHING_MORE_H_
true
bffa68cca27f81d891bf421cf121a23d7071b75f
C++
yohm/weighted_social_network_model
/random.hpp
UTF-8
734
2.9375
3
[ "MIT" ]
permissive
#ifndef RANDOM_HPP #define RANDOM_HPP #include <iostream> #include <boost/random.hpp> //================================================= // singleton class for random number generator class Random { public: static void Init(uint64_t seed, int num_threads = 1) { m_rnds.clear(); for(int i=0; i <num_threads; i++) { m_rnds.push_back( boost::random::mt19937(seed+i) ); } } static double Rand01(int thread_num) { boost::random::uniform_01<> uniform; return uniform(m_rnds[thread_num]); } static double Gaussian(int thread_num) { boost::random::normal_distribution<> gaussian; return gaussian(m_rnds[thread_num]); } private: static std::vector<boost::random::mt19937> m_rnds; }; #endif
true
e3897a6d99373f6b87615887f29afc2684031126
C++
GeekyPython/Code-Practice
/concepts/stl1.cpp
UTF-8
834
3.265625
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int main() { vector<int>v,w; for(int i=0;i<10;i++) { v.push_back(i+1); } for(int i=10;i<20;i++) { w.push_back(i); } for(auto i=v.begin();i!=v.end();i++) { cout<<*i<<" "; } cout<<"\n"; for(auto i=w.begin();i!=w.end();i++) { cout<<*i<<" "; } cout<<"\n"; cout<<"Swapping....\n"; v.swap(w); for(auto i=v.begin();i!=v.end();i++) { cout<<*i<<" "; } cout<<"\n"; for(auto i=w.begin();i!=w.end();i++) { cout<<*i<<" "; } cout<<"\n"; v.emplace(v.begin()+7,25); //v.push_back(25); for(auto i=v.begin();i!=v.end();i++) { cout<<*i<<" "; } cout<<"\n"; }
true
a7ee0d8cc1d7bf7473adcd3824e1500300707eb5
C++
ahaddad98/42_piscine_cplusplus
/day02/ex01/Fixed.cpp
UTF-8
2,039
2.921875
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Fixed.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ahaddad <ahaddad@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/26 20:46:48 by ahaddad #+# #+# */ /* Updated: 2021/06/02 21:05:16 by ahaddad ### ########.fr */ /* */ /* ************************************************************************** */ #include "Fixed.hpp" Fixed::Fixed(int r) { this->raw = r << this->bits; std::cout << "Int Constructor called" << std::endl; } Fixed::Fixed(float fl) { this->raw = (int)roundf(fl * (1 << this->bits)); std::cout << "Float Constructor called" << std::endl; } Fixed::Fixed(const Fixed& f1) { std::cout << "Copy constructor called" << std::endl; raw = f1.getRawBits(); } Fixed & Fixed::operator=(const Fixed &f) { std::cout << "Assignation operator called" << std::endl; raw = f.getRawBits(); return *this; } void Fixed::setRawBits(int const raw) { this->raw = raw; } int Fixed::getRawBits(void) const { std::cout << "getRawBits member function called" << std::endl; return raw; } Fixed::Fixed() { raw = 0; std::cout << "Default constructor called" << std::endl; } Fixed::~Fixed() { std::cout << "Destructor called" << std::endl; } int Fixed::toInt(void) const { return (this->raw >> this->bits); } float Fixed::toFloat(void) const { return (((float)this->raw) / (1 << this->bits)); } std::ostream &operator<<(std::ostream &os, Fixed const &fixed) { os << fixed.toFloat(); return (os); }
true
c25fd4cb6b8bfe52d695dd392029d47a554efd2b
C++
S1ckick/oop_game
/Game/Player/Player.h
UTF-8
787
2.828125
3
[]
no_license
// // Created by Максим on 03.10.2020. // #ifndef GAME_PLAYER_H #define GAME_PLAYER_H #include "../Board/Cell/Cell.h" #include "../Enemy/EnemyInterface.h" class Player { public: int getHealth(); void setHealth(int health); int getStars(); void setStars(int stars); int getCurrentX(); void setCurrentX(int currentX); int getCurrentY(); void setCurrentY(int currentY); int getStan(); void setStan(int stan); friend Player &operator+=(Player &player, ElementTypes elem); friend Player &operator+=(Player &player, EnemyInterface *enemy); friend std::ostream &operator<<(std::ostream &out, Player &player); private: int health; int stars; int currentX; int currentY; int stan; }; #endif //GAME_PLAYER_H
true
a8bc5f02086ff60ab208cfe1cac1be8c41eb57fc
C++
diptu/Teaching
/CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab 3 task 2( Division)/complex(9).h
UTF-8
657
2.921875
3
[ "MIT" ]
permissive
#ifndef COMPLEX_H_INCLUDED # define COMPLEX_H_INCLUDED class Complex { friend Complex operator - (Complex &a , Complex &b ) ; friend Complex operator - (int value , Complex &a ) ; friend Complex operator - (Complex &a , int value ) ; friend Complex operator * (Complex &a , Complex &b) ; friend Complex operator * (Complex &a , int value ) ; friend Complex operator * ( int value, Complex &a ) ; friend Complex operator / (Complex &a , Complex &b) ; private : double real , imag; public : Complex () ; Complex (double , double) ; Complex operator + (Complex) ; void Print () ; }; #endif // COMPLEX_H_INCLUDED
true
9d1743674d25fe76355a603aac059e31c9d79c1b
C++
chaemon/library
/graph/topological_sort.cpp
UTF-8
722
2.78125
3
[]
no_license
//{{{ topological sort bool visit(const Graph &g, int v, vector<int> &order, vector<int> &color,vector<int> &next) { color[v] = 1; FOR(e, g[v]) { if (color[e->dst] == 2) continue; if (color[e->dst] == 1){ order.clear(); int t=e->dst; while(1){ order.push_back(t); if(t==v)break; t=next[t]; } return false; } next[v]=e->dst; if (!visit(g, e->dst, order, color, next)) return false; next[v]=-1; } order.push_back(v); color[v] = 2; return true; } bool topologicalSort(const Graph &g, vector<int> &order) { int n = g.size(); vector<int> color(n),next(n,-1); REP(u, n) if (!color[u] && !visit(g, u, order, color, next)) return false; reverse(ALL(order)); return true; } //}}}
true
e6afc966d1d9f675772afb08f5267ae9bc019c6b
C++
gtangg12/Algorithm-Library
/maxflow.cpp
UTF-8
928
2.6875
3
[]
no_license
// Maxflow via Ford-Fulkerson implemented using Edmonds-Karp: O(VE^2) #include "header.h" const int MAXN = 1024; int N, M; vpi adj[MAXN]; // (des, cap) int par[MAXN]; int res[MAXN][MAXN]; int bfs(int s, int t) { fill(par, par + MAXN, -1); par[s] = -2; queue<pi> q; q.push({s, INF}); // (node, flow) while(!q.empty()) { int n = q.front().f; int f = q.front().s; q.pop(); for (auto e: adj[n]) { int c = e.f; if (par[c] == -1 && res[n][c] > 0) { par[c] = n; int nf = min(f, res[n][c]); if (c == t) return nf; q.push({c, nf}); } } } return 0; } int maxflow(int s, int t) { int f = 0; int nf; while (nf = bfs(s, t)) { f += nf; int n = t; while (n != s) { int p = par[n]; res[p][n] -= nf; res[n][p] += nf; n = p; } } return f; } void addEdge(int u, int v, int c) { adj[u].pb({v, c}); adj[u].pb({u, 0}); res[u][v] = c; res[v][u] = 0; } int main() { }
true
6b12399efe3ed2ead8bbda36d45b25bca0ea32c2
C++
omkarbuchade/CFS-scheduling
/code/threads/ioRequest.cc
UTF-8
1,129
2.75
3
[ "MIT-Modern-Variant" ]
permissive
//Name: Omkar Buchade #include "ioRequest.h" #include <iostream> #include "main.h" #include "IOalarm.h" void Request::writeRequest(std::string writeStr) { std::cout<<"\nCreating a write request"; int ticks= kernel->stats->totalTicks; ioRequest *requestObj=new ioRequest(WriteInt, kernel->currentThread, writeStr, ticks); kernel->reqList->Insert(requestObj); IOalarm *IOalarmObj = new IOalarm(); kernel->interrupt->Schedule(IOalarmObj,requestObj->getexecStart_time(), WriteInt); kernel->interrupt->SetLevel(IntOff); kernel->currentThread->Sleep(false); kernel->interrupt->SetLevel(IntOn); } void Request::readRequest() { std::cout<<"\nCreating a read request"; int ticks= kernel->stats->totalTicks; ioRequest *requestObj=new ioRequest(ReadInt, kernel->currentThread, "", ticks); kernel->reqList->Insert(requestObj); IOalarm *IOalarmObj = new IOalarm(); kernel->interrupt->Schedule(IOalarmObj,requestObj->getexecStart_time(), ReadInt); kernel->interrupt->SetLevel(IntOff); kernel->currentThread->Sleep(false); kernel->interrupt->SetLevel(IntOn); }
true
8ca7ecceddb617d12e6c6054d7dd7f8d7e8ab46b
C++
varkey98/Leetcode-Solutions
/pathInZigZagTree.cpp
UTF-8
255
2.65625
3
[]
no_license
#include<iostream> #include<vector> #include<math.h> vector<int> pathInZigZagTree(int label) { float k= log(label)/log(2)+1; int level=(int)k; int max=pow(2,level)-1; int pos=0; if(level%2==0) int pos=max-label+1+pow(2,level-1)-1 }
true
c15a2347575b3082022caafa4b04c38abe7cf43c
C++
daweizh/cpp
/chap02/99/exam3_10-2.cpp
UTF-8
292
3.546875
4
[]
no_license
编程实现两个变量x、y之间值的交换。 #include <iostream> using namespace std; int main(){ float x,y,t; x = 10.5; y = 30.6; cout << x << " " << y << endl; x+=y;y=x-y;x-=y; cout << x << " " << y << endl; return 0; }
true
917114ebac90cd2feba2035524937e701946e045
C++
bvbasavaraju/competitive_programming
/leetcode/top_interview_questions/easy/trees/2.cpp
UTF-8
1,503
4.03125
4
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; /* Q: Validate Binary Search Tree Given the root of a binary tree, determine if it is a valid binary search tree (BST). A valid BST is defined as follows: + The left subtree of a node contains only nodes with keys less than the node's key. + The right subtree of a node contains only nodes with keys greater than the node's key. + Both the left and right subtrees must also be binary search trees. Example 1: Input: root = [2,1,3] Output: true Example 2: Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. Constraints: The number of nodes in the tree is in the range [1, 104]. -231 <= Node.val <= 231 - 1 */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { private: bool isValid(TreeNode* node, long long mini, long long maxi) { if(node == nullptr) { return true; } if((node->val <= mini) || (node->val >= maxi)) { return false; } return isValid(node->left, mini, node->val) && isValid(node->right, node->val, maxi); } public: bool isValidBST(TreeNode* root) { return isValid(root, LONG_MIN, LONG_MAX); } };
true
c4d2be85fe86a0385b198bf990b6eb16515444e1
C++
mahyuddin/utexas-ros-pkg
/stacks/austinvilla/ground_truth/include/ground_truth/field_provider.h
UTF-8
5,889
2.65625
3
[]
no_license
/** * \file field_provider.h * \brief This header defines the dimensions of the field, as well as * declares the helper functions to draw out the field in 2D and 3D * * \author Piyush Khandelwal (piyushk), piyushk@cs.utexas.edu * Copyright (C) 2011, The University of Texas at Austin, Piyush Khandelwal * * License: Modified BSD License * * $ Id: 08/10/2011 11:07:07 AM piyushk $ */ #ifndef FIELD_PROVIDER_HWF1NX72 #define FIELD_PROVIDER_HWF1NX72 #include <Eigen/Core> #include <opencv/cv.h> #include <pcl_visualization/pcl_visualizer.h> namespace ground_truth { /* constants describing the field */ const float FIELD_Y = 3.950; ///< width of the field const float FIELD_X = 5.950; ///< length of the field const float GRASS_Y = 4.725; ///< width of the grass const float GRASS_X = 6.725; ///< length of the grass const float PENALTY_Y = 2.150; ///< distance of penalty box along width const float PENALTY_X = 0.550; ///< distance of penalty box along length const float CIRCLE_RADIUS = 0.650; ///< center circle radius const float PENALTY_CROSS_X = 1.200; ///< distance of penalty cross from field center const float GOAL_HEIGHT = 0.8; ///< height of top goal bar const float GOAL_Y = 1.5; ///< distance between goal posts /* Different points of interest on the field */ /* Landmarks - points on the ground plane that are easily identifiable */ enum GroundPoints { YELLOW_BASE_TOP = 0, YELLOW_BASE_PENALTY_TOP = 1, YELLOW_GOALPOST_TOP = 2, YELLOW_GOALPOST_BOTTOM = 3, YELLOW_BASE_PENALTY_BOTTOM = 4, YELLOW_BASE_BOTTOM = 5, YELLOW_PENALTY_TOP = 6, YELLOW_PENALTY_BOTTOM = 7, YELLOW_PENALTY_CROSS = 8, MID_TOP = 9, MID_CIRCLE_TOP = 10, MID_CIRCLE_BOTTOM = 11, MID_BOTTOM = 12, BLUE_BASE_TOP = 13, BLUE_BASE_PENALTY_TOP = 14, BLUE_GOALPOST_TOP = 15, BLUE_GOALPOST_BOTTOM = 16, BLUE_BASE_PENALTY_BOTTOM = 17, BLUE_BASE_BOTTOM = 18, BLUE_PENALTY_TOP = 19, BLUE_PENALTY_BOTTOM = 20, BLUE_PENALTY_CROSS = 21, NUM_GROUND_PLANE_POINTS = 22 }; /* High points - top corners of goals */ enum HighPoints { YELLOW_GOALPOST_TOP_HIGH = 0, YELLOW_GOALPOST_BOTTOM_HIGH = 1, BLUE_GOALPOST_TOP_HIGH = 2, BLUE_GOALPOST_BOTTOM_HIGH = 3, NUM_HIGH_POINTS = 4 }; /** * \class FieldProvider * \brief Provides locations of key field landmarks and helper functions to draw the field out in 2D and 3D */ class FieldProvider { private: Eigen::Vector3f centerField; ///< Coordinates for the field center Eigen::Vector3f groundPoints[NUM_GROUND_PLANE_POINTS]; ///< True locations of landmarks on the ground plane Eigen::Vector3f highPoints[NUM_HIGH_POINTS]; ///< True locations of the top points in a goal (for visualization) /* 2D Helper Functions */ /** * \brief Draws a line on an IplImage from 3D points using the appropriate scale */ void draw2dLine(IplImage* image, const Eigen::Vector3f &ep1, const Eigen::Vector3f &ep2, const CvScalar &color, int width); /** * \brief Draws a dot (small circle) on an IplImage from 3D points using the appropriate scale */ void draw2dCircle(IplImage * image, const Eigen::Vector3f &pt, int radius, const CvScalar &color, int width); /** * \brief Draws the center circle on an IplImage from 3D points using the appropriate scale */ void draw2dCenterCircle(IplImage *image, const Eigen::Vector3f &centerPt, const Eigen::Vector3f &circlePt, const CvScalar &color, int width); /** * \brief Scales the points from 3D locations to the correct pixel on an IplImage */ void convertCoordinates(cv::Point2d &pos2d, int height, int width, const Eigen::Vector3f &pos3d); /* 3D Helper Functions */ /** * \brief Draws a line in 3D space * * This function also draw out 2 small spheres at the end of the line */ void draw3dLine(pcl_visualization::PCLVisualizer &visualizer, const Eigen::Vector3f &ep1, const Eigen::Vector3f &ep2, double r, double g, double b, const std::string &name); /** * \brief Draws the center circle in 3d space * * This method currently uses the PCLVisualizer API for drawing circles. * Currently a wireframe of the center circle in the form of a Hexagon * is drawn * */ void draw3dCenterCircle(pcl_visualization::PCLVisualizer &visualizer, const Eigen::Vector3f &centerPt, const Eigen::Vector3f &circlePt, double r, double g, double b, const std::string &name); public: /** * \brief Constructor with field center coordinates * * This constructor always assumes the xy plane to be the ground */ FieldProvider (float x = 0.0, float y = 0.0, float z = 0.0); /** * \brief Draws out a 2D field to scale on an OpenCV IplImage * \param image The image on which the field is to be drawn * \param highlightPoint Indicates which landmark is to be highlighted(default is none) */ void get2dField(IplImage* image, int highlightPoint = -1); /** * \brief Draws out a 3d field to scale in a PCLVisualizer Window * \param visualizer the PCLVisualizer window object */ void get3dField(pcl_visualization::PCLVisualizer &visualizer); /** * \brief Returns the true location of a landmark * \param index Identifier for the landmark * \return The 3D location of the landmark */ inline Eigen::Vector3f getGroundPoint(int index) { return groundPoints[index]; } }; } #endif /* end of include guard: FIELD_PROVIDER_HWF1NX72 */
true
910da10455f81ad88905733f464ed45514d59285
C++
CZAlmon/School-Programs
/C++/Binary Search Tree for Games/elements.h
UTF-8
779
3.25
3
[]
no_license
#ifndef ELEMENTS_H #define ELEMENTS_H #include <iostream> #include <string> using namespace std; class Binary_tree; class tree_node { private: string title;//title int year_made;//year double highest_score;//score tree_node* left;//left node pointer tree_node* right;//right node pointer public: tree_node(string, int, double, tree_node*, tree_node*);//node maker string Get_title() const;//get title string int get_year_made() const;//get year made int double get_highest_score() const;//get score double void change_highest_score(double new_high_score); //change high score by modify function tree_node* getLeft() const; //get left node tree_node* getRight() const;// get right node friend class Binary_tree; // gives Binary_tree access }; #endif
true
d92759df3b1f0eb5daac8261ac1ecaad5b6db564
C++
LinuxKernelDevelopment/cppprimer
/ch05/EXE5_4_1/word.cpp
UTF-8
416
3.015625
3
[]
no_license
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; int main(void) { string preword, word, lword; int num = 1, largest = 0; while (cin >> word) { if (preword == word) { num++; } else { if (num >= largest) { largest = num; lword = preword; } num = 1; preword = word; } } cout << lword << '\t' << largest << endl; return 0; }
true
ca571ff2b191e7992d8f68319d6c016e2b690d15
C++
Rosovskyy/server-client
/server.cpp
UTF-8
1,942
2.65625
3
[]
no_license
#include <iostream> #include <unistd.h> #include <netinet/in.h> #include <sstream> #include <time.h> int main() { struct sockaddr_in server; char buf[1024]; int sd = socket(AF_INET, SOCK_STREAM, 0); if (sd < 0) { exit(EXIT_FAILURE); } memset(&server, 0, sizeof(struct sockaddr_in)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl(INADDR_ANY); server.sin_port = htons(2250); int bnd_code = bind(sd, (struct sockaddr *) &server, sizeof(server)); if (bnd_code < 0) { exit(EXIT_FAILURE); } int lst_code = listen(sd, 1); if (lst_code < 0) { exit(EXIT_FAILURE); } for (;;) { int psd = accept(sd, 0, 0); if (psd < 0) { continue; } int cc = recv(psd, buf, 1024, 0); if (cc == 0) { exit(EXIT_SUCCESS); } std::string sendString; std::stringstream ss; if (buf[0] == 't' || buf[0] == 'd') { time_t now = time(0); struct tm tstruct; char time_buf[80]; tstruct = *localtime(&now); if (buf[0] == 't') { strftime(time_buf, sizeof(time_buf), "%X", &tstruct); sendString = time_buf; } else { strftime(time_buf, sizeof(time_buf), "%Y-%m-%d", &tstruct); sendString = time_buf; } } else if (buf[0] == 'h') { sendString = "Hello!"; } else if (buf[0] == 'm') { std::string input = buf; int word_count(0); std::stringstream ss(input); std::string word; while (ss >> word) ++word_count; sendString = std::to_string(--word_count); } send(psd, sendString.c_str(), strlen(sendString.c_str()), 0); if (close(psd) == -1) { exit(EXIT_FAILURE); } close(psd); } }
true
7bef34536ad2c76beb40d061cdf2be59b4da51a3
C++
niks333/dsacodes
/stackUsingLL.cpp
UTF-8
1,106
3.734375
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class StackNode{ public: int data; StackNode* next; }; StackNode* newNode(int value){ StackNode* stackNode = new StackNode(); stackNode->next=NULL; stackNode->data=value; return stackNode; } bool isEmpty(StackNode* root){ return !root; } void push(StackNode** root,int value){ StackNode* stackNode=newNode(value); stackNode->next=(*root); (*root)=stackNode; cout<<(*root)->data<<" pushed in stack\n"; } int pop(StackNode** root){ if(isEmpty(*root)){ return INT_MIN; } else{ StackNode* tmp=*root; *root=(*root)->next; int popped=tmp->data; free(tmp); return popped; } } int top(StackNode *root){ return (root->data); } void display(StackNode* root){ while(root!=NULL){ cout<<(root->data)<<" "; root=root->next; } } int main() { StackNode* root=NULL; push(&root,95); push(&root,65); push(&root,55); push(&root,15); push(&root,25); int a=pop(&root); display(root); return 0; }
true
a2f10a9a9e7b630aedbdbfe8589060b0f4867e0e
C++
stdstring/leetcode
/Algorithms/Tasks.1001.1500/1108.DefangingIPAddress/solution.cpp
UTF-8
645
3.296875
3
[ "MIT" ]
permissive
#include <string> #include "gtest/gtest.h" namespace { class Solution { public: std::string defangIPaddr(std::string const &address) const { std::string result; for (char ch : address) { if (ch == '.') result.append("[.]"); else result.push_back(ch); } return result; } }; } namespace DefangingIPAddressTask { TEST(DefangingIPAddressTaskTests, Examples) { const Solution solution; ASSERT_EQ("1[.]1[.]1[.]1", solution.defangIPaddr("1.1.1.1")); ASSERT_EQ("255[.]100[.]50[.]0", solution.defangIPaddr("255.100.50.0")); } }
true
59eb7f9b195482028533745234a48cd87907a081
C++
alexandraback/datacollection
/solutions_5631989306621952_1/C++/Stummfilm/a.cpp
UTF-8
527
3.078125
3
[]
no_license
#include <iostream> #include <fstream> #include <string> #include <sstream> #include <cstdlib> #include <vector> #include <cmath> using namespace std; string solve(string s){ string result = ""; result += s[0]; for(int i = 1; i < s.size(); i++) { if(s[i] >= result[0]) result = s[i] + result; else result += s[i]; } return result; } int main() { int t; string s; cin >> t; for(int i = 0; i < t; i++){ cin >> s; cout << "Case #" << (i + 1) << ": " << solve(s) << endl; } return EXIT_SUCCESS; }
true
869a712feebccc3b0919c5010758b5d881e9720e
C++
DavidMilot/openGameEngine3D
/openGameEngine3D/src/Platforms/OpenGL/OpenGLVertexArray.cpp
UTF-8
3,873
2.640625
3
[ "MIT" ]
permissive
#include "ogepch.h" #include "Platforms/OpenGL/OpenGLVertexArray.h" #include <glad/glad.h> /* Hazel Engine License : Apache 2.0 */ namespace openGameEngine3D { static GLenum ShaderDataTypeToOpenGLBaseType (ShaderDataType type) { switch (type) { case ShaderDataType::Float: return GL_FLOAT; case ShaderDataType::Float2: return GL_FLOAT; case ShaderDataType::Float3: return GL_FLOAT; case ShaderDataType::Float4: return GL_FLOAT; case ShaderDataType::Mat3: return GL_FLOAT; case ShaderDataType::Mat4: return GL_FLOAT; case ShaderDataType::Int: return GL_INT; case ShaderDataType::Int2: return GL_INT; case ShaderDataType::Int3: return GL_INT; case ShaderDataType::Int4: return GL_INT; case ShaderDataType::Bool: return GL_BOOL; } std::cout << "false, Unknown ShaderDataType!"; return 0; } OpenGLVertexArray::OpenGLVertexArray () { OGE_PROFILE_FUNCTION (); glCreateVertexArrays (1, &m_RendererID); } OpenGLVertexArray::~OpenGLVertexArray () { OGE_PROFILE_FUNCTION (); glDeleteVertexArrays (1, &m_RendererID); } void OpenGLVertexArray::Bind () const { OGE_PROFILE_FUNCTION (); glBindVertexArray (m_RendererID); } void OpenGLVertexArray::Unbind () const { OGE_PROFILE_FUNCTION (); glBindVertexArray (0); } void OpenGLVertexArray::AddVertexBuffer (const Ref<VertexBuffer>& vertexBuffer) { OGE_PROFILE_FUNCTION (); std::cout << vertexBuffer->GetLayout ().GetElements ().size () << " Vertex Buffer has no layout!"; glBindVertexArray (m_RendererID); vertexBuffer->Bind (); uint32_t index = 0; const auto& layout = vertexBuffer->GetLayout (); for (const auto& element : layout) { switch (element.Type) { case ShaderDataType::Float: case ShaderDataType::Float2: case ShaderDataType::Float3: case ShaderDataType::Float4: case ShaderDataType::Int: case ShaderDataType::Int2: case ShaderDataType::Int3: case ShaderDataType::Int4: case ShaderDataType::Bool: { glEnableVertexAttribArray (m_VertexBufferIndex); glVertexAttribPointer (m_VertexBufferIndex, element.GetComponentCount (), ShaderDataTypeToOpenGLBaseType (element.Type), element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride (), (const void*)element.Offset); m_VertexBufferIndex++; break; } case ShaderDataType::Mat3: case ShaderDataType::Mat4: { uint8_t count = element.GetComponentCount (); for (uint8_t i = 0; i < count; i++) { glEnableVertexAttribArray (m_VertexBufferIndex); glVertexAttribPointer (m_VertexBufferIndex, count, ShaderDataTypeToOpenGLBaseType (element.Type), element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride (), (const void*)(element.Offset + sizeof (float) * count * i)); glVertexAttribDivisor (m_VertexBufferIndex, 1); m_VertexBufferIndex++; } break; } default: OGE_CORE_ASSERT (false, "Unknown ShaderDataType!"); } } m_VertexBuffers.push_back (vertexBuffer); } void OpenGLVertexArray::SetIndexBuffer (const Ref<IndexBuffer>& indexBuffer) { OGE_PROFILE_FUNCTION (); glBindVertexArray (m_RendererID); indexBuffer->Bind (); m_IndexBuffer = indexBuffer; } void OpenGLVertexArray::AddCustomVertexBuffer (uint32_t index, int size, ShaderDataType type, bool normalized, int stride, uint32_t offset) { glVertexAttribPointer (index, 3, ShaderDataTypeToOpenGLBaseType(type), normalized, stride * sizeof (float), (void*)offset); glEnableVertexAttribArray (index); //glVertexAttribDivisor (m_VertexBufferIndex, 1); not needed?? } void OpenGLVertexArray::RenderCube (unsigned int obj, int count) { // render the cube glBindVertexArray (obj); glDrawArrays (GL_TRIANGLES, 0, count); } }
true
299c9785443c938cb9fa6ad3ae4ac5061f1e4ead
C++
gwkdgwkd/examples
/c++/STL/effective_stl/31.cpp
UTF-8
6,179
3.90625
4
[]
no_license
#include <algorithm> #include <iostream> #include <iterator> #include <vector> // 了解各种与排序有关的选择 class Widget {}; bool qualityCompare(const Widget &lhs, const Widget &rhs) { return false; } // sort是一个非常不错的算法,但也并非在任何场合下都是完美无缺的。 // 只需排序出前20好的,可以使用partial_sort。 // 选出最好的几个,可以使用nth_element。 // partial_sort和nth_element效果基本相同, // 不同的是partial_sort排序了,nth_element没有排序。 // 对于等价的元素,partial_sort和nth_element有自己的做法, // 无法控制它们的行为。 // partial_sort、nth_element和sort都属于非稳定的排序算法, // stable_sort可以提供稳定排序。 // partial_sort和nth_element没有对应的稳定排序。 // partition算法可以把满足某个特定条件的元素放在区间的前部。 // 如果相对位置非常重要,那么可以使用stable_partition。 bool hasAcceptableQuality(const Widget &w) { return false; } // partial_sort、nth_element、sort和stable_sort算法都要求随机访问迭代器, // 所以这些算法只能被用于vector、string、deque和数组。 // 对于关联容器进行排序并没有实际意义。 // list是唯一需要排序却无法使用这些排序算法的容器。 // 为此,list特别提供了sort成员函数(稳定排序)。 // 如果需要在list中使用partial_sort、nth_element,只能使用间接的方法: // 1.将list中的元素拷贝到一个提供随机访问的迭代器容器中, // 然后对该容器执行期望的算法; // 2.先创建一个list::iterator的容器,在对容器执行相应的算法, // 然后通过其中的迭代器访问list的元素; // 3.利用一个包含迭代器的有序容器中的信息,通过反复地调用splice成员函数, // 将list中的元素跳转到期望的目标位置。 // 与partial_sort、nth_element、sort和stable_sort不同的是, // partition和stable_partition只要求双向迭代器就能完成工作。 // 所以对标准序列容器,都可以使用partition和stable_partition。 // 总结: // 1.如果需要对vector、string、deque或数组进行完全排序, // 那么可以使用sort或者stable_sort。 // 2.如果有一个vector、string、deque或数组, // 并且只需要对等价性最前面的n个元素进行排序,那么可以使用partial_sort。 // 3.如果有一个vector、string、deque或数组,并且需要找到第n个位置上的元素, // 或者需要找到等价性最前面的n个元素但有不必对这n个元素进行排序, // 那使用nth_element。 // 4.如果需要将一个标准序列容器中的元素按照是否满足某个特定的条件区分开来, // 那么partition和stable_partition可以做到。 // 5.如果数据在list中,可以直接调用partition和stable_partition, // 可以用list::sort来代替sort和stable_sort算法。 // partial_sort、nth_element功能需要间接实现。 // 6.可以通过使用关联容器来保证元素始终保存特定的顺序。 // 也可以考虑使用标准的非STL容器priority_queue, // 它总是保持其元素的顺序关系。 // 稳定的排序算法要比那些忽略稳定性的算法更为耗时。 // 按消耗资源排序,较少的算法排在前面: // partition<stable_partition<nth_element<partial_sort<sort<stable_sort int main() { std::vector<Widget> widgets; std::partial_sort(widgets.begin(), widgets.begin() + 20, widgets.end(), qualityCompare); std::nth_element(widgets.begin(), widgets.begin() + 19, widgets.end(), qualityCompare); std::vector<int> v{9, 4, 8, 2, 7, 3, 6, 1, 5}; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 9 4 8 2 7 3 6 1 5 std::partial_sort(v.begin(), v.begin() + 5, v.end()); std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 1 2 3 4 5 9 8 7 6 std::vector<int> v1{9, 4, 8, 2, 7, 3, 6, 1, 5}; std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 9 4 8 2 7 3 6 1 5 std::nth_element(v1.begin(), v1.begin() + 5, v1.end()); std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 5 4 1 2 3 6 7 8 9 // nth_element除了可以找出排名前n个元素,还有其他功能, // 比如可以用来找到一个区间的中间值,或者找到某个特定百分比上的值: std::vector<Widget>::iterator begin(widgets.begin()); std::vector<Widget>::iterator end(widgets.end()); // 找出具有中间质量级别的Widget: std::vector<Widget>::iterator goalPosition; goalPosition = begin + widgets.size() / 2; std::nth_element(begin, goalPosition, end, qualityCompare); // 找出具有75%质量的元素: std::vector<Widget>::size_type goalOffset = 0.25 * widgets.size(); std::nth_element(begin, begin + goalOffset, end, qualityCompare); std::vector<int> v2{9, 4, 8, 2, 7, 3, 6, 1, 5}; std::vector<int>::iterator begin1(v2.begin()); std::vector<int>::iterator end1(v2.end()); std::vector<int>::iterator goalPosition1; goalPosition1 = begin1 + v2.size() / 2; std::nth_element(begin1, goalPosition1, end1); std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 5 4 1 2 3 6 7 8 9 std::vector<int> v3{9, 4, 8, 2, 7, 3, 6, 1, 5}; std::vector<int>::iterator begin2(v3.begin()); std::vector<int>::iterator end2(v3.end()); std::vector<int>::size_type goalOffset2 = 0.25 * v3.size(); std::nth_element(begin2, begin2 + goalOffset2, end2); std::copy(v3.begin(), v3.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 1 2 3 4 5 7 6 8 9 // vector<Widget>::iterator goodEnd = // partition(widgets.begin(), widgets.end(), hasAcceptableQuality); // 调用partition后,所有满足要求的都被放在了begin和goodEnd之间的区间中。 // 其他大在goodEnd到end之间的区间中。 return 0; }
true
65103be0c9d54fd9825c1cb7ccfa4f8d8dc7658e
C++
mtorresdemello/Taller1
/CalcuSimple_PSTCompiler/listaInstrucciones.cpp
ISO-8859-1
9,923
2.890625
3
[]
no_license
#include "listaInstrucciones.h" void listaInstruccionesPROC_crearLI(listaInstrucciones &li){ li = NULL; } void listaInstruccionesPROC_destruirLI(listaInstrucciones &li){ if (li != NULL) { listaInstruccionesPROC_destruirLI (li->sig); delete li; li = NULL; } } boolean listaInstruccionesFUNC_isNull(listaInstrucciones li){ return boolean(li==NULL); } int listaInstruccionesFUNC_largo(listaInstrucciones li){ int i=0; while(li != NULL) { i++; li = li->sig; } return i; } void listaInstruccionesPROC_instertFront(listaInstrucciones &li, instruccion i){ listaInstrucciones aux; aux = new nodoInstruccion; aux->info = i; aux->sig = li; li = aux; } //utilizada para el armado de la estructura lista de instrucciones void listaInstruccionesPROC_instertBack(listaInstrucciones &li, instruccion i){ listaInstrucciones nuevo = new nodoInstruccion; nuevo->info = i; nuevo->sig = NULL; if (li == NULL){ li = nuevo; } else { listaInstrucciones aux = li; while (aux->sig != NULL) aux = aux->sig; aux->sig = nuevo; } } // el contador se suma afuera y le pasa para que buclee n veces hasta que da el siguiente elemento // util para ver todas las instrucciones en la estructura lista de instrucciones cuando se carge // para usar en ejecucion instruccion listaInstruccionesFUNC_darInstruccion(listaInstrucciones li, int numero){ int i = 0; while ( (li->sig != NULL) && (i != numero) ) { i++; li = li->sig; } return li->info; } // guarda una instrucicon a la lista con el discriminante- // tipo del enumeradoopsBasi leer y el nombre de la variable void listaInstruccionesPROC_agregarInstruccionLEER(StringDyn str, listaInstrucciones &li){ instruccion i; enumOpsBasicas ob; ob = LEER; // LEER * enumAS1 int numero_entero = 0; StringDyn nomVar1; StringDyn_crear(nomVar1); AS3 as3; AS4 as4; AS5 as5; AS6 as6; instruccionFUNC_cargar(i, str,ob, numero_entero,nomVar1, as3, as4, as5, as6); listaInstruccionesPROC_instertBack(li,i); } // guarda una instrucicon a la lista con el discriminante- tipo del // enumeradoopsBasi mostrar y el nombre de la variable void listaInstruccionesPROC_agregarInstruccionMOSTRAR(StringDyn str, listaInstrucciones &li){ instruccion i; enumOpsBasicas ob; ob = MOSTRAR; // MOSTRAR o EnumAS2 int numero_entero = 0; StringDyn nomVar1; StringDyn_crear(nomVar1); AS3 as3; AS4 as4; AS5 as5; AS6 as6; instruccionFUNC_cargar(i, str,ob, numero_entero,nomVar1, as3, as4, as5, as6); listaInstruccionesPROC_instertBack(li,i); } // guarda una instrucicon a la lista analizando cual de las combinaciones de 5 elementos es // para guardarla con su respectivo structura datos de la union y discriminante // de existir el error, tirarlo en el formato : // printf("\n***Error de compilaci%sn - linea %d: para la instruccion de la asignacion // con FUNC con 2 argumentos",nroLinea); //tilde void listaInstruccionesPROC_agregarInstruccionAScompuesta(arbolVariables abb, listaInstrucciones &li, listaStrings ls, int nroLinea, boolean &huboError, int &nroLineaWarning, boolean &compiloConCero){ boolean makeRoom = FALSE; huboError = FALSE; instruccion i; enumOpsBasicas ob; enumOpsArits oa; int numero_entero = 0; int as3_par1 = 0, as3_par2 = 0, as4_par1 = 0, as5_par2 = 0; StringDyn nomVar1; StringDyn_crear(nomVar1); AS3 as3; AS4 as4; AS5 as5; AS6 as6; // Define si es alguna de las funciones AS3-6 if (StringDyn_equalAnyFUNCarits(listaStringsFUNC_darTERCERstr(ls)) == TRUE) { enumOpsAritsFUNC_carga(oa, listaStringsFUNC_darTERCERstr(ls)); //si el dar 4 es un int y el dar 5 to es un int if (StringDyn_equalNumeroEntero(listaStringsFUNC_darCUARTOstr(ls)) == TRUE && StringDyn_equalNumeroEntero(listaStringsFUNC_darQUINTOstr(ls)) == TRUE) { ob = enum_AS3; as3_par1 = StringDynFUNC_stringToNumeric(listaStringsFUNC_darCUARTOstr(ls)); as3_par2 = StringDynFUNC_stringToNumeric(listaStringsFUNC_darQUINTOstr(ls)); AS3_FUNC_carga(as3, oa,as3_par1,as3_par2); if ( (oa == DIV) && (as3_par2 == 0) ) { nroLineaWarning = nroLinea; compiloConCero = TRUE; } } else if (StringDyn_equalNumeroEntero(listaStringsFUNC_darCUARTOstr(ls)) == TRUE && arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darQUINTOstr(ls)) == TRUE) { ob = enum_AS4; as4_par1 = StringDynFUNC_stringToNumeric(listaStringsFUNC_darCUARTOstr(ls)); AS4_FUNC_carga(as4, oa,as4_par1,listaStringsFUNC_darQUINTOstr(ls)); } //si el 4to es una var o sea una string y el 5to es un int else if (( arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darCUARTOstr(ls)) == TRUE ) && StringDyn_equalNumeroEntero(listaStringsFUNC_darQUINTOstr(ls)) == TRUE) { ob = enum_AS5; as5_par2 = StringDynFUNC_stringToNumeric(listaStringsFUNC_darQUINTOstr(ls)); AS5_FUNC_carga(as5, oa,listaStringsFUNC_darCUARTOstr(ls),as5_par2); if ( (oa == DIV) && (as5_par2 == 0) ) { nroLineaWarning = nroLinea; compiloConCero = TRUE; } } //si el 4to es una var o sea una string y el 5to es una var o sea una string else if ((arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darCUARTOstr(ls)) == TRUE) && (arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darQUINTOstr(ls)) == TRUE)) { ob = enum_AS6; AS6_FUNC_carga(as6, oa,listaStringsFUNC_darCUARTOstr(ls),listaStringsFUNC_darQUINTOstr(ls)); } else { huboError = TRUE; printf("\n***Error de compilaci%sn - l%snea %d: ",LETRA_o, LETRA_i, nroLinea); if ( StringDyn_equalNumeroEntero(listaStringsFUNC_darCUARTOstr(ls)) == FALSE && arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darCUARTOstr(ls)) == FALSE) { makeRoom = TRUE; printf("el primer argumento, luego de '"); StringDyn_print(listaStringsFUNC_darTERCERstr(ls)); printf("', \ndebe ser un n%smero entero o una variable declarada \nen la segunda secci%sn (VARIABLES)",LETRA_u,LETRA_o); } if ( StringDyn_equalNumeroEntero(listaStringsFUNC_darQUINTOstr(ls)) == FALSE && arbolVariablesFUNC_verificarExistenciaString(abb, listaStringsFUNC_darQUINTOstr(ls)) == FALSE) { if (makeRoom) { printf(", y tambi%sn ",LETRA_e); } printf("el segundo argumento, luego de '"); StringDyn_print(listaStringsFUNC_darTERCERstr(ls)); printf("', \ndebe ser un n%smero entero o una variable declarada \nen la segunda secci%sn (VARIABLES)",LETRA_u,LETRA_o); } } } else { //error ingreso una func incorrecta solo se soprotan 4 funcs // este nunca aparece, se controla afuera huboError = TRUE; printf("\n***Error de compilaci%sn - l%snea %d: Se ingreso una FUNCI%sN no reconocida por el compilador",LETRA_o, LETRA_i, nroLinea, LETRA_O); } if (!huboError) { instruccionFUNC_cargar(i, listaStringsFUNC_darPRIMERstr(ls),ob, numero_entero,nomVar1, as3, as4, as5, as6); listaInstruccionesPROC_instertBack(li,i); } } // Guardo las intruccion en la lista de instrucciones, le paso la lista de substring y se debera // validar correctamente todas las combinaciones, tanto LEER, MOSTRAR y asiganciones, dadas en el diseo. // Utilizando la estructura y haciendo nfasis en la union para las combinaciones en la asignacion. // tiene q retornar una bool para ver si hubo algun error, asi puedo saber si bajo todo o no void listaInstruccionesPROC_agregarInstruccionASsimpple(arbolVariables abb, listaInstrucciones &li, listaStrings ls, int nroLinea, boolean &huboError){ instruccion i; enumOpsBasicas ob; // enumOpsArits oa; int numero_entero = 0, par1 = 0; StringDyn nomVar1; StringDyn_crear(nomVar1); AS3 as3; AS4 as4; AS5 as5; AS6 as6; // Define si es alguna de las funciones AS3-6 if (StringDyn_equalNumeroEntero(listaStringsFUNC_darTERCERstr(ls)) == TRUE ) { ob = enum_AS1; par1 = StringDynFUNC_stringToNumeric(listaStringsFUNC_darTERCERstr(ls)); numero_entero = par1; instruccionFUNC_cargar(i, listaStringsFUNC_darPRIMERstr(ls),ob, numero_entero,nomVar1, as3, as4, as5, as6); listaInstruccionesPROC_instertBack(li,i); } else if (arbolVariablesFUNC_verificarExistenciaString(abb,listaStringsFUNC_darTERCERstr(ls)) == TRUE ) { ob = enum_AS2; StringDyn_copiar(nomVar1,listaStringsFUNC_darTERCERstr(ls)); instruccionFUNC_cargar(i, listaStringsFUNC_darPRIMERstr(ls),ob, numero_entero,nomVar1, as3, as4, as5, as6); listaInstruccionesPROC_instertBack(li,i); } else{ printf("\n***Error de compilaci%sn - l%snea %d",LETRA_o, LETRA_i, nroLinea); } }
true
665e0fae1e88d20056c1c170fe22707aee8aa38d
C++
Ampersandnz/se306-project-1
/src/upstage_pkg/src/renderer/Texture.cpp
UTF-8
713
2.578125
3
[]
no_license
#include "Texture.hpp" #include "Renderer.hpp" #include "../Util.hpp" ups::Texture::Texture(ups::Texture::Texture::TextureType tt, unsigned int width, unsigned int height, unsigned int innerWidth, unsigned int innerHeight) : _tt(tt), _width(width), _height(height), _isInRenderer(false), _data(0) { _innerWidth = (innerWidth) ? innerWidth : potAbove(width); _innerHeight = (innerHeight) ? innerHeight : potAbove(height); } ups::Texture::~Texture() { delete[] _data; } ups::TexHandle &ups::Texture::getRendererHandle(ups::Renderer &renderer) { if (!_isInRenderer) { _rendererHandle = renderer.makeTexHandle(*this); _isInRenderer = true; } return _rendererHandle; }
true
12665f5fbf59b4af8b41a7e13038d41a9f06f988
C++
IndiraBobburi/Algos-and-DS
/SortingAlgorithms/QuickSortoptimal.h
UTF-8
598
2.671875
3
[]
no_license
// // QuickSortOptimal.hpp // SortingAlgorithms // // Created by Indira Bobburi on 11/11/17. // Copyright © 2017 sjsu. All rights reserved. // #ifndef QUICKSORTOPTIMAL_H_ #define QUICKSORTOPTIMAL_H_ #include "QuickSorter.h" /** * The class that implements the optimal quicksort algorithm * for a vector of data by using a good pivot strategy. */ class QuickSortOptimal: public QuickSorter { public: QuickSortOptimal(string name); virtual ~QuickSortOptimal(); private: virtual Element& choose_pivot_strategy(const int left, const int right); }; #endif /* QUICKSORTOPTIMAL_H_ */
true
cc55e8e27d1faf914c2517538c32a23b1fb0f527
C++
BasvRossem/AllForBread
/Inventory/InventoryDisplay.cpp
UTF-8
17,191
2.515625
3
[]
no_license
#include "InventoryDisplay.hpp" #include <SFML/Graphics/Color.hpp> InventoryDisplay::InventoryDisplay(Party & party, sf::RenderWindow & window) : party(party), window(window), leftScreen(leftScreenSize.x, leftScreenSize.y), rightScreen(rightScreenSize.x, rightScreenSize.y) { ////Make virtualscreens sf::Vector2f leftScreenTopLeft(20.0, 20.0); sf::Vector2f rightScreenTopLeft(970.0, 20.0); leftScreen.setLocation(leftScreenTopLeft); rightScreen.setLocation(rightScreenTopLeft); ////Set backGround takatiki.loadFromFile("takatikimap.png"); background.setTexture(takatiki); background.setTextureRect({ 0, 0, 1920, 1080 }); ////Initiate tiles for (unsigned int i = 0; i < party.size(); i++) { pTile.first.push_back( std::make_shared<PlayerInventoryTile>( party[i], sf::Vector2f(0.0f, static_cast<float>(i * leftScreenSize.y / 4)), sf::Vector2f(static_cast<float>(leftScreenSize.x), static_cast<float>(leftScreenSize.y / 4)) ) ); } auto partyInventory = party.getInventory(); for (unsigned int i = 0; i < partyInventory.size(); i++) { pTile.second.push_back( std::make_shared<InventoryTile>( partyInventory[i], sf::Vector2f( 0.0f , static_cast<float>(i * 100) ), sf::Vector2f(static_cast<float>(rightScreenSize.x), 100.0f ) ) ); } ////Initiate selectbox selectBox.setPosition(pTile.first[0]->getSelectboxPosition()); selectBox.setSize(sf::Vector2f{ 80,80 }); selectBox.setFillColor(sf::Color(12, 85, 135)); selectBox.setOutlineColor(sf::Color(5, 55, 89)); ////varable needed for de selection selected.first = 0; selected.second = 0; lastSelected.first = 0; lastSelected.second = 0; ////text for navigation font.loadFromFile("Assets/arial.ttf"); text.setFont(font); text.setPosition(sf::Vector2f{ 10 ,1080 - 22 }); text.setCharacterSize(20); text.setFillColor(sf::Color::White); text.setString(""); text.setOutlineThickness(1); text.setOutlineColor(sf::Color::Black); } InventoryDisplay::~InventoryDisplay() { } void InventoryDisplay::use() { enum class InventoryMenu { left, right , equipItem , unequipItem}; enum class equip { left, right }; InventoryMenu state = InventoryMenu::left; equip eState = equip::left; keyHandler.setOverride(true); reloadTiles(); isOpen = true; sound.playSoundEffect(SoundEffect::bagOpen); while (isOpen && window.isOpen()) { sf::Event event; while (window.pollEvent(event)){ if (event.type == sf::Event::Closed) window.close(); if (event.type == sf::Event::KeyPressed) keyHandler.processKey(event.key.code); } draw(); switch (state) { case InventoryMenu::left: text.setString("Navigation use W A S D Unequip Item from player use Enter Exit inventory use ESC"); keyHandler.addListener(sf::Keyboard::A, []() {}); keyHandler.addListener(sf::Keyboard::D, [&]() {if (pTile.second.size() != 0) { state = InventoryMenu::right; setZeroSelected(1); }}); keyHandler.addListener(sf::Keyboard::W, [&]() { changeSelected(0, -1); }); keyHandler.addListener(sf::Keyboard::S, [&]() { changeSelected(0, 1); }); keyHandler.addListener(sf::Keyboard::U, []() {}); keyHandler.addListener(sf::Keyboard::Enter, [&]() {if (pTile.first[selected.second]->getWeaponTiles().size() != 0 || pTile.first[selected.second]->getArmorTiles().size() != 0) { state = InventoryMenu::unequipItem; select(selected.first, selected.second); lastSelected.first = selected.first; lastSelected.second = selected.second; setZeroSelected(0, lastSelected.second); }}); keyHandler.addListener(sf::Keyboard::Delete, [&]() {}); keyHandler.addListener(sf::Keyboard::Escape, [&]() {isOpen = false;}); break; case InventoryMenu::right: text.setString("Navigation use W A S D Equip Item to player use Enter Use a Consumeble use U Delete Item from Party inventory Exit inventory use ESC"); keyHandler.addListener(sf::Keyboard::A, [&]() {state = InventoryMenu::left; setZeroSelected(0); }); keyHandler.addListener(sf::Keyboard::D, []() {}); keyHandler.addListener(sf::Keyboard::W, [&]() {changeSelected(1, -1); }); keyHandler.addListener(sf::Keyboard::S, [&]() {changeSelected(1, 1); }); keyHandler.addListener(sf::Keyboard::U, [&]() {useItem(selected.second); if (itemToUse != nullptr) { isOpen = false; } }); keyHandler.addListener(sf::Keyboard::Delete, [&]() {if (pTile.second.size() != 0) { state = InventoryMenu::left; deleteItem(selected.second); changeSelected(0, 0);state = InventoryMenu::left; }}); keyHandler.addListener(sf::Keyboard::Enter, [&]() {state = InventoryMenu::equipItem; select(selected.first, selected.second); lastSelected.first = selected.first; lastSelected.second = selected.second; setZeroSelected(0); }); keyHandler.addListener(sf::Keyboard::Escape, [&]() {isOpen = false;}); break; case InventoryMenu::equipItem: text.setString("Navigation use W S Equip Item to player use Enter Exit Equip a Item use ESC"); keyHandler.addListener(sf::Keyboard::A, []() {}); keyHandler.addListener(sf::Keyboard::D, []() {}); keyHandler.addListener(sf::Keyboard::W, [&]() { changeSelected(0, -1); }); keyHandler.addListener(sf::Keyboard::S, [&]() { changeSelected(0, 1); }); keyHandler.addListener(sf::Keyboard::U, []() {}); keyHandler.addListener(sf::Keyboard::Delete, [&]() {}); keyHandler.addListener(sf::Keyboard::Escape, [&]() {state = InventoryMenu::right; reloadTiles(); setZeroSelected(0); }); keyHandler.addListener(sf::Keyboard::Enter, [&]() {state = InventoryMenu::left; addItemToCharacter(selected.second, lastSelected.second); setZeroSelected(0); }); break; case InventoryMenu::unequipItem: switch (eState) { case equip::left: text.setString("Navigation use W A S D Unequip Item from player use Enter Exit Unequip a Item use ESC"); keyHandler.addListener(sf::Keyboard::A, []() {}); keyHandler.addListener(sf::Keyboard::D, [&]() { eState = equip::right; changeSelected(1, 0, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::W, [&]() { changeSelected(0, -1, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::S, [&]() { changeSelected(0, 1, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::U, []() {}); keyHandler.addListener(sf::Keyboard::Delete, []() {}); keyHandler.addListener(sf::Keyboard::Enter, [&]() {state = InventoryMenu::left; removeItemFromCharacer(lastSelected.second, selected.first, selected.second); setZeroSelected(0); reloadTiles(); }); keyHandler.addListener(sf::Keyboard::Escape, [&]() {state = InventoryMenu::left; eState = equip::left; reloadTiles(); setZeroSelected(0); }); break; case equip::right: text.setString("Navigation use W A S D Unequip Item from player use Enter Exit Unequip a Item use ESC"); keyHandler.addListener(sf::Keyboard::A, [&]() { eState = equip::left; changeSelected(0, 0, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::D, []() {}); keyHandler.addListener(sf::Keyboard::W, [&]() { changeSelected(1, -1, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::S, [&]() { changeSelected(1, 1, lastSelected.second); }); keyHandler.addListener(sf::Keyboard::U, []() {}); keyHandler.addListener(sf::Keyboard::Delete, []() {}); keyHandler.addListener(sf::Keyboard::Enter, [&]() {state = InventoryMenu::left; removeItemFromCharacer(lastSelected.second, selected.first, selected.second); setZeroSelected(0); }); keyHandler.addListener(sf::Keyboard::Escape, [&]() {state = InventoryMenu::left; reloadTiles(); setZeroSelected(0); }); break; } break; } } sound.playSoundEffect(SoundEffect::bagClose); sf::sleep(sf::milliseconds(650)); } void InventoryDisplay::changeSelected(const int x, const int y, const int &character) { if (character == 4) { if (x == 0) { if (y + selected.second < signed int(pTile.first.size()) && y + selected.second >= 0) { selected.first = x; selected.second = y + selected.second; selectBox.setPosition(pTile.first[selected.second]->getSelectboxPosition()); } } else if (x == 1) { if (y + selected.second < signed int(pTile.second.size()) && y + selected.second >= 0) { selected.first = x; selected.second = y + selected.second; selectBox.setPosition(pTile.second[selected.second]->getSelectboxPosition()); } } } else { if (x == 0) { if (y + selected.second < signed int(pTile.first[character]->getWeaponTiles().size()) && y + selected.second >= 0) { selected.first = x; selected.second = y + selected.second; selectBox.setPosition(pTile.first[character]->getWeaponTiles()[selected.second]->getSelectboxPositionMini()); selectBox.setSize(sf::Vector2f{ 40,40 }); } } else if (x == 1) { if (y + selected.second < signed int(pTile.first[character]->getArmorTiles().size()) && y + selected.second >= 0) { selected.first = x; selected.second = y + selected.second; selectBox.setPosition(pTile.first[character]->getArmorTiles()[selected.second]->getSelectboxPositionMini()); selectBox.setSize(sf::Vector2f{ 20,20 }); } } } } void InventoryDisplay::setZeroSelected(const int & collum, const int &character) { if (collum == 0 && character == 4) { selected.first = collum; selected.second = 0; selectBox.setPosition(pTile.first[selected.second]->getSelectboxPosition()); selectBox.setSize(sf::Vector2f{ 80,80 }); } else if (collum == 1 && character == 4) { selected.first = collum; selected.second = 0; selectBox.setPosition(pTile.second[selected.second]->getSelectboxPosition()); selectBox.setSize(sf::Vector2f{ 80,80 }); } else if (character < 4) { if (pTile.first[character]->getWeaponTiles().size() != 0) { selected.first = collum; selected.second = 0; selectBox.setPosition(pTile.first[character]->getWeaponTiles()[0]->getSelectboxPositionMini()); selectBox.setSize(sf::Vector2f{ 40,40 }); } else if (pTile.first[character]->getArmorTiles().size() != 0) { selected.first = 1; selected.second = 0; selectBox.setPosition(pTile.first[character]->getArmorTiles()[0]->getSelectboxPositionMini()); selectBox.setSize(sf::Vector2f{ 20,20 }); } } } void InventoryDisplay::draw() { window.clear(); window.draw(background); drawLeftScreen(); drawRightScreen(); window.draw(selectBox); window.draw(text); window.display(); } void InventoryDisplay::drawLeftScreen() { leftScreen.drawSurfaceClear(halfTransparent); for (auto tile : pTile.first) { tile->draw(leftScreen); } leftScreen.drawSurfaceDisplay(); window.draw(leftScreen); } void InventoryDisplay::drawRightScreen() { rightScreen.drawSurfaceClear(halfTransparent); for (auto item : pTile.second) { item->draw(rightScreen); } rightScreen.drawSurfaceDisplay(); window.draw(rightScreen); } void InventoryDisplay::deleteItem(const int & i) { party.eraseItem(pTile.second[i]->getItem()); pTile.second.erase(std::remove(pTile.second.begin(), pTile.second.end(), pTile.second[i]), pTile.second.end()); pTile.second.clear(); auto partyInventory = party.getInventory(); for (unsigned int i = 0; i < partyInventory.size(); i++) { pTile.second.push_back( std::make_shared<InventoryTile>( partyInventory[i], sf::Vector2f(0.0f, static_cast<float>(i * 100)), sf::Vector2f(static_cast<float>(rightScreenSize.x), 100.0f) ) ); } } void InventoryDisplay::select(const int & collom, const int & row) { if (collom == 0) { pTile.first[row]->setColor(sf::Color(123, 249, 84)); pTile.first[row]->setBorderColor(sf::Color(72, 114, 59)); } else if (collom == 1) { pTile.second[row]->setColor(sf::Color(123, 249, 84)); pTile.second[row]->setBorderColor(sf::Color(72, 114, 59)); } } void InventoryDisplay::addItemToCharacter(const int & character, const int & item) { // DONT TOUCH THIS FUNCTION WITH A 10FT POLE std::shared_ptr<Weapon> a = std::dynamic_pointer_cast<Weapon>(pTile.second[item]->getItem()); std::shared_ptr<Armor> b = std::dynamic_pointer_cast<Armor>(pTile.second[item]->getItem()); if (a != nullptr) { std::vector<int> itemsToRemove; switch (a->getWeaponSlot()) { case WeaponSlots::twohanded: for (unsigned int i = 0; i < pTile.first[character]->getWeaponTiles().size(); i++) { std::shared_ptr<Weapon> tmp = std::dynamic_pointer_cast<Weapon>(pTile.first[character]->getItem(0, i)); if (tmp != nullptr) { itemsToRemove.push_back(i); } } for (unsigned int i = 0; i < itemsToRemove.size(); i++) { removeItemFromCharacer(character, 0, itemsToRemove[i] - i); } party.addWeapontoPartyMember(pTile.first[character]->getCharacter(), a); deleteItem(item); sound.playSoundEffect(SoundEffect::weaponEquip); break; case WeaponSlots::mainhand: for (unsigned int i = 0; i < pTile.first[character]->getWeaponTiles().size(); i++) { std::shared_ptr<Weapon> tmp = std::dynamic_pointer_cast<Weapon>(pTile.first[character]->getItem(0, i)); if (tmp != nullptr) { if (tmp->getWeaponSlot() == WeaponSlots::mainhand || tmp->getWeaponSlot() == WeaponSlots::twohanded) { removeItemFromCharacer(character, 0, i); } } } party.addWeapontoPartyMember(pTile.first[character]->getCharacter(), a); deleteItem(item); sound.playSoundEffect(SoundEffect::weaponEquip); break; case WeaponSlots::offhand: for (unsigned int i = 0; i < pTile.first[character]->getWeaponTiles().size(); i++) { std::shared_ptr<Weapon> tmp = std::dynamic_pointer_cast<Weapon>(pTile.first[character]->getItem(0, i)); if (tmp != nullptr) { if (tmp->getWeaponSlot() == WeaponSlots::offhand || tmp->getWeaponSlot() == WeaponSlots::twohanded) { removeItemFromCharacer(character, 0, i); } } } party.addWeapontoPartyMember(pTile.first[character]->getCharacter(), a); deleteItem(item); sound.playSoundEffect(SoundEffect::weaponEquip); break; default: break; } } else if (b != nullptr) { auto map = pTile.first[character]->getCharacter()->getArmorMap(); std::vector<ArmorSlots> slots; for (auto m : map) { slots.push_back(m.first); } auto alreadyUquipt = std::find(slots.begin(), slots.end(), b->getArmorSlot()); if (alreadyUquipt == slots.end()) { party.addArmortoPartyMember(pTile.first[character]->getCharacter(), b); deleteItem(item); } else { std::cout << "else van armor item equip\n"; for (unsigned int i = 0; i < pTile.first[character]->getArmorTiles().size(); i++) { std::shared_ptr<Armor> tmp = std::dynamic_pointer_cast<Armor>(pTile.first[character]->getItem(1, i)); if (tmp != nullptr) { if (tmp->getArmorSlot() == b->getArmorSlot()) { removeItemFromCharacer(character, 1, i); party.addArmortoPartyMember(pTile.first[character]->getCharacter(), b); deleteItem(item); sound.playSoundEffect(SoundEffect::armorEquip); } } } } } reloadTiles(); } void InventoryDisplay::removeItemFromCharacer(const int & character, const int & collom, const int & row) { if (pTile.first[character]->getWeaponTiles().size() !=0 || pTile.first[character]->getArmorTiles().size() !=0 ) { if (collom == 0) { std::shared_ptr<Weapon> a = std::dynamic_pointer_cast<Weapon>(pTile.first[character]->getItem(collom, row)); if (a != nullptr) { party.addToInventory(pTile.first[character]->getItem(collom, row)); pTile.first[character]->getCharacter()->removeWeapon(a->getWeaponSlot()); } reloadTiles(); } else if (collom == 1) { std::shared_ptr<Armor> b = std::dynamic_pointer_cast<Armor>(pTile.first[character]->getItem(collom, row)); if (b != nullptr) { party.addToInventory(pTile.first[character]->getItem(collom, row)); pTile.first[character]->getCharacter()->removeArmor(b->getArmorSlot()); } reloadTiles(); } } } void InventoryDisplay::reloadTiles(){ pTile.first.clear(); for (unsigned int i = 0; i < party.size(); i++) { pTile.first.push_back( std::make_shared<PlayerInventoryTile>( party[i], sf::Vector2f(0.0f, static_cast<float>(i * leftScreenSize.y / 4)), sf::Vector2f(static_cast<float>(leftScreenSize.x), static_cast<float>(leftScreenSize.y / 4)) ) ); } pTile.second.clear(); auto partyInventory = party.getInventory(); for (unsigned int i = 0; i < partyInventory.size(); i++) { pTile.second.push_back( std::make_shared<InventoryTile>( partyInventory[i], sf::Vector2f(0.0f, static_cast<float>(i * 100)), sf::Vector2f(static_cast<float>(rightScreenSize.x), 100.0f) ) ); } } void InventoryDisplay::useItem(const unsigned int & row) { itemToUse = std::dynamic_pointer_cast<Consumable>(pTile.second[row]->getItem()); if (itemToUse != nullptr) { itemToUse->activate(); itemToUse->setQuantityUses(itemToUse->getQuantityUses() - 1); if (itemToUse->getQuantityUses() <= 0) { deleteItem(row); } } } std::shared_ptr<Consumable> InventoryDisplay::getUsedItem() { std::shared_ptr<Consumable> temp = itemToUse; itemToUse = nullptr; return temp; }
true
f717a275df94549a026d15e22b5c3b874c2006a9
C++
cbehren/Iltis
/DustModule.H
UTF-8
2,419
2.515625
3
[]
no_license
#ifndef __DUST_MODULE_H #define __DUST_MODULE_H #ifdef _OPENMP #include "omp.h" #endif #include <iostream> #include "BaseParticle.H" #include "BaseCell.H" //This defines a number of implementations for the treatment of dust. //TODO this is all for the Lyman-alpha line, more or less. Make it more general? enum DUST_MODULE_TYPE{DM_NULL,DM_VERHAMME12,DM_DAHLIA}; class DustModule{ protected: virtual void init() = 0; static double G_Greenstein; static double albedo; static DUST_MODULE_TYPE type; public: virtual ~DustModule() {} virtual double scatter(const BaseCell* cell,const BaseParticle* p,double newk[],bool k_and_atom_velocity_given=false) = 0; static double GreensteinPhase(const double R); static double GreensteinProbability(const double mu); static void AnisotropicReemission(const double oldk[],double newk[]); virtual double ConvertDust(double density, double temperature, double metallicity) = 0; virtual double DustConversionFactor() = 0; virtual double tauConstFactor() = 0; virtual double getAlbedo() = 0; }; class DustModuleNull : public DustModule{ protected: void init(); public: DustModuleNull() {init();} double scatter(const BaseCell* cell,const BaseParticle* p,double newk[],bool k_and_atom_velocity_given=false); double DustConversionFactor(); double ConvertDust(double density, double temperature, double metallicity) {return 0;} //int ConvertDust(MultiFab& fab,const double dx); double tauConstFactor(); double getAlbedo(); }; class DustModuleVerhamme12 : public DustModule{ protected: void init(); public: DustModuleVerhamme12() {init();} double scatter(const BaseCell* cell,const BaseParticle* p,double newk[],bool k_and_atom_velocity_given=false); double DustConversionFactor(); double ConvertDust(double density, double temperature, double metallicity); //int ConvertDust(MultiFab& fab,const double dx); double tauConstFactor(); double getAlbedo(); }; class DustModuleDahlia : public DustModule{ protected: void init(); double tauConst=-1; public: DustModuleDahlia(); double scatter(const BaseCell* cell,const BaseParticle* p,double newk[],bool k_and_atom_velocity_given=false); double DustConversionFactor(); double ConvertDust(double density, double temperature, double metallicity); //int ConvertDust(MultiFab& fab,const double dx); double tauConstFactor(); double getAlbedo(); }; #endif
true
ffade0b6ff7bacd289b93fd05ee48769cf8555ed
C++
CathalRedmond/Games-Jam-2018
/GamesJam2018/GamesJam2018/Field.cpp
UTF-8
674
2.640625
3
[]
no_license
#include "Field.h" Field::Field() { } Field::~Field() { } void Field::render(sf::RenderWindow & t_window) { t_window.draw(m_fieldSprite); } void Field::setTexture(sf::Texture const & t_fieldTexture) { m_fieldTexture = t_fieldTexture; setUpSprites(); } sf::Sprite Field::getSprite() { return m_fieldSprite; } void Field::setPosition(sf::Vector2f t_fieldPosition) { m_fieldPosition = t_fieldPosition; m_fieldSprite.setPosition(m_fieldPosition); } void Field::setScale(float x, float y) { m_fieldSprite.setScale(sf::Vector2f(x, y)); } void Field::setUpSprites() { m_fieldSprite.setTexture(m_fieldTexture); m_fieldSprite.setPosition(m_fieldPosition); }
true
5870d50a217a199136c535ec218f87d04f783683
C++
captabhi/CodechefArchive
/robot&batons.cpp
UTF-8
802
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main() { int n,m,i,j,k,count1; cin>>n; cin>>m; int arr1[n]; char arr2[n]; for(i=0;i<n;i++) arr2[i]='#'; for(i=0;i<n;i++) { cin>>arr[i]; } i=0; while(i<n) { cin>>temp; arr2[temp]='*'; i++ } count1=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(arr1[j]==1)&&arr2[j]=='#') { flag=0; break; } else flag=1; } if(flag==1) count1++; temp=arr[n-1]; for(k=n-2;k>0;k++) { arr[k+1]=arr[k]; } arr[0]=temp; } cout<<"ANSWER:"<<count1<<endl; return 0; }
true
b6480d3e1f0d7b05d894bb5a2c50d43db71a5bf4
C++
crisdeodates/Robotics-control-toolbox
/ct_optcon/include/ct/optcon/filter/SystemModelBase.h
UTF-8
1,854
2.546875
3
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/********************************************************************************************************************** This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich. Licensed under the BSD-2 license (see LICENSE file in main directory) **********************************************************************************************************************/ #pragma once namespace ct { namespace optcon { /*! * \ingroup Filter * * \brief System model is an interface that encapsulates the integrator to be able to propagate the system, but is also * able to compute derivatives w.r.t. both state and noise. * * @tparam STATE_DIM * @tparam CONTROL_DIM */ template <size_t STATE_DIM, size_t CONTROL_DIM, typename SCALAR = double> class SystemModelBase { public: using state_vector_t = ct::core::StateVector<STATE_DIM, SCALAR>; using state_matrix_t = ct::core::StateMatrix<STATE_DIM, SCALAR>; using control_vector_t = ct::core::ControlVector<CONTROL_DIM, SCALAR>; using Time_t = SCALAR; //! Virtual destructor. virtual ~SystemModelBase() = default; //! Propagates the system giving the next state as output. virtual state_vector_t computeDynamics(const state_vector_t& state, const control_vector_t& control, const Time_t dt, Time_t t) = 0; //! Computes the derivative w.r.t state. virtual state_matrix_t computeDerivativeState(const state_vector_t& state, const control_vector_t& control, const Time_t dt, Time_t t) = 0; //! Computes the derivative w.r.t noise. virtual state_matrix_t computeDerivativeNoise(const state_vector_t& state, const control_vector_t& control, const Time_t dt, Time_t t) = 0; }; } // namespace optcon } // namespace ct
true
595f6f0d8b106cb2d5faaa3a128ea40db832368c
C++
beaucha3/LeetCode-OJ
/longest_substring_without_repeating_characters.cpp
UTF-8
1,801
3.703125
4
[]
no_license
class Solution { public: int lengthOfLongestSubstring(string s) { /* Idea: A hash table can be used to keep track of which characters have been seen so far in a given substring */ unordered_map<char, int> charTrack; /* Declare hash table */ int maxLength = 0; /* Length of longest substring w/out repeating characters. Initially set to 0 */ int start = -1; /* Used to help keep track of length of current substring (note: i - start will be this length) */ int i; /* Used to index characters in the string */ for(i = 0; i < s.length(); i++) /* Iterate through characters in the string */ { /* If the character is already in the hashmap, then we process the substring */ if(charTrack.count(s[i]) != 0) { if((i-1-start) > maxLength) /* Update with the new maximum length if necessary. i-1-start is the current length */ maxLength = (i-1-start); /* ** Update the value of start. ** It should be the larger of the index of the previous occurrence of s[i] ** and its current value (as this accounted for previous duplicates). */ if(charTrack[s[i]] > start) start = charTrack[s[i]]; /* This value is given by the hash map */ } charTrack[s[i]] = i; /* Add the character to the map */ } if((i-1-start) > maxLength) /* Update with the new maximum length one more time (necessary if longest substring is at the end) */ maxLength = (i-1-start); return maxLength; /* Return the maximum length */ } };
true
94edc77b3c5854f5fe70887f3331b49b1373708b
C++
anddregarcia/Laboratorio-PequenosExemplosC
/LISTA4.CPP
UTF-8
1,475
3.21875
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <malloc.h> struct reg { int id; struct reg *prox; struct reg *ant; }; struct reg *pos = NULL; void add(int novo_id) { struct reg *novo = (struct reg *) malloc(sizeof(reg)); novo->id=novo_id; if (pos==NULL) { novo->prox=NULL; // A novo->ant=NULL; // B pos=novo; // C } else if (pos->prox!=NULL) { novo->prox=pos->prox; // A novo->ant=pos; // B pos->prox=novo; // C novo->prox->ant=novo; // D } else { novo->prox=pos; // A novo->ant=pos; // B pos->prox=novo; // C pos->ant=novo; // D } } void rmv() { if (pos!=NULL) { if (pos->prox!=NULL) { pos->ant->prox=pos->prox; pos->prox->ant=pos->ant; if (pos==pos->ant || pos==pos->prox) { free(pos); pos=NULL; } else { struct reg *rmv = pos; pos=pos->ant; free(rmv); } } else { free(pos); pos=NULL; } } } void lista() { struct reg *atual = pos; if (atual!=NULL) { do { printf("%d\n",atual->id); atual=atual->prox; } while (atual!=pos); } else { printf("LISTA VAZIA!"); } } void main(void) { clrscr(); add(1); add(2); add(3); add(4); lista(); printf("Pos = %d\n\n",pos->id); rmv(); lista(); printf("Pos = %d\n\n",pos->id); rmv(); lista(); printf("Pos = %d\n\n",pos->id); rmv(); lista(); printf("Pos = %d\n\n",pos->id); rmv(); lista(); getch(); }
true
1fd0cedd47a44aa11dacca47c4d21f94d648a7fd
C++
msdedwards/FieldSweeper
/Board.cpp
UTF-8
2,564
2.96875
3
[]
no_license
#include "StdAfx.h" #include "Board.h" #include <ctime> CBoard::CBoard(void) : SquareRowCount(16), SquareColumnCount(16) { Reset(); } CBoard::~CBoard(void) { } CSquare& CBoard::GetSquare(int row, int col) { return _Squares[row][col]; } void CBoard::Reset() { GameOver=false; GameWon=false; for(UINT col=0; col<SquareColumnCount; col++) { for(UINT row=0; row<SquareRowCount; row++) { CSquare& square=GetSquare(row,col); square.Reset(); } } srand((unsigned int)time(NULL)); for (int randMines=(SquareRowCount*SquareColumnCount)/8; randMines>0; ) { int randcol= rand() % SquareColumnCount; int randrow= rand() % SquareRowCount; CSquare& square=GetSquare(randrow,randcol); if(!square.IsMine) { square.IsMine=true; UpdateAdjacentMineCount(randrow-1,randcol-1); UpdateAdjacentMineCount(randrow-1,randcol); UpdateAdjacentMineCount(randrow-1,randcol+1); UpdateAdjacentMineCount(randrow,randcol-1); UpdateAdjacentMineCount(randrow,randcol+1); UpdateAdjacentMineCount(randrow+1,randcol-1); UpdateAdjacentMineCount(randrow+1,randcol); UpdateAdjacentMineCount(randrow+1,randcol+1); randMines--; } } } void CBoard::UpdateAdjacentMineCount(int row, int col) { if(row>=0&&col>=0&&row<SquareRowCount&&col<SquareColumnCount) { CSquare& square=GetSquare(row,col); square.AdjacentMineCount++; } } void CBoard::PeekSquare(int row, int col) { CSquare& square=GetSquare(row,col); if(square.IsMine) { if(!square.IsFlagged) { GameOver=true; square.WasGameOver=true; } } else { Reveal(row, col); } } void CBoard::FlagSquare(int row, int col) { CSquare& square=GetSquare(row,col); square.IsFlagged=!square.IsFlagged; if(square.IsMine) { if(square.IsFlagged) { _FlagCount++; } else { _FlagCount--; } UpdateWinStatus(); } } void CBoard::SetSize(int rowCount, int colCount) { SquareRowCount=rowCount; SquareColumnCount=colCount; } void CBoard::Reveal(int row, int col) { if(row>=0&&col>=0&&row<SquareRowCount&&col<SquareColumnCount) { CSquare& square=GetSquare(row,col); if(square.IsHidden&&!square.IsMine) { _RevealedCount++; UpdateWinStatus(); square.IsHidden=false; if(square.AdjacentMineCount==0) { Reveal(row-1,col-1); Reveal(row-1,col); Reveal(row-1,col+1); Reveal(row,col-1); Reveal(row,col+1); Reveal(row+1,col-1); Reveal(row+1,col); Reveal(row+1,col+1); } } } } void CBoard::UpdateWinStatus(void) { GameOver=GameWon=((SquareColumnCount*SquareRowCount)-_FlagCount-_RevealedCount)==0; }
true
22cba554cb3923eff92fe5091a573a31e2d0817e
C++
mkbn-consultancy/modern_cpp
/noexcept/3_nested_exception.cpp
UTF-8
2,127
3.140625
3
[]
no_license
//-------- MKBN Training and Consultancy --------// //--------------- miri@mkbn.co.il ---------------// #include <iostream> #include <vector> #include <string> #include <fstream> void manipulateFile(const std::string& fName){ //open the file and do some manipulation on it try{ std::ifstream fin(fName); if(!fin.is_open()){ std::cout<<"[manipulateFile:] throw: "; throw std::runtime_error("cannot open file "); } else{ //do some staff... fin.close(); } } catch(std::runtime_error& ex){ std::runtime_error err(fName + ": " + ex.what()); std::cout<<err.what()<<std::endl; ex = err; throw; } } void processFiles(const std::vector<std::string>& files){ int numBrokenPaths = 0; //process all files for(auto f : files){ try{ manipulateFile(f); } catch(std::runtime_error& ex){ numBrokenPaths++; if(numBrokenPaths > 0.3*files.size()){ std::cout<<"[processFile:] throwing exception of threashold\n"; throw std::runtime_error("Too many broken paths, process stopped!"); } } } } int main(){ std::vector<std::string> filePaths {R"(C:\filesForModernCpp\1.txt)", R"(C:\filesForModernCpp\2.txt)", R"(C:\filesForModernCpp\3.txt)", R"(C:\filesForModernCpp\4.txt)", R"(C:\filesForModernCpp\5.txt)", R"(C:\filesForModernCpp\6.txt)", R"(C:\filesForModernCpp\7.txt)", R"(C:\filesForModernCpp\8.txt)", R"(C:\filesForModernCpp\9.txt)" }; try{ processFiles(filePaths); } catch(std::runtime_error& err){ std::cout<<"[in main]: Exception: "<<err.what(); } }
true
12928c6060e3e905b7f60ffde69e76aefcc6ce46
C++
Curiouser/simplex
/SimplexProblem.cpp
UTF-8
7,975
3.09375
3
[]
no_license
#include "stdafx.h" #include "SimplexProblem.h" using namespace std; SimplexProblem::SimplexProblem() { nbInequations = 0; nbVariables = 0; systemIneq = new double * [nbInequations]; //each systemIneq[nbIneq] is of size nbVariables + 2, for relational sign and result // we have deleted the +2 z = new double[nbVariables + 1]; //expression to maximize; //WHYYYYYYYYYYYYYYYY +1 ????????? signs = new int[nbInequations]; results = new double[nbInequations]; } SimplexProblem::SimplexProblem(int nbIneq, int nbVar) { nbInequations = nbIneq; nbVariables = nbVar; systemIneq = new double *[nbInequations]; z = new double[nbVariables + 1]; signs = new int[nbInequations]; results = new double[nbInequations]; } SimplexProblem::~SimplexProblem() { } int SimplexProblem::getNbIneq() { return nbInequations; } void SimplexProblem::setNbIneq(int nbIneq) { nbInequations = nbIneq; systemIneq = new double *[nbInequations]; signs = new int[nbInequations]; results = new double[nbInequations]; } int SimplexProblem::getNbVar() { return nbVariables; } void SimplexProblem::setNbVar(int nbVar) { nbVariables = nbVar; for (int i = 0; i < nbInequations; i++) systemIneq[i] = new double[nbVariables + 2]; z = new double[nbVariables + 1]; } double ** SimplexProblem::getSystIneq() { return systemIneq; } void SimplexProblem::setSystIneq(double ** array) { if (array == NULL) { cout << "Issue in SimplexProblem::setSystIneq array is null" << endl; return; } int i, j; int sizeA, sizeB; sizeA = sizeof(array) / sizeof(array[0][0]); systemIneq = new double*[sizeA]; for (i = 0; i < sizeA; i++) { sizeB = sizeof(array[i]) / sizeof(array[0][0]); systemIneq[i] = new double[sizeB]; for (j = 0; i < sizeB; j++) { systemIneq[i][j] = array[i][j]; } } } double * SimplexProblem::getZ() { return z; } void SimplexProblem::setZ(double * array) { if (array == NULL) cout << "Issue in SimplexProblem::setSystIneq array is null" << endl; else { int i, size; size = sizeof(array) / sizeof(array[0]); z = new double[size]; for (i = 0; i < size; i++) z[i] = array[i]; } } void SimplexProblem::setCoefficient(int ineq, int var, double coeff) { if (ineq >= 0 && ineq <= nbInequations && var >= 0 && var <= nbVariables) systemIneq[ineq][var] = coeff; else cout << "Problem in SimplexProblem::setCoefficient for inequation number " + ineq << "var number " + var << " not correct" << endl; } double SimplexProblem::getCoefficient(int ineq, int var) { if (ineq >= 0 && ineq <= nbInequations && var >= 0 && var <= nbVariables) return systemIneq[ineq][var]; else { cout << "Problem in SimplexProblem::getCoefficient for inequation number " + ineq << "var number " + var << " not correct" << endl; return -1; } } void SimplexProblem::setSign(int ineq, int sign) { if (ineq >= 0 && ineq <= nbInequations) { systemIneq[ineq][nbVariables + 1] = sign; signs[ineq] = sign; } else cout << "Problem in SimplexProblem::setSign for inequation number " + ineq << endl; } int SimplexProblem::getSign(int ineq) { if (ineq >= 0 && ineq <= nbInequations) return signs[ineq]; else { cout << "Problem in SimplexProblem::getSign for inequation number " + ineq << endl; return -1; } } void SimplexProblem::setResult(int ineq, double result) { if (ineq >= 0 && ineq <= nbInequations) { systemIneq[ineq][nbVariables + 2] = result; results[ineq] = result; } else cout << "Problem in SimplexProblem::setResult for inequation number " + ineq << endl; } double SimplexProblem::getResult(int ineq) { if (ineq >= 0 && ineq <= nbInequations) return results[ineq]; else { cout << "Problem in SimplexProblem::getResult for inequation number " + ineq << endl; return -1; } } void SimplexProblem::setCoeffInZ(int var, double coeff) { if (var >= 0 && var <= nbVariables) z[var] = coeff; else cout << "Problem in SimplexProblem::setCoeffInZ for variable " + var << endl; } double SimplexProblem::getCoeffInZ(int var) { if (var >= 0 && var <= nbVariables) return z[var]; else { cout << "Problem in SimplexProblem::getCoeffInZ for variable " + var << endl; return -1; } } void SimplexProblem::ReadFile(ifstream *file) //BOF NE FONCTIONNE PAS TROP // A REVOIR, PAS CORRIGEE { int nbLines = 0; //nbInequations int nbCol = 0; //nbVariables if (file) { *file >> nbLines >> nbCol; cout << endl << "nb of lines : " << nbLines << endl; cout << "nb of columns : " << nbCol << endl << endl; double **tab = new double*[nbLines]; setNbIneq(nbLines); setNbVar(nbCol); for (int i = 0; i <= nbLines; i++) { tab[i] = new double[nbCol + 2]; // +2 corresponds to the relational sign and result } for (int i = 0; i <= nbLines; i++) { for (int j = 0; j <= nbCol + 1; j++) { *file >> tab[i][j]; } } for (int i = 0; i <= nbLines; i++) { for (int j = 0; j <= nbCol + 1; j++) { cout << tab[i][j] << " "; } cout << endl; } cout << endl; double *z = new double[nbCol + 1]; for (int i = 0; i <= nbCol + 1; i++) { z[i] = tab[nbLines][i]; } cout << " Z = " << endl; for (int i = 0; i <= nbCol + 1; i++) { cout << z[i] << " "; } setSystIneq(tab); setZ(z); } else cout << "Erreur : Impossible d ouvrir le fichier " << endl; } void SimplexProblem::ReadFileBinaryValue(ifstream *file) { // TO DO } void SimplexProblem::createProblemFromIO() { int nbVar, nbIneq, sign = 0; double result, coeff = 0; do { cout << "Please write the number of linear inequations : " << endl; cin >> nbIneq; } while (nbIneq < 1); setNbIneq(nbIneq); cout << "\n" << endl; do { cout << "Please write the number of variables : " << endl; cin >> nbVar; } while (nbVar < 1); setNbVar(nbVar); cout << "\n" << endl; for (int i = 0; i < nbIneq; i++) { cout << "Now you are going to be asked the coefficient for each variable in inequation number " + i << endl; cout << "Please write 0 when the variable does not appear in the inequation " << endl; for (int j = 0; j < nbVar; j++) { cout << "coefficient for variable " + j << endl; cin >> coeff; setCoefficient(i, j, coeff); } cout << "\n" << endl; cout << "Please write the relational sign for inequation number" + i << endl; cout << "1 - Inferior or equal" << endl; cout << "2 - Superior or equal " << endl; cout << "3 - Equal " << endl << endl; do { cin >> sign; } while (sign != 1 && sign != 2 && sign != 3); setSign(i, sign); cout << "\n" << endl; cout << "Please write the result of inequation number " + i << endl; cin >> result; setResult(i, result); cout << "\n" << endl; } cout << endl << endl; cout << "You are now going to be asked about the coefficients in the function Z to maximize" << endl; cout << "Please write 0 when the variable does not appear in the inequation " << endl; for (int i = 0; i < nbVar; i++) { cout << "coefficient in Z for variable " + i << endl; cin >> coeff; setCoeffInZ(i, coeff); cout << "\n" << endl; } cout << endl << "The system of inequations is as follows : " << endl; for (int i = 0; i < nbIneq; i++) { cout << getCoefficient(i, 0) << "X1 "; for (int j = 1; j < nbVar; j++) cout << " + " << getCoefficient(i, j) << "X" << j + 1; switch (getSign(i)) { case 1: cout << " <= "; case 2: cout << " >= "; case 3: cout << " = "; } cout << getResult(i) << endl; } cout << "The function to maximize is " << endl; cout << " Z = "; cout << getCoeffInZ(0) << "X" << "1"; for (int i = 0; i < nbVar; i++) cout << " + " << getCoeffInZ(i) << "X" << i + 1; cout << endl << endl; }
true
1615f29154be41777ceaeadbd9e4e9f4d06d4eb6
C++
PrinceClover/cpp_learn
/20160615/src/complex.cc
UTF-8
1,930
3.4375
3
[]
no_license
/// /// @file complex.cc /// @author PrinceClover(871353611@qq.com) /// @date 2016-06-15 21:47:37 /// #include <iostream> #include <stdio.h> using std::cout; using std::endl; using std::cin; class Complex { //the inputstream and outputstream structure must be overload by friend //return value must be a quote of stream object friend std::ostream & operator << (std::ostream &os,const Complex &rhs); friend std::istream & operator >> (std::istream &is,Complex &rhs); friend Complex operator + (const Complex &lhs, const Complex &rhs); public: Complex(double dreal = 0,double dimag = 0) : _dreal(dreal) , _dimag(dimag) { cout << "Complex constructor" << endl; } private: double _dreal; double _dimag; }; Complex operator + (const Complex &lhs,const Complex &rhs) { return Complex(lhs._dreal + rhs._dreal, lhs._dimag + lhs._dimag); } std::ostream & operator << (std::ostream & os,const Complex &rhs) { if(rhs._dreal > 0) { os << rhs._dreal; if(rhs._dimag > 0) { os << " + " << rhs._dimag << "i"; } else if(rhs._dimag < 0) { os << " - " << rhs._dimag * (-1) << "i"; } } else if(rhs._dreal < 0) { os << " - " << rhs._dreal << endl; if(rhs._dimag > 0) { os << " + " << rhs._dimag << "i"; } else if(rhs._dimag < 0) { os << " - " << rhs._dimag *(-1) << "i"; } } else { if(rhs._dimag > 0) { os << " + " << rhs._dimag << "i"; } else if(rhs._dimag < 0) { os << " - " << rhs._dimag *(-1) << "i"; } } return os; } std::istream & operator >> (std::istream &is,Complex & rhs) { is >> rhs._dreal; while(is.get() != '*'); //'*' means end of dreal is >> rhs._dimag; return is; } int main(void) { Complex c1(1,-2); Complex c2(0,-4); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; Complex c3 = c1 + c2; cout << "c3 = " << c3 << endl; Complex c4(1,2); cin >> c4; cout << "c4 = " << c4 << endl; return 0; }
true
06f2b0eeae75dc63b38faed94f30bfb864ee11ae
C++
zhongxuanS/-
/PieceSet.h
UTF-8
645
3.203125
3
[]
no_license
#pragma once #include "Piece.h" //管理所有的图形,一共有7*4=28种 class PieceSet { public: enum{ NUM_PIECES = 7, NUM_ROTATIONS = 4 }; PieceSet(); ~PieceSet(); // 按照指定的id和rotation获取对应的图形 Piece* getPiece(int id, int rotation = 0) const; // 获得随机图形 inline Piece* getRandomPiece() const { return getPiece(rand() % NUM_PIECES, rand() % NUM_ROTATIONS); } protected: //保存所有的图形 Piece* pieces_[NUM_PIECES][NUM_ROTATIONS]; //从初始化的7个图形,通过旋转生产28种图形 void rotateAll(); // 逆时针旋转 void rotate(POINT* apt, int numPoints = 4); };
true
13bf03905810944b9780b39d7410ef1613cd8882
C++
Heihuang/view
/algorithm/stack/外观数列.hpp
UTF-8
1,115
4
4
[]
no_license
/* 题目:给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第n项,注意:整数序列中的每一项将表示为一个字符串。 「外观数列」是一个整数序列,从数字 1 开始,序列中的每一项都是对前一项的描述。 1. 1 2. 11 3. 21 4. 1211 5. 111221 */ class Solution { public: string countAndSay(int n) { if(n == 1) return "1"; string previous = countAndSay(n-1), result = ""; // 使用递归来一层一层往前推 int count = 1; // count用来计数 for(int i=0;i<previous.length();i++) { if(previous[i] == previous[i+1]) { count ++; // 比如previous是111221时,111部分会让count=3,此时i在第三个1处 } else { result += to_string(count) + previous[i]; // result会从空变成“31”(当i在第三个1处时) count = 1; // 由于i在第三个1处时,i+1处的值为2,1 != 2,所以count重新变成1 } } return result; } };
true
c921bdc05e56e46ec7b6997bfd637fbf06f4c346
C++
eddiehoyle/sevengine
/src/Utilities.cc
UTF-8
3,000
2.90625
3
[ "MIT" ]
permissive
// // Created by Eddie Hoyle on 6/08/16. // #include <iostream> #include <vector> #include <cmath> #include "Utilities.hh" void test( std::string x ) { // TODO } const char* readShaderFile( const std::string& path ) { // Try open the file FILE* fp = fopen(path.c_str(), "r"); if ( fp == NULL ) { return NULL; } fseek(fp, 0L, SEEK_END); long size = ftell(fp); fseek(fp, 0L, SEEK_SET); char* buf = new char[size + 1]; fread(buf, 1, size, fp); buf[size] = '\0'; fclose(fp); return buf; } GLuint compileShader( const char *path, GLenum type ) { GLuint id = glCreateShader( type ); const char* shader = readShaderFile( path ); glShaderSource( id, 1, &shader, NULL ); glCompileShader( id ); GLint result = GL_FALSE; GLsizei length; // Check the program glGetShaderiv( id, GL_COMPILE_STATUS, &result ); glGetShaderiv( id, GL_INFO_LOG_LENGTH, &length ); if ( length > 0 ){ std::vector< char > log( length + 1 ); glGetShaderInfoLog( id, length, &length, &log[0] ); printf( "%s\n", &log[0] ); } else { printf( "Shader compiled succesfully: %d\n", id ); } return id; } bool linkProgram( GLuint program, GLuint vertexId, GLuint fragmentId ) { // Link the program printf("Linking program\n"); glAttachShader( program, vertexId ); glAttachShader( program, fragmentId ); glLinkProgram( program ); GLint Result = GL_FALSE; int InfoLogLength; // Check the program glGetProgramiv( program, GL_LINK_STATUS, &Result); glGetProgramiv( program, GL_INFO_LOG_LENGTH, &InfoLogLength); if ( InfoLogLength > 0 ){ std::vector<char> ProgramErrorMessage(InfoLogLength+1); glGetProgramInfoLog(program, InfoLogLength, NULL, &ProgramErrorMessage[0]); printf("%s\n", &ProgramErrorMessage[0]); } glDetachShader( program, vertexId ); glDetachShader( program, fragmentId ); glDeleteShader( vertexId ); glDeleteShader( fragmentId ); printf( "Program %d linked with shaders [%d, %d] successfully!\n", program, vertexId, fragmentId ); return true; } void checkError() { GLenum err = glGetError(); while( err != GL_NO_ERROR ) { std::string error; switch( err ) { case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; default: return; } std::cerr << "GL_" << error.c_str() <<" - " << std::endl; err = glGetError(); } }
true
1c958e9e3dcee812bf35931c599420ab76c4c00c
C++
sllujaan/Modern-OpenGL
/Modern-OpenGL/Util.h
UTF-8
482
3.125
3
[]
no_license
#pragma once #include"pch.h" namespace util { static int loop = 0; /* * slows down the current thread. * @param[in] milliseconds: time for sleeping the current calling thread. * @param[in] logIteration: true or false, it prints the loop iteration. */ static void handleloopCount(size_t milliseconds, bool logIteration) { std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); if (logIteration) { loop++; std::cout << loop << std::endl; } } }
true
c8d34582c99d81a658dbd4453a483bbe84215e1a
C++
Equinox-/Mirage--
/SGE/GLUtil/GLTexture.cpp
UTF-8
5,948
2.578125
3
[]
no_license
/* * GLTexture.cpp * * Created on: Jul 31, 2013 * Author: lwestin */ #include "GLTexture.h" #include "GLColor.h" #include <stdio.h> #include <stdlib.h> #include <png.h> #include <GL/gl.h> GLTexture::GLTexture() { pixFMT = 0; rawData = NULL; height = 0; width = 0; textureID = 0; rowBytes = 0; bitsPerPixel = 0; } GLTexture::~GLTexture() { freeRawData(); freeTexture(); } void GLTexture::freeRawData() { if (rawData != NULL) { free(rawData); rawData = NULL; } } void GLTexture::freeTexture() { if (textureID > 0) { glDeleteTextures(1, &textureID); } } void GLTexture::loadToVRAM() { // If we are bound.... if (textureID == 0) { freeTexture(); if (rawData != NULL) { glGenTextures(1, &textureID); //Grab a texture ID bind(); glTexImage2D(GL_TEXTURE_2D, 0, pixFMT, width, height, 0, pixFMT, GL_UNSIGNED_BYTE, (GLvoid*) rawData); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } } } static texid_t currentTexture = 0; void GLTexture::bind() { if (rawData != NULL && textureID <= 0) { loadToVRAM(); } if (currentTexture != textureID && textureID > 0) { glBindTexture(GL_TEXTURE_2D, textureID); currentTexture = textureID; } } int GLTexture::loadFromPNG(FILE *fp) { //header for testing if it is a png png_byte header[8]; //read the header fread(header, 1, 8, fp); //test if png int is_png = !png_sig_cmp(header, 0, 8); if (!is_png) { return TEXTURE_LOAD_ERROR; } //create png struct png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png_ptr) { return TEXTURE_LOAD_ERROR; } //create png info struct png_infop info_ptr = png_create_info_struct(png_ptr); if (!info_ptr) { png_destroy_read_struct(&png_ptr, (png_infopp) NULL, (png_infopp) NULL); return TEXTURE_LOAD_ERROR; } //create png info struct png_infop end_info = png_create_info_struct(png_ptr); if (!end_info) { png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp) NULL); return TEXTURE_LOAD_ERROR; } //png load error jump position if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return TEXTURE_LOAD_ERROR; } //init png reading png_init_io(png_ptr, fp); //let libpng know you already read the first 8 bytes png_set_sig_bytes(png_ptr, 8); // read all the info up to the image data png_read_info(png_ptr, info_ptr); //variables to pass to get info int bit_depth, color_type; png_uint_32 twidth, theight; // get info about png png_get_IHDR(png_ptr, info_ptr, &twidth, &theight, &bit_depth, &color_type, NULL, NULL, NULL); bitsPerPixel = bit_depth * png_get_channels(png_ptr, info_ptr); //update width and height based on png info width = twidth; height = theight; #if TEXTURE_LOAD_DEBUGGING printf("PNG:\tLoaded %dx%d with a depth of %d and color type of ", width, height, bit_depth); #endif //Update color info switch (color_type) { case PNG_COLOR_TYPE_GRAY: pixFMT = GL_LUMINANCE; #if TEXTURE_LOAD_DEBUGGING printf("GL_LUMINANCE\n"); #endif break; case PNG_COLOR_TYPE_GRAY_ALPHA: pixFMT = GL_LUMINANCE_ALPHA; #if TEXTURE_LOAD_DEBUGGING printf("GL_LUMINANCE_ALPHA\n"); #endif break; case PNG_COLOR_TYPE_RGBA: pixFMT = GL_RGBA; #if TEXTURE_LOAD_DEBUGGING printf("GL_ARGB\n"); #endif break; case PNG_COLOR_TYPE_RGB: pixFMT = GL_RGB; #if TEXTURE_LOAD_DEBUGGING printf("GL_RGB\n"); #endif break; default: printf("\n"); fprintf(stderr, "PNG:\tUnsupported pixformat: %d\n", color_type); return TEXTURE_LOAD_ERROR; } // Update the png info struct. png_read_update_info(png_ptr, info_ptr); // Row size in bytes. rowBytes = png_get_rowbytes(png_ptr, info_ptr); // Allocate the image_data as a big block, to be given to opengl rawData = malloc(rowBytes * height); if (!rawData) { //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return TEXTURE_LOAD_ERROR; } //row_pointers is for pointing to image_data for reading the png with libpng png_bytep *row_pointers = new png_bytep[height]; if (!row_pointers) { //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); return TEXTURE_LOAD_ERROR; } // set the individual row_pointers to point at the correct offsets of image_data for (unsigned register int i = 0; i < height; ++i) { row_pointers[height - 1 - i] = (png_bytep) rawData + i * rowBytes; } //read the png into image_data through row_pointers png_read_image(png_ptr, row_pointers); //Now generate the OpenGL texture object GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); //clean up memory and close stuff png_destroy_read_struct(&png_ptr, &info_ptr, &end_info); delete[] row_pointers; return TEXTURE_LOAD_SUCCESS; } GLColor GLTexture::getColorAt(int x, int y) { GLColor c; char* ptr = ((char*) rawData) + (rowBytes * (height - y - 1) + (x * bitsPerPixel / 8)); switch (pixFMT) { case GL_RGBA: c.setValue( ((ptr[0] & 0xff) << 24) | ((ptr[1] & 0xff) << 16) | ((ptr[2] & 0xff) << 8) | (ptr[3] & 0xff)); break; case GL_RGB: c.setValue( ((ptr[0] & 0xff) << 24) | ((ptr[1] & 0xff) << 16) | ((ptr[2] & 0xff) << 8) | 0xff); break; case GL_LUMINANCE: c.setValue( ((ptr[0] & 0xff) << 24) | ((ptr[0] & 0xff) << 16) | ((ptr[0] & 0xff) << 8) | 0xff); break; case GL_LUMINANCE_ALPHA: c.setValue(0xffffffff & (ptr[0] & 0xff)); break; } return c; } int GLTexture::getWidth() { return width; } int GLTexture::getHeight() { return height; } int GLTexture::loadFromFile(const char *fname) { FILE *fp = fopen(fname, "rb"); // Open for binary reading if (!fp) { fprintf(stderr, "Unable to open file %s\n", fname); return TEXTURE_LOAD_ERROR; } // Grab the extension int status = loadFromPNG(fp); fclose(fp); return status; }
true
f427aeb99c5a3ebbbc65ca3475c0dbaa42cc4c32
C++
mmmatjaz/SL-hoap3
/user/cbUser/src/SampleTask.cpp
UTF-8
2,728
2.65625
3
[]
no_license
/*============================================================================ ============================================================================== SampleTask.cpp ============================================================================== Remarks: sekeleton to create the sample C++ task ============================================================================*/ // SL system headers #include "SL_system_headers.h" // SL includes #include "SL.h" #include "SL_user.h" #include "SL_tasks.h" #include "SL_task_servo.h" #include "SL_kinematics.h" #include "SL_dynamics.h" #include "SL_collect_data.h" #include "SL_shared_memory.h" #include "SL_man.h" // local includes #include "SampleTask.h" SampleTask::SampleTask() : start_time_(0), freq_(0), amp_(0) { } SampleTask::~SampleTask() { } int SampleTask::initialize() { start_time_ = 0.0; static int firsttime = TRUE; if (firsttime){ firsttime = FALSE; freq_ = 0.1; // frequency amp_ = 0.5; // amplitude } // prepare going to the default posture bzero((char *)&(target_[1]),N_DOFS*sizeof(target_[1])); for (int i=1; i<=N_DOFS; i++) { target_[i] = joint_default_state[i]; } // go to the target using inverse dynamics (ID) if (!go_target_wait_ID(target_)) { return FALSE; } // ready to go int ans = 999; while (ans == 999) { if (!get_int(const_cast<char*>("Enter 1 to start or anthing else to abort ..."),ans,&ans)) { return FALSE; } } // only go when user really types the right thing if (ans != 1) { return FALSE; } start_time_ = task_servo_time; printf("start time = %.3f, task_servo_time = %.3f\n", start_time_, task_servo_time); return TRUE; } int SampleTask::run() { double task_time = task_servo_time - start_time_; double omega = 2.0*PI*freq_; // NOTE: all array indices start with 1 in SL for (int i=R_EB; i<=R_EB; ++i) { target_[i].th = joint_default_state[i].th + amp_*sin(omega*task_time); target_[i].thd = amp_ * omega*cos(omega*task_time); target_[i].thdd = -amp_ * omega*omega*sin(omega*task_time); } // the following variables need to be assigned for (int i=1; i<=N_DOFS; ++i) { joint_des_state[i].th = target_[i].th; joint_des_state[i].thd = target_[i].thd; joint_des_state[i].thdd = target_[i].thdd; joint_des_state[i].uff = 0.0; } return TRUE; } int SampleTask::changeParameters() { int ivar; double dvar; get_int(const_cast<char*>("This is how to enter an integer variable"),ivar,&ivar); get_double(const_cast<char*>("This is how to enter a double variable"),dvar,&dvar); return TRUE; }
true
ac349e1c38f755979727aa812add68ba6257e7ba
C++
EliezerDY/c-
/class registration/Instructor.cpp
UTF-8
1,208
3.390625
3
[]
no_license
// project -E.Brown #include "Instructor.h" // instance functions Instructor::Instructor(): Instructor("Staff") { } Instructor::Instructor(std::string n): Instructor(n,""){ } Instructor::Instructor(std::string n, std::string d): name(n), department(d){ } std::string Instructor::getName() const { return name; } void Instructor::setName(std::string n) { name = n; } std::string Instructor::getDepartment() const { return department; } void Instructor::setDepartment(std::string d) { department = d; } //is this right? //addCourse void Instructor::addCourse(Course &cob){ int index =courses.getIndex(&cob); if (index== -1){ courses.push_back(&cob); } return; } //dropCourse void Instructor::dropCourse(Course &cob){ int index =courses.getIndex(&cob); if (index!= -1){ courses.erase(index); } return; } //void function void Instructor::display(){ std::cout<<"Instructor:"<<getName()<<"- "<<getDepartment()<<std::endl; std::cout<<"Courses: "; for(int i=0; i<courses.getSize(); i++){ std::cout<<courses[i]->getName()<< " "; } std::cout<<std::endl; }
true
61ffd8a49bc454047a3800ffe93737361226620f
C++
lineCode/SpaceshipWarriorCombatED
/client/include/network/NetworkConfig.hpp
UTF-8
734
2.828125
3
[]
no_license
#if !defined(NETWORK_CONFIG_HPP) #define NETWORK_CONFIG_HPP #include <string> class NetworkConfig { public: NetworkConfig(); NetworkConfig(const std::string &server_ip, short server_port); ~NetworkConfig(); void setServerIp(const std::string &ip); void setGameServerIp(const std::string &ip); void setServerPort(unsigned short port); void setGameServerPort(unsigned short port); const std::string &getServerIp() const; const std::string &getGameServerIp() const; short getServerPort() const; short getGameServerPort() const; private: std::string _server_ip; std::string _game_server_ip; short _server_port; short _game_server_port; }; #endif // NETWORK_CONFIG_HPP
true
ea787c0993cf938120f7592c89acb3cc70f62fbe
C++
mgorvat/Compression
/HuffmanEncoder.h
WINDOWS-1252
1,463
3.59375
4
[]
no_license
#ifndef HUFFMANENCODER_H_INCLUDED #define HUFFMANENCODER_H_INCLUDED #include <vector> #include <map> #include <utility> using namespace std; /** @author mgorvat Class, which associate values with their codes. Values after constructing class are immutable. */ template <class T> class HuffmanEncoder{ public: /** Constructor. Makes the map. input: values pointer to vector<T>, which containes values, which are keys for codes codes pointer to vector of codes. Code is a pair of two int values: length of code and it's numeric value. i-th element in vector must be code of -th element in values vector. Number of elements in values and codes must be equal. */ HuffmanEncoder(vector<T>* values, vector<pair<int, int> >* codes){ for(int i = 0; i < (int)values->size(); i++){ mp[(*values)[i]] = (*codes)[i]; } } /** Reutrn code, associated with element. input: val value, code of which need to be getted outpit: Code of velue as pair<int, int>, where first int is code length, and second is it's numeric value */ pair<int, int> getCode(T* val){return mp[*val];} private: map<T, pair<int, int> > mp;//Here class store values }; #endif // HuffmanEncoder_H_INCLUDED
true
88b8843f6343e2a6ad8bc7bb8c8036dbe7976547
C++
Arangear/The15Puzzle
/The15Puzzle/Coursework2/UI.h
UTF-8
2,287
3.0625
3
[]
no_license
//Author: Daniel Cieslowski //Date created: 23.10.2019 //Last modified: 24.10.2019 #pragma once #include "Solver.h" #include "PuzzleGenerator.h" #include "FileReader.h" #include "FileWriter.h" #include <set> //Class responsible for communication between users and the application. class UI { public: //Methods //Displays the user menu. void Display(); private: int problemSize = 4; bool allPuzzlesSolved = false; PuzzleGenerator puzzleGenerator; FileWriter fileWriter; FileReader fileReader; Solver solver; std::deque<Puzzle> puzzles; //Displays the option menu. void displayOptions(); void modifyProblemSize(); //Displays puzzle input menu. void inputPuzzle(); //Displays the generate puzzles menu. void generatePuzzles(); //Prints puzzles from memory. void printPuzzles(); //Displays the save to file menu. void savePuzzles(); //Displays the load from file menu. void loadPuzzles(); //Displays a yes or no menu with a message. //Returns whether the answer was a yes. bool askYesOrNo(const std::string message); //Asks whether to emulate turns and returns translated user input. bool emulateTurns(); //Asks whether to solve current configuration and returns translated user input. bool solveSingleState(); //Asks whether to calculate the number of partial solutions and returns translated user input. bool findPartials(); //Initiates solving the puzzle. void solvePuzzles(); //Asks whether to emulate turns and returns translated user input. void findSolution(const bool turnsOn, const bool current, Puzzle& puzzle); //Clears puzzles from memory. void clearPuzzles(); //Prints all solutions to console. void printSolutionsToConsole(); //Prints all solutions to file. void printSolutionsToFile(); //Validates input from user when typing in a puzzle. int ensureValidInput(std::set<int>& values, const int count, const int upper); //Displays an error message and clears input stream. void inputError(const std::string message); //Displays the choose file menu. //Returns filePath input from user. std::string getFilePath(const std::string message); //Displays whether opening filePath was successful based on result and if so displays message. void openFile(const result result, const std::string filePath, const std::string message); };
true
30f1508e922e58041783dcad4241ca0b2939efd4
C++
StHamish/various-algorithms
/algorithms/bit-manipulation/find-unique/aim.hpp
UTF-8
322
2.703125
3
[ "MIT" ]
permissive
/* The aim of this topic is: http://www.programcreek.com/2012/12/leetcode-solution-of-single-number-in-java/ Given an array of integers, every element appears twice except for one. Find that single one. */ // Algorithm to be tested template <class It> typename It::value_type find_unique(It&& beg, It&& end);
true
98f03c5547d46fe4933c8e6e4d0c6a94cf579aa0
C++
declard/diploma
/src/basiclayer.cpp
UTF-8
1,054
2.65625
3
[]
no_license
#include "basiclayer.h" double BasicLayer::bound(const MatrixD&m,MatrixIndex point) { if (point<0||point>=m.size()) return 0; return m.at(point); } QImage BasicLayer::toImage(const MatrixD&m) { QImage res(m.size(),QImage::Format_RGB16); MatrixIndex i,f,t(m.size()); for2DIncr(i,f,t) { char v(m.at(i)); res.setPixel(i,qRgb(v,v,v)); } return res; } MatrixD BasicLayer::fromImage(const QImage&im) { MatrixD res(im.size()); MatrixIndex i,f,t(im.size()); for2DIncr(i,f,t) { QRgb v(im.pixel(i)); res[i]=qGray(v); } return res; } MatrixIndex BasicLayer::boundariesOffset(const MatrixD&matr) const { return boundariesOffset(matr,size()); } MatrixIndex BasicLayer::boundariesOffset(const MatrixD&f,const MatrixIndex&t) { return boundariesOffset(f.size(),t); } MatrixIndex BasicLayer::boundariesOffset(const MatrixIndex&f,const MatrixIndex&t) { return (t-f)/2; } int BasicLayer::calcN(double A,int Np,int Nt) { int res; if (((Np+Nt)%2)==0) res=((int)A)*2+1; else res=((int)(A+0.5))*2; //qDebug()<<A<<Np<<Nt<<res; return res; }
true
247d71347112661eaabd709a0c2c813190059cdc
C++
yueyiqiu178/DataStructure
/set.cpp
UTF-8
1,564
2.71875
3
[]
no_license
#include<iostream> using namespace std; void Union(int [],int,int); int find(int [],int); int main(){ int parent[]={0,4,-2,7,-3,7,7,-5,4,3,2}; for(int i=1;i<=10;i++) cout<<parent[i]<<" "; cout<<endl; Union(parent,2,4); for(int i=1;i<=10;i++) cout<<parent[i]<<" "; cout<<endl; cout<<find(parent,7)<<endl; cout<<find(parent,9)<<endl; for(int i=1;i<=10;i++) cout<<parent[i]<<" "; cout<<endl; system("pause"); return 0; } void Union(int a[],int x,int y){ if(a[x]<=a[y]){ a[x]=a[x]+a[y]; a[y]=x; } else{ a[y]=a[y]+a[x]; a[x]=y; } } int find(int a[],int x){ int i=x; while(a[i]>0) i=a[i]; int j=x; int k; while(a[j]>0){ k=a[j]; a[j]=i; j=k; } return i; } void check(int x[],int n){ int count=0; bool checked[n]; for(int i=0;i<n;i++) check[i]=false; for(int i=0;i<n;i++){ if(x[i]==i) count++; } }
true
a37774a9eac817c35dec95e2362f19bf2866f9f4
C++
sguzwf/Algorithms
/sort/src/priority_queue.h
UTF-8
4,734
3.59375
4
[ "WTFPL" ]
permissive
#ifndef __PRIORYT_QUEUE_H__ #define __PRIORYT_QUEUE_H__ #include<iostream> #include<vector> #include<cassert> using std::vector; template<typename Real> class Priority_Queue { public: Priority_Queue(); Priority_Queue(vector<Real>v); void insert(Real v); void updateKey(int idx, Real newKey); static void heapSort(vector<Real>&); Real extractMin(); bool isEmpty(); void displayQ(); private: vector<Real>Q; void incKey(int idx, Real newKey); void decKey(int idx, Real newKey); static int getChildIdxTOSwap(int,vector<Real>&,int); }; template<typename Real> Priority_Queue<Real>::Priority_Queue() { } template<typename Real> Priority_Queue<Real>::Priority_Queue(vector<Real> vec) :Q(vector<Real>(vec.size(),0)) { int size = vec.size(); int len = 0; Real tmp = 0; for(auto val : vec) { int idx = len; int parentIdx = (len-1)/2; Q[idx] = val; while(idx > 0 && Q[idx] < Q[parentIdx]) { tmp = Q[idx]; Q[idx] = Q[parentIdx]; Q[parentIdx] = tmp; idx = parentIdx; parentIdx = (idx-1)/2; } len++; } } template<typename Real> void Priority_Queue<Real>::insert(Real v) { Q.push_back(v); int size = Q.size(); int idx = size-1; int pIdx = (idx-1)/2; Real tmp = 0; while(Q[idx] < Q[pIdx] && idx > 0) { tmp = Q[idx]; Q[idx] = Q[pIdx]; Q[pIdx] = tmp; idx = pIdx; pIdx = (idx-1)/2; } } template<typename Real> void Priority_Queue<Real>::updateKey(int idx, Real newKey) { int size = Q.size(); assert(idx < size); auto oldKey = Q[idx]; if(oldKey == newKey) return; else if(oldKey < newKey) incKey(idx,newKey); else decKey(idx,newKey); } template<typename Real> Real Priority_Queue<Real>::extractMin() { assert(!Q.empty()); Real top = Q[0]; Real lastEle = Q.back(); Q.pop_back(); if(!Q.empty()) incKey(0,lastEle); return top; } template<typename Real> bool Priority_Queue<Real>::isEmpty() { return Q.empty(); } template<typename Real> int Priority_Queue<Real>::getChildIdxTOSwap(int id, vector<Real >& vec, int size) { int retIdx = id; assert(size <= (int)vec.size()); int c1Idx = 2 * id + 1; int c2Idx = 2* id + 2; if(c1Idx < size && vec[retIdx] > vec[c1Idx]) retIdx = c1Idx; if(c2Idx < size && vec[retIdx] > vec[c2Idx]) retIdx = c2Idx; return retIdx; } template<typename Real> void Priority_Queue<Real>::incKey(int idx, Real newKey) { // bubble down int size = Q.size(); int oldKey = Q[idx]; assert(idx < size); assert(oldKey <= newKey); Q[idx] = newKey; int cIdxToSwap = getChildIdxTOSwap(idx,Q,size); Real tmp = 0; while(cIdxToSwap != idx) { tmp = Q[idx]; Q[idx] = Q[cIdxToSwap]; Q[cIdxToSwap] = tmp; idx = cIdxToSwap; cIdxToSwap = getChildIdxTOSwap(idx,Q,size); } } template<typename Real> void Priority_Queue<Real>::decKey(int idx, Real newKey) { int size = Q.size(); int pIdx = (idx-1)/2; Q[idx] = newKey; Real tmp = 0; while(idx > 0 && Q[idx] < Q[pIdx]) { tmp = Q[idx]; Q[idx] = Q[pIdx]; Q[pIdx] = tmp; idx = pIdx; pIdx = (idx-1)/2; } } template<typename Real> void Priority_Queue<Real>::heapSort(vector<Real >& vec) { int size = vec.size(); // construct heap Real tmp = 0; for(int i = 0; i < size; i++) { int idx = i; int pIdx = (idx-1)/2; //root ele has highest key while(idx > 0 && vec[idx] < vec[pIdx]) { tmp = vec[idx]; vec[idx] = vec[pIdx]; vec[pIdx] = tmp; idx = pIdx; pIdx = (idx-1)/2; } } // generate sorted vector for(int i = size-1; i >= 0; i--) { //swap root element tmp = vec[i]; vec[i] = vec[0]; vec[0] = tmp; // bubble down root element int idx = 0; int swapIdx = getChildIdxTOSwap(idx,vec,i); while(idx != swapIdx) { tmp = vec[idx]; vec[idx] = vec[swapIdx]; vec[swapIdx] = tmp; idx = swapIdx; swapIdx = getChildIdxTOSwap(idx,vec,i); } } } template<typename Real> void Priority_Queue<Real>::displayQ() { for(auto v : Q) std::cout<<v<<std::endl; } #endif
true
9d6cfc34ece0f2e7738af62bce57ad1ab94f2804
C++
HemanDas/cpp_project
/Lab_works/Lab_functions/User_defined/argument_returnvalue.cpp
UTF-8
368
3.078125
3
[]
no_license
#include<iostream> using namespace std; double getarea(double,double); int main() { double base,height,area; cout<<"input base and height:"<<endl; cin>>base>>height; area=getarea(base,height); cout<<"area of triangle is:"<<area<<endl; } double getarea(double b,double ht) { double area; area=((0.5)*b*ht); return area; }
true
196de1adb606770603bb9742dab9087efdef784e
C++
Abdulrehman964/ICT-project
/pgm1.cpp
UTF-8
300
3.203125
3
[]
no_license
#include<stdio.h> int factorial(int n) { if(n==0||n==1) return n; else return(n*factorial(n-1)); } int main() { int n=0,c=0; printf("Enter the number whose factorial has to be calculated : "); scanf("%d",&n); c=factorial(n); printf("The factorial of %d is %d ",n,c); printf("Bug"); }
true
a26a96258be411281410bf4a67d22bb598d9cde6
C++
amorim/Pesquisa-Operacional
/clique/Source.cpp
UTF-8
1,343
2.703125
3
[]
no_license
#include <ilcplex/ilocplex.h> #include <vector> #include <set> ILOSTLBEGIN class Graph { private: vector<set<int>> adjacencia; public: int nvertices; Graph(int nvertices) { this->nvertices = nvertices; adjacencia.resize(nvertices); } Graph(string filename) { ifstream file(filename); int vertices; file >> vertices; this->nvertices = vertices; adjacencia.resize(vertices); int a, b; while (file >> a >> b) { this->addEdge(a, b); } } void addEdge(int from, int to) { adjacencia[from].insert(to); adjacencia[to].insert(from); } set<int> getNeighboringVertices(int vertex) { return adjacencia[vertex]; } }; int main(int argc, char **argv) { IloEnv env; try { IloModel model(env); Graph* g = new Graph("in.txt"); IloInt v = g->nvertices; IloBoolVarArray x(env, v); for (IloInt i = 0; i < v; i++) { for (IloInt j = 0; j < v; j++) { set<int> neigh = g->getNeighboringVertices(i); if (!neigh.count(j) && i != j) model.add(x[i] + x[j] <= 1); } } model.add(IloMaximize(env, IloSum(x))); IloCplex cplex(model); cplex.solve(); env.out() << "Solution status = " << cplex.getStatus() << endl; env.out() << "Solution value = " << cplex.getObjValue() << endl; } catch (IloException &ex) { cerr << "Concert exception caught: " << ex << endl; } env.end(); return 0; }
true
c4d3543550a4045bc347e230793347d98f4a6921
C++
wangzilong2019/text
/蓝桥杯算法训练2/图/并查集/并查集找祖宗节点.cpp
GB18030
1,218
3.359375
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; const int N = 100001; int father[N]; int n, m; //ֱ¼ͱߵĸ struct Edge{ int u, v; //ÿߵ }e[N]; //ʼÿĸڵ void init() { for (int i = 1; i <= n; i++) { father[i] = i; } } // int find(int x) { if (x != father[x]) { father[x] = find(father[x]); //ѵǰڵ㵽ڽڵļϺȫΪڽڵ㼯Ϻ } return father[x]; //ڼϺ } int main () { int count = 0; //붥ͱߵĸ cin >>n >>m; //ÿߵ for (int i = 1; i <= m; i++) { cin>> e[i].u>> e[i].v; } init(); // for (int i = 1; i <= m; i++) { //ҵǰļϺ int p = find(e[i].u); int q = find(e[i].v); //ļϺͬۼ1 if (p == q) { count++; } else if (p > q) { father[p] = q; } else { father[q] = p; } } //ò鼯˼룬ڽڵ㼴1Žڵֵͬ1 for (int i = 1; i <= n; i++) { if (father[i] == 1) { count++; } } // cout<<count<<endl; return 0; }
true
ae14b0e1887b0b53ceb39f635db2104bebc644e2
C++
invincibleadam28/My-Coding-Journey
/Spiral Matrix.cpp
UTF-8
882
2.96875
3
[]
no_license
vector<int> solve(vector<vector<int>>& matrix) { vector<int> ans; int n = matrix.size(); if (n == 0) return ans; int m = matrix[0].size(); int left = 0, right = m - 1, top = 0, bottom = n - 1; int dir = 0; while (left <= right && top <= bottom) { if (dir == 0) { for (int i = left; i <= right; i++) { ans.push_back(matrix[top][i]); } top++; } else if (dir == 1) { for (int i = top; i <= bottom; i++) { ans.push_back(matrix[i][right]); } right--; } else if (dir == 2) { for (int i = right; i >= left; i--) { ans.push_back(matrix[bottom][i]); } bottom--; } else { for (int i = bottom; i >= top; i--) { ans.push_back(matrix[i][left]); } left++; } dir = (dir + 1) % 4; } return ans; }
true
3723d034bb5a7db7ca0d79ee777463964801eb50
C++
zpoint/Reading-Exercises-Notes
/The_C++_Standard_Library/multimap1.cpp
UTF-8
1,435
3.484375
3
[]
no_license
#include <map> #include <string> #include <iostream> #include <iomanip> int main() { // create multimap as string/string dictionary std::multimap<std::string, std::string> dict; // insert some elements in random order dict.insert({ { "day", "Tag" }, { "strange", "fremd" }, { "car", "Auto" }, { "smart", "elegant" }, { "trait", "Merkmal" }, { "strange", "seltsam" }, { "smart", "raffiniert" }, { "smart", "klug" }, { "clever", "raffiniert" } }); // print all elements std::cout.setf(std::ios::left, std::ios::adjustfield); std::cout << ' ' << std::setw(10) << "english " << "german " << std::endl; std::cout << std::setfill('-') << std::setw(20) << "" << std::setfill(' ') << std::endl; for (const auto& elem : dict) std::cout << ' ' << std::setw(10) << elem.first << elem.second << std::endl; std::cout << std::endl; // print all values for key "smart" std::string word("smart"); std::cout << word << ": " << std::endl; for (std::multimap<std::string, std::string>::iterator pos = dict.lower_bound(word); pos != dict.upper_bound(word); ++pos) { std::cout << " " << pos->second << std::endl; } // print all keys for value "raffiniert" word = ("raffiniert"); std::cout << word << ": " << std::endl; for (const auto& elem : dict) { if (elem.second == word) std::cout << " " << elem.first << std::endl; } return 0; }
true
f803b647546ca277f9dddcb3d4ef7a2ed44feb4b
C++
fsofelipe/CompGraficaUFPel
/Trabalho 1/mesh.cpp
ISO-8859-1
3,538
2.96875
3
[]
no_license
#include "mesh.hpp" Mesh::Mesh(char * path) { bool res = loadOBJ(path, vertices, uvs, normals); indexVBO(vertices, uvs, normals, indices, indexed_vertices, indexed_uvs, indexed_normals); createPriorList(); } std::vector<glm::vec3> Mesh::getVertices() { return indexed_vertices; } std::vector<glm::vec2> Mesh::getUvs() { return indexed_uvs; } std::vector<glm::vec3> Mesh::getNormals() { return indexed_normals; } std::vector<unsigned short> Mesh::getIndices() { return indices; } void Mesh::createPriorList() { //priorList.clear(); for (int i = 0; i < indices.size(); i++) { try { priorList.at(indices[i]) = priorList.at(indices[i]) + 1; } catch (const std::out_of_range& oor) { priorList.insert(std::pair<int, int>(indices[i], 1)); } } //sort(priorList.begin(), priorList.end(), sortBySec); } void Mesh::setIndex(std::vector<unsigned short> indices){ this->indices = indices; } void Mesh::setIndexedVertex(std::vector<glm::vec3> indexed_vertices){ this->indexed_vertices = indexed_vertices; } void Mesh::setPriorList(std::map <int, int> priorList){ this->priorList = priorList; } std::map <int, int> Mesh::getPriorList() { return priorList; } /* Retorna o vertice com o maior nmero de arestas e remove este da lista de prioridade */ int Mesh::getRemovingVertex() { std::map<int, int>::iterator it = std::max_element(priorList.begin(), priorList.end(), [](const std::pair<int, int>& p1, const std::pair<int, int>& p2) { return p1.second < p2.second; }); std::pair<int, int> ret = std::make_pair(it->first, it->second); priorList.erase(it); // cout << "aqui: " << ret.first << endl; return ret.first; } int Mesh::findEdgePair(int index1) { int mod = index1 % 3; int ret = -1; if (mod == 0 || mod == 1) ret = index1 + 1; if (mod == 2) ret = index1 - 2; return ret; } /* Remove uma aresta formada pelos vertices v1, v2 ao remover inserido um novo vertice v que o ponto mdio entre v1 e v2 */ void Mesh::removeEdge(int i1, int i2) { if (i1 < 0 && i2 < 0) return; glm::vec3 v1 = indexed_vertices[i1]; glm::vec3 v2 = indexed_vertices[i2]; glm::vec3 v = pontoMedio(v1, v2); for (int i = 0; i < indexed_vertices.size(); i++){ if (isEquals(indexed_vertices[i], v1) || isEquals(indexed_vertices[i], v2)) { indexed_vertices[i] = v; } } } void Mesh::remove() { if (!isFinal()) { int primeiro = getRemovingVertex(); int segundo = findEdgePair(primeiro); removeEdge(primeiro, segundo); } } bool Mesh::isFinal() { int count = 0; std::map<int, int>::iterator it = priorList.begin(); for (auto address_entry : priorList){ if (address_entry.second == 1) { count++; } } if ((count + 3) == priorList.size() - 1) return true; return false; } void Mesh::printPriorList() { cout << "Prior List: [" << priorList.size() << "]" << endl; std::map<int, int>::iterator it = priorList.begin(); for (it = priorList.begin(); it != priorList.end(); ++it) cout << "<" << it->first << " : " << it->second << ">" << endl; } void Mesh::printIndex() { for (int i = 0; i < indices.size(); i++) { cout << i << ": " << indices[i] << endl; } } void Mesh::printVertices() { cout << "tamanho: " << vertices.size() << endl; for (int i = 0; i < vertices.size(); i++) { cout << i << " : <" << vertices[i].x << ", " << vertices[i].y << ", " << vertices[i].z << ">" << endl; } }
true
f238ca5e4de66fc12d83c2315d703113188f457f
C++
alekseytanana/coding-challenges
/cpp_stepik_p1/3/string_constructor3.cpp
UTF-8
701
3.59375
4
[]
no_license
#include <cstddef> // size_t #include <cstring> // strlen, strcpy struct String { String(const char *str = "") : size(strlen(str)) { this->str = strcpy( new char [size+1], str ); } String(size_t n, char c) : size(n), str(new char [n+1]) { for (size_t i=0; i!=n; ++i) *(str + i) = c; str[n] = '\0'; } ~String() { delete [] str; } /* Реализуйте этот метод. */ void append(String &other) { size += other.size; char *new_str = new char [size+1]; strcpy(new_str, str); strcat(new_str, other.str); new_str[new_size] = '\0'; delete [] str; str = new_str; } size_t size; char *str; };
true
ba684ab975d64c7bd558d0f8f13566ba18b6a8c1
C++
joy-mollick/Only-Uva-Online-Judge-Solutions
/11151 - Longest Palindrome.cpp
UTF-8
1,113
3.171875
3
[]
no_license
#include<bits/stdc++.h> /* Nayeem Mollick Joy , Electrical & Electronic Engineering , University of Rajshahi. Passionate Contest Programmer , Coder , Android Developer */ using namespace std; // normal dp problem typedef unsigned long long ll; ll longest_pal(string str) { ll n =str.size(); ll i, j, k; ll dp[n][n]; // Create a table to store results of subproblems memset(dp,0,sizeof(dp)); // Strings of length 1 are palindrome of lentgh 1 for (i = 0; i < n; i++) dp[i][i] = 1; for (int i=2; i<=n; i++) { for (int j=0; j<n-i+1; j++) { int k = i+j-1; if (str[j] == str[k]) dp[j][k] = dp[j+1][k-1] + 2; else dp[j][k] = max(dp[j][k-1], dp[j+1][k]); } } return dp[0][n-1]; } int main() { string s; int n; scanf("%d",&n); cin.ignore(); while(n--) { getline(cin,s); if(s=="") { cout<<"0"<<endl; continue; } cout<<longest_pal(s)<<endl; } return 0; }
true
9625122df7a4770c8a8bb1c8edaa5784ba64986d
C++
riophae/exercises
/the-method-of-programming/ch01-string/06-find-longest-palindrome/01.cpp
UTF-8
1,272
3.359375
3
[]
no_license
#include <cstring> #include <iostream> void findLongestPalindrome(const char *str) { int max = 0; int max_start = -1; int max_end = -1; int len = strlen(str); int n; int start; int end; for (int i = 0; i < len; ++i) { for (int j = 0; i - j >= 0 && i + j < len; ++j) { if (str[i - j] != str[i + j]) break; n = j * 2 + 1; start = i - j; end = i + j; } if (n > max) { max = n; max_start = start; max_end = end; } for (int j = 0; i - j >= 0 && i + j + 1 < len; ++j) { if (str[i - j] != str[i + j + 1]) break; n = j * 2 + 2; start = i - j; end = i + j + 1; } if (n > max) { max = n; max_start = start; max_end = end; } } std::cout << max << " "; if (max_start > -1) { for (int i = max_start; i <= max_end; ++i) { std::cout << str[i]; } } std::cout << std::endl; } int main() { findLongestPalindrome("baxae"); findLongestPalindrome("axxae"); findLongestPalindrome("gbbcxcbbe"); findLongestPalindrome("aaaa"); findLongestPalindrome("aaa"); findLongestPalindrome("a^aa"); findLongestPalindrome("aa^a"); findLongestPalindrome(""); findLongestPalindrome("sator arepo tenet opera rotas"); return 0; }
true
7ce1dcd47e5c710eff6142375a20e1c2421b3feb
C++
ayundina/cpp_piscine
/day04/ex03/include/AMateria.hpp
UTF-8
493
2.875
3
[]
no_license
#ifndef AMATERIA_H #define AMATERIA_H #include "ICharacter.hpp" #include <iostream> class ICharacter; class AMateria { private: protected: std::string _type; unsigned int _xp; public: AMateria(); AMateria(std::string const &type); AMateria(const AMateria &m); AMateria &operator=(const AMateria &m); virtual ~AMateria(); const std::string &getType() const; unsigned int getXP() const; virtual AMateria *clone() const = 0; virtual void use(ICharacter &target) = 0; }; #endif
true
a61dcb367badc5a15977162917d184a2ec264788
C++
bunnyDrug/aoc-2020-cpp20
/day_4/main.cpp
UTF-8
4,808
3.1875
3
[]
no_license
#include <iostream> #include <map> #include <string> #include <fstream> #include <vector> #include <regex> using namespace std; int main() { // read input vector<map<string, string>> vector1; map<std::string, std::string> m; fstream inputFile("../input.txt"); string line; // create vector of maps for each passport while (getline(inputFile, line)) { if (line[0] == 0) { vector1.push_back(m); m.clear(); } // take each line and process each entry split by spaces // empty lines mean a new passport while (line.find(' ') != -1) { // if there are new elements - process from back to front int space = line.find_last_of(' '); string poppedString = line.substr(space + 1); int delim = poppedString.find_last_of(':'); string key = poppedString.substr(0, delim); string value = poppedString.substr(delim + 1); m.emplace(key, value); line.erase(space); } int delim = line.find(':'); string key = line.substr(0, delim); string value = line.substr(delim + 1); m.emplace(key, value); } vector1.push_back(m); m.clear(); cout << "Loaded input file and found " << vector1.size() << " passports" << endl; cout << "Processing..." << endl << endl; int validPassports = 0; for (const auto& passport: vector1){ string securityPolicy[] = {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}; int policyMatches = 0; for (const auto& p: securityPolicy) { if (passport.contains(p)) { auto passportElement = passport.find(p); if (passportElement->first == "byr") { if (stoi(passportElement->second) >= 1920 && stoi(passportElement->second) <= 2002) { policyMatches ++; continue; } } if (passportElement->first == "iyr") { if (stoi(passportElement->second) >= 2010 && stoi(passportElement->second) <= 2020) { policyMatches ++; continue; } } if (passportElement->first == "eyr") { if (stoi(passportElement->second) >= 2020 && stoi(passportElement->second) <= 2030) { policyMatches ++; continue; } } if (passportElement->first == "hgt") { regex cmHeightRegex("\d*(cm)"); if (regex_search(passportElement->second, cmHeightRegex)) { if (stoi(passportElement->second) >= 150 && stoi(passportElement->second) <= 193) { policyMatches++; continue; } } regex inchHeightRegex("\d*(in)"); if (regex_search(passportElement->second, inchHeightRegex)) { if (stoi(passportElement->second) >= 59 && stoi(passportElement->second) <= 76) { policyMatches++; continue; } } } if (passportElement->first == "hcl") { regex hairColour("#([a-f0-9]{6})"); if (regex_search(passportElement->second, hairColour)) { policyMatches++; continue; } } if (passportElement->first == "ecl") { string eyeColour[] = {"amb", "blu", "brn", "gry", "grn", "hzl", "oth"}; int counter = 0; for (auto colour: eyeColour) { if (passportElement->second == colour) { counter ++; } } if (counter == 1) { policyMatches ++; continue; } } if (passportElement->first == "pid") { if (passportElement->second.length() == 9) { regex ds("([0-9]{9})"); if (regex_search(passportElement->second, ds)) { policyMatches ++; continue; } } } } } if (policyMatches == 7) { validPassports ++; } policyMatches = 0; } cout << "valid passports = " << validPassports << endl; return 0; }
true
0c060093387a3e49de60f7f0c7a58ee5552d3dc2
C++
nosolobots/algo
/ds_algo_c/ch2/creativity/c_2_9.cpp
UTF-8
2,071
3.65625
4
[]
no_license
/* Write a C++ program that can input any polynomial in standard algebraic notation and outputs the first derivative of that polynomial. */ #include<iostream> #include<string> #include<map> #include<cstdlib> #include<cmath> #include<iomanip> using namespace std; class Polynom { public: Polynom(const string& spoly); friend ostream& operator<<(ostream& os, const Polynom& p); private: map<int, double> factors_; bool process_entry(const string& spoly); }; Polynom::Polynom(const string &spoly) { if(!process_entry(spoly)) throw "process entry error"; } ostream& operator<<(ostream &os, const Polynom &p) { bool first = true; for(auto it = p.factors_.rbegin(); it!=p.factors_.rend(); it++) { double coef = it->second; if(first && coef<0) cout << "-"; else if(!first) { cout << ((coef < 0) ? " - " : " + "); } cout << fixed << setprecision(2) << fabs(coef); cout << "*X^" << it->first; first = false; } return os; } bool Polynom::process_entry(const string &spoly) { int pos = 0, pinit; int len, exp; double coef; string term; while((pos = spoly.find('X', pos))!=string::npos) { // get factor exponent len = 0; pinit = pos + 2; while ((pinit + len) < spoly.size() && spoly[pinit + len] != ' ') ++len; exp = stoi(spoly.substr(pinit, len)); // get factor coefficient len = 0; pinit = pos - 2; while ((pinit - len)>=0 && spoly[pinit - len + 1] != ' ') ++len; coef = stod(spoly.substr(pinit - len + 1, len)); if ((pinit - len) > 0 && spoly[pinit - len]=='-') coef *= -1; factors_.insert({exp, coef}); ++pos; } return (factors_.size()!=0); } int main() { string poly; cout << "Enter polynom (ex: 4*X^3 + 2.5*X^1 - 11.3*X^0): "; getline(cin, poly); Polynom p(poly); cout << endl << p << endl; return EXIT_SUCCESS; }
true
93c27b8eca1b5a23c938650dddeac6cc104d3cf5
C++
jorgevag/CompPhysAss1
/main.cpp
UTF-8
6,305
2.890625
3
[]
no_license
#include <iostream> #include <vector> #include <cmath> #include <cstdlib> #include <fstream> // For RNG //#include <stdlib.h> // srand, rand //#include <time.h> // time #include <random> // for generator and uniform distribution, need C++11, so remember flag -std=c++11 //................. // Global Constants //''''''''''''''''' const double pi = 4.*atan(1.); // Portable definition of pi const double tau = 1; const double L = 0.5; const double alpha = 0.25; const double DeltaU = 1; const double T = 1; const double kB = 1; const double systemSize = 1; const size_t n = 201; //system size/resolution must be odd to include 0 double t = 1.77; const size_t m = 200000; // time steps const double dt = 1; const double D = (kB*T)/DeltaU; //................. // Function Headers //''''''''''''''''' double potential(double x, double t); // tau, L, alpha, Delta_U) double force(double x, double t); double gaussianRNG(); std::vector<double> gaussianRNGArray(size_t m); //takes in number of time steps double langevinEuler(double x, double t); std::vector<double> make1DBox(const size_t n); void createPotentialOutput(); // For plotting (testing) the potential, uses make1Dbox() void createForceOutput(); // For plotting (testing) the force, uses make1Dbox() void create2DRandomOutput(); // For plotting (testing) the our RNG, uses make1Dbox() void create3DRandomOutput(); // For plotting (testing) the our RNG, uses make1Dbox() // ??????????????????????????????????????????????????????????????????????????????????????????????????????? // CAN I AVOID HAVING THESE GLOBALLY DEFINED TO ALLOW IT TO GAIN ACCESS TO MY gaussianRNG()-FUNCTION?????? // ??????????????????????????????????????????????????????????????????????????????????????????????????????? // Activate RNG and create uniform distribution U(0,1): std::default_random_engine generator; std::uniform_real_distribution<double> distribution(0.0,1.0); //...... // Main //'''''' int main(int argc, char** argv){ std::ofstream outStream("Output/gaussianRandom.txt"); if (outStream.fail()){ std::cout << "Outputfile 'gaussianRandom.txt' opening failed. \n "; exit(1); } // Creating gaussian random numbers std::vector<double> gaussian_numbers; gaussian_numbers.resize(m); gaussian_numbers = gaussianRNGArray(m); // Creating gaussian plot for comparison std::vector<double> gaussian_curve; gaussian_curve.resize(m); std::vector<double> gaussian_xrange; gaussian_xrange.resize(m); double curve_interval = 6; for(int i=0; i<m; ++i){ gaussian_xrange[i] = i*curve_interval/m-curve_interval/2.0; gaussian_curve[i] = 1/sqrt(2*pi)*exp( -(pow(gaussian_xrange[i],2.0))/2.0 ); } for(int i=0; i<gaussian_numbers.size(); ++i){ outStream << gaussian_numbers[i] << " " << gaussian_xrange[i] << " " << gaussian_curve[i] << std::endl; } outStream.close(); return 0; } //......................... // Function Implementations //''''''''''''''''''''''''' double potential(double x, double t){ if( t - floor(t/tau)*tau < 0.75*tau ){ // OFF is more likely than ON, so this if comes first return 0; } else{ double loc_x = x-floor(x/L)*L; if( loc_x < alpha*L) return (DeltaU*loc_x)/(alpha*L); else return ( DeltaU*(L-loc_x) )/( L*(1-alpha) ); } } double force(double x, double t){ if( t - floor(t/tau)*tau < 0.75*tau ){ // OFF is more likely than ON, so this if comes first return 0; } else{ double loc_x = x-floor(x/L)*L; if( loc_x < alpha*L) return (DeltaU)/(alpha*L); else return -DeltaU/( L*(1-alpha) ); } } std::vector<double> gaussianRNGArray(size_t m){ //takes in number of time steps m=even double xi_1, xi_2; std::vector<double> gaussian_numbers; gaussian_numbers.resize(m); for (int i=0; i<m; i+=2){ xi_1 = distribution(generator); xi_2 = distribution(generator); gaussian_numbers[ i ] = sqrt( -2*log(xi_1) )*cos(2*pi*xi_2); gaussian_numbers[i+1] = sqrt( -2*log(xi_1) )*sin(2*pi*xi_2); } return gaussian_numbers; } double langevinEuler(double x, double t, double xi){ x = x - force(x,t)*dt + sqrt(2*D*dt)*xi; return x; } double gaussianRNG(){ return distribution(generator); } std::vector<double> make1DBox(const size_t n){ if(n%2 == 0){ std::cout << "Error in make1DBox():" << std::endl << "System size/resolution n must be an odd number to include 0!" << std::endl; exit(1); } std::vector<double> box; box.resize(n); for (int i=0; i<n; ++i){ box[i] = i*(systemSize/(n-1))- systemSize/2; } return box; } // Uses make1Dbox() void createPotentialOutput(){ // Output to plotPotential.py std::vector<double> box; box = make1DBox(n); std::ofstream outStream("Output/potential.txt"); if (outStream.fail()){ std::cout << "Outputfile 'potential.txt' opening failed. \n "; exit(1); } for(int i=0; i<box.size(); ++i){ outStream << box[i] << " " << potential(box[i],t) << std::endl; } outStream.close(); } // Uses make1Dbox() void createForceOutput(){ // Output to plotForce.py std::vector<double> box; box = make1DBox(n); std::ofstream outStream("Output/force.txt"); if (outStream.fail()){ std::cout << "Outputfile 'force.txt' opening failed. \n "; exit(1); } for(int i=0; i<box.size(); ++i){ outStream << box[i] << " " << force(box[i],t) << std::endl; } outStream.close(); } // Uses gaussianRNG() void create2DRandomOutput(){ // Output to plotRandom.py std::ofstream outStream("Output/random2d.txt"); if (outStream.fail()){ std::cout << "Outputfile 'random.txt' opening failed. \n "; exit(1); } for(int i=0; i<6000; ++i){ outStream << gaussianRNG() << " " << gaussianRNG() << std::endl; } outStream.close(); } void create3DRandomOutput(){ // Output to plotRandom.py std::ofstream outStream("Output/random3d.txt"); if (outStream.fail()){ std::cout << "Outputfile 'random3d.txt' opening failed. \n "; exit(1); } for(int i=0; i<6000; ++i){ outStream << gaussianRNG() << " " << gaussianRNG() << " " << gaussianRNG() << std::endl; } outStream.close(); }
true