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
fba123d9b8d8dc43527ac3997741fc5baeb720cd
C++
ndhuanhuan/16_coding_practice
/1201-1400/1381. Design a Stack With Increment Operation.cpp
UTF-8
642
3.34375
3
[]
no_license
// https://zxi.mytechroad.com/blog/stack/leetcode-1381-design-a-stack-with-increment-operation/ class CustomStack { public: CustomStack(int maxSize): max_size_(maxSize) {} void push(int x) { if(data_.size() == max_size_) return; data_.push_back(x); } int pop() { if(data_.size() == 0) return -1; int val = data_.back(); data_.pop_back(); return val; } void increment(int k, int val) { for(int i=0; i < min(static_cast<size_t>(k), data_.size()); ++i) { data_[i] += val; } } private: int max_size_; vector<int> data_; };
true
c2a68d8e0c53f389d25dd06603387c4573cd6337
C++
ThoseBygones/ACM_Code
/HDU/HDU 2159.cpp
GB18030
1,071
2.515625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int a[105],b[105]; int dp[105][105]; //iɱjֻԺܻõྭֵ int n,m,k,s; //άñ int main() { while(~scanf("%d%d%d%d",&n,&m,&k,&s)) { memset(dp,0,sizeof(dp)); for(int i=1; i<=k; i++) scanf("%d%d",&a[i],&b[i]); for(int i=1; i<=k; i++) { for(int j=b[i]; j<=m; j++) //ܴm->b[i]ԽӰ { for(int l=1; l<=s; l++) dp[j][l]=max(dp[j][l],dp[j-b[i]][l-1]+a[i]); } } if(dp[m][s]>=n) //ɱַʽܹõľֵҪ { for(int i=1; i<=m; i++) { if(dp[i][s]>=n) //ͶȱԽԽ { printf("%d\n",m-i); break; } } } else puts("-1"); } return 0; }
true
23ea356d8210057733e993783b9374ea6555126e
C++
camolezi/MinecraftCpp-OpenGL
/MinecraftC++/Sources/terrainRenderer.cpp
UTF-8
9,202
2.546875
3
[ "MIT" ]
permissive
#include <terrainRenderer.hpp> terrainRenderer::terrainRenderer(int size, glm::vec3 renderPosStart) : cubes(terrainRenderer::compareInMap) { this->size = size; loadSize = 900; renderPos = renderPosStart; generateSurfaceTerrain(); renderPosX = renderPos.x; renderPosY = renderPos.y; renderPosZ = renderPos.z; frameCounter = 0; drawBufferActive = false; this->loadThread = new std::thread(&terrainRenderer::loadCubes,this); //loadCubes(); } void terrainRenderer::draw(){ renderPosX = renderPos.x; renderPosY = renderPos.y; renderPosZ = renderPos.z; loadMutex.lock(); renderer.drawCubes(grassBlocks2.size(), &grassBlocks2.front() ,cubetype::grass); renderer.drawCubes(sandBlocks2.size(),&sandBlocks2.front(),cubetype::sand); renderer.drawCubes(woodBlocks2.size(), &woodBlocks2.front() ,cubetype::wood); renderer.drawCubes(leaveBlocks2.size(), &leaveBlocks2.front() ,cubetype::treeGrass); renderer.drawCubes(waterBlocks2.size(),&waterBlocks2.front(),cubetype::water); loadMutex.unlock(); frameCounter++; } void terrainRenderer::loadCubes(){ while(true){ int startRenderX = renderPosX - size/2; int endRenderX = renderPosX + size/2; int startRenderZ = renderPosZ - size/2; int endRenderZ = renderPosZ + size/2; auto initialIt = cubes.lower_bound(glm::vec3(startRenderX,0.0,startRenderZ)); auto it = initialIt; sandBlocks.clear(); grassBlocks.clear(); woodBlocks.clear(); leaveBlocks.clear(); waterBlocks.clear(); dirtBlocks.clear(); for(int x = startRenderX; x < endRenderX; x++){ it = cubes.lower_bound(glm::vec3(x,0.0,startRenderZ)); for(int z = startRenderZ; z < endRenderZ; z++){ while(it->first.z == z){ //Verify the need of rendering if(it->second.render == true){ switch(it->second.type){ case cubetype::grass: grassBlocks.push_back(it->first); break; case cubetype::sand: sandBlocks.push_back(it->first); break; case cubetype::water: waterBlocks.push_back(it->first); break; case cubetype::wood: woodBlocks.push_back(it->first); break; case cubetype::treeGrass: leaveBlocks.push_back(it->first); break; default: //std::cout << std::endl << "Tring to render Cube without a type" << std::endl; break; }; } it++; } } } loadMutex.lock(); grassBlocks2 = grassBlocks; sandBlocks2 = sandBlocks; waterBlocks2 = waterBlocks; woodBlocks2 = woodBlocks; leaveBlocks2 = leaveBlocks; loadMutex.unlock(); if(frameCounter >= 120){ //generateSurfaceTerrain(); frameCounter = 0; } }//End While } void terrainRenderer::generateSurfaceTerrain(){ cubes.clear(); int startRenderX = renderPos.x - loadSize/2; int endRenderX = renderPos.x + loadSize/2; int startRenderZ = renderPos.z - loadSize/2; int endRenderZ = renderPos.z + loadSize/2; float biomeValue = 0; //Ŧrees float max = 0.985f; float hight = 0; int depth = 3; float finalHight; glm::vec3 cubePos; cubetype typeCube; for(int i = startRenderX; i < endRenderX; i++){ for(int j = startRenderZ; j < endRenderZ; j++){ biomeValue = biomeNoise.valueNoise((float)(i)/200.0f,(float)(j)/200.0f); //DESERT BIOME if(biomeValue <= 0.45f){ typeCube = cubetype::sand; terrainNoise.setValueNoiseParameters(3,0.7f,1.8f); hight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); //Interpolate Biomes if(biomeValue >= 0.425f){ terrainNoise.setValueNoiseParameters(3,0.65f,1.5f); float grassHight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); hight = noise::lerp((hight*40),(grassHight*77), 20*(biomeValue - 0.425)); }else{ hight = hight * 40; } //GRASS BIOME }else if(biomeValue <=0.65f){ typeCube = cubetype::grass; terrainNoise.setValueNoiseParameters(3,0.65f,1.5f); hight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); //Interpolate biomes if(biomeValue <= 0.475f ){ terrainNoise.setValueNoiseParameters(3,0.7f,1.8f); float Sandhight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); hight = noise::lerp((Sandhight*40),(hight*77), 20*(biomeValue - 0.425)); }else if(biomeValue >= 0.6){ terrainNoise.setValueNoiseParameters(2,0.8f,2.0f); float Oceanhight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); hight = noise::lerp((hight*77),(Oceanhight*15), 20*(biomeValue - 0.6)); }else{ hight = hight*77; } //ŦREES if(terrainNoise.noise2D(i,j,3.5f,1) >= max){ for(int tronco = 0; tronco < 3 ; tronco++){ // woodBlocks.push_back(glm::vec3(grassBlocks.back().x,grassBlocks.back().y + 1 + tronco ,grassBlocks.back().z)); cubes.emplace(glm::vec3(i ,(int)hight + 1.5f + tronco , j),cubeInfo(cubetype::wood)); } for(int x = -2; x < 3; x++){ for(int y = -2; y < 3; y++){ for(int altura = 0; altura < 3; altura++){ cubes.emplace(glm::vec3(i + x ,(int)hight + 4.5f + altura , j + y),cubeInfo(cubetype::treeGrass)); // leaveBlocks.push_back(woodBlocks[arvore] + glm::vec3(x,3+altura,y)); } } } } //OCEAN }else{ typeCube = cubetype::water; terrainNoise.setValueNoiseParameters(2,0.8f,2.0f); hight = terrainNoise.valueNoise((float)(i)/85.0f,(float)(j)/85.0f); hight = hight*15; // cubes.emplace(glm::vec3(i, 0.5f + (int)(hight*15) , j),cubetype::water); } cubes.emplace(glm::vec3(i, (int)hight + 0.5f , j) ,cubeInfo(typeCube,false)); if(typeCube == cubetype::grass || typeCube == cubetype::sand){ for(int hightAux = 1; hightAux <= depth; hightAux++){ //cubes.emplace(glm::vec3(i, (int)hight + 0.5f - hightAux , j) ,typeCube ); cubes.emplace(glm::vec3(i, (int)hight + 0.5f - hightAux , j) ,cubeInfo(typeCube,false)); } } } } //Visible blocks for(auto& cube : cubes){ if( getCubeAt(glm::vec3(cube.first.x , cube.first.y + 1.0f , cube.first.z )) == cubetype::end || getCubeAt(glm::vec3(cube.first.x , cube.first.y - 1.0f , cube.first.z )) == cubetype::end || getCubeAt(glm::vec3(cube.first.x + 1.0f , cube.first.y , cube.first.z )) == cubetype::end || getCubeAt(glm::vec3(cube.first.x - 1.0f , cube.first.y , cube.first.z )) == cubetype::end || getCubeAt(glm::vec3(cube.first.x , cube.first.y , cube.first.z + 1.0f )) == cubetype::end || getCubeAt(glm::vec3(cube.first.x , cube.first.y , cube.first.z - 1.0f )) == cubetype::end ){ cube.second.render = true; } } } inline cubetype terrainRenderer::getCubeAt(glm::vec3 pos){ auto it = cubes.find(pos); if(it == cubes.end()){ return cubetype::end; }else{ return it->second.type; } } //Retuirn true if a < b bool terrainRenderer::compareInMap(const glm::vec3& a,const glm::vec3& b){ if(a.x < b.x){ return true; }else if(a.x > b.x){ return false; }else{ if(a.z < b.z){ return true; }else if(a.z > b.z){ return false; }else{ if(a.y < b.y){ return true; }else if(a.y > b.y){ return false; }else{ return false; } } } }
true
d91a6cb8623e124f7d6d82befdeec61e4ce22753
C++
KimBoWoon/ACM-ICPC
/ACM-ICPC/10814.cpp
UTF-8
556
3.234375
3
[ "MIT" ]
permissive
#include <iostream> #include <algorithm> #include <string> using namespace std; typedef struct Account { string name; int age, order; } account; int n; account a[100001]; bool comp(const account &x, const account &y) { if (x.age == y.age) { return x.order < y.order; } return x.age < y.age; } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i].age >> a[i].name; a[i].order = i; } sort(a, a + n, comp); for (int i = 0; i < n; i++) { cout << a[i].age << " " << a[i].name << endl; } }
true
b023efe98b93f509e84044bf6836a96532e9d6ae
C++
omanrichard/Final-Project-ECE-3220
/Final Project/main/thermalgraphics.cpp
UTF-8
633
2.984375
3
[]
no_license
#include "thermalGraphics.h" progressBar::progressBar(int x, int y, int length, int width){ //(x,y) cordinate upper left corner of object xMin = x; yMin = y; xSize = length; ySize = width; //background rectangle fill(50,127,17); rec(x,y,length,width); //empty bar fill(40,0,127); rec(x,y+width/4,length,width-width/2); //draw tracker } void progressBar::update(int percent){ //clear object fill(50,127,17); rec(xMin,yMin,xSize,ySize); //redraw empty bar fill(40,0,127); rec(xMin,yMin+ySize/4,xSize,ySize-ySize/2); //draw filled bar fill(255,0,0); rect(xMin,yMin,(xSize*percent)/100 ,ySize-ySize/2); }
true
d4645a4cccda9167cf16928d6a5a8f1f930234aa
C++
realbucksavage/esp-oled-sysmon
/esp/monitor/monitor.ino
UTF-8
2,230
2.765625
3
[]
no_license
#include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #include <ArduinoJson.h> #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> // Wifi SSID const char *ssid = "WifiSSID"; const char *pass = "Password"; WiFiClient client; HTTPClient http; DynamicJsonBuffer jsonBuffer(200); #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 // Declaration for an SSD1306 display connected to I2C (SDA, SCL pins) Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); void setup() { Serial.begin(115200); if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64 Serial.println(F("SSD1306 allocation failed")); for(;;); } display.clearDisplay(); display.setTextSize(1.6); display.setTextColor(WHITE); display.setCursor(0, 0); display.println("Connecting to WiFi:"); display.println(ssid); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(500); } display.println("Connected!"); display.display(); } void loop() { // Should be the HOST/IP of the flask server http.begin("http://the_ip_addr:9795/api/system"); int httpCode = http.GET(); display.clearDisplay(); display.setTextSize(1.6); display.setTextColor(WHITE); display.setCursor(0, 0); if (httpCode == 200) { JsonObject& root = jsonBuffer.parseObject(http.getString()); if (!root.success()) { display.println("Parse failed"); return; } JsonArray& cpus = root["cpu"]; showCpus(cpus); JsonObject& memory = root["mem"]; showMemory(memory); display.printf("Swap: %.2f%%\n", root["swp"].as<double>()); } else { display.println("HTTP GET FAILED"); } display.display(); delay(500); } void showCpus(JsonArray& cpus) { display.printf("CPUs (%d)\n", cpus.size()); for (long cpu : cpus) { display.printf("%d ", cpu); } display.println("%\n"); } void showMemory(JsonObject& mem) { double totalBytes = mem["total"].as<double>(); double availableBytes = mem["used"].as<double>(); display.println("Memory (GiB):"); // FIXME: Jay, you're a fucking idiot. display.printf("%.2f of %.2f\n", availableBytes / 1024 / 1024 / 1024, totalBytes / 1024 / 1024 / 1024); }
true
61867b98db92d958305f611ba38f1b360a2b8edd
C++
timostrating/PokeWorld
/src/util/input/keyboard.cpp
UTF-8
1,022
2.59375
3
[]
no_license
// // Created by sneeuwpop on 23-6-19. // #include "keyboard.h" #include <iostream> #include <map> // REMEMBER: we import this from <GLFW/glfw3.h> // // #define GLFW_RELEASE 0 // #define GLFW_PRESS 1 // #define GLFW_REPEAT 2 namespace INPUT::KEYBOARD { std::map<int, int> keyMap; bool firstKeyPressed = false; static void key_callback(GLFWwindow* window, int keyCode, int scancode, int action, int mods) { if (keyCode == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GLFW_TRUE); keyMap[keyCode] = action; firstKeyPressed = true; } void setup(GLFWwindow *window) { glfwSetKeyCallback(window, key_callback); } bool pressed(int keyCode) { return keyMap[keyCode] == GLFW_PRESS || keyMap[keyCode] == GLFW_REPEAT; } bool anyKeyEverPressed() { return firstKeyPressed; } void lateUpdate() { // TODO: implement this } }
true
46e0bafab2b93ca3e0252b42647fa45a64904848
C++
kevinche75/algorithms_and_datastructures_itmo_spring_2020
/Part_3/P3210_DBelyakov_1521.cpp
UTF-8
1,405
3.1875
3
[]
no_license
#include <iostream> using namespace std; const int t = (1 << 20) - 1; int a[2 * t + 2]; void delete_soldier(int y) { y += t; a[y] = 0; for (int i = y / 2; i > 0; i /= 2) { a[i] = a[2 * i] + a[2 * i + 1]; } } int get_position(int l, int r){ int res = 0; l += t; r += t; while (l <= r){ if (l % 2 == 1) { res += a[l]; l++; } if (r % 2 == 0){ res += a[r]; r--; } l /= 2; r /= 2; } return res; } int get_index(int v, int l, int r, int x){ if ((x == a[v]) & (a[v] - a[t + r] < x)){ return r; } if (x <= a[2 * v]){ return get_index(2 * v, l, l + (r - l + 1) / 2 - 1, x); } else { return get_index(2 * v + 1, l + (r - l + 1) / 2, r, x - a[2 * v]); } } int main() { int n, k; cin >> n >> k; for (int i = 1; i <= n; i++){ a[t + i] = 1; } for (int i = t; i >= 1; i--){ a[i] = a[2 * i] + a[2 * i + 1]; } int index = k, position; delete_soldier(k); for (int i = 0; i < n - 1; i++){ cout << index << " "; position = (get_position(1, index) + k) % a[1]; if (position == 0){ position = a[1]; } index = get_index(1, 1, t + 1, position); delete_soldier(index); } cout << index << endl; return 0; }
true
a3e80d8394db3568174183090af50630d5f5ecf1
C++
AryanP281/Sudoku-Solvers
/C++ Console/SudokuSolver.cpp
UTF-8
3,477
3.6875
4
[]
no_license
// SudokuSolver.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> #include <cmath> #include <random> #include <time.h> std::vector<char> SolveSudoku(char row, char col, char n, std::vector<char> board); bool PossibleMove(char row, char col, char move, char n, std::vector<char>& board); bool IsCorrect(std::vector<char>& board); int main() { int n = 9; std::cout << "Enter n: "; std::cin >> n; srand(time(NULL)); std::vector<char> board; board.push_back(rand() % n); for (char a = 1; a < n*n; ++a) { board.push_back(n); } std::vector<char> res = SolveSudoku(0, 1, n, board); //Checking if the solution is correct if (IsCorrect(res)) { //Printing the solved sudoku for (char row = 0; row < n; ++row) { for (char col = 0; col < n; ++col) { if (res[row * n + col] == n) std::cout << "| "; else std::cout << "|" << (int)res[row * n + col]; } std::cout << "|\n"; } } } std::vector<char> SolveSudoku(char row, char col, char n, std::vector<char> board) { //Checking if the sudoku has been solved if (row == n && col == 0) return board; //Selecting the value to be entered in the current cell for (char a = 0; a < n; ++a) { if (PossibleMove(row, col, a, n, board)) { board[row * n + col] = a; std::vector<char> res; if (col == n - 1) res = SolveSudoku(row + 1, 0, n, board); else res = SolveSudoku(row, col + 1, n, board); if (res.size() != 0) return res; board[row * n + col] = n; } } //Returning a empty vector as no solution was found return std::vector<char>(); } bool PossibleMove(char row, char col, char move, char n, std::vector<char>& board) { //Checking if row is safe for (char c = 0; c < col; ++c) { if (board[row * n + c] == move) return false; } //Checking if column is safe for (char r = 0; r < row; ++r) { if (board[r * n + col] == move) return false; } return true; } bool IsCorrect(std::vector<char>& board) { static char coords[] = { 0, 0 }; //Calculating the dimensions of the Sudoku grid char n = (char)sqrt(board.size()); //Exiting function as all the cells have been checked if (coords[0] == n) return true; //Checking if number is repeated in row for (char c = 0; c < n; ++c) { if (c != coords[1]) { if (board[coords[0] * n + coords[1]] == board[coords[0] * n + c]) return false; } } //Checking if number is repeated in column for (char r = 0; r < n; ++r) { if (r != coords[0]) { if (board[coords[0] * n + coords[1]] == board[r * n + coords[1]]) return false; } } //Updating the coords coords[0] = coords[1] == n - 1 ? coords[0] + 1 : coords[0]; coords[1] = coords[1] == n - 1 ? 0 : coords[1] + 1; //Recursively checking in the next cells return IsCorrect(board); }
true
198bf268ac48ac0816d9efb679f69f1f3759afe1
C++
downkhg/GAMP18
/ProgramingBasic/C/7.Struct/7.Struct/7.struct.cpp
UHC
4,007
3.21875
3
[]
no_license
#include <stdio.h> #include <string.h> //÷̾ //Ӽ(ɼִ°:):ɷġ(ݷ,,ü),ġ,,̸ //ü : ü ϴ ҵ  Ǵ ϴ 赵 /// : ü ϰ Ͽ ϴ ִ. //ü ̹Ƿ üȿ ִ.( Statusü ) struct Player //ü 4Ʈ ޸𸮰 Ҵȴ. 4ǹ ƴϸ ޸𸮰 ɼ. { char strName[253];//256 //253 . int nAtk; //4 int nDef; //4 int nHP; //4 int nExp; //4 int nLv; //4 }; //ü ̹Ƿ ϾǷ ϱؼ ؾѴ. Player InitPlayerVal(Player player, const char* name, int atk, int def, int hp, int exp, int lv) { //Player player;//ü . strcpy(player.strName, name); player.nAtk = atk;//ü player.nDef = def; player.nHP = hp; player.nExp = exp; player.nLv = lv; printf("InitPlayerVal:%d\n",&player); return player; } //ͷ ϸ ּҰ ϹǷ, ʾƵ ޸𸮰 氡ϴ. void InitPlayerPtr(Player* pPlayer, const char* name, int atk, int def, int hp, int exp, int lv) { printf("InitPlayerVal:%d\n", pPlayer); strcpy(pPlayer->strName, name); pPlayer->nAtk = atk;//ü pPlayer->nDef = def; pPlayer->nHP = hp; pPlayer->nExp = exp; pPlayer->nLv = lv; } void InitPlayerRef(Player& player, const char* name, int atk, int def, int hp, int exp, int lv) { printf("InitPlayerRef:%d\n", &player); strcpy(player.strName, name); player.nAtk = atk;//ü player.nDef = def; player.nHP = hp; player.nExp = exp; player.nLv = lv; } //½ ջ ʾƾϹǷ const ̿Ѵ. void PrintPlayer(const Player& player) { printf("############ %s ##############\n",player.strName); printf("Atk:%d\n",player.nAtk); printf("Def:%d\n", player.nDef); printf("HP:%d\n", player.nHP); printf("Exp:%d\n", player.nExp); printf("Lv:%d\n", player.nLv); } void StructMain() { Player player;//ü . player.nAtk = 10;//ü player.nDef = 10; player.nHP = 100; player.nExp = 0; player.nLv = 1; strcpy(player.strName, "test");//ڿ Լ ̿Ͽ ʱȭѴ. printf("player[%d]:%d\n", sizeof(player), &player); player = InitPlayerVal(player, "testval", 10, 10, 100, 0, 1); PrintPlayer(player); InitPlayerPtr(&player, "testptr", 10, 10, 100, 50, 1); PrintPlayer(player); InitPlayerRef(player, "testref", 20, 20, 110, 0, 2); PrintPlayer(player); //player == player //Ͽ. ü ̹Ƿ ޸𸮰 ٰؼ ٰ ϱƴ. } //ü: ޸𸮰 ȴ. union IpAdress { unsigned long laddr; unsigned char saddr[4]; }; void IpAdressMain() { union IpAdress addr; //ȣƮ: ǻ ڱڽ ϴ ּ. addr.saddr[0] = 1; addr.saddr[1] = 0; addr.saddr[2] = 0; addr.saddr[3] = 127; printf("[%d]:%x\n", sizeof(IpAdress), addr.laddr); } //#define TITLE 0 //ó⸦ ̿Ҽִ. enum E_GUISTATUS { TITLE, GAMEOVER, PLAY }; //enum: ǵȼڸ ϱ ϴ°. void EnumTestMain() { int eCurStatus; eCurStatus = E_GUISTATUS::PLAY; // 0 title̶ ǹ̰ ϱ⽱. //eCurStatus = 0; switch (eCurStatus) { case TITLE: printf("ŸƲ"); break; case GAMEOVER: printf("ӿ"); break; case PLAY: printf(" ..."); break; } } void main() { //IpAdressMain(); EnumTestMain(); }
true
675d81da57ccd437a1a4b7895b009730f3972d96
C++
NoamCohen1/ServersProject
/FileCacheManager.h
UTF-8
695
2.59375
3
[]
no_license
#ifndef SERVERSPROJECT_FILECACHEMANAGER_H #define SERVERSPROJECT_FILECACHEMANAGER_H #include "CacheManager.h" #include <iostream> #include <fstream> #include <vector> #define START_STRING 0 #define DELIMITER2 "$" class FileCacheManager : public CacheManager { public: FileCacheManager() { pthread_mutex_init(&mutex, nullptr); makeMap(); } virtual bool doWeHaveSolution(string problem); virtual string getSolution(string problem); vector<string> split(string buffer); void makeMap(); void addSolToMap(string problem, string solution); virtual void writeInfo(string problem, string solution); }; #endif //SERVERSPROJECT_FILECACHEMANAGER_H
true
1d5ce44a29576723ac3c06b9a10efd8bbe3b658a
C++
ikkz/FunctionParser
/src/DivideFunction.cpp
UTF-8
805
2.8125
3
[ "MIT" ]
permissive
#include <DivideFunction.h> #include <MinusFunction.h> #include <CosFunction.h> #include <SinFunction.h> #include <MultiplyFunction.h> namespace cl { DivideFunction::DivideFunction(BaseFunctionPtr lhs, BaseFunctionPtr rhs) : _lhs(lhs), _rhs(rhs), BaseFunction(T_DIVIDE_FUNCTION) { } std::string DivideFunction::str() const { return "(" + _lhs->str() + "/" + _rhs->str() + ")"; } double DivideFunction::value(double x) const { return _lhs->value(x) / _rhs->value(x); } BaseFunctionPtr DivideFunction::derivative() const { return std::make_shared<DivideFunction>(std::make_shared<MinusFunction>(std::make_shared<MultiplyFunction>(_lhs->derivative(), _rhs), std::make_shared<MultiplyFunction>(_lhs, _rhs->derivative())), std::make_shared<MultiplyFunction>(_rhs, _rhs)); } } // namespace cl
true
71112ef3789b067df4dbad2f06fea11bb8e7e5bd
C++
HeRaNO/OI-ICPC-Codes
/LibreOJ/LOJ6.cpp
UTF-8
406
2.625
3
[ "MIT" ]
permissive
#include "interaction.h" using namespace std; vector <int> ans; inline int Binary(int index) { int l = 0, r = 1000000, mid, res; while (l <= r) { mid = l + r >> 1; res = guess(index, mid); if (res > 0) r = mid - 1; else if (!res) return mid; else l = mid + 1; } return l; } int main() { int n = get_num(); for (int i = 0; i < n; i++) ans.push_back(Binary(i)); submit(ans); return 0; }
true
130ed2d9183db38374d071ccaf5f885eafb7e361
C++
dlakaplan/arduino
/matrix_sweep/matrix_sweep.ino
UTF-8
13,847
2.84375
3
[]
no_license
/* sweep across a RGB LED Matrix Can work with either 16x32 or 32x64 Matrices, but make sure to wire up correctly For 32x64 Matrix wiring is (for Arduino Mega): G1=25 R1=24 GND=GND B1=26 G2=28 R2=27 GND=GND B2=29 B=A1 A=A0 D=A3 C=A2 LAT=10 CLK=11 GND = GND OE=9 For 16x32 Matrix wiring is: G1=25 R1=24 GND=GND B1=26 G2=28 R2=27 GND=GND B2=29 B=A1 A=A0 GND=GND C=A2 LAT=A3 CLK=11 GND = GND OE=9 The program has three modes: pixel sweep, line sweep, and fill the speed can be changed by changing the potentiometer the mode can be changed by the switch See: https://learn.adafruit.com/32x16-32x32-rgb-led-matrix/test-example-code Download libraries from: https://github.com/adafruit/RGB-matrix-Panel and https://github.com/adafruit/Adafruit-GFX-Library */ // Set up the RGB LED Matrix // Taken from a number of Adafruit examples such as testshapes and testcolors #include <Adafruit_GFX.h> // Core graphics library #include <RGBmatrixPanel.h> // Hardware-specific library char NAME[] = "PULSE-O-MATIC"; char VERSION[] = "0.1"; char CREATOR[] = "D. KAPLAN"; // define this for debugging output to serial port // #define DEBUG // define this to use sound output #define SOUND // set these to 0 or 1 to swap directions #define X_DIR 1 #define Y_DIR 1 // use this for a 16x32 matrix // if using the 32x64, leave it undefined // #define Matrix16x32 // potentiometer for analog input const int potPin1=A7; // switches for digital input and to change the state of the sweep const int switchAPin = 7; const int switchBPin = 6; // digital output for speaker const int speakerPin = 12; // pins for wiring the Matrix #define CLK 11 // MUST be on PORTB! (Use pin 11 on Mega) #define OE 9 #define A A0 #define B A1 #define C A2 #ifdef Matrix16x32 #define LAT A3 RGBmatrixPanel matrix(A, B, C, CLK, LAT, OE, false); #else #define LAT 10 #define D A3 RGBmatrixPanel matrix(A, B, C, D, CLK, LAT, OE, false, 64); #endif //////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES //////////////////////////////////////////////////////////////////////////// // this is the built-in LED const int ledPin=13; // the types of sweeps possible enum sweep { NONE, PIXEL, LINE }; // which type are we doing sweep sweep_state; // and which state were we in sweep previous_state; int sensorvalue; // sweep delay in ms int sweepdelay; int previousdelay; // how can we color things? enum colormode { CONSTANT, PROGRESSIVE}; //////////////////////////////////////////////////////////////////////////// // Wheel() // Input a value 0 to 24 to get a color value. // The colours are a transition r - g - b - back to r. // Taken from Adafruit testshapes_32x64 //////////////////////////////////////////////////////////////////////////// uint16_t Wheel(byte WheelPos) { if(WheelPos < 8) { return matrix.Color333(7 - WheelPos, WheelPos, 0); } else if(WheelPos < 16) { WheelPos -= 8; return matrix.Color333(0, 7-WheelPos, WheelPos); } else { WheelPos -= 16; return matrix.Color333(0, WheelPos, 7 - WheelPos); } } //////////////////////////////////////////////////////////////////////////// // checkIO() // check the switch and potentiometer for input //////////////////////////////////////////////////////////////////////////// void checkIO() { // read the value from the sensor: sweepdelay = analog2sweep(analogRead(potPin1)); if (abs(sweepdelay - previousdelay) >= 5) { // if the change was large // use this to guard against small changes caused by ADC variability etc previousdelay=sweepdelay; #ifdef DEBUG Serial.print("Setting sweep delay to "); Serial.println(sweepdelay); #endif } digitalWrite(ledPin,digitalRead(switchAPin)); if (digitalRead(switchAPin) == LOW) { sweep_state = LINE; } else if (digitalRead(switchBPin) == LOW) { sweep_state = PIXEL; } else { sweep_state = NONE; } } //////////////////////////////////////////////////////////////////////////// // analog2sweep() // translate an analog sensor value [0,1024) // to a sweep delay in ms //////////////////////////////////////////////////////////////////////////// int analog2sweep(int analogvalue) { return analogvalue / 20; } //////////////////////////////////////////////////////////////////////////// // TonePlayer class //////////////////////////////////////////////////////////////////////////// class TonePlayer { int period; /////////////////// public: TonePlayer() { period=0; } /////////////////// void Play(int periodtouse) { int frequency; period=periodtouse; // determine the frequency from the delaytime frequency=10000/period; tone(speakerPin, frequency, period); } }; // initialize the tone player TonePlayer toneplayer; //////////////////////////////////////////////////////////////////////////// // generic Sweep class // keeps track of the last pixel updated and waits until the appropriate time to do the next one // should not be used on its own: // methods for TurnOn() and TurnOff() are virtual and need to be implemented in the derived classes //////////////////////////////////////////////////////////////////////////// class Sweep { protected: // current and last coordinates uint8_t x, y; uint8_t lastx, lasty; // this can be either a constant color or a progressive sweep that depends on the pixels colormode sweepcolormode; // for a constant color, these are the rgb values uint8_t pixelr, pixelg, pixelb; // last time a unit was set unsigned long previoustime; // is this instance on or off? boolean state; // should we update rows (y) as well as columns (x)? boolean updaterows; // factor to divide the delaytime for doing the sound timing int soundfactor; /////////////////// public: Sweep(colormode sweepcolormodetoset) { sweepcolormode=sweepcolormodetoset; // set default to WHITE pixelr=7; pixelg=7; pixelb=7; x=0; y=0; lastx=0; lasty=0; previoustime=0; // currently off state=false; // pixel by pixel updaterows=true; // length of the sound should be the length of a single unit soundfactor=1; } void setProgressive() { sweepcolormode=PROGRESSIVE; } void setColor(uint8_t r, uint8_t g, uint8_t b) { sweepcolormode=CONSTANT; pixelr=r; pixelg=g; pixelb=b; } /////////////////// void Update(int delaytime) { unsigned long currenttime = millis(); if (currenttime - previoustime >= delaytime) { // turn on state=true; // call the derived turn-on method here. TurnOn(); lastx=x; if (updaterows) { lasty=y; y++; if (y==matrix.height()) { x++; y=0; } } else { x++; } if (x==matrix.width()) { x=0; } #ifdef SOUND if (y==matrix.height()/2 || !updaterows) { toneplayer.Play(delaytime / soundfactor); } #endif previoustime=currenttime; } } /////////////////// // Turn on the current // this is virtual - needs to be sub-classed virtual void TurnOn(void) = 0; /////////////////// // Turn off the current and last unit // helps with state changes // this is virtual - needs to be sub-classed virtual void TurnOff(void) = 0; }; //////////////////////////////////////////////////////////////////////////// // PixelSweep class // sweeps across a single pixel // keeps track of the last pixel updated and waits until the appropriate time to do the next one //////////////////////////////////////////////////////////////////////////// class PixelSweep : public Sweep { /////////////////// public: PixelSweep(uint8_t r, uint8_t g, uint8_t b) : Sweep(CONSTANT) { setColor(r, g, b); soundfactor=1; updaterows=true; } /////////////////// void TurnOn() { matrix.drawPixel((matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), (matrix.height()-1)*(1-Y_DIR) + y*(2*Y_DIR-1), matrix.Color333(pixelr, pixelg, pixelb)); // now previous pixel as black if (!((x == lastx) && (y == lasty))) { matrix.drawPixel((matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), (matrix.height()-1)*(1-Y_DIR) + lasty*(2*Y_DIR-1), matrix.Color333(0, 0, 0)); } } /////////////////// // Just turn off the current and last pixel // helps with state changes void TurnOff() { if (state) { matrix.drawPixel((matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), (matrix.height()-1)*(1-Y_DIR) + y*(2*Y_DIR-1), matrix.Color333(0, 0, 0)); matrix.drawPixel((matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), (matrix.height()-1)*(1-Y_DIR) + lasty*(2*Y_DIR-1), matrix.Color333(0, 0, 0)); state=false; } } }; //////////////////////////////////////////////////////////////////////////// // LineSweep class // sweeps across a line // keeps track of the last line updated and waits until the appropriate time to do the next one //////////////////////////////////////////////////////////////////////////// class LineSweep : public Sweep { /////////////////// public: LineSweep() : Sweep(PROGRESSIVE) { soundfactor=4; updaterows=false; } /////////////////// void TurnOn() { // translate from x to color c int c = (24*x)/matrix.width(); // draw a line matrix.drawLine((matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), 0, (matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), matrix.height()-1, Wheel(uint8_t(c))); // now draw previous one as black if (x != lastx) { matrix.drawLine((matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), 0, (matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), matrix.height()-1, matrix.Color333(0, 0, 0)); } } /////////////////// // Just turn off the current and last line // helps with state changes void TurnOff() { if (state) { matrix.drawLine((matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), 0, (matrix.width()-1)*(1-X_DIR) + x*(2*X_DIR-1), matrix.height()-1, matrix.Color333(0, 0, 0)); matrix.drawLine((matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), 0, (matrix.width()-1)*(1-X_DIR) + lastx*(2*X_DIR-1), matrix.height()-1, matrix.Color333(0, 0, 0)); state=0; } } }; //////////////////////////////////////////////////////////////////////////// // AllOn class // Illuminates the whole matrix with a changing color //////////////////////////////////////////////////////////////////////////// class AllOn : public Sweep { /////////////////// public: AllOn() : Sweep(PROGRESSIVE) { soundfactor=4; updaterows=false; } /////////////////// void TurnOn() { int c = (24*x)/matrix.width(); matrix.fillScreen(Wheel(uint8_t(c))); } /////////////////// // Just turn off the matrix // helps with state changes void TurnOff() { matrix.fillScreen(matrix.Color333(0, 0, 0)); } }; //////////////////////////////////////////////////////////////////////////// // Identify() // Displays a splash screen //////////////////////////////////////////////////////////////////////////// void Identify() { // text handling from https://github.com/adafruit/RGB-matrix-Panel/blob/master/examples/testshapes_32x64/testshapes_32x64.ino // draw some text! matrix.setTextSize(1); // size 1 == 8 pixels high matrix.setTextWrap(true); // Don't wrap at end of line - will do ourselves matrix.setCursor(0, 0); // start at top left, with 8 pixel of spacing uint8_t w = 0; for (w=0; w<sizeof(NAME); w++) { matrix.setTextColor(Wheel(w)); if (w==8) { matrix.println(); } matrix.print(NAME[w]); } matrix.println(); matrix.setTextColor(matrix.Color333(7,7,7)); matrix.print("v. "); matrix.println(VERSION); matrix.setTextColor(matrix.Color333(2,2,2)); matrix.println(CREATOR); } //////////////////////////////////////////////////////////////////////////// // initialize the pixelsweep and linesweep, along with the fill PixelSweep pixelsweep(7, 7, 7); LineSweep linesweep; AllOn allon; //////////////////////////////////////////////////////////////////////////// void setup() { // have an external LED also there for showing when things happen pinMode(ledPin, OUTPUT); // switch for changing modes pinMode(switchAPin, INPUT_PULLUP); pinMode(switchBPin, INPUT_PULLUP); matrix.begin(); #ifdef DEBUG Serial.begin(9600); while (! Serial); // Wait untilSerial is ready - Leonardo #ifdef Matrix16x32 Serial.println("Using a 16x32 Matrix"); #else Serial.println("Using a 32x64 Matrix"); #endif #endif sweep_state=PIXEL; previous_state=PIXEL; previousdelay=0; Identify(); delay(500); } //////////////////////////////////////////////////////////////////////////// void loop() { // depending on the state of the sweep variable // run it in either mode switch (sweep_state) { case PIXEL: pixelsweep.Update(sweepdelay); break; case LINE: linesweep.Update(sweepdelay); break; case NONE: allon.Update(sweepdelay); break; } if (sweep_state != previous_state) { #ifdef DEBUG Serial.print("Previous state was "); Serial.println(previous_state); Serial.print("New state is "); Serial.println(sweep_state); #endif // did we just switch switch (previous_state) { case PIXEL: pixelsweep.TurnOff(); break; case LINE: linesweep.TurnOff(); break; case NONE: allon.TurnOff(); break; } previous_state=sweep_state; } checkIO(); }
true
90af3ae4efcdd012f1c32f7c1e9680eebaca75b4
C++
Verg84/COOP
/CH06/sample07.cpp
UTF-8
288
3.09375
3
[]
no_license
// greater #include<iostream> using namespace std; int main(){ int x,y; cout<<"Press two different numbers: "<<endl; if(!(cin>>x && cin>>y)){ cout<<"Invalid"<<endl; } else{ cout<<"The greater is "<<(x>y?x:y)<<endl; } return 0; }
true
d370794c04313e2572dac50e933a7d6e7bce77a6
C++
makenzielarsen/ITAK
/PortScanner.cpp
UTF-8
2,244
3.015625
3
[]
no_license
// // Created by Makenzie Larsen on 4/14/17. // #include "PortScanner.h" #include "Utils.h" PortScannerAnalyzer::PortScannerAnalyzer(const Configuration &configuration) : Analyzer(configuration) {} bool PortScannerAnalyzer::checkConfigurationValid() { string likelyAttack = configuration.getStringValue("Likely Attack Port Count"); string possibleAttack = configuration.getStringValue("Possible Attack Port Count"); return !(likelyAttack == " " || possibleAttack == " "); } ResultSet* PortScannerAnalyzer::run(ifstream &inputStream) { if (checkConfigurationValid()) { processData(inputStream); return analyze(); } return nullptr; } void PortScannerAnalyzer::processData(ifstream &ifstream) { string line; while (getline(ifstream, line)) { string array[4]; if(split(line, ',', array, 4)) { IPAddress srcAddress = array[1]; int desPort = stoi(array[3]); try { addressToPorts[srcAddress].insert(desPort); } catch (out_of_range) { addressToPorts[srcAddress] = { desPort }; } } } } ResultSet* PortScannerAnalyzer::analyze() { vector<string> attackers; vector<string> possibleAttackers; vector<string> portCount; vector<string> possiblePortCount; ResultSet* resultSet = new ResultSet; int likelyThreshold = configuration.getIntValue("Likely Attack Port Count"); int possibleThreshold = configuration.getIntValue("Possible Attack Port Count"); for (auto& x: addressToPorts) { string srcAddress = x.first; set<int> ports = x.second; if (ports.size() >= likelyThreshold) { attackers.push_back(srcAddress); portCount.push_back(to_string(ports.size())); } else if (ports.size() >= possibleThreshold) { possibleAttackers.push_back(srcAddress); possiblePortCount.push_back(to_string(ports.size())); } } resultSet->set("Likely attackers", attackers); resultSet->set("Possible Attackers", possibleAttackers); resultSet->set("Attacked Port Count", portCount); resultSet->set("Possible Attacked Port Count", possiblePortCount); return resultSet; }
true
3b50f3d6dd5678b5043329f065f955810e017957
C++
PiscesDante/LintCode
/75. 寻找峰值.cpp
UTF-8
710
2.84375
3
[]
no_license
class Solution { public: /* * @param A: An integers array. * @return: return any of peek positions. */ int findPeak(vector<int>& A) { int head = 0; int tail = A.size() - 1; int len = A.size(); while (head <= tail) { int mid = head + (tail - head) / 2; if (mid + 1 < len && mid - 1 >= 0) { if (A[mid] > A[mid + 1] && A[mid] > A[mid - 1]) { return mid; } } if (A[mid - 1] > A[mid]) tail = mid - 1; else if (A[mid] < A[mid + 1]) head = mid + 1; } return -1; } }; // 总耗时 177 ms // 您的提交打败了 96.80% 的提交!
true
2f74c50629611b8ad179e2512b9051908df44f9a
C++
phu54321/eudasm
/eudasm/eudasm/type/typevoid.h
UTF-8
440
2.59375
3
[]
no_license
#pragma once #include "typebase.h" class CType_Void : public CType { public: CType_Void(); virtual ~CType_Void(); virtual CTypeType GetType() const { return CTypeType::TYPE_NONE; } virtual bool IsElementaryType() const; virtual size_t GetSize() const; virtual size_t GetElementNum() const; virtual bool GetElementTypePtr(size_t index, CTypePtr& ptr, size_t& offset) const; virtual void EmitStringRepr(std::ostream& os) const; };
true
acee8fc5ad39024647df1da0e5ac19bd6c2b3f56
C++
WhiZTiM/coliru
/Archive2/92/a153cabd2719e4/main.cpp
UTF-8
393
2.921875
3
[]
no_license
#include <stddef.h> #include <type_traits> template<typename T> class Bar { public: template<size_t N> struct foo{}; template<typename> struct is_foo : std::false_type{}; template<size_t N> struct is_foo<foo<N>> : std::true_type{}; template<typename = typename std::enable_if<is_foo<foo<0>>::value>::type> Bar(int x) {} }; int main(){ Bar<double> b(5); }
true
a629df601dd0fc936d390cf5c306b69c7b99c6f1
C++
RBDLAB/Drones-Mission-Control
/Utilities.h
UTF-8
1,852
2.8125
3
[]
no_license
#pragma once #include <math.h> #include <map> struct Name { int rb; int markerIndex; }; struct Marker { int id; double x; double y; double z; Name oldName; Name newName; }; struct MarkerPos { int id; double time; long frame; double x; double y; double z; }; struct DataContainer { int n; MarkerPos* markers; }; typedef std::map<long, DataContainer> markersData; class Utils { public: static float *eulerAnglesZYX(float *q) { //normalize q float *n = new float[4]; float q_len = sqrt(q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]); for (int i = 0; i < 4; i++) n[i] = q[i] / q_len; float *euler = new float[3]; euler[0] = atan2(2 * (n[3] * n[0] - n[1] * n[2]), n[0] * n[0] + n[1] * n[1] - n[2] * n[2] - n[3] * n[3]); euler[1] = asin(2 * (n[1] * n[3] + n[2] * n[0])); euler[2] = atan2(2 * (n[1] * n[0] - n[2] * n[3]), n[0] * n[0] - n[1] * n[1] - n[2] * n[2] + n[3] * n[3]); return euler; } static void readMarkersPosFile(std::string fileName, markersData& markers_container) { FILE* ff = fopen(fileName.c_str(), "r"); markers_container.clear(); if (ff == NULL) return; while (!feof(ff)) { float dt; float frame; float nMarkers; fscanf(ff, "dt: %f frame: %f nMarkers: %f", &dt, &frame, &nMarkers); DataContainer container; MarkerPos* line = new MarkerPos[(int)nMarkers]; container.markers = line; container.n = nMarkers; for (int i = 0; i < nMarkers; i++) { float x, y, z; MarkerPos marker; marker.id = i; marker.frame = frame; marker.time = dt; fscanf(ff, " (%f,%f,%f) ", &marker.x, &marker.y, &marker.z);// &(line[i].x), &(line[i].y), &(line[i].z)); printf("(%f,%f,%f) ", marker.x, marker.y, marker.z);// (line[i].x), (line[i].y), (line[i].z)); line[i] = marker; } markers_container[(long)frame] = container; } } };
true
d3d4b00f57dc50f243d9ccd8cc03b859092ce2c3
C++
kailasgangan/Data-Structure
/searching sorting/BubbleSort.cpp
UTF-8
608
2.75
3
[]
no_license
#include<iostream> #include<bits/stdc++.h> using namespace std; int a[10]={150,2430,30,420,506,605,70,80,990,1020}; void BubbleSort(int a[],int Size){ int i,j,t; for(i=0;i<Size-1;i++){ for(j=0;j<Size-1;j++){ if(a[j]>a[j+1]){ t=a[j]; a[j]=a[j+1]; a[j+1]=t; } } } } int main(){ int Size = sizeof(a)/sizeof(a[0]); cout<<"Before sort \n"; for(int j=0;j<Size;j++) cout<<a[j]<<" "; BubbleSort(a,Size); cout<<"\n After sort \n"; for(int i=0;i<Size;i++) cout<<a[i]<<" "; return 0; return 0; }
true
131ff60625245c6af4b124d650ad09fe360a66e3
C++
leanprover-community/lean
/src/library/documentation.cpp
UTF-8
6,671
2.515625
3
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <string> #include <algorithm> #include <functional> #include <cctype> #include <utility> #include <vector> #include "util/sstream.h" #include "library/module.h" #include "library/documentation.h" namespace lean { struct documentation_ext : public environment_extension { /** Doc strings for the current module being processed. It does not include imported doc strings. */ list<std::pair<pos_info, std::string>> m_module_docs; /** Doc strings for declarations (including imported ones). We store doc_strings for declarations in the .olean files. */ name_map<std::string> m_doc_string_map; }; struct documentation_ext_reg { unsigned m_ext_id; documentation_ext_reg() { m_ext_id = environment::register_extension(std::make_shared<documentation_ext>()); } }; static documentation_ext_reg * g_ext = nullptr; static documentation_ext const & get_extension(environment const & env) { return static_cast<documentation_ext const &>(env.get_extension(g_ext->m_ext_id)); } static environment update(environment const & env, documentation_ext const & ext) { return env.update(g_ext->m_ext_id, std::make_shared<documentation_ext>(ext)); } struct doc_modification : public modification { LEAN_MODIFICATION("doc") name m_decl; std::string m_doc; doc_modification() {} /** A docstring for a declaration in the module. */ doc_modification(name const & decl, std::string const & doc) : m_decl(decl), m_doc(doc) {} void perform(environment & env) const override { auto ext = get_extension(env); ext.m_doc_string_map.insert(m_decl, m_doc); env = update(env, ext); } void serialize(serializer & s) const override { s << m_decl << m_doc; } static std::shared_ptr<modification const> deserialize(deserializer & d) { name decl; std::string doc; d >> decl >> doc; return std::make_shared<doc_modification>(decl, doc); } }; static void remove_blank_lines_begin(std::string & s) { optional<std::string::iterator> found; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '\n') { found = it + 1; } else if (!isspace(*it)) { break; } } if (found) s.erase(s.begin(), *found); } static void rtrim(std::string & s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } static unsigned get_indentation(std::string const & s) { bool r_init = false; unsigned r = 0; bool searching = true; unsigned i = 0; for (auto it = (const unsigned char*)s.data(), e = (const unsigned char*)s.data() + s.size(); it != e; ++it) { if (*it == '\n') { i = 0; searching = true; } else if (isspace(*it) && searching) { i++; } else if (searching) { searching = false; if (r_init) { r = std::min(r, i); } else { r = i; r_init = true; } } } return r; } static std::string unindent(std::string const & s) { unsigned i = get_indentation(s); if (i > 0) { std::string r; unsigned j = 0; for (auto it = s.begin(); it != s.end(); it++) { if (*it == '\n') { j = 0; r += *it; } else if (j < i) { j++; } else { r += *it; } } return r; } else { return s; } } static std::string add_lean_suffix_to_code_blocks(std::string const & s) { std::string r; unsigned sz = s.size(); unsigned i = 0; bool in_block = false; while (i < sz) { if (!in_block && s[i] == '`' && sz >= 4 && i < sz - 3 && s[i+1] == '`' && s[i+2] == '`') { unsigned end = i+3; // It could be like ```1 + 1``` i.e. non-alpha, // so checking not_space seems best. bool has_non_space = false; while (has_non_space == false && end < sz && s[end] != '\n') { has_non_space = isspace(s[end]) == 0; end++; } if (has_non_space) r += "```"; else r += "```lean"; r += s[i+3]; i += 4; in_block = true; } else if (in_block && s[i] == '`' && sz >= 3 && i < sz - 2 && s[i+1] == '`' && s[i+2] == '`') { r += "```"; i += 3; in_block = false; } else { r += s[i]; i++; } } if (in_block) { throw exception("invalid doc string, end of code block ``` expected"); } return r; } static std::string process_doc(std::string s) { remove_blank_lines_begin(s); rtrim(s); s = unindent(s); return add_lean_suffix_to_code_blocks(s); } environment add_module_doc_string(environment const & env, std::string doc, pos_info pos) { doc = process_doc(doc); auto ext = get_extension(env); ext.m_module_docs.emplace_front(pos, doc); auto new_env = update(env, ext); return module::add_doc_string(new_env, doc, pos); } environment add_doc_string(environment const & env, name const & n, std::string doc) { doc = process_doc(doc); auto ext = get_extension(env); if (ext.m_doc_string_map.contains(n)) { throw exception(sstream() << "environment already contains a doc string for '" << n << "'"); } ext.m_doc_string_map.insert(n, doc); auto new_env = update(env, ext); return module::add(new_env, std::make_shared<doc_modification>(n, doc)); } optional<std::string> get_doc_string(environment const & env, name const & n) { auto ext = get_extension(env); if (auto r = ext.m_doc_string_map.find(n)) return optional<std::string>(*r); else return optional<std::string>(); } void get_module_doc_strings(environment const & env, buffer<mod_doc_entry> & result) { auto ext = get_extension(env); module::get_doc_strings(env).for_each( [&] (std::string const & mod_name, list<std::pair<pos_info, std::string>> const & docs) { result.push_back({ some(mod_name), docs }); }); result.push_back({ {}, ext.m_module_docs }); } void initialize_documentation() { g_ext = new documentation_ext_reg(); doc_modification::init(); } void finalize_documentation() { doc_modification::finalize(); delete g_ext; } }
true
2578fdce86e2dab7f7af5d72b1c26ebfb27f4057
C++
Kasymkhankhubiyev/Sea-Battle-Game
/main.cpp
UTF-8
5,069
2.890625
3
[]
no_license
#include "Game.h" #include "Graphics.h" #include "player.h" int main() { Game game; //класс, который закручивает всю игруху Field field; //класс, рисующий поле //field.Draw_field_line(); Player player1; //бот Player player2;//тоже бот size_t mode, tact; menu_print();//выводим главное меню size_t n; std::cin >> n; mode = n; if (n == 1) //выбор режима {//play myselfe std::cout << " You are the PLAYER 1 " << std::endl; player_choice_menu(); size_t k; std::cin >> k; if (k == 1) //выбор типа задачи поля { player1.Set_ships_concole(); player2.Set_ship_type(); } if (k == 2) //поля задают боты { ship_types(); //4 по 1, 3 по 2, 2 по 3, и 1 по 4; player1.Set_ship_type(); player1.Draw_player_field(); //показываем игроку его поле player2.Set_ship_type(); //теперь мы расставили корабли и можем переходить к бою, но для этого сначала нужно показать игрокам их поля; player2.Draw_player_field(); //показываем игроку его поле } tact = player1.Choice(); } if (n == 2) { player_choice_menu(); //вывод меню выбора игрового режима size_t k; std::cin >> k; if (k == 1) //выбор типа задачи поля { player1.Set_ships_concole(); player2.Set_ship_type(); } if (k == 2) //поля задают боты { ship_types(); //4 по 1, 3 по 2, 2 по 3, и 1 по 4; player1.Set_ship_type(); player1.Draw_player_field(); //показываем игроку его поле player2.Set_ship_type(); //теперь мы расставили корабли и можем переходить к бою, но для этого сначала нужно показать игрокам их поля; player2.Draw_player_field(); //показываем игроку его поле } if (n == 0) { game.Exit(); } //очистка консоли и вызов нового текста; } if (n == 0) { game.Exit(); } system("cls"); size_t Score1 = player1.Get_Score();//записываем исходные данные size_t Score2 = player2.Get_Score();//счет size_t Ships1 = player1.Get_ships();//кол-во кораблей на поле (с каждым попаданием +1 очко) size_t Ships2 = player2.Get_ships(); while (Score1 != 7 && Score2 != 7)//закручиваем игру {//two bots simple done! bool comp = false; system("cls"); std::cout << " Player 1 Ships: " << Ships1 << " Score: " << Score1 << std::endl; std::cout << " Player 2 Ships: " << Ships2 << " Score: " << Score2 << std::endl; player1.Draw_battle_field(); size_t x, y; size_t sc = 1; if (mode == 1&& tact ==1 ) { player1.PersonTactic(comp, x, y); } if ((mode == 1 && tact == 2)||(mode==2)) { player1.EasyTactic(comp, x, y); } sc = player2.Compare2(x, y); if (sc == 1) { std::cout << "Yes! right Shoot!" << std::endl; player1.Reset(x, y); player1.ReDraw(Ships1, Score1, Ships2, Score2); Score1 = Score1 + sc; } else { player1.ReDraw(Ships1, Score1, Ships2, Score2); std::cout << "Oh, you missed! Shoot better!" << std::endl; } Sleep(2000); comp = false; system("cls"); std::cout << " Player 1 Ships: " << Ships1 << " Score: " << Score1 << std::endl; std::cout << " Player 2 Ships: " << Ships2 << " Score: " << Score2 << std::endl; if (mode == 2) { player2.Draw_battle_field(); } if (mode == 1) { std::cout << "Player 2 is shooting"; } player2.EasyTactic(comp, x, y); sc = player1.Compare2(x, y); if (mode == 2) { if (sc != 0) { std::cout << "Yes! right Shoot!" << std::endl; player2.Reset(x, y); player2.ReDraw(Ships1, Score1, Ships2, Score2); Score2 = Score2 + sc; } else { player2.ReDraw(Ships1, Score1, Ships2, Score2); std::cout << "Oh, you missed! Shoot better!" << std::endl; } Sleep(2000); } if (mode == 1) { if (sc != 0) { std::cout << "Yes! right Shoot!" << std::endl; Score2 = Score2 + sc; } else { player2.ReDraw(Ships1, Score1, Ships2, Score2); std::cout << "Oh, you missed! Shoot better!" << std::endl; } } } if (Score1 == 7) { std::cout << " Player 1 WON!!! " << std::endl; } if (Score2 == 7) { std::cout << " Player 2 WON!!! " << std::endl; } game.Exit(); return 0; } ///нужно считывать вводимый текст относительно клеток, нужно будет ввести редактор, считам поле как в шахматах "Е1" к примеру, Е в один блок, 1 в другой. // еще сделаем функию выхода, если вводит текст "Exit" - тогда сворачиваем игру.
true
f29f6c2b531f9ae9e60b9023a0747de092073be4
C++
shayyn20/CSE306
/assignment 2/main.cpp
UTF-8
5,177
2.640625
3
[]
no_license
#include "include.h" int main(int argc, char** argv) { if ((argc > 1) && (!strcmp(argv[1], "sh"))) { Polygon p = Polygon({ Vector(0.05, 0.15), Vector(0.2, 0.05), Vector(0.35, 0.15), Vector(0.35, 0.3), Vector(0.25, 0.3), Vector(0.2, 0.25), Vector(0.15, 0.35), Vector(0.1, 0.25), Vector(0.1, 0.2)}); Polygon c = Polygon({Vector(0.1, 0.1), Vector(0.3, 0.1), Vector(0.3, 0.3), Vector(0.1, 0.3)}); save_svg({p}, "test.svg"); save_svg({c}, "test1.svg"); save_svg({p, c}, "test3.svg"); p = sutherlandHodgman(p, c); save_svg({p}, "test2.svg"); return 0; } if ((argc > 1) && (!strcmp(argv[1], "t"))) { std::vector<Vector> points = { Vector(0.05, 0.15), Vector(0.2, 0.05), Vector(0.35, 0.15), Vector(0.35, 0.3), Vector(0.25, 0.3), Vector(0.2, 0.25), Vector(0.15, 0.35), Vector(0.1, 0.25), Vector(0.1, 0.2)}; std::vector<double> weights = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01}; return 0; } if ((argc > 1) && (!strcmp(argv[1], "vor"))) { // std::vector<Vector> points = { Vector(0.05, 0.15), Vector(0.2, 0.05), Vector(0.35, 0.15), Vector(0.35, 0.3), // Vector(0.25, 0.3), Vector(0.2, 0.25), Vector(0.15, 0.35), Vector(0.1, 0.25), // Vector(0.1, 0.2)}; Generator generator; std::vector<Vector> points = generateRandomPoints(50, generator); std::vector<Polygon> p = voronoiParalLinEnum(points); save_svg_with_point(p, points, "vor.svg"); points = lloydIteration_vor(points); p = voronoiParalLinEnum(points); save_svg_with_point(p, points, "vor_lloyd.svg"); return 0; } if ((argc > 1) && (!strcmp(argv[1], "pow"))) { // std::vector<Vector> points = { Vector(0.05, 0.15), Vector(0.2, 0.05), Vector(0.35, 0.15), Vector(0.35, 0.3), // Vector(0.25, 0.3), Vector(0.2, 0.25), Vector(0.15, 0.35), Vector(0.1, 0.25), // Vector(0.1, 0.2)}; // std::vector<double> weights = { 0.01, 0.02, 0.03, 0.04, // 0.05, 0.04, 0.03, 0.02, // 0.01}; Generator generator; std::vector<Vector> points = generateRandomPoints(100, generator); std::vector<double> weights = generateRandomWeights(100, generator); std::vector<Polygon> p = powerDiagram(points, weights); save_svg_with_point(p, points, "power.svg"); return 0; } if ((argc > 1) && (!strcmp(argv[1], "ga"))) { std::vector<Vector> points = { Vector(0.05, 0.15), Vector(0.2, 0.05), Vector(0.35, 0.15), Vector(0.35, 0.3), Vector(0.25, 0.3), Vector(0.2, 0.25), Vector(0.15, 0.35), Vector(0.1, 0.25), Vector(0.1, 0.2)}; std::vector<double> weights = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01}; std::vector<double> nw = gradAscent(points, weights, 0.6); std::vector<Polygon> p = powerDiagram(points, nw); for (int i = 0; i < int(nw.size()); i ++) { printf("w[%d] = %f \n", i, nw[i]); } save_svg(p, "ga.svg"); p.push_back(Polygon(points)); save_svg(p, "ga2.svg"); p = voronoiParalLinEnum(points); save_svg(p, "ga1.svg"); return 0; } if ((argc > 1) && (!strcmp(argv[1], "l"))) { Generator generator; std::vector<Vector> points = generateRandomPoints(50, generator); std::vector<Polygon> p = voronoiParalLinEnum(points); save_svg_with_point(p, points, "lloyd_vor.svg"); points = lloydIteration_vor(points); p = voronoiParalLinEnum(points); save_svg_with_point(p, points, "lloyd_vor2.svg"); return 0; } if ((argc > 1) && (!strcmp(argv[1], "ot"))) { Generator generator; std::vector<Vector> points = generateRandomPoints(100, generator, false); // points = lloydIteration_vor(points); std::vector<double> weights = optimalTransport(points, 1, "normal"); std::vector<Polygon> p = voronoiParalLinEnum(points); save_svg_with_point(p, points, "ot.svg"); p = powerDiagram(points, weights); save_svg_with_point(p, points, "ot2.svg"); return 0; } simulation(); return 0; }
true
684b3724cfd32654295476b0372a33ee6060c571
C++
pawelkulig1/StarCraft-III
/StarCraft III/Players/SI.hpp
UTF-8
847
2.5625
3
[]
no_license
// // SI.hpp // StarCraft III // // Created by Paweł Kulig on 25.10.2017. // Copyright © 2017 Paweł Kulig. All rights reserved. // #ifndef SI_hpp #define SI_hpp #include <stdio.h> #include "Player.hpp" #include "unit.h" #include "game.h" #include <stdlib.h> //rand() srand() #include <time.h> //time() class SI: public Player { int additionalAttack; int day; bool attackThisRound; public: SI(int day); void setadditionalAttack(int additionalAttack); int getadditionalAttakc(); void setday(int day); int getday(); void setattackThisRound(bool attackThisRound); bool getattackThisRound(); void checkIfAttack(); void createUnitsToAttack(); bool battle(Player *player); void choseRace(); int buildUnit(int unitNumber); }; #endif /* SI_hpp */
true
fb229e5794d549bb587755ea21ed2f79d1012086
C++
HarryWei/grafalgo
/java/cpp/graphAlgorithms/misc/cgraph.cpp
UTF-8
1,400
3.390625
3
[]
no_license
// usage: cgraph type // // Copy a graph of specified type from stdin to stdout. // Why you ask? To test input and output operators, of course. // We also do an assignment in between input and output, // in order to test the assignment operator. // // The allowed values of type are graph, wgraph, // digraph, wdigraph, flograph, wflograph. #include "stdinc.h" #include "Wgraph.h" #include "Wdigraph.h" #include "Wflograph.h" main(int argc, char *argv[]) { if (argc != 2) fatal("usage: cgraph type"); string s; if (strcmp(argv[1],"graph") == 0) { Graph g; g.read(cin); Graph g1(1,1); g1.copyFrom(g); cout << g1.toString(s); } else if (strcmp(argv[1],"wgraph") == 0) { Wgraph wg; wg.read(cin); Wgraph wg1(1,1); wg1.copyFrom(wg); cout << wg1.toString(s); } else if (strcmp(argv[1],"digraph") == 0) { Digraph dig; dig.read(cin); Digraph dig1(1,1); dig1.copyFrom(dig); cout << dig1.toString(s); } else if (strcmp(argv[1],"wdigraph") == 0) { Wdigraph wdig; wdig.read(cin); Wdigraph wdig1(1,1); wdig1.copyFrom(wdig); cout << wdig1.toString(s); } else if (strcmp(argv[1],"flograph") == 0) { Flograph fg; fg.read(cin); Flograph fg1(2,1); fg1.copyFrom(fg); cout << fg1.toString(s); } else if (strcmp(argv[1],"wflograph") == 0) { Wflograph wfg; wfg.read(cin); Wflograph wfg1(2,1); wfg1.copyFrom(wfg); cout << wfg1.toString(s); } else { fatal("usage: cgraph type"); } }
true
4cb3f765ef46f58c3e353dc7ebccc08db1b871d1
C++
Ahren09/CS31
/Discussion/CS 31 Dis W7.cpp
UTF-8
1,339
3.328125
3
[]
no_license
#include <cstring> #include <iostream> #include <cmath> using namespace std; //4 void reverse(char* arr){ //if(! *arr) return; OPTIONAL char* start=arr; char* end=arr; while(*(++end)); end--; /* OR: while(*(end++)); end-=2; //notice here the pointer goes back by 2 */ while(start<end){ char temp=*start; *start=*end; *end=temp; start++;end--; } } //6 void minMax(int arr[], int n, int*& min, int*& max){ if(n!=0){ //if(*arr) //WRONG!! min=arr; max=arr; int* i=arr; while(i<arr+n){ if(*i<*min) min=i; if(*i>*max) max=i; i++; } } return; } //9 void rotate(int* A, int n){ int rotation=n%6; if(rotation==0) return; else if(rotation<0) rotation+=6; //int index=rotation; int *B=&A; for(int i=6-rotation;i<6;i++){ swap(*A,*(A+6-rotation)); A++; } for(int i=) else if(n<0){ } } int main(){ char c[5]="ucla"; reverse(c); cout<<c<<endl; int arr[5]={0,5,7,-10,2}; int *pmin; int *pmax; minMax(arr,5,pmin,pmax); cout<<*pmin<<" "<<*pmax<<endl; int A[]={1,2,3,4,5,6}; int B[]={1,2,3,4,5,6}; }
true
d8fe7163ab2976279b87193311b339e96678a181
C++
ArrowganceStudios/Space-Navies-Arena
/src/Game.cpp
UTF-8
3,475
2.75
3
[ "MIT" ]
permissive
#include "Game.h" #include <iostream> #define internal static const double Game::MS_PER_UPDATE = (1.0 / FPS) * 1000; internal inline bool IsReadyToRender(ALLEGRO_EVENT_QUEUE *eventQueue, ALLEGRO_EVENT event) { return al_is_event_queue_empty(eventQueue) && event.type == ALLEGRO_EVENT_TIMER; } internal inline bool IsReadyToUpdate(ALLEGRO_EVENT event) { return event.type == ALLEGRO_EVENT_TIMER; } internal inline bool WindowGotClosed(ALLEGRO_EVENT event) { return event.type == ALLEGRO_EVENT_DISPLAY_CLOSE; } void Game::SetupAllegroInitialization() { //Init and install input devices al_init(); al_install_keyboard(); al_install_mouse(); } void Game::SetupDisplay() { //set display flags for anti-aliasing al_set_new_display_flags(ALLEGRO_RESIZABLE); al_set_new_display_option(ALLEGRO_VSYNC, 1, ALLEGRO_SUGGEST); al_set_new_bitmap_flags(ALLEGRO_MIN_LINEAR); al_set_new_display_option(ALLEGRO_SAMPLE_BUFFERS, 1, ALLEGRO_SUGGEST); al_set_new_display_option(ALLEGRO_SAMPLES, 6, ALLEGRO_SUGGEST); //create display and give it a name _display = al_create_display(WIDTH, HEIGHT); al_set_window_title(_display, "Space Navies Arena"); } void Game::SetupEventQueue() { _eventQueue = al_create_event_queue(); //register events from display, keyboard and mouse al_register_event_source(_eventQueue, al_get_display_event_source(_display)); al_register_event_source(_eventQueue, al_get_keyboard_event_source()); al_register_event_source(_eventQueue, al_get_mouse_event_source()); } void Game::SetupTimer() { _timer = al_create_timer(MS_PER_UPDATE); al_register_event_source(_eventQueue, al_get_timer_event_source(_timer)); al_start_timer(_timer); } void Game::AllegroCleanup() { al_destroy_display(_display); al_destroy_event_queue(_eventQueue); al_destroy_timer(_timer); } void Game::SwapBuffers() //and clear color { al_flip_display(); al_clear_to_color(al_map_rgb(0, 0, 0)); } Game::Game() : _isRunning(true) { //Allegro initializations SetupAllegroInitialization(); SetupDisplay(); SetupEventQueue(); SetupTimer(); } Game::~Game() { AllegroCleanup(); StatesCleanup(); } void Game::ProcessInput() { } void Game::Render() { if (IsReadyToRender(_eventQueue, _event)) { //Render //stuff //swap buffers and clear to color SwapBuffers(); } } void Game::Update() { if (IsReadyToUpdate(_event)) { //Temporary assertion if (_states.size()) { _states.top()->Update(); } else { //TODO: Handle this in a different way, as this is just bullshit std::cerr << "_states stack is left empty" << std::endl; std::cin.get(); Exit(); } } else if (WindowGotClosed(_event)) { Exit(); } } void Game::Flush() { al_wait_for_event(_eventQueue, &_event); al_flush_event_queue(_eventQueue); } void Game::ChangeState(State* newState) { if (newState) { //conversion to unique pointer UniquePointerState uniquePointerNewState = std::unique_ptr<State>(newState); //push to _states container with the use of std::move neccessary when performing //unq_ptr operations, since they have no copy constructor _states.push(std::move(uniquePointerNewState)); } else { //TODO: Handle exception when the provided state is a nullptr } } void Game::LeaveState() { _states.pop(); } void Game::StatesCleanup() { //iterates through each state, cleans up any memory allocations //and removes states from the stack as well. while (_states.size()) { _states.top()->Cleanup(); _states.pop(); } }
true
3123da639536d82e42104ac8411709b11a20eb23
C++
ThiagoAugustoSM/CInProjects
/2017-2/algoritmos/lista5/test.cpp
UTF-8
274
2.59375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main(){ vector <int> distancias(10); vector <bool> shortPath(10); // distancias.insert(0); distancias[1] = 3; shortPath[1] = false; cout << distancias[1]; return 0; }
true
2a6d0e155ec5e275ac535b52e57c6fb082262728
C++
klauchek/2-sem
/subcontainers_templated/vector_templated/vector_templated/vector_templated.cpp
UTF-8
2,043
3.46875
3
[]
no_license
 #include "vector_templated.h" template <typename T> subvector<T>::subvector() { mas = nullptr; capacity = 0; top = 0; } template <typename T> subvector<T>::~subvector() { delete[] mas; mas = nullptr; } template <typename T> void subvector<T>::clear() { top = 0; } template <typename T> void subvector<T>::expand(size_t new_cap) { T* new_mas = new T[new_cap]; for (int i = 0; i < top; i++) new_mas[i] = mas[i]; delete[] mas; mas = new_mas; } //добавление элемента в конец недовектора //с выделением дополнительной памяти при необходимости template <typename T> bool subvector<T>::push_back(T d) { if (capacity > top) { top++; mas[top - 1] = d; } else { expand(2 * ((capacity)+1)); capacity = 2 * ((capacity)+1); top++; mas[top - 1] = d; } return true; } //удаление элемента с конца недовектора template <typename T> T subvector<T>::pop_back() { if (top == 0) return 0; T last = mas[top - 1]; top--; return last; } //увеличить емкость недовектора template <typename T> bool subvector<T>::resize(size_t new_capacity) { T* new_mas = new T[new_capacity]; for (int i = 0; i < top; i++) { new_mas[i] = mas[i]; } capacity = new_capacity; delete[] mas; mas = new_mas; return true; } //очистить неиспользуемую памят template <typename T> void subvector<T>::shrink_to_fit() { if (capacity == top) return; if (capacity > top) { expand(top); capacity = top; } } //! Reloaded operator [] for vector template <typename T> T subvector<T>::operator [](int i) { return mas[i]; } template <typename T> size_t subvector<T>::get_cap() { return capacity; } template <typename T> size_t subvector<T>::get_top() { return top; }
true
0f87e2891e298c7b080e8f73bbb567b903ab1e3a
C++
iandioch/solutions
/uva/13146/solution.cc
UTF-8
869
3.15625
3
[]
no_license
#define min(a, b) ((a) < (b) ? (a) (b)) #include <iostream> using namespace std; int levenshtein(string a, string b) { int d[105][105]; int m = a.length(); int n = b.length(); for (int i = 1; i <= m; ++i) { d[i][0] = i; } for (int j = 1; j <= n; ++j) { d[0][j] = j; } for (int j = 1; j <= n; ++j) { for (int i = 1; i <= m; ++i) { int cost = 0; if (a[i-1] != b[j-1]) { cost = 1; } d[i][j] = min(d[i-1][j] + 1, min(d[i][j-1] + 1, d[i-1][j-1] + cost)); } } return d[m][n]; } int main() { int n; cin >> n; cin.ignore(); while (n--) { string a, b; getline(cin, a); getline(cin, b); cout << levenshtein(a, b) << "\n"; } return 0; }
true
dc592112d5482ce9f7b83c97b6bc9f49d4e31803
C++
danasf/simplepixel
/simplecolor.ino
UTF-8
5,877
3.125
3
[]
no_license
/** * Simple WS2812B / Neopixel Driver * Dana Sniezko & Alex Segura * Coded at Hacker School (http://www.hackerschool.com), Summer 2014 * * General resources: * http://www.avr-asm-tutorial.net/avr_en/beginner/ * http://www.avrbeginners.net/ * http://www.arduino.cc/ * https://learn.adafruit.com/adafruit-neopixel-uberguide/overview **/ #define NUM_LEDS 15 // number of LEDs #define BYTES (NUM_LEDS*3) // each LED has 3 color channels, NUM_LED*3 #define PORT PORTD // PORTD, see http://www.arduino.cc/en/Reference/PortManipulation #define LEDPIN PORTD6 // pin 6 on Arduino #define DEBUG true // Debug is on uint8_t* leds = NULL; void setup() { if(DEBUG) { Serial.begin(9600); } delay(1000); // wait a second! DDRD = DDRD | B01000000; // set pin 6 on PortD to output leds = (uint8_t*) malloc(BYTES); // allocate a memory block, great! memset(leds,0,BYTES); // zero out this memory space } void loop() { seqFill(255,0,0,30); // seq fill red seqFill(0,255,0,30); // seq fill green seqFill(0,0,255,30); // seq fill blue scanner(255,0,0,40); // larson scanner sine(0.05,10); //rainbow(0.01,10); // rainbows .... to implement } // sequential fill void seqFill(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) { // loop through for (int x=0; x < NUM_LEDS; x++) { if(DEBUG) { debug(x); } setColor(x,r,g,b); updateStrip(); delay(wait); } } // quick fill void quickFill(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) { // loop through for (int x=0; x < NUM_LEDS; x++) { if(DEBUG) { debug(x); } setColor(x,r,g,b); } updateStrip(); delay(wait); } // Larson Scanner void scanner(uint8_t r, uint8_t g, uint8_t b, uint8_t wait) { for (int x=0; x < NUM_LEDS; x++) { clear(); setColor(x,r,g,b); updateStrip(); delay(wait); } for (int x=NUM_LEDS; x > 0; x--) { clear(); setColor(x,r,g,b); updateStrip(); delay(wait); } } // Sine wave void sine(float rt, uint8_t wait) { float in,r; for(in = 0; in < PI*2; in = in+rt) { for(int i=0; i < NUM_LEDS; i++) { // 3 offset sine waves make a rainbow r = sin(i+in) * 127 + 128; setColor(i,(uint8_t)r,0,0); } updateStrip(); delay(wait); } } // blank out strip buffer void clear() { memset(leds,0,BYTES); } // debug function, prints out buffer at position x void debug(uint16_t x) { uint8_t *p = leds + x*3; Serial.print(x); Serial.print(":"); Serial.print(*p++); Serial.print(","); Serial.print(*p++); Serial.print(","); Serial.println(*p); } // make a color from RGB values, these strips are wired GRB so store in that order void setColor(uint16_t pixel,uint8_t r, uint8_t g, uint8_t b) { uint8_t *p = leds + pixel*3; *p++ = g; *p++ = r; *p = b; } void updateStrip() { noInterrupts(); // disable interrupts, we need fine control volatile uint8_t *p = leds; // pointer volatile uint8_t current = *p++; // get current byte, point to next byte volatile uint8_t high = PORT | _BV(LEDPIN); // high = PORTD6 is high volatile uint8_t low = PORT & ~_BV(LEDPIN); // all are low volatile uint8_t temp = low; // start temp at low volatile uint8_t bits = 8; // 8 bits per color chanel volatile uint8_t bytes = BYTES; // bytes in data /** * To send a 1, we need: * 13 cycles on, 7 off * * To send a 0, we need: * 6 cycles on, 14 off **/ asm volatile( "sendbit:" "\n\t" // Label for sending a bit (T=0) "st %a[portptr],%[high]" "\n\t" // 2 cycles, set port HIGH, needed for sending either 0 or 1 (T=2) "sbrc %[cur],7" "\n\t" // if MSB a 1, do the next instruction, else skip (1-2 cycle) (T=4) "mov %[temp],%[high]" "\n\t" // move high into temp, 1 cycle (T=4) "dec %[bits]" "\n\t" // decrement bit count, 1 cycle (T=5) "nop" "\n\t" // do nothing for 1 cycle (T=6) "st %a[portptr],%[temp]" "\n\t" // move temp val into port, 2 cycles (T=8) "mov %[temp],%[low]" "\n\t" // move low into temp, 1 cycle (T=9) "breq newbyte" "\n\t" // if bit count is 0, go to next byte, 1 or 2 cycles? (T=10) "rol %[cur]" "\n\t" // shift current byte left, 1 cycle (T=11) "nop" "\n\t" // do nothing for 1 cycle (T=12) "nop" "\n\t" // do nothing for 1 cycle (T=13) "st %a[portptr],%[low]" "\n\t" // 2 cycles, sets port LOW (T=15) "nop" "\n\t" // do nothing for 1 cycle (T=16) "nop" "\n\t" // do nothing for 1 cycle (T=17) "nop" "\n\t" // do nothing for 1 cycle (T=18) "rjmp sendbit" "\n\t" // jump back to the bit label (T=20) "newbyte:" "\n\t" // label for next byte (T=10) "ldi %[bits],8" "\n\t" // reset bit count to 8 bits (T=11) "st %a[portptr],%[low]" "\n\t" // 2 cycles, sets PORT to LOW (T=12) "dec %[bytes]" "\n\t" // remove 1 from byte count, 1 cycle (T=13) "ld %[cur],%a[p]+" "\n\t" // advance the pointer, load as current byte, 2 cycles (T=15) "nop" "\n\t" // do nothing for 1 cycle 1 (T=16) "nop" "\n\t" // do nothing for 1 cycle 1 (T=17) "nop" "\n\t" // do nothing for 1 cycle 1 (T=18) "brne sendbit" "\n\t" // (T=20) if byte count is not 0, send another bit! : // outputs NONE : // inputs // helpful resource: http://www.nongnu.org/avr-libc/user-manual/inline_asm.html [portptr] "e" (&PORT), [bits] "r" (bits), [bytes] "r" (bytes), [temp] "r" (temp), [high] "r" (high), [low] "r" (low), [p] "e" (p), [cur] "r" (current) ); delayMicroseconds(60); // latch data interrupts(); // we can enable interrupts again }
true
9cfb4f0ff1f8f46295ba17936e1f5fbca80eab21
C++
hamedsabri/RayTracingTheNextWeek
/src/raytrace/diffuseLight.h
UTF-8
1,174
2.84375
3
[ "MIT" ]
permissive
#pragma once /// \file raytrace/diffuseLight.h /// /// A diffuse emissive material. #include <raytrace/hitRecord.h> #include <raytrace/material.h> #include <raytrace/randomUnitVector.h> #include <raytrace/texture.h> RAYTRACE_NS_OPEN /// \class DiffuseLight /// /// An emissive class DiffuseLight : public Material { public: /// Explicit constructor with an texture input for sampling the emission. inline explicit DiffuseLight( const TextureSharedPtr& i_emissive ) : m_emissive( i_emissive ) { } /// This material emits light, but does not scatter any rays. /// /// \retval false inline virtual bool Scatter( const raytrace::Ray& i_ray, const HitRecord& i_hitRecord, gm::Vec3f& o_attenuation, raytrace::Ray& o_scatteredRay ) const override { return false; } inline virtual gm::Vec3f Emit( const gm::Vec2f& i_uv, const gm::Vec3f& i_position ) const override { return m_emissive->Sample( i_uv, i_position ); } private: TextureSharedPtr m_emissive; }; RAYTRACE_NS_CLOSE
true
2ac019c58a26959f75b98ef6102281a07e213bd7
C++
alooftr/OxyPremiumSRC
/CSGOSimple/valve_sdk/misc/BoneAccessor.h
UTF-8
368
2.6875
3
[]
no_license
#pragma once class matrix3x4_t; class CBoneAccessor { public: inline matrix3x4_t* GetBoneArrayForWrite() { return m_pBones; } inline void SetBoneArrayForWrite(matrix3x4_t* bone_array) { m_pBones = bone_array; } alignas(16) matrix3x4_t* m_pBones; int m_ReadableBones; // Which bones can be read. int m_WritableBones; // Which bones can be written. };
true
2b544204ffd6cc1cc62adde412b25821478e21d3
C++
liyuefeilong/leetcode
/Longest Valid Parentheses/Longest Valid Parentheses/LongestValidParentheses.h
UTF-8
549
3.328125
3
[]
no_license
#include <iostream> #include <string> #include <stack> using namespace std; class Solution { public: int longestValidParentheses(string s) { int maxLength = 0, start = 0; int Size = s.size(); stack<int> temp; for (int i = 0; i < Size; ++i) { if (s[i] == '(') { temp.push(s[i]); } else { if (temp.empty()) { start = i; } else { temp.pop(); if (temp.empty()) { if (maxLength < i - start + 1) maxLength = i - start + 1; } } } } return maxLength; } };
true
9952a6a13db7b1c9c9362e29e48a44e230076805
C++
ewilbur/ucr-work
/CS14/Lab 2/Martian/Smart.cpp
UTF-8
3,419
3.71875
4
[]
no_license
/* ****************************************************************************** Evan Wilbur CS14 UCR Winter 2016 January 2016 Assignment 2 Lab Section 21 ****************************************************************************** */ #include "Smart.h" Smart::Smart(unsigned val) : Martian(val) {} /* * Tests if a number is a perfect square */ const bool Smart::perfect_square(int val) const { return pow(floor(sqrt(val)), 2) == val; } /* * Uses Legrendre's theorem to determine if a number must be written as a sum * of four squares. */ const bool Smart::four_square(int val) const { while(pow_2_divides_number(val, 2)) val /= 4; return pow_2_divides_number(val - 7, 3); } /* * Tests divisibity by powers of 2. Because why not make things more * complicated than necessary by using bitshift? */ const bool Smart::pow_2_divides_number(int val, unsigned power) const { if(power == 0) return true; else if(val & 1 == 1) return false; else return pow_2_divides_number((val >> 1), power - 1); } /* * Takes a number that must be written as the sum of four squares and reduces * it to one that can be written as as sum of three squares. */ const int Smart::reduce_to_three_square(int val) { /* This is the lower bound of possible options. Because math */ int startIndex = floor(sqrt(val / 4)); for(int i = startIndex; i * i < val; i++) { /* Take a guess, up a tick */ ticks++; /* The new number passes the four-square test*/ if(!four_square(val - i * i)) return i; } } /* * Writes the number as a sum of two squares if possible. */ void Smart::solve_two_square() { int startIndex = sqrt(denomination >> 1); for(int i = startIndex; i * i < denomination; i++) { ticks++; if(perfect_square(denomination - i * i)) { solution[0] = i; solution[1] = sqrt(denomination - i * i); solutionSize = 2; solved = true; } } } /* * Writes a number as a sum of three squares. */ void Smart::solve_three_square() { for(int i = sqrt(denomination / 3); i * i < denomination; i++) { ticks++; /* Reduce the value to solve by i^2 */ Smart a(denomination - i * i); /* Try to solve it with two squares*/ a.solve_two_square(); /* If it has a two square solution, copy it over */ if(a.get_size()) { solution[0] = a[0]; solution[1] = a[1]; solution[2] = i; solutionSize = 3; solved = true; return; } } } void Smart::solve() { int residue; /* The number is a perfect square */ if(perfect_square(denomination)) { solution[0] = sqrt(denomination); solutionSize = 1; ticks++; } /* The number must be written as a sum of four squares*/ else if(four_square(denomination)) { /* Reduce it*/ residue = reduce_to_three_square(denomination); Smart a(denomination - residue * residue); solution[3] = residue; /* Solve the reduced solution */ a.solve_three_square(); /* Copy everything over */ solution[0] = a[0]; solution[1] = a[1]; solution[2] = a[2]; ticks += a.get_ticks(); solutionSize = 4; } else { /* Check if it has a two square solution */ solve_two_square(); /* If it doesn't, solve for the three square solution */ if(solutionSize == 0) solve_three_square(); } solved = true; return; }
true
d38c5a20765ca0b02181c460ccfbc72c34e5d2a2
C++
DanNixon/stfc-eew-2018
/code_samples/mcu/single_button/src/main.ino
UTF-8
638
2.78125
3
[]
no_license
#include <Streaming.h> const int button_pin = 15; volatile unsigned long last_change_time = 0; volatile bool button_pushed = false; unsigned int times_pressed = 0; void handle_interrupt() { const auto now = millis(); if (now - last_change_time > 500) { button_pushed = true; last_change_time = now; } } void setup() { Serial.begin(9600); pinMode(button_pin, INPUT_PULLUP); attachInterrupt(digitalPinToInterrupt(button_pin), handle_interrupt, FALLING); } void loop() { if (button_pushed) { button_pushed = false; Serial << "Button was pushed " << ++times_pressed << " time(s)\n"; } delay(10); }
true
81cfc999198f095827465979f49ebaf3320b365f
C++
JosvanGoor/ScientificVisualisation
/src/window/mousemoved.cc
UTF-8
2,017
2.71875
3
[]
no_license
#include "window.ih" #include <iostream> void Window::mouse_moved(double xpos, double ypos) { d_mouse_zx = xpos; d_mouse_zy = ypos; if (!d_mouse_dragging) return; // If we render in 3d we need to unproject the mouse and // translate the coordinates to screen space. if (d_drawmode == DrawMode::SMOKE3D || d_drawmode == DrawMode::STREAMTUBES) { glm::vec3 world_pos = unproject_mouse(); // if the coordinates fall outside of the grid we ignore them if (abs(world_pos.x) >= 10.0 || abs(world_pos.y) >= 10.0) return; xpos = ((world_pos.x + 10.0) / 20.0) * d_width; ypos = (1.0 - ((world_pos.y + 10.0) / 20.0)) * d_height; } double fix_x = d_width / static_cast<double>(d_simulation.gridsize() + 1) + 5; double fix_y = d_height / static_cast<double>(d_simulation.gridsize() + 1) + 5; xpos = xpos > fix_x ? xpos : fix_x; xpos = xpos < d_width - fix_x ? xpos : fix_x; ypos = ypos > fix_y ? ypos : fix_y; ypos = ypos < d_height - fix_y ? ypos : fix_y; int xi = clamp((d_simulation.gridsize() + 1) * (xpos / d_width)); int yi = clamp((d_simulation.gridsize() + 1) * ((d_height - ypos) / d_height)); int X = xi; //? int Y = yi; //?? if (X > (d_simulation.gridsize() - 1)) X = d_simulation.gridsize() - 1; if (Y > (d_simulation.gridsize() - 1)) Y = d_simulation.gridsize() - 1; if (X < 0) X = 0; if (Y < 0) Y = 0; ypos = d_height - ypos; double dx = xpos - d_mouse_lastx; double dy = ypos - d_mouse_lasty; double len = sqrt(dx * dx + dy * dy); if (len != 0.0) //shouldnt ever be false lol { dx *= 0.1 / len; dy *= 0.1 / len; } else cout << "the comment is wrong!\n"; size_t pos = Y * d_simulation.gridsize() + X; d_simulation.force_x()[pos] += dx; d_simulation.force_y()[pos] += dy; d_simulation.rho()[pos] = 10.0f; d_mouse_lastx = xpos; d_mouse_lasty = ypos; }
true
573093588953579c2af234f14e94b2a8f63840f2
C++
chukgu/Algorithm
/Baekjoon/Algorithm_study/2156_포도주 시식.cpp
UTF-8
1,003
2.5625
3
[]
no_license
#include <iostream> #include <string> #include <algorithm> #define max(a,b) (((a)>(b))?(a):(b)) using namespace std; int dp[10001][3]; int p[10001]; int main() { int T; scanf("%i", &T); for (int i = 1; i <= T; i++) { scanf("%i", &p[i]); } dp[1][0] = 0, dp[1][1] = p[1]; for (int i = 2; i <= T; i++) { dp[i][0] = max(dp[i - 1][0], max(dp[i - 1][1], dp[i - 1][2])); dp[i][1] = dp[i - 1][0] + p[i]; dp[i][2] = dp[i - 1][1] + p[i]; } printf("%i\n", max(dp[T][0], max(dp[T][1], dp[T][2]))); return 0; } //#include <iostream> //#include <string> //#include <algorithm> //#define max(a,b) (((a)>(b))?(a):(b)) //using namespace std; // //int dp[10001]; //int p[10001]; // //int main() //{ // int T; // scanf("%i", &T); // for (int i = 1; i <= T; i++) { // scanf("%i", &p[i]); // } // dp[0] = 0,dp[1] = p[1], dp[2] = p[1] + p[2]; // for (int i = 3; i <= T; i++) { // dp[i] = max(dp[i - 1], max(dp[i - 2] + p[i], dp[i - 3] + p[i - 1] + p[i])); // } // printf("%i\n", dp[T]); // return 0; //}
true
f0ec42b3f7250340aa64452bb11dbb42fd6ea820
C++
datakun/SourceCodeReading
/2015/OpenCL/Resources/Samples_UTF8_unix/Chapter5/Bitmap/MyError.h
UTF-8
505
2.78125
3
[]
no_license
// List5.4 /* * MyError.h (rev1.1, 28.Nov.2010) * Copyright 2010 Takashi Okuozno All rights reserved. */ #ifndef __MY_ERROR_H__ #define __MY_ERROR_H__ #include <string> class MyError { public: MyError(const std::string & msg, const std::string & function = "") {mMsg = msg + " " + function;} virtual ~MyError() {}; const std::string message() const {return mMsg;} const char * cstr() const {return mMsg.c_str();} private: std::string mMsg; }; #endif // __MY_ERROR_H__
true
c86c376295f50c7e1a067b662b554ff38b28be1b
C++
kevpeng/mips-simulation
/Simulate2.cpp
UTF-8
34,208
2.5625
3
[]
no_license
//g++ -Wall main.cpp Simulate.cpp InstructionMemory.cpp InstructionParser.cpp ConfigFileParser.cpp DataMemory.cpp ShiftLeft.cpp SignExtend.cpp ALU.cpp MUX.cpp ALUControl.cpp Control.cpp RegParser.cpp MemParser.cpp RegisterFile.cpp PC.cpp -o main /* * * * Author: Tianchang Yang * Date: 11/30/17 */ #include "Simulate.h" //Default constructor Simulate::Simulate(string filename) { myConfigFile = filename; batch = false; printMemory = false; writeToFile = false; ConfigFileParser configParser = ConfigFileParser(); configParser.configure(myConfigFile); string programFile = configParser.getInputFile(); string memoryFile = configParser.getMemoryFile(); string registerFile = configParser.getRegisterFile(); outputFile = configParser.getOutputFile(); batch = configParser.getOutputMode(); writeToFile = configParser.getWriteToFile(); printMemory = configParser.getPrintMemory(); instruction_Memory = InstructionMemory(programFile); //instruction_Memory.readAddress("00400000"); //cout << instruction_Memory.getInstruction() << endl; //cout << instruction_Memory.getInstruction().empty() << endl; //instruction_Memory.readAddress("00400C00"); //cout << instruction_Memory.getInstruction() << endl; //cout << instruction_Memory.getInstruction().empty() << endl; data_Memory = DataMemory(memoryFile); shift_Left_1 = ShiftLeft(); shift_Left_2 = ShiftLeft(); //cout << shift_Left_2.shift("11111111111111111111111111111111") << endl; sign_Extend = SignExtend(); //cout << sign_Extend.extend("11010100010000101") << endl; ALU_1 = ALU(); ALU_2 = ALU(); ALU_3 = ALU(); MUX_1 = MUX(); MUX_2 = MUX(); MUX_3 = MUX(); MUX_4 = MUX(); MUX_5 = MUX(); ALU_Control = ALUControl(); main_Control = Control(); register_File = RegisterFile(registerFile); //register_File.printRegisterFile(); //register_File.readRegister1("11111"); //cout << register_File.readData1() << endl; program_Counter = PC(); if (!writeToFile) { run(); } else { runNWrite(); } } //performs appropriate function void Simulate::run(){ string curAddress = program_Counter.getAddress(); instruction_Memory.readAddress(curAddress); string curInstruction = instruction_Memory.getInstruction(); string curOriginal = instruction_Memory.getOriginal(); cout << "------------------begining simulation------------------" << endl; while (!curInstruction.empty()) { if (!batch) { cout << "Press Enter to Continue"; cin.ignore(); } cout << "Next instruction is: " << curOriginal << endl; cout << "binary machine code: " << curInstruction << endl << endl; if (printMemory) { register_File.printRegisterFile(); cout << endl; data_Memory.print(); cout << endl; instruction_Memory.print(); } //PC cout << "PC: \ncurrent PC address: " << "0x" << curAddress << endl << endl; cout << "Instruction memory: current instruction memory address: " << "0x" << curAddress << endl; cout << "current instruction fetched from instruction memory: " << "0x" << bin2Hex(curInstruction) << endl; //cout << curInstruction << endl; //PC + 4 ALU_1.setOperand1(hex2Bin(curAddress)); ALU_1.setOperand2("00000000000000000000000000000100"); ALU_1.setOperation(1); ALU_1.execute(); string PC_plus_4 = bin2Hex(ALU_1.getOutput()); cout << endl; cout << "ALU 1: \naddress PC passed into ALU 1 is: 0x" << curAddress << endl; cout << "the other operand ALU 1 takes in is: 0x" << bin2Hex("00000000000000000000000000000100") << endl; cout << "the result of ALU 1 is: 0x" << bin2Hex(ALU_1.getOutput()) << endl << endl; //cout << curAddress << endl; //Control string opcode = curInstruction.substr(0, 6); main_Control.setOpcode(opcode); //cout << opcode << endl; cout << "Control: \nThe opcode passed to control is: 0x" << bin2Hex("00" + opcode) << endl; cout << "RegDst: " << main_Control.getRegDst() << endl; cout << "Jump: " << main_Control.getJump() << endl; cout << "Branch: " << main_Control.getBranch() << endl; cout << "MemRead: " << main_Control.getMemRead() << endl; cout << "MemToReg: " << main_Control.getMemToReg() << endl; cout << "ALUOp: " << main_Control.getALUOp() << endl; cout << "MemWrite: " << main_Control.getMemWrite() << endl; cout << "ALUSrc: " << main_Control.getALUSrc() << endl; cout << "RegWrite: " << main_Control.getRegWrite() << endl << endl; //MUX 1 MUX_1.setOperand1(curInstruction.substr(11,5)); MUX_1.setOperand2(curInstruction.substr(16,5)); MUX_1.setControl(main_Control.getRegDst()); MUX_1.execute(); string MUX_1_output = MUX_1.getOutput(); cout << "MUX 1: \nThe first operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; cout << "The second operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(16,5)) << endl; cout << "The control passed to MUX 1 from main control is: " << main_Control.getRegDst() << endl; cout << "The output from MUX 1 is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; //register file -- read register_File.readRegister1(curInstruction.substr(6,5)); register_File.readRegister2(curInstruction.substr(11,5)); register_File.writeToRegister(MUX_1_output); register_File.setWriteSignal(main_Control.getRegWrite()); string registerData1 = register_File.readData1(); string registerData2 = register_File.readData2(); cout << "Register File: \nThe first read register number is: 0x" << bin2Hex("000" + curInstruction.substr(6,5)) << endl; cout << "The second read register number is: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; cout << "The data read from first register is: 0x" << bin2Hex(registerData1) << endl; cout << "The data read from second register is: 0x" << bin2Hex(registerData2) << endl << endl; //sign extend string extend_Data = sign_Extend.extend(curInstruction.substr(16,16)); //cout << curInstruction.substr(16,16) << endl; cout << "Sign Extend: \nThe input is: 0x" << bin2Hex(curInstruction.substr(16,16)) << endl; cout << "The output is: 0x" << bin2Hex(extend_Data) << endl << endl; //MUX 2 MUX_2.setOperand1(registerData2); MUX_2.setOperand2(extend_Data); MUX_2.setControl(main_Control.getALUSrc()); MUX_2.execute(); string MUX_2_output = MUX_2.getOutput(); cout << "MUX 2: \nThe first operand passed in: 0x" << bin2Hex(registerData2) << endl; cout << "The second operand passed in: 0x" << bin2Hex(extend_Data) << endl; cout << "The control passed to MUX 2 from main control is: " << main_Control.getALUSrc() << endl; cout << "The output from MUX 2 is: 0x" << bin2Hex(MUX_2_output) << endl << endl; //ALU Control ALU_Control.setALUOp(main_Control.getALUOp()); //Set ALUOp before set instruction!!! ALU_Control.setInstruction(curInstruction.substr(26,6)); int ALUOperation = ALU_Control.getOutput(); cout << "ALU Control: \nThe instruction received is: 0x" << bin2Hex("00" + curInstruction.substr(26,6)) << endl; cout << "The ALUOp received from main control is: " << main_Control.getALUOp() <<endl; cout << "The control sending to ALU 3 is: " << ALUOperation << endl << endl; //ALU 3 ALU_3.setOperand1(registerData1); ALU_3.setOperand2(MUX_2_output); ALU_3.setOperation(ALUOperation); ALU_3.execute(); string ALU_3_result = ALU_3.getOutput(); bool isZero = ALU_3.isEqual(); cout << "ALU 3:\nOperand 1 is: 0x" << bin2Hex(registerData1) << endl; cout << "Operand 2 is: 0x" << bin2Hex(MUX_2_output) << endl; cout << "Operation for ALU 3 to perform is: " << ALUOperation << endl; cout << "the result of ALU 3 is: 0x" << bin2Hex(ALU_3_result) << endl; cout << "The two operand is equal or not: " << isZero << endl << endl; //Data memory data_Memory.setAddress(bin2Hex(ALU_3_result)); //if (main_Control.getMemRead()) { // cout << "ATTENTION: " << bin2Hex(ALU_3_result) << endl; //} data_Memory.setWriteData(registerData2); data_Memory.setMemWrite(main_Control.getMemWrite()); data_Memory.setMemRead(main_Control.getMemRead()); data_Memory.execute(); string memory_Data = data_Memory.readData(); cout << "Data Memory: \nAddress is set to: 0x" << bin2Hex(ALU_3_result) << endl; cout << "Data to write is: 0x" << bin2Hex(registerData2) << endl; cout << "MemWrite signal received from main control is: " << main_Control.getMemWrite() << endl; cout << "MemRead signal received from main control is: " << main_Control.getMemRead() << endl; cout << "The data read from data memory is: 0x" << bin2Hex(memory_Data) << endl << endl; //MUX 3 MUX_3.setOperand1(ALU_3_result); MUX_3.setOperand2(memory_Data); MUX_3.setControl(main_Control.getMemToReg()); MUX_3.execute(); string MUX_3_output = MUX_3.getOutput(); cout << "MUX 3: \nThe first operand passed in: 0x" << bin2Hex(ALU_3_result) << endl; cout << "The second operand passed in: 0x" << bin2Hex(memory_Data) << endl; cout << "The control passed to MUX 3 from main control is: " << main_Control.getMemToReg() << endl; cout << "The output from MUX 3 is: 0x" << bin2Hex(MUX_3_output) << endl << endl; if (opcode == "000000" && curInstruction.substr(26,6) == "101010") { if (MUX_3_output.substr(0,1) == "1") { MUX_3_output = "00000000000000000000000000000001"; } else { MUX_3_output = "00000000000000000000000000000000"; } if (registerData1.substr(0,1) == "0" && MUX_2_output.substr(0,1) == "1") { MUX_3_output = "00000000000000000000000000000000"; } } //writeback register_File.writeData(MUX_3_output); cout << "Writeback: \nThe RegWrite signal is: " << main_Control.getRegWrite() << endl; cout << "The data to write to register is: 0x" << bin2Hex(MUX_3_output) << endl; cout << "The register to write to is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; //shift left 1 string jump_address = shift_Left_1.shift(curInstruction.substr(6,26)); cout << "Shift left 1: \nThe instruction passed in is: 0x" << bin2Hex("00" + curInstruction.substr(6,26)) << endl; cout << "Shift result is: 0x" << bin2Hex(jump_address) << endl; //cout << PC_plus_4 << endl; jump_address = hex2Bin(PC_plus_4).substr(0,4) + jump_address; jump_address = bin2Hex(jump_address); //cout << jump_address << endl; cout << "The jump address is: 0x" << jump_address << endl << endl; //shift left 2 string branch_address = shift_Left_2.shift(extend_Data); cout << "Shift left 2: \nThe instruction passed in is: 0x" << bin2Hex(extend_Data) << endl; cout << "Shift result is: 0x" << bin2Hex(branch_address) << endl << endl; //ALU 2 ALU_2.setOperand1(hex2Bin(PC_plus_4)); ALU_2.setOperand2(branch_address); ALU_2.setOperation(1); ALU_2.execute(); string ALU_2_result = ALU_2.getOutput(); cout << "ALU 2:\nOperand 1 is: 0x" << PC_plus_4 << endl; cout << "Operand 2 is: 0x" << bin2Hex(branch_address) << endl; cout << "the result of ALU 2 is: 0x" << bin2Hex(ALU_2_result) << endl << endl; branch_address = bin2Hex(ALU_2_result); MUX_5.setOperand1(PC_plus_4); MUX_5.setOperand2(branch_address); int MUX_5_Control; if (isZero && main_Control.getBranch()) { MUX_5_Control = 1; } else { MUX_5_Control = 0; } MUX_5.setControl(MUX_5_Control); MUX_5.execute(); string MUX_5_output = MUX_5.getOutput(); cout << "MUX 5: \nThe first operand passed in: 0x" << PC_plus_4 << endl; cout << "The second operand passed in: 0x" << branch_address << endl; cout << "The control passed to MUX 5 from main control is: " << MUX_5_Control << endl; cout << "The output from MUX 5 is: 0x" << MUX_5_output << endl << endl; MUX_4.setOperand1(MUX_5_output); MUX_4.setOperand2(jump_address); MUX_4.setControl(main_Control.getJump()); MUX_4.execute(); string nextAddress = MUX_4.getOutput(); cout << "MUX 4: \nThe first operand passed in: 0x" << MUX_5_output << endl; cout << "The second operand passed in: 0x" << jump_address << endl; cout << "The control passed to MUX 4 from main control is: " << main_Control.getJump() << endl; cout << "The output from MUX 4 is: 0x" << nextAddress << endl << endl; //update address to PC and fetch next instruction curAddress = nextAddress; instruction_Memory.readAddress(curAddress); curInstruction = instruction_Memory.getInstruction(); curOriginal = instruction_Memory.getOriginal(); cout << endl << endl; //data_Memory.print(); //curInstruction = ""; } cout << "------------------end------------------" << endl; if (printMemory) { register_File.printRegisterFile(); cout << endl; data_Memory.print(); cout << endl; instruction_Memory.print(); } } //performs appropriate function void Simulate::runNWrite(){ ofstream writeFile; writeFile.open(outputFile); string curAddress = program_Counter.getAddress(); instruction_Memory.readAddress(curAddress); string curInstruction = instruction_Memory.getInstruction(); string curOriginal = instruction_Memory.getOriginal(); cout << "------------------begining simulation------------------" << endl; writeFile << "------------------begining simulation------------------" << endl; while (!curInstruction.empty()) { if (!batch) { cout << "Press Enter to Continue"; writeFile << "Press Enter to Continue" << endl; cin.ignore(); } cout << "Next instruction is: " << curOriginal << endl; cout << "binary machine code: " << curInstruction << endl << endl; writeFile << "Next instruction is: " << curOriginal << endl; writeFile << "binary machine code: " << curInstruction << endl << endl; if (printMemory) { register_File.printRegisterFile(); cout << endl; data_Memory.print(); cout << endl; instruction_Memory.print(); //register_File.writeToFile(outputFile); //writeFile << endl; //data_Memory.writeToFile(outputFile); //writeFile << endl; //instruction_Memory.print(); writeFile << "Printing Registers" << endl; map<int, string> registers = register_File.getMap(); for (int i = 0; i < 32; i++) { writeFile << "Register[" << i << "] = " << "\t 0x"<< bin2Hex(registers[i]) << endl; } writeFile << endl << "Memory Contents:" << endl; map<string,string> dataMemoryMap = data_Memory.getMap(); map<string,string>::iterator it2; for(it2 = dataMemoryMap.begin(); it2 != dataMemoryMap.end(); it2++){ string t = it2->second; writeFile << "address:[0x" << it2->first << "] = 0x" << bin2Hex(t) << endl; } writeFile << endl; writeFile << "Instruction Memory Contents:" << endl; map<string, string> myInstruction = instruction_Memory.getMap(); map<string,string>::iterator it3; for(it3 = myInstruction.begin(); it3 != myInstruction.end(); it3++){ string t = it3->second; writeFile << "address:[0x" << it3->first << "] = 0x" << bin2Hex(t) << endl; } writeFile << endl; } //PC cout << "PC: \ncurrent PC address: " << "0x" << curAddress << endl << endl; cout << "Instruction memory: current instruction memory address: " << "0x" << curAddress << endl; cout << "current instruction fetched from instruction memory: " << "0x" << bin2Hex(curInstruction) << endl; writeFile << "PC: \ncurrent PC address: " << "0x" << curAddress << endl << endl; writeFile << "Instruction memory: current instruction memory address: " << "0x" << curAddress << endl; writeFile << "current instruction fetched from instruction memory: " << "0x" << bin2Hex(curInstruction) << endl; //cout << curInstruction << endl; //PC + 4 ALU_1.setOperand1(hex2Bin(curAddress)); ALU_1.setOperand2("00000000000000000000000000000100"); ALU_1.setOperation(1); ALU_1.execute(); string PC_plus_4 = bin2Hex(ALU_1.getOutput()); cout << endl; cout << "ALU 1: \naddress PC passed into ALU 1 is: 0x" << curAddress << endl; cout << "the other operand ALU 1 takes in is: 0x" << bin2Hex("00000000000000000000000000000100") << endl; cout << "the result of ALU 1 is: 0x" << bin2Hex(ALU_1.getOutput()) << endl << endl; //cout << curAddress << endl; writeFile << endl; writeFile << "ALU 1: \naddress PC passed into ALU 1 is: 0x" << curAddress << endl; writeFile << "the other operand ALU 1 takes in is: 0x" << bin2Hex("00000000000000000000000000000100") << endl; writeFile << "the result of ALU 1 is: 0x" << bin2Hex(ALU_1.getOutput()) << endl << endl; //Control string opcode = curInstruction.substr(0, 6); main_Control.setOpcode(opcode); //cout << opcode << endl; cout << "Control: \nThe opcode passed to control is: 0x" << bin2Hex("00" + opcode) << endl; cout << "RegDst: " << main_Control.getRegDst() << endl; cout << "Jump: " << main_Control.getJump() << endl; cout << "Branch: " << main_Control.getBranch() << endl; cout << "MemRead: " << main_Control.getMemRead() << endl; cout << "MemToReg: " << main_Control.getMemToReg() << endl; cout << "ALUOp: " << main_Control.getALUOp() << endl; cout << "MemWrite: " << main_Control.getMemWrite() << endl; cout << "ALUSrc: " << main_Control.getALUSrc() << endl; cout << "RegWrite: " << main_Control.getRegWrite() << endl << endl; writeFile << "Control: \nThe opcode passed to control is: 0x" << bin2Hex("00" + opcode) << endl; writeFile << "RegDst: " << main_Control.getRegDst() << endl; writeFile << "Jump: " << main_Control.getJump() << endl; writeFile << "Branch: " << main_Control.getBranch() << endl; writeFile << "MemRead: " << main_Control.getMemRead() << endl; writeFile << "MemToReg: " << main_Control.getMemToReg() << endl; writeFile << "ALUOp: " << main_Control.getALUOp() << endl; writeFile << "MemWrite: " << main_Control.getMemWrite() << endl; writeFile << "ALUSrc: " << main_Control.getALUSrc() << endl; writeFile << "RegWrite: " << main_Control.getRegWrite() << endl << endl; //MUX 1 MUX_1.setOperand1(curInstruction.substr(11,5)); MUX_1.setOperand2(curInstruction.substr(16,5)); MUX_1.setControl(main_Control.getRegDst()); MUX_1.execute(); string MUX_1_output = MUX_1.getOutput(); cout << "MUX 1: \nThe first operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; cout << "The second operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(16,5)) << endl; cout << "The control passed to MUX 1 from main control is: " << main_Control.getRegDst() << endl; cout << "The output from MUX 1 is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; writeFile << "MUX 1: \nThe first operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; writeFile << "The second operand passed in: 0x" << bin2Hex("000" + curInstruction.substr(16,5)) << endl; writeFile << "The control passed to MUX 1 from main control is: " << main_Control.getRegDst() << endl; writeFile << "The output from MUX 1 is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; //register file -- read register_File.readRegister1(curInstruction.substr(6,5)); register_File.readRegister2(curInstruction.substr(11,5)); register_File.writeToRegister(MUX_1_output); register_File.setWriteSignal(main_Control.getRegWrite()); string registerData1 = register_File.readData1(); string registerData2 = register_File.readData2(); cout << "Register File: \nThe first read register number is: 0x" << bin2Hex("000" + curInstruction.substr(6,5)) << endl; cout << "The second read register number is: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; cout << "The data read from first register is: 0x" << bin2Hex(registerData1) << endl; cout << "The data read from second register is: 0x" << bin2Hex(registerData2) << endl << endl; writeFile << "Register File: \nThe first read register number is: 0x" << bin2Hex("000" + curInstruction.substr(6,5)) << endl; writeFile << "The second read register number is: 0x" << bin2Hex("000" + curInstruction.substr(11,5)) << endl; writeFile << "The data read from first register is: 0x" << bin2Hex(registerData1) << endl; writeFile << "The data read from second register is: 0x" << bin2Hex(registerData2) << endl << endl; //sign extend string extend_Data = sign_Extend.extend(curInstruction.substr(16,16)); //cout << curInstruction.substr(16,16) << endl; cout << "Sign Extend: \nThe input is: 0x" << bin2Hex(curInstruction.substr(16,16)) << endl; cout << "The output is: 0x" << bin2Hex(extend_Data) << endl << endl; writeFile << "Sign Extend: \nThe input is: 0x" << bin2Hex(curInstruction.substr(16,16)) << endl; writeFile << "The output is: 0x" << bin2Hex(extend_Data) << endl << endl; //MUX 2 MUX_2.setOperand1(registerData2); MUX_2.setOperand2(extend_Data); MUX_2.setControl(main_Control.getALUSrc()); MUX_2.execute(); string MUX_2_output = MUX_2.getOutput(); cout << "MUX 2: \nThe first operand passed in: 0x" << bin2Hex(registerData2) << endl; cout << "The second operand passed in: 0x" << bin2Hex(extend_Data) << endl; cout << "The control passed to MUX 2 from main control is: " << main_Control.getALUSrc() << endl; cout << "The output from MUX 2 is: 0x" << bin2Hex(MUX_2_output) << endl << endl; writeFile << "MUX 2: \nThe first operand passed in: 0x" << bin2Hex(registerData2) << endl; writeFile << "The second operand passed in: 0x" << bin2Hex(extend_Data) << endl; writeFile << "The control passed to MUX 2 from main control is: " << main_Control.getALUSrc() << endl; writeFile << "The output from MUX 2 is: 0x" << bin2Hex(MUX_2_output) << endl << endl; //ALU Control ALU_Control.setALUOp(main_Control.getALUOp()); //Set ALUOp before set instruction!!! ALU_Control.setInstruction(curInstruction.substr(26,6)); int ALUOperation = ALU_Control.getOutput(); cout << "ALU Control: \nThe instruction received is: 0x" << bin2Hex("00" + curInstruction.substr(26,6)) << endl; cout << "The ALUOp received from main control is: " << main_Control.getALUOp() <<endl; cout << "The control sending to ALU 3 is: " << ALUOperation << endl << endl; writeFile << "ALU Control: \nThe instruction received is: 0x" << bin2Hex("00" + curInstruction.substr(26,6)) << endl; writeFile << "The ALUOp received from main control is: " << main_Control.getALUOp() <<endl; writeFile << "The control sending to ALU 3 is: " << ALUOperation << endl << endl; //ALU 3 ALU_3.setOperand1(registerData1); ALU_3.setOperand2(MUX_2_output); ALU_3.setOperation(ALUOperation); ALU_3.execute(); string ALU_3_result = ALU_3.getOutput(); bool isZero = ALU_3.isEqual(); cout << "ALU 3:\nOperand 1 is: 0x" << bin2Hex(registerData1) << endl; cout << "Operand 2 is: 0x" << bin2Hex(MUX_2_output) << endl; cout << "Operation for ALU 3 to perform is: " << ALUOperation << endl; cout << "the result of ALU 3 is: 0x" << bin2Hex(ALU_3_result) << endl; cout << "The two operand is equal or not: " << isZero << endl << endl; writeFile << "ALU 3:\nOperand 1 is: 0x" << bin2Hex(registerData1) << endl; writeFile << "Operand 2 is: 0x" << bin2Hex(MUX_2_output) << endl; writeFile << "Operation for ALU 3 to perform is: " << ALUOperation << endl; writeFile << "the result of ALU 3 is: 0x" << bin2Hex(ALU_3_result) << endl; writeFile << "The two operand is equal or not: " << isZero << endl << endl; //Data memory data_Memory.setAddress(bin2Hex(ALU_3_result)); //if (main_Control.getMemRead()) { // cout << "ATTENTION: " << bin2Hex(ALU_3_result) << endl; //} data_Memory.setWriteData(registerData2); data_Memory.setMemWrite(main_Control.getMemWrite()); data_Memory.setMemRead(main_Control.getMemRead()); data_Memory.execute(); string memory_Data = data_Memory.readData(); cout << "Data Memory: \nAddress is set to: 0x" << bin2Hex(ALU_3_result) << endl; cout << "Data to write is: 0x" << bin2Hex(registerData2) << endl; cout << "MemWrite signal received from main control is: " << main_Control.getMemWrite() << endl; cout << "MemRead signal received from main control is: " << main_Control.getMemRead() << endl; cout << "The data read from data memory is: 0x" << bin2Hex(memory_Data) << endl << endl; writeFile << "Data Memory: \nAddress is set to: 0x" << bin2Hex(ALU_3_result) << endl; writeFile << "Data to write is: 0x" << bin2Hex(registerData2) << endl; writeFile << "MemWrite signal received from main control is: " << main_Control.getMemWrite() << endl; writeFile << "MemRead signal received from main control is: " << main_Control.getMemRead() << endl; writeFile << "The data read from data memory is: 0x" << bin2Hex(memory_Data) << endl << endl; //MUX 3 MUX_3.setOperand1(ALU_3_result); MUX_3.setOperand2(memory_Data); MUX_3.setControl(main_Control.getMemToReg()); MUX_3.execute(); string MUX_3_output = MUX_3.getOutput(); cout << "MUX 3: \nThe first operand passed in: 0x" << bin2Hex(ALU_3_result) << endl; cout << "The second operand passed in: 0x" << bin2Hex(memory_Data) << endl; cout << "The control passed to MUX 3 from main control is: " << main_Control.getMemToReg() << endl; cout << "The output from MUX 3 is: 0x" << bin2Hex(MUX_3_output) << endl << endl; writeFile << "MUX 3: \nThe first operand passed in: 0x" << bin2Hex(ALU_3_result) << endl; writeFile << "The second operand passed in: 0x" << bin2Hex(memory_Data) << endl; writeFile << "The control passed to MUX 3 from main control is: " << main_Control.getMemToReg() << endl; writeFile << "The output from MUX 3 is: 0x" << bin2Hex(MUX_3_output) << endl << endl; //special case of slt if (opcode == "000000" && curInstruction.substr(26,6) == "101010") { if (MUX_3_output.substr(0,1) == "1") { MUX_3_output = "00000000000000000000000000000001"; } else { MUX_3_output = "00000000000000000000000000000000"; } if (registerData1.substr(0,1) == "0" && MUX_2_output.substr(0,1) == "1") { MUX_3_output = "00000000000000000000000000000000"; } } //writeback register_File.writeData(MUX_3_output); cout << "Writeback: \nThe RegWrite signal is: " << main_Control.getRegWrite() << endl; cout << "The data to write to register is: 0x" << bin2Hex(MUX_3_output) << endl; cout << "The register to write to is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; writeFile << "Writeback: \nThe RegWrite signal is: " << main_Control.getRegWrite() << endl; writeFile << "The data to write to register is: 0x" << bin2Hex(MUX_3_output) << endl; writeFile << "The register to write to is: 0x" << bin2Hex("000" + MUX_1_output) << endl << endl; //shift left 1 string jump_address = shift_Left_1.shift(curInstruction.substr(6,26)); cout << "Shift left 1: \nThe instruction passed in is: 0x" << bin2Hex("00" + curInstruction.substr(6,26)) << endl; cout << "Shift result is: 0x" << bin2Hex(jump_address) << endl; writeFile << "Shift left 1: \nThe instruction passed in is: 0x" << bin2Hex("00" + curInstruction.substr(6,26)) << endl; writeFile << "Shift result is: 0x" << bin2Hex(jump_address) << endl; //cout << PC_plus_4 << endl; jump_address = hex2Bin(PC_plus_4).substr(0,4) + jump_address; jump_address = bin2Hex(jump_address); //cout << jump_address << endl; cout << "The jump address is: 0x" << jump_address << endl << endl; writeFile << "The jump address is: 0x" << jump_address << endl << endl; //shift left 2 string branch_address = shift_Left_2.shift(extend_Data); cout << "Shift left 2: \nThe instruction passed in is: 0x" << bin2Hex(extend_Data) << endl; cout << "Shift result is: 0x" << bin2Hex(branch_address) << endl << endl; writeFile << "Shift left 2: \nThe instruction passed in is: 0x" << bin2Hex(extend_Data) << endl; writeFile << "Shift result is: 0x" << bin2Hex(branch_address) << endl << endl; //ALU 2 ALU_2.setOperand1(hex2Bin(PC_plus_4)); ALU_2.setOperand2(branch_address); ALU_2.setOperation(1); ALU_2.execute(); string ALU_2_result = ALU_2.getOutput(); cout << "ALU 2:\nOperand 1 is: 0x" << PC_plus_4 << endl; cout << "Operand 2 is: 0x" << bin2Hex(branch_address) << endl; cout << "the result of ALU 2 is: 0x" << bin2Hex(ALU_2_result) << endl << endl; writeFile << "ALU 2:\nOperand 1 is: 0x" << PC_plus_4 << endl; writeFile << "Operand 2 is: 0x" << bin2Hex(branch_address) << endl; writeFile << "the result of ALU 2 is: 0x" << bin2Hex(ALU_2_result) << endl << endl; branch_address = bin2Hex(ALU_2_result); MUX_5.setOperand1(PC_plus_4); MUX_5.setOperand2(branch_address); int MUX_5_Control; if (isZero && main_Control.getBranch()) { MUX_5_Control = 1; } else { MUX_5_Control = 0; } MUX_5.setControl(MUX_5_Control); MUX_5.execute(); string MUX_5_output = MUX_5.getOutput(); cout << "MUX 5: \nThe first operand passed in: 0x" << PC_plus_4 << endl; cout << "The second operand passed in: 0x" << branch_address << endl; cout << "The control passed to MUX 5 from main control is: " << MUX_5_Control << endl; cout << "The output from MUX 5 is: 0x" << MUX_5_output << endl << endl; writeFile << "MUX 5: \nThe first operand passed in: 0x" << PC_plus_4 << endl; writeFile << "The second operand passed in: 0x" << branch_address << endl; writeFile << "The control passed to MUX 5 from main control is: " << MUX_5_Control << endl; writeFile << "The output from MUX 5 is: 0x" << MUX_5_output << endl << endl; MUX_4.setOperand1(MUX_5_output); MUX_4.setOperand2(jump_address); MUX_4.setControl(main_Control.getJump()); MUX_4.execute(); string nextAddress = MUX_4.getOutput(); cout << "MUX 4: \nThe first operand passed in: 0x" << MUX_5_output << endl; cout << "The second operand passed in: 0x" << jump_address << endl; cout << "The control passed to MUX 4 from main control is: " << main_Control.getJump() << endl; cout << "The output from MUX 4 is: 0x" << nextAddress << endl << endl; writeFile << "MUX 4: \nThe first operand passed in: 0x" << MUX_5_output << endl; writeFile << "The second operand passed in: 0x" << jump_address << endl; writeFile << "The control passed to MUX 4 from main control is: " << main_Control.getJump() << endl; writeFile << "The output from MUX 4 is: 0x" << nextAddress << endl << endl; //update address to PC and fetch next instruction curAddress = nextAddress; instruction_Memory.readAddress(curAddress); curInstruction = instruction_Memory.getInstruction(); curOriginal = instruction_Memory.getOriginal(); cout << endl << endl; writeFile << endl << endl; //data_Memory.print(); //curInstruction = ""; } cout << "------------------end------------------" << endl; writeFile << "------------------end------------------" << endl; if (printMemory) { register_File.printRegisterFile(); cout << endl; data_Memory.print(); cout << endl; instruction_Memory.print(); writeFile << "Printing Registers" << endl; map<int, string> registers = register_File.getMap(); for (int i = 0; i < 32; i++) { writeFile << "Register[" << i << "] = " << "\t 0x"<< bin2Hex(registers[i]) << endl; } writeFile << endl << "Memory Contents:" << endl; map<string,string> dataMemoryMap = data_Memory.getMap(); map<string,string>::iterator it2; for(it2 = dataMemoryMap.begin(); it2 != dataMemoryMap.end(); it2++){ string t = it2->second; writeFile << "address:[0x" << it2->first << "] = 0x" << bin2Hex(t) << endl; } writeFile << endl; writeFile << "Instruction Memory Contents:" << endl; map<string, string> myInstruction = instruction_Memory.getMap(); map<string,string>::iterator it3; for(it3 = myInstruction.begin(); it3 != myInstruction.end(); it3++){ string t = it3->second; writeFile << "address:[0x" << it3->first << "] = 0x" << bin2Hex(t) << endl; } writeFile << endl; } writeFile.close(); //cout << "writeToFile" << endl; } string Simulate::hex2Bin(string input) { string result; for (unsigned int i = 0; i < input.length(); i++) { char c = input[i]; if (c == '0') result += "0000"; if (c == '1') result += "0001"; if (c == '2') result += "0010"; if (c == '3') result += "0011"; if (c == '4') result += "0100"; if (c == '5') result += "0101"; if (c == '6') result += "0110"; if (c == '7') result += "0111"; if (c == '8') result += "1000"; if (c == '9') result += "1001"; if (c == 'A') result += "1010"; if (c == 'B') result += "1011"; if (c == 'C') result += "1100"; if (c == 'D') result += "1101"; if (c == 'E') result += "1110"; if (c == 'F') result += "1111"; } return result; } char Simulate::getHexCharacter(string str) { if(str.compare("1111") == 0) return 'F'; else if(str.compare("1110") == 0) return 'E'; else if(str.compare("1101")== 0) return 'D'; else if(str.compare("1100")== 0) return 'C'; else if(str.compare("1011")== 0) return 'B'; else if(str.compare("1010")== 0) return 'A'; else if(str.compare("1001")== 0) return '9'; else if(str.compare("1000")== 0) return '8'; else if(str.compare("0111")== 0) return '7'; else if(str.compare("0110")== 0) return '6'; else if(str.compare("0101")== 0) return '5'; else if(str.compare("0100")== 0) return '4'; else if(str.compare("0011")== 0) return '3'; else if(str.compare("0010")== 0) return '2'; else if(str.compare("0001")== 0) return '1'; else if(str.compare("0000")== 0) return '0'; return ' '; } string Simulate::bin2Hex(string input) { string endresult = ""; for(unsigned int i = 0; i < input.length(); i = i+4) { endresult += getHexCharacter(input.substr(i,4)); } return endresult; }
true
30fb0eebf9ebc3e22d85731258556beb900e27d8
C++
lythesia/leet
/cc/game-of-life/game-of-life.cc
UTF-8
1,589
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define inject(x) { cerr << "Function: " << __FUNCTION__ << ", Line: " << __LINE__ << ", " << #x << ": " << (x) << endl; } typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; typedef vector<vs> vvs; const int dir[][2] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} }; class Solution { public: void gameOfLife(vvi &b) { int m = b.size(), n = b[0].size(); for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(!b[i][j]) b[i][j] = -1; for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { int c = 0; for(int k=0; k<8; k++) { int nx = i + dir[k][0], ny = j + dir[k][1]; if(nx >= 0 && nx < m && ny >=0 && ny < n) { if(b[nx][ny] >= 0) c++; } } if(c) b[i][j] = b[i][j] >= 0 ? c : b[i][j] * c; } } for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { if(b[i][j] < 0) b[i][j] = b[i][j] == -3 ? 1 : 0; else b[i][j] = b[i][j] == 2 || b[i][j] == 3 ? 1 : 0; } } } }; void pmat(vvi &b) { for(size_t i=0; i<b.size(); i++) { for(size_t j=0; j<b[i].size(); j++) cout << b[i][j] << ' '; cout << endl; } } int main(int argc, const char *argv[]) { srand(time(nullptr)); vvi b(4, vi(4)); for(size_t i=0; i<b.size(); i++) { size_t cc = rand() % b[i].size() + 1; for(size_t j=0; j<cc; j++) b[i][j] = 1; random_shuffle(b[i].begin(), b[i].end()); } pmat(b); cout << endl; Solution so; so.gameOfLife(b); pmat(b); return 0; }
true
754597fd330c0457c19eda28a887a41776a2afff
C++
shreyaganesh/Leetcode-Practice
/190_reverse_bits.cpp
UTF-8
628
3.4375
3
[]
no_license
#include "iostream" class Solution { public: uint32_t reverseBits(uint32_t n) { int count=32; uint32_t reversed=0; for(int i =1; i<=32; i++) { reversed=(reversed<<1)|(n&0x01); n>>=1; } return reversed; } }; int main() { Solution revBits; uint32_t input = 0b10010100110010001111010101110011; uint32_t reversed = revBits.reverseBits(input); std::cout<<"Input: "<<input<<"\nReversed: "<<reversed<<std::endl; if(revBits.reverseBits(reversed)==input) std::cout<<"Output is correct!\n"; else std::cout<<"Incorrect Output. Try again.\n"; return 0; }
true
3b643323437a2564d4b052ebad70af6da3e2bafc
C++
shubhgkr/Codechef
/Tournaments/CYNO2019/KW6.cpp
UTF-8
485
2.734375
3
[]
no_license
/* * @author Shubham Kumar Gupta (shubhgkr) * github: http://www.github.com/shubhgkr * Created on 18/11/19. * Problem link: https://www.codechef.com/CYNO2019/problems/KW6 */ #include <iostream> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); int n; std::cin >> n; int cO = 0, cE = 0; int x; while (n--) { std::cin >> x; if (x & 1) cO++; else cE++; } if (std::abs(cO - cE) <= 1) std::cout << "DL"; else std::cout << "DETAIN"; return 0; }
true
d4ede122d0efb805459effd28c9c97b641a784fa
C++
yaroslavpalamar/samples
/interview_tasks/math/countFactors.cpp
UTF-8
1,068
3.859375
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* * 1. count all integer factors of a positive integer number N, including 1 and the number itself. * 2. For example for 12 there are 6 such factors: 1, 2, 3, 4, 6, 12. * 3. In this task N will be in the range [1, 10^12]. * 4. Function should return number of all possible factors of N. * Example for 12 it is 6 * */ int gcd (long long a, long long b, int& countFactors) { if (b==0) { countFactors++; return a; } return gcd (a, a%b, countFactors); } //slow solution int count_numbers_factorsSlow(long long n) { int result = 0; for (long long i = 1; i <= n; i++) { if ((n % i)==0) result++; } return result; } //fast solution int count_numbers_factorsFast(long long n) { int result = 0; long long i; for (i = 1; i*i < n; i++) { if ((n % i)==0) { result+=2; } } if (i*i==n) result++; return result; } int main() { const long long N = 12; cout << count_numbers_factorsFast(N) << endl; return 0; }
true
6b8821b7e972663eb4f83a56e7b4c6e65b4fac7e
C++
taynaralopes/projetoSolar
/projeto.cpp
UTF-8
2,098
2.9375
3
[]
no_license
#include "projeto.h" Projeto::Projeto() { } Consumidor Projeto::operator[](int indice) { return projetoSolar[indice]; } int Projeto::size() { return projetoSolar.size(); } void Projeto::inserirCliente(const Consumidor c) { projetoSolar.push_back(c); } int Projeto::QuantidadeDeProjetos() { return projetoSolar.size(); } bool Projeto::jaExiste(Consumidor a) { if(projetoSolar.size() >= 1){ for(int i = 0; i < projetoSolar.size(); i++){ if(a.getNome() == projetoSolar[i].getNome()){ return 1; } } } return 0; } void Projeto::ordenarPorCliente() { std::sort(projetoSolar.begin(), projetoSolar.end(), [](Consumidor t, Consumidor v){return t.getNome()< v.getNome();}); } void Projeto::ordenarPorConsumo() { std::sort(projetoSolar.begin(),projetoSolar.end(), [](Consumidor n,Consumidor m){return n.getConsumo() < m.getConsumo() ;}); } bool Projeto::salvarArquivo(QString file) { QFile arquivo(file); arquivo.open(QIODevice::WriteOnly); if(arquivo.isOpen() == 1){ for(auto a: projetoSolar){ QString linha = a.getNome() + "," + QString::number(a.getUnidadeConsumidora()) + "," + QString::number(a.getConsumo()) +"\n"; arquivo.write(linha.toLocal8Bit()); } arquivo.close(); return 1; }else{ return 0; } } bool Projeto::abrirArquivo(QString file) { QFile arquivo(file); if(arquivo.isOpen() == 1)return 1; else{ arquivo.open(QIODevice::ReadOnly); QString linha; QStringList dados; while(!arquivo.atEnd()){ Consumidor temp; linha = arquivo.readLine(); dados = linha.split(","); temp.setNome(dados[0]); temp.setUnidadeConsumidora(dados[1].toDouble()); temp.setConsumo(dados[2].toDouble()); temp.setPotencia(dados[2].toDouble()); temp.setN_modulos(temp.getPotencia()); inserirCliente(temp); } arquivo.close(); return 0; } }
true
b45bf03f4a4505639bed0110dceb8797e292e8fd
C++
LiuJiLan/LeetCodeStudy
/LC_0026. 删除排序数组中的重复项/#1.cpp
UTF-8
719
3.265625
3
[]
no_license
//2020.09.13_#1 class Solution { public: int removeDuplicates(vector<int>& nums) { int count = 0; //本质上for (int i = 0; i < nums.size(); i++)是对for _ in nums的改写 for (int i = 0; i < nums.size(); i++) { //count == 0 是防止||后的条件越界 //nums[i] > nums[count-1]就是当发现有新的元素出现 // if (count == 0 || nums[i] > nums[count-1]) { nums[count++] = nums[i]; } } return count; } }; /* int removeDuplicates(vector<int>& nums) { int i = 0; for (int n : nums) if (!i || n > nums[i-1]) nums[i++] = n; return i; } */
true
a794ee7b1c9fb5a075cad89dcee5836e1c7b8dbb
C++
lingqing97/c-primer_plus_programing
/10.10/10.10.7/10.10.7/list.h
UTF-8
348
2.921875
3
[]
no_license
#pragma once #ifndef LIST #define LIST #include <iostream> struct Node { int data; Node* next; }; class list { private: static const int LIMIT = 25; Node* first; int total; public: list() { first = NULL; } void insert(int data); bool del(int data); bool isEmpty() const; bool isFull() const; void reverse() const; }; #endif // !LIST
true
070e7d4fec9b0d364a068ee5897a42053e6aceee
C++
zerodeusx/programing_Gladkov
/lab31/src/lib.h
UTF-8
3,208
3.046875
3
[]
no_license
#pragma once #include <iostream> #include <cstring> #include <vector> #include <list> using namespace std; struct boss{ char first_name[50]; char second_name[50]; char email[50]; }; class Agency{ protected: char agency_name[50]; char servicing_city[50]; int agency_age; struct boss agency_boss; public: Agency() { }; Agency(char boss_f_name[50], char boss_s_name[50], char email[50], char name[50], char city[50], int age) { this->agency_age = age; strcpy( this->agency_boss.first_name, boss_f_name ); strcpy( this->agency_boss.second_name, boss_s_name ); strcpy( this->agency_boss.email, email ); strcpy( this->agency_name, name ); strcpy( this->servicing_city, city ); } ~Agency() { } int get_age(){ return this->agency_age; } virtual string name_of_class() = 0; virtual void myfun() final { cout << "\nfinal method!\n"; } }; class Law_agency : public Agency { char service_type[50]; int won_cases; public: int get_age(){ return this->agency_age; } virtual string name_of_class() override final{ return "Law"; } Law_agency() { }; Law_agency(char boss_f_name[50], char boss_s_name[50], char email[50], char name[50], char city[50], int age,char s_type[50], int wins) { this->agency_age = age; strcpy( this->agency_boss.first_name, boss_f_name ); strcpy( this->agency_boss.second_name, boss_s_name ); strcpy( this->agency_boss.email, email ); strcpy( this->agency_name, name ); strcpy( this->servicing_city, city ); strcpy( this->service_type, s_type); this->won_cases = wins; } ~Law_agency() { } string get_city(){ return servicing_city; } int get_won_cases(){ return won_cases; } string get_service(){ return service_type; } virtual int get_sth(){ return won_cases; } string print_l_ag(); }; class Mar_agency : public Agency { char servicing_method[50]; char cooperation_country[50]; bool weekends; public: virtual string name_of_class() override final{ return "Mar"; } Mar_agency() { }; Mar_agency(char boss_f_name[50], char boss_s_name[50], char email[50], char name[50], char city[50], int age, char serv_method[50], char coop[50], bool week) { this->agency_age = age; strcpy( this->agency_boss.first_name, boss_f_name ); strcpy( this->agency_boss.second_name, boss_s_name ); strcpy( this->agency_boss.email, email ); strcpy( this->agency_name, name ); strcpy( this->servicing_city, city ); strcpy( this->servicing_method, serv_method); strcpy( this->cooperation_country, coop); weekends = week; } ~Mar_agency() { } bool get_weekends(){ return weekends; } string get_city(){ return servicing_city; } virtual int get_sth(){ return agency_age; } int get_age(){ return this->agency_age; } string print_m_ag(); };
true
3cb3a1603645f1e332dcec6388c030845c873ef8
C++
wrawdanik/ApiPack2
/source/datastore/Topics.h
UTF-8
1,646
2.5625
3
[]
no_license
// // Created by warmi on 5/5/16. // #ifndef APIPACK2_TOPICS_H #define APIPACK2_TOPICS_H #include <cstddef> #include <ostream> #include <folly/Format.h> using namespace folly; namespace ApiPack2 { enum class Topic : size_t { Metamorphosis_Station , Metamorphosis_Linuep, Metamorphosis_Image, Metamorphosis_Person, Metamorphosis_Program_TmsId, Metamorphosis_Affiliation, Metamorphosis_Market, Metamorphosis_Schedule_Day, Metamorphosis_Provider, Metamorphosis_Headend, Metamorphosis_Rating_Body, Metamorphosis_Rating_Value, Metamorphosis_Animation, Metamorphosis_Award_Type, Metamorphosis_Award_Body, Metamorphosis_Genre, Metamorphosis_Production_Company, Metamorphosis_Advisory, Metamorphosis_Holiday, Metamorphosis_Playoff, Metamorphosis_Team, Metamorphosis_Venue, Metamorphosis_Warning, Metamorphosis_Conference, Metamorphosis_University }; std::ostream& operator<< (std::ostream & os, ApiPack2::Topic topic); namespace TopicConversion { const char *toChar(ApiPack2::Topic topic); } } namespace folly { template <> class FormatValue<ApiPack2::Topic> { public: explicit FormatValue(ApiPack2::Topic topic) : mTopic(topic) { } template <class FormatCallback> void format(FormatArg& arg, FormatCallback& cb) const { FormatValue<std::string>(ApiPack2::TopicConversion::toChar(mTopic)).format(arg, cb); } private: ApiPack2::Topic mTopic; }; } #endif //APIPACK2_TOPICS_H
true
f592ea6cb448b8284fbb877f157ee23c80f0f7ed
C++
xzhangpeijin/LHSLabs
/Term1Labs/Lab16.cpp
UTF-8
1,945
3.640625
4
[]
no_license
// ****************************** // * Lab 16 Peijin Zhang * // * Extra Additives * // ****************************** #include <iostream> #include <vector> #include <iomanip> #include <cmath> using namespace std; int asciitoint (char ch); void calculate(vector<char> &int1, vector<char> &int2, vector<int> largeint1,vector<int> largeint2, vector<int> finalint, int &int1digits, int &int2digits); int main () { vector<int> largeint1 (12,0); vector<int> largeint2 (12,0); vector<int> finalint (13,0); vector<char> int1 (12,'0'); vector<char> int2 (12,'0'); int int1digits, int2digits; for (int x = 0; x < 4; x++) { cout << "Enter your two numbers \n"; string int1a, int2a; getline(cin,int1a); getline(cin,int2a); int1digits = int1a.size(); int2digits = int2a.size(); for (int x = 0; x < 12; x++) { int1[x] = int1a[x]; } for (int x = 0; x < 12; x++) { int2[x] = int2a[x]; } calculate(int1, int2, largeint1, largeint2, finalint, int1digits, int2digits); } return 0; } int asciitoint(char ch) // pre: a character // post: an integer { return (ch - '0'); } void calculate(vector<char> &int1, vector<char> &int2, vector<int> largeint1, vector<int> largeint2, vector<int> finalint, int &int1digits, int &int2digits) // pre: four vectors, two integers // post: none { int begin = 0; for (int x = 0; x < int1digits; x++) { int a = 12 - int1digits + x; largeint1[a] = asciitoint(int1[x]); } for (int x = 0; x < int2digits; x++) { int a = 12 - int2digits + x; largeint2[a] = asciitoint(int2[x]); } for (int x = 0; x < 12; x++) { int a = 11 - x; int b = 12 - x; finalint[b] = finalint[b] + largeint1[a] + largeint2[a]; if (finalint[b] > 9) { finalint[b] = finalint[b] - 10; finalint[a] = 1; } } for (int x = 0; x < 13; x++) { if (finalint[x] > 0 && finalint[x] < 10) { begin = 1; } if (begin == 1) { cout << finalint[x]; } } cout << endl; }
true
fd418e96bcf0c58ab88f0567df7c12eca67a33b6
C++
Paul-Hi/Mango
/mango/src/rendering/renderer_pipeline_cache.hpp
UTF-8
9,358
2.796875
3
[ "Apache-2.0" ]
permissive
//! \file renderer_pipeline_cache.hpp //! \author Paul Himmler //! \version 1.0 //! \date 2022 //! \copyright Apache License 2.0 #ifndef MANGO_RENDERER_PIPELINE_CACHE_HPP #define MANGO_RENDERER_PIPELINE_CACHE_HPP #include <core/context_impl.hpp> namespace mango { //! \brief Cache for \a gfx_pipelines. //! \details Takes basic pipeline create infos, creates and caches \a gfx_pipelines. class renderer_pipeline_cache { public: //! \brief Constructs a new \a renderer_pipeline_cache. //! \param[in] context The internally shared context of mango. renderer_pipeline_cache(const shared_ptr<context_impl>& context) : m_shared_context(context){}; ~renderer_pipeline_cache() = default; //! \brief Sets a \a graphics_pipeline_create_info as base for graphics \a gfx_pipelines for opaque geometry. //! \param[in] basic_create_info The \a graphics_pipeline_create_info to set. inline void set_opaque_base(const graphics_pipeline_create_info& basic_create_info) { m_opaque_create_info = basic_create_info; } //! \brief Sets a \a graphics_pipeline_create_info as base for graphics \a gfx_pipelines for transparent geometry. //! \param[in] basic_create_info The \a graphics_pipeline_create_info to set. inline void set_transparent_base(const graphics_pipeline_create_info& basic_create_info) { m_transparent_create_info = basic_create_info; } //! \brief Sets a \a graphics_pipeline_create_info as base for graphics \a gfx_pipelines for shadow pass geometry. //! \param[in] basic_create_info The \a graphics_pipeline_create_info to set. inline void set_shadow_base(const graphics_pipeline_create_info& basic_create_info) { m_shadow_create_info = basic_create_info; } //! \brief Gets a graphics \a gfx_pipeline for opaque geometry. //! \param[in] geo_vid The \a vertex_input_descriptor of the geometry. //! \param[in] geo_iad The \a input_assembly_dedscriptor of the geometry. //! \param[in] wireframe True if the pipeline should render wireframe, else false. //! \param[in] double_sided True if the pipeline should render double sided, else false. //! \return A \a gfx_handle of a \a gfx_pipeline to use for rendering opaque geometry. gfx_handle<const gfx_pipeline> get_opaque(const vertex_input_descriptor& geo_vid, const input_assembly_descriptor& geo_iad, bool wireframe, bool double_sided); //! \brief Gets a graphics \a gfx_pipeline for transparent geometry. //! \param[in] geo_vid The \a vertex_input_descriptor of the geometry. //! \param[in] geo_iad The \a input_assembly_dedscriptor of the geometry. //! \param[in] wireframe True if the pipeline should render wireframe, else false. //! \param[in] double_sided True if the pipeline should render double sided, else false. //! \return A \a gfx_handle of a \a gfx_pipeline to use for rendering transparent geometry. gfx_handle<const gfx_pipeline> get_transparent(const vertex_input_descriptor& geo_vid, const input_assembly_descriptor& geo_iad, bool wireframe, bool double_sided); //! \brief Gets a graphics \a gfx_pipeline for shadow pass geometry. //! \param[in] geo_vid The \a vertex_input_descriptor of the geometry. //! \param[in] geo_iad The \a input_assembly_dedscriptor of the geometry. //! \param[in] double_sided True if the pipeline should render double sided, else false. //! \return A \a gfx_handle of a \a gfx_pipeline to use for rendering shadow pass geometry. gfx_handle<const gfx_pipeline> get_shadow(const vertex_input_descriptor& geo_vid, const input_assembly_descriptor& geo_iad, bool double_sided); private: //! \brief Key for caching \a gfx_pipelines. struct pipeline_key { //! \brief The \a vertex_input_descriptor of the \a pipeline_key. vertex_input_descriptor vid; //! \brief The \a input_assembly_descriptor of the \a pipeline_key. input_assembly_descriptor iad; //! \brief True if the cached pipeline renders wireframe, else false. bool wireframe; //! \brief True if the pipeline should render double sided, else false. bool double_sided; //! \brief Comparison operator equal. //! \param[in] other The other \a pipeline_key. //! \return True if other \a pipeline_key is equal to the current one, else false. bool operator==(const pipeline_key& other) const { if (wireframe != other.wireframe) return false; if (double_sided != other.double_sided) return false; if (vid.binding_description_count != other.vid.binding_description_count) return false; // attribute description count == binding description count ---> ALWAYS if (iad.topology != other.iad.topology) return false; for (int32 i = 0; i < vid.binding_description_count; ++i) { auto& bd0 = vid.binding_descriptions[i]; auto& bd1 = other.vid.binding_descriptions[i]; if (bd0.binding != bd1.binding) return false; if (bd0.input_rate != bd1.input_rate) return false; if (bd0.stride != bd1.stride) return false; auto& ad0 = vid.attribute_descriptions[i]; auto& ad1 = other.vid.attribute_descriptions[i]; if (ad0.binding != ad1.binding) return false; if (ad0.attribute_format != ad1.attribute_format) return false; if (ad0.location != ad1.location) return false; if (ad0.offset != ad1.offset) return false; } return true; } }; //! \brief Hash for \a pipeline_keys. struct pipeline_key_hash { //! \brief Function call operator. //! \details Hashes the \a pipeline_key. //! \param[in] k The \a pipeline_key to hash. //! \return The hash for the given \a pipeline_key. std::size_t operator()(const pipeline_key& k) const { // https://stackoverflow.com/questions/1646807/quick-and-simple-hash-code-combinations/ size_t res = 17; res = res * 31 + std::hash<bool>()(k.wireframe); res = res * 31 + std::hash<bool>()(k.double_sided); res = res * 31 + std::hash<int32>()(k.vid.binding_description_count); res = res * 31 + std::hash<uint8>()(static_cast<uint8>(k.iad.topology)); for (int32 i = 0; i < k.vid.binding_description_count; ++i) { auto& bd = k.vid.binding_descriptions[i]; res = res * 31 + std::hash<int32>()(bd.binding); res = res * 31 + std::hash<uint8>()(static_cast<uint8>(bd.input_rate)); res = res * 31 + std::hash<int32>()(bd.stride); auto& ad = k.vid.attribute_descriptions[i]; res = res * 31 + std::hash<int32>()(ad.binding); res = res * 31 + std::hash<uint32>()(static_cast<uint32>(ad.attribute_format)); res = res * 31 + std::hash<int32>()(ad.location); res = res * 31 + std::hash<int32>()(ad.offset); } return res; }; }; //! \brief The \a graphics_pipeline_create_info used as base for creating \a gfx_pipelines rendering opaque geometry. graphics_pipeline_create_info m_opaque_create_info; //! \brief The \a graphics_pipeline_create_info used as base for creating \a gfx_pipelines rendering transparent geometry. graphics_pipeline_create_info m_transparent_create_info; //! \brief The \a graphics_pipeline_create_info used as base for creating \a gfx_pipelines rendering shadow pass geometry. graphics_pipeline_create_info m_shadow_create_info; //! \brief The cache mapping \a pipeline_keys to \a gfx_pipelines of rendering opaque geometry. std::unordered_map<pipeline_key, gfx_handle<const gfx_pipeline>, pipeline_key_hash> m_opaque_cache; //! \brief The cache mapping \a pipeline_keys to \a gfx_pipelines of rendering transparent geometry. std::unordered_map<pipeline_key, gfx_handle<const gfx_pipeline>, pipeline_key_hash> m_transparent_cache; //! \brief The cache mapping \a pipeline_keys to \a gfx_pipelines of rendering shadow pass geometry. std::unordered_map<pipeline_key, gfx_handle<const gfx_pipeline>, pipeline_key_hash> m_shadow_cache; //! \brief Mangos internal context for shared usage. shared_ptr<context_impl> m_shared_context; }; } // namespace mango #endif // MANGO_RENDERER_PIPELINE_CACHE_HPP
true
5de1d7773f0b02d6e308b7e58ba61bf25d2586c9
C++
ZieIony/Ghurund
/engine/Engine.Core/src/core/math/Size.h
UTF-8
1,342
2.96875
3
[ "MIT" ]
permissive
#pragma once #include <stdint.h> #include <compare> #include <regex> namespace Ghurund::Core { struct IntSize { uint32_t width, height; auto operator<=>(const IntSize& other) const = default; static IntSize parse(const AString& text) { std::regex regex(" *(d+) *, *(d+) *"); std::smatch m; std::string s = text.Data; if (std::regex_match(s, m, regex)) { uint32_t width = std::stoul(m[1].str()); uint32_t height = std::stoul(m[2].str()); return { width, height }; } else { throw std::invalid_argument("invalid alignment string"); } } }; struct FloatSize { float width, height; auto operator<=>(const FloatSize& other) const = default; static FloatSize parse(const AString& text) { std::regex regex(" *(d+\\.d*) *, *(d+\\.d*) *"); std::smatch m; std::string s = text.Data; if (std::regex_match(s, m, regex)) { float width = std::stof(m[1].str()); float height = std::stof(m[2].str()); return { width, height }; } else { throw std::invalid_argument("invalid alignment string"); } } }; }
true
c6b153cf32cdf182f421e8f89445f0e66c981008
C++
begozcan/CS201-Homeworks
/Homework-3/Movie.h
UTF-8
1,037
2.90625
3
[]
no_license
// // Begum Ozcan - Homework 3 // 21302654 // CS201 - 3 // #ifndef HOMEWORK3_MOVIE_H #define HOMEWORK3_MOVIE_H #include <string> #include <iostream> #include "Actor.h" using namespace std; class Movie { public: Movie(string movieTitle, string directorName, int releaseDay, int releaseMonth, int releaseYear); Movie(); ~Movie(); string getDirectorName(); string getMovieTitle(); string getMovieTitleLower(); int getReleaseDay(); int getReleaseMonth(); int getReleaseYear(); void getActors(); string findActor(string actorName); void addActor(const string actorFirstName, const string actorLastName, const string actorRole); void removeActor(const string actorFirstName, const string actorLastName); private: struct ActorNode { Actor actor; ActorNode* next; }; string movieTitle; string movieTitleLower; string directorName; int releaseDay; int releaseMonth; int releaseYear; ActorNode* actorHead; }; #endif //HOMEWORK3_MOVIE_H
true
1334e1055043c4f445388fdf0265ba85183bb6f2
C++
komadog/cpp
/ABC062_B.cpp
UTF-8
505
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { int h,w; char board_a[100][100],board_b[102][102]; cin >> h >> w; for(int i=0; i<h; i++){ cin >> board_a[i]; } for (int i=0; i<h+2; i++){ for (int j=0; j<w+2; j++){ board_b[i][j] = '#'; } } for (int i=0; i<h; i++){ for (int j=0; j<w; j++){ board_b[i+1][j+1]=board_a[i][j]; } } for (int i=0; i<h+2; i++){ for (int j=0; j<w+2; j++){ cout << board_b[i][j]; } cout << endl; } }
true
4262c7731ef3f3fb08473301269963c549ad76ae
C++
feedblackg44/kpilabs2
/CHM/Lab3/Lab3/main.cpp
UTF-8
665
3.078125
3
[]
no_license
#include <iostream> #include "functions.h" using namespace std; int main() { int size = 5; int* numbersX = new int[size]; fillInSeq(numbersX, size); double** A = createMatrix(size); matrix5Init(A); cout << "Matrix after 1 gauss step:\n"; print(A, size); double* B = createVec(size); vector5Init(B); cout << "The right vec of matrix:\n"; print(B, size); double* X = createVec(size); vector5Init(X); zeidelMethodSolve(A, B, X, size); cout << "\nRes vector is:\n"; print(X, size); cout << "\nr = b - Ax:\n"; print(vecDelta(A, B, X, size), size, 15); system("pause"); return 0; }
true
ca18ccaab7df96487696cb57a2616f0d9d2ca383
C++
skyformat99/data_collector
/lib/ClientSocket.h
UTF-8
1,125
2.765625
3
[]
no_license
#pragma once #include <BaseSocket.h> #include <string> class ServerSocket; class SocketCallback; class SocketManager; class ClientSocket: public BaseSocket { public: ClientSocket(); ClientSocket(int clientType, int socketFD, SocketManager* socketMan, SocketCallback* callback, char* remoteServerIP, int remoteServerPort, int remoteClientPort, int localClientPort, ServerSocket* ownerServer); ~ClientSocket() {} int getClientType() { return m_clientType; } std::string getRemoteIP() { return m_remoteIP; } int getRemoteServerPort() { return m_remoteServerPort; } int getRemoteClientPort() { return m_remoteClientPort; } int getLocalClientPort() { return m_localClientPort; } bool sendData(std::string data); private: int m_clientType; //1 = independently created client, 2 = peer client created by server //IP of remote end (could be a server for an independent client, or a client for a peer client socket) char m_remoteIP[20]; int m_remoteServerPort; //-1 for peer clients accepted by a server socket int m_remoteClientPort; int m_localClientPort; ServerSocket* m_ownerServer; };
true
c57044cf8024706903323556f4526a7ce3ce186f
C++
dompham21/DoAn-ThiTracNghiem-C
/DocGhi.h
UTF-8
9,301
2.59375
3
[]
no_license
#pragma once #include <iostream> #include "Lop.h" #include "MonHoc.h" #include "CauHoiThi.h" #include "DiemThi.h" #include "SinhVien.h" int getIDTuFile() { int n; int x; int soLuong; //so luong phan tu da su dung ifstream fileIn; fileIn.open("SourceRDNumber.txt", ios_base::in); if(fileIn.fail()) cout << "Khong the doc file id"; fileIn >> n; //doc so luong phan tu source fileIn >> soLuong; int arr[n]; for (int i = 0; i < n; i++) fileIn >> arr[i]; x = arr[soLuong]; //lay phan tu dau tien fileIn.close(); ofstream fileout; fileout.open("SourceRDNumber.txt", ios_base::out); fileout << n << endl; fileout << soLuong+1 <<endl; for (int i = 0; i < n; i++) fileout << arr[i] << " "; fileout.close(); return x; } void luuFileDSCauHoi(PTRCauHoi root) { ofstream fileOut; fileOut.open("DanhSachCauHoi.txt", ios_base :: out); PTRCauHoi Stack[STACKSIZE]; PTRCauHoi p = root; int sp = -1; // Khoi tao Stack rong while (p!=NULL ) { fileOut << p->cht.ID <<endl; fileOut << p->cht.maMH << endl; fileOut << p->cht.noiDung << endl; fileOut << p->cht.dapAnA <<endl; fileOut << p->cht.dapAnB <<endl; fileOut << p->cht.dapAnC <<endl; fileOut << p->cht.dapAnD <<endl; fileOut << p->cht.dapAn <<endl; if (p->right != NULL) Stack[++sp]= p->right; if (p->left != NULL) p=p->left; else if (sp==-1) break; else p=Stack[sp--]; } fileOut.close(); } void docFileDSCauHoi(PTRCauHoi &root) { CauHoiThi cht; ifstream fileIn; fileIn.open("DanhSachCauHoi.txt", ios_base :: in ); if(fileIn.fail()) { cout << "Khong the doc file cau hoi thi"<<endl; } else { while (!fileIn.eof()) { fileIn >> cht.ID; if(cht.ID == 0) { break; } fileIn.ignore(); fileIn.getline(cht.maMH, sizeof(cht.maMH), '\n'); fileIn.getline(cht.noiDung, sizeof(cht.noiDung), '\n'); fileIn.getline(cht.dapAnA, sizeof(cht.dapAnA), '\n'); fileIn.getline(cht.dapAnB, sizeof(cht.dapAnB), '\n'); fileIn.getline(cht.dapAnC, sizeof(cht.dapAnC), '\n'); fileIn.getline(cht.dapAnD, sizeof(cht.dapAnD), '\n'); fileIn >> cht.dapAn; fileIn.ignore(); Insert_Tree(root, cht.ID, cht); } } fileIn.close(); } //xuat file mon hoc ra file DSmonhoc.txt void luuFileDSMonHoc(DanhSachMonHoc dsMonHoc) { ofstream fileOut; fileOut.open("DanhSachMonHoc.txt", ios_base :: out); fileOut << dsMonHoc.soLuong << "\n"; for (int i = 0; i < dsMonHoc.soLuong; i++) { fileOut << dsMonHoc.mh[i].maMH << endl; fileOut << dsMonHoc.mh[i].tenMH << endl; } fileOut.close(); } void docFileDSMonHoc(DanhSachMonHoc &dsMonHoc) { int n; ifstream fileIn; fileIn.open("DanhSachMonHoc.txt", ios::in); /* Doc so luong mon hoc o dong` dau tien su dung >> thi file doc xong thi` dung' cuoi' dong` chu khong xuong dong` */ if(fileIn.fail()) { cout << "Khong the doc file mon hoc"<<endl; } else { fileIn >> n; fileIn.ignore(); //bo qua \n for (int i = 0; i < n; i++) { MonHoc mh; fileIn.getline(mh.maMH, sizeof(mh.maMH),'\n'); fileIn.getline(mh.tenMH, sizeof(mh.tenMH), '\n'); themMonHoc(dsMonHoc,mh); } } fileIn.close(); } void docFileDSSinhVien( PTRSinhVien &p,char* maLop) { ifstream fileIn; char src[50]; char dest[5]; strcpy(src, "DSSV_"); strcpy(dest, ".txt"); strcat(src,maLop); strcat(src,dest); fileIn.open(src, ios_base :: in); if(fileIn.fail()) { cout << "Khong the doc file sinh vien"<<endl; } else { SinhVien sv; while(!fileIn.eof()) { fileIn.getline(sv.maSV, sizeof(sv.maSV),'\n'); if(strlen(sv.maSV) == 0) { //kiem tra ky tu space cuoi cung trong file break; } fileIn.getline(sv.ho, sizeof(sv.ho),'\n'); fileIn.getline(sv.ten, sizeof(sv.ten),'\n'); fileIn.getline(sv.phai, sizeof(sv.phai), '\n'); fileIn.getline(sv.password, sizeof(sv.password), '\n'); themMotSinhVien(p, sv); } } fileIn.close(); } void docFileDSDiem(PTRSinhVien FirstSV, char maLop[]) { ifstream fileIn; char maSV[16]; int slMonDaThi; char src[50]; char dest[5]; strcpy(src, "DIEM_"); strcpy(dest, ".txt"); strcat(src,maLop); strcat(src,dest); fileIn.open(src, ios_base :: in); if(fileIn.fail()) { cout<<"khong the doc file "<<src<<endl; } else { while(!fileIn.eof()) { fileIn.getline(maSV,sizeof(maSV),'\n'); if(strlen(maSV) == 0) { break; } fileIn>>slMonDaThi; fileIn.ignore(); PTRSinhVien p = searchSV(FirstSV,maSV); //Tim kiem sinh vien trong lop for(int i = 0; i < slMonDaThi; i++) { DiemThi dt; fileIn.getline(dt.maMH,sizeof(dt.maMH),'\n'); fileIn>>dt.diem; fileIn.ignore(); fileIn>> dt.bt.soCauHoi; fileIn.ignore(); dt.bt.cht = new CauHoiThi[dt.bt.soCauHoi]; dt.bt.dapAnDaChon = new char[dt.bt.soCauHoi]; for (int i = 0; i < dt.bt.soCauHoi; i++) { fileIn >> dt.bt.cht[i].ID; fileIn.ignore(); fileIn.getline(dt.bt.cht[i].noiDung, sizeof(dt.bt.cht[i].noiDung),'\n'); fileIn.getline(dt.bt.cht[i].dapAnA, sizeof(dt.bt.cht[i].dapAnA),'\n' ); fileIn.getline(dt.bt.cht[i].dapAnB, sizeof(dt.bt.cht[i].dapAnB) ,'\n'); fileIn.getline(dt.bt.cht[i].dapAnC, sizeof(dt.bt.cht[i].dapAnC),'\n' ); fileIn.getline(dt.bt.cht[i].dapAnD, sizeof(dt.bt.cht[i].dapAnD),'\n' ); fileIn >> dt.bt.cht[i].dapAn; fileIn.ignore(); fileIn >> dt.bt.dapAnDaChon[i]; fileIn.ignore(); } themMotDiemThi(p->sv.dsDiemThi, dt); } } } fileIn.close(); } void luuFileDSSV(PTRSinhVien p, char* maLop) { ofstream fileOut; char src[50]; char dest[5]; strcpy(src, "DSSV_"); strcpy(dest, ".txt"); strcat(src,maLop); strcat(src,dest); fileOut.open(src, ios_base :: out); PTRSinhVien nodeChaySV; nodeChaySV = new NodeSinhVien; nodeChaySV = p; while( nodeChaySV != NULL) { fileOut << nodeChaySV->sv.maSV << endl; fileOut << nodeChaySV->sv.ho << endl; fileOut << nodeChaySV->sv.ten << endl; fileOut << nodeChaySV->sv.phai << endl; fileOut << nodeChaySV->sv.password << endl; nodeChaySV = nodeChaySV->next; } fileOut.close(); } void luuFileDSDiem( PTRSinhVien FirstSV, char* maLop) { ofstream fileOut; char src[50]; char dest[5]; strcpy(src, "DIEM_"); strcpy(dest, ".txt"); strcat(src,maLop); strcat(src,dest); fileOut.open(src, ios_base::out); //Duyet qua danh sach sinh vien cua lop PTRSinhVien nodeChaySV; nodeChaySV = new NodeSinhVien; nodeChaySV = FirstSV; while(nodeChaySV != NULL){ fileOut<< nodeChaySV->sv.maSV << endl; fileOut<< demMonDaThi(nodeChaySV->sv.dsDiemThi) << endl; //dem so mon da thi (1 mon duoc thi 1 lan) if(demMonDaThi(nodeChaySV->sv.dsDiemThi) != 0) { //duyet danh sach diem thi cua sv PTRDiemThi nodeChayDT; nodeChayDT = new NodeDiemThi; nodeChayDT = nodeChaySV->sv.dsDiemThi; while(nodeChayDT != NULL){ fileOut<< nodeChayDT->dt.maMH<<endl; fileOut<< nodeChayDT->dt.diem<<endl; fileOut<< nodeChayDT->dt.bt.soCauHoi<<endl; for(int i=0;i< nodeChayDT->dt.bt.soCauHoi; i++) { //duyet danh sach cau hoi da thi cua sinh vien // Luu thong tin cau hoi fileOut << nodeChayDT->dt.bt.cht[i].ID << endl; fileOut << nodeChayDT->dt.bt.cht[i].noiDung << endl; fileOut << nodeChayDT->dt.bt.cht[i].dapAnA << endl; fileOut << nodeChayDT->dt.bt.cht[i].dapAnB << endl; fileOut << nodeChayDT->dt.bt.cht[i].dapAnC << endl; fileOut << nodeChayDT->dt.bt.cht[i].dapAnD << endl; fileOut << nodeChayDT->dt.bt.cht[i].dapAn << endl; //Luu dap an da chon fileOut << nodeChayDT->dt.bt.dapAnDaChon[i] << endl; } nodeChayDT = nodeChayDT->next; } } nodeChaySV = nodeChaySV->next; } fileOut.close(); } void docFileDSLop (DanhSachLop &dsLop) { ifstream fileIn; fileIn.open("DanhSachLop.txt", ios_base :: in ); if(fileIn.fail()) { cout << "Khong the doc file lop"; } else { fileIn >> dsLop.soLuong; fileIn.ignore(); for(int i = 0; i < dsLop.soLuong; i++) { dsLop.lh[i] = new LopHoc; fileIn.getline(dsLop.lh[i]->maLop, sizeof(dsLop.lh[i]->maLop),'\n'); if(strlen(dsLop.lh[i]->maLop) == 0) { //kiem tra ky tu space cuoi cung trong file break; } fileIn.getline(dsLop.lh[i]->tenLop, sizeof(dsLop.lh[i]->tenLop),'\n'); docFileDSSinhVien(dsLop.lh[i]->dsSinhVien,dsLop.lh[i]->maLop); docFileDSDiem(dsLop.lh[i]->dsSinhVien,dsLop.lh[i]->maLop); } } fileIn.close(); } void luuFileDSlop(DanhSachLop dsLop) { ofstream fileOut; fileOut.open("DanhSachLop.txt", ios_base::out); fileOut << dsLop.soLuong << endl; for (int i = 0; i < dsLop.soLuong; i++) { fileOut << dsLop.lh[i]->maLop << endl; fileOut << dsLop.lh[i]->tenLop << endl; luuFileDSSV(dsLop.lh[i]->dsSinhVien,dsLop.lh[i]->maLop); luuFileDSDiem(dsLop.lh[i]->dsSinhVien, dsLop.lh[i]->maLop); } fileOut.close(); } void luuFileQLLop(DanhSachLop dsLop) { ofstream fileOut; fileOut.open("DanhSachLop.txt", ios_base::out); fileOut << dsLop.soLuong << endl; for (int i = 0; i < dsLop.soLuong; i++) { fileOut << dsLop.lh[i]->maLop << endl; fileOut << dsLop.lh[i]->tenLop << endl; } fileOut.close(); }
true
ef3507745c1c01afb3011a52856d7e999daffea7
C++
Kannupriyasingh/CodeForces-Solutions
/Make_Sum_Divisible_By_P_LC_Imp.cpp
UTF-8
2,040
3.5625
4
[ "MIT" ]
permissive
/* Given an array of positive integers nums, remove the smallest subarray (possibly empty) such that the sum of the remaining elements is divisible by p. It is not allowed to remove the whole array. Return the length of the smallest subarray that you need to remove, or -1 if it's impossible. A subarray is defined as a contiguous block of elements in the array. Example 1: Input: nums = [3,1,4,2], p = 6 Output: 1 Explanation: The sum of the elements in nums is 10, which is not divisible by 6. We can remove the subarray [4], and the sum of the remaining elements is 6, which is divisible by 6. Example 2: Input: nums = [6,3,5,2], p = 9 Output: 2 Explanation: We cannot remove a single element to get a sum divisible by 9. The best way is to remove the subarray [5,2], leaving us with [6,3] with sum 9. Example 3: Input: nums = [1,2,3], p = 3 Output: 0 Explanation: Here the sum is 6. which is already divisible by 3. Thus we do not need to remove anything. Example 4: Input: nums = [1,2,3], p = 7 Output: -1 Explanation: There is no way to remove a subarray in order to get a sum divisible by 7. Example 5: Input: nums = [1000000000,1000000000,1000000000], p = 3 Output: 0 Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= p <= 109 */ class Solution { public: int minSubarray(vector<int>& nums, int p) { int n=nums.size(); nums[0]%=p; for(int i=1;i<n;i++) { nums[i]+=nums[i-1]; nums[i]%=p; } if(nums[n-1]==0) { return 0; } map<int,int> mp; mp[0]=-1; int ans=n; for(int i=0;i<n;i++) { mp[nums[i]]=i; int check=(nums[i]-nums[n-1]+p)%p; if(mp.find(check)!=mp.end()) { ans=min(ans,i-mp[check]); } } if(ans==n) { return -1; } return ans; } };
true
ac25c8c7b8a9d65809cacc4b498b4fce600e8891
C++
bobbyrx/CPP
/SHOP/SHOP/ProductShoes.cpp
UTF-8
948
3.015625
3
[]
no_license
#include <iostream> #include <cstring> #include "ProductShoes.h" #include <string> using namespace std; ProductShoes::ProductShoes() { Product:set_variant(shoes); } string ProductShoes::getBrand() const { return brand; } string ProductShoes::getColor() const { return color; } void ProductShoes::setWholeShoes(long double price, string color, string brand) { Product:set_price(price); this->color = color; this->brand=brand; } void ProductShoes::Print() const { cout << "\n\tPrinting the product info\n"; cout << "\tPrice: " << get_price() << " lv.\n"; cout << "\tIDtag: " << get_IDtag() << "\n"; cout << "\tType: "; switch (variant) { case book:cout << "Book\n"; break; case shoes:cout << "Shoes\n"; break; case phone:cout << "Phone\n"; break; default: cout << " \n"; break; } cout << "\tBrand: " << getBrand() << "\n"; cout << "\tColor: " << getColor() << "\n"; }
true
3b8be98a8f7b1de07b0559ef1cb7c4dc8b0a313d
C++
ArshaShiri/Courses
/Build a Modern Computer from First Principles/nand2tetris/projects/10/JackCompiler/JackCompiler/Helper.cpp
UTF-8
2,577
3.046875
3
[]
no_license
#include <dirent.h> #include <stdexcept> #include "Helper.h" #if defined(WIN32) || defined(_WIN32) #define PATH_SEPARATOR "\\" #else #define PATH_SEPARATOR "/" #endif std::vector<std::string> getListOfJackFiles(const std::string &fileOrDirPath) { auto listOfJackFiles = std::vector<std::string>{}; const auto extensionIndicator = '.'; const auto extensionIndicatorLocation = fileOrDirPath.find_last_of(extensionIndicator); // If we cannot find an extension, it means a directory given for compilation. // We then have to compile all the jack files in that directory. const auto isFilePathADirectory = extensionIndicatorLocation == fileOrDirPath.npos; if (isFilePathADirectory) { const auto inputFileExtension = ".jack"; DIR *dir; struct dirent *ent; if ((dir = opendir(fileOrDirPath.c_str())) != NULL) { while ((ent = readdir(dir)) != NULL) { const auto fileName = std::string{ent->d_name}; const auto extensionLocation = fileName.find(inputFileExtension); if (extensionLocation != fileName.npos) { const auto fileNameWithNoExtension = fileName.substr(0, extensionLocation); const auto inputFilePath = fileOrDirPath + PATH_SEPARATOR + fileNameWithNoExtension; listOfJackFiles.emplace_back(inputFilePath); } } } else throw std::runtime_error("Cannot open the given directory: " + fileOrDirPath); } else listOfJackFiles.emplace_back(fileOrDirPath); return listOfJackFiles; } bool isOp(const char character) { if (character == '+') return true; if (character == '-') return true; if (character == '*') return true; if (character == '/') return true; if (character == '&') return true; if (character == '|') return true; if (character == '<') return true; if (character == '>') return true; if (character == '=') return true; return false; } bool isUnaryOp(const char character) { if (character == '-') return true; if (character == '~') return true; return false; } bool isSymbol(const char character) { if (isOp(character)) return true; if (isUnaryOp(character)) return true; if (character == '}') return true; if (character == '(') return true; if (character == '{') return true; if (character == ')') return true; if (character == '[') return true; if (character == ']') return true; if (character == '.') return true; if (character == ',') return true; if (character == ';') return true; return false; }
true
1b2e5a4d96c4ea60939722d8db5b497585a65f86
C++
s011075g/Project-LimeViolet
/Project-LimeViolet/scr/Render2/RenderContext.hpp
UTF-8
670
2.6875
3
[]
no_license
#pragma once #include "RenderDevice.h" #include "../Common/Color.h" #include "Shader.hpp" class RenderContext { public: inline RenderContext(RenderDevice& device); inline void Clear(bool shouldClearColor, bool shouldClearDepth, bool shouldClearStencil, const Color4& color, uint32_t stencil); inline void Clear(const Color4& color, bool shouldClearDepth = false); inline void Draw(Shader& shader); private: RenderDevice & _device; }; inline RenderContext::RenderContext(RenderDevice& device) : _device(device) { } inline void RenderContext::Clear(bool shouldClearColor, bool shouldClearDepth, bool shouldClearStencil, const Color4& color, uint32_t stencil) { }
true
ddc3b33b88d01b1caabc3cb98e90cf5c351d2679
C++
madhusudansinghrathore/competitive_programming
/icpc_2018/a.cpp
UTF-8
1,225
3.15625
3
[]
no_license
#include<iostream> using namespace std; bool compare( unsigned short int first[], unsigned short int second[] ){ unsigned short int gec=0, gc=0; for( unsigned short int k=0; k<3; ++k ){ if( first[k]>second[k] ){ ++gec; ++gc; }else if( first[k]>=second[k] ){ ++gec; } } if((gec==3) && (gc>0) ){ return true; }else{ return false; } } int main(){ unsigned short int t, arr1[3], arr2[3], arr3[3], i, j; cin >> t; while(t--){ cin >> arr1[0] >> arr1[1] >> arr1[2]; cin >> arr2[0] >> arr2[1] >> arr2[2]; cin >> arr3[0] >> arr3[1] >> arr3[2]; if( compare(arr1, arr2) && compare(arr1, arr3) && compare(arr2, arr3) ){ cout << "yes\n"; }else if( compare(arr1, arr2) && compare(arr1, arr3) && compare(arr3, arr2) ){ cout << "yes\n"; }else if( compare(arr2, arr1) && compare(arr1, arr3) && compare(arr2, arr3) ){ cout << "yes\n"; }else if( compare(arr2, arr3) && compare(arr2, arr1) && compare(arr3, arr1) ){ cout << "yes\n"; }else if( compare(arr3, arr1) && compare(arr3, arr2) && compare(arr1, arr2) ){ cout << "yes\n"; }else if( compare(arr3, arr2) && compare(arr3, arr1) && compare(arr2, arr1) ){ cout << "yes\n"; }else{ cout << "no\n"; } } return 0; }
true
68357feeef5e3739644995ac71ea0ec0e462cff9
C++
ToDevelopersTeam/DS-Algos
/codechef/practice/beginner/Three_Way_Communications.cpp
UTF-8
550
2.734375
3
[]
no_license
#include <iostream> #include<math.h> using namespace std; int main(int argc, char const *argv[]) { int t,r,count=0; double a[3][3],dist; cin>>t; while(t--) { cin>>r; count=0; for(int i=0;i<3;i++) cin>>a[i][0]>>a[i][1]; for(int i=0;i<3;i++) { if(i!=2) dist = sqrt(pow(abs(a[i][0]-a[i+1][0]),2)+pow(abs(a[i][1]-a[i+1][1]),2)); else dist = sqrt(pow(abs(a[i][0]-a[0][0]),2)+pow(abs(a[i][1]-a[0][1]),2)); if(dist<=r) count++; } if(count>=2) cout<<"yes"<<endl; else cout<<"no"<<endl; } return 0; }
true
0ea441b58289cbe79ff9d0a63cceeb05709b575c
C++
el-bart/ACARM-ng
/src/logsplitter/LogSplitter/Parser.hpp
UTF-8
709
2.9375
3
[]
no_license
/* * Parser.hpp * */ #ifndef INCLUDE_LOGSPLITTER_PARSER_HPP_FILE #define INCLUDE_LOGSPLITTER_PARSER_HPP_FILE #include <string> #include <stdexcept> #include <boost/noncopyable.hpp> namespace LogSplitter { /** \brief parser looking for " [<digits>] " sequence. */ class Parser: private boost::noncopyable { public: /** \brief parse given string, looking for a thread number. * \param str string to be parsed. */ explicit Parser(const std::string &str); /** \brief get parsed line number. * \return line number parsed from string. */ unsigned int get(void) const { return num_; } private: const unsigned int num_; }; // class Parser } // namespace LogSplitter #endif
true
85e89c7b3ba19366c3e35c29a0588c1e40337de9
C++
bajajra30/Compiler-1
/Parser/test/test.cpp
UTF-8
241
2.765625
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; int main(int argc, char** argv) { ifstream in; string line; in.open(argv[1]); while ( in.good() ) { getline(in, line); std::cerr << "At line ::" << line << "\n"; } }
true
f9a9526abd2cf476bf88e058bc19079196573ab9
C++
cihancanayyildiz/CSE241
/HW02/circle.h
UTF-8
583
3.0625
3
[]
no_license
#ifndef CIRCLE_H #define CIRCLE_H #include <iostream> #include <fstream> #include <cmath> #include <cstdlib> using namespace std; //Defining circle class class Circle{ public: Circle(); Circle(double radius); Circle(double radius,double cx,double cy); void setCx(double); void setCy(double); void setRadius(double); const inline double getCx() const{ return cx; } const inline double getCy() const{ return cy; } const inline double getRadius() const{ return radius; } void draw(ofstream &file); private: double cx; double cy; double radius; }; #endif
true
c4149b5f3705cb6c555d6150c0e64bab2176d3db
C++
zw0610/SHMHT
/test_hash_table.cxx
UTF-8
1,485
2.828125
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include "resource.h" int main(int argc, const char * argv[]) { RNM rnm{}; rnm.insert_rnode(std::make_tuple<int32_t, uint64_t>(312, 9475628405), RNode(312, 9475628405, 2)); rnm.insert_rnode(std::make_tuple<int32_t, uint64_t>(36452, 2646593046), RNode(36452, 2646593046, 7)); // later removed rnm.print_rnodes(); std::cout << std::endl << "Deleting the second" << std::endl; rnm.delete_rnode(std::make_tuple<int32_t, uint64_t>(36452, 2646593046)); rnm.print_rnodes(); std::cout << std::endl << "Adding more and trying to find" << std::endl; rnm.insert_rnode(std::make_tuple<int32_t, uint64_t>(12, 74653047), RNode(12, 74653047, 65)); //rnm.print_rnode(); rnm.insert_rnode(std::make_tuple<int32_t, uint64_t>(6385, 26465930467), RNode(6385, 26465930467, 77)); rnm.print_rnodes(); auto x = rnm.find_rnode(std::make_tuple<int32_t, uint64_t>(12, 74653047)); if (x != nullptr) { std::cout << "found val: " << *x << " associated with key: (12, 74653047)" << std::endl; } else { std::cout << "no element associated with (12, 74653047)" << std::endl; } auto y = rnm.find_rnode(std::make_tuple<int32_t, uint64_t>(36452, 2646593046)); if (y != nullptr) { std::cout << "found val: " << *y << " associated with key: (36452, 2646593046)" << std::endl; } else { std::cout << "no element associated with (36452, 2646593046)" << std::endl; } return 0; }
true
395255fd94069afa2a41c198747af09f0699f5e0
C++
cchristou3/Firebrick
/Firebrick/CArmour.cpp
UTF-8
1,959
2.96875
3
[ "MIT" ]
permissive
#include "CArmour.h" #include "CMinion.h" CArmour::CArmour(string mName, int mDefenceValue):CEquipment(mName, mDefenceValue) {} void CArmour::Activate(CPlayer* pEnemyPlayer, CPlayer* pCurrentPlayer) { cout << "Armour activated" << endl; bool anyFriendlyMinions = CheckForFriendlyMinions(pCurrentPlayer); if (anyFriendlyMinions) // add defence points to a friendly minion { int numOfCardsOnCurrentTable = pCurrentPlayer->GetNumberOfCardsOnTable(); int randomFriendlyMinionPosition = Random(numOfCardsOnCurrentTable - 1); // -1 because we start from 0 // pick the random friendly minion unique_ptr<CCard> pRandomFriendlyCard = unique_ptr<CCard>(pCurrentPlayer->GetSelectedCardFromTable(randomFriendlyMinionPosition)); // down-casting it to an object of type CMinion CMinion* pChosenFriendlyMinionCard = dynamic_cast<CMinion*>(pRandomFriendlyCard.get()); unique_ptr<CMinion> pChosenFriendlyMinion; if (pChosenFriendlyMinionCard != nullptr) { pRandomFriendlyCard.release(); pChosenFriendlyMinion.reset(pChosenFriendlyMinionCard); } IncreaseDefence(std::move(pChosenFriendlyMinion)); } else { HealCurrentPlayer(pCurrentPlayer); cout << "Armour heals " << pCurrentPlayer->GetName() << ". " << pCurrentPlayer->GetName() << " health now " << pCurrentPlayer->GetHealthPoints() << endl; } } void CArmour::IncreaseDefence(unique_ptr<CMinion> pChosenFriendlyMinion) { int minionInitialDefencePoints = pChosenFriendlyMinion->GetDefence(); int additionalDefencePoints = this->GetEquipmentValue(); int minionUpdatedDefencePoints = minionInitialDefencePoints + additionalDefencePoints; pChosenFriendlyMinion->SetDefence(minionUpdatedDefencePoints); cout << "Armour increases defence points of " << pChosenFriendlyMinion->GetName() << ". " << pChosenFriendlyMinion->GetName() << "'s defence points now " << pChosenFriendlyMinion->GetDefence() << endl; pChosenFriendlyMinion.release(); // releasing the ownership }
true
874c64726f7d543707f7d774f48ff996c5c03495
C++
arthurkhadraoui/TP-2
/viewMenu.h
UTF-8
405
2.59375
3
[]
no_license
#ifndef VIEWMENU_H #define VIEWMENU_H #include "observer.h" #include "view.h" #include "controller.h" class ViewMenu: public View{ public: //Constructeur de ka ckasse viewMenu ViewMenu(Controller& _controller); //Mets à jour le MVC virtual void notify(); //Affiche le menu principal virtual void display(); private: //Controller du menu principal Controller& controller; }; #endif
true
ee88e5a2b5648c4af5087f6d8d21b3b316c80f62
C++
elifesciences-publications/TeamHJ-tissue
/src/vertex.cc
UTF-8
4,692
3
3
[ "MIT" ]
permissive
// // Filename : vertex.cc // Description : A class describing a vertex // Author(s) : Henrik Jonsson (henrik@thep.lu.se) // Created : April 2006 // Revision : $Id$ // #include <cmath> #include <cstdlib> #include <vector> #include "myMath.h" #include "vertex.h" #include "wall.h" Vertex::Vertex() { } Vertex::Vertex( const Vertex & vertexCopy ) { index_ = vertexCopy.index(); id_ = vertexCopy.id(); position_ = vertexCopy.position(); cell_ = vertexCopy.cell(); wall_ = vertexCopy.wall(); stressDirection_ = vertexCopy.stressDirection(); } Vertex:: Vertex( const std::vector<double> &position, size_t indexVal ) { position_ = position; index_ = indexVal; id_ = ""; //cell_ = vertexCopy.cell(); //wall_ = vertexCopy.wall(); //stressDirection_ = vertexCopy.stressDirection(); } Vertex::~Vertex() { } int Vertex::removeCell( Cell* val ) { for (size_t k=0; k<cell_.size(); ++k) if (cell_[k]==val) { cell_[k]=cell_[cell_.size()-1]; cell_.pop_back(); return 1; } return 0; } int Vertex::removeWall( Wall* val ) { for (size_t k=0; k<wall_.size(); ++k) if (wall_[k]==val) { wall_[k]=wall_[wall_.size()-1]; wall_.pop_back(); return 1; } return 0; } int Vertex::isBoundary(Cell *background) const { for (size_t wI=0; wI<numWall(); ++wI) if (wall_[wI]->hasCell(background)) return 1; return 0; } int Vertex::isNeighborViaWall(Vertex *v) const { for (size_t wI=0; wI<numWall(); ++wI) if (wall_[wI]->hasVertex(v)) return wI; return -1; } void Vertex::calculateStressDirection(DataMatrix &vertexData, DataMatrix &wallData, std::vector<size_t> &wallForceIndexes) { size_t dimensions = vertexData[0].size(); size_t numberOfWalls = wall_.size(); // Copy wall force data to temporary container and calculate mean values. std::vector< std::vector<double> > walls(2 * numberOfWalls); for (size_t i = 0; i < walls.size(); ++i) { walls[i].resize(dimensions); } for (size_t i = 0; i < wall_.size(); ++i) { Wall *w = wall_[i]; Vertex *v1 = w->vertex1(); Vertex *v2 = w->vertex2(); double force = 0.0; for (size_t j = 0; j < wallForceIndexes.size(); ++j) { force += wallData[w->index()][wallForceIndexes[j]]; } std::vector<double> n(dimensions); double A = 0.0; for (size_t j = 0; j < dimensions; ++j) { if (v1 == this) { n[j] = vertexData[v2->index()][j] - vertexData[v1->index()][j]; } else { n[j] = vertexData[v1->index()][j] - vertexData[v2->index()][j]; } A += n[j] * n[j]; } A = std::sqrt(A); for (size_t j = 0; j < dimensions; ++j) { n[j] /= A; } for (size_t j = 0; j < dimensions; ++j) { walls[2 * i + 0][j] = force * n[j]; walls[2 * i + 1][j] = -force * n[j]; } } // // Mean is always equal to zero so no need to subtract it. // // Calculate the correlation matrix. std::vector< std::vector<double> > R(dimensions); for (size_t i = 0; i < dimensions; ++i) { R[i].resize(dimensions); for (size_t j = 0; j < dimensions; ++j) { R[i][j] = 0.0; } } for (size_t k = 0; k < dimensions; ++k) { for (size_t l = 0; l < dimensions; ++l) { for (size_t i = 0; i < numberOfWalls; ++i) { R[k][l] += walls[i][k] * walls[i][l]; } R[k][l] /= numberOfWalls; } } // Find the eigenvectors with the two greatests corresponding eigenvalues. std::vector< std::vector<double> > candidates; std::vector< std::vector<double> > V; std::vector<double> d; myMath::jacobiTransformation(R , V, d); double max = 0.0; size_t max1 = d.size(); max = 0.0; for (size_t i = 0; i < d.size(); ++i) { if (std::abs(d[i]) >= max) { max1 = i; max = std::abs(d[i]); } } if (max1 == d.size()) { std::cerr << "Vertex::calculateStressDirection(): Unexpected behaviour." << std::endl; exit(EXIT_FAILURE); } // Find orthonormal basis. std::vector< std::vector<double> > E_(1); E_[0].resize(dimensions); for (size_t i = 0; i < dimensions; ++i) { // E_[0][i] = V[max1][i]; E_[0][i] = V[i][max1]; } for (size_t i = 0; i < E_.size(); ++i) { double sum = 0.0; for (size_t j = 0; j < dimensions; ++j) { sum += E_[i][j] * E_[i][j]; } for (size_t j = 0; j < dimensions; ++j) { E_[i][j] /= std::sqrt(sum); } } stressDirection_.resize(dimensions); for (size_t i = 0; i < dimensions; ++i) { stressDirection_[i] = d[max1] * E_[0][i]; } } std::vector<double> Vertex::stressDirection(void) const { return stressDirection_; }
true
6c0bff164d153d121dcbde3b44aa796232b68559
C++
tangyingzhong/ToolKit_Windows
/ToolKit/Tool/Socket/SocketClient.cpp
UTF-8
3,155
2.609375
3
[]
no_license
#include "SocketClient.h" #pragma comment(lib, "wsock32.lib") using namespace System::Network; // Construct the SocketClient SocketClient::SocketClient(IPAddress strIPAddress, NetPort iPortNo) :m_ServerSocket(NULL), m_ServerIP(strIPAddress), m_ServerPort(iPortNo), m_Disposed(false) { Initialize(); } // Detructe the SocketClient SocketClient::~SocketClient() { Destory(); } // Initialize the socket SocketClient::None SocketClient::Initialize() { CreateSocket(InterNetwork, Stream, Tcp); } // Dispose the socket SocketClient::None SocketClient::Destory() { if (!GetDisposed()) { SetDisposed(true); DestorySocket(); } } // Create a socket SocketClient::None SocketClient::CreateSocket(AddressFamily family, SocketType socketType, ProtocolType protocolType) { SetServerSocket(new Socket(family, socketType, protocolType)); } // Destory the socket SocketClient::None SocketClient::DestorySocket() { if (GetServerSocket()) { delete GetServerSocket(); SetServerSocket(NULL); } } // Open a server socket SocketClient::None SocketClient::Open() { if (GetServerSocket()) { GetServerSocket()->Open(); } } // Close the server socket SocketClient::None SocketClient::Close() { if (GetServerSocket()) { GetServerSocket()->Close(); } } // Connect to the server SocketClient::BOOL SocketClient::Connect() { if (GetServerSocket()) { return GetServerSocket()->Connect(GetServerIP(), GetServerPort()); } return false; } // Start the server SocketClient::BOOL SocketClient::Start() { // Open the server Open(); // Connect to the server return Connect(); } ///************************************************************************ /// <summary> /// Stop the server /// </summary> /// <returns></returns> /// <remarks> /// none /// </remarks> ///*********************************************************************** SocketClient::None SocketClient::Stop() { Close(); } ///************************************************************************ /// <summary> /// Receive the data from the client /// </summary> /// <param name=buffer></param> /// <param name=offset></param> /// <param name=len></param> /// <returns></returns> /// <remarks> /// none /// </remarks> ///*********************************************************************** SocketClient::BOOL SocketClient::Receive(SByteArray pReadBuffer, Length iOffset, Length iReadSize) { BOOL bSuccess = false; if (GetServerSocket()) { bSuccess = GetServerSocket()->Receive(pReadBuffer, iOffset, iReadSize); } return bSuccess; } ///************************************************************************ /// <summary> /// Send the data to the client /// </summary> /// <param name=buffer></param> /// <param name=offset></param> /// <param name=len></param> /// <returns></returns> /// <remarks> /// none /// </remarks> ///*********************************************************************** SocketClient::BOOL SocketClient::Send(SByteArray pWriteBuffer, Length iOffset, Length iWriteSize) { BOOL bSuccess = false; if (GetServerSocket()) { bSuccess = GetServerSocket()->Send(pWriteBuffer, iOffset, iWriteSize); } return bSuccess; }
true
258dccd79d6a15619892ebf12132d76e196872e0
C++
frazierk27/coe-f2018-fortran
/vectors.cpp
UTF-8
1,044
3.421875
3
[]
no_license
#include <iostream> #include <vector> using std::vector; using std::cout; using std::endl; vector<float> makeVector( int size, float value){ vector<float> x(size,value); return x; } int printVector(vector<float> Vector1){ for (auto i: Vector1){ cout << i << endl; } } int resetVectorToZero(vector<float> &myVector2){ for (auto &i : Vector2 ){ i = 0; } } vector<float> combineVector(vector<float> A, vector<float> B){ return C; } vector<float> combineVectorsAndEmpty(vector<float>vectorB){ for (auto i: vectorB){ vectorC.push_back(vectorB.back()); vectorB.pop_back(); } return vectorC; } int main () { vector<int> myVector = {4, 7,3, 2, 1}; vector<float> R(20,5); vector<vector<float>> N(10,R); cout << "N contains:" << endl; for (auto &x : N){ cout << x << " "; } for (auto &i: myVector){ cout << i << endl; i = 5; } for (auto i: myVector){ cout << i << endl; } vector<float> A = makeVector(5,3); vector<float> B = makeVector(7,2); vector<float> C = combineVector(A,B); printVector(C); }
true
d4cf81e08bc580dee259e67bedf17c482d4178c1
C++
ccarr419/Academic-Projects
/sideprojects/derivatives/derivative1.cpp
UTF-8
2,826
4.03125
4
[]
no_license
/* Author: Christian Carreras ** File: derivatve1.cpp ** Purpose: To find the derivative of polynomials */ #include <iostream> using namespace std; /* Function: menu() ** Returns: void ** Parameters: none ** Purpose: displays the menu for the user */ void menu(); /* Function: select() ** Returns: int ** Parameters: none ** Purpose: user selects the option to commence */ int select(); /* Function: singleTerm() ** Returns: void ** Parameters: none ** Purpose: user enters a single term and exponent */ void singleTerm(); /* Function: foX() "f of x" ** Returns: void ** Parameters: float, int ** Purpose: finds the derivative of the given polynomial */ void foX(float, int); //Polynomial containing a term and exponent struct poly { float term; int exp; }; int main() { menu(); int option = select(); while(!option) { cout << "\nThat is not a valid choice\n"; menu(); option = select(); } while(option != -1) { menu(); option = select(); } return 0; } void menu() { cout << "\nPlease select an option\n"; cout << "1. (Single Term)\n"; cout << "2. (Multiple Term) *N/A\n"; cout << "3. (Product Rule) *N/A\n"; cout << "4. (Quotient Rule) *N/A\n"; cout << "5. (Chain Rule) *N/A\n"; cout << "6. (Trig Terms) *N/A\n"; cout << "<-1 to exit>\n"; } int select() { int choice; cout << "\nPlease enter your choice: "; cin >> choice; switch(choice) { case 1: singleTerm(); return 1; case 2: return 2; case 3: return 3; case 4: return 4; case 5: return 5; case 6: return 6; case -1: return -1; default: return 0; } } void singleTerm() { poly singlePoly; cout << "Please enter the term: "; cin >> singlePoly.term; cout << "Please enter the exponent: "; cin >> singlePoly.exp; foX(singlePoly.term, singlePoly.exp); } void foX(float term, int exp) { if(term == 0) { cout << "f(x) = 0\n"; cout << "f'(x) = 0\n"; } else if(exp == 0) { cout << "f(x) = " << term << endl; cout << "f'(x) = 0\n"; } else if(term == 1) { if(exp == 1) { cout << "f(x) = x\n"; cout << "f'(x) = 1\n"; } else { cout << "f(x) = x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << exp << "x\n"; else cout << "f'(x) = " << exp << "x^" << exp-1 << endl; } } else if(term == -1) { if(exp == 1) { cout << "f(x) = -x\n"; cout << "f'(x) = -1\n"; } else { cout << "f(x) = -x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << term*exp << "x\n"; else cout << "f'(x) = " << term*exp << "x^" << exp-1 << endl; } } else { if(exp == 1) { cout << "f(x) = " << term << "x\n"; cout << "f'(x) = " << term << endl; } else { cout << "f(x) = " << term << "x^" << exp << endl; if(exp == 2) cout << "f'(x) = " << term*exp << "x\n"; else cout << "f'(x) = " << term*exp << "x^" << exp-1 << endl; } } }
true
7fab32fc0b281c6a68b5cfd28cb674ddfa45bad7
C++
alvinalvord/CPL
/uva/103/10327/a.cpp
UTF-8
1,033
3.328125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> void merge (int *left, int *right, int n, int m); void mergesort (int *arr, int n); long long swaps; void merge (int *left, int *right, int n, int m) { if (n > 1) mergesort (left, n); if (m > 1) mergesort (right, m); int i = 0, j = 0, size = n + m, *arr = (int *) malloc (sizeof (int) * size), dex = 0; while (i < n && j < m) { if (left[i] <= right[j]) { arr[dex++] = left[i++]; } else { arr[dex++] = right[j++]; swaps += n - i; } } while (i < n) arr[dex++] = left[i++]; while (j < m) arr[dex++] = right[j++]; for (i = 0; i < size; i++) left[i] = arr[i]; free (arr); } void mergesort (int *arr, int n) { int x = n / 2; int y = n - x; merge (arr, arr + x, x, y); } int main () { int n, i; while (scanf ("%d", &n) == 1) { int *arr = (int *) malloc (sizeof (int) * n); for (i = 0; i < n; i++) { scanf ("%d", arr + i); } swaps = 0; mergesort (arr, n); printf ("Minimum exchange operations : %lld\n", swaps); free (arr); } return 0; }
true
1fbc6c139011bac36f702a0df2ab923d7b1bb000
C++
yunqing/playground
/Singleton/singleton.h
UTF-8
479
2.671875
3
[ "MIT" ]
permissive
#ifndef __SINGLETON__ #define __SINGLETON__ // thread unsafe version class SimpleSingleton { public: static SimpleSingleton * get_singleton(); static void release_singleton(); int get_data(); void set_data(int); int get_data_static(); void set_data_static(int); SimpleSingleton * get_handle(); private: static SimpleSingleton * m_singleton; static int data_static; int data; SimpleSingleton() { this->data = 0; } }; #endif
true
779001139eaa3c667c5a770cb13f2121254311d6
C++
Badrivishal/CodeForcesPractice
/Cpp/Required_Remainder.cpp
UTF-8
478
2.640625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include<algorithm> #include <bits/stdc++.h> #include <iomanip> using namespace std; int main() { int t; cin >> t; while (t--) { long long int x, y, n, d; cin >> x >> y >> n; d = n / x; if ((d * x) + y <= n) { cout << (d * x) + y << endl; } else { cout << ((d - 1) * x) + y << endl; } } return 0; }
true
613fd9af46a491e76febb13f88e0da6063ba1806
C++
Ricky-Ting/coding-in-NJU
/C++/2018_practice/OJ2-13/my.cpp
UTF-8
1,150
2.765625
3
[]
no_license
#include<iostream> #include<ctime> #include<algorithm> #include<cmath> #include<cstdio> int tmp[10]; int snowflake[100001][7]; int x,y; int n; void input(void) { scanf("%d",&n); for(int i=0;i<n;i++) for(int j=0;j<6;j++) scanf("%d",&snowflake[i][j]); } bool cmp(int a, int b) { for(int i=0;i<6;i++) { if( (snowflake[a][0]==snowflake[b][i] && snowflake[a][1]==snowflake[b][(i+1)%6] && snowflake[a][2]==snowflake[b][(i+2)%6] && snowflake[a][3]==snowflake[b][(i+3)%6] && snowflake[a][4]==snowflake[b][(i+4)%6] && snowflake[a][5]==snowflake[b][(i+5)%6] ) || (snowflake[a][0]==snowflake[b][i] && snowflake[a][1]==snowflake[b][(i+5)%6] && snowflake[a][2]==snowflake[b][(i+4)%6] && snowflake[a][3]==snowflake[b][(i+3)%6] && snowflake[a][4]==snowflake[b][(i+2)%6] && snowflake[a][5]==snowflake[b][(i+1)%6] ) ) return true; } return false; } void solve(void) { for(int i=1;i<=20000000;i++) { x=rand()%n; y=rand()%n; if(x!=y) if(cmp(x,y)) { printf("Twin snowflakes found.\n"); return; } } printf("No two snowflakes are alike.\n"); } int main(void) { srand(time(NULL)); input(); solve(); }
true
e39197ee1bd247458401df2e80a65bf37dcbc877
C++
GoToChess/OOP-C-
/goto() is all powerful/chess/chess.cpp
UTF-8
1,966
2.8125
3
[]
no_license
#include "user.h" /* Header Files Layout Piece.h -> Board.h -> rules.h -> situations.h -> computer.h -> user.h ctdlib, iostream and using namespace std have all been added to the pieces class*/ /** * @author Jack McErlean <mcerlean-j@ulster.ac.uk> * B00713696 * Main Terminal * * objects from all our classes are made * constant while loop running with a state changer for who's go it is * while loop ended by a checkmate for user or computer * * @return 0 for exit of function */ int main() { int difficulty; int userturn = 1; Interface move; move.printLogo(); cpu move1(&difficulty); Rules king; situations piece; Board chess; while (1) { if (userturn) { if (piece.checkMate('B', board)) // user's king is in checkmate... game over { break; // breaks while loop and main ends } chess.printBoard(board); move.userInput(); move.movePiece(board); system("cls"); if (king.incheck('W', board)) { cout << "White king in check" << endl; } piece.pawn_promotion(board); if (move.playergo == 0) { userturn = 0; } } if (!userturn) { cout << "----------------- user's go over ------------------" << endl << endl; if (piece.checkMate('W', board)) // computer's king is in checkmate... game over { break; // breaks while loop and main ends } chess.printBoard(board); cout << "Computer's go... " << endl; if (difficulty == 1) { move1.easy_diff(board); } if (difficulty == 2) { move1.med_diff(board); } if (difficulty == 3) { move1.hard_diff(board); } if (king.incheck('W', board)) { cout << " Game over, User wins" << endl; break; } if (king.incheck('B', board)) { cout << "Black king in check" << endl; } piece.pawn_promotion(board); userturn = 1; } } return 0; }
true
8b43a4a116815e0ab7b7e0610302e4f53996aee5
C++
vishalpatil0/CPP-programs
/Initilize all element of array with same value.cpp
UTF-8
526
3.484375
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int main() { int arr1[10]={}; // all elements are zeros. int arr2[10]={0}; // all elements are zeros. int arr3[]={}; // elements upto 26 are 0 rest are garabage value. size of this array is depend on system architecture. int arr4[100]; //using for loop //using std:fill_in function int arr5[100]; fill_n(arr5,100,45); cout<<arr5[5]<<endl; int arr6[10]={1,2}; //this array have all remaining value as 0. return 0; }
true
45ed53077535cc64793b13af5aaf4661fc02ab94
C++
Leumash/ProjectEuler
/78/78.cc
UTF-8
2,074
3.6875
4
[]
no_license
/* Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can be separated into piles in exactly seven different ways, so p(5)=7. OOOOO OOOO O OOO OO OOO O O OO OO O OO O O O O O O O O Find the least value of n for which p(n) is divisible by one million. */ /* How many unique ways to fit N indistinguishable balls into K indistinguishable boxes where each box contains at least 1 ball? p(n) = Summation of above where 1 <= m <= n https://en.wikipedia.org/wiki/Partition_%28number_theory%29 In number theory, the partition function p(n) represents the number of possible partitions of a natural number n, which is to say the number of distinct ways of representing n as a sum of natural numbers (with order irrelevant). By convention p(0) = 1, p(n) = 0 for n negative. */ #include <iostream> #include <map> #include <utility> #define SIZE_LIMIT 10000000ll using namespace std; bool IsDivisible(int n, int divisor) { return n % divisor == 0; } long long GetPn(long long n, long long arr[]) { long long total = 0; long long multiplier = 1; for (long long k=1; k<=n; ++k) { long long inner1 = n - (k * (3 * k - 1)) / 2; long long inner2 = n - (k * (3 * k + 1)) / 2; if (inner1 >= 0) { total += multiplier * arr[inner1]; } if (inner2 >= 0) { total += multiplier * arr[inner2]; } if (inner1 < 0) { break; } multiplier *= -1; total %= SIZE_LIMIT; } arr[n] = total % SIZE_LIMIT; return arr[n]; } int GetNForWhichPnIsDivisibleBy(int divisor) { long long arr[100000]; arr[0] = 1; for (long long n=1; ; ++n) { long long Pn = GetPn(n, arr); if (IsDivisible(Pn, divisor)) { return n; } } } int main() { cout << GetNForWhichPnIsDivisibleBy(1000000) << endl; return 0; }
true
a023aad1c1952d4e19f61fab592b26bacdb1bd8c
C++
turingcompl33t/coroutines
/applications/binary-search/vanilla.hpp
UTF-8
760
2.765625
3
[ "MIT" ]
permissive
// vanilla.hpp // Vanilla binary search. // // Adapated from original code by Gor Nishanov. // https://github.com/GorNishanov/await/tree/master/2018_CppCon #ifndef VANILLA_BS_HPP #define VANILLA_BS_HPP template <typename Iter> bool vanilla_binary_search(Iter first, Iter last, int val) { auto len = last - first; while (len > 0) { auto const half = len / 2; auto const middle = first + half; auto middle_key = *middle; if (middle_key < val) { first = middle + 1; len = len - half - 1; } else { len = half; } if (middle_key == val) { return true; } } return false; } #endif // VANILLA_BS_HPP
true
fdee210bc8414a9452305f71df60537647e94592
C++
hallgeirl/master-project
/pathfinding/main.cpp
UTF-8
22,491
2.53125
3
[]
no_license
#include <FreeImage.h> #include <string> #include <fstream> #include <iostream> #include <cmath> #include <map> #include <algorithm> #include <vector> #include <assert.h> #include <limits> #include <unordered_map> #include <sstream> #include <getopt.h> #include <sys/time.h> #include "util.h" #include "vec2.h" #include "terrain.h" #include "clothoid.h" #include "fresnel.h" using namespace std; using namespace fresnel; using namespace clothoid; #ifndef PI #ifdef M_PI #define PI M_PI #else #define PI 3.14159265358979323846 #endif #endif #define PRINT_ALL(cont, counter, fmt, ...) for (size_t counter = 0; counter < cont.size(); counter++) printf(fmt, __VA_ARGS__); double getTime() { timeval t; gettimeofday(&t, 0); return (double)t.tv_sec + (double)t.tv_usec / 1000000.; } double weight_slope = 100.f*1., weight_curvature = 100.f*1, weight_road = 1.f; double heuristic_alpha = 1; //vec2d transrot(const vec2d& p, const vec2d& dp, double rot); // ////Rotate, then translate //vec2d rottrans(const vec2d& p, const vec2d& dp, double rot); struct node_t { vec2i p; double cost_g, cost_h; node_t(vec2i _p, double _cost_g, double _cost_h) : p(_p), cost_g(_cost_g), cost_h(_cost_h) { } double cost_f() const { return cost_g + cost_h; } bool operator< (const node_t& n2) const { return cost_f() > n2.cost_f(); } bool operator> (const node_t& n2) const { return cost_f() < n2.cost_f(); } bool operator== (const node_t& n2) const { return p == n2.p; } bool operator== (const vec2i n2) const { return p == n2; } }; //Heuristic for computing the cost from a to b. inline double h(const terrain_t& terrain, const vec2d& a, const vec2d& b) { double dx = a.x-b.x, dy = a.y-b.y; // dz = 0; double dz = terrain.getPointBilinear(b.x, b.y) - terrain.getPointBilinear(a.x, a.y); double len = sqrt(dx*dx+dy*dy); // return len*weight_road + dz*weight_slope/len; // *weight_slope; return heuristic_alpha*(len*weight_road + fabs(dz)*weight_slope); // *weight_slope; } inline double get_slope(const terrain_t& terrain, const vec2d& a, const vec2d& b) { double dx = a.x-b.x, dy = a.y-b.y; double dz = terrain.getPointBilinear(b.x, b.y) - terrain.getPointBilinear(a.x, a.y); // double length = sqrt(dx*dx+dy*dy); double slope = dz/sqrt(dx*dx+dy*dy); return slope; } inline double get_slope_no_norm(const terrain_t& terrain, const vec2d& a, const vec2d& b) { double dz = terrain.getPointBilinear(b.x, b.y) - terrain.getPointBilinear(a.x, a.y); return dz; } inline double transfer_slope(const terrain_t& terrain, const vec2d& a, const vec2d& b) { if (weight_slope == 0) return 0; // double k0 = 0.5; double k0 = 1; // double slope = fabs(get_slope(terrain, a, b)); double slope = fabs(get_slope_no_norm(terrain, a, b)); if (slope > k0) { // printf("slope is infinity\n"); // fflush(stdout); // return numeric_limits<double>::infinity(); } return weight_slope*slope; // return slope; // return weight_slope*(slope+slope*slope); } inline double transfer_curvature(const terrain_t& terrain, const vec2d& a, const vec2d& b, const vec2d& prev) { if (weight_curvature == 0) return 0; vec2d vb = b-a; vec2d va = a-prev; double lenA = va.length(); double lenB = vb.length(); if (lenA == 0 || lenB == 0) return 0; va = va * (1./lenA); vb = vb * (1./lenB); double cos_theta = va.dot(vb); cos_theta = fmax(fmin(cos_theta, 1),-1); double theta = acos(cos_theta); if (theta != theta) { printf("theta is NAN! %f %f %f %f %f\n", va.dot(vb), va.x, va.y, vb.x, vb.y); fflush(stdout); } double k0 = 0.03; double curvature = 2.f*sin(theta/2.f)/sqrt(lenA*lenB); if (curvature > k0) return numeric_limits<double>::infinity(); return weight_curvature*curvature; } //Transfer function for cost of making the road itself. This is dependent on the length of the road (how much material is used, basically) inline double transfer_road(const terrain_t& terrain, const vec2d& a, const vec2d& b) { double dx = a.x-b.x, dy = a.y-b.y; double dz = 0; // double dz = terrain.getPointBilinear(b.x, b.y) - terrain.getPointBilinear(a.x, a.y); return weight_road*sqrt(dx*dx+dy*dy+dz*dz); } //Integrate the cost over the path segment double cost(const terrain_t& terrain, const vec2d& a, const vec2d& v, const vec2d& b, bool first, bool last) { //do we have enough points to make a curve? If not, return a cost of 0. double i = 0; double cost_slope = 0; vec2d dir = b-v; const double tn = dir.length(); dir = dir / tn; const double step = 0.5*terrain.point_spacing; for (double t = 0; t < tn; t = i*step, i++) { double t1 = t, t2 = t+step; if (t2 > tn) t2 = tn; vec2d _a = dir*t1 + v, _b = dir*t2 + v; cost_slope += transfer_slope(terrain, _a, _b); // cost_slope += transfer_slope(terrain, _a, _b) * (t2-t1); // if (transfer_slope(terrain, _a, _b) > 4) // printf("slope %lf, (%lf,%lf)-(%lf,%lf): %lf-%lf\n", transfer_slope(terrain, _a, _b), _a.x, _a.y, _b.x, _b.y, terrain.getPointBilinear(_a.x, _a.y), terrain.getPointBilinear(_b.x, _b.y)); } double cost_road = transfer_road(terrain, v, b), cost_curvature = transfer_curvature(terrain, v, b, a); if (cost_road+cost_slope+cost_curvature == numeric_limits<double>::infinity()) return numeric_limits<double>::infinity(); return cost_road + cost_slope + cost_curvature; } vector<vec2d> pathFind(const terrain_t& terrain, vec2i start, vec2i end, int grid_density, int k) { map<vec2i, vec2i> predecessor; unordered_map<vec2i, double> in_open; unordered_map<vec2i, bool> closed; vector<node_t> open; start.x = ((int)(start.x/grid_density))*grid_density; start.y = ((int)(start.y/grid_density))*grid_density; end.x = ((int)(end.x/grid_density))*grid_density; end.y = ((int)(end.y/grid_density))*grid_density; //Make a list of neighbors with gcd(i,j) == 1 vector<vec2i> neighborhood; for (int i = 0; i <= k; i++) { for (int j = 0; j <= k; j++) { if (i == 0 && j == 0) continue; if (gcd(i,j) == 1) { neighborhood.push_back(vec2i(i,j)); if (i != 0) neighborhood.push_back(vec2i(-i,j)); if (j != 0) neighborhood.push_back(vec2i(i,-j)); if (j != 0 && i != 0) neighborhood.push_back(vec2i(-i,-j)); } } } // printf("Neighborhood:\n"); // PRINT_ALL(neighborhood, i, "%d,%d\n", neighborhood[i].x, neighborhood[i].y); node_t current(start, 0, 0); predecessor[start] = start; open.push_back(node_t(start, 0, h(terrain, terrain.gridToPoint(start), terrain.gridToPoint(end)))); make_heap(open.begin(), open.end()); while (open.size() > 0) { // sleep(1); // printf("Open:\n"); // PRINT_ALL(open, i, "%d %d: g: %.3f h: %.3f f: %.3f\n", open[i].p.x, open[i].p.y, open[i].cost_g, open[i].cost_h, open[i].cost_f()); //Get the next best node and pop it from the heap current = open.front(); pop_heap(open.begin(), open.end()); open.pop_back(); //If the node is already in the closed list, we have already processed it (this may happen if the node is added more than once due to a better route) unordered_map<vec2i, bool>::iterator closed_it = closed.find(current.p); if (closed_it != closed.end()) { continue; } //Mark this node as not being in the open list, and move it to the closed list. in_open.erase(current.p); closed[current.p] = true; // static int ii = 0; // ii++; // if (ii % 1000 == 0) // { // printf("current %d,%d\tnopen %zd\tnclosed %zd\tf %f\th %f\n", current.p.x, current.p.y, open.size(), closed.size(), current.cost_f(), current.cost_h); // fflush(stdout); // } // printf("Closed:\n"); // for (map<vec2i, bool>::iterator it = closed.begin(); it != closed.end(); it++) // { // printf("%d %d\n", it->first.x, it->first.y); // } // fflush(stdout); //Reached the end? if (current == end) { //Get the final cost // printf("Final cost %lf, %lf\n", current.cost_g, current.cost_h); break; } //Push the neighbors into the heap for (size_t i = 0; i < neighborhood.size(); i++) { //Position of next node vec2i pos = current.p + neighborhood[i]*grid_density; if (pos.x >= 0 && pos.y >= 0 && pos.x < terrain.width && pos.y < terrain.height) { if (closed.find(pos) != closed.end()) { continue; } //First curve segment? const vec2i& v = current.p; const vec2i& pa = predecessor[current.p]; const vec2i& pb = pos; node_t n(pos, current.cost_g + cost(terrain, terrain.gridToPoint(pa), terrain.gridToPoint(v), terrain.gridToPoint(pb), predecessor[current.p] == start, pos == end), h(terrain, terrain.gridToPoint(pos), terrain.gridToPoint(end))); if (n.cost_g == numeric_limits<double>::infinity()) continue; unordered_map<vec2i, double>::iterator in_open_it = in_open.find(n.p); if (in_open_it == in_open.end() || (in_open_it != in_open.end() && in_open_it->second > n.cost_g)) { open.push_back(n); push_heap(open.begin(), open.end()); in_open[n.p] = n.cost_g; predecessor[n.p] = current.p; } } } } // printf("Predecessors (successor -> predecessor):\n"); // for (map<vec2i, vec2i>::iterator it = predecessor.begin(); it != predecessor.end(); it++) // { // printf("%d,%d <- %d,%d\n", it->first.x, it->first.y, it->second.x, it->second.y); // } // cout << "Backtracking" << endl; //Backtrace vector<vec2d> result; vec2i current_pos = predecessor[end]; result.push_back(terrain.gridToPoint(end)); while (!(current_pos == start)) { // printf("current pos: %d %d\n", current_pos.x, current_pos.y); result.push_back(terrain.gridToPoint(current_pos)); current_pos = predecessor[current_pos]; } result.push_back(terrain.gridToPoint(start)); reverse(result.begin(), result.end()); while (result.size() < 3) result.push_back(result.back()); return result; } long filesize(ifstream& f) { long current = f.tellg(); f.seekg(0, ios::beg); long beg = f.tellg(); f.seekg(0, ios::end); long end = f.tellg(); f.seekg(current, ios::beg); return end-beg; } void writeRoadXML(string filename, const vector<vec2d>& controlPoints, const terrain_t& terrain) { vec2d startDirV = controlPoints[1] - controlPoints[0]; startDirV = startDirV * (1./startDirV.length()); double startDir = acos(fmin(fmax(startDirV.dot(vec2d(1.,0.)),-1), 1)); // Determine which quadrant the direction is in if (startDirV.y < 0) startDir = 2.*PI - startDir; ifstream head_f("roadxml_template_head.rnd"); ifstream tail_f("roadxml_template_tail.rnd"); int head_size = filesize(head_f); char* head_buf = new char[head_size]; head_f.read(head_buf, head_size); int tail_size = filesize(tail_f); char* tail_buf = new char[tail_size]; tail_f.read(tail_buf, tail_size); ofstream output(filename.c_str()); output.write(head_buf, head_size); output << " <XYCurve direction=\"0\" x=\"" << (double)controlPoints[0].x << "\" y=\"" << (double)controlPoints[0].y << "\">\n"; output << " <ClothoidSpline type=\"spline\">\n"; for (size_t i = 1; i < controlPoints.size(); i++) { output << " <Vectord2 x=\"" << controlPoints[i].x-controlPoints[0].x << "\" y=\"" << controlPoints[i].y-controlPoints[0].y << "\" />\n"; } output << " </ClothoidSpline>\n"; output << " </XYCurve>\n"; // Form the polynomials needed for the SZCurve ClothoidSpline spline(controlPoints); double step = 50; clothoid_point_t pos_prev = spline.lookup(0), pos_next = spline.lookup(min(step, spline.length())); output << " <SZCurve>\n"; output << " <Polynomial>\n"; output << " <begin direction=\"" << get_slope(terrain, pos_prev.pos, pos_next.pos) << "\" x=\"0\" y=\"" << terrain.getPointBilinear(pos_prev.pos.x, pos_prev.pos.y) << "\" />\n"; for (double t = step; t < spline.length()-step-1e-6; t += step) { // fprintf(stderr, "foo %lf %lf\n", t, spline.length()-step-1e-6); pos_prev = pos_next; pos_next = spline.lookup(t+step); stringstream ss_point; ss_point << "direction=\"" << get_slope(terrain, pos_prev.pos, pos_next.pos) << "\" x=\"" << t << "\" y=\"" << terrain.getPointBilinear(pos_prev.pos.x, pos_prev.pos.y) << "\""; output << " <end " << ss_point.str() << " />\n"; output << " </Polynomial>\n"; output << " <Polynomial>\n"; output << " <begin " << ss_point.str() << " />\n"; } // vec2d last = controlPoints.back(), secondLast = controlPoints[controlPoints.size()-2]; // length += (last-secondLast).length(); output << " <end direction=\"0\" x=\"" << spline.length() << "\" y=\"" << terrain.getPointBilinear(pos_next.pos.x, pos_next.pos.y) << "\" />\n"; output << " </Polynomial>\n"; output << " </SZCurve>\n"; output << " <BankingCurve>\n"; output << " <Polynomial>\n"; output << " <begin direction=\"0\" x=\"0\" y=\"0\" />\n"; output << " <end direction=\"0\" x=\"" << spline.length() << "\" y=\"0\" />\n"; output << " </Polynomial>\n"; output << " </BankingCurve>\n"; output << " <Portion endDistance=\"" << spline.length() << "\" endProfile=\"defaultNoMotorvei\" name=\"\" startProfile=\"defaultNoMotorvei\"/>\n"; output.write(tail_buf, tail_size); output.close(); delete[] head_buf; delete[] tail_buf; } void setPixelColor(FIBITMAP* bm, int x, int y, int r, int g, int b) { RGBQUAD rgb; rgb.rgbRed = r; rgb.rgbGreen = g; rgb.rgbBlue = b; FreeImage_SetPixelColor(bm, x, y, &rgb); } void usage() { printf("Usage:\n./pathfind [OPTIONS] <input raw file> <output filename w/o extension>\n"); printf("Options may be:\n"); printf("\t-a: Minimum elevation (default: 0)\n"); printf("\t-b: Maximum elevation (default: 2700)\n"); printf("\t-s: Resolution of heightmap (default: 10)\n"); printf("\t-d: Density of grid points (default: 4)\n"); printf("\t-h: Heuristic scalar. Multiply h with this value. Set to 0 to run Dijkstra instead of A*.\n"); } int main(int argc, char** argv) { //Parse command line arguments string output_name = "default"; string input_name = "default"; string output_roadxml, output_ctrlpoints; //Terrain heights double h_min = 900; double h_max = 2550; //Terrain dimensions // int h = 768, w = h; int h = 1024, w = h; double spacing = 10.; int grid_density = 4; // k = neighborhood radius int k = 5; //timers double t_pathfind; static struct option long_options[] = { {"startx", required_argument, NULL, 1}, {"starty", required_argument, NULL, 2}, {"endx", required_argument, NULL, 3}, {"endy", required_argument, NULL, 4}, }; //Starting and ending points vec2i start(-1,-1),end(-1,-1); int c; while ((c = getopt_long(argc, argv, "a:b:s:d:x:y:h:", long_options, NULL)) != EOF) { switch (c) { case 1: start.x = atoi(optarg); break; case 2: start.y = atoi(optarg); break; case 3: end.x = atoi(optarg); break; case 4: end.y = atoi(optarg); break; case 'a': h_min = atof(optarg); break; case 'b': h_max = atof(optarg); break; case 'x': w = atoi(optarg); break; case 'y': h = atoi(optarg); break; case 's': spacing = atof(optarg); break; case 'd': grid_density = atoi(optarg); break; case 'h': heuristic_alpha = atof(optarg); break; default: usage(); exit(1); break; } } srand(time(0)); if (start.x < 0) start.x = 0; if (start.y < 0) start.y = 0; if (end.x < 0) end.x = w-1; if (end.y < 0) end.y = h-1; //Terrain storage unsigned short* terrain_raw = new unsigned short[h*w]; terrain_t terrain(h, w, spacing); // vec2i start(10, 750), end(400, 170); // vec2i start(10, 360), end(750, 10); // vec2i start(0, 0), end(4000, 4000); // vec2i end(70, 570), start(900, 24); // start = vec2i(128, 512); // end = vec2i(1024-128, 512); //Input and output filenames input_name = argv[optind], output_name = argv[optind+1]; //Read terrain ifstream input(input_name.c_str(), ios::binary); input.read((char*)terrain_raw, w*h*2); input.close(); //Map the integers from the terrain to an actual height for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int base = i*w+j; terrain.data[base] = ((double)terrain_raw[base]/65536.) * (h_max-h_min) + h_min; if (terrain.data[base] < h_min || terrain.data[base] > h_max) cout << terrain.data[base] << endl; } } t_pathfind = -getTime(); vector<vec2d> path = pathFind(terrain, start, end, grid_density, k); t_pathfind += getTime(); // vector<vec2d> path; // for (int i = 0; i < 5; i++) // path.push_back(vec2d(rand() % 10240, rand() % 10240)); // path.push_back(vec2d(1750,2750)); // path.push_back(vec2d(1750,4000)); // path.push_back(vec2d(3000,5000)); // path.push_back(vec2d(5000,5000)); // path.push_back(vec2d(5750,3500)); // path.push_back(vec2d(6500,4750)); ClothoidSpline clothoidSpline(path, 0.75); writeRoadXML(output_name + ".rnd", path, terrain); //Write the road file { ofstream f(output_name + ".rd"); f << output_name + ".obj\n"; for (size_t i = 0; i < path.size(); i++) { f << path[i].x << " " << path[i].y << "\n"; } f.close(); } FreeImage_Initialise(); FIBITMAP* bm = FreeImage_Allocate(w, h, 24); for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { int base = i*w+j; unsigned char color = (unsigned char)((double)terrain_raw[base] / 65536. * 256.); RGBQUAD rgb; rgb.rgbRed = rgb.rgbBlue = rgb.rgbGreen = color; FreeImage_SetPixelColor(bm, j, i, &rgb); } } // for (double t = 0; t < clothoidSpline.length(); t += 10) double tmin = 0, tmax = clothoidSpline.length(); for (double t = tmin; t < tmax; t += 5) { clothoid_point_t p = clothoidSpline.lookup(t); // printf("p %lf %lf %lf\n", p.pos.x, p.pos.y, clothoidSpline.length()); double color = 255; double red = 1; double green = 1; // double green = 1.-min(p.curvature*100.,1.); // double green = 1.-min(p.integrated_curvature*500,1.); double blue = 1; blue = green; setPixelColor(bm, int(p.pos.x/terrain.point_spacing), int(p.pos.y/terrain.point_spacing), color*red, color*green,color*blue); } //Find cost of curve double step = 1; double cost_road = clothoidSpline.length()*weight_road, cost_slope = 0, cost_curvature = 0; for (double t = tmin; t < tmax; t += step) { double t0 = max(t-step, tmin), t1 = t, t2 = min(t+step, tmax-1e-5); clothoid_point_t p0, p1, p2; p0 = clothoidSpline.lookup(t0); p1 = clothoidSpline.lookup(t1); p2 = clothoidSpline.lookup(t2); cost_curvature += weight_curvature*p1.curvature*(t2-t1); cost_slope += transfer_slope(terrain, p1.pos, p2.pos); // printf("%lf %lf %lf, %lf %lf\n", cost_slope, p1.pos.x, p1.pos.y, p2.pos.x, p2.pos.y); // printf("cost %lf\n", cost_total); //double cost(const terrain_t& terrain, const vec2d& a, const vec2d& v, const vec2d& b, const vec2d T0, bool first, bool last) } double cost_total = cost_road + cost_slope + cost_curvature; // printf("Total cost: %lf, Length of curve: %lf\n", cost_total, clothoidSpline.length()); // printf("Breakup of costs:\n\tLength:\t%lf\n\tSlope:\t%lf\n\tCurvature:\t%lf\n", cost_road, cost_slope, cost_curvature); for (size_t i = 0; i < path.size(); i++) { RGBQUAD rgb; rgb.rgbRed = rgb.rgbBlue = 0; rgb.rgbGreen = 255; FreeImage_SetPixelColor(bm, path[i].x/terrain.point_spacing, path[i].y/terrain.point_spacing, &rgb); } //Save image { // printf("Saving image %s...\n", (output_name + ".png").c_str()); FreeImage_Save(FIF_PNG, bm, (output_name + ".png").c_str()); } printf("%lf %lf\n", t_pathfind, cost_total); FreeImage_Unload(bm); FreeImage_DeInitialise(); delete[] terrain_raw; return 0; }
true
7441b3d079913cc47e6bee9511fd2f36229458a5
C++
seonyeong0215/Take-care-of-our-house
/blueinno/Temp_ble/Temp_ble.ino
UTF-8
633
2.765625
3
[]
no_license
#include <RFduinoBLE.h> const int TempPin = 2; boolean isConnect; void setup() { pinMode(TempPin, INPUT); RFduinoBLE.deviceName = "smartband"; Serial.begin(9600); Serial.println("Start Test"); RFduinoBLE.begin(); } void loop() { RFduino_ULPDelay(SECONDS(1)); if (isConnect) { int val = analogRead(TempPin); float temp = (3.0*val/1024.0)*100; Serial.println(temp); RFduinoBLE.sendFloat(temp); } } void RFduinoBLE_onConnect() { Serial.println("RFduino connected"); isConnect = true; } void RFduinoBLE_onDisconnect() { Serial.println("RFduino disconnected"); isConnect = false; }
true
180f264304e66ec5353995c11e2413f0511f8df0
C++
Tsuguri/EngineQ
/EngineQ/Source/EngineQCommon/Resources/Resource.hpp
UTF-8
4,678
2.921875
3
[]
no_license
#ifndef ENGINEQ_RESOURCES_RESOURCE_HPP #define ENGINEQ_RESOURCES_RESOURCE_HPP // Standard includes #include <memory> #include <stdexcept> namespace EngineQ { namespace Resources { class ResourceDestroyedException : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class BaseResource { public: class BaseControlBlock { private: int nativeReferenceCount = 0; int allReferenceCount = 0; public: BaseControlBlock() = default; virtual ~BaseControlBlock() = default; int GetNativeReferenceCount() const; int GetAllReferenceCount() const; static void AddNativeReference(BaseControlBlock* controlBlock); static void AddManagedReference(BaseControlBlock* controlBlock); static void RemoveNativeReference(BaseControlBlock*& controlBlock); static void RemoveManagedReference(BaseControlBlock*& controlBlock); bool IsResourceDestroyed() const; protected: virtual void DestroyData() = 0; virtual bool IsDataDestroyed() const = 0; }; protected: BaseControlBlock* controlBlock = nullptr; BaseResource(BaseControlBlock* controlBlock); public: BaseResource() = default; virtual ~BaseResource() = default; int GetAllReferenceCount() const; int GetNativeReferenceCount() const; int GetManagedReferenceCount() const; bool operator == (std::nullptr_t) const; bool operator != (std::nullptr_t) const; }; template<typename TResourceType> class Resource : public BaseResource { public: class ControlBlock : public BaseControlBlock { friend class ResourceManager; private: std::unique_ptr<TResourceType> data; public: ControlBlock() = default; virtual ~ControlBlock() { } ControlBlock(std::unique_ptr<TResourceType> resource) : BaseControlBlock{}, data{ std::move(resource) } { } virtual void DestroyData() override { this->data = nullptr; } virtual bool IsDataDestroyed() const override { return this->data == nullptr; } TResourceType* Get() const { return this->data.get(); } Resource<TResourceType> GetResource() { if (this->IsResourceDestroyed()) throw ResourceDestroyedException{ "Resource is destroyed" }; return Resource<TResourceType>{ this }; } }; private: Resource(ControlBlock* controlBlock) : BaseResource{ controlBlock } { BaseControlBlock::AddNativeReference(this->controlBlock); } public: explicit Resource(std::unique_ptr<TResourceType> resource) : BaseResource{ new ControlBlock{ std::move(resource) } } { BaseControlBlock::AddNativeReference(this->controlBlock); } Resource() : BaseResource{ nullptr } { } virtual ~Resource() { if (this->controlBlock != nullptr) BaseControlBlock::RemoveNativeReference(this->controlBlock); } Resource(std::nullptr_t) : BaseResource{ nullptr } { } Resource& operator = (std::nullptr_t) { if (this->controlBlock != nullptr) { BaseControlBlock::RemoveNativeReference(this->controlBlock); this->controlBlock = nullptr; } return *this; } Resource(const Resource& other) : BaseResource{ other.controlBlock } { if (this->controlBlock != nullptr) BaseControlBlock::AddNativeReference(this->controlBlock); } Resource& operator = (const Resource& other) { if (this->controlBlock == other.controlBlock) return *this; if (this->controlBlock != nullptr) BaseControlBlock::RemoveNativeReference(this->controlBlock); this->controlBlock = other.controlBlock; if (this->controlBlock != nullptr) BaseControlBlock::AddNativeReference(this->controlBlock); return *this; } Resource(Resource&& other) : BaseResource{ other.controlBlock } { other.controlBlock = nullptr; } Resource& operator = (Resource&& other) { auto tmp = this->controlBlock; this->controlBlock = other.controlBlock; other.controlBlock = tmp; return *this; } TResourceType* operator -> () const { return static_cast<ControlBlock*>(this->controlBlock)->Get(); } TResourceType& operator * () const { return *static_cast<ControlBlock*>(this->controlBlock)->Get(); } ControlBlock* GetControlBlock() const { return static_cast<ControlBlock*>(this->controlBlock); } operator TResourceType* () const { if (this->controlBlock == nullptr) return nullptr; return static_cast<ControlBlock*>(this->controlBlock)->Get(); } }; } } #endif // !ENGINEQ_RESOURCES_RESOURCE_HPP
true
e02a44c910f9f1fa90bd3b9d2396c6d7566a6952
C++
DariaTestOrganization/C-_Projects
/MyProject/MyCar.cpp
UTF-8
2,774
3.125
3
[]
no_license
#include "MyCar.h" MyCar::MyCar() { this->texture.loadFromFile("Texture/mycar.png"); this->sprite.setTexture(this->texture); movementSpeed = 5.f; this->hpMax = 100; this->hp = this->hpMax; this->coins = 0; this->fuelMax = 5000; this->fuel = this->fuelMax; } MyCar::~MyCar() { } MyCar::MyCar(const MyCar& car) { texture = car.texture; sprite = car.sprite; hp = car.hp; hpMax= car.hpMax; fuel=car.fuel; fuelMax = car.fuelMax; coins = car.coins; movementSpeed = car.movementSpeed; } MyCar::MyCar(MyCar&& car) noexcept { swap(texture, car.texture); swap(sprite, car.sprite); swap(hp, car.hp); swap(hpMax, car.hpMax); swap(fuel, car.fuel); swap(fuelMax, car.fuelMax); swap(coins, car.coins); swap(movementSpeed, car.movementSpeed); } MyCar& MyCar::operator=(const MyCar& car) { if(this == &car) return *this; texture = car.texture; sprite = car.sprite; hp = car.hp; hpMax = car.hpMax; fuel = car.fuel; fuelMax = car.fuelMax; coins = car.coins; movementSpeed = car.movementSpeed; return *this; } MyCar& MyCar::operator=(MyCar&& car) noexcept { if (this == &car) return *this; swap(texture, car.texture); swap(sprite, car.sprite); swap(hp, car.hp); swap(hpMax, car.hpMax); swap(fuel, car.fuel); swap(fuelMax, car.fuelMax); swap(coins, car.coins); swap(movementSpeed, car.movementSpeed); return *this; } const FloatRect MyCar::getBounds() const { return this->sprite.getGlobalBounds(); } const int MyCar::getHp() const { return hp; } const int MyCar::getHpMax() const { return hpMax; } const int MyCar::getFuel() const { return fuel; } const int MyCar::getFuelMax() const { return fuelMax; } const int MyCar::getCoins() const { return coins; } const Texture& MyCar::getTexture() const { return texture; } const Sprite& MyCar::getSprite() const { return sprite; } const float MyCar::getMovementSpeed() const { return movementSpeed; } void MyCar::setHp(const int a) { hp = a; } void MyCar::setFuel(const int a) { fuel = a; } void MyCar::setCoins(const int a) { coins = a; } void MyCar::setPosition(float x, float y) { this->sprite.setPosition(x,y); } void MyCar::setSavedParametrs(stringstream& ss) { ss >> hp; ss >> fuel; ss >> coins; } void MyCar::addHp(const int a) { hp += a; } void MyCar::decreaseHp(const int a) { hp -= a; } void MyCar::addFuel(const int a) { fuel += a; } void MyCar::addCoins(const int a) { coins += a; } void MyCar::move(const float dirX, const float dirY) { this->sprite.move(dirX*movementSpeed, dirY* movementSpeed); } void MyCar::update() { if (hp > hpMax) hp = hpMax; if (hp <0) hp = 0; if (fuel > fuelMax) fuel = fuelMax; if (fuel < 0) fuel = 0; fuel -= 0.00001; } void MyCar::render(RenderTarget* target) { target->draw(this->sprite); }
true
b24c1c3f2bdc51faf63226b3d20b3b8e5979a75c
C++
TALI-OSU/Video-Code
/C++Basics/IntroToVariables.cpp
UTF-8
622
3.53125
4
[]
no_license
/****************************************** * Program: C++ Basics (2) - Intro to Variables * Author: TALI OSU * Description: How to declare variables in a C++ program. * Video Link: * **************************************/ #include <iostream> using namespace std; int main() { int myIntVar; myIntVar = 3; float myFloatVar = 2.2; bool myBoolVar = true; char myCharVar = '8'; string myStringVar = "Hello there!"; cout << myIntVar << endl; cout << myFloatVar << endl; cout << myBoolVar << endl; cout << myCharVar << endl; cout << myStringVar << endl; return 0; }
true
53faf937306a7f926665eb14d8c5e6f91a06da99
C++
aipotsyd/circular_buffer
/circular_buffer/src/cb_test.cpp
UTF-8
7,142
3.421875
3
[ "MIT" ]
permissive
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include <limits> #include "circular_buffer.h" struct leak_checker { leak_checker(int value) : m_value{ value } { ++count; } static std::size_t count; leak_checker() { ++count; } ~leak_checker() { --count; } leak_checker(const leak_checker& lc) : m_value{ lc.m_value} { ++count; } leak_checker(leak_checker&& lc) = default; leak_checker& operator=(const leak_checker&) = default; leak_checker& operator=(leak_checker&&) = default; int value() { return m_value; } private: int m_value; }; std::size_t leak_checker::count = 0; TEST_CASE("Pushing and popping (allocating and deallocating)", "[circular_buffer]") { leak_checker::count = 0; SECTION("Construct with capacity") { auto cb = circular_buffer<leak_checker>(5); REQUIRE(cb.size() == 0); REQUIRE(cb.capacity() == 5); REQUIRE(cb.empty()); REQUIRE(cb.max_size() > 0); REQUIRE(leak_checker::count == 0); cb.push_back(1); REQUIRE(cb.size() == 1); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 1); REQUIRE(cb.back().value() == 1); REQUIRE(leak_checker::count == 1); cb.push_back(2); REQUIRE(cb.size() == 2); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 1); REQUIRE(cb.back().value() == 2); REQUIRE(leak_checker::count == 2); cb.push_back(3); cb.push_back(4); cb.push_back(5); REQUIRE(cb.size() == 5); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 1); REQUIRE(cb.back().value() == 5); REQUIRE(leak_checker::count == 5); cb.push_back(6); REQUIRE(cb.size() == 5); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 2); REQUIRE(cb.back().value() == 6); REQUIRE(leak_checker::count == 5); cb.pop_front(); REQUIRE(cb.size() == 4); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 3); REQUIRE(cb.back().value() == 6); REQUIRE(leak_checker::count == 4); cb.pop_front(); REQUIRE(cb.size() == 3); REQUIRE(cb.front().value() == 4); REQUIRE(cb.back().value() == 6); REQUIRE(leak_checker::count == 3); cb.pop_front(); REQUIRE(cb.size() == 2); REQUIRE(cb.front().value() == 5); REQUIRE(cb.back().value() == 6); REQUIRE(leak_checker::count == 2); cb.pop_front(); REQUIRE(cb.size() == 1); REQUIRE(cb.front().value() == 6); REQUIRE(cb.back().value() == 6); REQUIRE(leak_checker::count == 1); cb.pop_front(); REQUIRE(cb.size() == 0); REQUIRE(cb.capacity() == 5); REQUIRE(cb.empty()); REQUIRE(leak_checker::count == 0); cb.push_back(7); REQUIRE(cb.size() == 1); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 7); REQUIRE(cb.back().value() == 7); REQUIRE(leak_checker::count == 1); cb.push_back(8); cb.push_back(9); REQUIRE(cb.size() == 3); REQUIRE(cb.capacity() == 5); REQUIRE(!cb.empty()); REQUIRE(cb.front().value() == 7); REQUIRE(cb.back().value() == 9); REQUIRE(leak_checker::count == 3); cb.clear(); REQUIRE(cb.size() == 0); REQUIRE(cb.capacity() == 5); REQUIRE(cb.empty()); REQUIRE(leak_checker::count == 0); } SECTION("Check empty construction does not allocate members") { REQUIRE(leak_checker::count == 0); circular_buffer<leak_checker> cb(5); REQUIRE(leak_checker::count == 0); } } TEST_CASE("Indexing", "[circular_buffer]") { auto cb = circular_buffer<int>(5); for (int i = 0; i < 10; ++i) { REQUIRE(cb.empty()); //const auto &const_cb = cb; const circular_buffer<int> &const_cb(cb); REQUIRE_THROWS_AS(cb.at(0), std::out_of_range); REQUIRE_THROWS_AS(cb.at(1), std::out_of_range); REQUIRE_THROWS_AS(const_cb.at(0), std::out_of_range); REQUIRE_THROWS_AS(const_cb.at(1), std::out_of_range); REQUIRE(cb.push_back(0)); REQUIRE(cb.push_back(1)); REQUIRE(cb.push_back(2)); REQUIRE(cb.at(0) == 0); REQUIRE(cb.at(1) == 1); REQUIRE(cb.at(2) == 2); REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 1); REQUIRE(cb[2] == 2); REQUIRE(const_cb.at(0) == 0); REQUIRE(const_cb.at(1) == 1); REQUIRE(const_cb.at(2) == 2); REQUIRE(const_cb[0] == 0); REQUIRE(const_cb[1] == 1); REQUIRE(const_cb[2] == 2); REQUIRE(cb.front() == 0); cb[0] = 3; REQUIRE(cb.front() == 3); REQUIRE(cb.at(0) == 3); REQUIRE(cb.at(1) == 1); REQUIRE(cb.at(2) == 2); REQUIRE(cb[0] == 3); REQUIRE(cb[1] == 1); REQUIRE(cb[2] == 2); REQUIRE(const_cb.at(0) == 3); REQUIRE(const_cb.at(1) == 1); REQUIRE(const_cb.at(2) == 2); REQUIRE(const_cb[0] == 3); REQUIRE(const_cb[1] == 1); REQUIRE(const_cb[2] == 2); cb[1] = 4; REQUIRE(cb.at(0) == 3); REQUIRE(cb.at(1) == 4); REQUIRE(cb.at(2) == 2); REQUIRE(cb[0] == 3); REQUIRE(cb[1] == 4); REQUIRE(cb[2] == 2); REQUIRE(const_cb.at(0) == 3); REQUIRE(const_cb.at(1) == 4); REQUIRE(const_cb.at(2) == 2); REQUIRE(const_cb[0] == 3); REQUIRE(const_cb[1] == 4); REQUIRE(const_cb[2] == 2); cb.pop_front(); REQUIRE(cb.at(0) == 4); REQUIRE(cb.at(1) == 2); REQUIRE(cb[0] == 4); REQUIRE(cb[1] == 2); REQUIRE(const_cb.at(0) == 4); REQUIRE(const_cb.at(1) == 2); REQUIRE(const_cb[0] == 4); REQUIRE(const_cb[1] == 2); cb.pop_front(); REQUIRE(cb.at(0) == 2); REQUIRE(cb[0] == 2); REQUIRE(const_cb.at(0) == 2); REQUIRE(const_cb[0] == 2); cb.pop_front(); } } TEST_CASE("Using Iterators", "[circular_buffer]") { auto cb = circular_buffer<int>(5); cb.push_back(0); cb.push_back(1); cb.push_back(2); REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 1); REQUIRE(cb[2] == 2); SECTION("Range-based for loop") { for (auto& i : cb) { i *= 10; } REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 10); REQUIRE(cb[2] == 20); } SECTION("Raw for loop with iterators (pre-increment") { for (auto i = cb.begin(); i != cb.end(); ++i) { *i *= 10; } REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 10); REQUIRE(cb[2] == 20); } SECTION("Raw for loop with iterators (post-increment") { for (auto i = cb.begin(); i != cb.end(); i++) { *i *= 10; } REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 10); REQUIRE(cb[2] == 20); } SECTION("Raw for loop with reverse iterators (pre-increment") { for (auto i = cb.rbegin(); i != cb.rend(); ++i) { *i *= 10; } REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 10); REQUIRE(cb[2] == 20); } SECTION("Raw for loop with reverse iterators (post-increment") { for (auto i = cb.rbegin(); i != cb.rend(); i++) { *i *= 10; } REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 10); REQUIRE(cb[2] == 20); } SECTION("Copy with iterators") { auto dest = circular_buffer<int>(5); dest.push_back(1); std::copy(cb.begin(), cb.end(), dest.begin()); REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 1); REQUIRE(cb[2] == 2); REQUIRE(dest[0] == 0); REQUIRE(dest[1] == 1); REQUIRE(dest[2] == 2); } SECTION("Copy with reverse iterators") { auto dest = circular_buffer<int>(5); dest.push_back(1); std::copy(cb.rbegin(), cb.rend(), dest.begin()); REQUIRE(cb[0] == 0); REQUIRE(cb[1] == 1); REQUIRE(cb[2] == 2); REQUIRE(dest[0] == 2); REQUIRE(dest[1] == 1); REQUIRE(dest[2] == 0); } }
true
6931a544d0b7cdcd5663b67e3a637a8fc7540989
C++
nikluep/genetic-evo
/GeneticEvolution/Optimizer.h
UTF-8
1,081
3.015625
3
[ "MIT" ]
permissive
#pragma once #include <vector> #include <chrono> #include "DroneController.h" class Optimizer { public: /** Create an optimizer for a set of controller. \param controllers DroneController to optimize \param generationTarget Number of generations to train for */ explicit Optimizer(std::vector<DroneController>& controllers, unsigned generationTarget) noexcept; /** Start the optimization process. */ void start(); /** Check progress of current generation. \returns Signals if the current generation is complete and a next one started */ bool doGenerationStep(); /** Select best performing controllers, replicate/transform them and kill of the others. */ void evolve(); /** Signals if the generation target has been hit. \returns True if current generation < generation target */ bool isTraining() const { return m_generation < m_generationTarget; }; private: std::vector<DroneController>& m_controllers; unsigned m_generation; const unsigned m_generationTarget; std::chrono::time_point<std::chrono::system_clock> m_generationStart; };
true
1653428d3a134ab5cade5ae604548c838e49a8f9
C++
colorbox/AtCoderLog
/abc/040/d.cpp
UTF-8
1,836
2.734375
3
[]
no_license
#include<bits/stdc++.h> #define rep(i,n) for(int i = 0; i < (n); i++) #define ll long long using namespace std; bool compare_by_second(pair<int, int> a, pair<int, int> b) { return a.second < b.second; } bool compare_by_second2(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) { return a.second < b.second; } struct UnionFind { vector<int> data; UnionFind(int size) : data(size, -1) { } bool unionSet(int x, int y) { x = root(x); y = root(y); if (x != y) { if (data[y] < data[x]) swap(x, y); data[x] += data[y]; data[y] = x; } return x != y; } bool findSet(int x, int y) { return root(x) == root(y); } int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); } int size(int x) { return -data[root(x)]; } }; int print_queue(queue<int> q){ while (!q.empty()){ cout << q.front()+1 << " "; q.pop(); } return 0; } vector< pair<pair<int, int>, int> > roads; int main(){ int n,m;cin>>n>>m; rep(i,m){ int a,b,y;cin>>a>>b>>y;a--;b--; auto p = make_pair(a,b); roads.push_back(make_pair(p, y)); } int q;cin>>q; vector<pair<int, int>> people; rep(i,q){ int v,w;cin>>v>>w;v--; people.emplace_back(v, w); } vector<pair<int, int>> p(people); sort(people.rbegin(), people.rend(), compare_by_second); sort(roads.rbegin(), roads.rend(), compare_by_second2); struct UnionFind uf(n); map<pair<int,int>,int>logger; int road_i=0; int yc=people[0].second; rep(i,q){ int oldest = people[i].second; int current_city = people[i].first; while(oldest < roads[road_i].second){ uf.unionSet(roads[road_i].first.first, roads[road_i].first.second); road_i++; } logger[people[i]]=uf.size(current_city); } rep(i,p.size()){ cout<<logger[p[i]]<<endl; } return 0; }
true
5fd6c394064e680279d2dab8d12b0d1776287c6e
C++
sayantikag98/Current_Data_Structures_and_Algorithms
/DSA_codes_in_cpp/Interview_Prep/Course_01_Basic_concepts_of_programming/Lec1_concepts_of_arrays_and_other_datatypes/mountain_view.cpp
UTF-8
1,164
3.15625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void func_alt(int* arr, int n){ int i = 0; while(i<n-1 and arr[i]<arr[i+1]){ i++; } if(i==0 or i ==n){ cout<<"False\n"; return; } while(i<n-1 and arr[i]>arr[i+1]){ i++; } if(i==n-1){ cout<<"True\n"; } else{ cout<<"False\n"; } } void func(int* arr, int n){ if(n<3){ cout<<"False"<<endl; return; } bool flag = 0, ans = 0; for(int i = 0; i<n-1; i++){ int left = i, right = i+1; if(arr[left]<arr[right]){ if(flag == 0){ flag = 0; } else if (flag != 0){ ans = 1; break; } } else if(left!= 0 and arr[left]>arr[left-1] and arr[left]>arr[right]){ flag = 1; } else if(right != n-1 and arr[right]<arr[left] and arr[right]>arr[right+1] ){ flag = 1; } else if(arr[left] == arr[right]){ ans = 1; break; } else if(arr[left] > arr[right]){ if(flag == 1){ flag = 1; } else if(flag != 1){ ans = 1; break; } } } if(ans == 1){ cout<<"False"<<endl; } else{ cout<<"True"<<endl; } } int main(){ int n; cin>>n; int* arr = new int [n]; for(int i = 0; i<n; i++){ cin>>arr[i]; } func_alt(arr, n); }
true
254d6c8f443caec77d2ab833ae5636268aa7cec0
C++
youmych/bomberman
/src/SpeedPowerUp.h
UTF-8
296
2.78125
3
[ "MIT" ]
permissive
#pragma once #include "PowerUp.h" /*! * Powerup that increases bombermans speed. */ class SpeedPowerUp : public PowerUp { public: /*! * Creates the powerup at the specified coordinates. */ SpeedPowerUp(int initialX, int initialY); protected: void applyEffects(Game* game) override; };
true
dc23bda70e777a3852307003a70c2c567f62db1d
C++
yull2310/book-code
/www.cplusplus.com-20180131/reference/locale/locale/combine/combine.cpp
UTF-8
392
3.40625
3
[]
no_license
// locale::combine example #include <iostream> // std::cout #include <locale> // std::locale, std::num_put int main () { std::locale loc(""); // initialized to environment's locale // combine loc with the "C" locale for num_put loc = loc.combine< std::num_put<char> > (std::locale::classic()); std::cout.imbue(loc); std::cout << 3.14159 << '\n'; return 0; }
true
de8748a072d46da2182b2525126c180ff8294f82
C++
20191844319/G41
/c5/5章16题/5 16.cpp
UTF-8
386
2.53125
3
[]
no_license
// 5 16.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main(int argc, char* argv[]) {int i,m,n; for(i=1;i<=4;i++) { for(m=1;m<=4-i;m++) {printf(" "); } for(n=1;n<=2*i-1;n++) { printf("*"); } printf("\n"); } for(i=1;i<=3;i++) { for(n=1;n<=i;n++) { printf(" "); } for(m=1;m<=7-2*i;m++) { printf("*"); } printf("\n"); } return 0; }
true
4cb8d8bfd0c9d5a6dc53bf7df9b157235d2b137e
C++
Mattishh/AlienInvaders
/Main.cpp
UTF-8
7,290
2.625
3
[]
no_license
#include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <iostream> #include <string> #include "Player.h" #include "Entity.h" #include "Enemy.h" #include "Bullet.h" #include "UI.h" #include <vector> using namespace std; int main() { //Variables int windowX = 640; int windowY = 960; float bulletTimer = 0; float reloadTime = 0.50; float enemyTimer = 0; float enemySpawnRate = 2.2; float enemyReloadTime = 0.50; float enemyBulletTimer = 0; string stringLives; //Fonts & text sf::Font thin; sf::Font regular; if (!thin.loadFromFile("assets/kenvector_future_thin.ttf")) { std::cout << "Thin font loading error"; } if (!regular.loadFromFile("assets/kenvector_future.ttf")) { std::cout << "Regular font loading error"; } sf::Text Lives; sf::Text Score; sf::Text gameOver; Score.setCharacterSize(25); Lives.setCharacterSize(25); Lives.setFont(regular); Score.setFont(thin); gameOver.setFont(regular); Lives.setPosition(sf::Vector2f(90, 20)); Score.setPosition(sf::Vector2f(400, 20)); gameOver.setString("Game Over"); gameOver.setCharacterSize(50); gameOver.setPosition(150, 500); //Sprites sf::Sprite background; background.setTextureRect(sf::IntRect(0, 0, windowX, windowY)); //Textures sf::Texture uiX; sf::Texture uiLives; sf::Texture enemyTexture; sf::Texture playerBulletTexture; sf::Texture enemyBulletTexture; sf::Texture playerTexture; sf::Texture backgroundTexture; backgroundTexture.setRepeated(true); if (!uiX.loadFromFile("assets/numeralX.png")) { std::cout << "Error loading numeralX from file" << std::endl; } if (!uiLives.loadFromFile("assets/player_life.png")) { std::cout << "Error loading player_life from file" << std::endl; } if (!backgroundTexture.loadFromFile("assets/background.png")) { std::cout << "Error loading background from file" << std::endl; } background.setTexture(backgroundTexture); if (!playerTexture.loadFromFile("assets/player.png")) { std::cout << "Error loading player from file" << std::endl; } if (!enemyTexture.loadFromFile("assets/enemy.png")) { std::cout << "Error loading enemy from file" << std::endl; } if (!playerBulletTexture.loadFromFile("assets/bullet_player.png")) { std::cout << "Error loading player bullet from file" << std::endl; } if (!enemyBulletTexture.loadFromFile("assets/bullet_enemy.png")) { std::cout << "Error loading enemy bullet from file" << std::endl; } //Vectors vector<Enemy>::const_iterator enemyIterate; vector<Enemy> enemyVector; vector<Bullet> bulletVector; //Objects Player player; player.sprite.setTexture(playerTexture); Bullet bullet; bullet.sprite.setTexture(playerBulletTexture); Enemy enemy; enemy.sprite.setTexture(enemyTexture); UI ui; ui.uiLives.setTexture(uiLives); ui.uiX.setTexture(uiX); ui.uiLives.setPosition(sf::Vector2f(25, 25)); ui.uiX.setPosition(sf::Vector2f(65, 30)); //Stuff sf::Clock clock; sf::Time time; sf::RenderWindow window(sf::VideoMode(windowX, windowY), "Alien Invaders"); while (window.isOpen()) { sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } if (ui.playerLives <= 0 && sf::Keyboard::isKeyPressed(sf::Keyboard::Return)) { player.isKilled = false; bulletVector.clear(); enemyVector.clear(); player.rect.setPosition(sf::Vector2f(255, 875)); ui.playerLives = 10; ui.score = 0; } //Player movement player.UpdatePlayer(time.asSeconds()); //Enemy spawning and spawn timer management enemyTimer += time.asSeconds(); if (enemyTimer >= enemySpawnRate) { enemy.rect.setPosition(rand() % 549, 0); enemyVector.push_back(enemy); enemyTimer = 0; } //Player bullet shooting and reload timer management bulletTimer += time.asSeconds(); if (bulletTimer >= reloadTime && sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && ui.playerLives > 0) { bullet.sprite.setTexture(playerBulletTexture); bullet.friendly = true; bullet.rect.setPosition(player.rect.getPosition().x + 51, player.rect.getPosition().y); bulletVector.push_back(bullet); bulletTimer = 0; } //Start drawing and managing bullets and enemies window.clear(); window.draw(background); for (int i = bulletVector.size() - 1; i >= 0; i--) { if (bulletVector[i].rect.getPosition().y > 960 + 100) { bulletVector.erase(bulletVector.begin() + i); } else if (bulletVector[i].rect.getPosition().y < 0 - 100) { bulletVector.erase(bulletVector.begin() + i); } else { bulletVector[i].UpdateBullet(time.asSeconds()); window.draw(bulletVector[i].sprite); } } enemyBulletTimer += time.asSeconds(); for (int i = enemyVector.size() - 1; i >= 0; i--) { if (enemyVector[i].rect.getPosition().y > 960 + 100) { enemyVector.erase(enemyVector.begin() + i); } else if (enemyVector[i].rect.getPosition().y < 0 - 100) { enemyVector.erase(enemyVector.begin() + i); } else if (enemyVector[i].isKilled == true) { enemyVector.erase(enemyVector.begin() + i); } else { if (enemyBulletTimer >= enemyReloadTime) { bullet.sprite.setTexture(enemyBulletTexture); bullet.friendly = false; bullet.rect.setPosition(enemyVector[i].rect.getPosition().x + 45, enemyVector[i].rect.getPosition().y + 91); bulletVector.push_back(bullet); enemyBulletTimer = 0; } enemyVector[i].UpdateEnemy(time.asSeconds()); window.draw(enemyVector[i].sprite); } } //Collisions for (int i = bulletVector.size() - 1; i >= 0; i--) { if (bulletVector[i].friendly == true) { for (int y = enemyVector.size() - 1; y >= 0; y--) { if (enemyVector[y].rect.getGlobalBounds().intersects(bulletVector[i].rect.getGlobalBounds())) { bulletVector[i].isKilled = true; enemyVector[y].isKilled = true; } } } if (bulletVector[i].friendly == false) { if (bulletVector[i].rect.getGlobalBounds().intersects(player.rect.getGlobalBounds())) { if (ui.playerLives > 0) { bulletVector[i].isKilled = true; player.isKilled = true; } } } } for (int i = enemyVector.size() - 1; i >= 0; i--) { if (enemyVector[i].rect.getGlobalBounds().intersects(player.rect.getGlobalBounds())) { if (ui.playerLives > 0) { player.isKilled = true; enemyVector[i].isKilled = true; } } } //Kill enemies for (int i = enemyVector.size() - 1; i >= 0; i--) { if (enemyVector[i].isKilled == true) { ui.score += 10; enemyVector.erase(enemyVector.begin() + i); } } //Kill bullets for (int i = bulletVector.size() - 1; i >= 0; i--) { if (bulletVector[i].isKilled == true) { bulletVector.erase(bulletVector.begin() + i); } } //Damage player if (player.isKilled == true && ui.playerLives > 0) { ui.playerLives -= 1; player.isKilled = false; } Score.setString("Score: "+ to_string(ui.score)); Lives.setString(to_string(ui.playerLives)); if (ui.playerLives > 0) { window.draw(player.sprite); } if (ui.playerLives <= 0) { window.draw(gameOver); } window.draw(ui.uiX); window.draw(ui.uiLives); window.draw(Lives); window.draw(Score); window.display(); time = clock.restart(); } return 0; }
true
b029b58731f7b76af75c10a921aa059a0cf9c35a
C++
vincentrolypoly/Malice
/Front-End-Compiler/Nodes/numberASTNode.cpp
UTF-8
604
2.8125
3
[]
no_license
#include "numberASTNode.hpp" #include "intTypeNode.hpp" #include "../checkInterface.hpp" #include <iostream> numberASTNode::numberASTNode(int val) { value = val; type = new intTypeNode(); } void numberASTNode::accept(CheckInterface *c, SymbolTable *currentST) { c->check(this,currentST); } void numberASTNode::destroyAST() { type->destroyAST(); delete type; } void numberASTNode::printVal() { std::cout<<value; } int numberASTNode::getValue() { return value; } typeNode* numberASTNode::getType() { return type; } int numberASTNode::weight(){ return 1; }
true
1a72fdd4487e05bdc166d33a5df9b7e86df0caae
C++
yhnnd/wego-c-tutorial
/resources/code/day-17-2.cpp
UTF-8
216
2.53125
3
[]
no_license
#include <stdio.h> int main() { int a, b; for (a = 1; a < 26; ++a) { for (b = 1; b < 26; ++b) { if (a * b % 26 == 1) { printf("%2d ??? %2d,\t%2d ????????\n", a, b, a); break; } } } return 0; }
true
0f3e9a93b40b5f75dd5621ec5de7edde2484496b
C++
dream0630/piscine_cpp_d07
/ex06/Toy.h
UTF-8
1,083
2.75
3
[]
no_license
#ifndef TOY_HPP #define TOY_HPP #include <string> #include <iostream> #include "Picture.h" class Toy { public: enum ToyType { BASIC_TOY, ALIEN, BUZZ, WOODY }; class Error { public: enum ErrorType { UNKNOWN, PICTURE, SPEAK }; ErrorType type; Error(); void setType(ErrorType type); std::string what() const; std::string where() const; }; protected: ToyType type; std::string name; Picture picture; Error error; int spanish = 0; public: Toy(); Toy(ToyType type, std::string const &name, std::string const &file); Toy(Toy const &toy); virtual ~Toy(); std::string const &getName() const; int getType() const; std::string const &getAscii() const; void setName(std::string const &name); bool setAscii(std::string const &ascii); virtual bool speak(std::string const message); virtual bool speak_es(std::string const message); Toy::Error const &getLastError() const; Toy &operator=(Toy const &toy); Toy &operator<<(std::string const & ascii); }; std::ostream &operator<<(std::ostream & os, Toy const & toy); #endif /* dream0630 */
true
6b3cb5354982f6d6a82e82c401a6e87e2885a017
C++
superTangcc/toc-collaborate
/Pochoir/RMQ/wordSA/sa_for_ints_larsson.cpp
UTF-8
4,192
2.9375
3
[]
no_license
#include "sa_for_ints_larsson.hpp" /* Implementiert die SA-Konstruktion von Larsson/Sadakane. * Alphabet must be in the range from 1 to k with no holes. * String 'text' *must* be 0-terminated! * text: text for which suffix array is to be constructed * length: length of text (including 0-termination) * k: # of different symbols in text (incl. final '0') * p: array of size length which holds SA afterwards */ void SAforIntsLarsson::construct(int* text, int length, int k, int* p) { int i, l; int c, cc, ncc, lab, cum, nbuck; int result = -1; int *al; int *pl; nbuck = 0; pl = p + length - k; al = text; memset(pl, -1, k*sizeof(int)); for(i=0; i<length; i++) { /* (1) link */ l = text[i]; al[i] = pl[l]; pl[l] = i; } lab = 0; /* (2) create p and label a */ cum = 0; i = 0; for(c = 0; c < k; c++){ for(cc = pl[c]; cc != -1; cc = ncc){ ncc = al[cc]; al[cc] = lab; cum++; p[i++] = cc; } if(lab + 1 == cum) { i--; } else { p[i-1] |= BUCK; nbuck++; } lab = cum; } result = ssortit(text, p, length, 1, p+i, nbuck); } int SAforIntsLarsson::ssortit(int a[], int p[], int n, int h, int *pe, int nbuck) { #define succ(i, h) ((t=(i)+(h))>=n? t-n: t) int *s, *ss, *packing, *sorting; int v, sv, vv, packed, lab, t, i; for(; h < n && p < pe; h=2*h) { packing = p; nbuck = 0; for(sorting = p; sorting < pe; sorting = s){ /* * find length of stuff to sort */ lab = a[*sorting]; for(s = sorting; ; s++) { sv = *s; v = a[succ(sv & ~BUCK, h)]; if(v & BUCK) v = lab; a[sv & ~BUCK] = v | BUCK; if(sv & BUCK) break; } *s++ &= ~BUCK; nbuck++; qsort2(sorting, a, s - sorting); v = a[*sorting]; a[*sorting] = lab; packed = 0; for(ss = sorting + 1; ss < s; ss++) { sv = *ss; vv = a[sv]; if(vv == v) { *packing++ = ss[-1]; packed++; } else { if(packed) { *packing++ = ss[-1] | BUCK; } lab += packed + 1; packed = 0; v = vv; } a[sv] = lab; } if(packed) { *packing++ = ss[-1] | BUCK; } } pe = packing; } /* * reconstuct the permutation matrix * return index of the entire string */ v = a[0]; for(i = 0; i < n; i++) p[a[i]] = i; return v; } /* * qsort from Bentley and McIlroy, Software--Practice and Experience 23 (1993) 1249-1265, specialized for sorting permutations based on successors */ void SAforIntsLarsson::vecswap2(int *a, int *b, int n) { while (n-- > 0) { int t = *a; *a++ = *b; *b++ = t; } } #define swap2(a, b) { t = *(a); *(a) = *(b); *(b) = t; } int* SAforIntsLarsson::med3(int *a, int *b, int *c, int *asucc) { int va, vb, vc; if ((va=asucc[*a]) == (vb=asucc[*b])) return a; if ((vc=asucc[*c]) == va || vc == vb) return c; return va < vb ? (vb < vc ? b : (va < vc ? c : a)) : (vb > vc ? b : (va < vc ? a : c)); } void SAforIntsLarsson::inssort(int *a, int *asucc, int n) { int *pi, *pj, t; for (pi = a + 1; --n > 0; pi++) for (pj = pi; pj > a; pj--) { if(asucc[pj[-1]] <= asucc[*pj]) break; swap2(pj, pj-1); } } void SAforIntsLarsson::qsort2(int *a, int *asucc, int n) { int d, r, partval; int *pa, *pb, *pc, *pd, *pl, *pm, *pn, t; if (n < 15) { inssort(a, asucc, n); return; } pl = a; pm = a + (n >> 1); pn = a + (n-1); if (n > 30) { /* On big arrays, pseudomedian of 9 */ d = (n >> 3); pl = med3(pl, pl+d, pl+2*d, asucc); pm = med3(pm-d, pm, pm+d, asucc); pn = med3(pn-2*d, pn-d, pn, asucc); } pm = med3(pl, pm, pn, asucc); swap2(a, pm); partval = asucc[*a]; pa = pb = a + 1; pc = pd = a + n-1; for (;;) { while (pb <= pc && (r = asucc[*pb]-partval) <= 0) { if (r == 0) { swap2(pa, pb); pa++; } pb++; } while (pb <= pc && (r = asucc[*pc]-partval) >= 0) { if (r == 0) { swap2(pc, pd); pd--; } pc--; } if (pb > pc) break; swap2(pb, pc); pb++; pc--; } pn = a + n; r = pa-a; if(pb-pa < r) r = pb-pa; vecswap2(a, pb-r, r); r = pn-pd-1; if(pd-pc < r) r = pd-pc; vecswap2(pb, pn-r, r); if ((r = pb-pa) > 1) qsort2(a, asucc, r); if ((r = pd-pc) > 1) qsort2(a + n-r, asucc, r); }
true
ec769f0aa112f140cb81472b90a8b6edb0a9dbb0
C++
WULEI7/WULEI7
/ACM俱乐部/大一下学期训练/第10周周赛/C 数字最大个数.cpp
UTF-8
303
2.59375
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; int main() { int n,a[100]; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; sort(a,a+n); int ans=1,temp=1; for(int i=1;i<n;i++) { if(a[i]==a[i-1]) temp++; else temp=1; if(temp>ans) ans=temp; } cout<<ans<<endl; return 0; }
true