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
c4099d9beb33789e19007e85e370b0f929eef871
C++
Lohit9/MasterYourAlgorithms
/General Questions/same_tree.cpp
UTF-8
513
3.125
3
[]
no_license
// // same_tree.cpp // // // Created by Lohit on 2016-01-17. // // #include <stdio.h> /* Program to check if 2 binary trees are the same - need to have teh same data values and structure */ bool isSame(struct Node* tree1, struct Node* tree2){ if(tree1 == NULL && tree2 == NULL){ return true; } if(tree1 == NULL || tree2 == NULL){ return false; } return tree1.data == tree2.data && isSame(tree1->left, tree2->left) && isSame(tree2->left,tree2->right); }
true
9a461c67160f593421319c8145b624ee1511189e
C++
atlas3141/Snake
/Main.cpp
UTF-8
4,632
2.71875
3
[]
no_license
#include "SDL.h" #include <iostream> #include <cstdlib> #include <ctime> #include "Sprite.h" using namespace std; class Segment { private: Sprite* sprite; int age; int x, y; public: Segment(int nx, int ny, SpriteGroup* group, SDL_Surface* screen, int board[50][50] ){ x = nx; y = ny; Uint32 red = SDL_MapRGB(screen->format,255,0,0); sprite = new Sprite (red, x, y, 10, 10); group->add(sprite); board[x/10][y/10] = 1; age = 0; } bool decay(int lifespan, SpriteGroup* group, vector<Segment*>* list, int index, int (&board)[50][50]){ age++; if (age > lifespan){ group->remove(*sprite); list->erase(list->begin()+index); board[x/10][y/10] = 0; return true; } else return false; } }; int main(){ srand (time(NULL)); int window_height = 500; int window_width = 500; SDL_Init(SDL_INIT_EVERYTHING); SDL_Window *window = NULL; window = SDL_CreateWindow ("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 500, 500, SDL_WINDOW_RESIZABLE); if (window == NULL){ cout << "Something Happened" << endl; } SDL_Surface *screen = SDL_GetWindowSurface(window); Uint32 white = SDL_MapRGB(screen->format,255,255,255); Uint32 red = SDL_MapRGB(screen->format,255,0,0); Uint32 blue = SDL_MapRGB(screen->format,0,0,255); SDL_FillRect(screen, NULL, white); SpriteGroup active_sprites; int board[50][50]; for (int i = 0; i < 50; i++){ for (int j = 0; j < 50; j++){ board[i][j] = 0; } } Segment segment (30,30, &active_sprites, screen, board); Sprite* object = new Sprite(blue,250,250,10,10); active_sprites.add(object); board[25][25] = 2; Uint32 startingTick; SDL_Event event; bool running = true; int speed = 100; Uint32 lastMove = SDL_GetTicks(); int headPos_x = 0; int headPos_y = 0; int lifespan = 1; vector<Segment*> segments; int direction = 0; bool pressed; segments.push_back(&segment); while (running == true){ startingTick = SDL_GetTicks(); SDL_FillRect(screen, NULL, white); active_sprites.draw(screen); SDL_UpdateWindowSurface(window); while (SDL_PollEvent(&event)){ if (event.type == SDL_QUIT){ running = false; cout << "Goodbye" << endl; break; } if (event.type == SDL_KEYDOWN){ if (event.key.keysym.sym == SDLK_UP && direction != 3 && !pressed){ direction = 1; pressed = true; } else if (event.key.keysym.sym == SDLK_RIGHT && direction != 4 && !pressed){ direction = 2; pressed = true; } else if (event.key.keysym.sym == SDLK_DOWN && direction != 1 && !pressed){ direction = 3; pressed = true; } else if (event.key.keysym.sym == SDLK_LEFT && direction != 2 && !pressed){ direction = 4; pressed = true; } if(event.key.keysym.sym == SDLK_a){ for (int i = 0; i < 50; i++){ for (int j = 0; j < 50; j++){ cout<< board[i][j]; } cout << endl; } } } } if(SDL_GetTicks() - lastMove > speed){ pressed = false; lastMove = SDL_GetTicks(); for(int i = 0; i < segments.size(); i++){ segments[i]->decay(lifespan,&active_sprites,&segments,i,board); } if(direction == 1) headPos_x -=10; else if(direction == 2) headPos_y +=10; else if(direction == 3) headPos_x +=10; else if(direction == 4) headPos_y -=10; if(board[headPos_y/10][headPos_x/10] == 2){ lifespan += 5; active_sprites.remove(*object); board[headPos_y/10][headPos_x/10] = 0; int newX,newY; do{ newX = rand() %50; newY = rand() %50; }while(board[newX][newY] != 0); board[newX][newY] = 2; delete object; object = new Sprite(blue,newX*10,newY*10,10,10); active_sprites.add(object); } if( board[headPos_y/10][headPos_x/10] == 1 || headPos_y < 0 || headPos_y > 500 || headPos_x < 0 || headPos_x > 500){ segments.clear(); delete object; active_sprites.empty(); object = new Sprite(blue, 250,250,10,10); active_sprites.add(object); lifespan = 1; headPos_y = 0; headPos_x = 0; direction = 0; for (int i = 0; i < 50; i++){ for (int j = 0; j < 50; j++){ board[i][j] = 0; } } board[25][25] = 2; segments.push_back(new Segment(headPos_y,headPos_x, &active_sprites, screen, board)); } segments.push_back(new Segment(headPos_y,headPos_x, &active_sprites, screen, board)); } if((1000/60)>SDL_GetTicks() - startingTick){ SDL_Delay(1000/60 - (SDL_GetTicks()-startingTick)); } } SDL_DestroyWindow(window); SDL_Quit(); return 0; }
true
2d3dae6d3e8497484f2667f43f3cf1c1bbfb64a5
C++
mm4ever/feature_3daoi
/src/SSDK/Shape.hpp
UTF-8
1,514
2.921875
3
[]
no_license
#ifndef SHAPE_HPP #define SHAPE_HPP #include <vector> #include "Point.hpp" namespace SSDK { /** * @brief 表示形状的类,存有形状的坐标位置 * * @author peter * @version 1.00 2018-01-05 peter * note:create it */ class Shape { public: enum class ShapeType { CIRCLE, RECTANGLE }; //>>>------------------------------------------------------------------- // constructor & destructor Shape(); virtual ~Shape(); //>>>------------------------------------------------------------------- // set & get function Point& centerPoint() { return this->m_centerPoint; } std::vector<Point>& limitPoints(){ return this->m_limitPoints; } ShapeType shapeType() {return this->m_shapeType;} //>>>------------------------------------------------------------------- // member function virtual void findBoundaryPoints() = 0; virtual bool canContain(SSDK::Shape *pShape) = 0; protected: //>>>------------------------------------------------------------------- // member variant std::vector<Point> m_limitPoints; //形状的临界点 ShapeType m_shapeType;//形状类型 Point m_centerPoint; //形状的中心点 //<<<------------------------------------------------------------------- }; }//End of namespace SSDK #endif // SHAPE_HPP
true
5683485b6618f33cdcdf471f54d729d69d61c8ff
C++
xdlaba02/light-field-image-format
/liblfif/include/components/stack_allocator.h
UTF-8
1,025
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
#pragma once #include <cstdint> #include <cstdlib> #include <cassert> #include <algorithm> #include <iostream> class StackAllocator { inline static uint8_t *m_base = nullptr; inline static uint8_t *m_head = nullptr; inline static uint8_t *m_end = nullptr; inline static uint8_t *m_max_head = nullptr; StackAllocator() = delete; static constexpr size_t alignment = 64; public: static void init(size_t size) { m_base = static_cast<uint8_t *>(aligned_alloc(alignment, size)); m_head = m_base; m_end = m_base + size; } static void cleanup() { std::cerr << "Stack allocator peak memory usage: " << m_max_head - m_base << " bytes.\n"; ::free(m_base); } static void *allocate(size_t size) { size_t bytes = (size + alignment - 1) & -alignment; assert(m_head + bytes < m_end); void *ptr = m_head; m_head += bytes; m_max_head = std::max(m_head, m_max_head); return ptr; } static void free(void *ptr) { m_head = static_cast<uint8_t *>(ptr); } };
true
9985fb0fd176b16ab5bb91c7b8678bfcc7e034b0
C++
GwonilJoo/Samsung_SDS_Algorithm
/2_TimeComplexity/D.cpp
UTF-8
1,164
3.140625
3
[]
no_license
// 2517 달리기 /* Inversion Count merge sort의 merge 과정! 근데 왜 시간초과 뜨냐;; -> endl 대신 '\n' 쓰기..... */ #include<iostream> #include<algorithm> using namespace std; struct Runner{ int pos; long long value; }; int N; Runner nums[500000]; Runner temp[500000]; int Rank[500000]; void merge(int s, int m, int e){ int p1 = s; int p2 = m+1; int k = s; while(p1<=m && p2<=e){ if(nums[p1].value >= nums[p2].value){ temp[k++] = nums[p1++]; } else{ Rank[nums[p2].pos] -= (m-p1+1); temp[k++] = nums[p2++]; } } while(p1 <= m){ temp[k++] = nums[p1++]; } while(p2 <= e){ temp[k++] = nums[p2++]; } for(int i=s;i<=e;i++){ nums[i] = temp[i]; } } void mergeSort(int s, int e){ if(s<e){ int mid = (s+e)/2; mergeSort(s,mid); mergeSort(mid+1,e); merge(s,mid,e); } } void init(){ cin >> N; for(int i=0;i<N;i++){ long long tmp; cin >> tmp; nums[i] = {i, tmp}; Rank[i] = i+1; } } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); init(); mergeSort(0,N-1); for(int i=0;i<N;i++) cout << Rank[i] << "\n"; }
true
098a499362630c685b610af6c96d75a43fca790f
C++
Sopel97/conference_db_gen
/conference_database_gen/include/Csv/CsvDocument.h
UTF-8
329
2.640625
3
[]
no_license
#pragma once #include <vector> #include "CsvRecord.h" class CsvDocument { public: void add(const CsvRecord& record); void add(CsvRecord&& record); std::string toString() const; friend std::ostream& operator<< (std::ostream& stream, const CsvDocument& doc); private: std::vector<CsvRecord> m_records; };
true
4ee74cde76e9a2ba4483ca6b0a04f3d6479ec0b4
C++
kevyuu/soul
/sample/triangle/triangle_sample.cpp
UTF-8
2,479
2.65625
3
[]
no_license
#include "core/panic.h" #include "core/type.h" #include "gpu/gpu.h" #include <app.h> using namespace soul; class TriangleSampleApp final : public App { gpu::ProgramID program_id_; auto render(gpu::TextureNodeID render_target, gpu::RenderGraph& render_graph) -> gpu::TextureNodeID override { const gpu::ColorAttachmentDesc color_attachment_desc = { .node_id = render_target, .clear = true, }; const vec2ui32 viewport = gpu_system_->get_swapchain_extent(); struct PassParameter { }; const auto& raster_node = render_graph.add_raster_pass<PassParameter>( "Triangle Test", gpu::RGRenderTargetDesc(viewport, color_attachment_desc), [](auto& parameter, auto& builder) -> void { // We leave this empty, because there is no any shader dependency. // We will hardcode the triangle vertex on the shader in this example. }, [viewport, this](const auto& parameter, auto& registry, auto& command_list) -> void { const gpu::GraphicPipelineStateDesc pipeline_desc = { .program_id = program_id_, .viewport = {.width = static_cast<float>(viewport.x), .height = static_cast<float>(viewport.y)}, .scissor = {.extent = viewport}, .color_attachment_count = 1, }; using Command = gpu::RenderCommandDraw; const Command command = { .pipeline_state_id = registry.get_pipeline_state(pipeline_desc), .vertex_count = 3, .instance_count = 1, }; command_list.push(command); }); return raster_node.get_color_attachment_node_id(); } public: explicit TriangleSampleApp(const AppConfig& app_config) : App(app_config) { gpu::ShaderSource shader_source = gpu::ShaderFile("triangle_sample.hlsl"); const std::filesystem::path search_path = "shaders/"; const auto entry_points = std::to_array<gpu::ShaderEntryPoint>( {{gpu::ShaderStage::VERTEX, "vsMain"}, {gpu::ShaderStage::FRAGMENT, "fsMain"}}); const gpu::ProgramDesc program_desc = { .search_path_count = 1, .search_paths = &search_path, .source_count = 1, .sources = &shader_source, .entry_point_count = entry_points.size(), .entry_points = entry_points.data(), }; program_id_ = gpu_system_->create_program(program_desc).value(); } }; auto main(int /* argc */, char* /* argv */[]) -> int { TriangleSampleApp app({}); app.run(); return 0; }
true
a4e20bfbd41c070be3a4237b29ab8b0f0264b734
C++
xiazhiheng/C
/List/SqlList.cpp
UTF-8
974
3.140625
3
[]
no_license
#include<iostream> using namespace std; #define MaxSize 10 SqlList* InitList(SqlList *sqlList); bool ListInsert(SqlList *sqlList,int i,int data); bool ListDelete(SqlList *sqlList,int i); typedef struct{ int data[MaxSize]; int length; }SqlList; int main(){ } SqlList* InitList(SqlList *sqlList){ sqlList = (SqlList*)malloc(sizeof(SqlList)*MaxSize); sqlList->length = 0; return sqlList; } bool ListInsert(SqlList *sqlList,int i,int data){ if(i > sqlList->length || i<1){ return false; } if(sqlList->length == MaxSize){ return false; } for(int j=sqlList->length;j>i-1;j--){ sqlList->data[j] = sqlList->data[j-1]; } sqlList->data[i-1] = data; sqlList->length++; return true; } bool ListDelete(SqlList *sqlList,int i){ if(i > sqlList->length-1 || i<1){ return false; } if(sqlList->length<1){ return false; } for(int j=i-1;j<sqlList->length-1;j++){ sqlList[j]=sqlList[j+1]; } sqlList->length--; return true; }
true
7488bfc00c63681c98823700014c5245116e0a05
C++
kkq1l/konfetki
/СandyWay/СandyWay/Hud.cpp
UTF-8
1,330
2.546875
3
[]
no_license
#include "Hud.h" Hud::Hud() { image.loadFromFile("Texture/life.png"); image.createMaskFromColor(Color(50, 96, 166)); t.loadFromImage(image); s.setTexture(t); s.setTextureRect(IntRect(783, 2, 15, 84)); bar.setFillColor(Color(0, 0, 0)); max = 100; key = 0; } void Hud::initGUI() { font.loadFromFile("Fonts/PixellettersFull.ttf"); gameOverText.setFont(font); gameOverText.setCharacterSize(60); gameOverText.setFillColor(sf::Color::Red); gameOverText.setString("Game Over!"); gameOverText.setPosition(555, 300); } void Hud::Reset() { key = 0; } void Hud::update(int k) { if (k > 1) { if (k < max) bar.setSize(Vector2f(10, (max - k) * 70 / max)); } else { key = 1; } } void Hud::draw(RenderWindow& window) { Vector2f center = window.getView().getCenter(); Vector2f size = window.getView().getSize(); if (key == 1) { font.loadFromFile("Texture/Fonts/PixellettersFull.ttf"); gameOverText.setFont(font); gameOverText.setCharacterSize(60); gameOverText.setFillColor(sf::Color::Red); gameOverText.setString("Game Over!"); gameOverText.setPosition(center.x-100, center.y); window.draw(gameOverText); } s.setPosition(center.x - size.x / 2 + 10, center.y - size.y / 2 + 10); bar.setPosition(center.x - size.x / 2 + 14, center.y - size.y / 2 + 14); window.draw(s); window.draw(bar); }
true
a23b7cd6e69af0285122466d4b5ff88548c76d24
C++
MarcoAFC/gameoflife
/src/life.cpp
UTF-8
5,004
3.234375
3
[]
no_license
#include "../include/life.h" #include "../include/matriz.h" /*! * A function that seeks the alive cells and places them in a map, while generating a hash for rule verification. * \param mat the matrix representing the table. * \param nlinhas the number of lines in the matrix. * \param ncol the number of columns in the matrix. * \param map the map where the cells are stored. */ void Life::set_alive(std::vector<std::vector<int>> &mat, int nlinhas, int ncol,std::multimap <int, int> &map){ hash = "a"; map.clear(); //iniciarBorda(nlinhas, ncol, mat); for(int i = 2;i < nlinhas - 2; ++i) { for (int j = 2;j < ncol - 2; ++j) { if(mat[i][j] == 1){ map.insert(std::pair<int,int>(i,j)); hash = std::string( hash + "l" + std::to_string(i) + "c" + std::to_string(j)); } } } /* for(auto p : map) { std::cout << p.first << ", " << p.second << "\n"; }*/ } /*! * A function that counts the neighbours of alive cells and them and checks if they pass the rules to remain alive. * \param mat the matrix representing the table. * \param mat2 the matrix representing the new shape of the table. * \param map the map where the alive cells are stored. */ void Life::contar_vizinho(std::vector<std::vector<int>> &mat,std::vector<std::vector<int>> &mat2,std::multimap <int, int> &map){ for(auto p : map) { std::cout << p.first << ", " << p.second << "\n"; int vizinhos = 0; if (mat[p.first-1][p.second-1] == 1){ vizinhos++; } if (mat[p.first][p.second-1] == 1){ vizinhos++; } if (mat[p.first+1][p.second-1] == 1){ vizinhos++; } if (mat[p.first-1][p.second] == 1){ vizinhos++; } if (mat[p.first+1][p.second] == 1){ vizinhos++; } if (mat[p.first-1][p.second+1] == 1){ vizinhos++; } if (mat[p.first][p.second+1] == 1){ vizinhos++; } if (mat[p.first+1][p.second+1] == 1){ vizinhos++; } //eventos para celula viva if(mat[p.first][p.second] == 1){ if(vizinhos < 2){ //morre de solidão mat2[p.first][p.second] = 0; } else if(vizinhos > 3){ //morre sufocada mat2[p.first][p.second] = 0; } else{ mat2[p.first][p.second] = 1; } } //evento para celula morta else if(vizinhos == 3){ mat2[p.first][p.second] = 1; } } std::cout<<"\n\n\n"; } /*! * A function that stores the positions of cells with potential changes. * \param mat the matrix representing the table. * \param mat2 the matrix representing the new shape of the table. * \param map the map where the alive cells are stored. * \param map2 the map where the neighbours of the alive cells are stored. */ void Life::guardar_vizinhos(std::vector<std::vector<int>> &mat,std::vector<std::vector<int>> &mat2, std::multimap <int, int> &map,std::multimap <int, int> &map2){ map2.clear(); for(auto p5 : map){ for(int cont1=-1;cont1 <=1; cont1++){ for (int cont2 = -1;cont2 <=1; cont2++){ if (cont1 !=0 && cont2 != 0){ map2.insert(std::pair<int,int>((p5.first+cont1),(p5.second+cont2))); } } } } /*for(auto p : map2) { std::cout << p.first << ", " << p.second << "\n"; }*/ } /*! * A function that checks if the system has reached any of the conditions to stop execution. * \param chave a hash representing the current system. It is checked to see if the system has happened before. * \param ligado a verification to see if the system if working properly. * \param maxgen the user-set maximum number of iterations. * \param geracao the current number of iterations. */ int Life::pararExec(std::vector<std::string> &chave, int ligado, int maxGen, int geracao){ //primeira geração para abrir o vetor if (maxGen == geracao){ return 0; } if (hash == "a"){ return 0; } for(unsigned int i=0; i<chave.size(); i++) { if(chave[i] == hash){ return 0; } } if(chave.size() == 0){ chave.push_back(hash); return 1; } chave.push_back(hash); return 1; }
true
d341385dffde8190653aaa9d2c2aad73f224cc8c
C++
IceAndSnow/touchdown
/src/players/generic_instantiator.h
UTF-8
885
2.90625
3
[]
no_license
#ifndef TOUCHDOWN_GENERIC_INSTANTIATOR_H #define TOUCHDOWN_GENERIC_INSTANTIATOR_H #include "player_instantiator.h" namespace players { template<typename TPlayer> class GenericInstantiator : public PlayerInstantiator { private: TPlayer* m_player; public: GenericInstantiator() { m_player = nullptr; } virtual game::Player* createNewPlayer() { if(m_player != nullptr) { cleanUp(); } m_player = new TPlayer(); return m_player; }; virtual std::string name() { TPlayer p; return p.name(); } virtual void cleanUp() { if(m_player != nullptr) { delete m_player; m_player = nullptr; } }; }; } #endif //TOUCHDOWN_GENERIC_INSTANTIATOR_H
true
7527b7125bd0ada117cdfc8e39d981d5b32ac8e6
C++
krishna6431/Data-Structure-Algorithms-Implementation-Using_CPP
/01_Recursion/04_head_recursion.cpp
UTF-8
466
3.375
3
[ "Apache-2.0" ]
permissive
//Data Structure Course //All Codes Are Written by Krishna //Recursion #include<iostream> using namespace std; int function1(int n); void function(int n){ if(n>0){ function(n-1); cout << n << " "; } } int main(){ int x=10; function(x); cout << endl; function1(x); cout << endl; return 0; } // converting head Recursion to loop int function1(int n){ int i=1; while(i<=n){ cout << i <<" "; i++; } return 0; }
true
96c4a48439b78d20a488cdacfeb8d9a71d048eeb
C++
SameOwner/gravity
/MyGame/MyGame/src/Fade/FadeSprite.h
UTF-8
492
2.734375
3
[]
no_license
#pragma once #include<functional> class FadeSprite { private: enum State { In, Out, Stop }; public: FadeSprite(); ~FadeSprite(); void init(); void start(); void update(float deltaTime); void draw()const; bool isActive()const; void addCallBack(const std::function<void()>& func); void in(float deltaTime); void stop(float deltaTime); void out(float deltaTime); private: float timer_; int state_; float fadeTimer_; bool isActive_; std::function<void()> function_; };
true
d818b7faf60164f0c7b0ac04dbd71727520bacef
C++
johnmangold/School-Projects
/csc456/prog3/mailbox/mailbox_functions.cpp
UTF-8
6,294
3.015625
3
[]
no_license
#include "mailbox.h" using namespace std; /************************************************************************ Function: bool create_memory(vector<int> &ids, int mb_num, int mb_size Author: John Mangold, Colter Assman, Jason Anderson Description: Creates shared memory segments Parameters: vector<int> &ids - in/out - stores all the shmids int mb_num - in - desired number of mailboxes int mb_size - in - desired mailbox size in kilobytes returns true - create memory segments returns false - segments already exist ************************************************************************/ bool create_memory(vector<int> &ids, int mb_num, int mb_size) { char *address; int shmid; int *start; //create shared memory blocks for(int i = 0;i < mb_num+1;i++) { shmid = shmget(SHMKEY+i, mb_size, IPC_CREAT | IPC_EXCL | 0666 ); if( shmid < 0 ) { return false; } ids.push_back(shmid); } //attach shared memory to process address = (char *) shmat(ids[0], 0, 0); //set up pointer to array of integers start = (int *) address; //assign size then shmids in sequential order in first block *start = mb_size; for( unsigned int i = 1; i <= ids.size(); i++) { *(start+i) = ids[i-1]; } ids.clear(); shmdt(address); return true; } /************************************************************************ Function: bool delete_mailbox( Author: John Mangold, Colter Assman, Jason Anderson Description: Deletes shared memory segments with no processes attached Parameters: returns true - segments will be deleted ************************************************************************/ bool delete_mailbox() { int shmid; int *start; //get shmid of first block and attach shmid = shmget(SHMKEY, 0, 0); start = (int *) shmat(shmid, 0, 0); for( unsigned int i = 1; *(start+i) != NULL; i++ ) { shmctl(*(start+i), IPC_RMID, 0); } shmdt((char *) start); return true; } /************************************************************************ Function: bool write_mailbox(int mb_num) Author: John Mangold, Colter Assman, Jason Anderson Description: Writes chars to desired mailbox Parameters: int mb_num - in - mailbox number to write to returns true - Information was written to shared memory ************************************************************************/ bool write_mailbox(int mb_num) { char *data; int shmid; int shmid1; int *start; unsigned int size; string s; struct sembuf wait, signal; int semid; unsigned short semval = 1; wait.sem_num = 0; wait.sem_op = -1; wait.sem_flg = SEM_UNDO; signal.sem_num = 0; signal.sem_op = 1; signal.sem_flg = SEM_UNDO; //create semaphore semid = semget(SEMKEY, 1, IPC_CREAT); //set semaphore value semctl(semid, 0, SETVAL, semval); //get shmid and size for appropriate mailbox //start+(mb_num+2) shmid = shmget(SHMKEY, 0, 0); start = (int *) shmat(shmid, 0, 0); size = *start; for(int i = 0; i < mb_num+2;i++) { shmid1 = *(start+i); } shmdt((char *) start); //attach to desired mailbox data = (char *) shmat(shmid1, 0, 0); if( data == (char *) -1) { cout << endl << "that didn't work" << endl; } //while input and not bigger than mailbox size //ctrl-d breaks this thing. don't know why. because programming. cout << "Enter data below. Press \"Enter\" to commit.\n"; getline(cin, s); if( s.size() >= size ) { s = s.substr(0,size); } //set lock semop(semid, &wait, 1); for(unsigned int i = 0; i < s.size(); i++) { *(data+i) = s[i]; } //unlock semop(semid, &signal, 1); //clean up semaphore and detach from shared memory semctl(semid, 0, IPC_RMID); shmdt(data); return true; } /************************************************************************ Function: bool copy_mailbox(int mb_num1, int mb_num2) Author: John Mangold, Colter Assman, Jason Anderson Description: Copys contents from mb_num1 to mb_num2 Parameters: int mb_num1 - in - mailbox number to copy from int mb_num2 - in - mailbox number to copy to returns true - Information was copied ************************************************************************/ bool copy_mailbox(int mb_num1, int mb_num2) { int *start; char *start1; char *start2; int shmid; int shmid1; int shmid2; int size; struct sembuf wait, signal; int semid; unsigned short semval = 1; wait.sem_num = 0; wait.sem_op = -1; wait.sem_flg = SEM_UNDO; signal.sem_num = 0; signal.sem_op = 1; signal.sem_flg = SEM_UNDO; //create semaphore semid = semget(SEMKEY, 1, IPC_CREAT); //set semaphore value semctl(semid, 0, SETVAL, semval); //get shmid and size for both mailboxes shmid = shmget(SHMKEY, 0, 0); start = (int *) shmat(shmid, 0, 0); size = *start; for(int i = 0; i < mb_num1+2;i++) { shmid1 = *(start+i); } for(int i = 0; i < mb_num2+2;i++) { shmid2 = *(start+i); } shmdt((char *) start); //attach to both mailboxes start1 = (char *) shmat(shmid1, 0, 0); start2 = (char *) shmat(shmid2, 0, 0); //set lock semop(semid, &wait, 1); //copy contents from mailbox1 to mailbox2 for( int i = 0; i < size; i++ ) { *(start2+i) = *(start1+i); } //unlock semop(semid, &signal, 1); //remove semaphore and detach semctl(semid, 0, IPC_RMID); shmdt(start1); shmdt(start2); return true; } /************************************************************************ Function: bool read_mailbox(int mb_num) Author: John Mangold, Colter Assman, Jason Anderson Description: Reads contents of mailbox and outputs to console Parameters: int mb_num - in - mailbox to read returns true - mailbox contents were read ************************************************************************/ bool read_mailbox(int mb_num) { int shmid; int shmid1; int *start; char *read; int size; int count = 0; //access first block and get size and mailbox shmid shmid = shmget(SHMKEY, 0, 0); start = (int *) shmat(shmid, 0, 0); size = *start; for(int i = 0; i < mb_num+2;i++) { shmid1 = *(start+i); } shmdt((char *) start); //attach to mailbox read = (char *) shmat(shmid1, 0, 0); //read through memory and output to screen while ( (*(read+count) != NULL) && (count < size)) { cout << *(read+count); count++; } cout << endl; shmdt(read); return true; }
true
04f7a30c13c24ab6dd2d238aadae13f58526bc3a
C++
HitLumino/mrpt
/libs/serialization/src/stl_serialize_unittest.cpp
UTF-8
1,802
2.625
3
[ "BSD-3-Clause" ]
permissive
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #include <mrpt/serialization/CSerializable.h> #include <mrpt/serialization/CArchive.h> #include <mrpt/serialization/stl_serialization.h> #include <mrpt/io/CMemoryStream.h> #include <gtest/gtest.h> using namespace mrpt::serialization; TEST(Serialization, STL_stdvector) { std::vector<uint32_t> m2, m1{1, 2, 3}; mrpt::io::CMemoryStream f; auto arch = mrpt::serialization::archiveFrom(f); arch << m1; f.Seek(0); arch >> m2; EXPECT_EQ(m1, m2); } TEST(Serialization, STL_stdmap) { std::map<uint32_t, uint8_t> m2, m1; m1[2] = 21; m1[9] = 91; mrpt::io::CMemoryStream f; auto arch = mrpt::serialization::archiveFrom(f); arch << m1; f.Seek(0); arch >> m2; EXPECT_EQ(m1, m2); } TEST(Serialization, STL_complex_error_type) { std::map<double, std::array<uint8_t, 2>> v1; std::map<double, std::array<int8_t, 2>> v2; // different type! v1[0.4].fill(2); mrpt::io::CMemoryStream f; auto arch = mrpt::serialization::archiveFrom(f); arch << v1; // Trying to read to a different variable raises an exception: f.Seek(0); try { arch >> v2; EXPECT_TRUE(false) << "Expected exception that was not raised!"; } catch (std::exception&) { // Good. } }
true
6339d99715194908dffa4105cf0d8b35e5bb47ab
C++
mdqyy/FeatureDetection
/libTracking/include/classification/FixedApproximateSigmoidParameterComputation.h
UTF-8
1,675
2.703125
3
[]
no_license
/* * FixedApproximateSigmoidParameterComputation.h * * Created on: 24.09.2012 * Author: poschmann */ #ifndef FIXEDAPPROXIMATESIGMOIDPARAMETERCOMPUTATION_H_ #define FIXEDAPPROXIMATESIGMOIDPARAMETERCOMPUTATION_H_ #include "classification/ApproximateSigmoidParameterComputation.h" namespace classification { /** * Approximate sigmoid parameter computation that determines the parameter only once * on construction. May be used when the mean SVM outputs of the positive and negative * samples rarely change. */ class FixedApproximateSigmoidParameterComputation : public ApproximateSigmoidParameterComputation { public: /** * Constructs a new fixed approximate sigmoid parameter computation. * * @param[in] highProb The probability of the mean output of positive samples. * @param[in] lowProb The probability of the mean output of negative samples. * @param[in] The estimated mean SVM output of the positive samples. * @param[in] The estimated mean SVM output of the negative samples. */ explicit FixedApproximateSigmoidParameterComputation(double highProb = 0.99, double lowProb = 0.01, double meanPosOutput = 1.01, double meanNegOutput = -1.01); ~FixedApproximateSigmoidParameterComputation(); std::pair<double, double> computeSigmoidParameters(const struct svm_model *model, struct svm_node **positiveSamples, unsigned int positiveCount, struct svm_node **negativeSamples, unsigned int negativeCount); private: double paramA; ///< Parameter A of the sigmoid function. double paramB; ///< Parameter B of the sigmoid function. }; } /* namespace classification */ #endif /* FIXEDAPPROXIMATESIGMOIDPARAMETERCOMPUTATION_H_ */
true
58c5f35d23b43e58fa3bc7d2ea2ed15bcc21085a
C++
Jin-SukKim/Algorithm
/Problem_Solving/leetcode/Algorithm/Sorting/56_Merge_Intervals/mergeIntervals.cpp
UTF-8
1,956
4.03125
4
[]
no_license
/* 56. Merge Intervals Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Example 1: Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6]. Example 2: Input: intervals = [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. Constraints: 1 <= intervals.length <= 104 intervals[i].length == 2 0 <= starti <= endi <= 104 */ #include <vector> #include <algorithm> // 겹치는 구간을 병합 class Solution { private: public: std::vector<std::vector<int>> merge(std::vector<std::vector<int>> &intervals) { if (intervals.empty()) return {}; std::sort(intervals.begin(), intervals.end(), [](const std::vector<int> &a, const std::vector<int> &b) { return a[0] < b[0]; }); std::vector<std::vector<int>> list; for (auto i : intervals) { // 이전 아이템의 끝이 다음 아이템의 시작값보다 작으면 겹치므로 병합해준다. if (!list.empty() && i[0] <= list[list.size() - 1][1]) // 이전 아이템의 끝과 다음 아이템의 끝 중 더 큰 값을 끝 값으로 사용 list[list.size() - 1][1] = std::max(list[list.size() - 1][1], i[1]); else list.push_back(i); } return list; } }; int main() { std::vector<std::vector<int>> list = { {1, 3}, {2, 6}, {8, 10}, {15, 18}}; Solution s; s.merge(list); return 0; }
true
64b11de14222375e0028c1c9e2e12da04c8dc29e
C++
eemurat3/Array
/Array.h
UTF-8
4,713
4.15625
4
[]
no_license
/** * @file Array.h * @author murat kaymaz * @brief This class is uses for array operation and can be used for all types * @version 0.1 * @date 2021-05-30 * * @copyright Copyright (c) 2021 * */ #ifndef ARRAY_H #define ARRAY_H template<class T> class Array{ public: /** * @brief Construct a new Array object * default array size equal 10 * */ Array(); /** * @brief Construct a new Array object * * @param size : array size */ Array(int size); /** * @brief Destroy the Array object * */ ~Array(); /** * @brief if array is not full add a new value end of array * * @param value : value to add */ void append(T value); /** * @brief * * @param index : index to add * @param value : insert the value in wanted index */ void insert(int index,T value); /** * @brief Erase the wanted index * * @param index : index to erase * @return T : Erased value */ T erase(int index); /** * @brief array value to set * * @param index : index to set * @param value : new value */ void setElement(int index,T value); /** * @brief Get the array Element * * @param index : index to get * @return T : index value -> if index is valid return the index value, else returning empty */ T getElement(int index); /** * @brief Get the array element * * @param index : index to get * @return T& : index value -> if index is valid return the index value, else returning empty */ T& operator[](int index); /** * @brief total number of elements in the array * * @return int : nmber of total elements */ int length(); /** * @brief : look for the desired value in the array * * @param key : searched value * @return int : if value is find return the index else return -1 */ int search(T key); /** * @brief reverse the arrar * */ void reverse(); /** * @brief show the array elements * */ void display(); private: /** * @brief swap the two value * * @param a : value 1 * @param b : value 2 */ void swap(T* a, T* b); T *array; int size; int len; }; #endif template<class T> Array<T>::Array(){ size = 10; array = new T[size]; len = 0; } template<class T> Array<T>::Array(int tsize){ size = tsize; len = 0; array = new T[size]; } template<class T> void Array<T>::append(T value){ if(len < size){ array[len]=value; len += 1; } else { std::cout<<"\narray size is full\n"; } } template<class T> void Array<T>::insert(int index, T value){ if(index >= 0 && index <= len){ for(int i=len;i>index;i--) array[i] = array[i-1]; array[index] = value; len += 1; } else { std::cout<<"\ninvalid index\n"; } } template<class T> T Array<T>::erase(int index){ if(index >=0 && index <= len-1){ T deleted = array[index]; for(int i=index;i<len-1;i++) array[i]=array[i+1]; len -= 1; return deleted; } return T( ); } template<class T> void Array<T>::setElement(int index, T value){ if(index >= 0 && index <= len-1) { array[index] = value; } } template<class T> T Array<T>::getElement(int index){ if(index >= 0 && index <= len-1) return array[index]; return T( ); } template<class T> T& Array<T>::operator[](int index){ return array[index]; } template<class T> int Array<T>::length(){ return len; } template<class T> int Array<T>::search(T key){ for(int i=0;i<len;i++) { if(array[i] == key) return i; } return -1; } template<class T> void Array<T>::reverse(){ for(int i=0,j=length()-1;i<j;i++,j--) swap(&array[i],&array[j]); } template<class T> void Array<T>::swap(T* a, T* b){ T temp=*a; *a=*b; *b=temp; } template<class T> void Array<T>::display(){ std::cout<<"\nElements are : "; for(int i=0;i<len;i++) std::cout<<array[i]<<" "; std::cout<<"\n"; } template<class T> Array<T>::~Array(){ delete []array; }
true
aa3a9b5c9fde39d8f166ff93b9e1f49a447df232
C++
makometr/ADS-9304
/Shunyaev/cw/Source/Node.h
UTF-8
1,349
2.765625
3
[]
no_license
#pragma once #include "Includes.h" class Node { friend class AVLTree; public: Node(int key, std::shared_ptr<Node> left = nullptr, std::shared_ptr<Node> right = nullptr); unsigned char GetHeight(); int GetKey(); int GetCounter(); int BalanceFactor(DemoState state = DemoState::NoDemo); void AdaptHeight(DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> NodeBalancing(std::shared_ptr<Node> node, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> Remove(int key, std::shared_ptr<Node> head, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> Insert(int key, std::shared_ptr<Node> head, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> Find(int key, std::shared_ptr<Node> head, DemoState state = DemoState::NoDemo); private: unsigned char height_; int key_; int counter_; std::shared_ptr<Node> left_; std::shared_ptr<Node> right_; static std::shared_ptr<Node> RotateRight(std::shared_ptr<Node> node, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> RotateLeft(std::shared_ptr<Node> node, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> FindMin(std::shared_ptr<Node> node, DemoState state = DemoState::NoDemo); static std::shared_ptr<Node> RemoveMin(std::shared_ptr<Node> node, DemoState state = DemoState::NoDemo); };
true
a13a14077435675553c2f04edd3fef0f9a04fddd
C++
kopecdav/CircleCi
/_libs_/byzance/MqttBuffer.cpp
UTF-8
2,619
2.875
3
[]
no_license
/* * DeviceList.h * * Created on: 11. 7. 2016 * Author: Viktor, Martin */ #include "MqttBuffer.h" #include "ByzanceJson.h" REGISTER_DEBUG(MqttBuffer); MqttBuffer::MqttBuffer(){ _msg_list.clear(); } // todo: destruktor!!! /** * @brief Lock buffer * @param none * @retval ==0 for success * !=0 for error */ MqttBuffer_Err_TypeDef MqttBuffer::lock(uint32_t ms){ osStatus status; status = _mutex.lock(ms); if(status!=osOK){ return MQTT_BUFFER_BUSY; } return MQTT_BUFFER_OK; } /** * @brief Lock buffer * @param none * @retval ==0 for success * !=0 for error */ MqttBuffer_Err_TypeDef MqttBuffer::unlock(){ osStatus status; status = _mutex.unlock(); if(status!=osOK){ return MQTT_BUFFER_BUSY; } return MQTT_BUFFER_OK; } /** * @brief Get message * @param none * @retval ==0 for success * !=0 for error */ MqttBuffer_Err_TypeDef MqttBuffer::add_message(message_struct* ms){ // funkce size se lockne sama if(_msg_list.size() >= MQTT_BUFFER_CAPACITY){ return MQTT_BUFFER_FULL; } // todo: throws exception on failure _msg_list.push_back(*ms); return MQTT_BUFFER_OK; } /** * @brief Get message * @param none * @retval ==0 for success * !=0 for error */ MqttBuffer_Err_TypeDef MqttBuffer::pick_up_message(message_struct *ms){ if(_msg_list.size()){ // vyčte první prvek *ms = _msg_list.front(); // smaže první prvek // todo: throws exception on failure _msg_list.pop_front(); } else { return MQTT_BUFFER_EMPTY; } return MQTT_BUFFER_OK; } /** * @brief Get message * @param none * @retval ==0 for success * !=0 for error */ MqttBuffer_Err_TypeDef MqttBuffer::get_only_message(message_struct *ms){ if(_msg_list.size()){ // vyčte první prvek *ms = _msg_list.front(); } else { return MQTT_BUFFER_EMPTY; } return MQTT_BUFFER_OK; } /** * @brief Get size of the list * @param none * @retval Number of allocated messages */ MqttBuffer_Err_TypeDef MqttBuffer::size(uint32_t *size){ *size = _msg_list.size(); return MQTT_BUFFER_OK; } /** * @brief Delete all messages in the list * @param none * @retval none */ MqttBuffer_Err_TypeDef MqttBuffer::clear(){ _msg_list.clear(); return MQTT_BUFFER_OK; } /** * Overi, jestli dana struktura je validni JSON a vrati jeho mid. * @return 0 - OK * @return number - error */ uint32_t get_json_msg_id(message_struct * msg_in, string * out_string){ picojson::value json_data_temp; // Neni to validni JSON if(ByzanceJson::validate(msg_in, json_data_temp) != ERROR_CODE_OK){ return 1; } *out_string = json_data_temp.get("mid").get<string>(); return 0; }
true
430f141de2f00d35f812bd3dadaf29c4f7095da7
C++
jrazoesp/Linux-Robotic-Arm
/demo.cpp
UTF-8
1,154
2.859375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <signal.h> #include <sched.h> #include <pthread.h> #include "RoboticArm.h" RoboticArm *RoboArm; void _cleanup(int signum) { std::cout << "\nINFO: Caught signal " << signum << std::endl; /* Delete all of the robotic-arm objects */ delete RoboArm; exit(signum); } int main(void) { /* Two joints robotic arm for the demo */ RoboArm = new RoboticArm(); /* Register a signal handler to exit gracefully */ signal(SIGINT, _cleanup); #ifdef RT_PRIORITY /* Higher priority for interrupt procesisng */ /* https://rt.wiki.kernel.org/index.php/HOWTO:_Build_an_RT-application */ struct sched_param sp = { .sched_priority = 99 }; if( sched_setscheduler(0, SCHED_FIFO, &sp) != 0 ) { std::cout << "WARNING: Failed to increase process priority!" << std::endl; } #endif RoboArm->Init(); usleep(2E06); /* Input a curve or shape to the roboarm to draw it */ for(;;) { RoboArm->UpdatePosition(); usleep(3E06); std::cout << std::endl; } return EXIT_SUCCESS; }
true
74cf240f44e8de8d630f194a0e3cb25831f10876
C++
anqin-gh/ECS
/src/ecs/cmp/entity.hpp
UTF-8
827
2.5625
3
[]
no_license
#pragma once #include <ecs/util/typealiases.hpp> #include "component.hpp" namespace ECS { struct Entity_t { explicit Entity_t() = default; constexpr EntityID_t getID() const noexcept { return ID; } template <typename CMP_t> void addBelongingComponent(const CMP_t& cmp) { auto typeID = cmp.getComponentTypeID(); m_components[typeID] = cmp.getID(); } auto begin() const noexcept { return std::begin(m_components); } auto begin() noexcept { return std::begin(m_components); } auto end() const noexcept { return std::end(m_components); } auto end() noexcept { return std::end(m_components); } private: inline static EntityID_t nextID{0}; EntityID_t ID{++nextID}; UMap_t<ComponentTypeID_t, ComponentID_t> m_components; }; } // namespace ECS
true
ca49ffd1542c148048fc5aba4822d90e56f01ca7
C++
furious/yoshisisland-leveltool
/functions.cpp
UTF-8
1,492
2.625
3
[]
no_license
#include "main.h" #define sprintf(format, ...) AnsiString().sprintf((format), __VA_ARGS__) // OTHER FUNCTIONS void fn_Log(UnicodeString text){ if(frsMain->chk_DebugInfo->Checked) frsMain->DebugInfo->Lines->Add(text); } // SNES ADDRESSING FUNCTIONS int addr2pc(int addr){ if(addr >= 0x400000) return addr - 0x400000; int bank = (addr & 0xFF0000) >> 16; int absolute = (addr & 0x00FFFF); int abs_corrected = absolute - 0x8000 * (1 - bank % 2); return (bank << 15) | abs_corrected; //return ((addr & 0xff0000) >> 1) | (addr & 0x7FFF); } int addr2snes(int addr){ int bank = (addr & 0xFF0000) * 2 + (addr & 0x008000) * 2; int absolute = addr & 0x00FFFF; int abs_corrected = absolute + 0x008000 - (absolute & 0x008000); return bank | abs_corrected; } int dickbutt2snes(int addr){ return addr2snes(addr2pc(addr)); } bool checkcrossbank(int addr, int size){ //fn_Log(addr2snes(addr + size) - addr2snes(addr)); return (addr2snes(addr) & 0xFF0000) >> 16 != (addr2snes(addr + size) & 0xFF0000) >> 16; } // ADDRESS FUNCTIONS unsigned short u8(char *value){ return *(((unsigned short*) value)); } unsigned short u16(char *value){ return *(((unsigned short*) value)); } unsigned int u24(char *value){ return *(((unsigned int*) value)) & 0xffffff; } unsigned int u32(char *value){ return *(((unsigned int*) value)); } char * int2bytes(unsigned int value, int size){ char * bytes = new char[size]; for(int x = 0; x < size; x++) bytes[x] = (value >> (x * 8)); return bytes; }
true
ea90b5a76d95273d4165306b70bb2db85a4d4614
C++
gtmcoder/bamtest
/src/bt.cpp
UTF-8
1,637
2.59375
3
[]
no_license
#include </Users/marth/Dropbox/Unix/Software/bamtest/bamtools/include/api/BamMultiReader.h> #include </Users/marth/Dropbox/Unix/Software/bamtest/bamtools/include/api/BamWriter.h> using namespace BamTools; // standard includes #include <iostream> #include <string> #include <vector> int main (int argc, char *argv[]) { std::cout << "Hello!" << std::endl; // file names std::vector<std::string> inputFilenames; inputFilenames.push_back("mutated_genome.bam"); std::string outputFilename = "out.bam"; //std::cout << "inputFilename=" << inputFilename << " outputFilename=" << outputFilename << std::endl; // attempt to open our BamMultiReader BamMultiReader reader; if ( !reader.Open(inputFilenames) ) { std::cerr << "Could not open input BAM files." << std::endl; return 1; } // retrieve 'metadata' from BAM files, these are required by BamWriter const SamHeader header = reader.GetHeader(); const RefVector references = reader.GetReferenceData(); // attempt to open our BamWriter BamWriter writer; if ( !writer.Open(outputFilename, header, references) ) { std::cerr << "Could not open output BAM file" << std::endl; return (1); } // iterate through all alignments, only keeping ones with high map quality BamAlignment al; long int count1 = 0; long int count2 = 0; while ( reader.GetNextAlignmentCore(al) ) { count1++; if ( al.MapQuality >= 30 ) { writer.SaveAlignment(al); count2++; } std::cout << "count1=" << count1 << " count2=" << count2 << std::endl; } // close the reader & writer reader.Close(); writer.Close(); }
true
de49afa3e91b5140c2209f7df61deb3edbbe23c6
C++
hysteriai/CppPrimer
/p40lx29.cpp
UTF-8
203
2.703125
3
[]
no_license
#include <iostream> using namespace std; int main() { // cin >> int input_value; // int i = {3.14}; // double salary = wage = 9999.99; int i = 3.14; cout << i << endl; return 0; }
true
91885a467f95b3ba8f5df370582168f3be073487
C++
sptungG/Data-Structure-Advanced
/Training 4-Divide&Conquer/C-EKO.cpp
UTF-8
2,447
3.1875
3
[]
no_license
/* Lumberjack Mirko needs to chop down M metres of wood. It is an easy job for him since he has a nifty new woodcutting machine that can take down forests like wildfire. However, Mirko is only allowed to cut a single row of trees. Mirko's machine works as follows: Mirko sets a height parameter H (in metres), and the machine raises a giant sawblade to that height and cuts off all tree parts higher than H (of course, trees not higher than H meters remain intact). Mirko then takes the parts that were cut off. (For example, if the tree row contains trees with heights of 20, 15, 10, and 17 metres, and Mirko raises his sawblade to 15 metres, the remaining tree heights after cutting will be 15, 15, 10, and 15 metres, respectively, while Mirko will take 5 metres off the first tree and 2 metres off the fourth tree (7 metres of wood in total).) Mirko is ecologically minded, so he doesn't want to cut off more wood than necessary. That's why he wants to se his sawblade as high as possible. ===Help Mirko find the maximum integer height of the sawblade that still allows him to cut off at least M metres of wood. **Input The first line of input contains two space-separated positive integers, N (the number of trees, 1≤N≤1000000) and M (Mirko's required wood amount, 1≤M≤2000000000). The second line of input contains N space-separated positive integers less than 1 000 000 000, the heights of each tree (in metres)-- --.The sum of all heights will exceed M, thus Mirko will always be able to obtain the required amount of wood. **Output The first and only line of output must contain the required height setting. TEST 5 20 4 42 40 26 46 =>36 -------------------------------------------- */ #include <bits/stdc++.h> using namespace std; const long long MAX = 1e6+5; int N; long long M; long long H[MAX]; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> N >> M; for (int i = 1; i <= N; i++) { cin >> H[i]; } long long l = 0, r = *max_element(H+1, H+N+1); long long m; long long minDif = 1e10; long long ans; while (r - l > 1) { m = (l+r)/2; long long sum = 0; for (int i = 1; i <= N; i++) { if (H[i] > m) sum += H[i] - m; } if (sum == M) { ans = m; break; } if (sum > M) { l = m; if (sum - M < minDif) ans = m; } else r = m; } cout << ans; }
true
b3e1989d6a6c7e6dd0d449a8bd058e6c94a50f7b
C++
principal6/TessellationTest
/Core/Camera.h
UTF-8
2,885
2.71875
3
[]
no_license
#pragma once #include "SharedHeader.h" class CCamera { public: enum class EType { FirstPerson, ThirdPerson, FreeLook }; enum class EMovementDirection { Forward, Backward, Rightward, Leftward, }; struct SCameraData { SCameraData() {} SCameraData(EType _eType, XMVECTOR _EyePosition, XMVECTOR _FocusPosition, XMVECTOR _UpDirection = XMVectorSet(0, 1, 0, 0), float _ZoomDistance = KDefaultZoomDistance, float _MinZoomDistance = KDefaultMinZoomDistance, float _MaxZoomDistance = KDefaultMaxZoomDistance) : eType{ _eType }, EyePosition{ _EyePosition }, FocusPosition{ _FocusPosition }, UpDirection{ _UpDirection }, BaseUpDirection{ _UpDirection }, BaseForwardDirection{ XMVector3Normalize(_FocusPosition - _EyePosition) }, Forward{ BaseForwardDirection }, ZoomDistance{ _ZoomDistance }, MinZoomDistance{ _MinZoomDistance }, MaxZoomDistance{ _MaxZoomDistance } {} static constexpr float KDefaultZoomDistance{ 10.0f }; static constexpr float KDefaultMinZoomDistance{ 1.0f }; static constexpr float KDefaultMaxZoomDistance{ 50.0f }; EType eType{}; XMVECTOR EyePosition{ XMVectorSet(0.0f, 0.0f, 0.0f, 1.0f) }; XMVECTOR FocusPosition{ XMVectorSet(0.0f, 0.0f, 1.0f, 1.0f) }; XMVECTOR UpDirection{ XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f) }; XMVECTOR BaseForwardDirection{ XMVector3Normalize(FocusPosition - EyePosition) }; XMVECTOR BaseUpDirection{ UpDirection }; float ZoomDistance{ KDefaultZoomDistance }; float MinZoomDistance{ KDefaultMinZoomDistance }; float MaxZoomDistance{ KDefaultMaxZoomDistance }; float Pitch{}; float Yaw{}; XMVECTOR Forward{}; }; public: CCamera(const std::string Name) : m_Name{ Name } {} ~CCamera() {} public: void Move(EMovementDirection Direction, float StrideFactor = 1.0f); void Rotate(int DeltaX, int DeltaY, float RotationFactor = 1.0f); void Zoom(int DeltaWheel, float ZoomFactor = 1.0f); void SetEyePosition(const XMVECTOR& Position); void SetPitch(float Value); void SetYaw(float Value); void SetType(EType eType); EType GetType() const { return m_CameraData.eType; } void SetData(const SCameraData& Data); const SCameraData& GetData() const { return m_CameraData; } const XMVECTOR& GetEyePosition() const { return m_CameraData.EyePosition; } const XMVECTOR& GetFocusPosition() const { return m_CameraData.FocusPosition; } const XMVECTOR& GetUpDirection() const { return m_CameraData.UpDirection; } const XMVECTOR& GetForward() const { return m_CameraData.Forward; } float GetPitch() const { return m_CameraData.Pitch; } float GetYaw() const { return m_CameraData.Yaw; } float GetZoomDistance() const { return m_CameraData.ZoomDistance; } const std::string& GetName() const { return m_Name; } private: void Update(); private: static constexpr float KPitchLimit{ XM_PIDIV2 - 0.01f }; private: std::string m_Name{}; SCameraData m_CameraData{}; };
true
1c0d4d93daa08704ad0209470f61e3a1022638ee
C++
aambbroo/MathRebus_
/MathRebus_.cpp
UTF-8
11,570
2.765625
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <ctype.h> #include <time.h> typedef struct accord { char Char; short Num; bool Use; }; struct accord Local_Accord[10]; int Nums[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; char Letters[26] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; char First_Item[11], Second_Item[11], Third_Item[11], Fourth_Item[11], Fifth_Item[11], Sixth_Item[11], Seventh_Item[11], Amount_Item[11]; short Border = 0;// short Term_Nums = 2; //слагаемые short Letter_Max_Nums = 1; //максимальное количество цифр - то есть длина item //bool Check1 = false, Check2, Check3, Check4, Check5, Check6, Check7, Check8, Check9, Check0, Check_All_Nums; bool Check[10], Check_All_Nums; unsigned long long Items[8]; //Items[0] == First_Item etc... clock_t start, start_bruteforce, end; void Print_Time() { end = clock(); int msec, msec_bruteforce; msec = (end - start) * 1000 / CLOCKS_PER_SEC; msec_bruteforce = (end - start_bruteforce) * 1000 / CLOCKS_PER_SEC; printf("\n\nAll time is %d seconds %d milliseconds.", msec / 1000, msec % 1000); printf("\n\nBruteforce time is %d seconds %d milliseconds.", msec_bruteforce / 1000, msec_bruteforce % 1000); } void Print_Result(); /*Проверка на нахождения в слагаемом или сумме*/ inline bool Letter_Check(char check) { for (int i = 0; i < 26; i++) { if (Letters[i] == check) return true; } //printf("Use not big latin letter!\n"); return false; } /*Инициализация значений логическх переменных*/ inline void Term_Init(void) { for (short i = 0; i < 10; i++) Check[i] = false; Check_All_Nums = false; for (short i = 0; i < 8; i++) Items[i] = 0; } /*Получаем указатель на соответсвующую переменную: слагаемое 1 - 7 или сумма*/ inline char* Choice(short i) { if (i == 1) return First_Item; else if (i == 2) return Second_Item; else if (i == 3) return Third_Item; else if (i == 4) return Fourth_Item; else if (i == 5) return Fifth_Item; else if (i == 6) return Sixth_Item; else if (i == 7) return Seventh_Item; else if (i == 8) return Amount_Item; } /*Разделяем входную строку на слагаемые и сумму*/ inline void Make_Items(char String[102]) { char b = '\0', bb = '\n'; char c; char* Word = NULL; short i; short offset = 0; short word = 0; bool No_Word = false; for (i = 0; i < 102; i++) { c = String[i]; if (c == b || c == bb) break; //должна идти проверка полученного выражения или вызов в другом месте данной проверки if (Letter_Check(c)) No_Word = false; else No_Word = true; if (!No_Word) { if (i == 0 && word == 0 && offset == 0) { word++; Word = Choice(word); Word[offset] = c; offset++; } else { Word[offset] = c; offset++; } } else { if (c == ' ' && (String[i + 1] == '+' || String[i + 1] == '=') && String[i + 2] == ' ') { i++; i++; Term_Nums = word; word++; if (String[i - 1] == '=') word = 8; Word = Choice(word); if (offset > Letter_Max_Nums) Letter_Max_Nums = offset; offset = 0; } } } } /*Проверка на простые ошибки*/ inline void Errors_Check() { printf("First item is %s.\n", First_Item); printf("Second item is %s.\n", Second_Item); printf("Third item is %s.\n", Third_Item); printf("Fourth item is %s.\n", Fourth_Item); printf("Fifth item is %s.\n", Fifth_Item); printf("Sixth item is %s.\n", Sixth_Item); printf("Seventh item is %s.\n", Seventh_Item); printf("Amount item is %s.\n", Amount_Item); if (Term_Nums < 2 || Term_Nums>7) printf("There are some problems with Term_Nums, it is %d.\n", Term_Nums); if (Letter_Max_Nums < 1 || Letter_Max_Nums>10) printf("There are some problems with Letter_Max_Nums, it is %d.\n", Letter_Max_Nums); } /*Занесение значение в Local_Accord*/ inline short Accord_Check(char c) { for (short i = 0; i < 10; i++) if (c == Local_Accord[i].Char) return Local_Accord[i].Num; return -1; } inline void Form_Accord_Struct() { char* Item = NULL; char letter; for (short i = 1; i <= Term_Nums; i++) { Item = Choice(i); for (short j = 0; j < strlen(Item); j++) { letter = Item[j]; short offset = Accord_Check(letter); if (offset == -1) { for (offset = 0; offset < 10; offset++) { if (!isalpha(Local_Accord[offset].Char)) { Local_Accord[offset].Char = letter; Local_Accord[offset].Use = true; offset = 10; } } } } } Item = Choice(8); for (short j = 0; j < strlen(Item); j++) { letter = Item[j]; short offset = Accord_Check(letter); if (offset == -1) { for (offset = 0; offset < 10; offset++) { if (!isalpha(Local_Accord[offset].Char)) { Local_Accord[offset].Char = letter; Local_Accord[offset].Use = true; offset = 10; } } } } } inline short Num_Return(char c) { for (short i = 0; i < 10; i++) { if (c == Local_Accord[i].Char) return Local_Accord[i].Num; } return -1; } inline void Make_Case() { char* Item = NULL; char c; unsigned long long m = 1; for (short i = 1; i <= Term_Nums; i++) { Item = Choice(i); m = 1; for (short j = strlen(Item) - 1; j >= 0; j--) {// c = Item[j]; short k = Num_Return(c); if (k == -1) { printf("\nThere is some problem\n"); return; } if (j == 0 && k == 0 && strlen(Item) > 1) { //printf("\n0 in start of item\n"); Border = -1; return; } Items[i - 1] += m * k; m *= 10; } } Item = Choice(8); m = 1; for (short j = strlen(Item) - 1; j >= 0; j--) {// c = Item[j]; short k = Num_Return(c); if (k == -1) { printf("\nThere is some problem\n"); return; } if (j == 0 && k == 0 && strlen(Item) > 1) { //printf("\n0 in start of item\n"); Border = -1; return; } Items[7] += m * k; m *= 10; } Border = 0; } /*Проверка решения*/ inline bool Try() { Make_Case(); if (Border != -1) if (Items[0] + Items[1] + Items[2] + Items[3] + Items[4] + Items[5] + Items[6] == Items[7]) return true; for (short i = 0; i < 8; i++) Items[i] = 0; return false; } inline bool Check_() { char* Item = NULL; char c; short s = 0; for (short i = 1; i <= Term_Nums; i++) { Item = Choice(i); c = Item[strlen(Item) - 1]; s += Num_Return(c); } Item = Choice(8); c = Item[strlen(Item) - 1]; if (s % 10 == Num_Return(c)) return true; else return false; } /*Подбор*/ void Bruteforce() { for (short i = 0; i < 10; i++) { short offset = 9; Local_Accord[offset].Num = Nums[i]; for (short j = 0; j < 10; j++) { if ((Local_Accord[offset].Use) && (j == i)) continue; offset = 8; Local_Accord[offset].Num = Nums[j]; for (short k = 0; k < 10; k++) { if ((Local_Accord[offset].Use) && (k == j || k == i)) continue; offset = 7; Local_Accord[offset].Num = Nums[k]; for (short l = 0; l < 10; l++) { if ((Local_Accord[offset].Use) && (l == k || l == j || l == i)) continue; offset = 6; Local_Accord[offset].Num = Nums[l]; for (short p = 0; p < 10; p++) { if ((Local_Accord[offset].Use) && (p == l || p == k || p == j || p == i)) continue; offset = 5; Local_Accord[offset].Num = Nums[p]; for (short o = 0; o < 10; o++) { if ((Local_Accord[offset].Use) && (o == p || o == l || o == k || o == j || o == i)) continue; offset = 4; Local_Accord[offset].Num = Nums[o]; for (short u = 0; u < 10; u++) { if ((Local_Accord[offset].Use) && (u == o || u == p || u == l || u == k || u == j || u == i)) continue; offset = 3; Local_Accord[offset].Num = Nums[u]; for (short y = 0; y < 10; y++) { if ((Local_Accord[offset].Use) && (y == u || y == o || y == p || y == l || y == k || y == j || y == i)) continue; offset = 2; Local_Accord[offset].Num = Nums[y]; for (short t = 0; t < 10; t++) { if ((Local_Accord[offset].Use) && (t == y || t == u || t == o || t == p || t == l || t == k || t == j || t == i)) continue; offset = 1; Local_Accord[offset].Num = Nums[t]; for (short x = 0; x < 10; x++) { if ((Local_Accord[offset].Use) && (x == t || x == y || x == u || x == o || x == p || x == l || x == k || x == j || x == i)) continue; offset = 0; Local_Accord[offset].Num = Nums[x]; if (!Check_()) continue; if (Try()) return; //Print_Result(); } } } } } } } } } } } void Print_Result() { if (Border == -1) return; printf("\n\n"); for (short i = 0; i < 8; i++) { if (1) { if (i == 7) printf(" = "); else if (i > 0) printf(" + "); printf("%lld", Items[i]); } } } int main() { printf("Enter string:\n"); char S[102]; int i = -1; char c = ' '; while (c != '\0' && c != '\n') { scanf("%c", &c); S[++i] = c; } start = clock(); Make_Items(S); Errors_Check(); Form_Accord_Struct(); start_bruteforce = clock(); Bruteforce(); Print_Time(); Print_Result(); return 0; }
true
5f5ba987df297fefa3b0cda9966231847bea2f1b
C++
logicaltrojan/Algorithm
/Algorithm/search/prime_1963.cpp
UTF-8
1,170
2.921875
3
[]
no_license
#include <iostream> #include <cstring> #include <queue> #include <string> #include <algorithm> #include <cstdio> using namespace std; int prime[10005]; int check[10005]; bool visited[10005]; int change(int n, int i, int j ){ if(i == 0 && j == 0) return -1; string temp = to_string(n); temp[i] = '0'+j; return stoi(temp); } void mach(int x, int ans){ queue <int> q; int temp; q.push(x); visited[x] = true; check[x] = 0; while(!q.empty()){ int now = q.front(); q.pop(); for(int i = 0; i<=3 ; i++ ){ for(int j = 0 ; j <= 9 ; j++){ temp = change(now,i,j); if(temp > 0 && prime[temp] == 0) if(visited[temp] == false){ q.push(temp); check[temp] = check[now]+1; visited[temp] = true; } } } } } int main(){ for(int i = 2; i <= 10000; i++){ if(prime[i] == 0) for(int j = i*i ;j<= 10000; j+= i) prime[j] = -1; } int tc; cin >> tc; int x; int y; while(tc--){ memset(visited, false, sizeof(visited)); memset(check, 0, sizeof(check)); scanf("%d %d", &x, &y); mach(x, y); if(visited[y] == false ) cout<< "Impossible" <<endl; else cout << check[y]<<endl; } }
true
7a9933cad1b878743af83353d2d1402d45d03a9f
C++
PacktPublishing/CPP-Game-Development-Cookbook
/Chapter4/Source/Recipe2/Source.cpp
UTF-8
602
3.546875
4
[ "MIT" ]
permissive
#include <iostream> #include <conio.h> using namespace std; bool Linear_Search(int list[], int size, int key) { // Basic sequential search bool found = false; int i; for (i = 0; i < size; i++) { if (key == list[i]) found = true; break; } return found; } bool Binary_Search(int *list, int size, int key) { // Binary search bool found = false; int low = 0, high = size - 1; while (high >= low) { int mid = (low + high) / 2; if (key < list[mid]) high = mid - 1; else if (key > list[mid]) low = mid + 1; else { found = true; break; } } return found; }
true
36642f776984efd9f7b2dd068965efe9ae16cc4a
C++
shablov/OrderBook
/src/orderbook/benchmark/ChangeOrderElementBenchmark.cpp
UTF-8
7,072
3.125
3
[]
no_license
#include <random> #include <iostream> #include "benchmark/benchmark.h" #include "orderbook/OrderBooks.h" template <typename OrderBookT> static OrderBookT createBook(uint64_t startPrice, uint64_t stepPrice, double delimeter, uint64_t bookSize) { OrderBookT book; uint64_t price = startPrice; uint64_t quantity = 1; uint64_t stepQuantity = 1; for (size_t i = 0; i < bookSize; ++i) { book.add({static_cast<double>(price) / delimeter, static_cast<double>(quantity), order::Side::BID}); book.add({static_cast<double>(price) / delimeter, static_cast<double>(quantity), order::Side::ASK}); price += stepPrice; quantity += stepQuantity; } return book; } template <typename OrderBookT> static void changeTopTenPercentPrices(benchmark::State& state) { uint64_t startPrice = 10; uint64_t stepPrice = 1; double delimeter = 10.; auto bookSize = static_cast<uint64_t>(state.range(0)); auto book = createBook<OrderBookT>(startPrice, stepPrice, delimeter, bookSize); auto topTenPercentEndPrice = startPrice + (bookSize / 10) * stepPrice; auto price = startPrice; for (auto _ : state) { book.change({static_cast<double>(price) / delimeter, 1., order::Side::BID}); book.change({static_cast<double>(price) / delimeter, 1., order::Side::ASK}); price += stepPrice; if (price >= topTenPercentEndPrice) { price = startPrice; } } state.SetItemsProcessed(static_cast<int64_t>(state.iterations() * 2)); } template <typename OrderBookT> static void changeAfterTenPercentPrices(benchmark::State& state) { uint64_t startPrice = 10; uint64_t stepPrice = 1; double delimeter = 10.; auto bookSize = static_cast<uint64_t>(state.range(0)); auto book = createBook<OrderBookT>(startPrice, stepPrice, delimeter, bookSize); auto endPrice = startPrice + bookSize * stepPrice; auto topTenPercentEndPrice = startPrice + (bookSize / 10) * stepPrice; auto price = topTenPercentEndPrice; for (auto _ : state) { book.change({static_cast<double>(price) / delimeter, 1., order::Side::BID}); book.change({static_cast<double>(price) / delimeter, 1., order::Side::ASK}); price += stepPrice; if (price >= endPrice) { price = topTenPercentEndPrice; } } state.SetItemsProcessed(static_cast<int64_t>(state.iterations() * 2)); } template <typename OrderBookT> static void changeProdLikeStatePrices(benchmark::State& state) { uint64_t startPrice = 10; uint64_t stepPrice = 1; double delimeter = 10.; auto bookSize = static_cast<uint64_t>(state.range(0)); auto book = createBook<OrderBookT>(startPrice, stepPrice, delimeter, bookSize); auto endPrice = startPrice + bookSize * stepPrice; auto topTenPercentEndPrice = startPrice + (bookSize / 10) * stepPrice; // 80% of the time, generate a random number for first 10% values // 20% of the time, generate a random number for last 90% values std::random_device rd; std::mt19937 gen(rd()); std::vector<double> i{ static_cast<double>(startPrice) / delimeter, static_cast<double>(topTenPercentEndPrice) / delimeter, static_cast<double>(topTenPercentEndPrice) / delimeter, static_cast<double>(endPrice) / delimeter}; std::vector<double> w{80, 0, 20}; std::piecewise_constant_distribution<> d(i.begin(), i.end(), w.begin()); for (auto _ : state) { book.change({static_cast<uint64_t>(d(gen) * delimeter) / delimeter, 1., order::Side::BID}); book.change({static_cast<uint64_t>(d(gen) * delimeter) / delimeter, 1., order::Side::ASK}); } state.SetItemsProcessed(static_cast<int64_t>(state.iterations() * 2)); } BENCHMARK_TEMPLATE(changeTopTenPercentPrices, order::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV2_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV2_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV3::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV3_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderV3_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeTopTenPercentPrices, orderEmpty::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, order::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV2_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV2_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV3::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV3_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderV3_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeAfterTenPercentPrices, orderEmpty::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, order::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV2_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV2_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV3::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV3_1::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderV3_2::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize"); BENCHMARK_TEMPLATE(changeProdLikeStatePrices, orderEmpty::Book) ->RangeMultiplier(16) ->Range(1 << 8, 1 << 16) ->ArgName("BookSize");
true
d60734591fe329fe49d2e05ab88a2a1cd9c00a4b
C++
katherine-yuan/Assignment-2
/Assignment 2/Cylinder.h
UTF-8
878
2.640625
3
[]
no_license
// Group 80 // Rebecca Schacht z5115440 2018/08/31 #ifndef MTRN2500_CYLINDER_H #define MTRN2500_CYLINDER_H #include "Shape.hpp" // Global variables to allow cylinder shape to form #define STACKS 1 // The number of subdivisions along the z axis #define SLICES 1000 // The number of subdivisions around the z axis class Cylinder : public Shape { public: Cylinder(); // Default constructor Cylinder(double radius_, double innerRadius_, double length_); ~Cylinder(); // Default destructor // Getter Functions double getLength(); double getRadius(); double getInRadius(); // Setter Functions void setLength(double length_); void setRadius(double radius_); void setInRadius(double innerRadius_); // Draw Function void draw(); protected: double radius; double innerRadius; double length; }; #endif // for MTRN2500_CYLINDER_H
true
381cc5aaef9a410c7c84be0a48a8d88b5aa491d3
C++
HekpoMaH/Olimpiads
/grupa A/olimpiada/ob6tinski/2012/NOI_1_2012_A/poker/author/poker_PF.cpp
UTF-8
882
3.046875
3
[]
no_license
#include <iostream> using namespace std; int main() {int a,b,c,d,e,t; cin>>a>>b>>c>>d>>e; if (a>b){t=a;a=b;b=t;} if (a>c){t=a;a=c;c=t;} if (a>d){t=a;a=d;d=t;} if (a>e){t=a;a=e;e=t;} if (b>c){t=b;b=c;c=t;} if (b>d){t=b;b=d;d=t;} if (b>e){t=b;b=e;e=t;} if (c>d){t=c;c=d;d=t;} if (c>e){t=c;c=e;e=t;} if (d>e){t=d;d=e;e=t;} if (b==a+1 && c==b+1 && d==c+1 && e==d+1) {cout<<"Straight\n";return 0;} t=0; if (a==b) t++; t*=2; if (b==c) t++; t*=2; if (c==d) t++; t*=2; if (d==e) t++; switch (t) {case 0:{cout<<"Nothing\n";break;} case 15:{cout<<"Impossible\n";break;} case 1:case 2:case 4:case 8:{cout<<"One Pair\n";break;} case 7:case 14:{cout<<"Four of a Kind\n";break;} case 3:case 6:case 12:{cout<<"Three of a Kind\n";break;} case 11:case 13:{cout<<"Full House\n";break;} default:cout<<"Two Pairs\n"; } return 0; }
true
f36790bd258a92a66d1e0d88bf8101e7ec6d111b
C++
MilWolf/OpenGL_SDL_Essai
/src/Camera.cpp
ISO-8859-1
3,896
3
3
[]
no_license
#include "Camera.h" Camera::Camera(): phi(0.0), theta(0.0), orientation(), axeVertical(0, 0, 1), deplacementLateral(), position(), pointCible() { } Camera::Camera(vec3 position, vec3 pointCible, vec3 axeVertical) : phi(0.0), theta(0.0), orientation(), axeVertical(axeVertical),deplacementLateral(), position(position), pointCible(pointCible) { setPointcible(pointCible); } void Camera::orienter(int xRel, int yRel) { // Modification des angles phi += -yRel * 0.8; theta += -xRel * 0.8; if(phi > 89.0) { phi = 89.0; } else if(phi < -89.0) { phi = -89.0; } float phiRadian = phi * M_PI / 180; float thetaRadian = theta * M_PI / 180; if(axeVertical.x == 1.0) { // Calcul des coordonnes sphriques orientation.x = sin(phiRadian); orientation.y = cos(phiRadian) * cos(thetaRadian); orientation.z = cos(phiRadian) * sin(thetaRadian); } // Si c'est l'axe Y else if(axeVertical.y == 1.0) { // Calcul des coordonnes sphriques orientation.x = cos(phiRadian) * sin(thetaRadian); orientation.y = sin(phiRadian); orientation.z = cos(phiRadian) * cos(thetaRadian); } // Sinon c'est l'axe Z else { // Calcul des coordonnes sphriques orientation.x = cos(phiRadian) * cos(thetaRadian); orientation.y = cos(phiRadian) * sin(thetaRadian); orientation.z = sin(phiRadian); } deplacementLateral = cross(axeVertical, orientation); deplacementLateral = normalize(deplacementLateral); // Calcul du point cibl pour OpenGL pointCible = position + orientation; } void Camera::deplacer(Input const &input, int fps) { float coeffVitesse=15.0f; if(input.mouvementSouris()) { orienter(input.getXRel(), input.getYRel()); } if(input.getTouche(SDL_SCANCODE_LSHIFT)) { coeffVitesse=25.0f; } if(input.getTouche(SDL_SCANCODE_W)) { position = position + orientation * (coeffVitesse/fps); pointCible = position + orientation; } if(input.getTouche(SDL_SCANCODE_S)) { position = position - orientation * (coeffVitesse/fps); pointCible = position + orientation; } if(input.getTouche(SDL_SCANCODE_A)) { position = position + deplacementLateral * (coeffVitesse/fps); pointCible = position + orientation; } if(input.getTouche(SDL_SCANCODE_D)) { position = position - deplacementLateral * (coeffVitesse/fps); pointCible = position + orientation; } } void Camera::lookAt(mat4 &modelview) { // Actualisation de la vue dans la matrice modelview = glm::lookAt(position, pointCible, axeVertical); } void Camera::setPointcible(glm::vec3 pointCible) { // Calcul du vecteur orientation orientation = pointCible - position; orientation = normalize(orientation); // Si l'axe vertical est l'axe X if(axeVertical.x == 1.0) { // Calcul des angles phi = asin(orientation.x); theta = acos(orientation.y / cos(phi)); if(orientation.y < 0) theta *= -1; } // Si c'est l'axe Y else if(axeVertical.y == 1.0) { // Calcul des angles phi = asin(orientation.y); theta = acos(orientation.z / cos(phi)); if(orientation.z < 0) theta *= -1; } // Sinon c'est l'axe Z else { // Calcul des angles phi = asin(orientation.x); theta = acos(orientation.z / cos(phi)); if(orientation.z < 0) theta *= -1; } // Conversion en degrs phi = phi * 180 / M_PI; theta = theta * 180 / M_PI; } Camera::~Camera() { } vec3 Camera::getPosition() { return this->position; } vec3 Camera::getPointCible() { return this->pointCible; } vec3 Camera::getAxeVertical() { return this->axeVertical; } vec3 Camera::getOrientation() { return this->orientation; } float Camera::getPhi() { return this->phi; } float Camera::getTheta() { return this->theta; }
true
0ee4afdc15b94ee7840b1fe5060d8e91a055374b
C++
everfor/Frankenstein
/Core/Physics/physics_engine.h
UTF-8
863
2.875
3
[ "Apache-2.0" ]
permissive
#pragma once #include "object.h" #include "physics_object.h" #include <vector> #include <glm/glm.hpp> class PhysicsEngine { public: PhysicsEngine(bool if_enable_gravity = false); virtual ~PhysicsEngine() {}; void addObject(PhysicsObject* obj) { objects.push_back(obj); }; void update(float delta); void switchGravity(bool new_switch); bool gravityEnabled() { return enableGravity; }; void setGravitationalAcc(glm::vec3& new_acc); glm::vec3& getGravitationalAcc() { return gravitationalAcc; }; private: // Velocity simulation void simulate(float delta); // Collision Detection void collide(float delta); std::vector<PhysicsObject*> objects; bool enableGravity; glm::vec3 gravitationalAcc; // Stored gravitational acceleration, just in case the user calls setter when gravity is disabled glm::vec3 storedGravitationalAcc; };
true
ef6baf5b8c2d4ca3d946faada51aba71c6a7a904
C++
karagog/gutil
/src/core/utils/circularint.h
UTF-8
3,217
3.296875
3
[ "Apache-2.0" ]
permissive
/*Copyright 2012-2015 George Karagoulis Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.*/ #ifndef GUTIL_CIRCULARINT_H #define GUTIL_CIRCULARINT_H #include <gutil/globals.h> NAMESPACE_GUTIL; /** Provides an integer that rolls over a max and min value. The integer has a defined range with minimum and maximum values. If you increment (or decrement) past these limits, the integer automatically "rolls over" to the opposite boundary. For example, if the range of the CircularInt is [0,5] and the integer's value is currently 5, by incrementing this number the next value will be 0. \note The size of this object is 12 bytes, as compared to a normal integer's 4 bytes. */ class CircularInt { GINT32 m_value; GINT32 m_min, m_max; public: /** Creates a new CircularInt with the given min and max values. \note Nothing prevents you from setting nonsensical values. */ CircularInt(GINT32 min, GINT32 max, GINT32 starting_val) { Reset(min, max, starting_val); } /** Resets the bounds and the value on the fly. \note Nothing prevents you from setting nonsensical values. */ void Reset(GINT32 min, GINT32 max, GINT32 start_val){ m_value = start_val; m_min = min; m_max = max; } /** Returns the minimum value of the integer. */ GINT32 MinimumValue() const{ return m_min; } /** Returns the maximum value of the integer. */ GINT32 MaximumValue() const{ return m_max; } /** Increments the value and rolls it over if greater than the max. */ void Increment(){ if(++m_value > m_max) m_value = m_min; } /** Decrements the value and rolls it over if less than the min. */ void Decrement(){ if(--m_value < m_min) m_value = m_max; } /** Prefix increment. */ GINT32 operator ++(){ Increment(); return m_value; } /** Postfix increment. */ GINT32 operator ++(int){ GINT32 ret(m_value); Increment(); return ret; } /** Prefix decrement. */ GINT32 operator --(){ Decrement(); return m_value; } /** Postfix decrement. */ GINT32 operator --(int){ GINT32 ret(m_value); Decrement(); return ret; } /** Increments the specified number of times. */ GINT32 operator += (GUINT32 n){ G_LOOP( n ){ Increment(); } return m_value; } /** Decrements the specified number of times. */ GINT32 operator -= (GUINT32 n){ G_LOOP( n ){ Decrement(); } return m_value; } /** Casts us as an integer. */ operator GINT32 () const{ return m_value; } }; END_NAMESPACE_GUTIL; #endif // GUTIL_CIRCULARINT_H
true
15228c993270070eee760ad6311cb5d98496e859
C++
glenco/SLsimLib
/TreeCode_link/peak_refinement.cpp
UTF-8
5,129
2.625
3
[ "MIT" ]
permissive
/* * peak_refinement.c * * Created on: Apr 8, 2011 * Author: bmetcalf * * Written for project with S.Hilbert for adaptive ray tracing through the Millennium II simulation. * * Uses a defection solver provided by the user. Adaptively finds regions with high kappa and refines * them to higher resolution */ #include "slsimlib.h" using namespace std; namespace ImageFinding{ /** Finding * * \brief Refines the grid based on the convergence so that high density regions have high resolution. * * No source is used in this process. The code acts as if all the mass is in SIS halos iteratively increasing the * resolution and kappa threshhold until the desired resolution is found. * */ short find_peaks( LensHndl lens /// Lens model ,GridHndl grid /// Grid to be refined. It must be initialized. ,PosType rEinsteinMin /// the Einstein radius of the smallest lens that should be resolved, sets resolution target ,PosType kappa_max /// highest kappa to be refined to, 1 or 2 is probably good enough ,std::vector<ImageInfo> &imageinfo /// the image ,int *Nimages /// number of peaks ){ //Point **i_points,*s_points,*dummy; PosType res_target = 0,threshold; long Nnewpoints = 0,Ntemp; unsigned long i; //ImageInfo *imageinfo = new ImageInfo; Kist<Point> * newpointskist = new Kist<Point>; if(grid->getInitRange() != grid->getNumberOfPoints() ){ *grid = grid->ReInitialize(lens); } // Add all points to imageinfo //MoveToTopList(grid->i_tree->pointlist); PointList::iterator i_tree_pl_current; i_tree_pl_current.current = (grid->i_tree->pointlist.Top()); do{ imageinfo[0].imagekist->InsertAfterCurrent(*i_tree_pl_current); }while(--i_tree_pl_current); // increase threshold while increasing angular resolution for(threshold = rEinsteinMin*(grid->getInitNgrid())/(grid->getInitRange())/4 ; threshold <= kappa_max ; threshold *= 3){ cout << "threshold " << threshold << endl; res_target = rEinsteinMin/threshold/2; // keeps resolution below size of smallest lens imageinfo[0].gridrange[2] = 1.0e99; imageinfo[0].gridrange[0] = imageinfo[0].gridrange[1] = 0.0; // take out points that are no longer above threshold imageinfo[0].imagekist->MoveToTop(); Ntemp = imageinfo[0].imagekist->Nunits(); for(i=0;i<Ntemp;++i){ if(imageinfo[0].imagekist->getCurrent()->kappa() < threshold){ imageinfo[0].imagekist->getCurrent()->in_image = NO; if(imageinfo[0].imagekist->AtTop()){ imageinfo[0].imagekist->TakeOutCurrent(); }else{ imageinfo[0].imagekist->TakeOutCurrent(); imageinfo[0].imagekist->Down(); } }else{ imageinfo[0].imagekist->getCurrent()->in_image = YES; if(imageinfo[0].imagekist->getCurrent()->gridsize > imageinfo[0].gridrange[1]) imageinfo[0].gridrange[1] = imageinfo[0].imagekist->getCurrent()->gridsize; if(imageinfo[0].imagekist->getCurrent()->gridsize < imageinfo[0].gridrange[2]) imageinfo[0].gridrange[2] = imageinfo[0].imagekist->getCurrent()->gridsize; //printf(" gridsize = %e\n",getCurrentKist(imageinfo[0].imagekist)->gridsize); imageinfo[0].imagekist->Down(); } } assert(imageinfo[0].imagekist->Nunits() <= Ntemp); //printf("restarget = %e gridrange[2] = %e gridrange[1] = %e\n",res_target,imageinfo[0].gridrange[2],imageinfo[0].gridrange[1]); //printf("first pass in image %li\n",imageinfo[0].imagekist->Nunits); bool touches_edge; findborders4(grid->i_tree,imageinfo.data(),touches_edge); //printf("restarget = %e gridrange[2] = %e gridrange[1] = %e\n",res_target,imageinfo[0].gridrange[2],imageinfo[0].gridrange[1]); Nnewpoints = IF_routines::refine_grid_kist(lens,grid,imageinfo.data(),1,res_target,2,newpointskist); while(newpointskist->Nunits() > 0){ // add new points that are above the threshold to image while(newpointskist->Nunits() > 0){ if(newpointskist->getCurrent()->kappa() > threshold){ imageinfo[0].imagekist->InsertAfterCurrent(newpointskist->TakeOutCurrent()); imageinfo[0].imagekist->Down(); imageinfo[0].imagekist->getCurrent()->in_image = YES; if(imageinfo[0].imagekist->getCurrent()->gridsize > imageinfo[0].gridrange[1]) imageinfo[0].gridrange[1] = imageinfo[0].imagekist->getCurrent()->gridsize; if(imageinfo[0].imagekist->getCurrent()->gridsize < imageinfo[0].gridrange[2]) imageinfo[0].gridrange[2] = imageinfo[0].imagekist->getCurrent()->gridsize; }else{ newpointskist->TakeOutCurrent()->in_image = NO; } } // find borders findborders4(grid->i_tree,imageinfo.data(),touches_edge); // refine all image points and outer border Nnewpoints = IF_routines::refine_grid_kist(lens,grid,imageinfo.data(),1,res_target,2,newpointskist); //printf("Nnewpoints = %li\n",Nnewpoints); } } divide_images_kist(grid->i_tree,imageinfo,Nimages); // need some way of returning all the points // free memory in grids, trees and images //free(imageinfo->points); //delete imageinfo; delete newpointskist; return 1; } } // end of namespace ImageFinding
true
e5c5d34251516dd09dcba9029c2393bcde769d71
C++
wtfenfenmiao/buptProgram
/prog_2/pagerank带调试信息.cpp
GB18030
5,285
2.609375
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #define _WINSOCK_DEPRECATED_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<unistd.h> //ֻһУlinuxwindows #include<string.h> #include<vector> #include<unordered_map> #include<iostream> #include<fstream> #include<algorithm> #include<string> using namespace std; //Gm:ÿһһϵ3УDZ3URL˭ int topNum = 10; double alpha = 0.85; double epsilon = 1.0; int dimen = 0; unordered_map<int, string> BianHaothis; class TriSparMatrix { public: unordered_map<int,unordered_map<int,double> > values; //Ԫֵ,ǰУ unordered_map<int, double> columnNum; //ÿһзԪܺ double others; }; void getvalues(TriSparMatrix* A,char* urltxt) { int N = 0; ifstream urlread; urlread.open(urltxt); if (!urlread.is_open()) { cout << "no such url file!" << endl; return; } string line; string url; int column = 0; int row = 0; while (getline(urlread, line)) { if (strlen(line.c_str())==0) //֮ǰwindowsֱline==""Dzеģlinux¾ͲУû취жϿǿյģֻȻ֪Ϊɶ { break; } cout<<line<<endl; char *ptemp; ptemp = strtok((char*)(line.c_str()), " "); url=(string)ptemp; cout<<url<<endl; ptemp = strtok(NULL, " "); column = stoi(ptemp)-1; cout<<"columnt:"<<column<<endl; BianHaothis.insert(make_pair(column, url)); //getline(urlread, line); ++N; cout<<N<<endl; } //getline(urlread, line); column=0; getchar(); while (getline(urlread, line)) { cout<<line<<endl; cout<<"there"<<endl; getchar(); char *ptemp; ptemp = strtok((char*)(line.c_str()), " "); column = stoi(ptemp)-1; //֮ǰŴ1ʼģǴ0ʼģܲ... ptemp = strtok(NULL, " "); row = stoi(ptemp)-1; cout<<"column:"<<column<<endl; cout<<"row:"<<row<<endl; getchar(); if (column > dimen) { dimen = column; } if (row > dimen) { dimen = row; } A->values[column][row] = 1; unordered_map<int, double>::iterator itvalues; itvalues = A->columnNum.find(column); if (itvalues != A->columnNum.end()) { itvalues->second += 1.0; } else A->columnNum[column] = 1.0; } unordered_map<int, double>::iterator iterColumnNum; for (iterColumnNum=A->columnNum.begin();iterColumnNum!=A->columnNum.end();++iterColumnNum) { unordered_map<int, double>::iterator iterValues; int columnIndex = iterColumnNum->first; double columnSum = iterColumnNum->second; for (iterValues = A->values[columnIndex].begin(); iterValues != A->values[columnIndex].end(); ++iterValues) { iterValues->second = alpha / columnSum + (1 - alpha) / N; } } A->others = (1 - alpha) / N; urlread.close(); } void matrixMulti(TriSparMatrix* A, double* pr, double* R) { double Rtemp=0.0; for (int j = 0; j < dimen; ++j) { Rtemp += pr[j]; } Rtemp *= A->others; for (int i = 0; i < dimen; ++i) { R[i]=Rtemp; unordered_map<int, double>::iterator iterLie; double PRtemp = 0.0; for (iterLie = A->values[i].begin(); iterLie != A->values[i].end(); ++iterLie) { R[i] += pr[iterLie->first] * iterLie->second; PRtemp += pr[iterLie->first]; } R[i] -= PRtemp*A->others; } } double diff(double* R, double* pr, int dimen) { double re = 0; for (int i = 0; i < dimen; i++) { re += abs(R[i] - pr[i]); } cout << re << endl; return re; } double* pagerank(char* urltxt) { TriSparMatrix* A = new TriSparMatrix; getvalues(A,urltxt); double* pr = new double[dimen]; for (int i = 0; i < dimen; i++) { pr[i] = 1.0; } double* R = new double[dimen]; memset(R, 0, dimen * sizeof(double)); matrixMulti(A, pr, R); while (1) { if (diff(R, pr, dimen) < epsilon) break; for (int i = 0; i < dimen; i++) { pr[i] = R[i]; } memset(R, 0, dimen * sizeof(double)); matrixMulti(A, pr, R); } delete[] pr; pr = NULL; delete A; A = NULL; return R; } int main(int argc, char* argv[]) { const char* urltxt = argv[1]; //Ҫconst char*дĶᱨ const char* top10txt = argv[2]; double* prvalue; prvalue = pagerank((char*)urltxt); //ӣpageranknewRֱdelete prvalueͿͷ FILE* topfile = fopen(top10txt, "a+"); int* top = new int[topNum]; top[0] = 1; for (int i = 2; i <= topNum; ++i) //ǰʮӸߵ { int j; for (j = 0; j<i - 1; ++j) { if (prvalue[i]>prvalue[top[j]]) { break; } } for (int k = i - 1; k >= j + 1; --k) { top[k] = top[k - 1]; } top[j] = i; } for (int i = topNum + 1; i<dimen; ++i) { int j; for (j = 0; j<topNum; ++j) { if (prvalue[i]>prvalue[top[j]]) { break; } } for (int k = topNum - 1; k >= j + 1; --k) { top[k] = top[k - 1]; } top[j] = i; } string url; for (int l = 0; l<topNum; ++l) { int Bian = top[l]; url = BianHaothis[Bian]; fprintf(topfile, "%s %.15lf\n", url.c_str(), prvalue[Bian]); } fclose(topfile); delete[] prvalue; prvalue = NULL; delete[] top; top = NULL; return 0; }
true
12eb258d496a07164036be5fc304ac5c8cae4c82
C++
jordancde/seamail
/src/models/thread.h
UTF-8
591
2.640625
3
[ "MIT" ]
permissive
#ifndef _THREAD_H_ #define _THREAD_H_ #include <iostream> #include <string> #include <vector> #include <nlohmann/json.hpp> #include "../utility/serializable.h" class Thread : public Serializable { void serialize(nlohmann::json&) const override; void deserialize(const nlohmann::json&) override; std::string genRandomId(); public: std::string id; std::string title; std::vector<std::string> emailIds; explicit Thread(std::string title, std::vector<std::string> emailIds = {}); Thread() = default; bool operator==(const Thread&) const; }; #endif
true
936885ed7f831dca3cfd00e1447cc6595f9204b0
C++
ShengKeTan/DalyPractice
/Log/util/list/list.cpp
UTF-8
600
3.21875
3
[]
no_license
#include <iostream> #include "list.h" int main(int argc, char** argv) { list<int> mlist; mlist.push_back(1); mlist.push_back(2); mlist.push_back(3); std::cout << mlist.size() << std::endl; for (list<int>::iterator it = mlist.begin(); it != mlist.end(); ++it) { std::cout << (*it) << std::endl; } mlist.clear(); std::cout << mlist.size() << std::endl; mlist.push_back(1); mlist.push_back(2); mlist.push_back(3); std::cout << mlist.size() << std::endl; for (list<int>::iterator it = mlist.begin(); it != mlist.end(); ++it) { std::cout << (*it) << std::endl; } return 0; }
true
673198935bcc4ddf685f21ea659d8774100c5c65
C++
dillonfeinman/Longest-Common-Subsequence
/program2.cpp
UTF-8
3,141
3.8125
4
[]
no_license
#include <string> #include <fstream> #include <cstdlib> #include <iostream> #include <chrono> using namespace std; //max takes in two ints, a and b, and returns the greater of the two by simple >= comparison //a and b are assumed to be integers. int max(int a, int b){ if(a >= b){ return a; //a is bigger } else { return b; //b is bigger } } //recLCS takes in the two strings to compare, linex and liney, and the lengths of those strings, //m and n, respectively. It finds the length of longest common subsequnce recursively. int recLCS(string linex, string liney, int m, int n){ if(m==0 || n==0){ //base case, end of string return 0; //not a match } else if(linex[m-1] == liney[n-1]){ //chars match return 1 + recLCS(linex, liney, m-1, n-1); //add 1 and recurse with the previous char } else { //chars dont match return max(recLCS(linex, liney, m-1, n), recLCS(linex, liney, m, n-1)); //take the larger after recursing } //with (m-1,n) and (m,n-1) } //(linex[m-2], liney[n-2]) int main(int argc, char * argv[]){ //main requires 3 args (other than ./program) inlcuding 2 input file names and fstream file; //the output file name. if(argc != 4){ cerr << "Need 3 args! <filex.txt>, <filey.txt>, <output.txt>" << endl; //if not 3 args, exit. exit(1); } string filex = argv[1]; //first input file name string filey = argv[2]; //second input file name string out = argv[3]; //output file name file.open(filex); //getting ready to read filex string linex; //chars from filex if(file.is_open()){ getline(file, linex); //linex = input from filex } else { cerr << "Could not open file: " << filex << "." << endl; cerr << "Exiting." <<endl; exit(1); } int m = linex.length(); //m = length of string from filex file.close(); file.open(filey); string liney; //chars from filey if(file.is_open()){ getline(file, liney);//liney = input from filey } else { cerr << "Could not open file: " << filey << "." << endl; cerr << "Exiting." <<endl; exit(1); } int n = liney.length(); //n = length of string from filey file.close(); auto start = chrono::high_resolution_clock::now(); //record start time int lcs_len = recLCS(linex, liney, m, n); //length of longest common subsequnce by calling recLCS with the //strings and length of strings auto end = chrono::high_resolution_clock::now(); //record end time auto time = chrono::duration_cast<chrono::microseconds>(end-start); //get time of algorithm in microseconds ofstream outfile; //ofstream to write to file outfile.open(out); //open out, name of output file if(outfile.is_open()){ outfile << lcs_len << endl; //write length to outfile outfile << time.count() << " microseconds."; //write elapsed time } else { cerr << "Could not write to file: " << out << "." << endl; cerr << "Exiting." <<endl; exit(1); } outfile.close(); //close file }
true
12230499bcc56a434b4a960b57cd280fc304f3f6
C++
eerick1997/Club
/Ejercicios/LeetCode/Permutations.cpp
UTF-8
1,006
3.296875
3
[]
no_license
//Problem link: https://leetcode.com/problems/permutations/ //Time complexity O(n * n!) //Space complexity O( n * n! ) class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector< vector<int> > ans; vector< bool > visited( nums.size(), false ); vector< int > current; makePermutation( nums, visited, current, ans ); return ans; } void makePermutation( vector<int> &nums, vector<bool> &visited, vector< int > current, vector< vector< int > > &ans){ if( current.size() == nums.size() ){ ans.push_back( current ); return; } for( int i = 0; i < nums.size(); i++ ){ if( !visited[ i ] ){ visited[ i ] = true; current.push_back( nums[ i ] ); makePermutation( nums, visited, current, ans ); current.pop_back(); visited[ i ] = false; } } } };
true
e0b34374dca72b090b04fd138da44d3f40514082
C++
ginkgo/AMP-LockFreeSkipList
/test/inarow/RecursiveSearch/InARowGameTask.h
UTF-8
5,180
2.59375
3
[]
no_license
/* * InARow.h * * Created on: 22.09.2011 * Author: Daniel Cederman * License: Boost Software License 1.0 (BSL1.0) */ #ifndef INAROWGAMETASK_H_ #define INAROWGAMETASK_H_ #include <pheet/pheet.h> #include "../../../pheet/misc/types.h" #include "../../../pheet/misc/atomics.h" #include <string.h> #include <stdlib.h> #include <iostream> #include <exception> #include "InARowTask.h" using namespace std; namespace pheet { template <class Pheet> class InARowGameTask : public Pheet::Task { unsigned int boardWidth; unsigned int boardHeight; unsigned int rowLength; unsigned int lookAhead; unsigned int* scenario; bool playScenario; char* currBoard; public: InARowGameTask(unsigned int width, unsigned int height, unsigned int rowlength, unsigned int lookahead, unsigned int* scenario) : boardWidth(width), boardHeight(height), rowLength(rowlength), lookAhead(lookahead), scenario(scenario),playScenario(scenario!=0) { currBoard = new char[boardHeight*boardWidth]; memset(currBoard,Empty,boardHeight*boardWidth); } ~InARowGameTask() {} virtual void operator()() { unsigned int turn = 0; unsigned int scenarioPtr = 0; unsigned int gameMoves[100]; while(true) { unsigned int playerMove; if(!playScenario) { printBoard(currBoard); while(true) { cout << "Pick a slot (1-" << boardWidth << "): "; cin >> playerMove; if(playerMove == 0) exit(0); playerMove--; if(playerMove<boardWidth) { gameMoves[turn++]=playerMove; break; } } } else playerMove = scenario[scenarioPtr++]-1; if(scenario[scenarioPtr-1]==0) { printf("Did not win :/\n"); return; } bool won = move(playerMove, Human); if(won) { if(!playScenario) { cout << "Player won!" << endl; cout << "Game: "; for(unsigned int i=0;i<turn;i++) cout << gameMoves[i]+1 << " "; cout << endl; printBoard(currBoard); } return; } unsigned int computerMove; computerMove = findBestMove(); won = move(computerMove, Computer); if(won) { if(!playScenario) { cout << "Computer won!" << endl; cout << "Game: "; for(unsigned int i=0;i<turn;i++) cout << gameMoves[i]+1 << " "; cout << endl; printBoard(currBoard); } return; } } } unsigned int getBoardWidth() { return boardWidth; } unsigned int getBoardHeight() { return boardHeight; } unsigned int getRowLength() { return rowLength; } unsigned int eval(char* board, unsigned int x, unsigned int y, bool& winner) { // TODO was unsigned and had a negative value. Check why int combos[4][2] = {{1,0},{0,1},{1,1},{1,-1}}; unsigned int val = 0; for(int i=0;i<4;i++) { unsigned int tval = connected(board,x,y,combos[i][0],combos[i][1])+connected(board,x,y,combos[i][0]*-1,combos[i][1]*-1); if(tval==getRowLength()+1) { // cout << "Winner!"; winner = true; } val = tval*tval; } return val; } unsigned int connected(char* board, int x, int y, int modx, int mody) { unsigned int ctr = 0; pheet_assert(y < getBoardHeight()); pheet_assert(x < getBoardWidth()); char type = board[y*getBoardWidth()+x]; while(x<getBoardWidth() && y<getBoardHeight() && x>=0 && y>=0) { if(board[y*getBoardWidth()+x]==type) ctr++; else break; x+=modx; y+=mody; } return ctr; } private: void printBoard(char* board) { for(unsigned int x=1;x<boardWidth+1;x++) cout << x << ""; cout << endl; for(int y=(int)boardHeight-1;y>=0;y--) { for(unsigned int x=0;x<boardWidth;x++) { if(board[y*boardWidth+x]==Empty) cout << " "; if(board[y*boardWidth+x]==Computer) cout << "X"; if(board[y*boardWidth+x]==Human) cout << "O"; } cout << endl; } } bool move(unsigned int slot, Player player) { unsigned int pos = boardHeight; for(unsigned int i=0;i<boardHeight;i++) { if(currBoard[i*boardWidth+slot]==0) { pos = i; currBoard[i*boardWidth+slot] = player; break; } } pheet_assert(pos < boardHeight); bool win=false; eval(currBoard,slot,pos,win); return win; } unsigned int findBestMove() //typename Task::TEC& tec) { int* vals = new int[boardWidth]; memset(vals,0,boardWidth*sizeof(int)); { typename Pheet::Finish f; for(unsigned int i=0;i<boardWidth;i++) if(currBoard[(getBoardHeight()-1)*getBoardWidth()+i]==0) Pheet::template spawn<InARowTask<Pheet> >(lookAhead, currBoard, i, false, &vals[i], this, 0, i==0); } unsigned int choice = 0; int cval = vals[0]; for(unsigned int i=0;i<boardWidth;i++) if(vals[i]<cval) { choice = i; cval = vals[i]; } /* cout << "Points: "; for(unsigned int i=0;i<boardWidth;i++) if(i==choice) cout << "[" << vals[i] << "]" << " "; else cout << vals[i] << " "; cout << endl;*/ delete vals; return choice; } }; } #endif /* INAROWGAMETASK_H_ */
true
551e7b4bedf04ba9a55f65c6063c1005b10da4b7
C++
Arduini-Projects/cpCMRI
/src/cpCMRI.cpp
UTF-8
20,586
2.625
3
[]
no_license
#include <Arduino.h> #include <cpCMRI.h> #include <I2Cexpander.h> #define CMRI_DEBUG_PROTOCOL 0x0001 #define CMRI_DEBUG_SERIAL 0x0002 #define CMRI_DEBUG_IOMAP 0x0004 #define CMRI_DEBUG_IO 0x0008 #define CMRI_DEBUG_TIMING 0x0010 #define DEBUG_INFO 0x0100 #define DEBUG_FREERAM 0x0200 #define DEBUG_IOMAP 0x0400 #define DEBUG_IOMAP_ADD 0x0800 #define DEBUG_IOMAP_INIT 0x1000 #define DEBUG_IOMAP_PACK 0x2000 #define DEBUG_IOMAP_UNPACK 0x4000 #define DEBUG_IOENTRY 0x8000 // Enable Serial.print() calls for debugging #define CMRI_DEBUG (0) // #define CMRI_DEBUG (CMRI_DEBUG_PROTOCOL | CMRI_DEBUG_SERIAL | CMRI_DEBUG_IOMAP | CMRI_DEBUG_IO) // #define CMRI_DEBUG (CMRI_DEBUG_PROTOCOL | CMRI_DEBUG_IO) // #define CMRI_DEBUG CMRI_DEBUG_IOMAP // #define CMRI_DEBUG CMRI_DEBUG_TIMING | CMRI_DEBUG_IOMAP #define TRACE(level) if (CMRI_DEBUG & (level)) // { then execute block } /** * Read a byte from the serial stream, if available. Timeout if no activity * * At 8N1, 9600 baud, the bit time is about 104 microseconds which makes each * character sent take 1.04 milliseconds. At 19200, bit time is 52.083 microseconds * and 0.5 milliseconds per character. * * Timeout is set to 1x character timings @9600 baud, or 2 @ 19,200. * If there isn't another byte waiting to be read by that time, get back to * the sketch's main loop() * * @return (0..0xFF valid incoming byte, -1 on timeout) */ int CMRI_Node::readByte(void) { elapsedMillis timeout = 0; while (true) { if (_serial.available() > 0) { return byte(_serial.read()); } if (timeout > 3) { TRACE(CMRI_DEBUG_SERIAL) { Serial.println("CMRI_Node::readByte() TIMEOUT"); } return -1; // after 10 character times @ 9600 baud (10mS), give up } } } /** * return ERROR on timeout without cluttering code */ #define GET_BYTE_WITH_ERRORCHECK() { c = CMRI_Node::readByte(); if (c == -1) { return CMRI_Packet::ERROR; }} /** * Read and parse a correctly structured CMRI packet from the serial link * while rejecting incorrectly formed and incomplete packets. * * Return NOOP if no input is available or if a read() timeout happens. * Processing overhead is less than 1mS for a full packet on an ESP32, 1uS for "nothing available"... * * @param packet Caller provides the packet instance to store the incoming data * @return The Type of the packet (I, P, T, R, N(oop), E(rror) or U(nknown)) */ CMRI_Packet::Type CMRI_Node::protocol_handler(void) { unsigned long time_begin, time_end; TRACE(CMRI_DEBUG_TIMING) { time_begin = micros(); } if (_serial.available() <= 0) { // fast return if nothing to read() TRACE(CMRI_DEBUG_TIMING) { time_end = micros(); if ((time_end - time_begin)> 25) { Serial.print("Microseconds for nothing: "); Serial.println(time_end - time_begin); } } return CMRI_Packet::NOOP; } TRACE(CMRI_DEBUG_TIMING) { Serial.print("Serial queue:"); Serial.println(_serial.available()); } int idx = 0; // incoming packet's BODY length int loops = 0; // in SYNC state, count of sequential "SYN" chars seen int c; // protocol byte being processed CMRI_Node::ParseState state = CMRI_Node::SYNC; while (1) { switch (state) { case CMRI_Node::SYNC: // Sync with packet byte stream... TRACE(CMRI_DEBUG_PROTOCOL) { Serial.println("state: CMRI_Node::SYNC"); } loops = 0; do { GET_BYTE_WITH_ERRORCHECK() loops++; // count the SYNs we commit... } while (c == CMRI_Packet::SYN); if (loops < 3) { break; // (we fell out early if we didn't see two SYNs and a presumed STX...) } state = CMRI_Node::HEADER; break; case CMRI_Node::HEADER: // ==== Packet Header ==== TRACE(CMRI_DEBUG_PROTOCOL) { Serial.println("state: CMRI_Node::HEADER"); } if (c != CMRI_Packet::STX) { // .. followed by a STX TRACE(CMRI_DEBUG_PROTOCOL) { Serial.print("ERROR: parse packet HEADER, no STX, instead got "); Serial.print(b2s(c)); } return CMRI_Packet::ERROR; // ERROR } GET_BYTE_WITH_ERRORCHECK() CMRI_Node::_paddr = byte(c) - 'A'; GET_BYTE_WITH_ERRORCHECK() CMRI_Node::_ptype = byte(c); state = CMRI_Node::BODY; break; case CMRI_Node::BODY: // ==== Packet Body ==== TRACE(CMRI_DEBUG_PROTOCOL) { Serial.println("state: CMRI_Node::BODY"); } GET_BYTE_WITH_ERRORCHECK() if (c == CMRI_Packet::ETX) { // ETX terminates a packet _packet.set(CMRI_Node::_ptype, CMRI_Node::_paddr, idx, CMRI_Node::_pbody); switch (_packet.type()) { case CMRI_Packet::INIT: if (_packet.address() == _address) { // to me if (initHandler) { (*initHandler)(_packet); } else { byte *body = _packet.content(); set_tx_delay(body[1] * 256 + body[2]); } } break; case CMRI_Packet::POLL: if (_packet.address() == _address) { // to me if (inputHandler) { _packet.clear(); _packet.set_type(CMRI_Packet::RX); _packet.set_address(_address); _packet.set_length( (get_num_input_bits() + 7) / 8); // in bytes, rounded up (*inputHandler)(_packet); // fill in _body... } else { _packet.set(CMRI_Packet::RX, _address, 0, NULL); // fake placeholder... } send_packet(_packet); } break; case CMRI_Packet::TX: if (_packet.address() == _address) { // to me if (outputHandler) { (*outputHandler)(_packet); } } break; case CMRI_Packet::ERROR: if (errorHandler) { (*errorHandler)(_packet); } break; default: break; } TRACE(CMRI_DEBUG_TIMING) { time_end = micros(); Serial.print("Microseconds for complete packet: "); Serial.println(time_end - time_begin); } return _packet.type(); } if (idx >= CMRI_Packet::BODY_MAX) { TRACE(CMRI_DEBUG_PROTOCOL) { Serial.print("ERROR: parse packet BODY overflow: more than "); Serial.print(CMRI_Packet::BODY_MAX); Serial.println(" bytes without ETX"); } return CMRI_Packet::ERROR; // ERROR if buffer would overflow } if (c == CMRI_Packet::DLE) { // DLE escapes the next character GET_BYTE_WITH_ERRORCHECK() } CMRI_Node::_pbody[idx++] = byte(c); // record the contents break; } } } /** * Convenience function to send out an already-constructed packet * @param packet The packet to send */ void CMRI_Node::send_packet(CMRI_Packet &packet) { if (_tx_delay) { delayMicroseconds(_tx_delay * 10); } _serial.write(CMRI_Packet::SYN); _serial.write(CMRI_Packet::SYN); _serial.write(CMRI_Packet::STX); _serial.write('A' + packet.address()); _serial.write(packet.type()); byte *body = packet.content(); for (int idy = 0; idy < packet.length(); idy++) { _serial.write(body[idy]); } _serial.write(CMRI_Packet::ETX); } /** * Simple linked list of IO entities */ ioEntry::ioEntry(int iodir, void *device, int iopin, unsigned int attributes) : iodirection(iodir), expander((I2Cexpander *)device), pin(iopin), flags(attributes), next(NULL) { // ensure pin is always in range for mem variables if (pin < 0) pin = 0; if ((flags & MEM1) && (pin > 0)) pin = 0; if ((flags & MEM8) && (pin > 7)) pin = 7; if ((flags & MEM16) && (pin > 15)) pin = 15; } bool ioEntry::read(void) { bool val; if (expander == BUILTIN) { val = digitalRead(pin); } else if (flags & (MEM1 | MEM8 | MEM16)) { val = bitRead(*(bool *)(expander), pin); } else { val = bitRead(expander->current(), pin); } TRACE(DEBUG_IOMAP_UNPACK) { Serial.print("ioEntry::write("); Serial.print(val, DEC); } if (flags & INVERT) { val = !val; TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" INVERT=> "); Serial.print(val, DEC); } } TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(")"); } return val; } void ioEntry::write(bool val) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.print("ioEntry::write("); Serial.print(val, DEC); } if (flags & INVERT) { val = !val; TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" INVERT=> "); Serial.print(val, DEC); } } if (expander == BUILTIN) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" BUILTIN "); } digitalWrite(pin, val); } else if (flags & (MEM1 | MEM8 | MEM16)) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" MEMORY "); } bitWrite(*(bool *)(expander), pin, val); } else { // I2Cexpander TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" I2C "); } bitWrite(expander->next, pin, val); } TRACE(DEBUG_IOMAP_UNPACK) { Serial.println(")"); } } /** * */ ioMap::ioMap(MapType t) { _type = t; _root = NULL; _tail = NULL; TRACE(DEBUG_IOMAP) { Serial.print("ioMap::ioMap("); Serial.print( (t == HOST_CENTRIC) ? "HOST_CENTRIC" : (t == NODE_CENTRIC) ? "NODE_CENTRIC" : "UNKNOWN"); Serial.println(");"); } } ioMap *ioMap::add(int iodir, void *device, int pin, unsigned int attributes) { TRACE(DEBUG_IOMAP_ADD) { Serial.print("ioMap::add("); Serial.print( (iodir == INPUT) ? "INPUT" : (iodir == OUTPUT) ? "OUTPUT" : "UNKNOWN"); Serial.print(", "); if (device == NULL) { Serial.print("BUILTIN"); } else { Serial.print("<"); Serial.print((unsigned int)device, HEX); Serial.print(">"); } Serial.print(", "); Serial.print(pin, DEC); Serial.print(", flags:0x"); Serial.print((unsigned int)attributes, HEX); Serial.print(": "); const char *sep = ""; if (attributes & INPUT_PULLUP) { Serial.print(sep); Serial.print("INPUT_PULLUP"); sep="|"; } if (attributes & OUTPUT_HIGH) { Serial.print(sep); Serial.print("OUTPUT_HIGH"); sep="|"; } if (attributes & OUTPUT_LOW) { Serial.print(sep); Serial.print("OUTPUT_LOW"); sep="|"; } if (attributes & MEM1) { Serial.print(sep); Serial.print("MEM1"); sep="|"; } if (attributes & MEM8) { Serial.print(sep); Serial.print("MEM8"); sep="|"; } if (attributes & MEM16) { Serial.print(sep); Serial.print("MEM16"); sep="|"; } if (attributes & INVERT) { Serial.print(sep); Serial.print("INVERT"); sep="|"; } Serial.print("); "); Serial.print(" _root = <"); Serial.print((unsigned int)_root, HEX); Serial.print("> "); Serial.print(" _tail = <"); Serial.print((unsigned int)_tail, HEX); Serial.println(">"); } ioEntry *io = new ioEntry(iodir, device, pin, attributes); if (_root == NULL) { _root = io; _tail = _root; } else { _tail->next = io; _tail = io; } return this; } ioMap *ioMap::initialize(void) { TRACE(DEBUG_IOMAP_INIT) { Serial.println("ioMap::initialize()"); } int count = 0; byte initial[MAX_EXPANDERS]; auto getExpanderNum = [&](I2Cexpander *e) { for (int idx = 0; idx < numSeen; idx++) { if (seen[idx] == e) return idx; } // didn't find it... if (numSeen < MAX_EXPANDERS) { seen[numSeen] = e; config[numSeen] = 0; initial[numSeen] = 0; return numSeen++; } return -1; }; // collect all I2C expanders and their bit directions... for (ioEntry *io = _root; io; io = io->next) { TRACE(DEBUG_IOMAP_INIT) { Serial.print(" ioEntry:"); if (count < 10) Serial.print(" "); Serial.print(count++, DEC); Serial.print(" "); } bool val = 0; if (io->flags | OUTPUT_HIGH) { val = 1; } else if (io->flags | OUTPUT_LOW) { val = 0; } if (io->flags | INVERT) { val = !val; } bool conf = ((io->iodirection == INPUT) ? 1 : 0); byte attr = INPUT; if (io->flags | INPUT_PULLUP) { attr = INPUT_PULLUP; } TRACE(DEBUG_IOMAP_INIT) { Serial.print("pin: "); if (io->pin < 10) Serial.print(" "); Serial.print(io->pin); Serial.print(", direction: "); Serial.print((io->iodirection == INPUT) ? "IN " : "OUT"); Serial.print(", initialize: "); Serial.print((io->flags & OUTPUT_HIGH) ? 1 : 0); Serial.print(", invert: "); Serial.print((io->flags & INVERT) ? 1 : 0); } if (io->expander == BUILTIN) { TRACE(DEBUG_IOMAP_INIT) { Serial.println(" Builtin"); } if (io->iodirection == INPUT) { pinMode(io->pin, attr); } else if (io->iodirection == OUTPUT) { pinMode(io->pin, OUTPUT); digitalWrite(io->pin, val); } } else if (io->flags & (MEM1 | MEM8 | MEM16)) { TRACE(DEBUG_IOMAP_INIT) { Serial.print(" Memory: "); if (io->flags & MEM1) { Serial.print("MEM1"); } if (io->flags & MEM8) { Serial.print("MEM8"); } if (io->flags & MEM16) { Serial.print("MEM16");} Serial.println(); } if (io->iodirection == OUTPUT) { io->write(val); } } else { // I2C expanders... int idx = getExpanderNum(io->expander); TRACE(DEBUG_IOMAP_INIT) { Serial.print(" Expander: "); Serial.print(idx); if (idx < 0) Serial.print(" ERROR"); Serial.println(); } if (idx < 0) return this; // error config[idx] |= conf << io->pin; initial[idx] |= val << io->pin; } } // After loop completes, initialize all the expanders... for (int idx = 0; idx < numSeen; idx++) { TRACE(DEBUG_IOMAP_INIT) { Serial.print(" Writing Expander: "); Serial.print(idx); Serial.print(": config=0x"); Serial.print(config[idx], HEX); Serial.print(", write=0x"); Serial.print(initial[idx], HEX); Serial.println(); } seen[idx]->init(config[idx]); seen[idx]->write(initial[idx]); } } void ioMap::unpack(byte *OB, int maxlen) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.print("ioMap::unpack("); Serial.print("OB["); const char *sep = "0x"; for (int x = 0; x < maxlen; x++) { Serial.print(sep); Serial.print(OB[x], HEX); sep = ", 0x"; } Serial.print("]:"); Serial.print(maxlen, DEC); Serial.print(") "); Serial.print(_type == HOST_CENTRIC ? "HOST_CENTRIC" :_type == NODE_CENTRIC ? "NODE_CENTRIC" : "UNKNOWN" ); Serial.println(""); } // walk the bits in OB and the ordered list in _root, assigning output bits to each output... ioEntry *io = _root; int count = 0; for (int _bit = 0; (_bit < (maxlen * 8)) && io; _bit++) { // two alternatives: // 1) HOST_CENTRIC: each bit in OB is an output bit, find each ioEntry of type OUTPUT and assign, or // 2) NODE_CENTRIC: each bit in OB is associated with an ioEntry, but only type==OUTPUTs get used/assigned. // the MapType _type determines which heurstic to use if (_type == HOST_CENTRIC) { while (io && (io->iodirection != OUTPUT)) { count++; io=io->next; } if (io == NULL) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.println(" Break: out of ioEntries"); } break; // at end of ioEntries... } } // else SPARSE if (io && (io->iodirection == OUTPUT)) { bool val = bitRead(OB[_bit / 8], (_bit % 8)); TRACE(DEBUG_IOMAP_UNPACK) { Serial.print(" ioEntry:"); Serial.print(count); Serial.print(" bit: "); Serial.print(_bit, DEC); Serial.print(", val:"); Serial.print(val); Serial.print(" "); } io->write(val); } if (io == NULL) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.println(" Break: out of ioEntries"); } break; // at end of ioEntries... } count++; io=io->next; } // after loop completes, write out all the expanders... for (int idx = 0; idx < numSeen; idx++) { seen[idx]->write(); } } void ioMap::pack(byte *IB, int maxlen) { TRACE(DEBUG_IOMAP_PACK) { Serial.print("ioMap::pack("); Serial.print(_type == HOST_CENTRIC ? "HOST_CENTRIC" :_type == NODE_CENTRIC ? "NODE_CENTRIC" : "UNKNOWN" ); Serial.println(")"); } // pre-read all the expanders... for (int idx = 0; idx < numSeen; idx++) { seen[idx]->read(); } // walk the bits in IB and the ordered list in _root, reading bits from each input... ioEntry *io = _root; int count = 0; for (int _bit = 0; (_bit < (maxlen * 8)) && io; _bit++) { // two alternatives: // 1) HOST_CENTRIC: each bit in IB is an input bit, find each ioEntry of type INPUT and read it, or // 2) NODE_CENTRIC: each bit in IB is associated with an ioEntry, but only type==INPUTs get used/read. // the MapType _type determines which heurstic to use if (_type == HOST_CENTRIC) { while (io && (io->iodirection != INPUT)) { count++; io=io->next; } if (io == NULL) { TRACE(DEBUG_IOMAP_PACK) { Serial.println(" Break: out of ioEntries"); } break; // at end of ioEntries... } } // else SPARSE // read the bits if (io && (io->iodirection == INPUT)) { bool val = io->read(); TRACE(DEBUG_IOMAP_PACK) { Serial.print(" ioEntry:"); Serial.print(count); Serial.print(" bit: "); Serial.print(_bit, DEC); Serial.print(", val:"); Serial.println(val); } bitWrite(IB[_bit / 8], (_bit % 8), val); } count++; if (io == NULL) { TRACE(DEBUG_IOMAP_UNPACK) { Serial.println(" Break: out of ioEntries"); } break; // at end of ioEntries... } io=io->next; } } int ioMap::numInputs() { ioEntry *io = _root; int count = 0; if (_type == NODE_CENTRIC) { // count = number of i/o bits total, ignoring I or O direction... for (io = _root; io; io = io->next) { count++; } return count; } else { for (io = _root; io; io = io->next) { if (io->iodirection == INPUT) { count++; } } return count; } } int ioMap::numOutputs() { ioEntry *io = _root; int count = 0; if (_type == NODE_CENTRIC) { // count = number of i/o bits total, ignoring I or O direction... for (io = _root; io; io = io->next) { count++; } return count; } else { for (io = _root; io; io = io->next) { if (io->iodirection == OUTPUT) { count++; } } return count; } }
true
d97bdefa0f077dff64607712a86721ad5cc2c6a4
C++
whuang8/Data-Structures-Algorithms
/C++/DataStructures/Heap.cpp
UTF-8
1,956
3.515625
4
[]
no_license
#include "Heap.h" #include <stdlib.h> #include <stdio.h> #include <string.h> Heap::Heap(int maxSize){ _maxSize = maxSize; _heap = new int[_maxSize]; _last = 0; } Heap::~Heap(){ delete [] _heap; } int parent(int node){ return (node-1)/2; } int left(int node){ return node*2 + 1; } int right(int node){ return node * 2 + 2; } bool Heap::insert(int data){ if (_last == _maxSize) { //heap is full return false; } //insert node at end of heap _heap[_last] = data; _last++; //sort heap int child = _last - 1; int p = parent(child); while(child > 0){ if (_heap[child] < _heap[p]){ //swap int temp = _heap[child]; _heap[child] = _heap[p]; _heap[p] = temp; child = p; p = parent(child); } else{ //no swapping needed break; } } return true; } bool Heap::removeMin(int &data){ //check in heap is empty if (_last == 0){ //heap is empty return false; } //heap not empty data = _heap[0]; //replace head node with last node _heap[0] = _heap[--_last]; //sort heap int parent = 0; int l = left(parent); int r = right(parent); while(l < _last){ int minChild = l; //check if right child is less than left if (r < _last && _heap[r] < _heap[l]){ minChild = r; } if (_heap[minChild] < _heap[parent]){ //swap int temp = _heap[minChild]; _heap[minChild] = _heap[parent]; _heap[parent] = temp; parent = minChild; l = left(parent); r = right(parent); } else{ //nothing to swap break; } } return true; } // int main(int argc, char const *argv[]) // { // Heap *h = new Heap(1000); // h->insert(2); // h->insert(3); // h->insert(4); // h->insert(27); // h->insert(51); // h->insert(23); // h->insert(-94); // int data; // for (int i = 0; i < 7; ++i) // { // h->removeMin(data); // printf("%d\n",data ); // } // return 0; // }
true
c7923ceea42d8c32f683f42e1b62bc87676633cd
C++
chris-misa/StarFlow
/backend/src/kernels/old/host_timing_profiler.h
UTF-8
3,800
2.65625
3
[]
no_license
#ifndef STARFLOW_KERNELS_HOST_PROFILER #define STARFLOW_KERNELS_HOST_PROFILER #include <iostream> #include <fstream> #include <chrono> #include <vector> using namespace std; using namespace std::chrono; #include "flat_hash_map.hpp" // Builds a timing profile of each monitored source address. // (example 1) #define DUMP 1 #define STATS 1 #define BENCHMARK 1 #define BENCHMARK_CT 1000000 namespace starflow { namespace kernels { template<typename T> class HostProfiler : public raft::kernel { public: const char * outFileName; uint32_t profileDuration = 0; high_resolution_clock::time_point last, cur, start, end; ska::flat_hash_map<uint32_t, std::vector<uint32_t>> hostTimes; std::vector<uint32_t> blankValue; uint32_t startTs = 0; uint32_t endTs = 0; uint64_t counter=0; // input: profile dump file name, duration of profile (ms). explicit HostProfiler(const char *of, uint32_t profDur) : raft::kernel() { outFileName = of; profileDuration = profDur; last = high_resolution_clock::now(); start = high_resolution_clock::now(); input.template add_port<T>("in"); } // Dump profile. Format: host ip, # arrivals, timestamps (all uint_64) void dumpProfile(){ std::cout << "dumping profile to: " << outFileName << std::endl; ofstream o; o.open(outFileName, ios::binary); uint64_t tsesWritten = 0; for (auto kv : hostTimes){ uint32_t hostIp = kv.first; uint32_t tsCt = uint32_t(kv.second.size()); o.write((char *) &hostIp, sizeof(hostIp)); o.write((char *) &tsCt, sizeof(tsCt)); for (auto ts : kv.second){ o.write((char *) &ts, sizeof(ts)); tsesWritten++; } } o.close(); std::cout << "\twrote " << tsesWritten << " timestamps" << std::endl; } raft::kstatus run() override { // get a referecne to the CLFR batch object. auto &clfrVector(input["in"].template peek<T>()); // handle a batch. for (auto kv : clfrVector){ // key is src addr. uint32_t key = *((uint32_t *) &(kv.first.c_str()[4])); auto got = hostTimes.find(key); if (got == hostTimes.end()){ hostTimes[key] = blankValue; got = hostTimes.find(key); } // update profile. for (auto pfs : kv.second.packetVector){ got->second.push_back(pfs.ts); #ifdef STATS endTs = max(pfs.ts, endTs); #endif } } // handleBatch(clfrVector); input["in"].recycle(); // recycle to move to next item. // for benchmarking. #ifdef BENCHMARK counter+= clfrVector.size(); if (counter > BENCHMARK_CT){ // std::cout << "read " << counter << " CLFRs " << endl; // report throughput. cur = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>( cur - last ).count(); std::cout << std::fixed << "time to gen host profiles with " << BENCHMARK_CT << " CLFRs: " << duration <<" processing rate: " << 1000.0*(float(counter)/float(duration)) << std::endl; counter = 0; last = high_resolution_clock::now(); #ifdef STATS std::cout << "number of hosts: " << hostTimes.size() << " time interval represented: " << (endTs - startTs)/1000.0 << " (ms)" << std::endl; #endif } #endif #ifdef DUMP // Dump profile and exit (entire app for now). if ((endTs - startTs) > (profileDuration*1000)){ end = high_resolution_clock::now(); auto duration = duration_cast<milliseconds>( end - start ).count(); std::cout << "total time to get profile: " << duration << " ms" << std::endl; dumpProfile(); // return (raft::stop); exit(0); } #endif return (raft::proceed); } // void handleBatch(std::vector<T> batchVector){ // } }; } } #endif
true
3736076d600cd6b3270cb750291a2bee539103ec
C++
NSchwindt/Weather.Scroll
/WeatherTTGO-V2Web.ino
UTF-8
2,194
2.53125
3
[]
no_license
#include "WiFi.h" #include <HTTPClient.h> #include <iostream> #include <string.h> #include <SPI.h> #include "LedMatrix.h" #define NUMBER_OF_DEVICES 4 //number of led matrix connect in series #define CS_PIN 15 #define CLK_PIN 13 #define MISO_PIN 2 //we do not use this pin just fill to match constructor #define MOSI_PIN 12 LedMatrix ledMatrix = LedMatrix(NUMBER_OF_DEVICES, CLK_PIN, MISO_PIN, MOSI_PIN, CS_PIN); const char* ssid = "gotem"; const char* password = "hellothere"; String zip_code = ""; String temp = ""; String weatherText = ""; String location = ""; String finalTxt = ""; void setup() { ledMatrix.init(); ledMatrix.clear(); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); } } void loop() { if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status HTTPClient http; Serial.begin(9600); http.begin("http://dataservice.accuweather.com/currentconditions/v1/349291?apikey=##############&language=en-US&details=false"); //Specify the URL int httpCode = http.GET(); //Make the request if (httpCode > 0) { //Check for the returning code String payload = http.getString(); Serial.print(payload); weatherText = payload.substring( payload.indexOf("WeatherText")+14,payload.indexOf("WeatherIcon")-3); temp = payload.substring(payload.indexOf("\"Imperial\"")+20,payload.indexOf(",\"Unit\":\"F\"")) + " F"; location = payload.substring( payload.indexOf("/en/us")+7 , payload.indexOf("current-weather")-7); location.toUpperCase(); zip_code = payload.substring( payload.indexOf("/en/us")+16 , payload.indexOf("current-weather")-1); finalTxt = location + " " + zip_code + " " + temp + " " + weatherText + " "; } else { Serial.println("Error on HTTP request"); } http.end(); //Free the resources } ledMatrix.setText(finalTxt); for(int i=0;i<2400;i++){ ledMatrix.clear(); ledMatrix.scrollTextLeft(); ledMatrix.drawText(); ledMatrix.commit(); delay(25); } }
true
5d3f255568ff90ca4206fe9120bc20870af77136
C++
siklosid/co-cluster
/src/Reader/ReaderControl.h
UTF-8
2,147
2.828125
3
[]
no_license
/*! ReaderControl controls the Reader thread objects that reads the */ /*! different parts of the dataset. In Constructor it gets */ /*! the type of the readers, than creates them by the help of */ /*! ReaderFactory. It allows as much Reader threads to read as much */ /*! is given in parameter. */ #ifndef __READER_CONTROL_H #define __READER_CONTROL_H #include <vector> #include <string> #include "Utils/log.h" #include "Utils/Mutex.h" #include "Utils/CoClusterParams.h" #include "ReaderFactory.h" #include "ReaderBase.h" using std::vector; using std::string; class ReaderControl { public: ReaderControl(const CoClusterParams &params, vector< Data<double>* > *data_set); ~ReaderControl(); /*! Calls the Start function of all reader thread in readers_ vect */ void StartRead(); /*! Reader object calls this function in its main cycle before starts reading. */ /*! If the number of readers who are reading at the moment reaches the limit */ /*! then it stops on mutex_read_ mutex */ void CanIRead(); /*! Reader object calls this function in its main cycle after reading. */ /*! If the number of readers who are reading at the moment is just went */ /*! under the limit then it releases the mutex_read_ mutex */ void FinishedRead(); /*! Reads test data into the same dataset continuously */ void StartReadTest(); private: /*! Gets the readers string from params and returns a vector of the reader types */ void GetReaderTypes(const string &readers, vector< string > *reder_types_vect); /*! Gets the input_files string from params and returns a vector of the input_files */ void GetInputFiles(const string &input_files, vector< string > *input_files_vect); /*! Each element of the vector points to a partition of the dataset. */ DataSet *data_set_; /*! For every part of the dataset it stores a reader */ vector< ReaderBase* > readers_; /*! Counts the number of threads who are reading at the moment */ int semafor_; /*! Number of threads */ int num_threads_; Mutex mutex_semafor_; Mutex mutex_read_; ReaderFactory *reader_factory_; }; #endif // __READER_CONTROL_H
true
3293377a6490dc9d7b8aa72b348fb80b57ee5c27
C++
chiahsun/problem_solving
/Algospot/PI/solve1.cc
UTF-8
1,442
2.71875
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> const bool debug = false; const int M = 10000+5; char pi[M]; int a[M]; int get_type(int begin, int end) { bool d_same = true; int d = pi[begin+1] - pi[begin]; for (int i = begin+2; i < end; ++i) if (pi[i]-pi[i-1] != d) { d_same = false; break; } if (d_same) { if (d == 0) return 1; else if (d == 1 or d == -1) return 2; return 5; } bool iter_same = true; int i1 = pi[begin], i2 = pi[begin+1]; for (int i = begin+2; i < end; i += 2) { if (pi[i] != i1 or (i+1 < end and pi[i+1] != i2)) { iter_same = false; break; } } if (iter_same) return 4; return 10; } int main() { int nCase; scanf("%d", &nCase); while (nCase--) { scanf("%s", pi); if (debug) printf("now : %s\n", pi); int len = strlen(pi); a[2] = get_type(0, 3); a[3] = get_type(0, 4); a[4] = get_type(0, 5); for (int i = 5; i < len; ++i) { int vmin = a[i-3] + get_type(i-2, i+1); if (i >= 6) vmin = std::min(vmin, a[i-4] + get_type(i-3, i+1)); if (i >= 7) vmin = std::min(vmin, a[i-5] + get_type(i-4, i+1)); a[i] = vmin; } printf("%d\n", a[len-1]); } return 0; }
true
7cc49682a7f46f87079526ae92c35d8ec14f7281
C++
shinsumicco/pose-graph-optimization
/src/se2/problem.h
UTF-8
4,262
2.625
3
[]
no_license
#ifndef SE2_PROBLEM_H #define SE2_PROBLEM_H #include <iostream> #include <fstream> #include <string> #include <ceres/ceres.h> #include <ceres/autodiff_cost_function.h> #include "types.h" #include "error_function.h" namespace se2 { void build_problem(const constraints_t& constraints, poses_t& poses, ceres::Problem& problem) { ceres::LossFunction* loss_function = nullptr; for (const auto& constraint: constraints) { auto pose_start_itr = poses.find(constraint.id_start); if (pose_start_itr == poses.end()) { std::cerr << "Pose ID: " << constraint.id_start << " not found." << std::endl; continue; } auto pose_end_itr = poses.find(constraint.id_end); if (pose_end_itr == poses.end()) { std::cerr << "Pose ID: " << constraint.id_end << " not found." << std::endl; continue; } // 情報行列をコレスキー分解してマハラノビス距離の計算に用いる // (対角行列を想定しているので,情報行列の対角成分の平方根を格納する) // (マハラノビス距離の定義を参照) std::array<double, 3> decomposed_information; for (unsigned int i = 0; i < 3; ++i) { decomposed_information.at(i) = sqrt(constraint.information.at(i)); } // AutoDiffCostFunctionでコスト関数とヤコビアンを構築 // テンプレート引数 // 残差パラメータ: 3個 // 第1引数: 1個 (絶対位置A x) // 第2引数: 1個 (絶対位置A y) // 第3引数: 1個 (絶対位置A theta) // 第4引数: 1個 (絶対位置B x) // 第5引数: 1個 (絶対位置B y) // 第6引数: 1個 (絶対位置B theta) // // 相対姿勢[x, y, theta]とコレスキー分解した情報行列の対角成分decomposed_informationを設定する // (相対姿勢は局所的には信頼できるものとする) ceres::CostFunction* cost_function = new ceres::AutoDiffCostFunction<error_function, 3, 1, 1, 1, 1, 1, 1>( new error_function(constraint.x, constraint.y, constraint.theta, decomposed_information)); // 残差項を設定 // cost_function構築時に入れた相対姿勢に対して,その相対姿勢の両端のノードの絶対姿勢を入れて絶対姿勢の誤差を計算させる problem.AddResidualBlock(cost_function, loss_function, &(pose_start_itr->second.x), &(pose_start_itr->second.y), &(pose_start_itr->second.theta), &(pose_end_itr->second.x), &(pose_end_itr->second.y), &(pose_end_itr->second.theta)); } auto pose_start_itr = poses.begin(); if (pose_start_itr == poses.end()) { std::cerr << "There are no poses" << std::endl; exit(EXIT_FAILURE); } // 経路の始点を最適化時に定数とする problem.SetParameterBlockConstant(&(pose_start_itr->second.x)); problem.SetParameterBlockConstant(&(pose_start_itr->second.y)); problem.SetParameterBlockConstant(&(pose_start_itr->second.theta)); } bool solve_problem(ceres::Problem& problem) { ceres::Solver::Options options; options.max_num_iterations = 100; options.linear_solver_type = ceres::SPARSE_NORMAL_CHOLESKY; ceres::Solver::Summary summary; ceres::Solve(options, &problem, &summary); std::cout << summary.FullReport() << std::endl; return summary.IsSolutionUsable(); } void output_poses(const std::string& filename, const poses_t& poses) { std::fstream outfile; outfile.open(filename.c_str(), std::istream::out); if (!outfile) { std::cerr << "Couldn't open a file: " << filename << std::endl; exit(EXIT_FAILURE); } for (const auto& pair : poses) { outfile << pair.first << "," << pair.second.x << "," << pair.second.y << "," << pair.second.theta << std::endl; } } } // namespace se2 #endif // SE2_PROBLEM_H
true
fa4aa51bd1aba9b0bbb9486f31b1663fc35f57ff
C++
hwl19951007/Cpp_Primer_Exercise
/chapter5/5.21.cpp
UTF-8
966
3.34375
3
[]
no_license
#include <iostream> #include <vector> #include <string> using namespace std; int main() { const vector<string> scores = { "F", "D", "C", "B", "A", "A++" }; string lettergrade; int grade; while (cin >> grade) { if (grade < 60) lettergrade = scores[0]; else lettergrade = scores[(grade - 50) / 10]; cout << lettergrade << '\n'; } }#include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> vstr; string str; string exist_str; while (cin >> str) { vstr.push_back(str); if (exist_str == str) break; exist_str = str; } str = vstr[0]; auto beg = vstr.begin() + 1; bool tag = false; while (beg != vstr.end()){ if (!isupper(str[0])) { //不管首字母是否大写,迭代器必须继续指向下一个元素。 str = *beg; ++beg; continue; } if (str == *beg) { tag = true; break; } str = *beg; ++beg; } if (tag) cout << str; else cout << "no repeat word."; }
true
343eeb6207df36f62e558833d9fc2db45650202e
C++
Gofrettin/simple-aes-cpp
/test/test_pkcs7_padding.cpp
UTF-8
1,946
2.921875
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include <cstring> #include "../src/Pkcs7Padding.h" #include "../src/AES.h" #include "../src/debug.h" TEST(PKCS7PaddingTest, PadIncompleteBlock){ uint8_t block [] = { 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00 }; size_t dataLength = 12; uint8_t expectedPadding [] = { 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x04, 0x04, 0x04, 0x04 }; PKCS7Padding::AddBlockPadding(block, dataLength, AES_BLOCK_SIZE); ASSERT_EQ(0, memcmp(block, expectedPadding, AES_BLOCK_SIZE)); } TEST(PKCS7PaddingTest, PadCompleteBlock){ uint8_t block [] = { 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x00, 0x00, 0x00 }; size_t dataLength = 0; uint8_t expectedPadding [] = { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 }; PKCS7Padding::AddBlockPadding(block, dataLength, AES_BLOCK_SIZE); ASSERT_EQ(0, memcmp(block, expectedPadding, AES_BLOCK_SIZE)); } TEST(PKCS7PaddingTest, RemovePaddingIncompleteBlock){ uint8_t paddedBlock [] = { 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x00, 0x01, 0x02, 0x04, 0x04, 0x04, 0x04, 0x04 }; size_t blockLength = AES_BLOCK_SIZE; PKCS7Padding::RemoveBlockPadding(paddedBlock, &blockLength); ASSERT_EQ(12, blockLength); } TEST(PKCS7PaddingTest, RemovePaddingCompleteBlock){ uint8_t paddedBlock [] = { 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10 }; size_t blockLength = AES_BLOCK_SIZE; PKCS7Padding::RemoveBlockPadding(paddedBlock, &blockLength); ASSERT_EQ(0, blockLength); }
true
117ab2aea632ecf2a4ac3a940a74efc21fd24a2a
C++
sehe/ideone_slurp
/output/9MmE9.cpp
UTF-8
2,004
2.734375
3
[]
no_license
// error: OK // langId: 44 // langName: C++11 // langVersion: gcc-4.8.1 // time: 0 // date: 2012-09-10 15:39:48 // status: 0 // result: 0 // memory: 0 // signal: 0 // public: false // ------------------------------------------------ #include <iostream> static constexpr auto MOD = 1000000007LL; inline /*hint hint*/ long long mod(long long x) { if (x >= 0 && x < MOD) return x; x %= MOD; if (x < 0) return x + MOD; return x; } struct matrix { long long m[4][4]; static matrix multiply(const matrix &a, const matrix &b) { matrix c; for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { c.m[i][j] = 0; for (int k = 0; k < 4; k++) c.m[i][j] += a.m[i][k] * b.m[k][j]; } return c; } void normalize() { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) m[i][j] = mod(m[i][j]); } }; static matrix operator*(matrix const& a, matrix const& b) { return matrix::multiply(a,b); } template <typename T> T pow(T const&a, long long n) { if (n == 0) throw "not implemented"; if (n == 1) return a; auto b = pow(a*a, n>>1); return (n & 1)? b*a : b; } int main() { //std::cout << "pow(2, 0): " << pow(2, 0) << std::endl; std::cout << "pow(2, 1): " << pow(2ll, 1) << std::endl; std::cout << "pow(2, 2): " << pow(2ll, 2) << std::endl; std::cout << "pow(2, 3): " << pow(2ll, 3) << std::endl; std::cout << "pow(2, 4): " << pow(2ll, 4) << std::endl; std::cout << "pow(2, 5): " << pow(2ll, 5) << std::endl; std::cout << "pow(2, 10): " << pow(2ll, 10) << std::endl; std::cout << "pow(2, 16): " << pow(2ll, 16) << std::endl; std::cout << "pow(2, 32): " << pow(2ll, 32) << std::endl; matrix v = { { { 1,2,3,4}, { 2,3,4,5}, { 3,4,5,6}, { 7,8,9,0} } }; for (long i = 0; i< (1ul << 22ul); ++i) { auto e = pow(v, 16); e.normalize(); } } // ------------------------------------------------ #if 0 // stdin #endif #if 0 // stdout #endif #if 0 // stderr #endif #if 0 // cmpinfo #endif
true
91d9b67a229bf728e6f154b08bfa579bd38a4f33
C++
huskycat1202/100June
/1764.cpp
UTF-8
433
2.625
3
[]
no_license
#include<iostream> #include<string> #include<algorithm> using namespace std; int main(){ int n, m, sum=0, k=0; string N[500000], M, K[500000]; cin >> n >> m; for(int i=0; i<n; i++){ cin >> N[i]; } sort(N,N+n); for(int i=0; i<m; i++){ cin >> M; if(binary_search(N,N+n,M)){ K[k++]=M; sum++; } } sort(K, K+k); cout << sum << "\n"; for(int i=0; i<k; i++){ cout << K[i] << "\n"; } }
true
b718663e1c97e0fc9dd403e1d14f2e26ca843264
C++
jhomble/redis
/lib_acl_cpp/include/acl_cpp/redis/redis_client_pool.hpp
GB18030
1,684
2.6875
3
[]
no_license
#pragma once #include "acl_cpp/acl_cpp_define.hpp" #include "acl_cpp/connpool/connect_pool.hpp" namespace acl { /** * redis ӳ̳࣬ connect_pool connect_pool ͨõй * TCP ӳصͨ÷ * redis connection pool inherting from connect_pool, which includes * TCP connection pool methods. */ class ACL_CPP_API redis_client_pool : public connect_pool { public: /** * 캯 * constructor * @param addr {const char*} ˵ַʽip:port * the redis-server's listening address, format: ip:port * @param count {int} ӳص * the max connections for each connection pool * @param idx {size_t} ӳضڼе±λ( 0 ʼ) * the subscript of the connection pool in the connection cluster */ redis_client_pool(const char* addr, int count, size_t idx = 0); virtual ~redis_client_pool(); /** * ӳʱʱ估 IO дʱʱ() * set the connect and read/write timeout in seconds * @param conn_timeout {int} ӳʱʱ * the timeout to connect in seconds * @param rw_timeout {int} IO дʱʱ() * the timeout to read/write in seconds * @return {redis_client_pool&} */ redis_client_pool& set_timeout(int conn_timeout, int rw_timeout); protected: /** * ി麯: ô˺һµ * virtual function in class connect_pool to create a new connection * @return {connect_client*} */ virtual connect_client* create_connect(); private: int conn_timeout_; int rw_timeout_; }; } // namespace acl
true
98c122a57872c43d0929bd1c99b0b7bbd6f956d8
C++
JameyWoo/csmile
/parse.cpp
UTF-8
18,745
2.8125
3
[ "MIT" ]
permissive
#include "parse.h" #include "scan.h" ofstream out("Output-parseTree.txt", ios::out); void error() { error_cnt += 1; cout << "ErrorToken >> " << ptoken.type << ": " << ptoken.value << endl; } Token match(string expected) { Token tmp = ptoken; // cout << "ptoken.type = " << ptoken.type << " ptoken.val = " << ptoken.value << endl; // cout << "expected: " << expected << endl; // 匹配一个类型 if (ptoken.type == expected) { // cout << "match: " << ptoken.value << endl; if (ptoken.type != "EndFile") ptoken = getToken(); } else { error(); } return tmp; } TreeNode* param(TreeNode* k) { TreeNode* t = new TreeNode("Param"); TreeNode* p = NULL; TreeNode* q = NULL; if (k == NULL && ptoken.type == "void") { p = new TreeNode("void"); match("void"); } else if (k == NULL && ptoken.type == "int") { p = new TreeNode("int"); match("int"); } else if (k != NULL) { p = k; } if (p != NULL) { t->child[0] = p; if (ptoken.type == "Id") { q = new TreeNode("ParamId"); q->name = ptoken.value; q->line = ptoken.line; t->child[1] = q; t->child_cnt = 2; match("Id"); } // TODO: 处理数组传参 } return t; } TreeNode* param_list(TreeNode* k) { // TODO: 到这里暂停, 明天再写. 完善函数的操作 TreeNode* t = param(k); // 先读一个参数 TreeNode* p = t; k = NULL; while (ptoken.type == "Comma") { // 如果读到逗号, 说明还有下一个参数 match("Comma"); TreeNode* q = param(k); if (q != NULL) { if (t == NULL) { // ! 是否多余 t = p = q; } else { p->sibling = q; p = q; } } } return t; } TreeNode* params() { TreeNode* t = new TreeNode("Params"); // 根节点, 参数s TreeNode* p = NULL; if (ptoken.type == "void") { p = new TreeNode("void"); match("void"); if (ptoken.type == "RightBracket") { if (t != NULL) { t->child[0] = p; t->child_cnt = 1; } } else { t->child[0] = param_list(p); t->child_cnt = 1; } } else { t->child[0] = param_list(p); t->child_cnt = 1; } return t; } TreeNode* local_declaration() { /** * 一系列的局部声明 */ TreeNode* t = NULL; TreeNode* p = NULL; TreeNode* q = NULL; while (ptoken.type == "int") { p = new TreeNode("LocVarDecl"); // 局部变量声明, 只有int类型 TreeNode* q1 = new TreeNode("int"); p->child[0] = q1; match("int"); if (ptoken.type == "Id") { TreeNode* q2 = new TreeNode("Id"); q2->name = ptoken.value; q2->line = ptoken.line; p->child[1] = q2; match("Id"); // TODO: 添加数组 if (ptoken.type == "Semicolon") { match("Semicolon"); p->child_cnt = 2; } else if (ptoken.type == "Assign") { match("Assign"); Token tmp = match("Num"); match("Semicolon"); int val = stoi(tmp.value); q2->val = val; p->child_cnt = 2; } else { match("Semicolon"); } } if (p != NULL) { if (t == NULL) { t = q = p; } else { q->sibling = p; q = p; } } } return t; } TreeNode* selection_stmt() { TreeNode* t = new TreeNode("Selection"); match("if"); match("LeftBracket"); if (t != NULL) { t->child[0] = expression(); } match("RightBracket"); bool has_bracket = false; if (ptoken.type == "LeftBigBkt") { has_bracket = true; match("LeftBigBkt"); } t->child[1] = statement_list(); if (has_bracket) match("RightBigBkt"); if (ptoken.type == "else") { match("else"); // else 部分, 存在child[2]里 // cout << "else 的开始部分*******************" << endl; if (t != NULL) { bool has_bracket_2 = false; if (ptoken.type == "LeftBigBkt") { // cout << "else 有括号***********************" << endl; has_bracket_2 = true; match("LeftBigBkt"); } else { // cout << "else 无括号***********************" << endl; } t->child[2] = statement_list(); if (has_bracket_2) match("RightBigBkt"); } } return t; } TreeNode* iteration_stmt() { TreeNode* t = new TreeNode("Iteration"); match("while"); match("LeftBracket"); if (t != NULL) { t->child[0] = expression(); } match("RightBracket"); match("LeftBigBkt"); if (t != NULL) { t->child[1] = statement_list(); } match("RightBigBkt"); return t; } TreeNode* var() { TreeNode* t = NULL; TreeNode* p = NULL; if (ptoken.type == "Id") { p = new TreeNode("Id"); p->name = ptoken.value; p->line = ptoken.line; match("Id"); // TODO: 添加数组 t = p; // 非数组时 } return t; } TreeNode* args() { TreeNode* t = new TreeNode("Args"); TreeNode *s = NULL, *p = NULL; if (ptoken.type != "RightBracket") { s = expression(); p = s; while (ptoken.type == "Comma") { TreeNode* q; match("Comma"); q = expression(); if (q != NULL) { if (s == NULL) { s = p = q; } else { p->sibling = q; p = q; } } } } if (s != NULL) { t->child[0] = s; } return t; } TreeNode* call(TreeNode* k) { TreeNode* t = new TreeNode("Call"); if (k != NULL) { t->child[0] = k; } match("LeftBracket"); if (ptoken.type == "RightBracket") { match("RightBracket"); return t; } else if (k != NULL) { t->child[1] = args(); match("RightBracket"); } return t; } TreeNode* factor(TreeNode* k) { TreeNode* t = NULL; if (k != NULL) { if (ptoken.type == "LeftBracket" && k->nodekind != "ArrayElem") { // TODO: 数组元素 t = call(k); } else { t = k; } } else { if (ptoken.type == "LeftBracket") { match("LeftBracket"); t = expression(); match("RightBracket"); } else if (ptoken.type == "Id") { k = var(); if (ptoken.type == "LeftBracket" && k->nodekind != "ArrayElem") { t = call(k); } else { t = k; } } else if (ptoken.type == "Num") { t = new TreeNode("Const"); if ((t != NULL) && (ptoken.type == "Num")) { t->val = stoi(ptoken.value); } match("Num"); } else { ptoken = getToken(); } } return t; } TreeNode* term(TreeNode* k) { TreeNode* t = factor(k); k = NULL; while (ptoken.type == "MDOP") { TreeNode* q = new TreeNode("MDOp"); q->op = ptoken.value; q->child[0] = t; match(ptoken.type); q->child[1] = term(k); t = q; } return t; } TreeNode* additive_expression(TreeNode* k) { TreeNode* t = term(k); k = NULL; while (ptoken.type == "PMOP") { // 加减 TreeNode* q = new TreeNode("PMOp"); q->op = ptoken.value; q->child[0] = t; match("PMOP"); q->child[1] = term(k); t = q; } return t; } TreeNode* simple_expression(TreeNode* k) { // 这里会处理只有一个整数的情况 TreeNode* t = additive_expression(k); k = NULL; if (ptoken.type == "CompareOp") { // 比较 TreeNode* q = new TreeNode("CompareOp"); q->line = ptoken.line; q->op = ptoken.value; q->child[0] = t; t = q; match(ptoken.type); t->child[1] = additive_expression(k); return t; } return t; } TreeNode* expression() { // cout << "expression token: " << ptoken.type << endl; if (ptoken.type == "input") { // 如果是输入 TreeNode* input = new TreeNode("Input"); match("input"); match("LeftBracket"); match("RightBracket"); return input; } else if (ptoken.type == "output") { TreeNode* output = new TreeNode("Output"); match("output"); match("LeftBracket"); if (output != NULL) { output->child[0] = expression(); } match("RightBracket"); return output; } TreeNode* t = var(); if (t == NULL) { t = simple_expression(t); // ! 开头不是Id的情况 } else { // Id 开头 TreeNode* p = NULL; if (ptoken.type == "Assign") { p = new TreeNode("Assign"); match("Assign"); p->child[0] = t; p->child[1] = expression(); // 赋值的另一边可能是一个表达式 return p; } else { t = simple_expression(t); } } return t; } TreeNode* return_stmt() { TreeNode* t = new TreeNode("ReturnStmt"); match("return"); // cout << "exp 之前 -- 0" << endl; if (ptoken.type == "Semicolon") { match("Semicolon"); return t; } else { if (t != NULL) { // cout << "exp 之前" << endl; t->child[0] = expression(); t->child_cnt = 1; } } match("Semicolon"); return t; } TreeNode* expression_stmt() { TreeNode* t = NULL; t = expression(); match("Semicolon"); return t; } TreeNode* statement() { TreeNode* t = NULL; if (ptoken.type == "if") { t = selection_stmt(); } else if (ptoken.type == "while") { t = iteration_stmt(); } else if (ptoken.type == "return") { t = return_stmt(); } else if (ptoken.type == "Id") { t = expression_stmt(); } else if (ptoken.type == "intput" || ptoken.type == "output") { t = expression_stmt(); } return t; } TreeNode* statement_list() { /** * 一系列的语句 */ TreeNode* t = statement(); TreeNode* p = t; // 判断哪些token可以做为statement的开始 while (ptoken.type == "if" || ptoken.type == "Id" || ptoken.type == "while" || ptoken.type == "return" || ptoken.type == "semicolon" || ptoken.type == "input" || ptoken.type == "output") { TreeNode* q; // cout << "ptoken.type == " << ptoken.type << endl; q = statement(); if (q != NULL) { if (t == NULL) { t = p = q; } else { p->sibling = q; p = q; } } } return t; } // TODO: 是否要区分一下声明且赋值与普通声明 TreeNode* compound_stmt() { // * 解析函数体 TreeNode* t = new TreeNode("Compound"); // 函数体 match("LeftBigBkt"); t->child[0] = local_declaration(); // 声明都在前面, 以sibling连接 t->child[1] = statement_list(); // 下面是各种语句, 以sibling连接 if (t->child[0] == NULL) { t->child[0] = t->child[1]; t->child[1] = NULL; } t->child_cnt = 2; match("RightBigBkt"); return t; } TreeNode* declaration() { /** * 对声明(函数/变量)的递归下降分析 */ TreeNode* t; TreeNode* p; // cout << ptoken.type << ": " << ptoken.value << endl; if (ptoken.type == "int") { p = new TreeNode("int"); match("int"); } else { p = new TreeNode("void"); match("void"); } if (p != NULL && ptoken.type == "Id") { // 变量/函数名 TreeNode* q = new TreeNode("Id"); q->name = ptoken.value; q->line = ptoken.line; match("Id"); // TODO: 需要增加数组 if (ptoken.type == "Semicolon") { // 检测到分号, 变量声明 t = new TreeNode("VarDecl"); t->child[0] = p; t->child[1] = q; t->child_cnt = 2; // 记录子节点的个数 match("Semicolon"); } else if (ptoken.type == "Assign") { // 初始化变量并赋值 match("Assign"); Token tmp = match("Num"); match("Semicolon"); int val = stoi(tmp.value); t = new TreeNode("VarAssign"); t->child[0] = p; t->child[1] = q; t->child_cnt = 2; q->val = val; } else if (ptoken.type == "LeftBracket") { // 左括号, 说明是函数 match("LeftBracket"); t = new TreeNode("FunDecl"); t->child[0] = p; t->child[1] = q; t->child[2] = params(); // ! 解析函数的参数 match("RightBracket"); t->child[3] = compound_stmt(); t->child_cnt = 4; } else { error(); } } return t; } TreeNode* declaration_list() { /** * 不断检测声明 * 包括函数声明和变量声明. */ TreeNode* t = declaration(); // 检测一个声明 TreeNode* p = t; // while (ptoken.type != "int" && ptoken.type != "void" && ptoken.type != "EndFile") { // ptoken = getToken(); // if (ptoken.type == "EndFile") break; // } while (ptoken.type == "int" || ptoken.type == "void") { // 检测到int整形, void函数 // cout << "声明的类型 ................... : " << ptoken.type << endl; TreeNode* q; q = declaration(); if (q != NULL) { if (t == NULL) { // ! 似乎不正常, 前面t为NULL说明没有检测到decl, 可以报错 t = p = q; } else { p->sibling = q; // *每个声明是并列的, 用兄弟结点连接. p = q; } } } match("EndFile"); // cout << "hehe\n"; return t; } // 前序遍历获取语法树打印 void preOrder(TreeNode* t, string indent) { // if (t != NULL) // out << "t->nodekind = " << t->nodekind << endl; if (t == NULL) { out << "NULL!" << endl; return; } if (t->nodekind == "FunDecl") { out << indent << "FunctionDeclaration {\n" << indent << " type: FunctionDeclaration\n" << indent << " id: " << t->child[1]->name << endl << indent << " params: [\n"; TreeNode* param = t->child[2]->child[0]; while (param != NULL) { if (param->nodekind == "void") { out << indent << " " << param->nodekind << endl; } else { out << indent << " " << param->child[0]->nodekind << ": " << param->child[1]->name << endl; } param = param->sibling; } out << indent << " ]\n" << indent << " body: BlockStatement {\n" << indent << " type: BlockStatement\n" << indent << " body: [\n"; preOrder(t->child[3], indent + " "); out << indent << " ]\n" << indent << " }\n" << indent << "}\n"; if (t->sibling != NULL) preOrder(t->sibling, indent); return; } if (t->nodekind == "Compound") { if (t->child[1] != NULL) { TreeNode* loc = t->child[0]; out << indent << loc->nodekind << ":{\n"; while (loc != NULL) { out << indent << " " << loc->child[0]->nodekind << ": " << loc->child[1]->name << endl; loc = loc->sibling; } out << indent << "}\n"; } TreeNode* stmt = NULL; if (t->child[1] == NULL) { stmt = t->child[0]; } else stmt = t->child[1]; while (stmt != NULL) { preOrder(stmt, indent); stmt = stmt->sibling; } return; } if (t->nodekind == "ReturnStmt") { out << indent << t->nodekind << ": {\n"; preOrder(t->child[0], indent + " "); out << indent << "}\n"; return; } if (t->nodekind == "Id") { out << indent << t->nodekind << ": " << t->name << endl; } else if (t->nodekind == "Const") { out << indent << t->nodekind << ": " << t->val << endl; } else if (t->nodekind != "Input") { out << indent << t->nodekind << ": {\n"; } else { // ReturnStmt 会出现在这里输出 out << indent << t->nodekind << endl; } for (int i = 0; i < MAX_CHILDREN; ++i) { // out << "i = " << i << endl; if (t->child[i] == NULL) break; blank += 2; if (i == 2 && t->nodekind == "Selection") { if (t->child[2] != NULL) { out << indent << "Else:\n"; } } preOrder(t->child[i], indent + " "); blank -= 2; } if (t->nodekind != "Id" && t->nodekind != "Input" && t->nodekind != "Const") { out << indent << "}\n"; } // Assign 的sibling会重复 // out << "t->nodekind = " << t->nodekind << endl; if (t->sibling != NULL) { if (t->nodekind != "Assign") { preOrder(t->sibling, indent); } } } void printParse(TreeNode* t) { out << "Program:{\n" << " type: program,\n" << " body: [\n"; string indent = " "; preOrder(t, indent); out << " ]\n" << "}\n"; out.close(); // ifstream in("parse.txt", ios::in); // 输出到控制台 // string s; // while (getline(in, s)) { // cout << s << endl; // } cout << "error cnt: " << error_cnt << endl; } TreeNode* parse(bool print) { TreeNode* t; ptoken = getToken(); // 获取第一个token, 开始语法分析 t = declaration_list(); // 获取声明列表, c-由一系列整数/函数声明组成 if (print) { printParse(t); cout << "parse print over !" << endl; } return t; }
true
c6c95f045bb0f7423e8e76e7e2512c0da1479147
C++
NEEC-KAMATA-D3Software/2017Summer_Gr9_UtaWima
/Framework/Source/Component/RenderClientComponent.h
SHIFT_JIS
1,802
2.515625
3
[]
no_license
#pragma once #include<Source\Component\Component.h> #include<string> #include<memory> #include<Source\Component\Animation\AnimatorComponent.h> /** * @file RigidInstanceRenderComponent.h * @brief CX^X`I[i[R|[lgNX * @dital ̃R|[lgĂIuWFNg̓CX^X`悳 * @authro {DP * @date 2017/03/13 */ namespace framework { class CubeRenderTrget; class CubeDepthTarget; } namespace component { class RenderOwnerComponent; class RenderClientComponent:public framework::Component { public: RenderClientComponent(); ~RenderClientComponent(); const std::string& getModelName(); /** * @brief * @Detail ׂẴR|[lgĂɌĂ΂ */ virtual void init()override; /** * @brief p[^Zbg * @param param p[^ */ void setParam(const std::vector<std::string>& param)override; /** * @brief ̃NCAg̃L[u}bv݂̏Jn */ void cubMapWriteBegin(); /** * @brief ̃NCAg̃L[u}bv݂̏I */ void cubMapWriteEnd(); std::shared_ptr<framework::CubeRenderTrget> getCubeMap(); /** * @brief ̃NCAg̃L[u}bv݂̏I */ std::weak_ptr<AnimatorComponent> getAnimator(); private: std::weak_ptr<component::RenderOwnerComponent> findModelOwner(); private: std::shared_ptr<framework::CubeRenderTrget> m_pCubeTarget; std::shared_ptr<framework::CubeDepthTarget> m_pCubeDepthTarget; std::weak_ptr<AnimatorComponent> m_pAnimator; //!`悷郂f̖O std::string m_ModelName; }; }
true
63ebf8eb8c526dcf59faf40e4171abd40ac01524
C++
nasty091/answer-home-work
/22-9/ex2.cpp
UTF-8
755
3.265625
3
[]
no_license
#include <iostream> #include <queue> #include <math.h> using namespace std; bool isPrimeNumber(int x){ if (x<2) return false; if (x>2){ for(int i = 2; i<= sqrt(x);i++){ if(x % i == 0){ return false; } } } return true; } int main(){ int n; int k; cin >> n; queue<int>q; for(int i = 2; i < 10;i++){ if(isPrimeNumber(i)==true){ q.push(i); } } while(!q.empty()){ for(int i = 1; i <= 9; i++){ k = q.front()*10 + i; if(isPrimeNumber(k) && k<=n){ q.push(q.front()*10 + i); } } cout << q.front()<< " "; q.pop(); } return 0; }
true
7ac414475e92b878ef3ec474a98d5f9df6a5aa4f
C++
neelchoudhury/cp
/Codechef and Spoj/L-Z/NOWAYS.cpp
UTF-8
619
2.671875
3
[]
no_license
#include<bits/stdc++.h> #define ll long long int #define MOD 1000000007 using namespace std; ll power(ll a,ll b, ll c) { ll y=a,x=1; while(b>0) { if(b%2==1) x=(x*y)%c; y=(y*y)%c; b=b/2; } return x%c; } ll nck(ll n, ll k) { ll result = 1 ; for (ll i=1; i<= min(k,n-k); i++) { result = ((result%MOD)*((n-i+1)%MOD))%MOD; result = ((result%MOD) *(power(i,MOD-2,MOD)%MOD))%MOD; } return result%MOD; } int main() { ll t,n,k; scanf("%lld", &t); while(t--) { scanf("%lld %lld",&n, &k ); ll ans; if(n==0) ans=0; else ans=nck(n,k); printf("%lld\n", ans); } return 0; }
true
03936008230cc473a82ed87a9ac5e422fd11745f
C++
LucianoTorrano/TicTacToe
/main.h
UTF-8
1,426
2.609375
3
[]
no_license
/* * main.h * * Created on: 28 sep. 2021 * Author: lucho */ #ifndef MAIN_H_ #define MAIN_H_ #include <iostream> #include <string> #include "type.h" #include "GameData.h" #include "UserData.h" #include "utilities.h" const std::string VOID_ARCHIVE_NAME = "-"; const std::string TXT_ARCHIVE_ENDING = ".txt"; /* Imprime por consola las condiciones y reglas de juego */ void printGameInitPage(); /* Pregunta a los usuarios si desean guardar el historial de jugadas. En el caso que lo deseen * les pide un nombre de archivo. Posteriormente crea un archivo de texto con el nombre dado. * Si no desean guardar el historial se le asigna a matchResume una cadena predeterminada como * VOID_ARCHIVE_NAME, por el cual el programa interpretara que no hay archivo cuando se utilice * esta cadena */ status_t createMatchResumeArchive(std::string * matchResume); /* Imprime el titulo en el archivo de texto creado indicando quienes son los jugadores y sus * respectivas fichas */ status_t setMatchResumeArchiveTitle(std::string matchResume,UserData * playerOne,UserData * playerTwo); /* Imprime el estado actual del tablero y el numero de jugada que se esta llevando a cabo */ status_t printBoardInGameResume(GameData * game, std::string matchResume); /* Libera la memoria pedida */ void freeMemory(UserData * playerOne, UserData *playerTwo, GameData *game, std::string * matchResumeName); #endif /* MAIN_H_ */
true
10713f7c34886c7dbc8c4d189b85674d82c4ee7b
C++
tsingke/Homework_Turing
/刘润轩/Experiment_2/SourceCode/2.5.2.cpp
WINDOWS-1252
413
3.046875
3
[]
no_license
#include <iostream> #include <windows.h> using namespace std; float PI = 3.14; float zhouchang(float r); float s(float r); int main() { float r,l,S; cout << "Please input 뾶=" << endl; cin >> r; l=zhouchang(r); S = s(r); cout << "ܳ=" << l << endl << "=" << S <<endl; system("pause"); return 0; } float zhouchang(float r) { return 2*PI*r; } float s(float r) { return PI*r*r; }
true
61e049553e1d88c3618fcd2481719f7577d4e701
C++
yushengding/win32_Mygame
/win32_Mygame/MyDirector.cpp
GB18030
2,679
2.546875
3
[]
no_license
//ѧţ1252957 // //ļGameScene //ļϷĵ һ дĹ캯趨ʼ // MyDirectorӽijĻƷԼ· // ͨԸIJﵽлЧ #include "stdafx.h" #include "MyDirector.h" #include <iostream> #include "selftimer.h" #include "GameScene.h" #include "initScene.h" using namespace std; MyDirector::MyDirector(void) { initScene *a=new initScene(); pushScene(a); srand(GetCurrentTime()); } MyDirector::~MyDirector(void) { } // MyDirector *MyDirector::getDirector(){ static MyDirector instance; return &instance; } void MyDirector::setKeyStatu(string key,string statu) { key_statu[key]=statu; } string MyDirector::getKeyStatu(string key){ map<string , string> ::iterator iter; iter = key_statu.find(key); if(iter!=key_statu.end()) return iter->second; return ""; } void MyDirector::setHWND(HWND hWnd){ this->hWnd=hWnd; } HWND MyDirector::getHWND() { return this->hWnd; } //ڵupdate ӵScene->update() void MyDirector::update(){ HBRUSH hbrush=CreateSolidBrush(RGB(255,255,255)); HDC hdc=GetDC(MyDirector::getDirector()->getHWND()); SelectObject(MyDirector::getDirector()->hMemDC,hbrush); if(Queue_Scene.empty()) { DeleteObject(hbrush); DeleteDC(hdc); return ; } else { MyDirector::getDirector()-> hMemDC = CreateCompatibleDC(hdc); MyDirector::getDirector()->hBitmap = CreateCompatibleBitmap(hdc,768*0.7, 1024*0.7); SelectObject(MyDirector::getDirector()->hMemDC, MyDirector::getDirector()->hBitmap); HBRUSH hbrush=CreateSolidBrush(RGB(255,255,255)); RECT rect; rect.top=0; rect.left=0; rect.bottom=1024*0.7; rect.right=768*0.7; FillRect(MyDirector::getDirector()->hMemDC,&rect,hbrush); Queue_Scene.front()->action(); Queue_Scene.front()->collision_detec(); Queue_Scene.front()->update(); Queue_Scene.front()->draw(); BitBlt(hdc, 0, 0,756*0.7,1024*0.7,MyDirector::getDirector()->hMemDC, 0, 0, SRCCOPY); DeleteObject(hbrush); DeleteDC(hdc); DeleteDC(hMemDC); DeleteObject(hBitmap); } } //ʼб Լ void MyDirector::setWinSize(size winSize){ this->winSize=winSize; } size MyDirector::getWinSize(){ return this->winSize; } void MyDirector::pushScene(MyScene* scene){ Queue_Scene.push(scene); } void MyDirector::popScene(){ Queue_Scene.pop(); } void MyDirector::ConsolePrint(string out){ static int time=0; if(time ==0) { time++; } AllocConsole(); std::cout<<out; //FreeConsole(); } MyScene* MyDirector::getScene() { return (Queue_Scene.front()); }
true
3060eb38691e59dc7ed12bdb606ec01d2614f192
C++
nilsso/cisc310-lab2
/src/queue.hpp
UTF-8
2,298
4.09375
4
[]
no_license
#pragma once #include <list> #include <initializer_list> //! Generic queue // Generalized implementation of the queue data structure which // enforces FIFO (first in, first out) insertion/deletion order. template <class T> class queue { private: //! Underlying buffer std::list<T> m_buffer; public: //! Default constructor queue() = default; //! Copy constructor queue(const queue<T>&) = default; //! Initializer list constructor queue(std::initializer_list<T> list): m_buffer{ list.begin(), list.end() } {} //! Iterators constructor template <class InputIt> queue(InputIt first, InputIt last): m_buffer{ first, last } {} //! Is empty bool empty() const { return m_buffer.empty(); } //! Enqueue value // @param val Queued (added) value. void enqueue(T val) { m_buffer.push_back(val); } //! Dequeue value // @return Dequeued (removed) value, or -1 if empty. T dequeue() { uint16_t val = -1; if (!m_buffer.empty()) { val = m_buffer.front(); m_buffer.pop_front(); } return val; } //! Erase elements // @param n Number of elements to erase. void erase(int n) { m_buffer.erase(m_buffer.begin(), std::next(m_buffer.begin(), n)); } //! Clear queue of all elements void clear() { m_buffer.clear(); } //! Is normal (first element is zero) bool normal() const { return m_buffer.front() == 0; } //! Normalize // If not already normal, subtracts the first element from itself and all elements. void normalize() { if (!normal()) { uint16_t front = m_buffer.front(); for (auto &v: m_buffer) v -= front; } } //! Peek some // @return Vector of first n values in queue. std::vector<T> peek(size_t n) const { return { m_buffer.cbegin(), std::next(m_buffer.cbegin(), std::min(n, m_buffer.size())) }; }; //! Peek all // @return Vector of all values in queue. std::vector<T> peek() const { return peek(m_buffer.size()); } //! Size size_t size() const { return m_buffer.size(); } };
true
895ca74e6122d7c57116a620dacc64af23b9b155
C++
kuronekonano/OJ_Problem
/1003Tiles of Tetris, NOT!.cpp
GB18030
461
3
3
[]
no_license
#include<stdio.h> long long gcd(long long x,long long y) { if(y==0) { return x; } else { return gcd(y,x%y); } } int main() { long long a,b; while(scanf("%lld%lld",&a,&b)!=EOF) { if(a==0&&b==0) { return 0; } long long k=gcd(a,b);///Լ printf("%lld\n",a*b/k/k);///СԼ } return 0; }
true
03285f32aea97a73bb343490d40c0e2b6a1c192f
C++
yangjae33/sw15_jaehyuk
/11375.cpp
UTF-8
1,062
2.625
3
[]
no_license
#include<iostream> #include<vector> using namespace std; int N,M; vector<vector<int> > work; vector<int> assigned; vector<int> visited; int dfs(int idx){ if(visited[idx] == 1){ return 0; } visited[idx] = 1; for(int i = 0; i<work[idx].size(); i++){ if(assigned[work[idx][i]] == -1){ assigned[work[idx][i]] = idx; return 1; } else{ if(dfs(assigned[work[idx][i]]) == 1){ assigned[work[idx][i]] = idx; return 1; } } } return 0; } int main(){ cin>>N>>M; work.resize(N+1); assigned.resize(M+1); visited.resize(N+1); fill(assigned.begin(), assigned.end(), -1); int K; for(int i = 0; i<N; i++){ cin>>K; int input; for(int j = 0; j<K; j++){ cin>>input; work[i].push_back(input); } } int sum = 0; for(int i = 0; i<N; i++){ for(int j = 0; j<M; j++) visited[j] = 0; sum += dfs(i); } cout<<sum; }
true
09730842307c063af838bb64930b5f9fcb6b4d38
C++
fanzhaoyun/LeetCode
/dataStruct.h
UTF-8
128
2.6875
3
[]
no_license
#pragma once using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(nullptr) {}; };
true
e194536655a3b0b2707c51e691e38073a3e5ea88
C++
Jooye0n/Algorithm
/BAEKJOON/17822.cpp
UTF-8
3,877
3.21875
3
[]
no_license
/* https://www.acmicpc.net/problem/17822 입력 첫째 줄에 N, M, T이 주어진다. 둘째 줄부터 N개의 줄에 원판에 적힌 수가 주어진다. i번째 줄의 j번째 수는 (i, j)에 적힌 수를 의미한다. 다음 T개의 줄에 xi, di, ki가 주어진다. 4 4 1 1 1 2 3 5 2 4 2 3 1 3 5 2 1 3 2 2 0 1 */ #include <cstdio> #include <iostream> #include <vector> using namespace std; int n,m,t; int result; vector<vector<int> > v(51); void foundSameNumber(){ //인접하면서 같은 수 찾는다. //있으면, 지운다. 없으면 전체 평균 작은수 +1 큰수 -1 bool chk[51][51] = {0, }; bool flag = false; int tempTotal = 0; int tempCnt = 0; //같은 원판에서 인접 for(int i=1; i<=n; i++){ for(int j=0; j<m-1; j++){ if(v[i][j] == 0) continue; if(j != 0 && v[i][j] == v[i][j-1]){//이전꺼와같음 chk[i][j] = true; chk[i][j-1] = true; } if(v[i][j] == v[i][j+1]){//다음꺼와같음 chk[i][j] = true; chk[i][j+1] = true; } if(j == 0 && v[i][j] == v[i][m-1]){ chk[i][j] = true; chk[i][m-1] = true; } } } //다른 판에서 인접 for(int i=0; i<m; i++){ for(int j=1; j<=n; j++){ if(v[j][i] == 0) continue; if(j != 1){ if(v[j][i] == v[j-1][i]){ chk[j][i] = true; chk[j-1][i] = true; } } if(j != n){ if(v[j][i] == v[j+1][i]){ chk[j][i] = true; chk[j+1][i] = true; } } } } //지우기 for(int i=1; i<=n; i++){ for(int j=0; j<m; j++){ if(v[i][j] !=0){ tempTotal+=v[i][j]; tempCnt++; if(chk[i][j] == true){ flag = true; v[i][j] = 0; } } } } if(flag == false && tempTotal !=0){//인접한 같은 수 없음 int div = tempTotal % tempCnt; tempTotal /= tempCnt; if(div == 0){ for(int i=1; i<=n; i++){ for(int j=0; j<m; j++){ if(v[i][j] == 0) continue; if(v[i][j] > tempTotal) v[i][j]--; else if(v[i][j] < tempTotal) v[i][j]++; } } }else{ for(int i=1; i<=n; i++){ for(int j=0; j<m; j++){ if(v[i][j] == 0) continue; if(v[i][j] > tempTotal) v[i][j]--; else if(v[i][j] <= tempTotal) v[i][j]++; } } } } } int calculTotal(){ int result =0; for(int i=1; i<=n; i++){ for(int j=0; j<m; j++){ if(v[i][j] != 0) result += v[i][j]; } } return result; } void turnVector(int a, int b, int c){ int tuenCnt = c % m; for(int i=1; i<=n; i++){ if(i % a == 0){ if(b == 0){//시계 for(int j=0; j<tuenCnt; j++){ v[i].insert(v[i].begin(), v[i].back()); v[i].pop_back(); } }else if(b == 1){//반시계 for(int j=0; j<tuenCnt; j++){ v[i].push_back(v[i].front()); v[i].erase(v[i].begin()); } } } } foundSameNumber(); } int main(){ cin>>n>>m>>t; for(int i=1; i<=n; i++){ for(int j=0 ;j<m; j++){ int temp; cin>>temp; v[i].push_back(temp); } } while(t--){ int a,b,c; cin>>a>>b>>c; turnVector(a,b,c); } cout<<calculTotal(); return 0; }
true
2b6b655892586c465b0e7f766fc4bfff6c0f1e38
C++
georgeshanti/XSe
/include/xse/linux/Connection.hpp
UTF-8
705
2.8125
3
[ "MIT" ]
permissive
#ifndef XSE_LINUX_CONNECTION #define XSE_LINUX_CONNECTION #include<sys/socket.h> #include<iostream> #include<netinet/in.h> #include<string.h> #include<unistd.h> #define IPV4 AF_INET #define IPV6 AF_INET6 #define TCP SOCK_STREAM #define UPD SOCK_DGRAM namespace XSe{ class Connection{ private: public: int connection; Connection(int conn):connection(conn){} bool valid(){ return this->connection!=0; } int receive(char *buffer, int size) const{ return ::read( this->connection , buffer, size); } void send(const char *buffer, int size) const{ ::send( this->connection , buffer , size , 0 ); } void close() const{ ::close(this->connection); } }; } #endif
true
e90e92efbe245e631a084efccddee80235fbeb07
C++
PawelBoe/PECS
/PECS/core/Entity.h
UTF-8
773
2.578125
3
[ "MIT" ]
permissive
// // Created by Pawel Boening on 17/06/18. // #ifndef ECS_ENTITY_H #define ECS_ENTITY_H #include <cstdint> namespace pecs { typedef uint32_t EntityIndex; typedef uint8_t EntityVersion; typedef uint32_t EntityId; class Entity { public: struct Hash { unsigned int operator()(Entity const& e) const { return e.index(); } }; Entity(); Entity(EntityIndex index, EntityVersion version); EntityId id() const; EntityIndex index() const; EntityVersion version() const; bool operator==(const Entity &rhs) const; bool operator!=(const Entity &rhs) const; private: EntityId _id; }; } #endif //ECS_ENTITY_H
true
66f534ed9e9b5df3844e17f5b2ede06c6212d0c6
C++
osak/Contest
/AOJ/0116.cc
UTF-8
2,993
3.25
3
[]
no_license
//Name: Recutangular Searching //Level: 3 //Category: 累積和,連続区間 //Note: 類題 POJ1964 /* * あるマスについて,そのマスを含めてそれより上にいくつ白マスが連続しているかを記憶しておく. * すると,1行内のある区間を底辺に持つ長方形の面積は,区間長 * その区間内の最小値で与えられることが分かる. * * これはスタックを使い,ある高さの区間がいくつ連続しているかを高さの昇順で管理すると効率良く求められる. * 1行を左から右になめながら値をpushしていくが,このとき * ・スタックトップより大きい値であればそのままpushする. * ・スタックトップより小さい値 h' であれば,このマスを含んで h' より高い長方形は作れないため,スタックトップを h' に揃えてしまう. * つまり, h' より小さい値が出てくるまでスタックを巻き戻しながらその個数を数え,最後に h' を同数追加すればよい. * 以前にpushした値を起点とする長方形は,巻き戻しの途中で右方向の最大区間長を得られるためここで計算できる. * * また, h' を同数追加するという処理は (値, 長さ) のペアを管理するようにすると効率的に処理できる. * この処理をした上でのオーダーは,各マスを1回ずつなめる操作でO(N^2),スタック操作は高々2N回しかpushされず,したがってpopも2N回であるからO(N). * よって全体のオーダーは O(N^2). */ #include <iostream> #include <string> #include <stack> #include <algorithm> using namespace std; int acc[1024][1001]; int main() { cin.tie(0); ios::sync_with_stdio(0); while(true) { int H, W; cin >> H >> W; if(!H && !W) break; for(int i = 0; i < W; ++i) { acc[0][i] = 0; } for(int i = 0; i < H; ++i) { string line; cin >> line; for(int c = 0; c < W; ++c) { if(i > 0) acc[i][c] = acc[i-1][c]; if(line[c] == '*') acc[i][c] = 0; else acc[i][c]++; } } int ans = 0; for(int r = 0; r < H; ++r) { // 番兵 acc[r][W] = 0; // スタックの中身は常に昇順になっている. stack<pair<int,int> > stk; for(int c = 0; c <= W; ++c) { int len = 0; const int cur = acc[r][c]; while(!stk.empty() && stk.top().first >= cur) { len += stk.top().second; const int area = len * stk.top().first; ans = max(ans, area); stk.pop(); } ++len; stk.push(make_pair(cur, len)); } } cout << ans << endl; } return 0; }
true
a0c619b8f3179e4d2c86f2eebd8759b747d5c5b5
C++
SimonBrandner/Basic2DGameEngine
/Game.cpp
UTF-8
548
2.6875
3
[]
no_license
#ifndef GAME #define GAME #include "Game.hpp" Game::Game(int length, int mapSizeX, int mapSizeY, bool * q) : MapSizeX(), MapSizeY(), quit() { // Variables MapSizeX = mapSizeX; MapSizeY = mapSizeY; quit = q; } // Variables std::vector<Pixel> Game::getChangedPixels() { std::vector<Pixel> changedPixels; return changedPixels; } void Game::passInput(std::string pressedKey) { if (pressedKey == "none"){return;} // Set variable based on pressed key } void Game::update() { // Game update function } #endif
true
717cfdb945a8aa9c5bbcbb65d32c14fc9f9d5102
C++
VolodymyrShchyhelsky/Client-Server-remote
/Server/mytcpserver.cpp
UTF-8
4,207
2.65625
3
[]
no_license
#include "mytcpserver.h" MyServer::MyServer(QObject *parent): QObject(parent) { // Data base of pathes to programs db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("E:/QT/Server/PathDataBase.db"); db.open(); server = new QTcpServer(this); connect(server,SIGNAL(newConnection()),this,SLOT(newConnection())); if(!server->listen(QHostAddress::Any,5555)) { qDebug()<<"NotListen"; } else { qDebug()<<"Listen"; } } void MyServer::newConnection() { qDebug()<<"User conected"; socket = server->nextPendingConnection(); connect(socket, SIGNAL(readyRead()), this , SLOT(sockReady())); connect(socket, SIGNAL(disconnected()), this, SLOT(sockDisc())); } //Receive command from client in JSON format void MyServer::sockReady() { Data = socket->readAll(); doc = QJsonDocument::fromJson(Data,&docError); if (docError.errorString().toInt() == QJsonParseError::NoError) { if (doc.object().value("program")=="openNow") { OutputRunningPrograms(); } else if(doc.object().value("program")=="runNow") { RunProgramToUser(); } else if(doc.object().value("program")=="runThis") { RunProgramFromUser(doc.object().value("runThis").toString()); } } else { qDebug() << "Json Error \n"; } } //Pass all names of program which user can run (from database) void MyServer::RunProgramToUser() { if(db.isOpen()) { QSqlQuery query; if(query.exec("SELECT Name FROM folder_path")) { QString nameBase; while(query.next()) { QString name = "{\"name\":\"" + query.value(0).toString() + "\"},"; nameBase = nameBase+name; } QByteArray RPTU="{\"connect\":\"ToRun\",\"programYouCanRun\":[" + nameBase.toUtf8() + "{\"name\":\"erorname\"}]}"; socket->write(RPTU); } else { qDebug() << "SELECT trouble"; } } else { qDebug() << "DB isnt open"; } } //Recive name of program which server must run -> find path in data base -> run using "system" void MyServer::RunProgramFromUser(QString name) { if(db.isOpen()) { QSqlQuery query; QString sqlString = "SELECT Path FROM folder_path WHERE name = '" + name + "'"; if(query.exec(sqlString)) { query.first(); QString path = query.value(0).toString(); const QString s = "start " + path; system(s.toStdString().c_str()); } else { qDebug() << "Select trouble"; } } else { qDebug() << "Data Base isnt open"; } } //Get running processes using "EnumWindows" function -> convert from file to json format -> send to client void MyServer::OutputRunningPrograms() { QFile file; file.setFileName("E:\\Program.json"); file.open(QIODevice::Append); file.resize(0); file.close(); EnumWindows(StaticEnumWindowsProc, 0); file.setFileName("E:\\Program.json"); if (file.open(QIODevice::ReadOnly)) { QByteArray fromFile = file.readAll(); QByteArray RunPrograms = "{\"connect\":\"ToOutput\",\"result\":[" + fromFile + "{\"name\":\"erorname\"}]}"; socket->write(RunPrograms); socket->waitForBytesWritten(5000); } file.close(); } //Get running processes and write them to file BOOL MyServer::StaticEnumWindowsProc(HWND hwnd, LPARAM lParam) { WCHAR title[255]; GetWindowText(hwnd, title, 255); QString currentHWMD = "{\"name\":\""; if(QString::fromWCharArray(title) != "") { currentHWMD += QString::fromWCharArray(title); currentHWMD += "\"},"; QFile file; file.setFileName("E:\\Program.json"); if (file.open(QIODevice::Append)) { QTextStream outStream(&file); outStream << currentHWMD; } file.close(); } return TRUE; } void MyServer::sockDisc() { qDebug() << "Disconect"; socket->deleteLater(); }
true
46ae746d4ae763f27d73522450e851bfecba999f
C++
shaohua0720/sbl-sandbox
/samples/nmr2d/ista.cc
UTF-8
2,843
2.53125
3
[ "MIT" ]
permissive
/* Copyright (c) 2019 Bradley Worley <geekysuavo@gmail.com> * Released under the MIT License. * * Compilation: * g++ -std=c++14 -O3 ista.cc -o ista -lfftw3_threads -lfftw3 -lm */ #include "inst.hh" int main (int argc, char **argv) { /* read the instance data from disk. */ auto data = load(argc, argv); /* problem sizes. */ constexpr size_array N = { 2048, 2048 }; constexpr std::size_t n = N[0] * N[1]; const std::size_t m = data.size(); /* prepare fftw. */ fft2<N[0], N[1]> F; auto dy = F.data(); /* number of iterations. */ const std::size_t iters = 1000; /* threshold reduction factor. */ const double mu = 0.98; /* construct the schedule and measured * vectors from the data table. */ auto S = schedule_vector(data, N); auto y = measured_vector(data, N); /* allocate x, fx. */ complex_vector x{new double[n][K]}; complex_vector fx{new double[n][K]}; for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) x[i][k] = fx[i][k] = 0; /* compute the initial thresholding value. */ for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) dy[i][k] = y[i][k]; F.fwd(); double thresh = 0; for (std::size_t i = 0; i < n; i++) { double dy2 = 0; for (std::size_t k = 0; k < K; k++) { dy[i][k] /= std::sqrt(n); dy2 += std::pow(dy[i][k], 2); } thresh = std::max(thresh, mu * std::sqrt(dy2)); } /* iterate. */ for (std::size_t it = 0; it < iters; it++) { /* compute the current spectral estimate. */ for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) dy[i][k] = S[i] * (y[i][k] - x[i][k]); F.fwd(); for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) fx[i][k] += dy[i][k] / std::sqrt(n); /* apply the l1 function. */ for (std::size_t i = 0; i < n; i++) { double fxnrm = 0; for (std::size_t k = 0; k < K; k++) fxnrm += std::pow(fx[i][k], 2); fxnrm = std::sqrt(fxnrm); for (std::size_t k = 0; k < K; k++) fx[i][k] *= (fxnrm > thresh ? 1 - thresh / fxnrm : 0); } /* update the time-domain estimate. */ for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) dy[i][k] = fx[i][k]; F.inv(); for (std::size_t i = 0; i < n; i++) for (std::size_t k = 0; k < K; k++) x[i][k] = dy[i][k] / std::sqrt(n); /* update the threshold. */ thresh *= mu; } /* output the results. */ std::cout.precision(9); std::cout << std::scientific; for (std::size_t i = 0; i < N[0] / 2; i++) { for (std::size_t j = 0; j < N[1]; j++) { const std::size_t J = (j + N[1] / 2) % N[1]; const std::size_t idx = i + N[0] * J; std::cout << i << " " << j << " " << fx[idx][0] << "\n"; } } }
true
5526a439a93a84b7e234be16f520780d08a40471
C++
intel/AVB-AudioModules
/public/inc/internal/audio/smartx_test_support/IasTimeStampCounter.hpp
UTF-8
2,065
2.75
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (C) 2018 Intel Corporation.All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ /** * @file IasTimeStampCounter.hpp * @brief Time Stamp Counter, based on rdtsc, to be used for performance optimizations. * @date May 06, 2013 */ #ifndef IASTIMESTAMPCOUNTER_HPP_ #define IASTIMESTAMPCOUNTER_HPP_ namespace IasAudio { /** * @brief Private inline function to get the current time stamp (rdtsc) */ inline uint32_t getTimeStamp() { uint32_t tsc=0; __asm__ volatile( "rdtsc;" "movl %%eax, %0;" : "=r" (tsc) : "0" (tsc) : "%eax", "%edx" ); return tsc; } /** * @brief Private inline function to get the current time stamp (rdtsc), 64 bit version */ inline uint64_t getTimeStamp64(void) { uint32_t a, d; __asm__ volatile("rdtsc" : "=a" (a), "=d" (d)); return (((uint64_t)a) | (((uint64_t)d) << 32)); } class IasTimeStampCounter { public: /** * @brief Constructor. */ IasTimeStampCounter() { mTimeStampStart = getTimeStamp(); }; /** * @brief Destructor, virtual by default. */ virtual ~IasTimeStampCounter() {}; /** * @brief reset() method -> starts a new measurement. */ void reset() { mTimeStampStart = static_cast<uint64_t>(getTimeStamp()); }; /** * @brief get() method -> gets the number of (rdtsc) clock ticks since the last reset. */ uint32_t get() { return (getTimeStamp() - mTimeStampStart); }; private: /** * @brief Copy constructor, private unimplemented to prevent misuse. */ IasTimeStampCounter(IasTimeStampCounter const &other); /** * @brief Assignment operator, private unimplemented to prevent misuse. */ IasTimeStampCounter& operator=(IasTimeStampCounter const &other); // Member variables uint32_t mTimeStampStart; ///< The rdtsc time stamp when the reset() method was called. }; } // namespace IasAudio #endif // IASTIMESTAMPCOUNTER_HPP_
true
abb8de49942fbc11abd71ec65999073c4ad129bc
C++
alediaferia/morph-again
/src/core/parser.cpp
UTF-8
8,085
3.03125
3
[]
no_license
#include "parser.h" #include "type.h" #include "constant.h" #include "assign.h" #include "arith.h" #include "strlit.h" #include "array.h" #include "seq.h" #include "exprstmt.h" #include <sstream> #include <iostream> #define TRY_MATCH(arg) \ if (!match(arg)) \ return; #define TRY_MATCH_ELSE(arg, _else) \ if (!match(arg)) \ return _else; Parser::Parser(std::unique_ptr<Lexer> lexer) : _lexer(std::move(lexer)) { _scope = std::make_shared<Scope>(); } void Parser::setInput(const std::string &input) { _lexer->setSource(input.cbegin(), input.cend()); } void Parser::error(const std::string &err) { std::cerr << err << std::endl; } void Parser::syntaxError(const std::string &err) { std::ostringstream ss; ss << "Syntax error: " << err; error(ss.str()); } void Parser::undeclIdError(const std::string &id) { std::ostringstream ss; ss << "Undeclared identifier '" << id << "'" << std::endl; error(ss.str()); } void Parser::next() { _token = _lexer->scan(); } bool Parser::match(Token::Tag tag) { if (_token->tag() != tag) { std::ostringstream ss; ss << "Unexpected token type '" << _token->tag() << "' (expected '" << tag << "')" << std::endl; syntaxError(ss.str()); return false; } next(); return true; } bool Parser::match(char c) { if (**_token != c) { std::ostringstream ss; ss << "Unexpected token '" << **_token << "' (" << _token->tag() << ")" << " (expected '" << c << "')" << std::endl; syntaxError(ss.str()); return false; } next(); return true; } // <program> ::= <expr> std::shared_ptr<Node> Parser::program(bool newScope) { next(); if (newScope) // pushing a new scope _scope = std::make_shared<Scope>(_scope); auto stmts_ = stmts(); std::shared_ptr<Node> node_; if (!stmts_) node_ = Stmt::Null; else node_ = std::static_pointer_cast<Node>(stmts()); if (newScope) // popping scope _scope = _scope->parent(); return node_; } // // <func-decl> ::= 'fn' <identifier> '()' -> <type> <block> // void Parser::funcDecl() { // } // // <block> ::= '{' (decls|stmts) '}' // void Parser::block() { // TRY_MATCH('{'); // // pushing a new scope // _scope = std::make_shared<Scope>(_scope); // // parsing declarations // decls(); // // parsing statements // // TODO // // restoring scope // _scope = _scope->parent(); // } // <decl> ::= <basic-type> <id> [=<expr>] std::shared_ptr<Stmt> Parser::decl() { if (_token->tag() == Token::BASIC) { std::shared_ptr<Stmt> stmt; auto id_ = id(); auto idStmt = std::make_shared<ExprStmt>(id_); if (**_token == '=') { // inline assignment auto assign = assignTo(id_); stmt = std::make_shared<Seq>(idStmt, assign); } else { stmt = idStmt; } _scope->put(id_->token(), id_); return stmt; } else if (_token->tag() == Token::FN) { return std::make_shared<ExprStmt>(fn()); } std::ostringstream ss; ss << "Unexpected '" << **_token << "' for declaration" << std::endl; error(ss.str()); return nullptr; } std::shared_ptr<Type> Parser::type() { std::shared_ptr<Token> tok = _token; TRY_MATCH_ELSE(Token::BASIC, nullptr); return std::static_pointer_cast<Type>(tok); } // <assign> ::= <id> '=' <expr>; std::shared_ptr<Stmt> Parser::assign() { auto tok = _token; TRY_MATCH_ELSE(Token::ID, nullptr); auto id = _scope->get(tok); if (!id) { std::ostringstream ss; ss << "Undeclared identifier '" << **tok << "'" << std::endl; error(ss.str()); return nullptr; } return assignTo(id); } std::shared_ptr<Stmt> Parser::assignTo(std::shared_ptr<Id> id) { TRY_MATCH_ELSE('=', nullptr); auto expr_ = expr(); auto set = std::make_shared<Assign>(id, expr_); return set; } // <factor> ::= CONSTANT | // IDENT | // <parenexpr> std::shared_ptr<Expr> Parser::factor() { std::shared_ptr<Expr> expr; switch (_token->tag()) { case Token::NUM: expr = std::make_shared<Constant>(_token, Type::Int); next(); break; case Token::STRLIT: { auto strlit = std::static_pointer_cast<StrLit>(_token); expr = std::make_shared<Constant>(_token, std::make_shared<Array>(strlit->length(), Type::Char)); next(); break; } case Token::ID: { auto word = std::static_pointer_cast<Word>(_token); auto identifier = word->toString(); auto id = _scope->get(_token); if (!id) { undeclIdError(_token->toString()); } next(); return id; } case Token::OTHER: { if (**_token == '(') { expr = parenExpr(); } next(); break; } default: error("Syntax error"); } return expr; } // <parenexpr> ::= '(' <expr> ')' std::shared_ptr<Expr> Parser::parenExpr() { TRY_MATCH_ELSE('(', nullptr); auto expr_ = expr(); TRY_MATCH_ELSE(')', nullptr); return expr_; } // <expr> ::= <term> ('+'|'-') <term> std::shared_ptr<Expr> Parser::expr() { auto term_ = term(); while (**_token == '+' || **_token == '-') { auto tok = _token; next(); term_ = std::make_shared<Arith>(tok, term_, term()); } return term_; } // <stmt> ::= (<decl> | <ret>) ';' std::shared_ptr<Stmt> Parser::stmt() { std::shared_ptr<Stmt> node_; if (_token->tag() == Token::BASIC || _token->tag() == Token::FN) node_ = decl(); else if (_token->tag() == Token::RETURN) node_ = ret(); else return Stmt::Null; TRY_MATCH_ELSE(';', nullptr); return node_; } // <term> ::= <factor> ('*'|'/') <factor> std::shared_ptr<Expr> Parser::term() { auto factor_ = factor(); while (**_token == '*' || **_token == '/') { auto tok = _token; next(); factor_ = std::make_shared<Arith>(tok, factor_, factor()); } return factor_; } // <fn> ::= 'fn' <identifier> '(' (<arg>[,<arg>])* ')' <block> std::shared_ptr<Fn> Parser::fn() { TRY_MATCH_ELSE(Token::FN, nullptr); std::shared_ptr<Token> tok = _token; TRY_MATCH_ELSE(Token::ID, nullptr); auto fnId = std::static_pointer_cast<Word>(tok); auto reserved = _scope->get(fnId); if (reserved) { error("Cannot redefine symbol"); return nullptr; } TRY_MATCH_ELSE('(', nullptr); std::vector<std::shared_ptr<Id>> args; std::shared_ptr<Scope> fnScope = std::make_shared<Scope>(_scope); while (**_token != ')') { auto id_ = id(); fnScope->put(id_->token(), id_); args.push_back(id_); if (**_token != ',') break; } TRY_MATCH_ELSE(')', nullptr); auto seq = block(fnScope); auto fn = std::make_shared<Fn>(fnId, Type::Void, args, std::static_pointer_cast<Seq>(seq)); _scope->put(fnId, fn); return fn; } std::shared_ptr<Id> Parser::id() { std::shared_ptr<Type> t = type(); std::shared_ptr<Token> tok = _token; TRY_MATCH_ELSE(Token::ID, nullptr); return std::make_shared<Id>(std::static_pointer_cast<Word>(tok), t); } // <stmts> ::= <stmt>+ std::shared_ptr<Seq> Parser::stmts() { std::shared_ptr<Seq> seq_; auto stmt_ = stmt(); if (stmt_ == Stmt::Null) { return std::make_shared<Seq>(stmt_, Stmt::Null); } else { return std::make_shared<Seq>(stmt_, stmts()); } } // <block> ::= '{' <stmts> '}' std::shared_ptr<Stmt> Parser::block(std::shared_ptr<Scope> scope) { TRY_MATCH_ELSE('{', nullptr) auto prevScope = _scope; if (scope) _scope = scope; auto block = stmts(); _scope = prevScope; TRY_MATCH_ELSE('}', nullptr) return block; } // <return> ::= 'return' <expr> std::shared_ptr<Ret> Parser::ret() { TRY_MATCH_ELSE(Token::RETURN, nullptr); return std::make_shared<Ret>(expr()); }
true
4caef4f4de9c1f98ac896b3732612f7f30c4b469
C++
adityavk/json-parser
/TestCases/AllTestCases.cpp
UTF-8
9,471
3.140625
3
[]
no_license
// // AllTestCases.cpp // JSONParser // // Created by Aditya Vikram on 13/03/21. // #include "AllTestCases.hpp" #include "lexer.hpp" #include <iostream> using namespace std; using namespace JSONParser; void lexString() { const std::string input("\"hello world\"fafnnk"); cout<< "Lexed: "<< StringLexer::lex(input)<< "\n"; } void lexEmptyString() { const std::string input("\"\""); cout<< "Empty lexed: "<< StringLexer::lex(input)<< "\n"; } void lexStringNegative() { const std::string input(""); cout<< "Not string lexed: "<< StringLexer::lex(input)<< "\n"; } void lexTrue() { const std::string input("true"); cout<< "True Lexed: "<< BoolLexer::lex(input)<< "\n"; } void lexFalse() { const std::string input("false"); cout<< "False Lexed: "<< BoolLexer::lex(input)<< "\n"; } void lexTrueAnd() { const std::string input("trueAbc"); cout<< "True And lexed: "<< BoolLexer::lex(input)<< "\n"; } void lexFalseAnd() { const std::string input("falseAbc"); cout<< "False And lexed: "<< BoolLexer::lex(input)<< "\n"; } void lexBoolNegative() { const std::string input("abc"); cout<< "Not bool lexed: "<< NullLexer::lex(input)<< "\n"; } void lexNull() { const std::string input("null"); cout<< "Null Lexed: "<< NullLexer::lex(input)<< "\n"; } void lexNullAnd() { const std::string input("nullAbc"); cout<< "Null And lexed: "<< NullLexer::lex(input)<< "\n"; } void lexNullNegative() { const std::string input("abc"); cout<< "Not null lexed: "<< NullLexer::lex(input)<< "\n"; } void lexZero() { const std::string input("0"); cout<< "Zero Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexPositiveInteger() { const std::string input("2"); cout<< "2 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexNegativeInteger() { const std::string input("-1"); cout<< "-1 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongPositiveInteger() { const std::string input("2147915791750"); cout<< "2147915791750 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongNegativeInteger() { const std::string input("-115710570175015015701"); cout<< "-115710570175015015701 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexFloatingPointZero() { const std::string input("0.0"); cout<< "0.0 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongerFloatingPointZero() { const std::string input("0.0000"); cout<< "0.0000 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexPositiveFloatingPoint() { const std::string input("100.3"); cout<< "100.3 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexNegativeFloatingPoint() { const std::string input("-1101.0"); cout<< "-1101.0 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongPositiveFloatingPoint() { const std::string input("214.7915791750"); cout<< "214.7915791750 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongNegativeFloatingPoint() { const std::string input("-115.710570175015015701"); cout<< "-115.710570175015015701 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexZeroAnd() { const std::string input("0aava"); cout<< "0 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexPositiveIntegerAnd() { const std::string input("2a"); cout<< "2 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexNegativeIntegerAnd() { const std::string input("-1a"); cout<< "-1 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongPositiveIntegerAnd() { const std::string input("2147915791750abcdafaf"); cout<< "2147915791750 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongNegativeIntegerAnd() { const std::string input("-115710570175015015701afgag"); cout<< "-115710570175015015701 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexFloatingPointZeroAnd() { const std::string input("0.0a"); cout<< "0.0 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongerFloatingPointZeroAnd() { const std::string input("0.0000ava"); cout<< "0.0000 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexPositiveFloatingPointAnd() { const std::string input("100.3gwg"); cout<< "100.3 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexNegativeFloatingPointAnd() { const std::string input("-1101.0e."); cout<< "-1101.0 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongPositiveFloatingPointAnd() { const std::string input("214.7915791750mlamf."); cout<< "214.7915791750 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexLongNegativeFloatingPointAnd() { const std::string input("-115.710570175015015701afgag"); cout<< "-115.710570175015015701 and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexEndingWithDot() { const std::string input("-115."); cout<< "-115. Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexEndingWithDotAnd() { const std::string input("-115.adfa"); cout<< "-115. and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexTwoMinus() { const std::string input("--1"); cout<< "--1 Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexMinusDot() { const std::string input("-.123afaf"); cout<< "-.123afaf and Lexed: "<< NumberLexer::lex(input)<< "\n"; } void lexTwoDotsTogether() { const std::string input("1..afaf"); cout<< "1..afaf and Lexed: "<< NumberLexer::lex(input)<< "\n"; } template<typename T> void print(const std::vector<T>& vec) { cout<< "Printing vector: "; for (const auto& element : vec) { cout<< element << ", "; } cout<< "\n"; } void lexEverything() { // print(Lexer::lex("1.0null4.3true\"wow, lol.g agnonn\"false")); // print(Lexer::lex("1.0null4.3truefalse\"wow, lol.g agnonn\"")); // print(Lexer::lex("\"wow, lol.g agnonn\"1.04.3true\"wow, lol.g agnonn\"falsenull")); // print(Lexer::lex("1.0null4.3true\"wow, lol.g agnonn\"falsetrue")); } void TestClass::runAllTests() { lexString(); lexEmptyString(); lexStringNegative(); lexTrue(); lexFalse(); lexTrueAnd(); lexFalseAnd(); lexBoolNegative(); lexNull(); lexNullAnd(); lexNullNegative(); lexZero(); lexPositiveInteger(); lexNegativeInteger(); lexLongPositiveInteger(); lexLongNegativeInteger(); lexFloatingPointZero(); lexLongerFloatingPointZero(); lexPositiveFloatingPoint(); lexNegativeFloatingPoint(); lexLongPositiveFloatingPoint(); lexLongNegativeFloatingPoint(); lexZeroAnd(); lexPositiveIntegerAnd(); lexNegativeIntegerAnd(); lexLongPositiveIntegerAnd(); lexLongNegativeIntegerAnd(); lexFloatingPointZeroAnd(); lexLongerFloatingPointZeroAnd(); lexPositiveFloatingPointAnd(); lexNegativeFloatingPointAnd(); lexLongPositiveFloatingPointAnd(); lexLongNegativeFloatingPointAnd(); lexEndingWithDot(); lexEndingWithDotAnd(); lexTwoMinus(); lexMinusDot(); lexTwoDotsTogether(); lexEverything(); } static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::string LexerTestClass::generate(JSONParser::TokenType tokenType) { switch (tokenType) { case JSONParser::TokenType::String: { constexpr int stringLen = 12; string tmp_s; tmp_s.reserve(stringLen); tmp_s += '\"'; for (int i = 0; i < stringLen; ++i) tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; tmp_s += '\"'; return tmp_s; } case JSONParser::TokenType::Int: { uint64_t num = rand(); return to_string(num); } case JSONParser::TokenType::Double: { double num = (static_cast<double>(rand()) / RAND_MAX) * ((rand() % 2) ? -1.0 : 1.0); return to_string(num); } case JSONParser::TokenType::Bool: return (rand() % 2) == 0 ? "true" : "false"; case JSONParser::TokenType::Null: return "null"; case JSONParser::TokenType::JsonFormatSpecifier: { switch (rand() % 6) { case 0: return ","; case 1: return ":"; case 2: return "{"; case 3: return "}"; case 4: return "["; case 5: return "]"; } } case JSONParser::TokenType::None: return ""; } } uint64_t LexerTestClass::timeLexer(const int numIter, int numParts) { std::vector<std::string> inputs; inputs.reserve(numIter); srand(static_cast<unsigned>(time(nullptr))); for (int i = 0; i < numIter; ++i) { std::string s; for (int j = 0; j < numParts; ++j) { TokenType type = static_cast<TokenType>((rand() % static_cast<int>(TokenType::None))); s.append(generate(type)); } inputs.push_back(s); } uint64_t timeElapsed = 0; for (const auto& input : inputs) { auto startTime = std::chrono::steady_clock::now(); auto lexOut = Lexer::lex(input); auto elapsed = std::chrono::steady_clock::now() - startTime; timeElapsed += std::chrono::duration_cast<std::chrono::nanoseconds>(elapsed).count(); // print(lexOut); } return timeElapsed; }
true
ed7d7c72076e9c5c191551ec04c7a42897d6e1b8
C++
cms-sw/cmssw
/Geometry/CommonTopologies/interface/TkRadialStripTopology.h
UTF-8
9,871
2.703125
3
[ "Apache-2.0" ]
permissive
#ifndef _TkRADIAL_STRIP_TOPOLOGY_H_ #define _TkRADIAL_STRIP_TOPOLOGY_H_ #include "Geometry/CommonTopologies/interface/RadialStripTopology.h" /** * \class TkRadialStripTopology * A StripTopology in which the component strips subtend a constant * angular width, and, if projected, intersect at a point. * * \author Tim Cox * * WARNING! Wherever 'float strip' is used the units of 'strip' are angular * widths of each strip. The range is from 0.0 at the extreme edge of the * 'first' strip at one edge of the detector, to nstrip*angular width * at the other edge. <BR> * The centre of the first strip is at strip = 0.5 <BR> * The centre of the last strip is at strip = 0.5 + (nstrip-1) <BR> * This is for consistency with CommonDet usage of 'float strip' (but * where units are strip pitch rather than strip angular width.)<BR> * * WARNING! If the mid-point along local y of the plane of strips does not correspond * to the local coordinate origin, set the final ctor argument appropriately. <BR> * * this version is optimized for tracker and is FINAL */ class TkRadialStripTopology final : public RadialStripTopology { public: /** * Constructor from: * \param ns number of strips * \param aw angular width of a strip * \param dh detector height (usually 2 x apothem of TrapezoidalPlaneBounds) * \param r radial distance from symmetry centre of detector to the point at which * the outer edges of the two extreme strips (projected) intersect. * \param yAx orientation of local y axis: 1 means pointing from the smaller side of * the module to the larger side (along apothem), and -1 means in the * opposite direction, i.e. from the larger side along the apothem to the * smaller side. Default value is 1. * \param yMid local y offset if mid-point of detector (strip plane) does not coincide with local origin. * This decouples the extent of strip plane from the boundary of the detector in which the RST is embedded. */ TkRadialStripTopology(int ns, float aw, float dh, float r, int yAx = 1, float yMid = 0.); /** * Destructor */ ~TkRadialStripTopology() override {} // ========================================================= // StripTopology interface - implement pure methods // ========================================================= /** * LocalPoint on x axis for given 'strip' * 'strip' is a float in units of the strip (angular) width */ LocalPoint localPosition(float strip) const override; /** * LocalPoint for a given MeasurementPoint <BR> * What's a MeasurementPoint? <BR> * In analogy with that used with TrapezoidalStripTopology objects, * a MeasurementPoint is a 2-dim object.<BR> * The first dimension measures the * angular position wrt central line of symmetry of detector, * in units of strip (angular) widths (range 0 to total angle subtended * by a detector).<BR> * The second dimension measures * the fractional position along the strip (range -0.5 to +0.5).<BR> * BEWARE! The components are not Cartesian.<BR> */ LocalPoint localPosition(const MeasurementPoint&) const override; /** * LocalError for a pure strip measurement, where 'strip' * is the (float) position (a 'phi' angle wrt y axis) and * stripErr2 is the sigma-squared. Both quantities are expressed in * units of theAngularWidth of a strip. */ LocalError localError(float strip, float stripErr2) const override; /** * LocalError for a given MeasurementPoint with known MeasurementError. * This may be used in Kalman filtering and hence must allow possible * correlations between the components. */ LocalError localError(const MeasurementPoint&, const MeasurementError&) const override; /** * Strip in which a given LocalPoint lies. This is a float which * represents the fractional strip position within the detector.<BR> * Returns zero if the LocalPoint falls at the extreme low edge of the * detector or BELOW, and float(nstrips) if it falls at the extreme high * edge or ABOVE. */ float strip(const LocalPoint&) const override; // the number of strip span by the segment between the two points.. float coveredStrips(const LocalPoint& lp1, const LocalPoint& lp2) const override; /** * Pitch (strip width) at a given LocalPoint. <BR> * BEWARE: are you sure you really want to call this for a RadialStripTopology? */ float localPitch(const LocalPoint&) const override; /** * Angle between strip and symmetry axis (=local y axis) * for given strip. <BR> * This is like a phi angle but measured clockwise from y axis * rather than counter clockwise from x axis. * Note that 'strip' is a float with a continuous range from 0 to * float(nstrips) to cover the whole detector, and the centres of * strips correspond to half-integer values 0.5, 1.5, ..., nstrips-0.5 * whereas values 1, 2, ... nstrips correspond to the upper phi edges of * the strips. */ float stripAngle(float strip) const override { return yAxisOrientation() * (phiOfOneEdge() + strip * angularWidth()); } /** * Total number of strips */ int nstrips() const override { return theNumberOfStrips; } /** * Height of detector (= length of long symmetry axis of the plane of strips). */ float stripLength() const override { return theDetHeight; } /** * Length of a strip passing through a given LocalPpoint */ float localStripLength(const LocalPoint&) const override; // ========================================================= // Topology interface (not already implemented for // StripTopology interface) // ========================================================= MeasurementPoint measurementPosition(const LocalPoint&) const override; MeasurementError measurementError(const LocalPoint&, const LocalError&) const override; /** * Channel number corresponding to a given LocalPoint.<BR> * This is effectively an integer version of strip(), with range 0 to * nstrips-1. <BR> * LocalPoints outside the detector strip plane will be considered * as contributing to the edge channels 0 or nstrips-1. */ int channel(const LocalPoint&) const override; // ========================================================= // RadialStripTopology interface itself // ========================================================= /** * Angular width of a each strip */ float angularWidth() const override { return theAngularWidth; } /** * Phi pitch of each strip (= angular width!) */ float phiPitch(void) const override { return angularWidth(); } /** * Length of long symmetry axis of plane of strips */ float detHeight() const override { return theDetHeight; } /** * y extent of strip plane */ float yExtentOfStripPlane() const override { return theDetHeight; } // same as detHeight() /** * Distance from the intersection of the projections of * the extreme edges of the two extreme strips to the symmetry * centre of the plane of strips. */ float centreToIntersection() const override { return theCentreToIntersection; } /** * (y) distance from intersection of the projections of the strips * to the local coordinate origin. Same as centreToIntersection() * if symmetry centre of strip plane coincides with local origin. */ float originToIntersection() const override { return (theCentreToIntersection - yCentre); } /** * Convenience function to access azimuthal angle of extreme edge of first strip * measured relative to long symmetry axis of the plane of strips. <BR> * * WARNING! This angle is measured clockwise from the local y axis * which means it is in the conventional azimuthal phi plane, * but azimuth is of course measured from local x axis not y. * The range of this angle is * -(full angle)/2 to +(full angle)/2. <BR> * where (full angle) = nstrips() * angularWidth(). <BR> * */ float phiOfOneEdge() const override { return thePhiOfOneEdge; } /** * Local x where centre of strip intersects input local y <BR> * 'strip' should be in range 1 to nstrips() <BR> */ float xOfStrip(int strip, float y) const override; /** * Nearest strip to given LocalPoint */ int nearestStrip(const LocalPoint&) const override; /** * y axis orientation, 1 means detector width increases with local y */ float yAxisOrientation() const override { return theYAxisOrientation; } /** * Offset in local y between midpoint of detector (strip plane) extent and local origin */ float yCentreOfStripPlane() const override { return yCentre; } /** * Distance in local y from a hit to the point of intersection of projected strips */ float yDistanceToIntersection(float y) const override; private: int theNumberOfStrips; // total no. of strips in plane of strips float theAngularWidth; // angle subtended by each strip = phi pitch float theAWidthInverse; // inverse of above float theTanAW; // its tangent float theDetHeight; // length of long symmetry axis = twice the apothem of the enclosing trapezoid float theCentreToIntersection; // distance centre of detector face to intersection of edge strips (projected) float thePhiOfOneEdge; // local 'phi' of one edge of plane of strips (I choose it negative!) float theTanOfOneEdge; // the positive tangent of the above... float theYAxisOrientation; // 1 means y axis going from smaller to larger side, -1 means opposite direction float yCentre; // Non-zero if offset in local y between midpoint of detector (strip plane) extent and local origin. double theRadialSigma; // radial sigma^2( uniform prob density along strip) }; #endif
true
e389f4362a94611d51d528ee1d2b00b0f7368d30
C++
yerson001/mycpp
/oop/p14_multiple_files/main.cpp
UTF-8
301
3.296875
3
[]
no_license
#include "add_and_sum.h" #include <iostream> int main(){ std::vector<int> a{1,2,3,4,5}; std::cout << "Orignal vector: "; for (auto i: a){ std::cout << i << " "; } std::cout <<"\n"; std::cout << "Add 1 to each element and sum the vector: "<< AddAndSum(a) << "\n"; }
true
700b5851953d841322477edfe1b31d0fb160a0b1
C++
Ras-al-Ghul/SPOJ
/PRISMSA.cpp
UTF-8
408
2.5625
3
[]
no_license
// diff. S formula with respect to a and substitue for h using V and a // diff. = 0, solve for a // plug a in S formula written only in terms of a #include <iostream> #include <cmath> using namespace std; int main(){ int t; scanf("%d", &t); double vol, S, a; while(t--){ scanf("%lf", &vol); a = pow(4*vol,0.3333333333333333333333333); S = 3*a*a*sqrt(3)/2; printf("%.10lf\n", S); } return 0; }
true
d42100ceb01783e9e470744f898a8a87b7950e7b
C++
Moenya1030/CPPStudyCode
/作业/lab10/Lab10_1.cpp
GB18030
1,589
3.84375
4
[]
no_license
//һΪLab10_1.cpp ʵҪ //aһΪMatrixľ࣬洢һάdouble飬Լȡ //bͨ+ʵ֮ͬĵ+㣬C=A+B //cͨ<<ʹÿͨʾcout<<CʾC #include<iostream> #include<string.h> using namespace std; class Matrix; ostream& operator<<(ostream &out,const Matrix &m); class Matrix { public: Matrix(int r=0,int c=0); void setMatrix(int r=0,int c=0); Matrix operator+(const Matrix &m) const; friend ostream& operator<<(ostream &out,const Matrix &m); private: double elements[100][100]; int row,col; }; Matrix::Matrix(int r,int c):row(r),col(c) { for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { cin>>elements[i][j]; } } } void Matrix::setMatrix(int r,int c) { row=r; col=c; for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { cin>>elements[i][j]; } } } Matrix Matrix::operator+(const Matrix &m) const { Matrix m1; for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { m1.elements[i][j]=elements[i][j]+m.elements[i][j]; } } m1.row=row; m1.col=col; return m1; } ostream& operator<<(ostream &out,const Matrix &m) { int i,j; for(i=0;i<m.row;i++) { for(j=0;j<m.col;j++) { out<<m.elements[i][j]<<" "; } out<<endl; } return out; } int main() { Matrix m1(4,5),m2(4,5); cout<<"\nm1+m2:\n"<<m1+m2<<endl; return 0; }
true
92cc00f2c4e144e53542e2f22ad9d59f08c4d134
C++
RBrNx/GED-RPG-Coursework
/RPG Coursework/gameOverState.cpp
UTF-8
1,883
2.796875
3
[]
no_license
#include "gameOverState.h" #include "statePlay.h" #include "game.h" #include "stateBattle.h" gameOverState::gameOverState() { textFont = TTF_OpenFont("MavenPro-Regular.ttf", 36); //init font gameOverText = new Label(); gameWinText = new Label(); battleWinText = new Label(); gameWinText->textToTexture("You have won the game!",textFont); battleWinText->textToTexture("You won the battle!",textFont); gameOverText->textToTexture("Game Over",textFont); //set up label } void gameOverState::Draw(SDL_Window * window) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.4f, 0.4f, 0.4f, 0.0f); //grey background if(((StateBattle *)battleState)->GetPlayerDead() == true){ gameOverText->draw(-0.8f,0.0f); }else if(((StatePlay *)PlayState)->GetMonsterCount() == 0){ gameWinText->draw(-0.8f,0.0f); }else if(((StateBattle *)battleState)->GetMonsterDead() == true){ battleWinText->draw(-0.8f,0.0f); //draw label } SDL_GL_SwapWindow(window); } void gameOverState::Enter() { } void gameOverState::Exit() { } bool gameOverState::GetContinuable() { return 0; } bool gameOverState::GetGameStarted() { return 0; } void gameOverState::SetGameStarted() { } void gameOverState::Init(Game * context) { } void gameOverState::Init(Game &context) { } void gameOverState::Update(Game &context){ } void gameOverState::HandleSDLEvent(SDL_Event const &sdlEvent, Game &context) { if(sdlEvent.type == SDL_KEYDOWN) { if(((StateBattle *)battleState)->GetMonsterDead() == true){ context.setState(PlayState);//go back to playstate after a win } if(((StateBattle *)battleState)->GetPlayerDead() == true){ context.setState(stateMenu); //go back to main menu after a loss } if(((StatePlay *)PlayState)->GetMonsterCount() == 0){ context.setState(stateMenu); //go back to main menu after a loss } } } gameOverState::~gameOverState(){ }
true
7105db9e29eeb0fed91d12c0fc35f880b1e6c529
C++
cca-company/BattleShip
/BattleShip/GameManager.h
UHC
763
2.59375
3
[]
no_license
#pragma once #include "stdafx.h" #include "Player.h" #include "Render.h" class GameManager { public: /* initialize function */ GameManager(); ~GameManager(); void StartGame(); // մϴ int StartSoloPlay(); // ¶ ÷̸ մϴ int StartNetworkPlay(); // ¶ ÷̸ մϴ protected: Network ConnectNetwork(); // ¶ ÷̸ Ʈũ մϴ void InitGame(PlayerType playerType1, PlayerType playerType2); // ʱȭմϴ void InitNetworkGame(Network network); // Ʈũ ʱȭմϴ protected: Player* m_Player1; Player* m_Player2; Render m_Render; int m_PlayTurn; };
true
b0ae86333e9a86ddfbcbc29e459fc1b5a25a8e1f
C++
Manuel1426/my-teaching-materials
/by-language/cpp/cpp-oo/templates/workshop/07.cpp
UTF-8
191
2.671875
3
[]
no_license
#include <iostream> #include <string> using namespace std; int main() { //Create a simple class template which contains 2 item and has both a get and a set method for these! return 0; }
true
85362a0f6fecc089c77371a7c51bf5d65ac65517
C++
qhpark/compiler-adacs
/ringbuffer.hpp
UTF-8
801
3.109375
3
[]
no_license
#ifndef __RINGBUFFER_HPP_ #define __RINGBUFFER_HPP_ class RingBuffer { public: RingBuffer(); // give size. RingBuffer(int bytes); ~RingBuffer(); // get last position //int get_last_pos(); // return how much buffer is used. int num_stored(); // return how much more is left to read int num_unread(); // return how much more space is left int num_free(); // get c-style string, this updates start_position. char *flush_str(int end_position); // add a character at the end // returns the updates position int add_char(char c); // get a character from the start_pos // and advances every time it's called. // returns current position int get_char(char &c); private: char *buffer, *buf; int size, stored, free; int start_pos, read; }; #endif
true
1b306efb3448669f2de5f6b30d89ec24bb0fab33
C++
buglog/desert-stalker
/Engine/Spike.h
UTF-8
592
3.0625
3
[]
no_license
#pragma once #include "Vampire.h" class Spike { //spikes are 10 pixels wide each. these spikes extrude to a length of 15 pixels. public: void init(int setx, int sety, int setlength); //choose your direction of spikes. each function draws, blocks, and kills the vamp all by itself. void floor(Vampire& vamp, Graphics& gfx); void top(Vampire& vamp, Graphics& gfx); void left(Vampire& vamp, Graphics& gfx); void right(Vampire& vamp, Graphics& gfx); public: int x; int y; int length = 10; private: static constexpr int width = 10; static constexpr int height = 15; Sprite sprite; };
true
57cd8aefd18537c099d965ccea7ce794ba536508
C++
MohammadMoeinKeyvani/ArkanoidGame
/Engine/Paddle.h
UTF-8
557
2.8125
3
[]
no_license
#pragma once #include "Vec2.h" #include "Ball.h" #include "Colors.h" #include "Keyboard.h" class Paddle { public: Paddle(Vec2 inputPos, float inputHalfWidt, float inputHalfHeight); bool DoBallCollision(Ball& ball) const; void DoWallCollision(const Rect wall); void Update(float deltaTime, Keyboard& keyboard); void Draw(Graphics& gfx); Rect GetRectangle() const; private: Vec2 position; Color color = Colors::LightGray; float halfWidth; float halfHeight; float speed = 200; float margin = halfWidth / 5.0f; Color marginColor = Colors::Red; };
true
5b282f5db104c79d232c45f21ff8d19bc53bffae
C++
yielding/code
/cpp.fp/io.monad/optional.cpp
UTF-8
1,101
3.625
4
[]
no_license
#include <iostream> #include <functional> using namespace std; template<class T> class optional { public: optional() : _isValid(false) {} // Nothing optional(T x) : _isValid(true) , _v(x) {} // Just auto isValid() const { return _isValid; } auto val() const { return _v; } template <typename R> auto fmap(function<R(T)>& f) -> optional<R> { return isValid() ? optional<R> { f(_v) } : optional<R> {}; } private: bool _isValid; // the tag T _v; }; template <typename A, typename B> auto fmap(function<B(A)> f) -> function<optional<B>(optional<A>)> { return [f](optional<A> opt) { return opt.isValid() ? optional<B> { f(opt.val()) } : optional<B> {}; }; } template <typename A, typename B> auto fmap(function<B(A)> f, optional<A> opt) -> optional<B> { return opt.isValid() ? optional<B> { f(opt.val()) } : optional<B> { }; } int main(int argc, char *argv[]) { optional<int> a(2); optional<int> b(4); function<int(int)> f = [](int i) -> int { return i*i; }; auto b = a.fmap(f); cout << b.val(); return 0; }
true
a41c04b68f7941095eaa8908862ae68ea6544dad
C++
Mauricioduque/Proyecto_final
/Rabbits_Adventures/jabalienemigo.cpp
UTF-8
2,222
2.5625
3
[]
no_license
/* Proyecto: Rabbit's Adventures Creado por: Laura Isabel Vidal - Mauricio Duque Informática II Facultad de Ingeniería Departamento de Electrónica y Telecomunicaciones Universidad de Antioquia Clase Jabali Enemigo: objeto del segundo mundo, que se desplaza en determina seccion y se encuentra asociado a un timer, si el conejo colisiona con este puede perder una de sus vidas */ #include "jabalienemigo.h" #include "ppconejo.h" //se carga la imagen y se inicia el timer asociado JabaliEnemigo::JabaliEnemigo(int inicio,int fin,QGraphicsItem *parent) : QGraphicsItem(parent) { direccion = -1; inicioPos=inicio; finPos=fin; setFlag(ItemClipsToShape); sprite = QPixmap(":/jabali.png"); QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(nextSprite())); timer->start(50); } //Variación del sprite que esta asociada al timer(SLOT) y verifica la colisión void JabaliEnemigo::nextSprite() { //Manejo de Sprites //Distancia en caada sprite posSprite += 100; //Condicion volver al primer sprite, si sobre pasa la dimension la imagen plana if(posSprite >= 800) { posSprite = 0; } if(this->pos().x() < inicioPos|| this->pos().x() >= finPos) { direccion = -direccion; setTransform(QTransform(direccion, 0, 0, 1, 0, 0)); } setPos(this->pos().x() + (direccion*7), this->pos().y()); QList<QGraphicsItem *> colliding_items = collidingItems(); //If one of the colliding items is an Enemy, destroy both the bullet and the enemy for (int i = 0, n = colliding_items.size(); i < n; ++i){ if (typeid(*(colliding_items[i])) == typeid(PPConejo)){ emit estadoJuego(2); return; } } } //se crea la margen del objeto QRectF JabaliEnemigo::boundingRect() const { return QRectF(0,0,98,100); } //Se dibuja el objeto en la escena a partir del sprite void JabaliEnemigo::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { painter->drawPixmap(0,0, sprite, posSprite, 0,100, 100); setTransformOriginPoint(boundingRect().center()); Q_UNUSED(widget) Q_UNUSED(option) } int JabaliEnemigo::type() const { return Type; }
true
24b490a6bb0c23e9cef64664d311491bde5497ba
C++
scipianus/Algorithm-contests
/CodeForces/MemSQL Start[c]UP 2.0 Round 1/A/A.cpp
UTF-8
559
2.734375
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; int n, m; char s[100]; string nume[8] = {"vaporeon", "jolteon", "flareon", "espeon", "umbreon", "leafeon", "glaceon", "sylveon"}; int main() { int i, j; bool ok; std::ios_base::sync_with_stdio(false); cin >> n; cin >> s; for(i = 0; i < 8; ++i) { m = nume[i].length(); if(n != m) continue; ok = true; for(j = 0; j < n; ++j) { if(s[j] == '.') continue; if(s[j] != nume[i][j]) ok = false; } if(ok) { cout << nume[i] << "\n"; return 0; } } return 0; }
true
c77c872e31ea4d18e0e27cf5031cfec22aa565e0
C++
Fatnerdfy/Monopoly
/Richers2/Richers2/game.cpp
UTF-8
1,694
2.84375
3
[]
no_license
// // game.cpp // Richers2 // // Created by CQQ on 2017/9/24. // Copyright © 2017年 CQQ. All rights reserved. // #include <iostream> using namespace std; #include "game.h" #include "menu.h" Game * Game::game = nullptr; Game * Game::getInstance() { if (game == nullptr) { int gid = 1; GameFactory * gf = new GameFactory; game = gf->createGame(gid); } return game; } Game::Game() { } Game::~Game() { } void Game::init() { mnuCur = Menu::getInstance(MenuID::MENU_MAIN); nCountPlayers = 2; //默认2个玩家(电脑和用户) nVolume = 50; nResolutionX = 1024; nResolutionY = 768; } void Game::run() { bool goon = true; while(goon) { goon = mnuCur->process(Game::getInstance()) ; } } void Game::term() { Menu::releaseAllMenus(); } void Game::setMenu(Menu * menu) { mnuCur = menu; } void Game::setPlayersCount(int num) { nCountPlayers = num; cout << "Set number of players = " << nCountPlayers << endl; } void Game::loadRecord(int recID) { cout << "Loading record with id=" << recID << endl; } void Game::saveRecord(int recID) { cout << "Saving to record with id=" << recID << endl; } void Game::setVolume(int vol) { nVolume = vol; cout << "Set Volume to " << vol << endl; } void Game::setResolution(int xres, int yres) { nResolutionX = xres; nResolutionY = yres; cout << "Set Resolution to " << nResolutionX << " X " << nResolutionY << endl; } Game * GameFactory::createGame(int gid) { switch (gid) { case 1: return new Game(); break; default: return new Game(); break; } }
true
a3469918ab3978195a64137a3c40306c0f37b259
C++
shifushihuaidan/op11
/C++/测试.cpp
GB18030
405
2.75
3
[ "MIT" ]
permissive
#include<iostream> using namespace std; #include <ctime> #include<windows.h> int main () { SYSTEMTIME sysTime; ZeroMemory(&sysTime, sizeof(sysTime)); GetLocalTime(&sysTime); cout << "ʱΪ" << sysTime.wYear << "" << sysTime.wMonth << "" <<sysTime.wDay<<""<<endl; cout <<sysTime.wHour << "ʱ" <<sysTime.wMinute << "" << sysTime.wSecond <<""<<endl; return 0; }
true
eccae618077e0a990f82edfdf9d694bda38a7e59
C++
RuslanArkh/PatientsApp
/photodao.cpp
UTF-8
2,517
2.78125
3
[]
no_license
#include "photodao.h" #include "photo.h" #include "dbmanager.h" #include "dbmanager_exceptions.h" #include <QSqlDatabase> #include <QSqlQuery> #include <QString> PhotoDao::PhotoDao(QSqlDatabase & database) : mDatabase(database) { } void PhotoDao::init() const { if (!mDatabase.tables().contains("photo")) { QSqlQuery query(mDatabase); query.exec("CREATE TABLE photo (id INTEGER PRIMARY KEY," "patient_id INTEGER," "filename TEXT," "image_data BLOB," "created_on TEXT," "FOREIGN KEY (patient_id) REFERENCES patient(id) ON DELETE CASCADE);"); } } void PhotoDao::addPhoto(const Photo &photo) const { QSqlQuery query(mDatabase); query.prepare("INSERT INTO photo" "(patient_id, filename, image_data, created_on) " "VALUES(:patient_id, :filename, :image_data, :created_on)"); query.bindValue(":patient_id", photo.GetPatientId()); query.bindValue(":filename", photo.GetFileName()); query.bindValue(":image_data", photo.GetImageBytes()); query.bindValue(":created_on", photo.GetCreationDate()); if (!query.exec()) DBManagerEx::SqlQueryFailed(query.lastError()).raise(); photo.SetId(query.lastInsertId().toInt()); } void PhotoDao::removePhoto(int id) const { QSqlQuery query(mDatabase); query.prepare("DELETE FROM photo WHERE id = (:id)"); query.bindValue(":id", id); if (!query.exec()) DBManagerEx::SqlQueryFailed(query.lastError()).raise(); } std::vector<Photo *> * PhotoDao::photosByPatientId(int id) const { QSqlQuery query(mDatabase); query.prepare("SELECT * FROM photo WHERE patient_id=(:patient_id)"); query.bindValue(":patient_id", id); if (query.exec()) { std::vector<Photo *> * photos = new std::vector<Photo *>; while (query.next()) { int temp_id = query.value(0).toInt(); int temp_patient_id = query.value(1).toInt(); QString temp_filename = query.value(2).toString(); QPixmap temp_pixmap = QPixmap(); temp_pixmap.loadFromData(query.value(3).toByteArray()); QDate temp_created_on = query.value(4).toDate(); Photo * p = new Photo(temp_patient_id, temp_filename, temp_pixmap, temp_created_on); p->SetId(temp_id); photos->push_back(p); } return photos; } else { // TODO: Exception return nullptr; } }
true
90c97dc407a3249ec97cc5405c6f0e06f27a3ff9
C++
ElSpato/Funciones
/Funciones y subrutinas/ejercicio10.cpp
UTF-8
1,776
3.046875
3
[]
no_license
#include<iostream> #include<conio.h> using namespace std; void matrizA(); int main(){ matrizA(); getch(); return 0; } void matrizA(){ int a[20][20],b[20][20],c[20][20]; int k,m,n; cout<<"\t.:Matriz A:."<<endl; do { cout<<"Filas de A: "; cin>>k; cout<<"Columnas de A: "; cin>>m; if(k < 0 || m <0){ cout<<"\nError"<<endl; } cout<<"\n"; } while(k<0 || m<0); for(int i=0;i<k;i++) { for(int j=0;j<m;j++) { cout<<"Digite el valor para A["<<i<<"]["<<j<<"]: "; cin>>a[i][j]; } } cout<<"\n"; cout<<"\t.:Matriz B:."<<endl; do { cout<<"Filas de B: "; cin>>m; cout<<"Columnas de B: "; cin>>n; if(m < 0 || n <0){ cout<<"\nError"<<endl; } cout<<"\n"; } while(m<0 || n<0); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cout<<"Digite el valor para B["<<i<<"]["<<j<<"]: "; cin>>b[i][j]; } } for(int i=0;i<k;i++) { for(int j=0;j<n;j++) { c[i][j]=0; } } for(int i=0;i<k;i++) { for(int j=0;j<n;j++) { for(int z=0;z<m;z++) { c[i][j] += a[i][z] * b[z][j]; } } } cout<<"\n\t.:La Matriz A:."<<endl; for(int i=0;i<k;i++) { for(int j=0;j<m;j++) { cout<<a[i][j]<<" "; } cout<<"\n"; } cout<<"\n\t.:La Matriz B:."<<endl; for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { cout<<b[i][j]<<" "; } cout<<"\n"; } cout<<"\n\t.:La Matriz C:."<<endl; for(int i=0;i<k;i++) { for(int j=0;j<n;j++) { cout<<c[i][j]<<" "; } cout<<"\n"; } }
true
ac67447ec7bae6564807b496c7b8c01b4def8bec
C++
NarouMas/ZeroJudge
/c123 00514 - Rails.cpp
UTF-8
868
2.59375
3
[]
no_license
#include<iostream> #include<stack> using namespace std; int main() { stack<int> st; int n,a[1005],t,pushn; bool dis; while(cin>>n) { if(n==0) break; cin>>a[0]; while(a[0]!=0) { for(int i=1;i<n;i++) cin>>a[i]; while(st.size()!=0) st.pop(); st.push(1); t=0,pushn=2,dis=true; while(st.size()!=0&&dis) { if(st.top()==a[t]) { //cout<<"pop:"<<st.top()<<endl; st.pop(); t++; if(st.size()==0&&pushn<=n) { //cout<<"in push:"<<pushn<<endl; st.push(pushn); pushn++; } } if(st.size()>0) { if(st.top()!=a[t]&&pushn<=n) { //cout<<"out push:"<<pushn<<endl; st.push(pushn); pushn++; } else if(st.top()!=a[t]) { dis=false; } } } if(dis) cout<<"Yes\n"; else cout<<"No\n"; cin>>a[0]; } } }
true
213b28594fb1f5fee1394ec1af69341273fbab2c
C++
JZZQuant/genneteq
/gennet/graph.h
UTF-8
3,513
2.875
3
[]
no_license
/*****************************************************************************/ /* Author: Jason Sauppe */ /* Date: 2010-06-16 */ /* File: graph.h */ /* Description: */ /* Contains design details for a custom graph class. */ /*****************************************************************************/ #ifndef GRAPH_H #define GRAPH_H // Required include's #include <vector> using std::vector; #include <string> using std::string; const int NODE_IND_OFFSET = 1; const int EQF_IND_OFFSET = 1; // Forward Declarations struct Config; template <typename T> class Matrix; struct GraphNode { int id; int index; double supply; }; class Graph { public: Graph(); ~Graph(); void initialize(Config *conf); void print() const; void exportColFile(const char *colFileOut) const; void exportDatFile(const char *datFileOut) const; // Inlined functions int getNumNodes() const; int getNumArcs() const; int getNumEqualFlowSets() const; double getBigM() const; double supply(int i) const; double cost(int i, int j) const; double capacity(int i, int j) const; double multiplier(int i, int j) const; int equalFlowIndex(int i, int j) const; double equalFlowNodeValue(int i, int r) const; protected: // Variables int numNodes; int numArcs; int numEqualFlowSets; double totalSupply; double maxArcCost; double maxArcCapacity; double bigM; vector<GraphNode *> nodes; Matrix<double> arcCosts; Matrix<double> arcCapacities; Matrix<double> arcMultipliers; Matrix<int> eqFlowSetIndices; Matrix<double> eqFlowNodeValues; // Functions void initializeDataStructures(); void addSelfLoops(); void addSelfLoop(int i); void readColFile(const char *filename); void readGSFile(const char *filename); void processProblemLine(string nextLine); void processEdgeLine(string nextLine); void processArcLine(string nextLine); void processNodeLine(string nextLine); void processCommentLine(string nextLine); void parseGSArcLine(string nextLine); void parseGSEqualFlowLine(string nextLine, int eqFlowNum); private: // Nothing }; /*****************************************************************************/ /* Inline function declarations */ /*****************************************************************************/ inline int Graph::getNumNodes() const { return numNodes; } inline int Graph::getNumArcs() const { return numArcs; } inline int Graph::getNumEqualFlowSets() const { return numEqualFlowSets; } inline double Graph::getBigM() const { return bigM; } inline double Graph::supply(int i) const { return nodes[i]->supply; } inline double Graph::cost(int i, int j) const { return arcCosts.get(i, j); } inline double Graph::capacity(int i, int j) const { return arcCapacities.get(i, j); } inline double Graph::multiplier(int i, int j) const { return arcMultipliers.get(i, j); } inline int Graph::equalFlowIndex(int i, int j) const { return eqFlowSetIndices.get(i, j); } inline double Graph::equalFlowNodeValue(int i, int r) const { return eqFlowNodeValues.get(i, r); } #endif // GRAPH_H
true
705ddc388d1e5044500d807a232c0422835846d6
C++
NicMen99/Jojo-Run
/Src/Entities/Obstacle.h
UTF-8
488
2.796875
3
[]
no_license
// // Created by Niccolo on 28/02/2021. // #ifndef JOJO_RUN_OBSTACLE_H #define JOJO_RUN_OBSTACLE_H #include "Entity.h" class Obstacle : public Entity { public: Obstacle(EntityType mtype, const std::string & name) : Entity(EntityGroup::Obstacle, mtype, name) { } ~Obstacle() override {}; void setDamage(int damage) { m_damage = damage; } int getDamage() const override { return m_damage; }; private: int m_damage = 0; }; #endif //JOJO_RUN_OBSTACLE_H
true
c40d73fb4e53132ac03d9fc02fe05d9d7575719a
C++
utt-zachery/ping-plus-plus
/flags/TTLFlag.h
UTF-8
600
2.828125
3
[]
no_license
#pragma once #include <string> #include "AbstractFlag.h" #include "../exceptions/SyntaxException.h" //Concrete flag class that allows users to execute a custom command if PING requests are systematically failing class TTLFlag : public AbstractFlag { public: TTLFlag(); //Default behavior will be set to 255. If the user passes in a command string and the threshold is reached, the command will be executed void parseCommand(int argc, const char ** arg); void setTTL(int toSet); int getTTL(); private: int customTTL; bool isNumber(const std::string& s); };
true
03e21bf4249dd4ccd8853a0a1bd032e1f8d55559
C++
Queuebee2/OS-buffer
/project/buffer.test.cpp
UTF-8
10,855
2.890625
3
[]
no_license
#include <gtest/gtest.h> #include <stdlib.h> #include <fcntl.h> #include <thread> #include <vector> using namespace std; // GTEST info message hack https://stackoverflow.com/a/48924764/6934388 #define GTEST_COUT_INFO std::cerr << "\033[33m" << "[ INFO ] " << "\033[37m" // declarations of methods you want to test (should match exactly) void bufferReset(); void writeLog(string msg, int position); void readLog(); void bufferAdd(int addition); int bufferReturnRemoved(); void bufferRemove(); void setBound(int requestSize); void toggleBounds(); // helpers from buffer to access member variables int getBufferSize(); int getLogSize(); int getValueAt(int ind); int getCurrentBound(); int getPrevBound(); string readLogAt(int ind); // int getCurrentIndex(); deprecated const int UNBOUNDED = -1; // TODO how to just use the same value from buffer.cpp instead of reinitializing here? const int AMT_TESTS = 10; const int AMT_ACTIONS = 100; const int AMT_HALF = 50; namespace { // helpers void taskWithInput(int number, void (*func)(int)){ for (int i = 0; i < AMT_ACTIONS; i++){ func(number); } } void taskNoInput(void (*f)()){ for (int i = 0; i < AMT_ACTIONS; i ++){ f(); } } void taskNoInputReturnInt(int (*f)()){ for (int i = 0; i < AMT_ACTIONS; i ++){ int r = f(); } } /* █████╗ ██████╗████████╗██╗ ██╗ █████╗ ██╗ ████████╗███████╗███████╗████████╗███████╗ ██╔══██╗██╔════╝╚══██╔══╝██║ ██║██╔══██╗██║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ███████║██║ ██║ ██║ ██║███████║██║ ██║ █████╗ ███████╗ ██║ ███████╗ ██╔══██║██║ ██║ ██║ ██║██╔══██║██║ ██║ ██╔══╝ ╚════██║ ██║ ╚════██║ ██║ ██║╚██████╗ ██║ ╚██████╔╝██║ ██║███████╗ ██║ ███████╗███████║ ██║ ███████║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚══════╝╚══════╝ ╚═╝ ╚══════╝ */ TEST(BufferBasic, bufferReset){ // mess starting values bufferReset(); // weird thing to do as this assumes it works correctly already. bufferAdd(10); toggleBounds(); // try reset bufferReset(); // confirm reset worked (nonexhaustive) EXPECT_EQ(getCurrentBound(), -1); EXPECT_EQ(getPrevBound(), -1); EXPECT_EQ(getBufferSize(), 0); EXPECT_EQ(getLogSize(), 0); } TEST(BufferBasic, bufferInitialSize){ bufferReset(); EXPECT_EQ(0,getBufferSize()); EXPECT_EQ(0,getLogSize()); } TEST(BufferBasic, toggleBounds){ bufferReset(); EXPECT_EQ(getCurrentBound(), UNBOUNDED); bufferReset(); toggleBounds(); EXPECT_EQ(getCurrentBound(), UNBOUNDED); bufferReset(); setBound(10); EXPECT_EQ(getCurrentBound(), 10); toggleBounds(); EXPECT_EQ(getCurrentBound(), UNBOUNDED); toggleBounds(); EXPECT_EQ(getCurrentBound(), 10); } TEST(BufferBasic, singleAdd){ int TESTVAL = 100; bufferReset(); bufferAdd(TESTVAL); EXPECT_EQ(getValueAt(0), TESTVAL); EXPECT_EQ(getBufferSize(), 1); } TEST(BufferBasic, singleRemove){ int TESTVAL = 100; bufferReset(); bufferAdd(TESTVAL); bufferRemove(); EXPECT_EQ(getBufferSize(), 0); } // renamed from testChangeBoundAdd TEST(BufferBasic, automaticBoundChange){ int TESTVAL1 = 100; int TESTVAL2 = 200; int TESTBOUND1 = 20; int TESTBOUND2 = 33; int TESTBOUND3 = 100; bufferReset(); thread t1(taskWithInput, TESTBOUND1, setBound); thread t2(taskWithInput, TESTVAL1, bufferAdd); thread t3(taskWithInput, TESTBOUND2, setBound); thread t4(taskWithInput, TESTBOUND3, setBound); thread t5(taskWithInput, TESTVAL2, bufferAdd); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); // TODO EXPECT_EQ... } TEST(BufferBasic, automaticBoundRestrict){ int TESTVAL1 = 100; int TESTVAL2 = 200; int TESTBOUND1 = 3; int TESTBOUND2 = 5; int TESTBOUND3 = 7; bufferReset(); thread t1(taskWithInput, TESTBOUND1, setBound); thread t2(taskWithInput, TESTVAL1, bufferAdd); thread t3(taskWithInput, TESTBOUND2, setBound); thread t4(taskWithInput, TESTBOUND3, setBound); thread t5(taskWithInput, TESTVAL2, bufferAdd); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); // check that the bufferBound is exactly one of the expected bound sizes int expected_size[] = {TESTBOUND1, TESTBOUND2, TESTBOUND3}; bool bBoundIsOfExpectedSize = find(begin(expected_size), end(expected_size), getCurrentBound()) != end(expected_size); EXPECT_EQ(bBoundIsOfExpectedSize, true); // check if the buffersize is at least lower than the max bound. // bool bBufferSizeWithinBounds = getBufferSize() < getCurrentBound(); int bufferSize = getBufferSize(); int curr_bound = getCurrentBound(); EXPECT_TRUE(bufferSize <= curr_bound); // expect amt_threads*amt_actions log entries int logSize = getLogSize(); int expectedLogSize = AMT_ACTIONS*5; EXPECT_TRUE(logSize == expectedLogSize); } TEST(BufferBasic, singleRemoveWithRetrieval){ int TESTVAL = 100; bufferReset(); bufferAdd(TESTVAL); int r = bufferReturnRemoved(); EXPECT_EQ(getBufferSize(), 0); EXPECT_EQ(r, TESTVAL); } TEST(Buffer, doubleAdd){ int TESTVAL1 = 100; int TESTVAL2 = 200; bufferReset(); bufferAdd(TESTVAL1); EXPECT_EQ(getValueAt(0), TESTVAL1); bufferAdd(TESTVAL2); EXPECT_EQ(getValueAt(1), TESTVAL2); } TEST(Buffer, maxValueAdd){ bufferReset(); bufferAdd(INT16_MAX); bufferAdd(INT32_MAX); // bufferAdd(INT64_MAX); EXPECT_EQ(getValueAt(0), INT16_MAX); EXPECT_EQ(getValueAt(1), INT32_MAX); // EXPECT_EQ(getValueAt(2), INT64_MAX); } TEST(Buffer, returnLastElementAfterBoundChange){ int TESTVAL1 = 100; int TESTVAL2 = 200; bufferReset(); bufferAdd(TESTVAL1); bufferAdd(TESTVAL1); bufferAdd(TESTVAL2); setBound(2); int r = bufferReturnRemoved(); EXPECT_EQ(r, TESTVAL1); } TEST(Buffer, minValueAddition){ bufferReset(); bufferAdd(INT16_MIN); bufferAdd(INT32_MIN); // bufferAdd(INT64_MIN); EXPECT_EQ(getValueAt(0), INT16_MIN); EXPECT_EQ(getValueAt(1), INT32_MIN); // EXPECT_EQ(getValueAt(2), INT64_MIN); } TEST(Buffer, dualAddition){ bufferReset(); thread firstRemover(taskWithInput, 1, bufferAdd); thread secondRemover(taskWithInput, 2, bufferAdd); firstRemover.join(); secondRemover.join(); // expect the amount of actions per thread times the amount of threads EXPECT_EQ(getBufferSize(), AMT_ACTIONS*2); } TEST(BufferConcurrency, dualConcurrentAddition){ bool flag1; bool flag2; int TESTVALUE_1 = 1; int TESTVALUE_2 = 2; for (size_t TEST_INDEX = 0; TEST_INDEX < AMT_TESTS; TEST_INDEX++) { // if (testsuccess == true){ // break; // } bufferReset(); setBound(AMT_ACTIONS); thread firstAdder(taskWithInput, TESTVALUE_1, bufferAdd); thread secondAdder(taskWithInput, TESTVALUE_2, bufferAdd); firstAdder.join(); secondAdder.join(); for (size_t i = 0; i < AMT_HALF; i++) { if (getValueAt(i) == TESTVALUE_1){ flag1 = true; }else if (getValueAt(i) == TESTVALUE_2){ flag2 = true; } } if (flag1 && flag2){ return SUCCEED(); } else { flag1 = false; flag2 = false; } } GTEST_COUT_INFO << "this test can fail by chance!" << endl; FAIL(); } TEST(BufferConcurrency, addAndRemoveEverything){ int TESTVALUE_1 = 1; int TESTVALUE_2 = 2; bufferReset(); // add 2 * AMT_ACTIONS values thread t1(taskWithInput, TESTVALUE_1, bufferAdd); thread t2(taskWithInput, TESTVALUE_2, bufferAdd); t1.join(); t2.join(); // remove 2 * AMT_ACTIONS values thread t3(taskNoInput, bufferRemove); thread t4(taskNoInput, bufferRemove); t3.join(); t4.join(); EXPECT_EQ(getBufferSize(), 0); } TEST(BufferConcurrency, addAndRemoveEverythingWithRetrieval){ int TESTVALUE_1 = 1; int TESTVALUE_2 = 2; bufferReset(); // add 2 * AMT_ACTIONS values thread t1(taskWithInput, TESTVALUE_1, bufferAdd); thread t2(taskWithInput, TESTVALUE_2, bufferAdd); t1.join(); t2.join(); // remove 2 * AMT_ACTIONS values thread t3(taskNoInputReturnInt, bufferReturnRemoved); thread t4(taskNoInputReturnInt, bufferReturnRemoved); t3.join(); t4.join(); EXPECT_EQ(getBufferSize(), 0); } TEST(BufferConcurrency, removeTooMany){ int TESTVAL = 100; bufferReset(); bufferAdd(TESTVAL); thread t1(taskNoInput, bufferRemove); thread t2(taskNoInput, bufferRemove); t1.join(); t2.join(); string expected = "added element " + to_string(TESTVAL) + " to buffer succesfully"; EXPECT_EQ(readLogAt(0), expected); EXPECT_EQ(getBufferSize(), 0); EXPECT_EQ(getLogSize(), (AMT_ACTIONS*2) + 1); // todo EXPECT_EQ for some values in log to see if the fails are logged correctly bool foundExpectedFailMsg = false; for (int i = 0; i < getLogSize() ; i++){ if (readLogAt(i).compare("failed removing element. Buffer empty") == 0){ foundExpectedFailMsg = true; break; } } EXPECT_TRUE(foundExpectedFailMsg); } TEST(BufferConcurrency, addAndRemove){ int TESTVAL1 = 100; int TESTVAL2 = 200; bufferReset(); thread t1(taskWithInput, TESTVAL1, bufferAdd); thread t2(taskWithInput, TESTVAL2, bufferAdd); thread t3(taskNoInput, bufferRemove); thread t4(taskNoInput, bufferRemove); t1.join(); t2.join(); t3.join(); t4.join(); EXPECT_EQ(getLogSize(), 4*AMT_ACTIONS); // todo: write EXPECT_EQs for log } }
true
81fa9fa3455b17840e83a67a965fc16e8ab5162a
C++
zielona9/PersonalBudget
/UserManager.h
UTF-8
880
2.828125
3
[]
no_license
#ifndef USERMANAGER_H #define USERMANAGER_H #include <iostream> #include <vector> #include "User.h" #include "SupportingMethods.h" #include "FileWithUsers.h" using namespace std; class UserManager { int idOfLoggedInUser; vector <User> users; FileWithUsers fileWithUsers ; bool doesLoginExists(string login); int getNewUserId(); User enterNewUserDetails(); public: UserManager(string fileNameWithUsers):fileWithUsers(fileNameWithUsers) { idOfLoggedInUser=0; users=fileWithUsers.getUsersFromFile(); }; void setIdOfLoggedInUser(int userId); bool isUserLoggedIn(); void userRegistration(); int userLogin(); void listAllUsers(); void changePasswordOfLoggedInUser(); void userLogout(); int getIdOfLoggedInUser(); char selectOptionFromMainMenu(); char selectOptionFromUserMenu(); }; #endif
true
8e9278a2f0ed03871293509d449fe71792158472
C++
kshvedov/PA8_CS122_DataAnalysis
/PA8_S2_K_Shvedov/DataAnalysis.cpp
UTF-8
1,817
3.453125
3
[]
no_license
#include "DataAnalysis.h" //empty constructor DataAnalysis::DataAnalysis() { } //empty destructor DataAnalysis::~DataAnalysis() { mCsvStream.close(); } //runs the analisys application void DataAnalysis::runAnalysis(void) { openFile(); readFile(); writeTrends(); } //opens the file stream void DataAnalysis::openFile(void) { mCsvStream.open("data.csv"); } //reads one line from the file void DataAnalysis::readLine(string &data, int &units, string &status) { string temp; getline(mCsvStream, temp, ','); if (!temp.empty()) { units = stoi(temp); getline(mCsvStream, data, ','); getline(mCsvStream, status, '\n'); } } //loops through the file until end of file and then prints both trees out in order void DataAnalysis::readFile(void) { string tdata, tstatus; int tunits = 0; getline(mCsvStream, tdata); while (!mCsvStream.eof()) { readLine(tdata, tunits, tstatus); insertIntoTrees(tdata, tunits, tstatus); } cout << "Sold Tree" << endl; mTreeSold.inOrderTraversal(); cout << endl << "Purchased Tree" << endl; mTreePurchased.inOrderTraversal(); } //checks data and inserts in the right tree void DataAnalysis::insertIntoTrees(string data, int units, string status) { if (status == "Sold") { mTreeSold.insert(data, units); } else if (status == "Purchased") { mTreePurchased.insert(data, units); } } //writes the trends from the trees void DataAnalysis::writeTrends(void) { cout << endl << "Least Sold" << endl; mTreeSold.findSmallest().printData(); cout << "Most Sold" << endl; mTreeSold.findLargest().printData(); cout << endl << endl << "Least Purchased" << endl; mTreePurchased.findSmallest().printData(); cout << "Most Purchased" << endl; mTreePurchased.findLargest().printData(); }
true