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
404f0a966aac255c71b9515cc22617a847d067e8
C++
jtpunt/c-and-c-plus-plus
/Algorithms/StoogeSort/main.cpp
UTF-8
3,789
3.71875
4
[]
no_license
/********************************************************************* ** Author: Jonathan Perry ** Date: 1/21/2018 ** Description: This file contains code for reading data for 3 vectors ** from a text file, code writing the content of those 3 vectors to a file ** called "stooge.out", code printing the contents of the vector to the ** console, and code for generating set amount of random numbers and storing ** each number in a single vector. *********************************************************************/ #include "StoogeSort.hpp" #include <iostream> #include <fstream> #include <stdlib.h> #include <time.h> using std::vector; using std::ifstream; using std::ofstream; using std::string; using std::cout; using std::endl; // Prints all the contents of the vector to the console void printVector(vector <int> v){ for (unsigned int i = 0; i < v.size(); i++) { cout << v[i] << " "; } cout << endl; } // Takes in 3 vectors and fills them with data from a specified file name void readFile(string fileName, vector <int> &v1, vector <int> &v2, vector <int> &v3){ ifstream ioFile; bool firstNumber = true; bool firstArray = true; bool secondArray = false; int integer, arr_size, numsRead = 0; ioFile.open(fileName.c_str()); if (ioFile.fail()) cout << "The file failed to open: " << endl; else{ while (ioFile >> integer){ // firstNumber in the text file indicates the size of the array to be read in if(firstNumber){ arr_size = integer; cout << "size of array: " << integer << endl; cout << "contents of array: " << endl; firstNumber = false; } else if(numsRead < arr_size){ cout << integer << " "; if(firstArray) v1.push_back(integer); else if(secondArray) v2.push_back(integer); else v3.push_back(integer); numsRead++; if(numsRead == arr_size){ firstNumber = true; // set to true to read integer in for the second array if(firstArray){ firstArray = false; // set to false to push integers into the second array secondArray = true; } else if(secondArray){ secondArray = false; } numsRead = 0; cout << endl << endl; } } } } ioFile.close(); // Close the file } // Takes in 3 vectors and writes each of their content to a specified file name void writeFile(string filename, vector <int> v1, vector <int> v2, vector <int> v3){ ofstream myFile; myFile.open(filename.c_str()); if(myFile.fail()){ cout << "The file failed to open: " << endl; }else{ for(int i = 0; i < v1.size(); i++){ myFile << v1[i] << " "; } myFile << "\n"; for(int i = 0; i < v2.size(); i++){ myFile << v2[i] << " "; } myFile << "\n"; for(int i = 0; i < v3.size(); i++){ myFile << v3[i] << " "; } myFile << "\n"; } myFile.close(); } // Generates an (size) amount of random numbers between 1-10000 and stores them in the vector that was sent in void generateNumbers(vector <int> &v, int size){ srand((unsigned)time(NULL)); for(int i = 0; i < size; i ++){ // generate a random # between 1-10000 and store it in the vector v.push_back(rand() % 10000 + 1); } } int main(){ // vector <int> v; // generateNumbers(v, 10000); // clock_t timer = clock(); // StoogeSort(v, 0, v.size()- 1); // timer = clock() - timer; // cout << "StoogeSort took " << (float)timer / (float)CLOCKS_PER_SEC << " seconds."; vector <int> v1, v2, v3; readFile("data.txt", v1, v2, v3); cout << "Running StoogeSort on first vector" << endl; StoogeSort(v1, 0, v1.size() - 1); printVector(v1); cout << "Running StoogeSort on first vector" << endl; StoogeSort(v2, 0, v2.size() - 1); printVector(v2); cout << "Running StoogeSort on first vector" << endl; StoogeSort(v3, 0, v3.size() - 1); printVector(v3); writeFile("stooge.out", v1, v2, v3); return 0; }
true
d6aa4b4aed2470975cc97e991ac91dee7d392fc2
C++
caryleo/EImC
/EImC/ModeRead.cpp
GB18030
2,652
3.03125
3
[]
no_license
#include"stdafx.h" #include "ModeRead.h" #include "ModeErrorReport.h" ModeRead::ModeRead()//ʼ { lineLen = 0; readPos = -1; lineNum = 0; colNum = 0; file = NULL; lastch = '\0'; memset(filePathName, '\0', sizeof(filePathName)); } int ModeRead::getLine() { return lineNum; } int ModeRead::getCol() { return colNum; } char ModeRead::scan() { //ȡַ if (readType == 1) { if (readPos + 1 < in_content.size()) { ++readPos; if(lastch=='\n'){ // lineNum++; //кۼ colNum=0;//к } else colNum++; lastch=in_content[readPos]; return in_content[readPos]; } else return -1; } if (readType == 2) { if (!file) { //ûļ return -1; } if (readPos == lineLen - 1) { //ȡ lineLen = fread(line, 1, BUFLEN, file); //¼ػ if (lineLen == 0) { //û lineLen = 1; //ݳΪ1 line[0] = -1; //ļ } readPos = -1; //ָȡλ } readPos++; //ƶȡ char ch = line[readPos]; //ȡµַ if (lastch == '\n') { // lineNum++; //кۼ colNum = 0;//к } if (ch == -1) { //ļԶر fclose(file); file = NULL; } else if (ch == '\n') colNum++; //ǻУкŵ lastch = ch; //¼һַ return ch; //ַ } } int ModeRead::readMode() { cout << "ѡļ뷽ʽ" << endl; cout << "1.ֱ 2.ļ" << endl; cin >> readType; if (readType == 1)//ֱ { cout << "" << endl; char in_char; while (cin.get(in_char)) { if(in_char=='@') return 0; else in_content.push_back(in_char); } //output(); return 0; } else if (readType == 2)//ļ { cout << "ļ·" << endl; cin >> filePathName; file = fopen(filePathName, "r"); if (!file) { ModeErrorReport EMR(100, 0, 0); EMR.report(); return -1; } else { string line; ifstream in_file(filePathName); while (getline(in_file, line)) { cout << line << endl; } return 0; } } } /*鿴in_contentݣֶ룩 void ModeRead::output() { int m=0; while(m<in_content.size()) { cout<<in_content[m]; m++; } } */ /* int main() { ModeRead a; int m=a.readMode(); for(int i=0;i<5;i++) cout<<a.scan()<<endl; if(m==-1) { cout<<""<<endl; return -1; } return 0; } */
true
45757b351fa9e42052ca61b47e9e15d0cc38a590
C++
pytseng/etch-a-sketch
/sensorCode/sensorCode.ino
UTF-8
1,973
2.71875
3
[]
no_license
//#define SENSORPINA A0 // x axis #define verticalPin A0 #define horizontalPin A1 #include <Adafruit_LSM303_U.h> #include <Adafruit_LSM303.h> int accelRead=0; String vertical = ""; String horizontal = ""; String dataString = ""; unsigned long targetTime=0; const unsigned long interval=2500; //TODO: How fast should we read Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321); void setup(){ #ifndef ESP8266 while (!Serial); // will pause Zero, Leonardo, etc until serial console opens #endif Serial.begin(115200); Serial.println("Accelerometer Test"); Serial.println(""); /* Initialise the sensor */ if(!accel.begin()) { /* There was a problem detecting the ADXL345 ... check your connections */ Serial.println("Ooops, no LSM303 detected ... Check your wiring!"); while(1); } // TODO: begin the serial connection with a baudrate of 115200 } void shakeErase() // Use Accelerometer to clear the drawing. { sensors_event_t event; accel.getEvent(&event); accelRead = event.acceleration.y; // Serial.print(accelRead); if(abs(accelRead) > 5) Serial.println("rst"); //This is where the clear function will be triggered } void loop(){ if(millis()>=targetTime){ targetTime= millis()+interval; // Serial.println(analogRead(SENSORPINA)); //TODO: Add other sensor read outs //TODO: convert values into a string https://www.arduino.cc/en/Tutorial/StringConstructors vertical = String(analogRead(verticalPin), DEC); horizontal = String(analogRead(horizontalPin), DEC); //TODO: combine them into a string that can be understood by server.js dataString = horizontal + "," + vertical; //TODO: send the string over serial Serial.println(dataString); } // TODO: Detect if you want to reset the screen(shake the etch-a-sketch) // TODO: write the reset message(see server.js) to the serial port shakeErase(); delay(100); }
true
e65586eaac32cdc3103083aa70a416be81f7e6d3
C++
LaMinato/LodeRunner1
/main.cpp
WINDOWS-1251
13,530
2.75
3
[]
no_license
#include <SFML/Graphics.hpp> #include "map.h" #include "view.h" #include <iostream> #include <sstream> #include "menu.h" #include <vector> #include <list> using namespace sf; //////////////////////////////////// ////////////////////////// class Entity { public: float dx, dy, x, y, speed,moveTimer;// int w,h,health; bool life, isMove, onGround; Texture texture; Sprite sprite; String name;// , . update Entity(Image &image, float X, float Y,int W,int H,String Name){ x = X; y = Y; w = W; h = H; name = Name; moveTimer = 0; speed = 0; health = 100; dx = 0; dy = 0; life = true; onGround = false; isMove = false; texture.loadFromImage(image); sprite.setTexture(texture); sprite.setOrigin(w / 2, h / 2); } FloatRect GetRect() { return FloatRect(x,y,w,h); } }; //////////////////////////////////////////////////// //////////////////////// class Player :public Entity { public: enum { left, right, up, down, jump, stay, ladder, win, onladder, rope } state;// - int playerScore;// Player(Image &image, float X, float Y,int W,int H,String Name):Entity(image,X,Y,W,H,Name){ playerScore = 1; state = stay; if (name == "Player1"){ sprite.setTextureRect(IntRect(0, 0, w, h)); } } void control(){ if (Keyboard::isKeyPressed){// if (Keyboard::isKeyPressed(Keyboard::Left)) {// state = left; speed = 0.1; sprite.setScale(-1,1); } if (Keyboard::isKeyPressed(Keyboard::Right)) { state = right; speed = 0.1; sprite.setScale(1,1); } if ((Keyboard::isKeyPressed(Keyboard::Up))&&(state == ladder)) { state = up; dy+= -0.1; } if ((Keyboard::isKeyPressed(Keyboard::Down))&&((state == ladder)||(state == onladder))) { state = down; dy += 0.1; } if ((Keyboard::isKeyPressed(Keyboard::Left))&&(state == rope)) { dx = -0.1; } if ((Keyboard::isKeyPressed(Keyboard::Right))&&(state == rope)) { dx = 0.1; } if ((Keyboard::isKeyPressed(Keyboard::Down))&&(state == rope)) { dy = 0.15; state = stay; } if (Keyboard::isKeyPressed(Keyboard::C)) { for (int i = y / 32; i < (y + h) / 32; i++)// for (int j = x / 32; j<(x + w) / 32; j++) { if (TileMap [i+1][j+1] == '0') TileMap[i+1][j+1] = '5'; } } if (Keyboard::isKeyPressed(Keyboard::X)) { for (int i = y / 32; i < (y + h) / 32; i++)// for (int j = x / 32; j<(x + w) / 32; j++) { if (TileMap [i+1][j-1] == '0') TileMap[i+1][j-1] = '5'; } } } } void checkCollisionWithMap(float Dx, float Dy)// { for (int i = y / 32; i < (y + h) / 32; i++)// for (int j = x / 32; j < (x + w) / 32; j++) { if (TileMap [i][j] == 'e') state = win; if (TileMap[i+1][j] == 'f') state = onladder; if (TileMap[i][j] == 'f') { state = ladder; } if (TileMap[i][j] == 's') { TileMap[i][j] = ' '; playerScore--; } if (TileMap[i][j] == 'd') { life = false; for (int k = HEIGHT_MAP-1; k > 1; k--) for (int m = WIDTH_MAP-1; m > 1; m--) { TileMap[k][m] = 'd'; } } if ((TileMap[i][j] == '0') || (TileMap[i][j] == '1'))// ? { if (Dy>0){ y = i * 32 - h; dy = 0; onGround = true; }// Y => ( ) . , if (Dy<0){ y = i * 32 + 32; dy = 0; }// ( ) if (Dx>0){ x = j * 32 - w; }// if (Dx<0){ x = j * 32 + 32; }// } if (TileMap[i][j] == 'r') { state = rope; } //else { onGround = false; }// . } } void update(float time) { control();// switch (state)// { case right:dx = speed; break;// case left:dx = -speed; break;// case up: dx = 0; break;// ( ) case down: dx = 0; break;// ( ) case ladder: dx = 0; break; case stay: dx = 0; break;// case onladder: dx = 0; break; case rope: dx = 0; break; } x += dx*time; checkCollisionWithMap(dx, 0);// y += dy*time; checkCollisionWithMap(0, dy);// Y sprite.setPosition(x + w / 2, y + h / 2); // if (health <= 0){ life = false; } if (!isMove){ speed = 0; } //if (!onGround) { dy = dy + 0.0015*time; }// if (life) { setPlayerCoordinateForView(x, y); } if ((state != ladder)||(state != onladder)) dy = dy + 0.0015*time; if ((state == ladder)||(state == onladder)) dy = 0;// if (state == rope) dy = 0; } }; class Enemy :public Entity{ public: Enemy(Image &image, float X, float Y,int W,int H,String Name):Entity(image,X,Y,W,H,Name){ if (name == "EasyEnemy"){ sprite.setTextureRect(IntRect(5, 0, w, h)); dx = 0.1; dy = 0.8; sprite.setScale(-1,1); } } void checkCollisionWithMap(float Dx, float Dy)// { for (int i = y / 32; i < (y + h) / 32; i++)// for (int j = x / 32; j<(x + w) / 32; j++) { if ((TileMap[i][j] == '0')||(TileMap[i][j] == '1'))// , { if (Dy>0){ y = i * 32 - h; }// Y => ( ) . , if (Dy<0){ y = i * 32 + 32; }// ( ) if (Dx>0){ x = j * 32 - w; dx = -0.1; sprite.scale(-1, 1); }// if (Dx<0){ x = j * 32 + 32; dx = 0.1; sprite.scale(-1, 1); }// } if (TileMap[i][j] == '5') { //y = (i+1)*32-h; x = (j+1)*32 - w; } } } void update(float time) { if (name == "EasyEnemy"){// //moveTimer += time;if (moveTimer>3000){ dx *= -1; moveTimer = 0; }// 3 x += dx*time; checkCollisionWithMap(dx, 0);// y += dy*time; checkCollisionWithMap(0, dy);// Y sprite.setPosition(x + w / 2, y + h / 2); // if (health <= 0){ life = false; } } } }; /*void Robot(Player pl, Enemy en) { if (en.x < pl.x) { if (en.y < pl.y) { GetLadder(en.x, en.y, 1); } else if (en.y = pl.y) { en.dx = -0.075; } else { GetLadder(en.x, en.y, 2); } } else { if (en.y < pl.y) { GetLadder(en.x, en.y, 3); } else if (en.y = pl.y) { en.dx = -0.075; } else { GetLadder(en.x, en.y, 4); } } };*/ void UpdateMap(int time, std::vector <Destroyed> &des) { for (int l = 0; l < HEIGHT_MAP; l++) for (int m = 0; m < WIDTH_MAP; m++) { bool exist = false; if (TileMap[l][m] == '5') for (int k = 0; k < des.size(); k++) { if ((l == des[k].i)&&(m == des[k].j)) exist = true; } if (!exist) { Destroyed destr; destr.i = l; destr.j = m; destr.sec = 4; des.push_back(destr); } } for (int k = 0; k < des.size(); k++) { des[k].sec -= time; if (des[k].sec == 0) { TileMap[des[k].i][des[k].j] = '0'; } } }; int main() { RenderWindow window(VideoMode(1376, 768), "Lode Runner 2016"); menu(window); view.reset(FloatRect(0, 0, 640, 480)); std::vector <Enemy> Enemies; std::vector <Destroyed> destr; Image map_image; map_image.loadFromFile("images/map.png"); Texture map; map.loadFromImage(map_image); Sprite s_map; s_map.setTexture(map); Image heroImage; heroImage.loadFromFile("images/myhero.bmp"); heroImage.createMaskFromColor(Color(0,0,0)); Image easyEnemyImage; easyEnemyImage.loadFromFile("images/shamaich.png"); easyEnemyImage.createMaskFromColor(Color(0, 0, 0));// . Player p(heroImage, 750, 500, 27, 32,"Player1");// Enemy easyEnemy(easyEnemyImage, 850, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy);// , Enemy easyEnemy2(easyEnemyImage, 950, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy2); Enemy easyEnemy3(easyEnemyImage, 1050, 500, 19 , 32,"EasyEnemy"); Enemies.push_back(easyEnemy3); Clock clock; while (window.isOpen()) { float time = clock.getElapsedTime().asMicroseconds(); float MapTime = clock.getElapsedTime().asSeconds(); clock.restart(); time = time / 800; if (p.state == p.win) { std::cout << "You win!" << '\n'; system("pause"); window.close(); } Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } p.update(time);// Player update function for (int i = 0; i < Enemies.size(); i++) Enemies[i].update(time); window.setView(view); window.clear(); for (int i = 0; i < HEIGHT_MAP; i++) for (int j = 0; j < WIDTH_MAP; j++) { if (TileMap[i][j] == '0') s_map.setTextureRect(IntRect(0, 0, 32, 32)); if (TileMap[i][j] == ' ') s_map.setTextureRect(IntRect(32, 0, 32, 32)); if (TileMap[i][j] == '5') s_map.setTextureRect(IntRect(32, 0, 32, 32)); if (TileMap[i][j] == '1') s_map.setTextureRect(IntRect(0, 0, 32, 32)); if ((TileMap[i][j] == 's')) s_map.setTextureRect(IntRect(64, 0, 32, 32)); if ((TileMap[i][j] == 'f')) s_map.setTextureRect(IntRect(96, 0, 32, 32)); if ((TileMap[i][j] == 'r')) s_map.setTextureRect(IntRect(128, 0, 32, 32)); if (TileMap[i][j] == 'e') s_map.setTextureRect(IntRect(160, 0, 32, 32)); if (TileMap[i][j] == 'd') s_map.setTextureRect(IntRect(192,0,32,32)); s_map.setPosition(j * 32, i * 32); window.draw(s_map); } if (p.playerScore == 0) { for (int j = 5; j < 14; j++) TileMap[j][10] = 'f'; } for (int i = 0; i < Enemies.size(); i++) window.draw(Enemies[i].sprite); window.draw(p.sprite); window.display(); for (int i = 0; i < Enemies.size(); i++) { if (p.GetRect().intersects(Enemies[i].GetRect())) p.life = false; } if (p.life == false) { std::cout << "You Died!" << '\n'; system("pause"); window.close(); } } return 0; }
true
8b88b700e28db706d60038581ceade98b271ca5d
C++
zhming0/Mingorithm
/ACM/BOJ1521.cpp
UTF-8
775
2.6875
3
[]
no_license
#include <iostream> #include<map> #include<stdio.h> using namespace std; int main (int argc, char * const argv[]) { int n,x,y; int p=0; scanf("%d",&n); while (n--) { int i; int ans=0; map<string,bool> m; string s; scanf("%d %d",&x,&y); for (i=0; i<x; i++) { int pos=1; int found; cin>>s; while ((found=s.find('/', pos))!=string::npos) { m[s.substr(0, found)]=true; pos=found+1; } m[s]=true; } for (i=0; i<y; i++) { cin>>s; int found,pos=1; while ((found=s.find('/', pos))!=string::npos) { if (m.count(s.substr(0, found))==0) { ans++; m[s.substr(0, found)]=true; } pos=found+1; } if (m.count(s)==0) { m[s]=true; ans++; } } printf("Case #%d: %d\n",++p,ans); } return 0; }
true
b1433945feacb149ac2b4d5aa2a8a722c6a3353b
C++
Armanis22/ProjectFuego
/ProjectFuego/ResourceManager.h
UTF-8
453
2.890625
3
[]
no_license
#pragma once #include <SFML\Graphics.hpp> #include <map> template <typename Enum, typename Resource> class ResourceManager { public: const Resource& get(Enum name) const { return m_resources.at(name); } protected: void addResource(Enum name, const std::string& fileName) { Resource resource; resource.loadFromFile(fileName); m_resources.insert(std::make_pair(name, resource)); } private: std::map<Enum, Resource> m_resources; };
true
b639dd9ee19f8fc66ba7e802fa81d008db2ee9a4
C++
cnyali-czy/code
/vjudge/平衡树/A.cpp
UTF-8
2,639
2.671875
3
[]
no_license
#define DREP(i, s, e) for(int i = s; i >= e ;i--) #define REP(i, s, e) for(int i = s; i <= e ;i++) #define DEBUG fprintf(stderr, "Passing [%s] in Line %d\n", __FUNCTION__, __LINE__) #define chkmax(a, b) a = max(a, b) #define chkmin(a, b) a = min(a, b) #include <bits/stdc++.h> using namespace std; const int maxn = 100000 + 10; template <typename T> inline T read() { T ans(0), p(1); char c = getchar(); while (!isdigit(c)) { if (c == '-') p = -1; c = getchar(); } while (isdigit(c)) { ans = ans * 10 + c - 48; c = getchar(); } return ans * p; } struct node { int l, r, s, val, order; node() : l(0), r(0), s(0) {} node(int _val) : val(_val), l(0), r(0), s(1), order(rand()){}; }t[maxn]; int cnt, root; int newnode(int val) { t[++cnt] = node(val); return cnt; } void maintain(int x) {t[x].s = t[t[x].l].s + t[t[x].r].s + 1;} void split(int x, int &a, int &b, int val) { if (!x) a = b = 0; else { if (t[x].val > val) split(t[b = x].l, a, t[x].l, val); else split(t[a = x].r, t[x].r, b, val); maintain(x); } } void merge(int &x, int a, int b) { if (!(a * b)) x = a + b; else { if (t[a].order > t[b].order) merge(t[x = b].l, a, t[b].l); else merge(t[x = a].r, t[a].r, b); maintain(x); } } void insert(int val) { int x(0), y(0), z(newnode(val)); split(root, x, y, val); merge(x, x, z); merge(root, x, y); } void del(int val) { int x(0), y(0), z(0); split(root, x, y, val-1); split(y, y, z, val); merge(y, t[y].l, t[y].r); merge(y, y, z); merge(root, x, y); } int rnk(int val) { int x(0), y(0); split(root, x, y, val-1); int ans = t[x].s + 1; merge(root, x, y); return ans; } int kth(int k, int now = root) { while (t[t[now].l].s + 1 != k) if (k <= t[t[now].l].s) now = t[now].l; else { k -= t[t[now].l].s + 1; now = t[now].r; } return t[now].val; } int pre(int val) { int x(0), y(0); split(root, x, y, val-1); int ans = kth(t[x].s, x); merge(root, x, y); return ans; } int nxt(int val) { int x(0), y(0); split(root, x, y, val); int ans = kth(1, y); merge(root, x, y); return ans; } int n, m, k; int main() { #ifdef CraZYali freopen("A.in", "r", stdin); freopen("A.out", "w", stdout); #endif cin >> n; srand((unsigned long long)new char); while (n--) { int opt = read<int>(); switch(opt) { case 1: insert(read<int>()); break; case 2: del(read<int>()); break; case 3: printf("%d\n", rnk(read<int>())); break; case 4: printf("%d\n", kth(read<int>())); break; case 5: printf("%d\n", pre(read<int>())); break; case 6: printf("%d\n", nxt(read<int>())); break; } } return 0; }
true
5b6590e94b2c896f18c2f7237c1fedfd19e10f78
C++
SWCDSI/QUIC
/AARPorjectAll/jnitest/test_conv_data_optimized.cpp
UTF-8
1,460
3.375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> float abs(float value){ if(value>=0) return value; else return -1*value; } // function used in ultraphone to get only the necessary convolutions float getSumAbsConInRange(float *source, int sourceSize, float *pulse, int pulseSize, int rangeStart, int rangeEnd){ int rangeSize = rangeEnd - rangeStart; int rangeOffset = (int)((pulseSize-1)/2); // this is used to compensate the "same" option conv in matlab printf("rangeOffset = %d\n", rangeOffset); // 1. make some data format check if(rangeOffset > rangeStart){ printf("[ERROR]: rangeOffset > rangeStart"); return -1; } if(sourceSize < pulseSize){ printf("[ERROR]: only support sourceSize >= pulseSize"); return -1; } float sum = 0; for(int i = 0; i<rangeSize; i++){ int pulseIdx = 0; float con = 0; for( int x = i+rangeStart-rangeOffset; x < sourceSize && pulseIdx < pulseSize; x++) { printf("x = %d, source now = %f, pulse now = %f\n", x, source[x], pulse[pulseIdx]); con += source[x]*pulse[pulseIdx]; pulseIdx ++; } printf("con = %f\n", con); sum += abs(con); } return sum; } int main(){ float source[] = {2,-1,-4,-4,3,2,-5,1,2,-4}; float pulse[] = {-1,0,2,-4,6}; int rangeStart = 3-1; // note this is one less than the matlab setting for compensating c++ 0 start index int rangeEnd = 5; float result = getSumAbsConInRange(source,10,pulse,5,rangeStart, rangeEnd); printf("result = %f\n", result); return 0; }
true
959b6e728c0473240d2673ba74e236f62519077b
C++
Nelnir/PasswordManager
/uTests/tst_abstractfilemanagertest.h
UTF-8
2,405
3.015625
3
[]
no_license
#include <gtest/gtest.h> #include <gmock/gmock-matchers.h> #include "abstractfilemanager.h" #include <memory> #include <QDir> struct TestData{ QString m_login; QString m_password; friend QDataStream& operator>>(QDataStream& stream, TestData& data){ stream >> data.m_login >> data.m_password; return stream; } friend QDataStream& operator<<(QDataStream& stream, const TestData& data){ stream << data.m_login << data.m_password; return stream; } bool operator==(const TestData& data) const { return m_login.toLower() == data.m_login.toLower() && m_password == data.m_password; } }; class BaseFileManagerTest : public testing::Test{ public: virtual void SetUp(){ m_1 = std::make_unique<BaseFileManager<TestData>>(); } virtual void TearDown(){ } protected: std::unique_ptr<BaseFileManager<TestData>> m_1; }; TEST_F(BaseFileManagerTest, CreatingFile) { EXPECT_FALSE(QFile("data/data.cfg").exists()); EXPECT_TRUE(m_1->load(QString("data/data.cfg"))); EXPECT_TRUE(QFile("data/data.cfg").exists()); m_1->unload(); QDir("data").removeRecursively(); EXPECT_FALSE(QFile("data/data.cfg").exists()); } TEST_F(BaseFileManagerTest, SavingToFileAndReading) { TestData acc; acc.m_login = "login"; acc.m_password = "password"; m_1->load("data/data.cfg"); EXPECT_EQ(0, m_1->size()); m_1->addData(acc); EXPECT_EQ(1, m_1->size()); m_1->save(); m_1->unload(); EXPECT_EQ(0, m_1->size()); m_1->load("data/data.cfg"); ASSERT_EQ(1, m_1->size()); EXPECT_EQ(acc, *m_1->container().begin()->second); m_1->unload(); QDir("data").removeRecursively(); } TEST_F(BaseFileManagerTest, ID_Test) { TestData acc; acc.m_login = "login"; acc.m_password = "pass"; int id = m_1->addData(acc); EXPECT_EQ(acc, **m_1->getItemWithId(id)); int id2 = m_1->addData(acc); EXPECT_NE(id, id2); m_1->unload(); } TEST_F(BaseFileManagerTest, ReplaceTest) { TestData acc1; acc1.m_login = "login"; acc1.m_password = "pass"; TestData acc2; acc2.m_login = "pass"; acc2.m_password = "login"; int id = m_1->addData(acc1); int id2 = m_1->addData(acc2); EXPECT_TRUE(m_1->replace(id, acc2)); EXPECT_EQ(**m_1->getItemWithId(id), acc2); EXPECT_FALSE(m_1->replace(id2 + 1, acc1)); }
true
f06716d358edbe97b6405a23fa0f6cab9ace69ac
C++
oderayi/cbs
/simpleInterest.cpp
UTF-8
551
3.921875
4
[]
no_license
/* The simple interest on a principal (P) at a rate (R) for time (T) ins computed as Simple Interest = PRT / 100 Write a C++ program to input P, R and T, and compute the simple interest */ // Program to compute simple interest #include <iostream> using namespace std; int main(){ float principal, rate, simpleInterest, time; cout << "Enter principal, rate and time:" << endl; cin >> principal >> rate >> time; simpleInterest = (principal * rate * time) / 100; cout << endl; cout << "Simple interest = " << simpleInterest; return 0; }
true
22c43c389b3049f9ba87cb0309d3181353017f1c
C++
samerbuj/qix
/menu.cpp
ISO-8859-1
794
2.8125
3
[]
no_license
#include "menu.h" #include<iostream> using namespace std; void MenuPrincipal() //Mostra el men principal amb les diferents opcions que podem escollir. { cout << "------Menu Principal------" << endl << endl; cout << "1.- Jugar" << endl; cout << "2.- Configurar" << endl; cout << "3.- Millors Puntuacions" << endl; cout << "4.- Sortir" << endl << endl; cout << "--------------------------" << endl; } //==================================// void MenuNivellDificultat() //Aquest s el men que permet canviar entre les diferents dificultats del joc. { cout << "------Menu Dificultat------" << endl << endl; cout << "1.- Principiant" << endl; cout << "2.- Mitja" << endl; cout << "3.- Expert" << endl << endl; cout << "---------------------------" << endl; }
true
357d23959df5992beb470b61129b46afbc802529
C++
GabeOchieng/ggnn.tensorflow
/program_data/PKU_raw/60/1396.c
UTF-8
370
2.859375
3
[]
no_license
int shu(int a) { int i,n; for (i=2;i<=sqrt(a);i++) { if (a%i==0) return 0; } return 1; } main() { int m,j,sum=0; scanf("%d",&m); for (j=3;j<=m-2;j++) { if (shu(j) && shu(j+2)) { printf("%d %d\n",j,j+2); sum++; } } if (sum==0) printf("empty"); }
true
6e826e1d532f0c7aeb740318fa44fc459e1661a0
C++
PeterZhouSZ/TranslationSync
/src/graph.h
UTF-8
8,598
3.109375
3
[]
no_license
#ifndef GRAPH_H #define GRAPH_H #include <iostream> #include <fstream> #include <string> #include <random> #include <stdlib.h> #include <string> #include <algorithm> using namespace std; class Params{ public: //Graph specific parameters: int n; //#nodes double p; //Probability of each edge double noise_ratio; // probability that a sample has noise int noise_type; // possible noise types: // 0: gaussian with mean 0 and std_dev=0.001 // 1: uncentered gaussian with mean 1 and std_dev=1 // 2: uncentered uniform [-1, 3] bool load_graph = false; // if true, load graph from file char* graph_file_name; double bias; double inc; double* s; //weight of each node, s[i] = bias + inc*i/(n-1) //edge (i,j) exists w.p. p*s[i]*s[j] //sample specific parameters: double a, b; double sigma; double stopping; default_random_engine generator; //solver specific parameters: int max_iter = 1000; double decay = 0.9; Params(){ } Params(int argc, char** argv){ n = atoi(argv[1]); p = atof(argv[2]); bias = atof(argv[3]); inc = atof(argv[4]); noise_type = atoi(argv[5]); noise_ratio = atof(argv[6]); s = new double[n]; for (int i = 0; i < n; i++){ s[i] = bias + inc*i/(n-1); } max_iter = atoi(argv[7]); decay = atof(argv[8]); a = atof(argv[9]); b = atof(argv[10]); sigma = atof(argv[11]); stopping = atof(argv[14]); if (argc > 13){ load_graph = true; graph_file_name = argv[13]; } else { load_graph = false; } cerr << "Initiating Parameters: "; cerr << "n=" << n; cerr << ", edge_density=" << p; cerr << ", bias=" << bias; cerr << ", incremental=" << inc; cerr << ", noise_type=" << noise_type; cerr << ", noise_ratio=" << noise_ratio; cerr << ", sigma=" << sigma; cerr << ", noise_parameters=(" << a << "," << b << ")"; cerr << ", stopping=" << stopping; cerr << endl; } ~Params(){ delete s; } double noise(){ uniform_real_distribution<double> small_noise(-sigma, sigma); uniform_real_distribution<double> uniform(a, b); uniform_real_distribution<double> dice(0.0, 1.0); double noise = small_noise(generator); if (dice(generator) <= noise_ratio){ noise = uniform(generator); } return noise; } double ground_truth(){ normal_distribution<double> ground_truth(0.0, 1.0); // should not matter, can be just zero return ground_truth(generator); } }; class Graph{ public: int n; // #nodes int m; // #edges double* x; double* x0; vector<pair<double, int>>* adj; // #edges in terms of adjacency matrix vector<pair<int, int>> edges; Params* params; bool* visited; // used to check connectivity int num_visited; Graph(){ } Graph(Params* _params){ params = _params; n = params->n; //generate ground truth x x = new double[n]; x0 = new double[n]; for (int i = 0; i < n; i++){ x[i] = params->ground_truth(); x0[i] = i; } adj = new vector<pair<double, int>>[n]; //generate samples, possibly with noise if (params->load_graph){ edges.clear(); ifstream fin(params->graph_file_name); fin >> n >> m; for (int e = 0; e < m; e++){ int i, j; fin >> i >> j; assert(i < j); edges.push_back(make_pair(i, j)); adj[i].push_back(make_pair(0.0, j)); adj[j].push_back(make_pair(0.0, i)); } fin.close(); cerr << "Done Loading Graph From " << params->graph_file_name; cerr << "#nodes=" << n; cerr << ", #edges=" << m; cerr << endl; } else { m = 0; double p = params->p; double* s = params->s; edges.clear(); for (int i = 0; i < n; i++){ double s_i = s[i]; for (int j = i+1; j < n; j++){ double s_j = s[j]; double dice = rand()*1.0 / RAND_MAX; if (dice <= p * s_i * s_j){ edges.push_back(make_pair(i, j)); double t_ij = x[i] - x[j] + params->noise(); adj[i].push_back(make_pair(t_ij, j)); adj[j].push_back(make_pair(-t_ij, i)); m++; } } } visited = new bool[n]; num_visited = 0; memset(visited, false, sizeof(bool)*n); dfs(0); int num_extra_edges = 0; for (int i = 1; i < n; i++){ if (!visited[i]){ int dice = rand() % num_visited; int count = 0; for (int j = 0; j < n; j++){ if (visited[j]){ if (count == dice){ //add edge to (i, j) and then dfs(j) double t_ij = x[i] - x[j] + params->noise(); adj[i].push_back(make_pair(t_ij, j)); adj[j].push_back(make_pair(-t_ij, i)); edges.push_back(make_pair(min(i, j), max(i, j))); dfs(i); m++; num_extra_edges++; break; } else { count++; } } } } } delete visited; cerr << "Done Generating Graph: "; cerr << "#nodes=" << n; cerr << ", #edges=" << m << " (#extras=" << num_extra_edges << ")"; cerr << endl; } //ground truth normalization/shift int* d = new int[n]; memset(d, 0, sizeof(int)*n); for (auto e = edges.begin(); e != edges.end(); e++){ int i = e->first, j = e->second; d[i]++; d[j]++; } normalize(n, d, x); normalize(n, d, x0); } ~Graph(){ for (int i = 0; i < n; i++){ adj[i].clear(); } delete x0; delete x; } inline void normalize(int n, int* d, double* z){ double up = 0.0, down = 0.0; for (int i = 0; i < n; i++){ up += sqrt(d[i])*z[i]; down += sqrt(d[i]); } double shift = up/down; for (int i = 0; i < n; i++){ z[i] -= shift; } } inline Graph copy(){ Graph g; g.n = this->n; g.m = this->m; g.adj = new vector<pair<double, int>>[g.n]; g.edges = this->edges; g.x = new double[g.n]; g.x0 = new double[g.n]; for (int i = 0; i < g.n; i++){ g.x[i] = x[i]; g.x0[i] = x0[i]; } g.params = this->params; return g; } void resample(){ for (int i = 0; i < n; i++){ adj[i].clear(); x0[i] = (rand()*1.0 / RAND_MAX) * 100.0; } for (auto e = edges.begin(); e != edges.end(); e++){ int i = e->first, j = e->second; double t_ij = x[i] - x[j] + params->noise(); adj[i].push_back(make_pair(t_ij, j)); adj[j].push_back(make_pair(-t_ij, i)); } } void dump(char* filename){ ofstream fout(filename); fout << n << " " << m << endl; int count = 0; for (int e = 0; e < edges.size(); e++){ int i = edges[e].first, j = edges[e].second; assert(i < j); fout << i << " " << j << endl; } fout.close(); } private: void dfs(int i){ num_visited++; visited[i] = true; for (auto it = adj[i].begin(); it != adj[i].end(); it++){ int j = it->second; if (!visited[j]){ dfs(j); } } } }; class Solver{ virtual inline double solve(Graph& graph, string output_name){ }; }; #endif
true
64a2014258be9eec3904a427c8887cfdaf8ef13f
C++
eamarquise/SER401-FALL-19-Project35
/Archive/P35Brute/PreferredMeetingTimes.h
UTF-8
757
3.046875
3
[]
no_license
/* * PreferredMeetingTimes.h * Description: * A Class to give a student's meeting times * * Created on: Sep. 30, 2019 * Author: mcilibra * * Edited on: Oct. 06, 2019 * Author: eamarquise */ #ifndef PREFERREDMEETINGTIMES_H_ #define PREFERREDMEETINGTIMES_H_ #include <vector> class PreferredMeetingTimes { /* preferredMeetingTime: Based on MST * will take the 3 preferred meeting times for students in order of importance. * 0) Night-time: 12:00AM - 4:00AM * 1) Early Morning: 4:00AM - 8:00AM * 2) Morning: 8:00AM - 12:00PM * 3) Afternoon: 12:00PM - 4:00PM * 4) Early Evening: 4:00PM - 8:00PM * 5) Evening: 8:00PM - 12:00AM */ public: std::vector<int> meetingTimes; }; #endif /* PREFERREDMEETINGTIMES_H_ */
true
43ca8ee0ba71bfc7d6a1d087524a82d083c7b1ba
C++
MarkRakhmatov/ImageCapture
/Utils/src/CallWrapper.h
UTF-8
906
2.84375
3
[ "MIT" ]
permissive
#pragma once #include <chrono> #include <thread> #include <type_traits> #include <utility> enum class ECheckOperation { IN_PROGRESS, SUCCESS, FAIL, }; template< typename TCheckerFunc, TCheckerFunc& CheckerFunc, typename TFunc, typename ... TArgs> std::pair<typename std::result_of<TFunc(TArgs...)>::type, bool> WaitForAsyncCall(TFunc&& func, std::chrono::milliseconds timeout, TArgs ... args) { using ReturnType = typename std::result_of<TFunc(TArgs...)>::type; auto startTime = std::chrono::system_clock::now(); do { ReturnType res = func(std::forward<TArgs>(args)...); ECheckOperation opStatus = CheckerFunc(res); if(opStatus == ECheckOperation::SUCCESS) { return {res, true}; } if(opStatus == ECheckOperation::FAIL) { break; } } while(std::chrono::system_clock::now() - startTime < timeout); return {ReturnType{}, false}; }
true
aa7cee1c2053220b9e9c5c53ff8f27bbd8c1039b
C++
lipeng28/Gklee
/Gklee/include/cuda/thrust/detail/backend/binary_search.h
UTF-8
8,992
2.578125
3
[ "NCSA" ]
permissive
/* * Copyright 2008-2012 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file binary_search.h * \brief Backend interface to binary search functions. */ #pragma once #include <thrust/iterator/iterator_traits.h> #include <thrust/iterator/detail/minimum_space.h> #include <thrust/detail/backend/cpp/binary_search.h> #include <thrust/detail/backend/generic/binary_search.h> namespace thrust { namespace detail { namespace backend { namespace dispatch { template <typename ForwardIterator, typename T, typename StrictWeakOrdering, typename Backend> ForwardIterator lower_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::lower_bound(begin, end, value, comp); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering> ForwardIterator lower_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, thrust::host_space_tag) { return thrust::detail::backend::cpp::lower_bound(begin, end, value, comp); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering, typename Backend> ForwardIterator upper_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::upper_bound(begin, end, value, comp); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering> ForwardIterator upper_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, thrust::host_space_tag) { return thrust::detail::backend::cpp::upper_bound(begin, end, value, comp); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering, typename Backend> bool binary_search(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::binary_search(begin, end, value, comp); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering> bool binary_search(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp, thrust::host_space_tag) { return thrust::detail::backend::cpp::binary_search(begin, end, value, comp); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering, typename Backend> OutputIterator lower_bound(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::lower_bound(begin, end, values_begin, values_end, output, comp); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering, typename Backend> OutputIterator upper_bound(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::upper_bound(begin, end, values_begin, values_end, output, comp); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering, typename Backend> OutputIterator binary_search(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp, Backend) { return thrust::detail::backend::generic::binary_search(begin, end, values_begin, values_end, output, comp); } } // end namespace dispatch template <typename ForwardIterator, typename T, typename StrictWeakOrdering> ForwardIterator lower_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::lower_bound(begin, end, value, comp, typename thrust::iterator_space<ForwardIterator>::type()); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering> ForwardIterator upper_bound(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::upper_bound(begin, end, value, comp, typename thrust::iterator_space<ForwardIterator>::type()); } template <typename ForwardIterator, typename T, typename StrictWeakOrdering> bool binary_search(ForwardIterator begin, ForwardIterator end, const T& value, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::binary_search(begin, end, value, comp, typename thrust::iterator_space<ForwardIterator>::type()); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering> OutputIterator lower_bound(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::lower_bound(begin, end, values_begin, values_end, output, comp, typename thrust::detail::minimum_space< typename thrust::iterator_space<ForwardIterator>::type, typename thrust::iterator_space<InputIterator>::type, typename thrust::iterator_space<OutputIterator>::type >::type()); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering> OutputIterator upper_bound(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::upper_bound(begin, end, values_begin, values_end, output, comp, typename thrust::detail::minimum_space< typename thrust::iterator_space<ForwardIterator>::type, typename thrust::iterator_space<InputIterator>::type, typename thrust::iterator_space<OutputIterator>::type >::type()); } template <typename ForwardIterator, typename InputIterator, typename OutputIterator, typename StrictWeakOrdering> OutputIterator binary_search(ForwardIterator begin, ForwardIterator end, InputIterator values_begin, InputIterator values_end, OutputIterator output, StrictWeakOrdering comp) { return thrust::detail::backend::dispatch::binary_search(begin, end, values_begin, values_end, output, comp, typename thrust::detail::minimum_space< typename thrust::iterator_space<ForwardIterator>::type, typename thrust::iterator_space<InputIterator>::type, typename thrust::iterator_space<OutputIterator>::type >::type()); } } // end namespace backend } // end namespace detail } // end namespace thrust
true
0a489fd9cf047b635d9eb144f863ea8dac35e5cb
C++
th4m/c-audio-tag
/src/Parser.cpp
UTF-8
1,578
2.734375
3
[]
no_license
#include <string.h> #include <fstream> #include <taglib/id3v2tag.h> #include <audiotag/Parser.hpp> using namespace TagLib::ID3v2; // Helper functions std::string Parser::trim (std::string str) { size_t first = str.find_first_not_of(' '); size_t last = str.find_last_not_of(' '); return str.substr(first, last - first + 1); } bool Parser::contains (std::string str, std::string fnd) { return str.find(fnd) != std::string::npos; } // Parse strings in file to tag Tag* Parser::fileToTag (std::string filename) { std::ifstream file(filename); std::string line; Tag * tag = new Tag(); while (std::getline(file, line)) { // Assuming one-line tags written in file size_t first = line.find_first_of(':') + 1; if (contains(line, "#Title:")) { tag->setTitle(trim(line.substr(first))); } else if (contains(line, "#Artist:")) { tag->setArtist(trim(line.substr(first))); } else if (contains(line, "#Album:")) { tag->setAlbum(trim(line.substr(first))); } else if (contains(line, "#Comment:")) { tag->setComment(trim(line.substr(first))); } else if (contains(line, "#Genre:")) { tag->setGenre(trim(line.substr(first))); } else if (contains(line, "#Year:")) { tag->setYear(std::stoul(trim(line.substr(first)))); } else if (contains(line, "#Track:")) { tag->setTrack(std::stoul(trim(line.substr(first)))); } } return tag; }
true
9907b16b720c27e296635eec13e4646d89a1a06a
C++
karldoenitz/HiJoke
/Application/register/RegisterHandler.cpp
UTF-8
1,546
2.90625
3
[]
no_license
// // Created by 李志豪 on 10/3/15. // #include "RegisterHandler.h" bool Register::user_register(std::string username, std::string password) { std::shared_ptr<DatabaseOperator>databaseOperator(new DatabaseOperator()); std::shared_ptr<User>user(new User()); user->set_username(username); user = databaseOperator->userManager->get_user(user, 1); if (user->get_status()!=0){ return false; } std::shared_ptr<Utils>utils(new Utils()); std::string uuid = utils->uuid(); user->set_username(username); user->set_password(cppcms::util::md5hex(password)); user->set_usercode(uuid); user->set_status(1); bool result = databaseOperator->userManager->save_user(user); return result; } void RegisterHandler::main(std::string url) { std::string username = request().post("username"); std::string password = request().post("password"); cppcms::json::value json_result; if (username.length()<1||password.length()<1){ json_result["result"] = false; json_result["reason"] = "注册失败,请输入用户名或密码"; response_as_json(json_result); return; } Register *registerUser = new Register(); bool result = registerUser->user_register(username, password); if (result){ json_result["result"] = true; json_result["reason"] = "注册成功"; } else{ json_result["result"] = false; json_result["reason"] = "注册失败"; } response_as_json(json_result); delete registerUser; }
true
421e36030012fd6bf6674f4db0c4c69e63001cc3
C++
Ehkiden/Shapes-Calculation
/Cylinder.cpp
UTF-8
972
3.796875
4
[]
no_license
#include "Cylinder.h" #include <cmath> #include <iostream> using namespace std; //default constructor Cylinder::Cylinder():Circle() { radius = 0; height = 0; } //constructor Cylinder::Cylinder(double r, double h):Circle(r) { radius = r; height = h; } //computes the area double Cylinder::Area() { double area = (pow(radius, 2) * (atan(1) * 4)) * 2 + 2 * (atan(1) * 4)*radius*height; return area; } //calculates the volume double Cylinder::Volume() { double volume = (atan(1) * 4)*(pow(radius,2))*height; return volume; } void Cylinder::expand(int factor) { radius = radius*factor; height = height*factor; } //displays the required info void Cylinder::display() { double area = this->Area(); double volume = this->Volume(); cout << "Cylinder: (radius = " << radius << ", height = " << height << ")" << endl; cout << "The area is: " << area << endl; cout << "The volume is: " << volume << endl; cout << endl; }
true
c71b2ce83411f7c1baf800d6d386dae6c7652631
C++
JoeAltmaier/Odyssey
/Odyssey/SSAPI_Server/ManagedObjects/FloatVectorFilter.h
UTF-8
2,820
2.703125
3
[]
no_license
//************************************************************************ // FILE: FloatVectorFilter.h // // PURPOSE: Defines the FloatVectorFilter object that will be used // to filter result sets for ObjectManager::ListIds() //************************************************************************ #ifndef __FLOAT_VECTOR_FILTER_H__ #define __FLOAT_VECTOR_FILTER_H__ #include "SSAPIFilter.h" #include "SSAPITypes.h" class Container; class Comparator; #ifdef WIN32 #pragma pack(4) #endif class FloatVectorFilter : public Filter{ Container *m_pValueVector; // contains pointers to float int m_fieldId; Comparator *m_pComparator; protected: //************************************************************************ // FloatVectorFilter: // // PURPOSE: The default constructor //************************************************************************ FloatVectorFilter( const ValueSet &valueSet ); public: //************************************************************************ // ~FloatVectorFilter: // // PURPOSE: The destructor //************************************************************************ virtual ~FloatVectorFilter(); //************************************************************************ // Ctor: // // PURPOSE: A means of dynamic, self-contained type creation. // new()s and returns an instance //************************************************************************ static Filter* Ctor( const ValueSet &valueSet ){ return new FloatVectorFilter( valueSet ); } //************************************************************************ // DoesApply: // // PURPOSE: Gives a chance to the filter to decide if a given valueset // applies to the filtered set //************************************************************************ virtual Filter::FILTER_RC DoesApply( ValueSet &valueSet ); protected: //************************************************************************ // BuildYourselfFromAValueSet: // // PURPOSE: Populates data members with values from the value set. // Derived classes should override this method if they want // to populate their data members AND THEY MUST call this // method on their base class before doing any processing! //************************************************************************ virtual bool BuildYourselfFromAValueSet( ValueSet &valueSet ); private: //************************************************************************ // ClearValueVector: // // PURPOSE: Deallocates memory taken for elements in the m_valueVector //************************************************************************ void ClearValueVector(); }; #endif // __SSAPI_FLOAT_VECTOR_FILTER_H__
true
5b5c6f63dbd9f28f2d5324092043161cdef2dce8
C++
drlongle/leetcode
/algorithms/problem_1200/solution.cpp
UTF-8
2,120
3.46875
3
[]
no_license
/* 1200. Minimum Absolute Difference Easy Given an array of distinct integers arr, find all pairs of elements with the minimum absolute difference of any two elements. Return a list of pairs in ascending order(with respect to pairs), each pair [a, b] follows a, b are from arr a < b b - a equals to the minimum absolute difference of any two elements in arr Example 1: Input: arr = [4,2,1,3] Output: [[1,2],[2,3],[3,4]] Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order. Example 2: Input: arr = [1,3,6,10,15] Output: [[1,3]] Example 3: Input: arr = [3,8,-10,23,19,-4,-14,27] Output: [[-14,-10],[19,23],[23,27]] */ #include <algorithm> #include <atomic> #include <bitset> #include <cassert> #include <cmath> #include <condition_variable> #include <functional> #include <future> #include <iostream> #include <iterator> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <sstream> #include <stack> #include <thread> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; #define ll long long #define ull unsigned long long class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { sort(begin(arr), end(arr)); int mindiff = numeric_limits<int>::max(); for (size_t i = 1; i < arr.size(); ++i) { mindiff = min(mindiff, arr[i] - arr[i-1]); } vector<vector<int>> res; for (size_t i = 1; i < arr.size(); ++i) { if (mindiff == arr[i] - arr[i-1]) res.emplace_back(vector<int>{arr[i-1], arr[i]}); } return res; } }; int main() { Solution sol; vector<int> arr; // Output: [[1,2],[2,3],[3,4]] arr = {4,2,1,3}; // Output: [[1,3]] arr = {1,3,6,10,15}; // Output: [[-14,-10],[19,23],[23,27]] arr = {3,8,-10,23,19,-4,-14,27}; auto res = sol.minimumAbsDifference(arr); for (auto& r: res) { copy(begin(r), end(r), ostream_iterator<int>(cout, ", ")); cout << endl; } return 0; }
true
6aea16a8afa5eea9c4a08d655a946d5f513b36ec
C++
Graff46/OGSR-Engine
/ogsr_engine/xrGame/date_time.cpp
UTF-8
4,568
2.84375
3
[ "Apache-2.0" ]
permissive
//////////////////////////////////////////////////////////////////////////// // Module : date_time.h // Created : 08.05.2004 // Modified : 08.05.2004 // Author : Dmitriy Iassenev // Description : Date and time routines //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" u64 generate_time(u32 years, u32 months, u32 days, u32 hours, u32 minutes, u32 seconds, u32 milliseconds) { THROW(years > 0); THROW(months > 0); THROW(days > 0); u64 t1, t2, t3, t4; t1 = years / 400; t2 = years / 100; t3 = years / 4; bool a1, a2, a3; a1 = !(years % 400); a2 = !(years % 100); a3 = !(years % 4); t4 = a3 && (!a2 || a1) ? 1 : 0; u64 result = u64(years - 1) * u64(365) + t1 - t2 + t3; if (months > 1) result += u64(31); if (months > 2) result += u64(28 + t4); if (months > 3) result += u64(31); if (months > 4) result += u64(30); if (months > 5) result += u64(31); if (months > 6) result += u64(30); if (months > 7) result += u64(31); if (months > 8) result += u64(31); if (months > 9) result += u64(30); if (months > 10) result += u64(31); if (months > 11) result += u64(30); result += u64(days - 1); result = result * u64(24) + u64(hours); result = result * u64(60) + u64(minutes); result = result * u64(60) + u64(seconds); result = result * u64(1000) + u64(milliseconds); #if 0 u32 _years; u32 _months; u32 _days; u32 _hours; u32 _minutes; u32 _seconds; u32 _milliseconds; split_time (result,_years,_months,_days,_hours,_minutes,_seconds,_milliseconds); VERIFY (years == _years); VERIFY (months == _months); VERIFY (days == _days); VERIFY (hours == _hours); VERIFY (minutes == _minutes); VERIFY (seconds == _seconds); VERIFY (milliseconds == _milliseconds); #endif return (result); } void split_time(u64 time, u32& years, u32& months, u32& days, u32& hours, u32& minutes, u32& seconds, u32& milliseconds) { milliseconds = u32(time % 1000); time /= 1000; seconds = u32(time % 60); time /= 60; minutes = u32(time % 60); time /= 60; hours = u32(time % 24); time /= 24; years = u32(u64(400) * time / u64(365 * 400 + 100 - 4 + 1) + 1); u64 t1, t2, t3, t4; t1 = years / 400; t2 = years / 100; t3 = years / 4; bool a1, a2, a3; a1 = !(years % 400); a2 = !(years % 100); a3 = !(years % 4); t4 = a3 && (!a2 || a1) ? 1 : 0; u64 result = u64(years - 1) * u64(365) + t1 - t2 + t3; time -= result; ++time; months = 1; if (time > 31) { ++months; time -= 31; if (time > 28 + t4) { ++months; time -= 28 + t4; if (time > 31) { ++months; time -= 31; if (time > 30) { ++months; time -= 30; if (time > 31) { ++months; time -= 31; if (time > 30) { ++months; time -= 30; if (time > 31) { ++months; time -= 31; if (time > 31) { ++months; time -= 31; if (time > 30) { ++months; time -= 30; if (time > 31) { ++months; time -= 31; if (time > 30) { ++months; time -= 30; } } } } } } } } } } } days = u32(time); }
true
9d952ca262baed88c48402615b843234f733ed44
C++
DenverN3/Nimbus
/cplusplus/align/lib/libnimbus/src/Utils.cpp
UTF-8
2,143
2.921875
3
[ "MIT" ]
permissive
#include "stdafx.h" #include "Utils.h" namespace Nimbus { namespace utils { char complement_base( char b ) { char rval = 'N' ; switch(b) { case 'A': rval = 'T' ; break ; case 'T': rval = 'A' ; break ; case 'G': rval = 'C' ; break ; case 'C': rval = 'G' ; break ; case 'a': rval = 't' ; break ; case 't': rval = 'a' ; break ; case 'g': rval = 'c' ; break ; case 'c': rval = 'g' ; break ; default: rval = 'N' ; break ; } return rval ; } std::vector<std::string> split_string( std::string x, std::string d ) { // std::vector<std::string> rval = std::vector<std::string>() ; // fill the rval size_t pos = 0; std::string t ; while( (pos = x.find(d)) != std::string::npos ) { t = x.substr(0, pos) ; rval.push_back( t ) ; x.erase( 0, pos + d.length() ) ; } // add the last entry rval.push_back( x ) ; // return the data return rval ; } int QueryStart( std::vector< std::pair<int,int> > path ) { // declare the return value int rval = 0 ; // traversing the path, we will see whether the query coorindate exceeds 0. // If it does break as we found the query start. If not try the next position in the path for( std::vector< std::pair<int,int> >::iterator it=path.begin(); it!=path.end(); ++it ) { if( it->second > 0 ) { break ; } else { rval++ ; } } return rval ; } int QueryEnd( std::vector< std::pair<int,int> > path ) { // the return value int rval = (int) path.size() - 1 ; // the end value of the query int endval = path.at(path.size() - 1).second ; // traverse the path from the end to the beginning for( std::vector< std::pair<int,int> >::reverse_iterator it=path.rbegin(); it!=path.rend(); ++it ) { // if we found that the current query coordinate equals // the end coordinate, decrease the counter. If not we have // found the end and should break the loop if( it->second != endval ) { break ; } else { rval-- ; } } return rval ; } } }
true
bafd6cc42819e69b604e916c202f36f9d3824d8a
C++
gregjohnson2017/NeuralNet
/network.h
UTF-8
1,182
2.671875
3
[]
no_license
#ifndef NETWORK_H #define NETWORK_H #include <stdio.h> #include <vector> #include "layer.h" using namespace std; typedef double (*errorFunc)(double activation, void* answer); typedef struct sampleSet{ vector<vector<double> > *inputData; vector<double> *answers; int sampleSize; // length of 1d array stretch before next sample // ex 64x64 image: sampleSize = 4096 } sampleSet; sampleSet* getSamples(const char *fileName); void printSample(vector<double> sample); class Network{ public: int nLayers, nInputs, nOutputs; errorFunc getError; Network(int nLayers, int nInputs, int nOutputs, errorFunc err); //Network(vector<Layer*> &layers, int nInputs, int nOutputs); Network(const char *fileName, errorFunc err); ~Network(); static double trainingConstant(){ return 0.3; } static int batchSize(){ return 25; } vector<Layer*> layers; vector<double> getOutputs(); void test(const char *testingData); void train(const char *fileName, double trainingConstant); void feedForward(vector<double> &inputs); void backPropagate(); void printNetwork(); void computeOutputError(double answer); void save(const char *fileName); }; #endif
true
8e1a34a61e1d75885cdae98fd203361221139e96
C++
Aditi1017/SDE-Problems
/Day 1/CPP/6.cpp
UTF-8
907
2.9375
3
[]
no_license
#include<bits/stdc++.h> using namespace std; void mergeIntervals(vector<vector<int>>& intervals) { if(intervals.size()<=1) cout << -1 ; sort(intervals.begin(), intervals.end()); vector<vector<int>> output; output.push_back(intervals[0]); for(int i=1; i<intervals.size(); i++) { if(output.back()[1] >= intervals[i][0]) output.back()[1] = max(output.back()[1] , intervals[i][1]); else output.push_back(intervals[i]); } for(int i =0 ; i <output.size(); i++) { for(int j =0 ;j <output[i].size() ; j++) cout << output[i][j] << " "; cout << endl; } } int main() { vector<vector<int>> intervals = [[1,3],[2,6],[8,10],[15,18]] mergeIntervals(intervals); return 0; }
true
4031a0c039320790735df043cbc8be5c63d6a350
C++
proydakov/codeforces
/Codeforces_Round_#142/B/solution.cpp
UTF-8
1,048
2.96875
3
[]
no_license
#include <cmath> #include <vector> #include <cstdint> #include <iostream> std::vector<char> build(int n) { std::vector<char> prime (n + 1, true); prime[0] = prime[1] = false; for (int i = 2; i <= n; ++i) { if (prime[i]) { if (i * 1ll * i <= n) { for (int j = i * i; j <= n; j += i) { prime[j] = false; } } } } return prime; } int main() { std::ios::sync_with_stdio(false); int n; std::cin >> n; std::vector<char> cache = build(1000000); for(int i = 0; i < n; i++) { uint64_t test; std::cin >> test; double val = std::sqrt((double)test); uint64_t ival = (uint64_t)(val); if(ival * ival != test) { std::cout << "NO" << std::endl; } else { if(cache[ival]) { std::cout << "YES" << std::endl; } else { std::cout << "NO" << std::endl; } } } return 0; }
true
0b694b128c94f1adfa5b6d293cb9daf4ab77e791
C++
wenjietseng/nctu-CPE
/0926/zeros-and-ones.cpp
UTF-8
872
2.6875
3
[]
no_license
// Zeros and Ones uva 10324 #include <cstdio> #include <cstring> #include <algorithm> #include <vector> #include <string> #include <map> #include <queue> #include <stack> #include <iostream> using namespace std; #define MAXN 1000000 + 5 char line[MAXN]; int main() { int n, i, j, ans, test_case = 1; while (scanf("%s", line) != EOF) { scanf("%d", &n); cout << "Case " << test_case++ << ":" << endl; while (n--) { scanf("%d%d", &i, &j); ans = 1; if (i > j) { int tmp = i; i = j; j = tmp; } for (int k = i+1; k <= j; k++) { if (line[i] != line[k]) { ans = 0; break; } } printf("%s\n", ans ? "Yes" : "No"); } } return 0; }
true
197e9c4164be856d9115a5894ad3c1399351be40
C++
dwks/HexRacer
/src/input/InputAction.h
UTF-8
439
2.59375
3
[]
no_license
#ifndef PROJECT_INPUT__INPUT_ACTION_H #define PROJECT_INPUT__INPUT_ACTION_H namespace Project { namespace Input { class InputAction { public: enum InputType {KEY, BUTTON, AXIS}; double offValue; double onValue; InputAction(double off_value, double on_value) : offValue(off_value), onValue(on_value) {} virtual ~InputAction() {} virtual InputType type() const = 0; }; } // namespace Input } // namespace Project #endif
true
5e853ac1019127f26ead6877cdbaad13ed5c9d54
C++
samwetha/CatBurglars
/CatBurglars/CatBurglars/Channel.cpp
UTF-8
695
3
3
[]
no_license
#include "Channel.h" #include <iostream> Channel::Channel(int id) : mID(id), mActive(false), mTimer(0){ } bool Channel::isActive() { return mActive; } int Channel::getID() { return mID; } void Channel::setActive(bool toggle, float holdlength) { bool istoggle = toggle; float HOLD = holdlength; if (istoggle) { mActive = true; mToggled = true; } if (HOLD > 0 && istoggle == false) { mToggled = false; mSetActiveTime(HOLD); } } void Channel::mSetActiveTime(float holdlength) { mTimer = holdlength; } void Channel::runTimer() { if (mTimer > 0) { mTimer-= 0.0002; } if (mTimer > 0) { mActive = true; } else if (!mToggled) { mActive = false; } }
true
4eb43a8bf384ac100076e4b2d51f0eb2cedf4a1b
C++
Karthikeyan1920/CodeChef
/Code_Ensemble20/Help_Martha.cpp
UTF-8
3,195
2.796875
3
[]
no_license
#include<bits/stdc++.h> using namespace std; typedef signed long long int ll; ll finddir(string str, char ele){ ll lctr = 0, rctr = 0, uctr = 0, dctr = 0; for(ll i = 0; str[i] != '\0'; i++){ if(str[i] == 'L') lctr++; if(str[i] == 'D') dctr++; if(str[i] == 'U') uctr++; if(str[i] == 'R') rctr++; } switch(ele){ case 'L': return lctr; case 'U': return uctr; case 'R': return rctr; case 'D': return dctr; } return 0; } int main(){ ll tc; cin>>tc; while(tc--){ ll x1, y1, x2, y2, n; string str; cin>>str; cin>>x1>>y1; cin>>n; while(n--){ cin>>x2>>y2; int flag = 1; ll rightctr = 0, leftctr = 0, upctr = 0, downctr = 0; (x1 > x2) ? leftctr = x1 - x2 : rightctr = x2 - x1; (y1 > y2) ? downctr = y1 - y2 : upctr = y2 - y1; if(finddir(str, 'L') < leftctr || finddir(str, 'D') < downctr || finddir(str, 'R') < rightctr || finddir(str, 'U') < upctr){ cout<<"NO"<<endl; flag = 0; } //cout<<upctr<<" "<<downctr<<" "<<rightctr<<" "<<leftctr<<endl; string out = ""; for(ll i = 0; str[i] != '\0'; i++){ if((leftctr == 0) && (downctr == 0) && (rightctr == 0) && (upctr == 0)) break; else{ switch(str[i]){ case 'L': if(leftctr > 0){ leftctr--; out += 'L'; } break; case 'R': if(rightctr > 0){ rightctr--; out += 'R'; } break; case 'U': if(upctr > 0){ upctr--; out += 'U'; } break; case 'D': if(downctr > 0){ downctr--; out += 'D'; } break; } } /*if(leftctr) if(str[i] == 'L'){ leftctr--; out += 'L'; } if(rightctr) if(str[i] == 'R'){ rightctr--; out += 'R'; } if(upctr) if(str[i] == 'U'){ upctr--; out += 'U'; } if(downctr) if(str[i] == 'D'){ downctr--; out += 'D'; }*/ } if(flag){ cout<<"YES"<<" "<<out.length()<<endl; } } } }
true
f09895155cd1667353a9b293aed823c7e37c26b9
C++
Juzley/typeordie
/Laser.cpp
UTF-8
1,066
2.640625
3
[ "MIT" ]
permissive
#include "Laser.h" #include "Game.h" #include "TextureManager.h" #include "SoundManager.h" #include "Utils.h" namespace typing { const std::string Laser::LASER_SOUND("sounds/laser.wav"); const float Laser::LINE_DRAW_TIME = 0.0f; const float Laser::LINE_FADE_TIME = 0.5f; const float Laser::LIFETIME = LINE_DRAW_TIME + LINE_FADE_TIME; void Laser::Init() { SOUNDS.Add(LASER_SOUND); } void Laser::Draw() { float alpha; if (m_age < LINE_DRAW_TIME) { alpha = 1.0f; } else { alpha = 1.0f - (m_age - LINE_DRAW_TIME) / LINE_FADE_TIME; } DrawLine(ColourRGBA(m_col, alpha), m_start, m_end); glLineWidth(4.0f); DrawLine(ColourRGBA(m_col, alpha / 2.0f), m_start, m_end); glLineWidth(1.0f); } void Laser::Update() { m_age += GAME.GetFrameTime(); } bool Laser::Unlink() { return (m_age >= LIFETIME); } void Laser::OnSpawn() { SOUNDS.Play(LASER_SOUND); } }
true
15a3da1f51341439aea52093bfeed358fc63f2b5
C++
Fr3ud/42_CPP_pool
/d08/ex00/main.cpp
UTF-8
535
3.078125
3
[]
no_license
#include "easyfind.hpp" int main( void ) { std::list<int> list; list.push_back(4); list.push_back(2); list.push_back(3); list.push_back(5); list.push_back(7); try { easyfind(list, 3); } catch (std::exception& e) { std::cout << "Value not found" << std::endl; } try { easyfind(list, 42); } catch (std::exception& e) { std::cout << "Value not found" << std::endl; } try { easyfind(list, 4); } catch (std::exception& e) { std::cout << "Value not found" << std::endl; } return 0; }
true
37ed0ed6e6b4108ebb6a027d60b752f36fa3efed
C++
DaDaMrX/Sophomore
/DataStructure/21.连连看游戏辅助 (BFS).cpp
UTF-8
2,199
3.140625
3
[]
no_license
/* 21.连连看游戏辅助 (BFS) */ #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; typedef long long ll; const int INF = 0x7f7f7f7f; const int N = 110; struct Point { int x, y; Point() {} Point(int x, int y) : x(x), y(y) {} }; typedef Point Vector; Point operator+(Point& p, Vector& v) { return Point(p.x + v.x, p.y + v.y); } bool operator==(Point &p1, Point &p2) { return p1.x == p2.x && p1.y == p2.y; } bool operator!=(Point &p1, Point &p2) { return !(p1 == p2); } //方向向量, 0,1,2,3分别代表下,右,上,左 Vector dir[4]; void init_dir() { dir[0] = Vector(1, 0); dir[1] = Vector(0, 1); dir[2] = Vector(-1, 0); dir[3] = Vector(0, -1); } int n, m; int map[N][N]; Point start, finish; bool in_range(Point& to) { return to.x >= 0 && to.x < n && to.y >= 0 && to.y < m; } queue<Point> q; int step[N][N], direct[N][N]; //step[x][y]记录起点到(x,y)点转弯次数 //direct[x][y]记录起走到(x,y)点的方向 bool bfs(Point start) { memset(direct, -1, sizeof(direct)); memset(step, -1, sizeof(step)); while (!q.empty()) q.pop(); init_dir(); q.push(start); step[start.x][start.y] = 0; while (!q.empty()) { Point from = q.front(); q.pop(); for (int i = 0; i < 4; i++) { Point to = from + dir[i]; if (!in_range(to)) continue; //出界 if (to != finish && map[to.x][to.y]) continue; //遇到墙 if (step[to.x][to.y] != -1) continue; //之前走过 if (step[from.x][from.y] == 2 && i != direct[from.x][from.y]) continue; //转弯数大于2 if (to == finish) return true; //到终点 //其他情况,正常入队 q.push(to); direct[to.x][to.y] = i; if (direct[from.x][from.y] != -1 && i != direct[from.x][from.y]) step[to.x][to.y] = step[from.x][from.y] + 1; else step[to.x][to.y] = step[from.x][from.y]; } } return false; } int main() { scanf("%d%d", &n, &m); for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) scanf("%d", &map[i][j]); scanf("%d%d", &start.x, &start.y); scanf("%d%d", &finish.x, &finish.y); if (map[start.x][start.y] != map[finish.x][finish.y]) printf("FALSE\n"); else printf("%s\n", bfs(start) ? "TRUE" : "FALSE"); return 0; }
true
305cf3c1b00471cf9794fa9b2c36315d5d6b8e0b
C++
Ain-Crad/Algorithm-and-DataStructure-Practice
/Uva/Uva221.cpp
UTF-8
1,690
2.8125
3
[]
no_license
/* * * Author : Aincrad * * Date : Wed 14 Nov 07:22:41 CST 2018 * */ #include <bits/stdc++.h> using namespace std; const int maxn = 107; struct Building{ int id; double x, y, w, d, h; }; Building bld[maxn]; int xp[maxn * 2]; int n; bool cmp(const Building& a, const Building& b){ if(a.x == b.x){ return a.y < b.y; } else{ return a.x < b.x; } } bool visible(int ct, int x){ ///cout << "target: " << bld[ct].id << endl; for(int i = 0; i < n; i++){ if(i == ct) continue; if(bld[i].y <= bld[ct].y && bld[i].x <= x && bld[i].x + bld[i].w >= x){ //cout << bld[i].id << endl; if(bld[i].h >= bld[ct].h) return false; } } //cout << "******" << endl; return true; } int main(){ #ifndef ONLINE_JUDGE freopen("in.txt", "r", stdin); #endif int cnt = 1; while(cin >> n){ if(n == 0) break; memset(bld, 0, sizeof(bld)); double x, y, w, d, h; for(int i = 0; i < n; i++){ bld[i].id = i + 1; cin >> x >> y >> w >> d >> h; bld[i].x = x, bld[i].y = y, bld[i].w = w, bld[i].d = d, bld[i].h = h; xp[2 * i] = x, xp[2 * i + 1] = x + w; } sort(bld, bld + n, cmp); sort(xp, xp + 2 * n); int m = unique(xp, xp + 2 * n) - xp; vector<int> vec; for(int i = 0; i < n; i++){ for(int j = 0; j < m - 1; j++){ if(bld[i].x >= xp[j + 1] || bld[i].x + bld[i].w <= xp[j]) continue; if(visible(i, (xp[j] + xp[j + 1]) / 2)){ vec.push_back(bld[i].id); break; } } } if(cnt > 1) cout << endl; printf("For map #%d, the visible buildings are numbered as follows:\n", cnt++); int len = vec.size(); for(int i = 0; i < len; i++){ if(!i) cout << vec[i]; else cout << " " << vec[i]; } cout << endl; } return 0; }
true
4d17c8a082790fe0d1196612161ef68806d334b2
C++
MarquessV/cBirdpp
/include/cbirdpp/Observation.h
UTF-8
1,848
2.78125
3
[]
no_license
#ifndef CBIRDPP_OBSERVATION_H #define CBIRDPP_OBSERVATION_H #include <string> #include <variant> #include <vector> namespace cbirdpp { /* * A simple container class for holding the information returned by the eBird API when making observation requests. * The getter method names directly correlate with the names given to the variables by the JSON response. */ struct Observation { std::string speciesCode; std::string comName; std::string sciName; std::string locId; std::string locName; std::string obsDt; unsigned int howMany; double lat; double lng; bool obsValid; bool obsReviewed; bool locationPrivate; }; struct DetailedObservation : public Observation { std::string checklistId; std::string countryCode; std::string countryName; std::string firstName; bool hasComments; bool hasRichMedia; std::string lastName; std::string locID; // eBird provides locId in normal responses too, they appear to be the same, will remove if that turns out to be the case. std::string obsId; bool presenceNoted; std::string subId; std::string subnational1Code; std::string subnational1Name; std::string subnational2Code; std::string subnational2Name; std::string userDisplayName; operator Observation() const { return {speciesCode, comName, sciName, locId, locName, obsDt, howMany, lat, lng, obsValid, obsReviewed, locationPrivate}; } }; struct DetailedObservations : public std::vector<DetailedObservation> { DetailedObservations() = default; }; struct Observations : public std::vector<Observation> { Observations() = default; }; /* * An extension of the Observation class to include field for requests that have the detail argument set */ } #endif
true
6333c72d84c5c3054c2a45c711c75418ec754f2a
C++
TomChoi/coding_interview
/questions/chapter02/q2-4/test_case/test_case.cpp
UTF-8
3,872
2.984375
3
[]
no_license
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #include "catch.hpp" #include "../answer.cpp" bool CheckResult(LinkedList<int>& list, int partition, int len, int left){ Node<int>* current = list.head; int length = list.getLength(); if( length != len ) return false; for( int i = 1; i <= length; i++ ){ if( i <= left ){ if( current->data >= partition ){ return false; } }else{ if( current->data < partition ){ return false; } } current = current->next; } return true; } TEST_CASE( "Coding test Chapter02", "[Question04]" ) { SECTION("1"){ LinkedList<int> input; input.appendNode(3); input.appendNode(5); input.appendNode(8); input.appendNode(5); input.appendNode(10); input.appendNode(2); input.appendNode(1); int partition = 5; int left = 3; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } SECTION("2"){ LinkedList<int> input; input.appendNode(3); input.appendNode(5); input.appendNode(8); input.appendNode(5); input.appendNode(10); input.appendNode(2); input.appendNode(1); int partition = 10; int left = 6; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } SECTION("3"){ LinkedList<int> input; input.appendNode(1); input.appendNode(1); input.appendNode(3); input.appendNode(10); input.appendNode(3); input.appendNode(25); input.appendNode(11); int partition = 11; int left = 5; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } SECTION("4"){ LinkedList<int> input; input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); input.appendNode(1); int partition = 1; int left = 0; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } SECTION("5"){ LinkedList<int> input; input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); int partition = 10; int left = 0; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } SECTION("6"){ LinkedList<int> input; input.appendNode(11); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); input.appendNode(10); int partition = 11; int left = 36; REQUIRE( CheckResult( Partition(input, partition), partition, input.getLength(), left) ); } }
true
5918054b6d9085c53fd3cb6ca9b5d6c37b10178c
C++
ltempier/arduino_van
/main/Victron.h
UTF-8
1,309
2.515625
3
[]
no_license
#ifndef VICTRON_h #define VICTRON_h #include <Arduino.h> #include <SoftwareSerial.h> /* ERR CODE: 0 No error 2 Battery voltage too high 17 Charger temperature too high 18 Charger over current 19 Charger current reversed 20 Bulk time limit exceeded 21 Current sensor issue (sensor bias/sensor broken) 26 Terminals overheated 33 Input voltage too high (solar panel) 34 Input current too high (solar panel) 38 Input shutdown (due to excessive battery voltage) 116 Factory calibration data lost 117 Invalid/incompatible firmware 119 User settings invalid */ class Victron { private: float pvWatt = 0; float pvVolt = 0; float bVolt = 0; float bAmp = 0; float yeldToday = 0; //kWh float yeldYesterday= 0; //kWh int chargeState = 0; int errCode = 0; //const int comDelayMicros = 100; boolean fetch(); SoftwareSerial victronSerial = SoftwareSerial(3, 4); // RX, TX not used int computeStateOfChargeFromVoltage(); public: void setup(); void loop(); float getPvWatt(); float getBVolt(); float getPvVolt(); int getChargeStateCode(); String getChargeStateLabel(); int getErrCode(); String getErrLabel(); int getBatteryStateOfCharge(); }; #endif
true
f39109b8166c6eb8600d0fd5774318f3d985dba1
C++
freme/raybeam
/ray.h
UTF-8
646
3.3125
3
[]
no_license
// ray.h #ifndef _RAY_H_ #define _RAY_H_ 1 #include "vector3.h" #include <iostream> class Ray { public: Ray() {} Ray(const Vector3& a, const Vector3& b) { data[0] = a; data[1] = b; } Ray(const Ray& r) { *this = r; } Vector3 origin() const { return data[0]; } Vector3 direction() const { return data[1]; } Vector3 pointAtParameter(float t) const { return data[0] + t*data[1]; } Vector3 data[2]; }; inline std::ostream& operator<<(std::ostream& os, const Ray& r) { os << '(' << r.origin() << ") + t(" << r.direction() << ')'; return os; } #endif // _RAY_H_
true
5c4908a0a3c1bb144ccecf3e7feb8b58808954de
C++
lklok66/uMOF_STD11
/include/umof/any.h
UTF-8
4,170
2.9375
3
[]
no_license
/********************************************************************* This file is part of the uMOF library. Copyright (C) 2014 Artem Shal artiom.shal@gmail.com The uMOF library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. **********************************************************************/ #pragma once #include "config.h" #include "type.h" #include "detail/type.h" #include <new> #include <stdexcept> namespace umof { /*! \breif The Any class holds the copy of any data type. */ class UMOF_EXPORT Any { public: /*! Constructs invalid Any holder. */ Any(); /*! Copy value from other holder. */ Any(Any const& other); /*! Move value from other holder. */ Any(Any &&other); /*! Destroys Any and contained object. */ ~Any(); /*! Constructs Any with the given value. */ template<typename T> Any(T const& value); /*! Constructs Any with array value. Special constructor for static arrays. */ template<typename T, std::size_t N> Any(T(&value)[N]); /*! Destroys containing object and set new value. */ /*template<typename T> void reset(T const& value);*/ /*! Destroys containing object. */ void reset(); void reset(detail::TypeTable *table); Type type() const; void *object() const; private: template<typename T> friend T* any_cast(Any*); friend class Method; const detail::TypeTable* _table; void* _object; }; template<typename T> Any::Any(T const& x) : _table(&detail::Type<T>::table), _object(nullptr) { const T *src = &x; detail::Type<T>::clone(&src, &_object); } template<typename T, std::size_t N> Any::Any(T(&x)[N]) : _table(detail::Type<T*>::table()), _object(nullptr) { new (&_object) T*(&x[0]); } /*template<typename T> void Any::reset(T const& x) { if (_table) _table->static_delete(&_object); _table = Table<T>::get(); const T *src = &x; Table<T>::clone(&src, &_object); }*/ template <typename T> inline T* any_cast(Any* operand) { if (operand && operand->_table == &detail::Type<T>::table) return detail::Type<T>::cast(&operand->_object); return nullptr; } template <typename T> inline T* any_cast(Any const* operand) { return any_cast<T>(const_cast<Any*>(operand)); } /*! Casts Any container to a given type T. \relates Any Use it as follows: \code{.cpp} Any a{5.0}; double d = any_cast<double>(a); \endcode */ template <typename T> inline T any_cast(Any& operand) { using nonref = typename std::remove_reference<T>::type; nonref* result = any_cast<nonref>(&operand); if (!result) throw std::runtime_error("Bad cast"); return *result; } /*! Casts Any container to a given type T. \relates Any Use it as follows: \code{.cpp} Any a{5.0}; double d = any_cast<double>(a); \endcode */ template <typename T> inline T const& any_cast(Any const& operand) { using nonref = typename std::remove_reference<T>::type; return any_cast<nonref const&>(const_cast<Any&>(operand)); } }
true
588ba65432c59101954a9c13d154f423332a177d
C++
Raven45/DataLib
/DataLib/NodeSingle.hpp
UTF-8
1,270
3.078125
3
[]
no_license
#include "Node.hpp" namespace DataLib { template <class DataType> class NodeSingle : public Node<DataType> { public: NodeSingle(); NodeSingle(DataType Data); NodeSingle(NodeSingle<DataType>* Pointer); NodeSingle(DataType Data, NodeSingle<DataType>* Pointer); NodeSingle(NodeSingle<DataType> &Copy); NodeSingle<DataType>* GetPointer(); void SetPointer(NodeSingle<DataType>* P); private: NodeSingle<DataType>* P; }; template<class DataType> NodeSingle<DataType>::NodeSingle() : Node<DataType>() { } template<class DataType> NodeSingle<DataType>::NodeSingle(DataType Data) : Node<DataType>(Data) { } template<class DataType> NodeSingle<DataType>::NodeSingle(NodeSingle<DataType>* Pointer) : Node<DataType>() { P = Pointer; } template<class DataType> NodeSingle<DataType>::NodeSingle(DataType Data, NodeSingle<DataType>* Pointer) : Node<DataType>(Data) { P = Pointer; } template<class DataType> NodeSingle<DataType>::NodeSingle(NodeSingle<DataType> &Copy) : Node<DataType>(Copy) { this->P = Copy.P; } template<class DataType> NodeSingle<DataType>* NodeSingle<DataType>::GetPointer() { return P; } template<class DataType> void NodeSingle<DataType>::SetPointer(NodeSingle<DataType>* P) { this->P = P; } }
true
eea0bb5074a8e2f7d11d4513eab183fd83ab0cba
C++
smallinsect/WindowsAPI
/WinAPI/DemoWin14/DemoWin14.cpp
UTF-8
5,923
2.703125
3
[]
no_license
// DemoWin14.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include "DemoWin14.h" #define MAX_LOADSTRING 100 // 全局变量: HINSTANCE hInst; // 当前实例 WCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 WCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 // 此代码模块中包含的函数的前向声明: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此处放置代码。 // 初始化全局字符串 LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_DEMOWIN14, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_DEMOWIN14)); MSG msg; // 主消息循环: while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } // // 函数: MyRegisterClass() // // 目标: 注册窗口类。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DEMOWIN14)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_DEMOWIN14); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassExW(&wcex); } // // 函数: InitInstance(HINSTANCE, int) // // 目标: 保存实例句柄并创建主窗口 // // 注释: // // 在此函数中,我们在全局变量中保存实例句柄并 // 创建和显示主程序窗口。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; // 将实例句柄存储在全局变量中 HWND hWnd = CreateWindowW(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // 函数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目标: 处理主窗口的消息。 // // WM_COMMAND - 处理应用程序菜单 // WM_PAINT - 绘制主窗口 // WM_DESTROY - 发送退出消息并返回 // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static LOGFONT lf;//逻辑字体结构 static HFONT hOrgFont, hFont;//字体句柄 switch (message) { case WM_CREATE: //lf.lfCharSet = 1;//字符集 1 默认系统字符集 //lf.lfClipPrecision = 0;//0 表示不剪裁 //lf.lfEscapement = 0;//角度 设为0 表示水平的 //lstrcpy(lf.lfFaceName, TEXT("黑体"));//字体名称 //lf.lfHeight = 60;//字体高度 //lf.lfItalic = 0;//字体是否斜体 //lf.lfOrientation = 0;//每个字的方向 //lf.lfOutPrecision = 0;//字体匹配的精度 //lf.lfPitchAndFamily = 0;// 字体宽度和字体家族 //lf.lfQuality = 0;//字体的质量 点整字体使用 //lf.lfStrikeOut = 0;//字体上有没有删除线 //lf.lfUnderline = 0;//字体下划线 //lf.lfWeight = 0;//字体的粗细 //lf.lfWidth = 0;//字体的宽度 //hFont = CreateFontIndirect(&lf);//创建字体 //hFont = CreateFont(80,0,0,0,0,0,0,0,0,0,0,0,0,TEXT("楷体_GB2312")); hFont = (HFONT)GetStockObject(SYSTEM_FONT);//库存字体 break; case WM_COMMAND: { int wmId = LOWORD(wParam); // 分析菜单选择: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); // TODO: 在此处添加使用 hdc 的任何绘图代码... hOrgFont = (HFONT)SelectObject(hdc, hFont); TextOut(hdc, 100, 200, TEXT("爱白菜的小昆虫"), 7); SelectObject(hdc, hOrgFont);//将原来的字体绑定 DeleteObject(hFont);//删除创建的字体 EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // “关于”框的消息处理程序。 INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
true
f44703194f2de3c1552c489ff1853fdf0201d67a
C++
Abdullah-Al-Zishan/C-Multi-threading
/condition_variable_and_threads.cpp
UTF-8
3,626
3.234375
3
[]
no_license
#include <queue> #include <iostream> #include <chrono> #include <thread> #include <mutex> #include <random> #include <condition_variable> bool done; bool notify; std::mutex print_mutex; std::mutex queue_mutex; std::queue<int> error_log; std::condition_variable cond; void worker_function(int id, std::mt19937 &generator) { /* prints the id of the worker and says that it works */ { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "[worker" << id << "]\trunning ...." << std::endl; } /* simulating of the work, making some random delay */ std::this_thread::sleep_for(std::chrono::seconds(1 + generator() % 5)); /* simulating of an error occurrance */ { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "[worker " << id << "]\tan arror occured ..." << std::endl; } /* reporting an error and adding it to the queue */ int err_code = (1 + generator() % 5) * 100 + 1; { std::unique_lock<std::mutex> locker(queue_mutex); error_log.push(err_code); notify = true; cond.notify_one(); } } void logger_function(void) { /* starting message */ { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "[logger]\trunning ...." << std::endl; } /* while the signal will be passed */ while (!done) { std::unique_lock<std::mutex> locker(queue_mutex); /* to avoid spurious wakeup */ while (!notify) cond.wait(locker); /* used another overloaded version of the cond.wait(locker, predicate); cond.wait(locker, [&]() { return !(error_log.empty()); }); */ while (!error_log.empty()) { std::unique_lock<std::mutex> qlock(print_mutex); std::cout << "[logger]\tprocessing error: " << error_log.front() << std::endl; error_log.pop(); } notify = false; } } std::mutex lock; std::condition_variable cond_var; void worker_function2(std::mt19937 &generator) { /* prints the id of the worker and says that it works */ { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "[worker]\trunning ...." << std::endl; } /* simulating of the work, making some random delay */ std::this_thread::sleep_for(std::chrono::seconds(1 + generator() % 5)); { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "[worker]\tfinished ..." << std::endl; } std::unique_lock<std::mutex> ulock(lock); done = true; std::notify_all_at_thread_exit(cond_var, std::move(ulock)); } int main() { /* initialising a random number generator */ std::mt19937 generator((unsigned int)std::chrono::system_clock::now().time_since_epoch().count()); /* running of a logger */ std::thread log_thread(logger_function); /* running of workers */ std::vector<std::thread> workers; for (int i = 0; i < 5; i++) workers.push_back(std::thread(worker_function, i + 1, std::ref(generator))); for (auto &e : workers) e.join(); done = true; log_thread.join(); std::cout << "main running..." << std::endl; std::thread worker(worker_function2, std::ref(generator)); worker.detach(); std::cout << "main crunching..." << std::endl; std::this_thread::sleep_for(std::chrono::seconds(1 + generator() % 5)); { std::unique_lock<std::mutex> locker(print_mutex); std::cout << "main waiting for worker..." << std::endl; } std::unique_lock<std::mutex> lock(lock); while (!done) cond_var.wait(lock); std::cout << "main finished..." << std::endl; std::cin.get(); return (0); }
true
d71f6f79b1558e4c809ca6b9212d893d3d43ae7a
C++
elsenorchris/SubCparser
/LexicalAnalysis.h
UTF-8
563
2.59375
3
[]
no_license
// LexicalAnalysis.h: interface for the LexicalAnalysis class. // ////////////////////////////////////////////////////////////////////// #if !defined(_LA_) #define _LA_ #include <iostream> #include <fstream> #include <string> #include <unordered_map> using namespace std; class LexicalAnalysis { public: char nextChar; int charClass; string lexeme; private: ifstream *fp; public: int lex(); LexicalAnalysis(ifstream *fp); virtual ~LexicalAnalysis(); private: void addChar(); void getChar(); }; #endif
true
0a90c6fab35d45c87845e8ea311681ed22be91d4
C++
insidepower/cpptest
/littleBigEndianTest/Cpp1.cpp
UTF-8
804
3.140625
3
[]
no_license
#include <iostream> #include <iomanip> using namespace std; typedef struct t_my{ unsigned int a; t_my * next; } t_my; typedef struct { unsigned short b; unsigned short c; t_my * d; } t_myy; char alpha[]= "abcdefghijklmnopqrstuvwxyz"; char * p_alpha = alpha; int main(void){ t_my u; u.a = 0x77558855; t_myy * m; m = (t_myy *) &u; cout << hex << m->b << endl; cout << hex << m->c << endl; t_myy * m2 = (t_myy *) p_alpha; t_myy m3; cout << hex << "alpha offset 2 bytes is = " << ((t_myy *) p_alpha)->c << endl; cout << hex << "alpha offset 2 bytes is = " << m2->c << endl; m3.b = 2; m3.c = 3; m3.d = &u; cout << m3.d->a << endl; t_my u2; u2.a = 0x77558866; m3.d->next = &u2; cout << m3.d->next->a << endl; return 0; }
true
e38977af12af8dc498c4b799ceb577bb43d2dc68
C++
jeffmeese/qtep
/core/commandlineoption.cpp
UTF-8
2,985
3.21875
3
[]
no_license
#include "commandlineoption.h" #include <algorithm> CommandLineOption::CommandLineOption(const std::string & name) { init({name}, ""); } CommandLineOption::CommandLineOption(const std::vector<std::string> & names) : mNames(names) { init(names, ""); } CommandLineOption::CommandLineOption(const std::string & name, const std::string & description, const std::string & valueName, const std::string & defaultValue) { init(std::vector<std::string>{name}, description, valueName, defaultValue); } CommandLineOption::CommandLineOption(const std::vector<std::string> & names, const std::string & description, const std::string & valueName, const std::string & defaultValue) { init(names, description, valueName, defaultValue); } CommandLineOption::CommandLineOption(const CommandLineOption & other) { *this = other; } CommandLineOption::~CommandLineOption() { } std::vector<std::string> CommandLineOption::defaultValues() const { return mDefaultValues; } std::string CommandLineOption::description() const { return mDescription; } CommandLineOption::Flags CommandLineOption::flags() const { return mFlags; } void CommandLineOption::init(const std::vector<std::string> & names, const std::string & description, const std::string & valueName, const std::string & defaultValue) { mNames = names; mValueName = valueName; mDescription = description; mFlags = None; if (!defaultValue.empty()) { mDefaultValues.push_back(defaultValue); } } std::vector<std::string> CommandLineOption::names() const { return mNames; } void CommandLineOption::setDefaultValue(const std::string & defaultValue) { std::vector<std::string> values; values.push_back(defaultValue); setDefaultValues(values); } void CommandLineOption::setDefaultValues(const std::vector<std::string> & defaultValues) { mDefaultValues = defaultValues; } void CommandLineOption::setDescription(const std::string & description) { mDescription = description; } void CommandLineOption::setFlags(Flags flags) { mFlags = flags; } void CommandLineOption::setValueName(const std::string & valueName) { mValueName = valueName; } void CommandLineOption::swap(const CommandLineOption & other) { //std::swap(*this, other); } std::string CommandLineOption::valueName() const { return mValueName; } CommandLineOption & CommandLineOption::operator =(const CommandLineOption & other) { if (this == &other) return *this; mNames = other.names(); mDescription = other.description(); mDefaultValues = other.defaultValues(); mFlags = other.flags(); mValueName = other.valueName(); return *this; } CommandLineOption & CommandLineOption::operator =(CommandLineOption && other) { if (this == &other) return *this; mNames = other.names(); mDescription = other.description(); mDefaultValues = other.defaultValues(); mFlags = other.flags(); mValueName = other.valueName(); return *this; }
true
895e375e04d0d7966a75bfde127d6b9701919dff
C++
joonlee701/-
/astar/astar_pathfinding.cpp
UTF-8
5,117
3.140625
3
[]
no_license
#include <iostream> #include <fstream> #include <sstream> #include <string> #include <time.h> #include <vector> using namespace std; #define length 200 #define blocked 1 #define open 0 #define visited 2 #define start 0 #define finish 39999 class searchNode{ private: struct NODE{ int parent; int h,f,g; int state; }; vector <int> openList; vector <NODE*> map; bool success; public: int getHvalue(int); bool checkState(int, int); void readFile(); void build(); void findPath(); void insert(int); void setRoot(); void printResult(); void printMap(); void checkSuccess(); }; void searchNode::build() { setRoot(); while(!success) { findPath(); } } void searchNode::readFile() { ifstream instream("Map.txt"); string line,block; while(getline(instream,line)) { istringstream linestream(line); while(getline(linestream, block, ',')) { NODE *n = new NODE; n->state = atoi(block.c_str()); map.push_back(n); } } } void searchNode::setRoot() { success = false; map[start]->g = 0; map[start]->h = getHvalue(0); map[start]->f = map[start]->h; map[start]->parent = -1; map[start]->state = visited; openList.push_back(start); } bool searchNode::checkState(int index, int preindex) { bool state = true; if(map[index]->state == blocked) { state = false; } if(map[index]->state == visited) { if(map[preindex]->g + 14 > map[index]->g) state = false; } return state; } void searchNode::printResult(){ int a; a = finish; while(a != start) { cout << a <<endl; map[a]->state = 9; a = map[a]->parent; } cout << start <<endl; cout << "cost : " << map[finish]->f; } void searchNode::printMap() { ofstream outstream("outMap.txt"); for(int i = 0; i < map.size() - 1; i++) { outstream << map[i]->state << " "; if(i % 200 == 199) outstream << endl; } } void searchNode::findPath() { int index = openList.front(); openList.erase(openList.begin()); if(index/length != 0 && index%length != length-1 && checkState(index-length +1, index)) { int ru = index - length + 1; map[ru]->f = map[index]->f + 13; getHvalue(ru); map[ru]->g = map[ru]->f + map[ru]->h; map[ru]->parent = index; map[ru]->state = visited; insert(ru); } if(index%length != length-1 && checkState(index+1, index) ) { int r = index + 1; map[r]->f = map[index]->f + 10; getHvalue(r); map[r]->g = map[r]->f + map[r]->h; map[r]->parent = index; map[r]->state = visited; insert(r); } if(index/length != length-1 && index%length != length-1 && checkState(index+length+1, index)) { int rd = index + length + 1; map[rd]->f = map[index]->f + 13; getHvalue(rd); map[rd]->g = map[rd]->f + map[rd]->h; map[rd]->parent = index; map[rd]->state = visited; insert(rd); } if(index/length != length-1 && checkState(index+length, index)) { int d = index + length; map[d]->f = map[index]->f + 10; getHvalue(d); map[d]->g = map[d]->h + map[d]->f; map[d]->parent = index; map[d]->state = visited; insert(d); } if(index/length != 199 && index%length != 0 && checkState(index+length-1, index)) { int ld = index + length - 1; map[ld]->f = map[index]->f + 13; getHvalue(ld); map[ld]->g = map[ld]->f + map[ld]->h; map[ld]->parent = index; map[ld]->state = visited; insert(ld); } if(index%length != 0 && checkState(index-1, index)) { int l = index - 1; map[l]->f = map[index]->f + 10; getHvalue(l); map[l]->g = map[l]->h + map[l]->f; map[l]->parent = index; map[l]->state = visited; insert(l); } if(index/length != 0 && index%length != 0 &&checkState(index-length-1, index)) { int lu = index - length - 1; map[lu]->f = map[index]->f + 13; getHvalue(lu); map[lu]->g = map[lu]->f + map[lu]->h; map[lu]->parent = index; map[lu]->state = visited; insert(lu); } if(index/length != 0 && checkState(index-length, index)) { int u = index - length; map[u]->f= map[index]->f + 10; getHvalue(u); map[u]->g = map[u]->f + map[u]->h; map[u]->parent = index; map[u]->state = visited; insert(u); } checkSuccess(); } void searchNode::checkSuccess() { for(int i = 0; i < openList.size(); i++) if(openList[i] == finish) success = true; if(success) { printResult(); } } int searchNode::getHvalue(int index) { int x_coord, y_coord, differ; x_coord = 199 - (index % length); y_coord = 199 - (index / length); differ = abs(x_coord - y_coord); return (differ * 10) + (abs(x_coord - differ) * 14); } void searchNode::insert(int index) { int m, temp; if(openList.size() == 0) openList.push_back(index); else { openList.push_back(index); for(m = openList.size() - 1; m!=0;){ if (map[openList[m]]->f <= map[openList[m/2]]->f){ temp = openList[m/2]; openList[m/2] = openList[m]; openList[m] = temp; m = m/2; } else break; } } } void main() { searchNode startNode; clock_t startTime, endTime; vector <int> num; startTime = clock(); startNode.readFile(); startNode.build(); endTime = clock(); startNode.printMap(); cout << "Time : " << (double)(endTime - startTime)/CLOCKS_PER_SEC << endl; return; }
true
ed8e1790da5c757bd92c6a3725dd5bd3bf938ebd
C++
TrieBr/GMIDE
/GMIDE/GMAsset_Sprite.h
UTF-8
2,926
2.859375
3
[]
no_license
#ifndef GMASSET_SPRITE_H #define GMASSET_SPRITE_H #include "GMAsset.h" #include <QFile> //Bounding box modes enum BoundingBoxMode { Automatic = 0, FullImage = 1, Manual = 2 }; //Collision kinds enum CollisionKind { Precise = 0, Rectangle = 1, Ellipse = 2, Diamond = 3 }; /* * Sprite Asset * * */ class GMAsset_Sprite : public GMAsset { public: //Constructor GMAsset_Sprite(); //Load the asset from the specified file virtual bool Load(const QFileInfo &file); //Get the pixmap icon for this asset virtual QPixmap GetPixmap(); //Create an editor for this asset virtual QSharedPointer<AssetEditor> CreateEditor(); //Accessors for type of sprite int GetType() const; void SetType(int value); //Origin accessors QPoint GetOrigin() const; void SetOrigin(const QPoint &value); //Accessors for Color Kind CollisionKind GetCollisionKind() const; void SetCollisionKind(CollisionKind value); //Accessors for Color Tolerance int GetColTolerance() const; void SetColTolerance(int value); //Accessors for Seperation Masks bool GetSepMasks() const; void SetSepMasks(bool value); //Accessors for BBox Mode BoundingBoxMode GetBboxMode() const; void SetBboxMode(BoundingBoxMode value); //Accessors for BBox QRect GetBbox() const; void SetBbox(const QRect &value); //Accessors for Horizontal Tile (Texture Settings) bool GetHTile() const; void SetHTile(bool value); //Accessors for Vertical Tile (Texture Settings) bool GetVTile() const; void SetVTile(bool value); //Accessors for For 3D (Texture Settings) bool GetFor3D() const; void SetFor3D(bool value); //Accessors Size of the sprite QSize GetSize() const; void SetSize(const QSize &value); //Get number of frames in this sprite int GetFrameCount(); //Get pixmap for specified frame index (will load from disk) QPixmap GetFramePixmap(int frameIndex); private: //Sprite Properties int type; //Type of sprite QPoint origin; //Origin CollisionKind collisionKind; //Collision Kind int colTolerance; //Color Tolerance bool sepMasks; //Seperate collision masks BoundingBoxMode bboxMode; //Bounding Box mode QRect bbox; //Bounding box size bool hTile; //Texture Settings: Tile: Horizontal bool vTile; //Texture Settings: Tile: Vertical bool for3D; //Texture Settings: Used for 3D (Must be a power of 2) QSize size; //Dimensions os sprite; QList<QFileInfo> frames; //Frames in the sprite (List of Pixmaps) }; #endif // GMASSET_SPRITE_H
true
61fa90eea8cf1e44e022c8f14d4b8c36db3734e1
C++
Joshitha18/problem-solving
/platforms/Leetcode/DailyChallenge/March/4_LinkedList_Intersection/ll_intersection_2.cpp
UTF-8
632
3.421875
3
[]
no_license
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void sign(ListNode *head) { ListNode *temp=head; while(temp) { temp->val *= -1; temp = temp->next; } } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { sign(headA); ListNode *tempB=headB; while(tempB){ if (tempB->val < 0) break; tempB=tempB->next; } sign(headA); return tempB; } };
true
047e032c19027971c3c44ba6f986ccca30f0e23e
C++
CloudNartiveProjects/SEAL
/native/src/seal/util/polycore.h
UTF-8
6,238
2.71875
3
[ "MIT", "CC0-1.0" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #pragma once #include "seal/util/common.h" #include "seal/util/pointer.h" #include "seal/util/uintcore.h" #include <algorithm> #include <cstdint> #include <cstring> #include <limits> #include <sstream> #include <stdexcept> namespace seal { namespace util { SEAL_NODISCARD inline std::string poly_to_hex_string( const std::uint64_t *value, std::size_t coeff_count, std::size_t coeff_uint64_count) { #ifdef SEAL_DEBUG if (!value) { throw std::invalid_argument("value"); } #endif // First check if there is anything to print if (!coeff_count || !coeff_uint64_count) { return "0"; } std::ostringstream result; bool empty = true; value += util::mul_safe(coeff_count - 1, coeff_uint64_count); while (coeff_count--) { if (is_zero_uint(value, coeff_uint64_count)) { value -= coeff_uint64_count; continue; } if (!empty) { result << " + "; } result << uint_to_hex_string(value, coeff_uint64_count); if (coeff_count) { result << "x^" << coeff_count; } empty = false; value -= coeff_uint64_count; } if (empty) { result << "0"; } return result.str(); } SEAL_NODISCARD inline std::string poly_to_dec_string( const std::uint64_t *value, std::size_t coeff_count, std::size_t coeff_uint64_count, MemoryPool &pool) { #ifdef SEAL_DEBUG if (!value) { throw std::invalid_argument("value"); } #endif // First check if there is anything to print if (!coeff_count || !coeff_uint64_count) { return "0"; } std::ostringstream result; bool empty = true; value += coeff_count - 1; while (coeff_count--) { if (is_zero_uint(value, coeff_uint64_count)) { value -= coeff_uint64_count; continue; } if (!empty) { result << " + "; } result << uint_to_dec_string(value, coeff_uint64_count, pool); if (coeff_count) { result << "x^" << coeff_count; } empty = false; value -= coeff_uint64_count; } if (empty) { result << "0"; } return result.str(); } SEAL_NODISCARD inline auto allocate_poly( std::size_t coeff_count, std::size_t coeff_uint64_count, MemoryPool &pool) { return allocate_uint(util::mul_safe(coeff_count, coeff_uint64_count), pool); } inline void set_zero_poly(std::size_t coeff_count, std::size_t coeff_uint64_count, std::uint64_t *result) { #ifdef SEAL_DEBUG if (!result && coeff_count && coeff_uint64_count) { throw std::invalid_argument("result"); } #endif set_zero_uint(util::mul_safe(coeff_count, coeff_uint64_count), result); } SEAL_NODISCARD inline auto allocate_zero_poly( std::size_t coeff_count, std::size_t coeff_uint64_count, MemoryPool &pool) { return allocate_zero_uint(util::mul_safe(coeff_count, coeff_uint64_count), pool); } SEAL_NODISCARD inline auto allocate_poly_array( std::size_t poly_count, std::size_t coeff_count, std::size_t coeff_uint64_count, MemoryPool &pool) { return allocate_uint(util::mul_safe(poly_count, coeff_count, coeff_uint64_count), pool); } inline void set_zero_poly_array( std::size_t poly_count, std::size_t coeff_count, std::size_t coeff_uint64_count, std::uint64_t *result) { #ifdef SEAL_DEBUG if (!result && poly_count && coeff_count && coeff_uint64_count) { throw std::invalid_argument("result"); } #endif set_zero_uint(util::mul_safe(poly_count, coeff_count, coeff_uint64_count), result); } SEAL_NODISCARD inline auto allocate_zero_poly_array( std::size_t poly_count, std::size_t coeff_count, std::size_t coeff_uint64_count, MemoryPool &pool) { return allocate_zero_uint(util::mul_safe(poly_count, coeff_count, coeff_uint64_count), pool); } inline void set_poly( const std::uint64_t *poly, std::size_t coeff_count, std::size_t coeff_uint64_count, std::uint64_t *result) { #ifdef SEAL_DEBUG if (!poly && coeff_count && coeff_uint64_count) { throw std::invalid_argument("poly"); } if (!result && coeff_count && coeff_uint64_count) { throw std::invalid_argument("result"); } #endif set_uint(poly, util::mul_safe(coeff_count, coeff_uint64_count), result); } inline void set_poly_array( const std::uint64_t *poly, std::size_t poly_count, std::size_t coeff_count, std::size_t coeff_uint64_count, std::uint64_t *result) { #ifdef SEAL_DEBUG if (!poly && poly_count && coeff_count && coeff_uint64_count) { throw std::invalid_argument("poly"); } if (!result && poly_count && coeff_count && coeff_uint64_count) { throw std::invalid_argument("result"); } #endif set_uint(poly, util::mul_safe(poly_count, coeff_count, coeff_uint64_count), result); } } // namespace util } // namespace seal
true
2eb66e59f08d5209aeeefa07debea7ce21e3575a
C++
DreamDreames/OJ
/LeetCode/79_Word_Search.cpp
UTF-8
2,107
3.484375
3
[]
no_license
#include "shared.h" /* Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. For example, Given board = [ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ] word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false. */ namespace WordSearch { class Solution { public: bool exist(vector<vector<char>>& board, string word) { if(word.empty()) return true; if(board.size() == 0) return false; vector<vector<bool>> status(board.size(), vector<bool>(board[0].size(), false)); map<char, vector<pair<int,int>>> records; for(int i = 0; i < board.size(); ++ i){ for(int j = 0; j < board[i].size(); ++ j){ if(word[0] == board[i][j]){ if(search(board, status, word, 0, i, j)) return true; } } } return false; } private: bool search(vector<vector<char>>& board, vector<vector<bool>>& status, string& word, int start, int x, int y){ if(start == word.size()) return true; if(x < 0 || x >= board.size() || y < 0 || y >= board[0].size()) return false; if(status[x][y] || word[start] != board[x][y]) return false; status[x][y] = true; if (search(board, status, word, start + 1, x + 1, y) || search(board, status, word, start + 1, x, y + 1) || search(board, status, word, start + 1, x - 1, y) || search(board, status, word, start + 1, x, y - 1)) return true; status[x][y] = false; return false; } }; }
true
3b1fa93fc8d4ed15b6e578ba11cf2898d5107459
C++
BishuPoonia/coding
/CPP/Pattern/pattern.cpp
UTF-8
903
3.171875
3
[]
no_license
#include <iostream> using namespace std; int main() { // Pattern #1 cout << "Pattern no. 1:" << endl; int a, b; for (a = 1; a <= 9; a++){ for (b = 1; b <= a; b++){ cout << a; } cout << "\n"; } // Pattern #2 cout << "\n\nPattern no. 2" << endl; int c, d; for (c = 1; c <= 9; c++){ for (d = 1; d <= c; d++){ cout << d; } cout << "\n"; } // Pattern #3 cout << "\n\nPattern no. 3" << endl; int e, f; for (e = 1; e <= 9; e++){ for (f = 1; f <= e + e; f++){ cout << f++; } cout << "\n"; } // Pattern #4 cout << "\n\nPattern no. 4" << endl; int g, h; for (g = 0; g <= 9; g++){ for (h = 0; h <=g; h++){ cout << h%2; } cout << "\n"; } return 0; }
true
307f36a8ef72e8bd26818bbcf2c4febaecc786ac
C++
getState/Algorithm
/코드플러스중급1/그리디/가장긴증가하는부분수열2.cpp
UTF-8
553
2.578125
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <algorithm> using namespace std; vector<int> arr; vector<int> dp; int N; int main() { cin >> N; int input; for (int i = 0; i < N; i++) { cin >> input; arr.push_back(input); } for (int i = 0; i < N; i++) { auto it = lower_bound(dp.begin(), dp.end(), arr[i]); if (it != dp.end()) { *it = arr[i]; } else { dp.push_back(arr[i]); } } cout << dp.size() << endl; }
true
8c0eef1e6c39fba8d8b2475c3a104a0958a40c04
C++
hgedek/cpp-samples
/literaltype.cpp
UTF-8
866
3.875
4
[]
no_license
// constexpr types are literal types // int float char ... // you can define your literal type [ constexpr ctor ] #include <iostream> struct ConstStr { const char* ptr_; std::size_t size_; template <size_t N> constexpr ConstStr(const char (&a)[N]): ptr_(a), size_(N) {} constexpr const char* data() const { return ptr_; } constexpr char operator[](unsigned index) { return ptr_[index]; } constexpr std::size_t size() const { return size_; } }; constexpr std::size_t countlower(ConstStr str,unsigned index = 0, size_t count = 0) { if ( index >= str.size()) return count; if ( str[index] >= 'a' && str[index] <= 'z' ) return countlower(str, ++index, ++count); else return countlower(str, ++index, count); } int main() { constexpr auto count = countlower("sample text"); std::cout << count << std::endl; }
true
10626e3c47a1c405d0a0ad03f5c5b58811007239
C++
sharkofsteppe/Cpp_modules
/cpp_module_03/ex03/DiamondTrap.cpp
UTF-8
1,493
3.046875
3
[]
no_license
#include "DiamondTrap.hpp" DiamondTrap::DiamondTrap( std::string name ) : ClapTrap( name + "_clap_name" ), _Name( name ) { this->setHP(getFragsHP()); this->setAD(getFragsAD()); std::cout << "DiamondTrap constructor have done the work" << std::endl; } DiamondTrap::DiamondTrap( void ) : ClapTrap( "Default_clap_name"), _Name("DEFAULT") { std::cout << "DiamondTrap Default constructor have done the work" << std::endl; } DiamondTrap::~DiamondTrap() { std::cout << "DiamondTrap Destructor have done the work" << std::endl; } DiamondTrap::DiamondTrap( DiamondTrap const & ref ) { std::cout << "DiamondTrap Copy constructor worked here" << std::endl; *this = ref; } DiamondTrap & DiamondTrap::operator=( DiamondTrap const &ref ) { std::cout << "Assignation operator called " << std::endl; this->_Name = ref.getName(); this->_Hitpoints = ref.getHP(); this->_EnergyPoints = ref.getEP(); this->_AttackDamage = ref.getAD(); return (*this); } void DiamondTrap::WhoAmI( void ) const { std::cout << "DIAMONDTRAPS NAME :" << this->_Name << std::endl; std::cout << "_________________________________________________" << std::endl; showConditions(); std::cout << "FOR CHECK: HP of FRAGTRAPS = 100. AD of FRAGTRAPS = 30. EP of SCAVTRAP = 50" << std::endl; } unsigned int DiamondTrap::getFragsHP( void ) const { return (this->fragHP); } unsigned int DiamondTrap::getFragsAD() const { return (this->fragAD); }
true
a86ccf91cb653e458326d5d85c6b9a716f4ddefc
C++
miquelgalianallorca/Navmesh
/game/pathfinding/pathNavmesh.cpp
UTF-8
5,994
2.921875
3
[]
no_license
#include <stdafx.h> #include <algorithm> #include "pathNavmesh.h" #include "pugixml/pugixml.hpp" PathNavmesh::PathNavmesh() : isStepByStepModeOn(false), startNode(nullptr), endNode(nullptr), navmesh(nullptr) {} PathNavmesh::~PathNavmesh() { navmesh = nullptr; for (Node* node : nodes) delete node; nodes.clear(); path.clear(); } void PathNavmesh::Load(std::vector<Pathfinder::NavPolygon>* _navmesh, std::vector<Pathfinder::Link>* _links) { navmesh = _navmesh; links = _links; // Clear previous nodes for (Node* node : nodes) delete node; nodes.clear(); // Get nodes from navmesh for (unsigned i = 0; i < navmesh->size(); ++i) { Pathfinder::NavPolygon& polygon = navmesh->at(i); // Each polygon is a node Node* node = new Node(); node->cost = 1; node->navmeshIndex = i; // Node position: centroid of verts USVec2D centroid(0.f, 0.f); for (const USVec2D& vert : polygon.m_verts) centroid += vert; centroid /= static_cast<float>(polygon.m_verts.size()); node->pos = centroid; nodes.push_back(node); } } void PathNavmesh::ResetNodes() { for (Node* node : nodes) { node->parent = nullptr; node->g = 0.f; node->f = 0.f; } path.clear(); openList.clear(); closedList.clear(); } // Heuristics: Euclidean distance. Manhattan could give longer paths than necessary. // Start and end in screen coords bool PathNavmesh::AStar(USVec2D start, USVec2D end) { /* openlist closedlist add nodeInicio a openlist, coste 0 while not openlist.vacio nodo = openlist.pop_shortest() if isGoal(nodo) return buildPath(nodo) else for nextNode : conexiones(node) if nextNode in closedlist continue if nextNode in openlist update cost in openlist if smaller else add to openlist con padre node buildPath(pathnode) while(padre(pathNode)) add node(pathNode) to path return path */ ResetNodes(); endPos = end; // Set start & end nodes startNode = GetClosestNode(start); endNode = GetClosestNode(end); if (!startNode || !endNode) return false; openList.push_back(startNode); if (!isStepByStepModeOn) { while (openList.size() > 0) { bool Step = AStarStep(); if (Step) return true; } } return false; } PathNavmesh::Node* PathNavmesh::GetClosestNode(const USVec2D& pos) const { Node* closestNode = nullptr; float closestDist = 99999.f; for (Node* node : nodes) { const float dist = node->pos.Dist(pos); if (dist < closestDist) { closestNode = node; closestDist = dist; } } return closestNode; } bool PathNavmesh::AStarStep() { // Get shortest openList.sort(PathNavmesh::OrderByShortest); Node* node = openList.front(); // Check goal if (node == endNode) { BuildPath(node); return true; } openList.pop_front(); // Connections std::list<Node*> connections = GetConnections(node); for (Node* next : connections) { // Connection is in closed list auto it = std::find(closedList.begin(), closedList.end(), next); if (it != closedList.end()) { continue; } // Connection is in open list it = std::find(openList.begin(), openList.end(), next); if (it != openList.end()) { // Update cost in open list if smaller const float newCost = node->g + next->cost; if (newCost < (*it)->g) { (*it)->g = newCost; (*it)->parent = node; } } // Add to openlist with node as parent else { next->parent = node; next->g = next->cost + node->g; next->f = next->g + Heuristics(next, endNode); openList.push_back(next); closedList.push_back(node); } } return false; } void PathNavmesh::DrawDebug() { MOAIGfxDevice& gfxDevice = MOAIGfxDevice::Get(); gfxDevice.SetPenColor(1.f, 0.f, .5f, 1.f); // Draw points to follow for (unsigned i = 0; i < pathPoints.size(); ++i) { USVec2D& pos = pathPoints.at(i); USRect rect; rect.mXMin = pos.mX - 6.f; rect.mXMax = pos.mX + 6.f; rect.mYMin = pos.mY - 6.f; rect.mYMax = pos.mY + 6.f; MOAIDraw::DrawEllipseFill(rect, 6); if (i < pathPoints.size() - 1) MOAIDraw::DrawLine(pos, pathPoints.at(i + 1)); } } std::list<PathNavmesh::Node*> PathNavmesh::GetConnections(const Node* node) { // cout << "Get connections of: " << posX << " " << posY; std::list<Node*> connections; if (!node) return connections; const Pathfinder::NavPolygon& polygon = navmesh->at(node->navmeshIndex); for (const Pathfinder::NavPolygon::Edge& edge : polygon.m_Edges) { const int neighbourIndex = edge.m_neighbourIndex; for (Node* n : nodes) { if (n->navmeshIndex == neighbourIndex) { connections.push_back(n); break; } } } return connections; } void PathNavmesh::BuildPath(Node* node) { path.clear(); pathPoints.clear(); std::cout << "Building path..." << endl; pathPoints.push_back(endPos); while (node->parent != nullptr) { path.push_back(node); // Locations for pathfollowing pathPoints.push_back(node->pos); if (node->parent) pathPoints.push_back(GetMidEdgePoint(node)); node = node->parent; } path.push_back(node); pathPoints.push_back(startNode->pos); std::cout << "Path built." << endl; } float PathNavmesh::Heuristics(const Node* next, const Node* goal) const { USVec2D nextPos = next->pos; USVec2D goalPos = goal->pos; return nextPos.Dist(goalPos); } USVec2D PathNavmesh::GetMidEdgePoint(const Node* node) const { USVec2D point; const int nodeIndex = node->navmeshIndex; const int parentIndex = node->parent->navmeshIndex; for (auto& edge : navmesh->at(parentIndex).m_Edges) { if (edge.m_neighbourIndex == nodeIndex) { point = edge.m_center; break; } } return point; }
true
b1d961409e6325e575c964699db95588b290d9cc
C++
ckobylko/HIPAccBenchmark
/src/MinMaxDetector/MinMaxDetector.cpp
UTF-8
559
2.78125
3
[]
no_license
#include "../../include/MinMaxDetector/MinMaxDetector.h" #include <stdexcept> #include <stdio.h> void MinMaxDetector::Run(unsigned int uiKernelSize) { if (uiKernelSize < 3) { throw std::runtime_error( "The kernel size must be greater than or equal to 3!" ); } else if ((uiKernelSize & 1) == 0) { throw std::runtime_error("The kernel size must be odd!"); } printf( "\n Running \"MinMaxDetector\" - Kernel-size= %d:\n", uiKernelSize ); _RunFloat(uiKernelSize); _RunUInt8(uiKernelSize); printf("\n"); }
true
61fcc3da8fdf1b2fc1d60d523545fe0d48182df4
C++
hachi-88/atcoder
/abc/111/abc111c.cpp
UTF-8
1,536
2.90625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int f(vector<pair<int, int>> v1, vector<pair<int, int>> v2, int n) { int ans = 0; ans += (n / 2 - v1[0].first); if (v1[0].second != v2[0].second) { ans += (n / 2 - v2[0].first); } else { if (v2.size() > 1) { ans += (n / 2 - v2[1].first); } else { ans += (n / 2); } } return ans; } int main() { unordered_map<int, int> m1; unordered_map<int, int> m2; int n; cin >> n; for (int i = 0; i < n; i++) { int _v; cin >> _v; if (i % 2) { if (m1.find(_v) == m1.end()) { m1[_v] = 1; } else { m1[_v]++; } } else { if (m2.find(_v) == m2.end()) { m2[_v] = 1; } else { m2[_v]++; } } } vector<pair<int, int>> v1; vector<pair<int, int>> v2; for (auto m : m1) { v1.push_back({m.second, m.first}); } for (auto m : m2) { v2.push_back({m.second, m.first}); } sort(v1.begin(), v1.end(), greater<pair<int, int>>()); sort(v2.begin(), v2.end(), greater<pair<int, int>>()); int ans = 0; if (v1[0].first > v2[0].first) { ans += f(v1, v2, n); } else if (v1[0].first < v2[0].first) { ans += f(v2, v1, n); } else { int a = f(v1, v2, n); int b = f(v2, v1, n); ans += min(a, b); } cout << ans << endl; return 0; }
true
74fe33021b65f3bce1a7b562995f68148a0b9409
C++
abhigrover101/leetcode
/all palindromes.cpp
UTF-8
1,228
3.28125
3
[]
no_license
#include<iostream> #include<string> #include<vector> using namespace std; bool isPalindrome(string s,int i,int j){ while(i<j && s[i]==s[j]){ i++; j--; continue; } if(i>=j) return true; return false; } void palindromes(string s,int start,vector<string> &ans,vector<vector<string> > &all){ if(start >= s.length()){ all.push_back(ans); //ans.clear(); return; } int i = start; for(i=start;i<s.length();i++){ if(isPalindrome(s,start,i)){ ans.push_back(s.substr(start,i-start+1)); palindromes(s,i+1,ans,all); ans.pop_back(); } } return; } vector<vector<string> > allpalindromes(string s){ vector<string> ans; vector<vector<string> > all; palindromes(s,0,ans,all); return all; } int main(){ string s; cin>>s; vector<vector<string> > ans; ans = allpalindromes(s); int i=0,j; for(i=0;i<ans.size();i++){ for(j=0;j<ans[i].size();j++) cout<<ans[i][j]<<" "; cout<<endl; } return 0; }
true
aaaec0729b129310bf23caa88a6ccb38af908dcf
C++
sopyer/Shadowgrounds
/storm/storm3dv2/Clipper.cpp
UTF-8
1,665
2.609375
3
[]
no_license
// Copyright 2002-2004 Frozenbyte Ltd. #ifdef _MSC_VER #pragma warning(disable:4103) #endif //------------------------------------------------------------------ // Includes //------------------------------------------------------------------ #include "storm3d.h" #include "VertexFormats.h" #include "../../util/Debug_MemoryManager.h" //------------------------------------------------------------------ // Clip2DRectangle // Returns false if rectancle is completely outside screen //------------------------------------------------------------------ bool Clip2DRectangle(Storm3D *st,Vertex_P2DUV &ul,Vertex_P2DUV &dr) { // Get Screen coordinates Storm3D_SurfaceInfo ss=st->GetScreenSize(); int sxm=0; int sym=0; // Cull if (ul.p.x>dr.p.x) return false; if (ul.p.y>dr.p.y) return false; // Check if completely outside screen if (ul.p.x>(ss.width-1)) return false; if (ul.p.y>(ss.height-1)) return false; if (dr.p.x<sxm) return false; if (dr.p.y<sym) return false; // Test up-left X (ul) if (ul.p.x<sxm) { float tcp=(dr.uv.x-ul.uv.x)/(dr.p.x-ul.p.x); ul.uv.x += tcp*(sxm-ul.p.x); ul.p.x = float(sxm); } // Test up-left Y (ul) if (ul.p.y<sym) { float tcp=(dr.uv.y-ul.uv.y)/(dr.p.y-ul.p.y); ul.uv.y += tcp*(sym-ul.p.y); ul.p.y = float(sym); } // Test down-right X (dr) if (dr.p.x>(ss.width-1)) { float tcp=(dr.uv.x-ul.uv.x)/(dr.p.x-ul.p.x); dr.uv.x += tcp*((ss.width-1)-dr.p.x); dr.p.x = float(ss.width-1); } // Test down-right Y (dr) if (dr.p.y>(ss.height-1)) { float tcp=(dr.uv.y-ul.uv.y)/(dr.p.y-ul.p.y); dr.uv.y += tcp*((ss.height-1)-dr.p.y); dr.p.y = float(ss.height-1); } // Visible return true; }
true
4e228dba8d6b5d6ea75ab2df9ab6182985dc32be
C++
JaeseokWoo/Algorithm
/Programmers/네트워크.cpp
UTF-8
860
3.4375
3
[]
no_license
/** * @date: 2021-07-02 * @version: vol1 * @access: dfs를 통해 네트워크 수를 계산하였다. * @weaknesses & learned: */ #include <string> #include <vector> using namespace std; const int MAX_N = 200; int N; vector<vector<int>> connected; bool visited[MAX_N]; void init() { for (int i = 0; i < N; ++i) { visited[i] = false; connected[i][i] = 0; } } void dfs(int here) { if (visited[here]) return; visited[here] = true; for (int next = 0; next < N; ++next) { if (!visited[next] && connected[here][next]) dfs(next); } } int solution(int n, vector<vector<int>> computers) { connected = computers; N = n; int answer = 0; init(); for (int i = 0; i < N; ++i) { if (!visited[i]) { dfs(i); answer++; } } return answer; }
true
259716c58251b722201b1b060c52dcd3f4cb1b4e
C++
HanWanxia/hello-world
/DBMS/RKDBMS/FileLogic.h
UTF-8
845
2.53125
3
[]
no_license
#pragma once /************************************************** [ClassName] CFileLogic [Function] Database file logic class **************************************************/ class CFileLogic { public: // Get the path of the database description file CString GetDBFile(CString path); // Get the path of the database folder CString GetDBFolder(const CString strDBName); // Get the path of the database table description file CString GetTableFile(const CString strDBName); // Get the path of the table definition file CString GetTbDefineFile(const CString strDBName, const CString strTableName); // Get the path of the table record file CString GetTbRecordFile(const CString strDBName, const CString strTableName); private: // Change relative path into an absolute path. CString GetAbsolutePath(const CString strRelativePath); };
true
ea7dd469bf749646948d455d5983bbafb9085217
C++
dgrij/assignment1
/RootAssignment1/RootAssignment1/LineKeeper.cpp
UTF-8
467
2.71875
3
[]
no_license
// Provides definitions for the declarations made in Line.h #include "LineKeeper.h" // Using-declarations using std::cout; using std::endl; using std::strcpy; LineKeeper::LineKeeper(const char* fileName) //: linePtr{ new char[1]{ '\0' } } { //cout<<"inside lk"<<endl; char* temp = new char[1000]; std::ifstream fin; fin.open(fileName); while(!fin.eof()){ fin.getline(temp, 1000); push_back(temp); } fin.close(); delete[] temp; }
true
81db220d0d58d09036cbed0d5375aa02111237ec
C++
SayaUrobuchi/uvachan
/AtCoder/arc065_a.cpp
UTF-8
593
2.859375
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; const int NUM_STR = 4; const string str[] = {"dream", "dreamer", "erase", "eraser"}; int main() { int i, j, k; bool is_pos; string s; getline(cin, s); for (i=s.size(), is_pos=true; i>0&&is_pos; i=k) { for (j=0; j<NUM_STR; j++) { if (i >= str[j].size() && strcmp(str[j].c_str(), s.c_str()+(i-str[j].size())) == 0) { break; } } if (j < NUM_STR) { k = i - str[j].size(); s.resize(k); } else { is_pos = false; } } if (!is_pos) { puts("NO"); } else { puts("YES"); } return 0; }
true
54ef61363c26207fe5dd1b4f32b070f204bef27c
C++
jmestanza/TPF_Stratego
/StrategoDEF/stratego/stratego/src/framework/view/utils/getKey.cpp
UTF-8
1,929
2.5625
3
[]
no_license
#include "getKey.h" map<int,int> allegroCodes; void getKeyInit() { allegroCodes[ALLEGRO_KEY_0] = '0'; allegroCodes[ALLEGRO_KEY_1] = '1'; allegroCodes[ALLEGRO_KEY_2] = '2'; allegroCodes[ALLEGRO_KEY_3] = '3'; allegroCodes[ALLEGRO_KEY_4] = '4'; allegroCodes[ALLEGRO_KEY_5] = '5'; allegroCodes[ALLEGRO_KEY_6] = '6'; allegroCodes[ALLEGRO_KEY_7] = '7'; allegroCodes[ALLEGRO_KEY_8] = '8'; allegroCodes[ALLEGRO_KEY_9] = '9'; allegroCodes[ALLEGRO_KEY_FULLSTOP] = '.'; allegroCodes[ALLEGRO_KEY_PAD_0] = '0'; allegroCodes[ALLEGRO_KEY_PAD_1] = '1'; allegroCodes[ALLEGRO_KEY_PAD_2] = '2'; allegroCodes[ALLEGRO_KEY_PAD_3] = '3'; allegroCodes[ALLEGRO_KEY_PAD_4] = '4'; allegroCodes[ALLEGRO_KEY_PAD_5] = '5'; allegroCodes[ALLEGRO_KEY_PAD_6] = '6'; allegroCodes[ALLEGRO_KEY_PAD_7] = '7'; allegroCodes[ALLEGRO_KEY_PAD_8] = '8'; allegroCodes[ALLEGRO_KEY_PAD_9] = '9'; allegroCodes[ALLEGRO_KEY_A] = 'a'; allegroCodes[ALLEGRO_KEY_B] = 'b'; allegroCodes[ALLEGRO_KEY_C] = 'c'; allegroCodes[ALLEGRO_KEY_D] = 'd'; allegroCodes[ALLEGRO_KEY_E] = 'e'; allegroCodes[ALLEGRO_KEY_F] = 'f'; allegroCodes[ALLEGRO_KEY_G] = 'g'; allegroCodes[ALLEGRO_KEY_H] = 'h'; allegroCodes[ALLEGRO_KEY_I] = 'i'; allegroCodes[ALLEGRO_KEY_J] = 'j'; allegroCodes[ALLEGRO_KEY_K] = 'k'; allegroCodes[ALLEGRO_KEY_L] = 'l'; allegroCodes[ALLEGRO_KEY_M] = 'm'; allegroCodes[ALLEGRO_KEY_N] = 'n'; allegroCodes[ALLEGRO_KEY_O] = 'o'; allegroCodes[ALLEGRO_KEY_P] = 'p'; allegroCodes[ALLEGRO_KEY_Q] = 'q'; allegroCodes[ALLEGRO_KEY_R] = 'r'; allegroCodes[ALLEGRO_KEY_S] = 's'; allegroCodes[ALLEGRO_KEY_T] = 't'; allegroCodes[ALLEGRO_KEY_U] = 'u'; allegroCodes[ALLEGRO_KEY_V] = 'v'; allegroCodes[ALLEGRO_KEY_W] = 'w'; allegroCodes[ALLEGRO_KEY_X] = 'x'; allegroCodes[ALLEGRO_KEY_Y] = 'y'; allegroCodes[ALLEGRO_KEY_Z] = 'z'; } char getKey(int code) { if (allegroCodes.find(code) == allegroCodes.end()) return -1; return allegroCodes[code]; }
true
8159800aea4b60663b7336ec1bd1c0c481e1c107
C++
vouching/tasks-for-inf-c-
/tasks7/task7_3.cpp
UTF-8
1,039
2.984375
3
[]
no_license
#include <iostream> #include <string> #include <cmath> #include <algorithm> #include <vector> #include <iomanip> #include <fstream> #include <sstream> #include <map> using namespace std; struct student { string name; string surname; int day_birth; int month_birth; int year_birth; }; student pushh() { student f; cin>>f.name>>f.surname>>f.day_birth>>f.month_birth>>f.year_birth; return f; } int main() { map <int,student> as; int i; cin>>i; for(int y=1;y<=i;y++) { student f; f=pushh(); as[y]=f; } cin>>i; for(int y=1;y<=i;y++) { string h; int u; cin>>h>>u; if(h=="name") { cout<<as[u].name<<" "<<as[u].surname<<endl; } if(h=="date") { cout<<setfill('0')<<setw(2)<<as[u].day_birth<<"."<<setw(2)<<as[u].month_birth<<"."<<as[u].year_birth<<endl; } if((h!="name")&&(h!="date")) { cout<<"bad request"<<endl; } } }
true
277c3ab63ff652430a2928728fd5153fcc348b30
C++
take-cheeze/rpgtukuru-iphone
/KutoEngine/kuto/kuto_array.h
UTF-8
1,464
3.4375
3
[]
no_license
/** * @file * @brief 静的配列クラス 普通の配列より便利に安全に * @author project.kuto */ #pragma once #include "kuto_types.h" #include "kuto_error.h" #include <cstring> namespace kuto { /// 静的配列クラス 普通の配列より便利に安全に template<class T, uint CAPACITY> class Array { public: typedef T* iterator; typedef const T* const_iterator; public: Array() {} iterator begin() { return buffer_; } const_iterator begin() const { return buffer_; } iterator end() { return buffer_ + CAPACITY; } const_iterator end() const { return buffer_ + CAPACITY; } T& front() { return buffer_[0]; } const T& front() const { return buffer_[0]; } T& back() { return buffer_[CAPACITY - 1]; } const T& back() const { return buffer_[CAPACITY - 1]; } uint size() const { return CAPACITY; } bool empty() const { return false; } uint capacity() const { return CAPACITY; } T& at(uint index) { kuto_assert(index < CAPACITY); return buffer_[index]; } const T& at(uint index) const { kuto_assert(index < CAPACITY); return buffer_[index]; } T& operator[](uint index) { kuto_assert(index < CAPACITY); return buffer_[index]; } const T& operator[](uint index) const { kuto_assert(index < CAPACITY); return buffer_[index]; } T* get() { return buffer_; } const T* get() const { return buffer_; } void zeromemory() { std::memset(buffer_, 0, sizeof(buffer_)); } private: T buffer_[CAPACITY]; }; } // namespace kuto
true
197e3c9aabc44c9b870620f2eafc5e5549a9ef28
C++
medhavisinha/Cpp-STL-Maps
/Workshop/inserting_data.cpp
UTF-8
501
2.859375
3
[]
no_license
#include<iostream> #include<map> #include<iterator> using namespace std; int main(){ map<int, int> m1; m1.insert(pair<int, int>(1, 5)); m1.insert(pair<int, int>(2, 10)); m1.insert(pair<int, int>(3, 15)); m1.insert(pair<int, int>(4, 20)); m1.insert(pair<int, int>(5, 25)); //m1.clear(); map<int, int>::iterator itr; for (itr = m1.begin(); itr != m1.end(); ++itr) { cout << '\t' << itr->first << '\t' << itr->second << '\n'; } cout<<"\n"; }
true
bcbeef7c2332a6bfc62683413c2dff3ff0dbd570
C++
baruken/invcat2d
/prototypes/megaman-uno/Timer.cpp
UTF-8
348
2.8125
3
[]
no_license
#include "Timer.hpp" Timer::Timer():m_nTicks(0) { #ifdef DEBUG std::cout << "Timer constructor: " << this << std::endl; #endif } Timer::~Timer() { #ifdef DEBUG std::cout << "Timer destructor: " << this << std::endl; #endif } void Timer::Start() { m_nTicks = SDL_GetTicks(); } int Timer::GetTicks() { return SDL_GetTicks() - m_nTicks; }
true
4e5200f5adc75e00af0531b8be4eb3a5d6dba310
C++
kwosingyu/SimPla
/example/obsolete/modeling/ebmesh.cpp
UTF-8
6,606
2.765625
3
[ "BSD-3-Clause" ]
permissive
/*! \example example_ebmesh.cpp The EBMesh tool can generate Cartesian meshes for solvers that use embedded boundary algorithms. \n It uses a ray-tracing technique based on hierarchical oriented bounding boxes in MOAB. \section EBMesh_cpp_title EBMesher Tool With Options \subsection EBMesh_cpp_in Input Reads in an input geometry file from data directory (sphere), \subsection EBMesh_cpp_out Output Exports a mesh file with CutCell data. \subsection EBMesh_cpp_src Source Code */ #include "meshkit/MKCore.hpp" #include "meshkit/MeshOp.hpp" #include "meshkit/EBMesher.hpp" #include "meshkit/SCDMesh.hpp" #include "meshkit/ModelEnt.hpp" using namespace MeshKit; #define DEFAULT_TEST_FILE "demo.stp" const bool debug_EBMesher = true; int load_and_mesh(const char *input_filename, const char *output_filename, int whole_geom, int *n_intervals, int mesh_based_geom, double box_increase, int vol_frac_res); int main(int argc, char **argv) { // check command line arg std::string input_filename; const char *output_filename = NULL; int whole_geom = 1; int n_interval[3] = {100, 100, 20}; int mesh_based_geom = 0; double box_increase = .03; int vol_frac_res = 0; if (argc > 2 && argc < 11) { input_filename += argv[1]; if (argc > 2) whole_geom = atoi(argv[2]); if (argc > 3) n_interval[0] = atoi(argv[3]); if (argc > 4) n_interval[1] = atoi(argv[4]); if (argc > 5) n_interval[2] = atoi(argv[5]); if (argc > 6) mesh_based_geom = atoi(argv[6]); if (argc > 7) output_filename = argv[7]; if (argc > 8) box_increase = atof(argv[8]); if (argc > 9) vol_frac_res = atoi(argv[9]); } else { std::cout << "Usage: " << argv[0] << "<input_geom_filename> <whole_geom> {x: # of intervals} {y: # of intervals} {z: # of intervals} {mesh_based_geom} {output_mesh_filename} {box_size_increase} {vol_frac_res}" << std::endl; std::cout << "<input_geom_filename> : input geometry file name" << std::endl; std::cout << "<whole_geom> : make mesh for whole geom or individually(1/0), default whole geom(1)" << std::endl; std::cout << "{x/y/z: # ofintervals} : optional argument. # of intervals. if it is not set, set to 10." << std::endl; std::cout << "<mesh_based_geom> : use mesh based geometry(1/0), default not-use(0)" << std::endl; std::cout << "{output_mesh_filename} : optional argument. if it is not set, dosn't export. can output mesh file (e.g. output.vtk.)" << std::endl; std::cout << "{box size increase} : optional argument. Cartesian mesh box increase form geometry. default 0.03" << std::endl; std::cout << "{vol_frac_res} : optional argument, volume fraction resolution of boundary cells for each material, you can specify it as # of divisions (e.g. 4)." << std::endl; std::cout << std::endl; if (argc != 1) return 1; std::cout << "No file specified. Defaulting to: " << DEFAULT_TEST_FILE << std::endl; std::string file_name = DEFAULT_TEST_FILE; input_filename += DEFAULT_TEST_FILE; } if (load_and_mesh(input_filename.c_str(), "demo_ebmesh.vtk", whole_geom, n_interval, mesh_based_geom, box_increase, vol_frac_res)) return 1; return 0; } int load_and_mesh(const char *input_filename, const char *output_filename, int whole_geom, int *n_interval, int mesh_based_geom, double box_increase, int vol_frac_res) { bool result; time_t start_time, load_time, mesh_time, vol_frac_time, export_time, query_time_techX, query_time; // start up MK and load the geometry MKCore mk; mk.load_mesh(input_filename, NULL, 0, 0, 0, true); mk.save_mesh("input.vtk"); // get the volumes MEntVector vols; mk.get_entities_by_dimension(3, vols); // make EBMesher EBMesher *ebm = (EBMesher *) mk.construct_meshop("EBMesher", vols); ebm->use_whole_geom(whole_geom); ebm->use_mesh_geometry(mesh_based_geom); ebm->set_num_interval(n_interval); ebm->increase_box(box_increase); if (mesh_based_geom) ebm->set_obb_tree_box_dimension(); // mesh embedded boundary mesh, by calling execute mk.setup_and_execute(); time(&mesh_time); // caculate volume fraction, only for geometry input if (vol_frac_res > 0) { result = ebm->get_volume_fraction(vol_frac_res); if (!result) { std::cerr << "Couldn't get volume fraction." << std::endl; return 1; } } time(&vol_frac_time); // export mesh if (output_filename != NULL) { ebm->export_mesh(output_filename); } time(&export_time); // techX query function test double boxMin[3], boxMax[3]; int nDiv[3]; std::map<CutCellSurfEdgeKey, std::vector<double>, LessThan> mdCutCellSurfEdge; std::vector<int> vnInsideCellTechX; ebm->get_grid_and_edges_techX(boxMin, boxMax, nDiv, mdCutCellSurfEdge, vnInsideCellTechX); time(&query_time_techX); // multiple intersection EBMesh_cpp_fraction query test std::map<CutCellSurfEdgeKey, std::vector<double>, LessThan> mdCutCellEdge; std::vector<int> vnInsideCell; result = ebm->get_grid_and_edges(boxMin, boxMax, nDiv, mdCutCellEdge, vnInsideCell); if (!result) { std::cerr << "Couldn't get mesh information." << std::endl; return 1; } time(&query_time); std::cout << "# of TechX cut-cell surfaces: " << mdCutCellSurfEdge.size() << ", # of nInsideCell: " << vnInsideCell.size() / 3 << std::endl; std::cout << "EBMesh is succesfully finished." << std::endl; std::cout << "Time including loading: " << difftime(mesh_time, start_time) << " secs, Time excluding loading: " << difftime(mesh_time, load_time) << " secs, Time volume fraction: " << difftime(vol_frac_time, mesh_time) << " secs"; if (output_filename != NULL) { std::cout << ", Time export mesh: " << difftime(export_time, vol_frac_time) << " secs"; } std::cout << ", TechX query time: " << difftime(query_time_techX, export_time) << " secs, multiple intersection EBMesh_cpp_fraction query (elems, edge-cut fractions): " << difftime(query_time, query_time_techX) << " secs."; std::cout << std::endl; mk.clear_graph(); return 0; }
true
215ab91ff9f2afd9a15bfeb5f8e6096fc0c076ea
C++
Okrio/ecmedia
/servicecore/source/codingHelper.h
GB18030
3,204
3.34375
3
[]
no_license
#include<string> #include<windows.h> #include<vector> using namespace std; //utf8 ת Unicode static std::wstring Utf82Unicode(const std::string& utf8string) { int widesize = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, NULL, 0); if (widesize ==0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { throw std::exception("Invalid UTF-8 sequence."); } else if (widesize == 0) { throw std::exception("Error in conversion."); } std::vector<wchar_t> resultstring(widesize); int convresult = ::MultiByteToWideChar(CP_UTF8, 0, utf8string.c_str(), -1, &resultstring[0], widesize); if (convresult != widesize) { throw std::exception("Error in conversion!"); } return std::wstring(&resultstring[0]); } //unicode תΪ ascii static std::string WideByte2Acsi(const std::wstring& wstrcode) { int asciisize = ::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, NULL, 0, NULL, NULL); if (asciisize == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { throw std::exception("Invalid UNICODE sequence."); } else if (asciisize == 0) { throw std::exception("Error in conversion."); } std::vector<char> resultstring(asciisize); int convresult =::WideCharToMultiByte(CP_OEMCP, 0, wstrcode.c_str(), -1, &resultstring[0], asciisize, NULL, NULL); if (convresult != asciisize) { throw std::exception("Error in conversion!"); } return std::string(&resultstring[0]); } //utf-8 ת ascii static std::string UTF_82ASCII(const std::string& strUtf8Code) { std::string strRet(""); //Ȱ utf8 תΪ unicode std::wstring wstr = Utf82Unicode(strUtf8Code); // unicode תΪ ascii strRet = WideByte2Acsi(wstr); return strRet; } /////////////////////////////////////////////////////////////////////// //ascii ת Unicode static std::wstring Acsii2WideByte(const std::string& strascii) { int widesize = MultiByteToWideChar (CP_ACP, 0, strascii.c_str(), -1, NULL, 0); if (widesize == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION) { throw std::exception("Invalid ACSII sequence."); } else if (widesize == 0) { throw std::exception("Error in conversion."); } std::vector<wchar_t> resultstring(widesize); int convresult = MultiByteToWideChar (CP_ACP, 0, strascii.c_str(), -1, &resultstring[0], widesize); if (convresult != widesize) { throw std::exception("Error in conversion!"); } return std::wstring(&resultstring[0]); } //Unicode ת Utf8 static std::string Unicode2Utf8(const std::wstring& widestring) { int utf8size = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, NULL, 0, NULL, NULL); if (utf8size == 0) { throw std::exception("Error in conversion."); } std::vector<char> resultstring(utf8size); int convresult = ::WideCharToMultiByte(CP_UTF8, 0, widestring.c_str(), -1, &resultstring[0], utf8size, NULL, NULL); if (convresult != utf8size) { throw std::exception("Error in conversion!"); } return std::string(&resultstring[0]); } //ascii ת Utf8 static std::string ASCII2UTF_8(const std::string& strAsciiCode) { std::string strRet(""); //Ȱ ascii תΪ unicode std::wstring wstr = Acsii2WideByte(strAsciiCode); // unicode תΪ utf8 strRet = Unicode2Utf8(wstr); return strRet; }
true
bff8a461a2f058269850d549f173fd6df9d247a9
C++
Eli-yp/Data_structure
/Sort/ShellSort.cpp
UTF-8
778
3.265625
3
[]
no_license
//希尔排序 #include<iostream> #include "sort.h" using namespace std; void ShellSort(SqList *L) { int i, j; int increment = L->length; do { increment = increment / 3 + 1; //增量序列 for(i = increment + 1; i <= L->length; ++i) { if(L->r[i] < L->r[i-increment]) { //需将L->r[i]插入有序增量子表 L->r[0] = L->r[i]; //暂缓在L->r[0]; for(j = i - increment; j > 0 && L->r[0] < L->r[j]; j-=increment) L->r[j+increment] = L->r[j]; //记录后移,查找插入位置 L->r[j+increment] = L->r[0]; //插入 } } } while(increment > 1); } int main(int argc, char **argv) { SqList L = {{0,9,1,5,8,3,7,4,6,2}, 9}; ShellSort(&L); for(int i = 1; i <= L.length; ++i) cout << L.r[i] << " "; cout << endl; return 0; }
true
a1b19fc81904eccfbdd1f527bc38938e79153165
C++
cristofer2021/EJERCICIO-DE-FIN-Y-INCIO-
/main.cpp
UTF-8
315
2.859375
3
[]
no_license
#include <iostream> using namespace std; int main() { int inicio,fin,s; s=0; cout << " ingrese el punto de inicio \n"; cin>> inicio; cout <<" ingrese el punto de fin\n"; cin>> fin; do { s=s+inicio; inicio=inicio+1; }while (inicio<fin); cout << " la sumatoria es :"<<s; }
true
c4a484afcd1453aef8b57844ac48e146577debba
C++
BenDaMan88/Terminal-Based-Pizza-Ordering-Site-5-1-2018
/Restaurant.h
UTF-8
2,319
3.09375
3
[]
no_license
/****************************************************************************** ** Program Filename: Restaurant.h ** Author: Ben Johnson ** Date: April 30, 2018 ** Description: pizza ordering site, terminal based. ** Inpupt: data read in from premade file and user input. ** Output: results printed to file or terminal depending on user's choice. ******************************************************************************/ #ifndef RESTAURANT #define RESTAURANT #include <iostream> using namespace std; class Restaurant { private: Menu menu; employee* employees; hours* week; int num_days; int num_employees; string name; string phone; string address; public: void load_data(); bool login(int& i); void view_menu(); void view_hours(); void view_address(); void view_phone(); void search_menu_by_price(); void search_by_ingredients(); void place_order(); void change_hours(); void add_to_menu(); void remove_from_menu(); void view_orders(); void remove_orders(); int find_num_employees(); bool is_pos_int(string input); int get_int(string input); bool is_pizza(string input); void set_restaurant_info(); void place_order(Menu &menu); bool is_pizza(string input, Menu &menu); void get_change_hour_info(string &day, string &open, string &close); void get_menu_info(string&name, string&s, string&m, string&l, string&n); void get_ingredients_info(string&num,string*&ingredients,int&num_ingredients); void place_order_info(string&name,string&size,string&num); //setters void set_menu(Menu menu); void set_employees(employee* employees); void set_week(hours* hours); void set_name(string name); void set_phone(string phone); void set_address(string address); void set_num_days(int num_days); void set_num_employees(int num_employees); //getters const Menu get_menu(); const employee* get_employee(); const hours* get_week(); const string get_name(); const string get_phone(); const string get_address(); const int get_num_days(); const int get_num_employees(); Restaurant(); ~Restaurant(); Restaurant(const Restaurant &copy); const Restaurant& operator=(const Restaurant &copy); }; #endif
true
be9fc71c5fef7995f574b38d2e82036f1faaae32
C++
Jin-SukKim/Algorithm
/Problem_Solving/baekjoon/DFS/14391_sub_paper/subPaper.cpp
UTF-8
2,594
3.453125
3
[]
no_license
#include <iostream> #include <vector> #include <string> // 가로는 direction에 true로 되어있고 세로는 false로 되어있다. int sum(std::vector<std::vector<int>> &paper, std::vector<std::vector<bool>> &direction, int &N, int &M, int row, int column) { int totalSum = 0; for (int i = 0; i < N; i++) { int sum = 0; for (int j = 0; j < M; j++) { // 가로 연속 if (direction[i][j]) { sum = sum * 10 + paper[i][j]; } // 끊기면 전체 합에 추가 else { totalSum += sum; sum = 0; } } totalSum += sum; } for (int j = 0; j < M; j++) { int sum = 0; for (int i = 0; i < N; i++) { // 세로 연속 if (!direction[i][j]) { sum = sum * 10 + paper[i][j]; } // 끊기면 전체 합에 추가 else { totalSum += sum; sum = 0; } } totalSum += sum; } return totalSum; } void dfs(std::vector<std::vector<int>> &paper, std::vector<std::vector<bool>> &direction, int &N, int &M, int row, int column, int& maxSum) { if (row == N) { maxSum = std::max(maxSum, sum(paper, direction, N, M, row, column)); return; } // 가로 끝에 도달했으면 row + 1한뒤 column은 처음부터 다시 돌아간다. if (column == M) { dfs(paper, direction, N, M, row + 1, 0, maxSum); return; } // 어떤 칸을 탐색할 때 해당 칸을 가로로 사용할지, 세로로 사용할지 교려한다. // 현재 칸을 가로로 사용 direction[row][column] = true; dfs(paper, direction, N, M, row, column + 1, maxSum); // 현재 칸을 세로로 사용 direction[row][column] = false; dfs(paper, direction, N, M, row, column + 1, maxSum); } int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); int N, M; std::cin >> N >> M; std::vector<std::vector<int>> paper(N, std::vector<int>(M)); for (int i = 0; i < N; i++) { std::string s; std::cin >> s; for (int j = 0; j < M; j++) paper[i][j] = s[j] - '0'; } int max = 0; std::vector<std::vector<bool>> direction(N, std::vector<bool>(M, false)); dfs(paper, direction, N, M, 0, 0, max); std::cout << max; return 0; }
true
5683abb63387dfc854814478bb4a0744d13ba273
C++
Dhruv-KDB/Arduino-codes
/Methane_sensor.ino
UTF-8
1,461
3.109375
3
[]
no_license
int gas_sensor = A0; //Sensor pin float R0 = 10; //Sensor Resistance in fresh air from previous code float b=1.133; float m=-0.318; void setup() { Serial.begin(9600); //Baud rate pinMode(gas_sensor, INPUT); //Set gas sensor as input } void loop() { float sensor_volt; //Define variable for sensor voltage float RS_gas; //Define variable for sensor resistance float RS_air; //Define variable fro sensor resistnace in air float R0; //Define variable for R0 float sensorValue; //Define variable for analog readings for (int x = 0 ; x < 500 ; x++){ sensorValue = sensorValue + analogRead(A0); //Add analog values of sensor 500 times } sensorValue = sensorValue / 500.0; //Take average of readings sensor_volt = sensorValue * (5.0 / 1023.0); //Convert average to voltage RS_air = ((5.0 * 10.0) / sensor_volt) - 10.0; //Calculate RS in air R0 = RS_air / 4.4; //Calculate R0 float ratio; //Define variable for ratio sensor_volt = sensorValue * (5.0 / 1023.0); //Convert average to voltage RS_gas = ((5.0 * 10.0) / sensor_volt) - 10.0; //Calculate RS for gas ratio = RS_gas / R0; double ppm_log = (log10(ratio) - b) / m; //Get ppm value in linear scale according to the the ratio value double ppm = pow(10, ppm_log); Serial.print("R0 = "); Serial.println(R0);//Convert ppm value to log scale Serial.print("PPM methane = "); Serial.println(ppm); delay(2000); }
true
ca5a9cfe5a71e063e0ebf0d516ee7e0aecddc869
C++
mohamedelsayeed/client-server-model
/ServerModel/Server.cpp
UTF-8
3,815
2.75
3
[]
no_license
#include <iostream> #include <string> #include <WS2tcpip.h> #pragma comment(lib, "ws2_32.lib") using namespace std; #define DEFAULT_PORT "27015" #define DEFAULT_BUFLEN 512 void main() { // Initialize Winsock WSADATA wsData; int wsResult = WSAStartup(MAKEWORD(2, 2), &wsData); if (wsResult != 0) { cerr << "Can't start Winsock, Err # " << wsResult << endl; return; } // Fill in a hint structure struct sockaddr_in hints; ZeroMemory(&hints, sizeof(hints)); hints.sin_family = AF_INET; hints.sin_port = htons(54000); hints.sin_addr.S_un.S_addr = INADDR_ANY; /* // Resolve the server address and port struct addrinfo* result = NULL; wsResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result); if (wsResult != 0) { cerr << "getaddrinfo failed with error: " << wsResult << endl; WSACleanup(); return; } */ //Create Socket SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, 0); if (ListenSocket == INVALID_SOCKET) { cerr << "Can't create scoket, Err# " << WSAGetLastError() << endl; WSACleanup(); return; } // Setup the TCP listening socket wsResult = bind(ListenSocket, (sockaddr*)&hints, sizeof(hints)); if (wsResult == SOCKET_ERROR) { cerr << "bind failed with error :" << WSAGetLastError() << endl; WSACleanup(); return; } wsResult = listen(ListenSocket, SOMAXCONN); if (wsResult == SOCKET_ERROR) { cerr << "listen failed with error :" << WSAGetLastError() << endl; closesocket(ListenSocket); WSACleanup(); return; } // Accept a client socket struct sockaddr_in client; int clientsize = sizeof(client); SOCKET ClientSocket = accept(ListenSocket, (sockaddr*)&client, &clientsize); if (ClientSocket == INVALID_SOCKET) { cerr << "accept failed with Err# " << WSAGetLastError() << endl; WSACleanup(); return; } char host[NI_MAXHOST]; // Client's remote name char service[NI_MAXSERV]; // Service (i.e. port) the client is connect on ZeroMemory(host, NI_MAXHOST); ZeroMemory(service, NI_MAXSERV); if (getnameinfo((sockaddr*)&client, sizeof(client), host, NI_MAXHOST, service, NI_MAXSERV, 0) == 0) { cout << host << " connected on port " << service << endl; } //close server socket no longer needed closesocket(ListenSocket); int iSendResult; char recvbuf[DEFAULT_BUFLEN]; int recvbuflen = DEFAULT_BUFLEN; //receive /*while (true) { wsResult = recv(ClientSocket, recvbuf, recvbuflen, 0); if (wsResult > 0) { cout << "Bytes received: " << string(recvbuf, 0, wsResult) << endl; } // Echo the buffer back to the sender iSendResult = send(ClientSocket, recvbuf, wsResult, 0); if (iSendResult == SOCKET_ERROR) { cerr << "send failed with error :" << WSAGetLastError() << endl; closesocket(iSendResult); WSACleanup(); return; } cout << "Bytes sent: " << string(recvbuf, 0, iSendResult) << endl; if (wsResult == 0) { cout << "Connection is closing" << endl; } else { cout << "recv failed with error " << WSAGetLastError << endl; closesocket(ClientSocket); WSACleanup(); } }*/ char buff[4096]; while (true) { ZeroMemory(buff, 4096); // Wait for client to send data int bytesReceived = recv(ClientSocket, buff, 4096, 0); if (bytesReceived == SOCKET_ERROR) { cerr << "Error in recv(). Quitting" << endl; break; } if (bytesReceived == 0) { cout << "Client disconnected " << endl; break; } cout <<" Recieved " <<string(buff, 0, bytesReceived) << endl; // Echo message back to client send(ClientSocket, buff, bytesReceived + 1, 0); } //Shutdown connection wsResult = shutdown(ClientSocket, SD_SEND); if (ClientSocket == SOCKET_ERROR) { cerr << "shutdown failed with error :" << WSAGetLastError() << endl; closesocket(ClientSocket); WSACleanup(); return; } //clean up closesocket(ClientSocket); WSACleanup(); return ; }
true
34534c7998653a5c944a451960ed05ebd182ee27
C++
tpetrychyn/TextBasedTurnBasedGame
/Attacker.cpp
UTF-8
1,048
3.25
3
[]
no_license
// // Attacker.cpp // cs115_assignment4 // // Created by Taylor Petrychyn on 2014-11-17. // Copyright (c) 2014 Taylor Petrychyn. All rights reserved. // #include "Attacker.h" Attacker::Attacker() : Monster() { damage = 2; health = 10; points = 20; } Attacker::Attacker(const Position& start) : Monster(start) { damage = 2; health = 10; points = 20; } Attacker::~Attacker() { } Attacker::Attacker(const Attacker& original) { damage = original.damage; health = original.health; points = original.points; position = original.position; } Attacker& Attacker::operator=(const Attacker& original) { damage = original.damage; health = original.health; points = original.points; position = original.position; return *this; } char Attacker::getDisplayChar() const { return 'A'; } Monster* Attacker::getClone() const { return new Attacker(*this); } Position Attacker::calculateMove(const Game &game, const Position &player_position) { return calculateToPosition(game, player_position); }
true
982c9ee12523c492d7578f3b93104955f6c6ca19
C++
SaberDa/LeetCode
/C++/11-containerWihMostWater.cpp
UTF-8
884
3.34375
3
[]
no_license
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<int> height; height.push_back(1); height.push_back(8); height.push_back(6); height.push_back(2); height.push_back(5); height.push_back(4); height.push_back(8); height.push_back(3); height.push_back(7); // two pointers // every time move one of the pointers, // first compare the current result with the old result // then length minus 1 // compare two pointers and move int res = 0; int length = height.size() - 1; int l = 0; int r = height.size() - 1; while (l < r) { res = max(res, min(height[l], height[r]) * length); length--; if (height[l] <= height[r]) { l++; } else { r--; } } cout << res << endl; return 0; }
true
e55a5c860cc151b1d1083301074ba9a8907a1a92
C++
luxiangnk/Maze-Solver
/Algorithms/IterativeDeepeningSearch.h
UTF-8
782
2.53125
3
[ "MIT" ]
permissive
#ifndef AI_PROJECT_ITERATIVEDEEPENINGSEARCH_H #define AI_PROJECT_ITERATIVEDEEPENINGSEARCH_H #include "AbstractSearchAlgorithm.h" class IterativeDeepeningSearch : public AbstractSearchAlgorithm { private: pair<shared_ptr<Node>, bool> DLS(double **array, int dimension, const shared_ptr<Node> &root, const shared_ptr<Node> &goal, int limit, float time_limit); IterativeDeepeningSearch() : AbstractSearchAlgorithm() {}; IterativeDeepeningSearch(const IterativeDeepeningSearch &); void operator=(const IterativeDeepeningSearch &); public: static IterativeDeepeningSearch &getInstance(); int run_algorithm(double **array, int dimension, int *start, int *target, float time_limit) override; }; #endif //AI_PROJECT_ITERATIVEDEEPENINGSEARCH_H
true
abb6fbe37ca8f781208a6e4e8ff6b29f2ba68cb4
C++
iremashvili2000/Simple-tasks
/oop1.cpp
UTF-8
1,683
2.90625
3
[]
no_license
#include <iostream> #include <string> using namespace std; // programa aris oop tematikis,igi poulobs sami adamianidan udidesi wlovanebis mqones da yvelaze meti fulis mqone adamians // da bechdavs class func { string name, surname, id; double fuli; int age; public: func() { } ~func(){ } void input(); void printmayuta(); void ufrosiasakis(); int getage() { return age; } double getfuli() { return fuli; } }; func fuliani(func&, func&, func&); func didi(func&, func&, func&); void func::input() { static int counter = 1; cout << "name: "<<counter<<": "; cin >> name; cout << "surname: "; cin >> surname; cout << "idi: "; cin >> id; cout << "money: "; cin >> fuli; cout << "age: "; cin >> age; counter++; } void func::printmayuta() { cout << "yvelaze fuliani tipi: " << name << " " << surname << endl; cout << " misi idi: " << id << endl << "age: " << age << endl; cout << "fulis raodenoba: " << fuli; cout << endl; } void func::ufrosiasakis() { cout << "yvelaze didi asakis adamiani: " << name << " " << surname << endl; cout << " misi idi: " << id << endl << "age: " << age << endl; cout << "fulis raodenoba: " << fuli; cout << endl; } func fuliani(func& a, func& b, func& c) { func*t; if (a.getfuli() > b.getfuli())t = &a; else t = &b; if (c.getfuli() > t->getfuli())t = &c; return * t; } func didi(func& a, func& b, func& c) { func *t; if (a.getage() > b.getage())t = &a; else t = &b; if (c.getage() > t->getage())t = &c; return *t; } int main() { func A, B, C; A.input(); B.input(); C.input(); func D = fuliani(A, B, C); D.printmayuta(); func G = didi(A, B, C); G.ufrosiasakis(); system("pause"); }
true
0be182f9f484c9ac926343d59a0b93de38ad9df7
C++
pv-k/NNLib4
/ConsoleApplication1/LogisticCostModule.h
UTF-8
3,029
2.859375
3
[]
no_license
#ifndef LOGISTIC_COST_MODULE_H #define LOGISTIC_COST_MODULE_H #include "CostModule.h" template <class T> class LogisticCostModule : public CostModule<T> { const double eps; double log2_; double log2(double x) { return (double)(std::log(x) / log2_); } public: LogisticCostModule() : CostModule(), eps(0.000000001), log2_(std::log(2)) { } virtual double sub_GetCost(const Tensor<T>& net_output, const Tensor<T>& expected_output, const std::vector<T>& importance_weights, bool normalize_by_importance, double lambda); virtual void sub_bprop(const Tensor<T>& net_output, const Tensor<T>& expected_output, const std::vector<T>& importance_weights, bool normalize_by_importance, Tensor<T>& output_gradients_buffer, double lambda); }; template <class T> double LogisticCostModule<T>::sub_GetCost(const Tensor<T>& net_output, const Tensor<T>& expected_output, const std::vector<T>& importance_weights, bool normalize_by_importance, double lambda) { double cost = 0; double importance_sum = 0; size_t minibatch_size = net_output.GetDimensionSize(net_output.NumDimensions()-1); size_t num_features = net_output.Numel() / minibatch_size; if (normalize_by_importance) for (size_t sample_ind = 0; sample_ind<minibatch_size; sample_ind++) importance_sum += importance_weights[sample_ind]; else importance_sum = 1; for (size_t sample_ind = 0; sample_ind<minibatch_size; sample_ind++) { size_t offset = num_features*sample_ind; for (size_t feature_ind = 0; feature_ind<num_features; feature_ind++) { size_t feature_offset = offset+feature_ind; cost += importance_weights[sample_ind]*(-expected_output[feature_offset]*log2(net_output[feature_offset]+eps) -(1-expected_output[feature_offset])*log2(1-net_output[feature_offset]+eps)); } } return lambda*cost/importance_sum; } template <class T> void LogisticCostModule<T>::sub_bprop(const Tensor<T>& net_output, const Tensor<T>& expected_output, const std::vector<T>& importance_weights, bool normalize_by_importance, Tensor<T>& output_gradients_buffer, double lambda) { double cost = 0; double importance_sum = 0; size_t minibatch_size = net_output.GetDimensionSize(net_output.NumDimensions()-1); assert(minibatch_size == importance_weights.size()); size_t num_features = net_output.Numel() / minibatch_size; if (normalize_by_importance) for (size_t sample_ind = 0; sample_ind<minibatch_size; sample_ind++) importance_sum += importance_weights[sample_ind]; else importance_sum = 1; for (size_t sample_ind = 0; sample_ind<minibatch_size; sample_ind++) { size_t offset = num_features*sample_ind; for (size_t feature_ind = 0; feature_ind<num_features; feature_ind++) { size_t feature_offset = offset+feature_ind; output_gradients_buffer[feature_offset] = static_cast<T>(lambda*importance_weights[sample_ind]/importance_sum*( (1-expected_output[feature_offset]) / (1-net_output[feature_offset]+eps) - expected_output[feature_offset] / (net_output[feature_offset]+eps) ) / log2_); } } } #endif
true
25c6985cc0ab9e111e48d1acab5590f1412e9a09
C++
yak1ex/packrat_qi
/typeindex.hpp
UTF-8
1,930
2.515625
3
[]
no_license
/***********************************************************************/ /* */ /* typeindex.hpp: Backport for std::type_index in C++0x */ /* */ /* Written by Yak! / Yasutaka ATARASHI */ /* */ /* This software is distributed under the terms of */ /* Boost Software License 1.0 */ /* (http://www.boost.org/LICENSE_1_0.txt). */ /* */ /* $Id$ */ /* */ /***********************************************************************/ #ifndef YAK_UTIL_TYPEINDEX_HPP #define YAK_UTIL_TYPEINDEX_HPP #include <cstddef> #include <typeinfo> #include <boost/functional/hash.hpp> namespace yak { namespace util { class type_index { public: type_index(const std::type_info& rhs) : target(&rhs) {} bool operator==(const type_index& rhs) const { return *target == *rhs.target; } bool operator!=(const type_index& rhs) const { return *target != *rhs.target; } bool operator< (const type_index& rhs) const { return target->before(*rhs.target); } bool operator<=(const type_index& rhs) const { return !rhs.target->before(*target); } bool operator> (const type_index& rhs) const { return rhs.target->before(*target); } bool operator>=(const type_index& rhs) const { return !target->before(*rhs.target); } std::size_t hash_code() const { return boost::hash<const std::type_info*>()(target); } const char* name() const { return target->name(); } private: const std::type_info* target; }; }} #endif
true
b03018a4605dcf1ef3be72d23be2fa13af401332
C++
aurthconan/fanLens
/test/sample/randomize_terrain/PointGenerator.h
UTF-8
1,247
2.703125
3
[ "MIT" ]
permissive
#ifndef POINTGENERATOR_H #define POINTGENERATOR_H #include <fanVector3.h> #include <vector> class PointGenerator { public: class PointIndex { public: PointIndex( size_t level, size_t x, size_t y ); size_t mConvertedLevel; size_t mConvertedX; size_t mConvertedY; size_t mOriginalLevel; size_t mOriginalX; size_t mOriginalY; private: PointIndex(); }; PointGenerator( size_t level = 0, PointGenerator* parent = NULL, fan::fanVector3<float> a = fan::fanVector3<float>(), fan::fanVector3<float> b = fan::fanVector3<float>(), fan::fanVector3<float> c = fan::fanVector3<float>(), fan::fanVector3<float> d = fan::fanVector3<float>() ); ~PointGenerator(); fan::fanVector3<float> getPoint( const PointIndex& index ); private: PointGenerator(); const size_t mLevel; static size_t computeIndex( const PointIndex& index ); PointGenerator* mHigherLevel; PointGenerator* mLowerLevel; std::vector<fan::fanVector3<float> > mPoints; std::vector<bool> mGenerated; }; #endif /* end of include guard: POINTGENERATOR_H */
true
60f2e64749b2b930201592620afbe9f634c6201d
C++
cnc4less/PCA9555_Experiments
/Arduino/PCA9555_button_v01/PCA9555_button_v01.ino
UTF-8
1,559
2.71875
3
[ "MIT" ]
permissive
/* Author: Alberto Tam Yong Date: 09-07-14 PCA9555 Breakout Board Button testing LED circuit VCC --- |>|---/\/\---PCA9555 LED R=220 Button circuit PCA9555 ---./ .---GND Using a Teensy 2.0 for testing. If using and Arduino UNO, change LED pin to 13. */ #include <Wire.h> //Define the devices you'll use #define LED 11 //using a Teensy 2.0, LED is on pin 11 #define INT 10 #define i2c_address 0x21 byte io = B11111111; //keeps track of the state of each output //By default, they are all sourcing. void setup() { pinMode(INT,INPUT); pinMode(LED,OUTPUT); delay(10); digitalWrite(LED,HIGH); Wire.begin(); //set microcontroller as master Wire.beginTransmission(i2c_address); Wire.write(0x06); //configure PORT0 Wire.write(0x80); //B10000000, 0-6 output, 7 input Wire.endTransmission(); Wire.beginTransmission(i2c_address); Wire.write(0x02); //output PORT0 Wire.write(io); //default. all off, sourcing. Wire.endTransmission(); delay(1000); digitalWrite(LED,LOW); } void loop() { //Read inputs from PCA9555 Wire.beginTransmission(0x21); Wire.write(0x00); Wire.endTransmission(); Wire.requestFrom(0x21,1); byte input = Wire.read(); //Is button grounded? if(input == B01111111) { Wire.beginTransmission(i2c_address); Wire.write(0x02); //output PORT0 Wire.write(B00000000); //0-7 sinking Wire.endTransmission(); } else { Wire.beginTransmission(i2c_address); Wire.write(0x02); //output PORT0 Wire.write(B11111111); //0-7 sourcing Wire.endTransmission(); } }
true
3ecc22e162e47b54db5e33ed9120e0fb3975da73
C++
CyberHacker11/Lessons
/Lesson 23/Lesson 23.cpp
UTF-8
3,847
3.15625
3
[]
no_license
#include<iostream> #include<fstream> #include<string> #include<iomanip> #include<stdio.h> using namespace std; // out -> write // in -> read // app -> append void file_txt_write() { //ofstream fout("hakuna.txt", ios::out); ofstream fout("hakuna.txt", ios_base::app); if (!fout) { throw "File not found"; } if (fout.is_open()) { fout << "Salam millet" << endl; } else { throw "File not open exception"; } fout.close(); } void file_txt_read() { ifstream fin("hakuna.txt", ios::in); if (fin.is_open()) { string value; //fin >> value; //getline(fin, value); while (!fin.eof()) { getline(fin, value); cout << value << endl; } } fin.close(); } void file_binary_write() { ofstream fout("arr.bin", ios::binary); int arr[5]{ 10,20,3,4,5 }; if (fout.is_open()) { fout.write((char*)arr, sizeof(int) * 5); } fout.close(); } void file_binary_read() { ifstream fin("arr.bin", ios::binary); int arr[5]{}; if (fin.is_open()) { fin.read((char*)arr, sizeof(int) * 5); } for (size_t i = 0; i < 5; i++) { cout << arr[i] << " "; }cout << endl; } class Contact { public: string name; string surname; string number; Contact() = default; Contact(const string& name, const string& surname, const string& number) { this->name = name; this->surname = surname; this->number = number; } }; void file_txt_write_object() { Contact contact("Tural", "Tural", "1234567"); ofstream fout("contact.txt", ios::app); fout.setf(ios::left); if (fout.is_open()) { fout << setw(20) << contact.name << " " << setw(20) << contact.surname << " " << setw(20) << contact.number << endl; } fout.close(); } void file_txt_read_object() { Contact contact; ifstream fin("contact.txt"); if (fin.is_open()) { while (!fin.eof()) { fin >> contact.name; fin >> contact.surname; fin >> contact.number; cout << contact.name << endl; cout << contact.surname << endl; cout << contact.number << endl; } } fin.close(); } void find(const string& name) { Contact contact; ifstream fin("contact.txt"); if (fin.is_open()) { bool isFind = false; while (!fin.eof()) { fin >> contact.name; fin >> contact.surname; fin >> contact.number; if (contact.name == name) { cout << contact.name << endl; cout << contact.surname << endl; cout << contact.number << endl; isFind = true; break; } } if (!isFind) cout << "Not found" << endl; } fin.close(); } void deleteContact(const string& name) { Contact contact; ifstream fin("contact.txt"); ofstream fout("tmp.txt", ofstream::app); if (fin.is_open()) { bool isFind = false; while (!fin.eof()) { fin >> contact.name; fin >> contact.surname; fin >> contact.number; fout.setf(ios::left); if (contact.name == name) isFind = true; else { if (contact.name != "") fout << setw(20) << contact.name << " " << setw(20) << contact.surname << " " << setw(20) << contact.number << endl; contact.name = ""; } } if (!isFind) cout << "Not found" << endl; } fin.close(); fout.close(); remove("contact.txt"); { ofstream fout("contact.txt", ofstream::app); ifstream fin("tmp.txt"); if (fin.is_open()) { bool isFind = false; while (!fin.eof()) { fin >> contact.name; fin >> contact.surname; fin >> contact.number; fout.setf(ios::left); if (contact.name != "") fout << setw(20) << contact.name << " " << setw(20) << contact.surname << " " << setw(20) << contact.number << endl; contact.name = ""; } } fin.close(); remove("tmp.txt"); } } int main() { //file_txt_write(); //file_txt_read(); //file_binary_write(); //file_binary_read(); //file_txt_write_object(); //file_txt_read_object(); //find("Nicat"); deleteContact("Nicat"); return 0; }
true
4f1ba8f117b0c7c41bb871e6ac2ef6815662d6fa
C++
SeokLeeUS/Markov_localization
/get_pseudo_ranges/get_pseudo_ranges/get_pseudo_ranges.cpp
UTF-8
1,300
2.953125
3
[]
no_license
#include <algorithm> #include <iostream> #include <vector> #include "helpers.h" using namespace std; float control_stdev = 1.0f; float movement_per_timestep = 1.0f; int map_size = 25; vector <float> landmark_positions{ 5,10,12,20 }; vector <float> pseudo_range_estimator(vector<float> landmark_positions, float pseudo_position); int main() { for (int i = 0; i < map_size; ++i) { float pseudo_position = float(i); vector<float> pseudo_ranges = pseudo_range_estimator(landmark_positions, pseudo_position); if (pseudo_ranges.size() > 0) { for (size_t s = 0; s < pseudo_ranges.size(); ++s) { cout << "x:" << i << "\t" << pseudo_ranges[s] << endl; } cout << "--------------------" << endl; } } return 0; } vector<float> pseudo_range_estimator(vector<float> landmark_positions, float pseudo_position) { vector<float> pseudo_ranges; float temp; unsigned int j = 0; //int i = 0; while (j < landmark_positions.size()) { temp = float(landmark_positions[j] - pseudo_position); if (temp <= 0){ j++; } else { //pseudo_ranges[i] = temp; pseudo_ranges.push_back(temp); //i++; j++; } } sort(pseudo_ranges.begin(), pseudo_ranges.end()); return pseudo_ranges; }
true
1fd28566c2644e3e0025197a094c2491ad533f69
C++
stormysun513/project-euler
/p1.cpp
UTF-8
357
3.328125
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, char **argv) { int sum = 0, target = 3; while(target < 1000) { sum += target; target += 3; } target = 5; while(target < 1000) { sum += target; target += 5; } target = 15; while(target < 1000) { sum -= target; target += 15; } cout << "Ans: " << sum << endl; return 0; }
true
74ce81c24c4cceefd0be3897702fc80035342da1
C++
malinfeng/Blog_mlf
/刷题/剑指offer/01_二维数组中的查找.cpp
UTF-8
877
3.484375
3
[]
no_license
 #include <iostream> #include <vector> using namespace std; class Solution { public: bool Find(int target, vector<vector<int> > array) { if (array.empty() || array[0].empty()) { return false; } int row = array.size() - 1; int colu = 0; while(row >= 0 && colu < array[0].size()) { if (array[row][colu] == target) { return true; } else if (array[row][colu] < target) { ++colu; } else { --row; } } return false; } }; int main() { Solution a; vector<vector<int> > array = { {1, 2, 8, 9}, {2, 4, 9, 12}, {4, 7, 10, 13}, {6, 8, 11, 15} }; auto ret = a.Find(7, array); return 0; }
true
9606d7f260f48f8d9ebb9d873ea1af2ee6144d2e
C++
Shaked-g/cpp2
/Test.cpp
UTF-8
1,728
2.875
3
[ "MIT" ]
permissive
/** * @file Test.cpp * @author Shaked Gofin * @brief * @version 0.1 * @date 07-03-2021 * * @copyright Copyright (c) 2021 * */ #include "doctest.h" #include "snowman.hpp" #include <stdexcept> using namespace ariel; #include <cassert> #include <string> #include <algorithm> #include <iostream> #include <string.h> using namespace std; string nospaces(string input) { std::erase(input, ' '); std::erase(input, '\t'); std::erase(input, '\n'); std::erase(input, '\r'); return input; } TEST_CASE("Good snowman code") { CHECK(nospaces(snowman(11114411)) == nospaces("_===_\n(.,.)\n( : )\n( : )")); } TEST_CASE("Checks Bad Input for Amount of Body Parts") { CHECK(snowman(555)=="0"); CHECK(snowman(1)=="0"); CHECK(snowman(11)=="0"); CHECK(snowman(111)=="0"); CHECK(snowman(1111)=="0"); CHECK(snowman(11111)=="0"); CHECK(snowman(111111)=="0"); CHECK(snowman(111111111)=="0"); CHECK(snowman(5)=="0"); } TEST_CASE("Checks Bad Input for Approved Body Parts") { CHECK(snowman(55555555)=="0"); CHECK(snowman(15555555)=="0"); CHECK(snowman(61666666)=="0"); CHECK(snowman(55155555)=="0"); CHECK(snowman(55515555)=="0"); CHECK(snowman(55551555)=="0"); CHECK(snowman(55555155)=="0"); CHECK(snowman(55555515)=="0"); CHECK(snowman(55555551)=="0"); } TEST_CASE("Checks Hat") { string H1 = "_===_"; string H2 = "___....."; string H3 = "_/_\\"; string H4 = "___(_*_)"; CHECK(nospaces(snowman(11111111)).substr(0, 5 )== H1); CHECK(nospaces(snowman(21111111)).substr(0, 8 )== H2); CHECK(nospaces(snowman(31111111)).substr(0, 4 )== H3); CHECK(nospaces(snowman(41111111)).substr(0, 8 )== H4); }
true
32d06092b2b4ac8b5580e1903d3874792a2e8e57
C++
mashago/study
/http_server/hs4/http_request.h
UTF-8
7,167
2.890625
3
[]
no_license
#ifndef _HTTP_REQUEST_H_ #define _HTTP_REQUEST_H_ extern "C" { #include <stdio.h> } #include <string> #include <map> #include <algorithm> #include "http_util.h" #define MAX_HTTP_REQUEST_URL_SIZE 5120 struct http_request_t { enum HTTP_METHOD { METHOD_NULL = 0 , METHOD_GET = 1 , METHOD_POST = 2 }; int method; std::string url; std::map<std::string, std::string> param_map; std::map<std::string, std::string> header_map; std::string content; http_request_t() { method = METHOD_NULL; url = ""; param_map.clear(); header_map.clear(); content = ""; }; void init() { method = METHOD_NULL; url = ""; param_map.clear(); header_map.clear(); content = ""; } // set string line, not include /r/n. return real line size, include /r/n. // if return == 0, means not include a full line // if return < 0, means http line format error // if return > 0: // 1.line.size() > 0, line include a header // 1.line.size() == 0, line is /r/n int _get_line(std::string &line, const char *buffer, int size) { line = ""; int i = 0; const char *ptr = buffer; bool has_line = false; bool has_r = false; // skip space while (i < size) { if (*ptr != ' ') { break; } ptr++; i++; } while (i < size) { if (*ptr == '\r') { ptr++; i++; has_r = true; continue; } if (*ptr == '\n') { if (has_r) { i++; has_line = true; break; } else { // format error i = -1; break; } } line.append(ptr, 1); ptr++; i++; } if (has_line == false) { if (i == -1) { // http header format error return -1; } else { // not include a http header line return 0; } } return i; } // unpack first line. // return -1 for format error int _unpack_first_line(std::string &line) { // 1.get method // 2.get url char method_str[255]; uint32_t i = 0; uint32_t j = 0; // 1. while (IS_SPACE(line[i]) && i < line.size()) { i++; } if (i == line.size()) { printf("_unpack_first_line:error, no method\n"); return -1; } while (!IS_SPACE(line[i]) && i < line.size() && j < sizeof(method_str) - 1) { method_str[j] = line[i]; i++; j++; } if (i == line.size()) { printf("_unpack_first_line:error, no url\n"); return -1; } method_str[j] = '\0'; printf("_unpack_first_line:method_str=%s\n", method_str); if (strcasecmp(method_str, "GET") && strcasecmp(method_str, "POST")) { printf("_unpack_first_line:error, unimplemented method\n"); return -1; } if (strcasecmp(method_str, "GET") == 0) { this->method = METHOD_GET; } if (strcasecmp(method_str, "POST") == 0) { this->method = METHOD_POST; } // 2. while (IS_SPACE(line[i]) && i < line.size()) { i++; } if (i == line.size()) { // error, no url printf("_unpack_first_line:error, no url\n"); return -1; } j = 0; char tmp_url[MAX_HTTP_REQUEST_URL_SIZE+1]; if (line.size() - 14 > MAX_HTTP_REQUEST_URL_SIZE) // 14 for "POST HTTP/1.1" { // error, url too long printf("_unpack_first_line:error, url too long\n"); return -1; } while (!IS_SPACE(line[i]) && i < line.size() && j < MAX_HTTP_REQUEST_URL_SIZE) { tmp_url[j] = line[i]; i++; j++; } tmp_url[j] = '\0'; if (i == line.size()) { printf("_unpack_first_line:error, no http version\n"); return -1; } printf("_unpack_first_line:tmp_url=%s\n", tmp_url); uint32_t url_size = j; if (url_size == 0) { printf("_unpack_first_line:error, no url\n"); return -1; } j = 0; while (j < url_size && tmp_url[j] != '?') { this->url.append(tmp_url+j, 1); j++; } // printf("_unpack_first_line:url=%s\n", this->url.c_str()); if (j == url_size || j == url_size - 1) { // no param in url, or end with '?', return return 0; } const char *ptr = tmp_url + j + 1; std::string param(ptr, url_size - j - 1); url_param_to_map(param, this->param_map); return 0; } // input buffer and buffer size // if return 0, buffer not include a full http request // if return -1, http request format error // else return http request data buffer size int unpack(const char *buffer, int buffer_size) { // 1.get first line // 2.get other header // 3.get content printf("\n"); printf("unpack:-------- start buffer_size=%d\n", buffer_size); int ret = 0; const char *ptr = buffer; int line_size = 0; std::string line_str; int total_size = buffer_size; // 1. line_size = _get_line(line_str, ptr, buffer_size); printf("unpack:line_size=%d\n", line_size); if (line_size <= 0) { // not include a line or data error return line_size; } if (line_str.size() == 0) { // something go wrong, first line should not be /r/n return -1; } // printf("unpack:line_str=%s\n", line_str.c_str()); ret = _unpack_first_line(line_str); if (ret != 0) { // unpack first line fail printf("unpack:unpack first line fail\n"); return -1; } ptr += line_size; buffer_size -= line_size; // debug print printf("unpack:method=%d\n", this->method); printf("unpack:url=%s\n", this->url.c_str()); printf("unpack:param_map.size()=%lu\n", this->param_map.size()); for (auto iter = this->param_map.begin(); iter != this->param_map.end(); iter++) { printf("[%s]:[%s]\n", iter->first.c_str(), iter->second.c_str()); } printf("unpack:---- after first line buffer_size=%d\n", buffer_size); // 2. while ((line_size = _get_line(line_str, ptr, buffer_size)) > 0 && line_str.size() > 0) { // printf("line_str=[%s]\n", line_str.c_str()); header_to_map(line_str, this->header_map); ptr += line_size; buffer_size -= line_size; } if (line_size < 0) { printf("unpack:http request format error\n"); return -1; } if (line_size == 0) { printf("unpack:not inclue a full http request\n"); return 0; } if (line_str.size() == 0) { // get /r/n line, skip it ptr += line_size; buffer_size -= line_size; } // debug print printf("unpack:header_map.size()=%lu\n", this->header_map.size()); for (auto iter = this->header_map.begin(); iter != this->header_map.end(); iter++) { printf("[%s]:[%s]\n", iter->first.c_str(), iter->second.c_str()); } printf("unpack:---- after header buffer_size=%d\n", buffer_size); // 3. int content_length = 0; auto iter = this->header_map.find("Content-Length"); if (iter != this->header_map.end()) { char *end; content_length = (int)strtol(iter->second.c_str(), &end, 10); if (end == iter->second.c_str()) { printf("unpack:Content-Length not a int\n"); return -1; } } printf("unpack:content_length=%d\n", content_length); if (content_length > 0) { if (buffer_size < content_length) { // not include full content return 0; } this->content = std::move(std::string(ptr, content_length)); ptr += content_length; buffer_size -= content_length; printf("unpack:content=[%s]\n", content.c_str()); } printf("unpack:-------- get a full http request\n\n"); return total_size - buffer_size; } }; #endif
true
092ed33c2f75d344e54504a48b8b84f7bae5bdd3
C++
liuq901/code
/ZOJ/z_1937.cpp
UTF-8
854
2.625
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> int n,a[501],ans[501]; int main() { void search(int); while (1) { scanf("%d",&n); if (!n) break; if (n==1) { printf("1\n"); continue; } a[1]=1; a[0]=20000000; search(2); for (int i=1;i<=a[0]-1;i++) printf("%d ",ans[i]); printf("%d\n",ans[a[0]]); } system("pause"); return(0); } void search(int dep) { if (dep>=a[0]) return; for (int i=dep-1;i>=1;i--) for (int j=i;j>=1;j--) { int x=a[i]+a[j]; if (x<=a[dep-1]) break; if (x>n) continue; a[dep]=x; if (x==n) { a[0]=dep; memcpy(ans,a,sizeof(a)); return; } search(dep+1); } }
true
382a7d737c03f61b2d5ab3672ce70d74410cf375
C++
geekmomprojects/sound-meter-pendant
/SoundMeterPendant/SoundMeterPendant.ino
UTF-8
4,041
2.578125
3
[ "MIT" ]
permissive
/**************************************** Sound level sketch to read values from a microphone breakout and display on an 8x8 mini Dotstar LED matrix. Currently using an Adafruit matrix (https://www.adafruit.com/product/3444) and a MEMS microphone breakout board: https://www.adafruit.com/product/2716 Algorithm adapted from Adafruit's CPX VU meter code here: https://learn.adafruit.com/adafruit-microphone-amplifier-breakout/measuring-sound-levels ****************************************/ #include <SPI.h> #include <Adafruit_GFX.h> #include <Adafruit_DotStarMatrix.h> #include <Adafruit_DotStar.h> #ifndef PSTR #define PSTR // Make Arduino Due happy #endif #define DATAPIN 4 #define CLOCKPIN 3 #define MICPIN 1 #define MATRIX_WIDTH 8 #define MATRIX_HEIGHT 8 Adafruit_DotStarMatrix matrix = Adafruit_DotStarMatrix( MATRIX_WIDTH, MATRIX_HEIGHT, DATAPIN, CLOCKPIN, DS_MATRIX_BOTTOM + DS_MATRIX_RIGHT + DS_MATRIX_COLUMNS + DS_MATRIX_PROGRESSIVE, DOTSTAR_BRG); uint16_t soundLevels[MATRIX_WIDTH]; uint8_t soundLevelPointer = 0; float input_floor; float input_ceiling; #define NUM_SAMPLES 160 // CURVE should be a value between -10 and 10 - empirically tested to arrive at best value for this setup float CURVE = 4.0; float SCALE_EXPONENT = pow(10, CURVE * -0.1); float samples[NUM_SAMPLES]; float sample_buffer[NUM_SAMPLES]; float log_scale(float input_value, float input_min, float input_max, float output_min, float output_max) { float normalized_input_value = (input_value - input_min) / (input_max - input_min); return output_min + pow(normalized_input_value, SCALE_EXPONENT) * (output_max - output_min); } float sum(float* values, uint16_t nvalues) { float sum = 0; for (int i = 0; i < nvalues; i++) { sum = sum + values[i]; } return sum; } float mean(float* values, uint16_t nvalues) { return sum(values, nvalues)/nvalues; } float normalized_rms(float *values, uint16_t nvalues) { int minbuf = (int) mean(values, nvalues); for (int i = 0; i < nvalues; i++) { sample_buffer[i] = pow((values[i] - minbuf),2); } return sqrt(sum(sample_buffer, nvalues)/nvalues); } void recordSamples() { for (int i = 0; i < NUM_SAMPLES; i++) { samples[i] = analogRead(MICPIN); } } void setup() { Serial.begin(112500); matrix.begin(); matrix.setBrightness(72); matrix.fillScreen(0); matrix.setRotation(2); // Sound levels array to store data for last 8 readings for (int i = 0; i < MATRIX_WIDTH; i++) { soundLevels[i] = 0; } // Record an initial sample to calibrate. Assume it's quiet when we start // recordSamples(); //input_floor = normalized_rms(samples, NUM_SAMPLES) + .1; // Empirically determined by testing different values input_floor = 1.0; input_ceiling = input_floor + 6; } int peak = 0; void loop() { float magnitude = 0; uint8_t level; recordSamples(); magnitude = normalized_rms(samples, NUM_SAMPLES); float c = log_scale(constrain(magnitude, input_floor, input_ceiling), input_floor, input_ceiling, 0, MATRIX_HEIGHT-1); /* Serial.print(magnitude); Serial.print(" "); Serial.print(input_floor); Serial.print(" "); Serial.print(input_ceiling); Serial.print(" "); Serial.println(c); */ level = (int) c; //Storing last 8 sound levels in an array for a running level display - not currently used soundLevels[soundLevelPointer] = level; soundLevelPointer = (soundLevelPointer + 1) % MATRIX_WIDTH; //uint16_t color = matrix.Color(32*level, 0, 255-32*level); uint16_t peak_color = matrix.Color(255,255,0); // Let the peak fall a little more gradually than the sound levels matrix.fill(0); if (level >= peak) { peak = level; } else { peak = max(peak - 1, level); } matrix.drawLine(0,0,3,peak,peak_color); matrix.drawLine(4,peak,7,0,peak_color); matrix.show(); delay(5); }
true
8a27dcc25d175c5a424690e5b8707b4497af0feb
C++
nastyakuzenkova/CSC-Algorithms
/II/11G.cpp
UTF-8
851
2.6875
3
[]
no_license
#include <cstdio> #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; int t, n; int a[101]; void read_input() { freopen("varnim.in", "rt", stdin); scanf("%d", &t); for (int i = 0; i < t; ++i) { scanf("%d", &n); int r = 0; for (int j = 0; j < n; ++j) { scanf("%d", &a[j]); int val; if (a[j] % 4 == 0) { val = a[j] - 1; } else if (a[j] % 4 == 3){ val = a[j] + 1; } else { val = a[j]; } r = r ^ val; } if (r != 0) { printf("FIRST\n"); } else { printf("SECOND\n"); } } } int main() { freopen("varnim.out", "wt", stdout); read_input(); // clock_t begin, end; // double time_spent; // begin = clock(); // end = clock(); // time_spent = (double)(end - begin) / CLOCKS_PER_SEC; // printf("TIME %f\n", time_spent); return 0; }
true
34066f8066459538988676e6209cb0cc2bfdc339
C++
mwjin/stroustrup-ppp
/chap03/ex08_test_odd_even.cpp
UTF-8
293
3.34375
3
[]
no_license
#include "../std_lib_facilities.h" int main() { int n; cout << "Enter an integer: "; cin >> n; cout << endl; if (n % 2 == 0) cout << "The value " << n << " is an even number." << endl; else cout << "The value " << n << " is an odd number." << endl; }
true
6cc4a4f4695538ab2b14a7a4c957b6659a1828c4
C++
nikizhelqzkov/Music_Collection
/App/Login.cpp
UTF-8
1,772
3.34375
3
[]
no_license
#include "Login.h" /** * @brief Помощна функция, която проверява дали потребителя има профил в системата * * @param username * @param password * @return true * @return false */ bool Login::login(std::string username, std::string password) { std::ifstream input(username + ".txt"); if (!input.is_open()) { return false; } int res = 10 + username.size() + 11; input.seekg(res); std::string userPass; std::getline(input, userPass, ';'); return userPass == password; } /** * @brief UI за логин на потребител и връща отговор дали е логнат успешно или не * * @return true * @return false */ bool Login::userLogin() { std::cout << "WRITE YOUR USERNAME AND PASSWORD \n"; std::cin.ignore(); std::string username; std::string password; std::cout << "username: "; std::getline(std::cin, username); std::cout << "\npassword: "; std::getline(std::cin, password); std::cout << std::endl; if (login(username, password)) { std::cout << "Successful login\n"; Login n; setUsername(username); return true; } else { std::cout << "Ivalid username or password\n"; return false; } } /** * @brief Мутатор извеждащ стойността на член-данната userName; * * @return std::string */ std::string Login::getUsername() const { return userName; } /** * @brief Мутатор с аргумент, който се вкарва в член-данната userName * * @param _username */ void Login::setUsername(std::string _username) { userName = _username; }
true
3a4caeb68f2ee4e3ae5eed07254d92776520cc48
C++
Amith17/Heap-of-Students
/Address.cpp
UTF-8
770
2.953125
3
[]
no_license
//cpp file for address object #include "Address.h" #include <string> #include <iostream> using namespace std; string Address::get_streetAddress(){ return streetAddress; } void Address::set_streetAddress(string streetAddress){ Address::streetAddress = streetAddress; } string Address::get_address2(){ return address2; } void Address::set_address2(string address2){ Address::address2 = address2; } string Address::get_city(){ return city; } void Address::set_city(string city){ Address::city = city; } string Address::get_state(){ return state; } void Address::set_state(string state){ Address::state = state; } string Address::get_zip(){ return zip; } void Address::set_zip(string zip){ Address::zip = zip; } Address::Address(){ } Address::~Address(){ }
true
5ca5954dbd369bfe656436d48be926702266fe5a
C++
Edroor/libmsci
/sparse/full_matrix.h
UTF-8
2,705
2.671875
3
[ "MIT" ]
permissive
#ifndef FULL_MATRIX_H #define FULL_MATRIX_H #include "matrix_base.h" namespace libpetey { namespace libsparse { template <class index_t, class scalar> class full_matrix:public matrix_base<index_t, scalar> { protected: index_t m; index_t n; scalar **data; public: friend class sparse<index_t, scalar>; //destroys a large piece of the functionality of the sparse_array class: friend class sparse_array<index_t, scalar>; full_matrix(); full_matrix(index_t min, index_t nin); full_matrix(scalar **dat, index_t min, index_t nin); full_matrix(scalar *dat, index_t min, index_t nin); full_matrix(matrix_base<index_t, scalar> *other); full_matrix(full_matrix<index_t, scalar> &other); full_matrix(sparse<index_t, scalar> &other); full_matrix(sparse_array<index_t, scalar> &other); void identity(); void ones(); virtual ~full_matrix(); //access elements: virtual scalar operator ( ) (index_t i, index_t j); virtual long cel(scalar val, index_t i, index_t j); //access rows: virtual scalar *operator ( ) (index_t i); virtual void get_row(index_t i, scalar *row); //matrix multiplication: virtual matrix_base<index_t, scalar> * mat_mult(matrix_base<index_t, scalar> *cand); //matrix addition: virtual matrix_base<index_t, scalar> * add(matrix_base<index_t, scalar> * b); //vector multiplication: virtual scalar * vect_mult(scalar *cand); virtual scalar * left_mult(scalar *cor); virtual void vect_mult(scalar *cand, scalar *result); virtual void left_mult(scalar *cor, scalar *result); //scalar multiplication: virtual void scal_mult(scalar cand); //take transpose: virtual void transpose(); //informational: virtual void dimensions(index_t &mout, index_t &nout) const; //norm: virtual scalar norm(); //IO: virtual size_t read(FILE *fs); virtual size_t write(FILE *fs); virtual void print(FILE *fs); virtual int scan(FILE *fs); //type conversion: virtual matrix_base<index_t, scalar> & operator = (full_matrix<index_t, scalar> &other); virtual matrix_base<index_t, scalar> & operator = (sparse<index_t, scalar> &other); virtual matrix_base<index_t, scalar> & operator = (sparse_array<index_t, scalar> &other); virtual matrix_base<index_t, scalar> * clone(); //virtual full_matrix<index_t, scalar> & operator = (matrix_base<index_t, scalar> &other); /* virtual operator sparse<index_t, scalar>& (); virtual operator sparse_array<index_t, scalar>& (); virtual operator full_matrix<index_t, scalar>& (); */ }; } //end namespace libsparse } //end namespace libpetey #endif
true
1a8ac54d3c3181f04f3d2dfd79571c758ba26b34
C++
giovaneaf/CompetitiveProgramming
/Spoj/BSCXOR.cpp
UTF-8
122
2.5625
3
[]
no_license
#include <iostream> using namespace std; int main() { int p,q; cin >> p >> q; cout << (p^q) << endl; return 0; }
true
2a869b4306266f3d84c6cd1d47f85139c3f5bb8d
C++
mehmetaliaksoy/simple_blackjack
/game.h
UTF-8
984
2.765625
3
[]
no_license
#ifndef GAME_H #define GAME_H #include "dealer.h" #include "simpleplayer.h" class Game { public: enum Result { UNKNOWN, BLACKJACK_PUSH, PLAYER_WINS_BLACKJACK, DEALER_WINS_BLACKJACK, PLAYER_WINS_GREATER_HAND, DEALER_WINS_PLAYER_BUST, PLAYER_WINS_DEALER_BUST, PLAYER_PUSH, DEALER_WINS_GREATER_HAND }; Game(Dealer* pDealer, SimplePlayer* pPlayer, Deck* pDeck); void Init(int shuffleCount = 5); void Play(); int DetermineWinner(); private: int getPlayerChoice(); const int BLACKJACK = 21; const int DEALER_BOTTOM_LIMIT = 17; const int INITIAL_CARD_COUNT = 2; Dealer* m_pDealer; SimplePlayer* m_pPlayer; Deck* m_pDeck; }; #endif // GAME_H
true
55fa088db8398e595acf5ba53beb2dcc165e8a9e
C++
Dark1024/Proyecto_OA
/primaryindex.h
UTF-8
906
2.828125
3
[]
no_license
#ifndef PRIMARYINDEX_H #define PRIMARYINDEX_H //Importacion de encazados necesarios #include <string> #include <sstream> #include "object.h" using namespace std; /*********************************************************************** *Clase que se utiliza para manejar los indices primarios del archivo de *registro, permiten una busqueda rapida y son de mucha ayuda en la *lectura de registros ********************************************************************** */ class PrimaryIndex:public Object { public: //Constructor PrimaryIndex(string = "", streamoff = 0); ~PrimaryIndex(); //Mutadores y accesores const string getKey() const; const streamoff getOffset() const; virtual bool operator == (const PrimaryIndex&); //toString string toString(); //caracteristicas privadas private: string key; streamoff offset; }; #endif // PRIMARYINDEX_H
true