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
01df02a28104630b2da5c3aab94e0e7dc8e0e986
C++
chengzeyi/whu-acm-oj
/archive/167_Oil-Detecting.cpp
UTF-8
1,388
3
3
[]
no_license
#include <bits/stdc++.h> void block(size_t i, size_t j, std::vector<std::string> &graph) { if (i >= graph.size() || j >= graph.front().size()) { return; } if (graph[i][j] == 'X') { return; } graph[i][j] = 'X'; block(i - 1, j, graph); block(i - 1, j - 1, graph); block(i - 1, j + 1, graph); block(i + 1, j, graph); block(i + 1, j - 1, graph); block(i + 1, j + 1, graph); block(i, j - 1, graph); block(i, j + 1, graph); } size_t calcNumOfOilSite(std::vector<std::string> &graph) { size_t h = graph.size(), w = graph.front().size(); size_t count = 0; for (size_t i = 0; i < h; ++i) { for (size_t j = 0; j < w; ++j) { if (graph[i][j] == 'X') { continue; } ++count; block(i, j, graph); } } return count; } #ifdef DEBUG #define cin _ss namespace std { stringstream _ss; } #endif int main(int argc, char *argv[]) { #ifdef DEBUG std::cin << R"(1 10 XXOOXOXOOO 3 3 OXO XOX OXO 0 0)"; #endif size_t r, c; while (true) { std::cin >> r >> c; if ((r | c) == 0) { break; } std::vector<std::string> graph(r); for (size_t i = 0; i < r; ++i) { std::cin >> graph[i]; } std::cout << calcNumOfOilSite(graph) << std::endl; } return 0; }
true
131c165f5e60c66a0b805d2a4db19f4c236fb9e9
C++
DataManagementLab/DBx1000
/system/utils/mem_alloc.cpp
UTF-8
4,700
2.6875
3
[ "ISC" ]
permissive
#include "mem_alloc.h" #include "helper.h" #include "global.h" // Assume the data is strided across the L2 slices, stride granularity // is the size of a page void mem_alloc::init(uint64_t part_cnt, uint64_t bytes_per_part) { //set bucket_cnt to: max(g_thread_cnt,g_init_parallelism)*4+1 if (g_thread_cnt < g_init_parallelism) _bucket_cnt = g_init_parallelism * 4 + 1; else _bucket_cnt = g_thread_cnt * 4 + 1; pid_arena = new std::pair<pthread_t, int>[_bucket_cnt]; for (int i = 0; i < _bucket_cnt; i++) pid_arena[i] = std::make_pair(0, 0); if (THREAD_ALLOC) { assert(!g_part_alloc); init_thread_arena(); } } void Arena::init(int arena_id, int size) { _buffer = NULL; _arena_id = arena_id; _size_in_buffer = 0; _head = NULL; _block_size = size; } void* Arena::alloc() { FreeBlock* block; if (_head == NULL) { // reclamation list is empty: allocate from the buffer //calc required mem size and align it to MEM_ALIGN: size % MEM_ALIGN = 0 int size = (_block_size + sizeof(FreeBlock) + (MEM_ALLIGN - 1)) & ~(MEM_ALLIGN - 1); if (_size_in_buffer < size) { //size exceeds remaining buffer capacity, allocate new memory and assign to buffer //remaining buffer space will be leaked, but compared with occupied memory space (40960*buffer_size) negligible _buffer = (char*)malloc(_block_size * 40960); _size_in_buffer = _block_size * 40960; // * 8; } block = (FreeBlock*)_buffer; block->size = _block_size; _size_in_buffer -= size; _buffer = _buffer + size; } else { //allocate from reclamation list block = _head; _head = _head->next; } return (void*)((char*)block + sizeof(FreeBlock)); } void Arena::free(void* ptr) { //memory-layout: [FreeBlock - Metadata][Storage of size 'size'], calculate ptr to FreeBlock from storage ptr FreeBlock* block = (FreeBlock*)((UInt64)ptr - sizeof(FreeBlock)); block->next = _head; _head = block; } void mem_alloc::init_thread_arena() { //set buf_cnt to: max(g_thread_cnt, g_init_parallelism) UInt32 buf_cnt = g_thread_cnt; if (buf_cnt < g_init_parallelism) buf_cnt = g_init_parallelism; _arenas = new Arena * [buf_cnt]; for (UInt32 i = 0; i < buf_cnt; i++) { _arenas[i] = new Arena[SizeNum]; for (int n = 0; n < SizeNum; n++) { assert(sizeof(Arena) == 128); _arenas[i][n].init(i, BlockSizes[n]); } } } void mem_alloc::register_thread(int thd_id) { if (THREAD_ALLOC) { //if use per-thread allocator pthread_mutex_lock(&pid_arena_lock); pthread_t pid = pthread_self(); int entry = pid % _bucket_cnt; //map pid to bucket while (pid_arena[entry].first != 0) { //pid_arena entry occupied, check next arena slot printf("conflict at entry %d (pid=%ld)\n", entry, pid); entry = (entry + 1) % _bucket_cnt; } //occupy free pid_arena entry pid_arena[entry].first = pid; pid_arena[entry].second = thd_id; pthread_mutex_unlock(&pid_arena_lock); } } void mem_alloc::unregister() { if (THREAD_ALLOC) { pthread_mutex_lock(&pid_arena_lock); for (int i = 0; i < _bucket_cnt; i++) { pid_arena[i].first = 0; pid_arena[i].second = 0; } pthread_mutex_unlock(&pid_arena_lock); } } int mem_alloc::get_arena_id() { int arena_id; #if NOGRAPHITE pthread_t pid = pthread_self(); int entry = pid % _bucket_cnt; while (pid_arena[entry].first != pid) { if (pid_arena[entry].first == 0) //early return: pid entry not found in arena break; entry = (entry + 1) % _bucket_cnt; } arena_id = pid_arena[entry].second; #else arena_id = CarbonGetTileId(); #endif return arena_id; } int mem_alloc::get_size_id(UInt32 size) { for (int i = 0; i < SizeNum; i++) { if (size <= BlockSizes[i]) return i; } //size should not exceed largest blocksize printf("size = %d\n", size); assert(false); } void mem_alloc::free(void* ptr, uint64_t size) { if (NO_FREE) {} else if (THREAD_ALLOC) { int arena_id = get_arena_id(); FreeBlock* block = (FreeBlock*)((UInt64)ptr - sizeof(FreeBlock)); int size = block->size; int size_id = get_size_id(size); _arenas[arena_id][size_id].free(ptr); } else { std::free(ptr); } } //TODO the program should not access more than a PAGE // to guanrantee correctness // lock is used for consistency (multiple threads may alloc simultaneously and // cause trouble) void* mem_alloc::alloc(uint64_t size, uint64_t part_id) { void* ptr; if (size > BlockSizes[SizeNum - 1]) //size exceeds block size, don't use buffer and reclamation not possible ptr = malloc(size); else if (THREAD_ALLOC && (warmup_finish || enable_thread_mem_pool)) { int arena_id = get_arena_id(); int size_id = get_size_id(size); ptr = _arenas[arena_id][size_id].alloc(); } else { ptr = malloc(size); } return ptr; }
true
39a978db5a2b98759a7bba502310ddfc4865479c
C++
google-code/7559-saleconfritas
/codigo/Persona/src/main.cpp
UTF-8
584
2.71875
3
[]
no_license
#include <iostream> #include <unistd.h> #include <stdio.h> #include "Persona.h" int main(int argc, char **argv) { /* Control de parametros * 1 - cantidad de pisos del edificio * 2 - cantidad de ascensores * 3 - capacidad del ascensor * 4 - velocidad del ascensor * 5 - modo debug * 6 - modo log * 7 - modo synchro * 8 - modo cout */ Persona *p = new Persona(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atoi(argv[4]), atoi(argv[5]), atoi(argv[6]), atoi(argv[7]), atoi(argv[8])); bool value = p->llamarAscensorYEsperar(); delete (p); return value; }
true
4c1a7d08a623b2133b05257ff702a33ee0dca4db
C++
ljeongseok/Arduino
/door_lock/Doorlock.cpp
UTF-8
2,986
2.859375
3
[]
no_license
#include "Doorlock.h" Doorlock::Doorlock(int serial_bps, int lcd_addr) : MiniCom(serial_bps,lcd_addr){ } void Doorlock::init(int led_pin, int servo_pin) { MiniCom::init(); this->led_pin = led_pin; pinMode(led_pin,OUTPUT); lock.attach(servo_pin); print(0,"[[Door Lock]]"); lock.write(0); offLcd(); } void Doorlock::readpassword() { password = readRom(BASE_ADDRESS); } void Doorlock::setPassword() { tick(); bSetPassword = !bSetPassword; if(bSetPassword){ // 새 비밀번호 입력 시작 onLcd(); input = ""; inputStar=""; bInput=true; print(1,inputStar.c_str()); } else{ // 새 비밀번호 입력 완료 // ROM에 비밀번호 저장 password = input; // 비밀번호 갱신 writeRom(BASE_ADDRESS,input.c_str()); bSetPassword = !bSetPassword; bInput=false; print(1,""); offLcd(); } } // int Doorlock::setTimeout(unsigned long time, timer_callback f) // { // return timer.setTimeout(time,f); // } void Doorlock::process(char key) { tick(); // timer = getTimer(); if (key == '*' && bInput == false){ // 키 입력 시작 input = ""; inputStar =""; bInput = true; // timerId = timer.setTimeout(5000,reset); onLcd(); t2 = millis(); ptime = true; print(1,"chance :",check_password); } else if(key == '#' && bInput == true){ // 키 입력 완료 // timer.deleteTimer(timerId); bInput = false; ptime = false; check(); // 마지막 처리 offLcd(); } else if(bInput){ input += key; inputStar +="*"; print(1,inputStar.c_str()); // timer.restartTimer(timerId); t2 = millis(); } } void Doorlock::check() { if (input==password){ // 비밀번호 일치 lock.write(90); print(1,"open"); delay(5000); lock.write(0); print(1,""); check_password = 3; } else { // 비밀번호 불일치 for(int i=0;i<3;i++){ delay(100); tick(); } check_password--; print(1,"chance :",check_password); if(check_password == 0){ offLcd(); print(1,"fail"); delay(600000); print(1,""); check_password=3; tick(); } } } void Doorlock::tick() { digitalWrite(led_pin,HIGH); delay(100); digitalWrite(led_pin,LOW); } void Doorlock::reset() { input = ""; inputStar=""; bInput = false; ptime = false; if (check_password<3){ print(1,"chance :",check_password); } else print(1,""); offLcd(); } void Doorlock::run() { MiniCom::run(); if(ptime){ t1 = millis(); if(t1 - t2 > 5000){ reset(); } } }
true
68aab2d69dc845b7c0f2c79e8e900bac3b636685
C++
amrithabastin/CS141
/lab10_q1.cpp
UTF-8
854
3.53125
4
[]
no_license
#include<iostream> using namespace std; //declaring class class box{ //acess public: //properties int height; int breadth; int length; }; int main(){ //declaing objects box box1; box box2; //and needed vaiables float volume= 0.0; //assinging values tproperties of bjects in class , inputs cout<< "enter dimensions of box1"<<endl; cin>>box1.height; cout<<endl; cin>>box1.breadth; cout<<endl; cin>>box1.length; cout<<endl<<endl<<endl; volume = box1.height*box1.breadth*box1.length; cout<<"volume of box1 is = "<<volume<<endl<<endl<<endl; cout<< "enter dimensions of box2"<<endl; cin>>box2.height; cout<<endl; cin>>box2.breadth; cout<<endl; cin>>box2.length; cout<<endl<<endl<<endl; //volume volume = box2.height*box2.breadth*box2.length; cout<<"volume of box2 is = "<<volume<<endl<<endl<<endl; return 0; }
true
6fb50f96eae839c3239b6389f72e428089045899
C++
CallumCarmicheal/CubedWorld
/Source/CubedWorld.Server/Console.cpp
UTF-8
2,938
2.984375
3
[]
no_license
#include "Console.h" #include <conio.h> /* * Create the console */ void Console::Create() { int hConHandle = 0; HANDLE lStdHandle = 0; FILE *fp = 0; // Allocate a console AllocConsole(); // redirect unbuffered STDOUT to the console lStdHandle = GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(PtrToUlong(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "w"); *stdout = *fp; setvbuf(stdout, NULL, _IONBF, 0); // redirect unbuffered STDIN to the console lStdHandle = GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(PtrToUlong(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "r"); *stdin = *fp; setvbuf(stdin, NULL, _IONBF, 0); // redirect unbuffered STDERR to the console lStdHandle = GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(PtrToUlong(lStdHandle), _O_TEXT); fp = _fdopen(hConHandle, "w"); *stderr = *fp; setvbuf(stderr, NULL, _IONBF, 0); } /* * print to the console */ void Console::WriteLine(char* str) { printf(str); NewLine(); } /* * print formatted to console */ void Console::WriteLineF(char* str, ...) { va_list argptr = NULL; va_start(argptr, str); vprintf(str, argptr); va_end(argptr); printf("\n"); } /* * print formatted to console */ void Console::WriteLineF(LPWSTR str, ...) { va_list argptr = NULL; va_start(argptr, str); vwprintf(str, argptr); va_end(argptr); printf("\n"); } /* * print to the console */ void Console::WriteLine(LPWSTR str) { wprintf(str); NewLine(); } /* * print to the console */ void Console::Write(char* str) { printf(str); } /* * print to the console */ void Console::Write(LPWSTR str) { wprintf(str); } /* * Print a new line */ void Console::NewLine() { printf("\n"); } /* * Set consoles title */ void Console::SetTitle(LPCSTR str) { SetConsoleTitle(str); } void Console::Wait() { _getch(); } void Console::Wait(char* str) { Console::Write(str); Console::Wait(); } void Console::Wait(LPWSTR str) { Console::Write(str); Console::Wait(); } void Console::WaitLine(char* str) { Console::WriteLine(str); Console::Wait(); } void Console::WaitLine(LPWSTR str) { Console::WriteLine(str); Console::Wait(); } void Console::WaitF(char* str, ...) { va_list argptr = NULL; va_start(argptr, str); vprintf(str, argptr); va_end(argptr); Console::Wait(); } void Console::WaitF(LPWSTR str, ...) { va_list argptr = NULL; va_start(argptr, str); vwprintf(str, argptr); va_end(argptr); Console::Wait(); } void Console::WaitLineF(char* str, ...) { va_list argptr = NULL; va_start(argptr, str); vprintf(str, argptr); va_end(argptr); printf("\n"); Console::Wait(); } void Console::WaitLineF(LPWSTR str, ...) { va_list argptr = NULL; va_start(argptr, str); vwprintf(str, argptr); va_end(argptr); printf("\n"); Console::Wait(); }
true
844c1ad4d2a6fe94de4518785187a19df6e96a03
C++
benmandrew/Andleite
/header/input.h
UTF-8
679
2.71875
3
[ "MIT" ]
permissive
#ifndef __INPUT_H_INCLUDED__ #define __INPUT_H_INCLUDED__ #pragma once #include <map> #include <SDL2/SDL.h> #include "observer.h" enum InputEvent { KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT }; typedef std::map<SDL_Keycode, InputEvent> keyMap; class Input : public Subject { private: bool quit = false; static const std::map<SDL_Keycode, InputEvent> inputMap; static std::map<SDL_Keycode, InputEvent> createMap() { std::map<SDL_Keycode, InputEvent> m; m[SDLK_w] = KEY_UP; m[SDLK_s] = KEY_DOWN; m[SDLK_a] = KEY_LEFT; m[SDLK_d] = KEY_RIGHT; return m; } public: void pollEvents(); bool doQuit(); }; #endif
true
19a160baef73b42a14a6b547fc9261fbf45d3417
C++
wxx17395/Leetcode
/c++ project/Question bank/Q700-Q799/Q785.cpp
UTF-8
933
3.375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { vector<int> color; bool valid; public: bool isBipartite(vector<vector<int>>& graph) { int n = graph.size(); valid = true; color.assign(n, 0); for (int i = 0; i < n && valid; ++i){ if (color[i] == 0){ dfs(i,1,graph); } } return valid; } private: void dfs(int node, int c, const vector<vector<int>>& graph){ color[node] = c; int cNext = (c == 1 ? 2 : 1); for (int next : graph[node]){ if (color[next] == 0){ dfs(next, cNext, graph); if (!valid){ return; } } else if (color[next] != cNext){ valid = false; return; } } } }; int main() { std::cout << "Hello, World!" << std::endl; return 0; }
true
accb5fcbccccdc509dde2528dad66e36ba23ed96
C++
J-dog22/Windows-Recon-Deceptor
/Deceptive_whoami/Source.cpp
UTF-8
3,717
2.6875
3
[]
no_license
#include <iostream> #include <fstream> #include <string> using namespace std; int main(int argc, char* argv[]) { ifstream infile; string user = "\\User1"; string tmp; if (argc == 1) { infile.open("..\\..\\..\\Results_files\\computerName.txt"); if (infile.is_open()) { if (getline(infile, tmp)) { cout << tmp << user << "\n"; } infile.close(); } else cout << "Unable to open file"; } else if (string(argv[1]) == "/?") { infile.open("..\\..\\..\\Results_files\\whoami_results_files\\whoami_help.txt"); if (infile.is_open()) { while (getline(infile, tmp)) { cout << tmp << "\n"; } infile.close(); } else cout << "Unable to open file"; } else if (string(argv[1]) == "/user") { int count = 0; int startLine; infile.open("..\\..\\..\\Results_files\\whoami_results_files\\whoami_all.txt"); if (infile.is_open()) { while (getline(infile, tmp)) { if (string(tmp).find("User Name") != std::string::npos) { startLine = count; //cout << startLine << " is the starting\n"; } count++; } infile.clear(); infile.seekg(0, infile.beg); count = 0; cout << "\nUSER INFORMATION\n----------------\n\n"; while (getline(infile, tmp)) { if (count >= startLine) { if (tmp.empty()) { break; } cout << tmp << "\n"; } count++; } infile.close(); } else cout << "Unable to open file"; } else if (string(argv[1]) == "/groups") { int count = 0; int startLine; infile.open("..\\..\\..\\Results_files\\whoami_results_files\\whoami_all.txt"); if (infile.is_open()) { while (getline(infile, tmp)) { if (string(tmp).find("Group Name") != std::string::npos) { startLine = count; //cout << userStart << " is the starting\n"; } count++; } infile.clear(); infile.seekg(0, infile.beg); count = 0; cout << "\nGROUP INFORMATION\n-----------------\n\n"; while (getline(infile, tmp)) { if (count >= startLine) { if (tmp.empty()) { break; } cout << tmp << "\n"; } count++; } infile.close(); } else cout << "Unable to open file"; } else if (string(argv[1]) == "/priv") { int count = 0; int startLine; infile.open("..\\..\\..\\Results_files\\whoami_results_files\\whoami_all.txt"); if (infile.is_open()) { while (getline(infile, tmp)) { if (string(tmp).find("Privilege Name") != std::string::npos) { startLine = count; //cout << userStart << " is the starting\n"; } count++; } infile.clear(); infile.seekg(0, infile.beg); count = 0; cout << "\nPRIVILEGES INFORMATION\n----------------------\n\n"; while (getline(infile, tmp)) { if (count >= startLine) { if (tmp.empty()) { break; } cout << tmp << "\n"; } count++; } infile.close(); } else cout << "Unable to open file"; } else if (string(argv[1]) == "/all") { infile.open("..\\..\\..\\Results_files\\whoami_results_files\\whoami_all.txt"); if (infile.is_open()) { while (getline(infile, tmp)) { cout << tmp << "\n"; } infile.close(); } else cout << "Unable to open file"; } // // logging // time_t result = time(NULL); char dt[26]; ctime_s(dt, sizeof dt, &result); //cout << "The UTC date and time is:" << dt << endl; ofstream outfile; outfile.open("..\\..\\..\\Results_files\\logfile.txt", ios::app); outfile << dt << "\t" << string(argv[0]) << " " << string(argv[1]) << "\n"; outfile.close(); return 0; }
true
375134cc85fc95a21d6ab8a1a44607ed6b824c00
C++
Verssae/TypingTrainer
/TypingTrainer/Utill.cpp
UHC
6,243
2.71875
3
[]
no_license
#include "Utill.h" #include <Windows.h> #include <conio.h> #include <iomanip> #include <sstream> using namespace std; FileManager::FileManager() : mRankings() { cout << "!\n"; } FileManager::~FileManager() { } void FileManager::RoadRanking() { // txt Ͽ ŷ ͸ mRankings ifstream fin; fin.open("Ranking.txt" ); // ӽ if (fin.is_open()) { while (!fin.eof()) { string str,tmp; int acc, time, cpm; getline(fin, tmp); istringstream iss(tmp); iss >> str >> acc >> time >> cpm; if (iss.fail()) { break; } Ranking data(str, acc, time, cpm); mRankings.push_back(data); } fin.close(); } else { ofstream fout; fout.open("Ranking.txt"); } } void FileManager::SaveRanking() { // mRankings ŷ ͸ txt Ϸ ofstream Write; string tmp; Write.open("Ranking.txt"); for (int i = 0; i < mRankings.size(); i++) { tmp = ""; tmp = tmp + mRankings[i].GetNick() + " " + to_string(mRankings[i].GetAccuracy()) + " " + to_string(mRankings[i].GetTime()) + " " + to_string(mRankings[i].GetCPM()) + "\n"; Write.write(tmp.c_str(), tmp.size()); } Write.close(); } void FileManager::ShowRanking() { for (int i = 0; i < mRankings.size(); i++) { cout << mRankings[i].GetNick() << ", " << mRankings[i].GetAccuracy() << ", " << mRankings[i].GetTime() << ", " << mRankings[i].GetCPM() << "\n"; } } void FileManager::Realignment(char Type, string Order) { Ranking tmp; if (Order == "UP") { switch (Type) { case 'N': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetNick() < mRankings[j].GetNick()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'A': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetAccuracy() < mRankings[j].GetAccuracy()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'T': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetTime() < mRankings[j].GetTime()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'C': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetCPM() < mRankings[j].GetCPM()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; } } else { // DOWN switch (Type) { case 'N': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetNick() > mRankings[j].GetNick()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'A': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetAccuracy() > mRankings[j].GetAccuracy()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'T': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetTime() > mRankings[j].GetTime()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; case 'C': for (int i = 0; i < mRankings.size(); i++) { for (int j = i + 1; j < mRankings.size(); j++) { if (mRankings[i].GetCPM() > mRankings[j].GetCPM()) { tmp = mRankings[i]; mRankings[i] = mRankings[j]; mRankings[j] = tmp; } } } break; } } } Ranking::Ranking() : mNick(""), mAccuracy(0), mTime(0), mCPM(0) {} Ranking::Ranking(const string nick, const int acc, const int time, const int cpm) : mNick(nick), mAccuracy(acc), mTime(time), mCPM(cpm) { } Ranking::~Ranking() {} void Ranking::Update(const string nick, const int acc, const int time, const int cpm) { mNick = nick; mAccuracy = acc; mTime = time; mCPM = cpm; } namespace console { // http://www.cplusplus.com/forum/windows/121444/ void SetColor(unsigned short color) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color); } void SetWindowSize(int x, int y) { HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE); if (h == INVALID_HANDLE_VALUE) throw std::runtime_error("Unable to get stdout handle."); // If either dimension is greater than the largest console window we can have, // there is no point in attempting the change. { COORD largestSize = GetLargestConsoleWindowSize(h); if (x > largestSize.X) throw std::invalid_argument("The x dimension is too large."); if (y > largestSize.Y) throw std::invalid_argument("The y dimension is too large."); } CONSOLE_SCREEN_BUFFER_INFO bufferInfo; if (!GetConsoleScreenBufferInfo(h, &bufferInfo)) throw std::runtime_error("Unable to retrieve screen buffer info."); SMALL_RECT& winInfo = bufferInfo.srWindow; COORD windowSize = { winInfo.Right - winInfo.Left + 1, winInfo.Bottom - winInfo.Top + 1 }; if (windowSize.X > x || windowSize.Y > y) { // window size needs to be adjusted before the buffer size can be reduced. SMALL_RECT info = { 0, 0, x < windowSize.X ? x - 1 : windowSize.X - 1, y < windowSize.Y ? y - 1 : windowSize.Y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window before resizing buffer."); } COORD size = { x, y }; if (!SetConsoleScreenBufferSize(h, size)) throw std::runtime_error("Unable to resize screen buffer."); SMALL_RECT info = { 0, 0, x - 1, y - 1 }; if (!SetConsoleWindowInfo(h, TRUE, &info)) throw std::runtime_error("Unable to resize window after resizing buffer."); } void SetCursorVisible(bool visible) { CONSOLE_CURSOR_INFO cur; cur.bVisible = visible; cur.dwSize = 2; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cur); } }
true
3910daf8cdbd53537e2b53027c95aa691a913de9
C++
Jiltseb/Leetcode-Solutions
/solutions/715.range-module.246936325.ac.cpp
UTF-8
1,605
3.375
3
[ "MIT" ]
permissive
map<int, int>::iterator lower_bound2(map<int, int> &mp, int key) { if (mp.empty()) return mp.end(); auto it = mp.lower_bound(key); if (it->first == key) return it; if (it == mp.begin()) return mp.end(); it--; return it; } class RangeModule { map<int, int> mp; public: RangeModule() {} void addRange(int left, int right) { removeRange(left, right); auto it = lower_bound2(mp, left); right--; if (it != mp.end() && it->second == left - 1) left = it->first; if (mp.count(right + 1)) { int t = right + 1; right = mp.find(t)->second; mp.erase(t); } mp[left] = right; } bool queryRange(int left, int right) { right--; auto it = lower_bound2(mp, left); return it != mp.end() && it->second >= right; } void removeRange(int left, int right) { right--; if (mp.empty()) return; auto it = mp.lower_bound(left); if (it != mp.begin()) { it--; if (it->first < left) { if (it->second >= left) { if (it->second > right) mp[right + 1] = it->second; it->second = left - 1; } } it++; } while (it != mp.end() && it->first <= right) { auto temp = it; it++; if (temp->second > right) mp[right + 1] = temp->second; mp.erase(temp); } } }; /** * Your RangeModule object will be instantiated and called as such: * RangeModule* obj = new RangeModule(); * obj->addRange(left,right); * bool param_2 = obj->queryRange(left,right); * obj->removeRange(left,right); */
true
1cae3cec96f2e89dee249d25b79121904d7807ae
C++
pzdksnb/Basic_oop
/Basic/program.cpp
UTF-8
3,239
3.03125
3
[]
no_license
/* * File: program.cpp * ----------------- * This file is a stub implementation of the program.h interface * in which none of the methods do anything beyond returning a * value of the correct type. Your job is to fill in the bodies * of each of these methods with an implementation that satisfies * the performance guarantees specified in the assignment. */ #include <string> #include "program.h" #include "statement.h" #include "../StanfordCPPLib/error.h" using namespace std; Program::Program() { } Program::~Program() { this->clear(); } void Program::clear() { for(auto &it:mp){ delete it.second.exp; it.second.exp = nullptr; } mp.clear(); } void Program::addSourceLine(int lineNumber, string line) { if(mp.count(lineNumber)==1) { mp[lineNumber].information =line; if(mp[lineNumber].exp!=nullptr) mp[lineNumber].exp=nullptr ; } if(mp.count(lineNumber)==0) mp[lineNumber]=line; } void Program::removeSourceLine(int lineNumber) { if(mp.count(lineNumber)==0) error("SYNTAX ERROR"); if(mp.count(lineNumber)==1) { delete mp[lineNumber].exp; mp.erase(lineNumber); }; } string Program::getSourceLine(int lineNumber) { if(mp.count(lineNumber)==1) return "lineNumber"; if(mp.count(lineNumber)==0) return ""; } void Program::setParsedStatement(int lineNumber, Statement *st) { if(mp.count(lineNumber)==0) error("SYNTAX ERROR"); else { delete mp[lineNumber].exp; mp[lineNumber].exp=st; } } Statement *Program::getParsedStatement(int lineNumber) { if(mp.count(lineNumber)==1) return mp[lineNumber].exp; if(mp.count(lineNumber)==0) error("SYNTAX ERROR"); } int Program::getFirstLineNumber() { if(mp.empty()){ return -1; } auto it = mp.begin(); return it->first; } int Program::getNextLineNumber(int lineNumber) { if(mp.count(lineNumber+1)==1) return lineNumber+1; if(mp.count(lineNumber)==0 || mp.count(lineNumber+1)==0) return -1; } bool Program::Find(int a){ auto it=mp.begin(); for(;it!=mp.end();it++){ if(it->first == a) return true; } return false; } void Program::show(){ auto it=mp.begin(); for(;it!=mp.end();it++){ cout<<it->second.information<<endl; } } void Program::runprogram(EvalState &state){ if(mp.empty()) { error("error running"); return; } auto it = mp.begin(); for( ;it!=mp.end();it++){ try{ (it->second.exp)->execute(state); } catch(ErrorException &a){ TokenScanner scanner; if(scanner.getTokenType(a.getMessage())==NUMBER){ if(!this->Find(stringToInteger(a.getMessage()))){ error("goto"); return; } else{ int n=stringToInteger(a.getMessage()); it=mp.find(n); continue; } }else{ error(a.getMessage()); } } catch (int lineNumber) { // int a=stringToInteger(output); it=mp.find(lineNumber); if(it!=mp.end()) it--; else error("goto"); } } }
true
c16031feb447e4caa591470b786ad6d0ae8a9ce3
C++
stefanpantic/pascalina
/include/ast/iteration.hpp
UTF-8
871
3.140625
3
[]
no_license
#pragma once #include <memory> // unique_ptr #include "expression.hpp" #include "statement.hpp" namespace pascalina { /* * @brief AST node for iteration statement. */ class iteration : public statement { public: explicit iteration(expression *condition, statement *body) : m_condition(std::move(condition)), m_body(std::move(body)) { std::clog << "[constructor]" << __PRETTY_FUNCTION__ << std::endl; } // Getters inline const expression *condition() const { return m_condition.get(); } inline const statement *body() const { return m_body.get(); } // Accept visitor member function llvm::Value *accept(util::visitor &v) const override { return v.visit(*this); } private: std::unique_ptr<expression> m_condition; std::unique_ptr<statement> m_body; }; // class pascalina::iteration } // namespace pascalina
true
20a0634191ecf2815cf217c0cd9fdce6388662e7
C++
rlodina99/Learn_cpp
/Olimpiada/2015/9_enunturi/rlodina_arc.cpp
UTF-8
2,636
2.75
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> using namespace std; ifstream f("arc.in"); //ifstream f ("C:\\Eval_OJI_2014_IX\\probleme\\arc\\teste\\5-arc.in"); ofstream g ("arc.out"); int main() { int v; //nr cerintei int n; //nr de bile f>>v; f>>n; int arr[n]; for(int i =0; i< n; i++){ f >> arr[i]; } int auxVal = arr[0]; int auxNr = 1; if (v == 1){ for(int i=1; i<n; i++ ){ if (auxVal != arr[i]) { auxNr ++; auxVal = arr[i]; } } g << auxNr; } else { int idx = 0; //index start secventa int val = 0; //valoare (nr) bila din secvanta int nr = 0; //cate bile sunt in secventa int idxMax = 0; //index start secventa maxima int nrMax = 0; //cate bile sunt in secventa maxima int k = 1; //de unde sa inceap cautarea secventei maxime while(1){ idx = idxMax = k; val = arr[k]; nr = nrMax = 1; //caut secventa maxima incepand cu idx for(int i = k; i<n; i++){ if (arr[i] == 0 ) continue; //bila eliminata if (val == arr[i]){ nr ++; } else { if (nr > nrMax){ nrMax = nr; idxMax = idx; } idx = i; val = arr[i]; nr = 1; } } if (nrMax <=2){ //nu am gasit nici o secventa > de 3 bile int nrRamase = 0; //cate bile au ramas for(int i = 0; i<n; i++){ if (arr[i] > 0) nrRamase ++; } g << nrRamase << '\n'; for(int i = 0; i<n; i++){ if (arr[i] > 0) g << arr[i] << '\n'; } } else { //elimin din sir (le pun pe 0) nrMax bile inceand cu idxMax int j = idxMax; while(nrMax){ if (arr[j] != 0) { arr[j] = 0; nrMax --; } j++; } for(int i = 0; i<n; i++) cout << arr[i] << " "; //verific daca dupa eliminare in zona in care am eliminat s-a great o noua grupare de minim 3 bile //pt. asta mut k inapoi pe inceput secventa identica cu arr[idxMax-1] j = idxMax-1; if (j <0) continue; //am eliminat pana inceput val = arr[j]; nr = 1; while(j<0){ // mergem inspre inceput pana gasim inceputul unei secvente if (arr[j] != 0){ if (val != arr[j]) break; } j--; } if (j>0) k = j; //pornim cautarea urmatoarei secvente din vecinatatea elimanarii de mai sus } } } return 0; }
true
6bbeeb77c93c70be55bc7d0032b345a43f222703
C++
ZyrianCode/Library
/pExpressionFormatter.h
UTF-8
3,039
3.15625
3
[]
no_license
#pragma once #include <string> #include <vector> #include <stack> #include <utility> #include "Validator.h" using std::string; using std::to_string; using std::stack; using std::vector; using std::pair; class ExpressionFormatter { string _expression; public: ExpressionFormatter(); ~ExpressionFormatter(); vector<string> FormateToInfix(vector<string> &Expression); private: void FormateNumbers(vector<string>& Expression, int& i, vector<string>& InfixExpression, string& Token, string& NumbersCell); void FormateOperators(vector<string>& Expression, int& i, vector<string>& InfixExpression, string& Token, string& NumbersCell); void FormateLetters(vector<string>& Expression, int& i, vector<string>& InfixExpression, string& Token, string& NumbersCell); void FormateFunctions(vector<string>& Expression, int& i, vector<string>& InfixExpression, string& Token, string& NumbersCell); void FormateBrackets(vector<string>& Expression, int& i, vector<string>& InfixExpression, string& Token, string& NumbersCell); bool IsFunction(string& Token); int CheckPositionOfFirstLetterWhichMatchesToExistingFunctionName(string& Expression); void ReincarnateInBracketsExpression(vector<string>& InfixExpression, string& Token, string& ReincarnatedOpeningBracket, string& ReincarnatedOperand, string& ReincarnatedClosingBracket); void ReincarnateOpeningBracketAfterToken(vector<string>& InfixExpression, string& Token, string& ReincarnatedOpeningBracket); void ReincarnateBracketBetweenTokenAndOperand(vector<string>& InfixExpression, string& Token, string& ReincarnatedBracket, string& ReincarnatedOperand); void PlaceReincarnatedOperandAfterToken(vector<string>& InfixExpression, string& Token, string& ReincarnatedOperand); void PlaceTokenAfterReincarnatedOperand(vector<string>& InfixExpression, string& ReincarnatedOperand, string& Token); void PlaceReincarnatedOperatorAfterNumericOperand(vector<string>& InfixExpression, string& NumericOperand, string& ReincarnatedOperator); void PlacedTokenAfterNumericOperand(vector<string>& InfixExpression, string& NumericOperand, string& Token); void PlaceReincarnatedOperatorBetweenTokenAndReincarnatedOperand(vector<string>& InfixExpression, string& Token, string& ReincarnatedOperator, string& ReincarnatedOperand); void PlaceReincarnatedOperatorBetweenNumericOperandAndToken(vector<string>& InfixExpression, string& NumericOperand, string& ReincarnatedOperator, string& Token); void PlaceTokenBetweenReincarnatedOperands(vector<string>& InfixExpression, string& Token, string& ReincarnatedOperand); void PlaceTokenAndReincarnateOperand(vector<string>& InfixExpression, string& Token, string& ReincarnatedOperand); void PlaceTokenAndReincarnateOperator(vector<string>& InfixExpression, string& Token, string& ReincarnatedOperator); void PlaceReincarnatedOperandAfterNumericOperandAndToken(vector<string>& InfixExpression, string& NumericOperand, string& Token, string& ReincarnatedOperand); };
true
54b31b3da1ef978ec6945963376b60025e02de4c
C++
PriyaPilla4/Cplusplus
/Maze Game/room.hpp
UTF-8
818
2.984375
3
[]
no_license
// // room.hpp // projectnumber2 // // Created by Priya Pilla on 2/24/20. // Copyright © 2020 Priya Pilla. All rights reserved. // #ifndef room_hpp #define room_hpp #include <stdio.h> #include <iostream> #include <vector> #include "passage.hpp" class Room{ private: std::string name = "no name"; std::vector<std::string> items; Passage* northPassage; Passage* eastPassage; Passage* southPassage; Passage* westPassage; public: Room(); Room(std::string _name, Passage* nP , Passage* eP, Passage* sP , Passage* wP); std::string GetName(); Passage* GetNorthPassage(); Passage* GetEastPassage(); Passage* GetSouthPassage(); Passage* GetWestPassage(); void AddItem(std::string item); std::string AcquireNextItem(); }; #endif /* room_hpp */
true
1e6bba22992f485e295bff77f65fcdfaebb49aa2
C++
thalium/icebox
/third_party/retdec-3.2/src/fileformat/types/resource_table/resource_table.cpp
UTF-8
7,708
2.90625
3
[ "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "OpenSSL", "WTFPL", "LGPL-2.1-only", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LGPL-2.0-or-later", "JSON", "Zlib", "NCSA", "LicenseRef-scancode-proprietary-license", "G...
permissive
/** * @file src/fileformat/types/resource_table/resource_table.cpp * @brief Class for resource table. * @copyright (c) 2017 Avast Software, licensed under the MIT license */ #include <sstream> #include "retdec/utils/conversion.h" #include "retdec/fileformat/types/resource_table/resource_table.h" using namespace retdec::utils; namespace retdec { namespace fileformat { /** * Constructor */ ResourceTable::ResourceTable() { } /** * Destructor */ ResourceTable::~ResourceTable() { } /** * Get number of stored resources * @return Number of stored resources */ std::size_t ResourceTable::getNumberOfResources() const { return table.size(); } /** * Get total declared size of resources * @return Total declared size of resources */ std::size_t ResourceTable::getSizeInFile() const { std::size_t sum = 0; for(const auto &r : table) { sum += r.getSizeInFile(); } return sum; } /** * Get total loaded size of resources * @return Total loaded size of resources */ std::size_t ResourceTable::getLoadedSize() const { std::size_t sum = 0; for(const auto &r : table) { sum += r.getLoadedSize(); } return sum; } /** * Get selected resource * @param rIndex Index of selected resource (indexed from 0) * @return Pointer to selected resource or @c nullptr if resource index is invalid */ const Resource* ResourceTable::getResource(std::size_t rIndex) const { return (rIndex < getNumberOfResources()) ? &table[rIndex] : nullptr; } /** * Get resource by name * @param rName Name of the resource to get * @return Pointer to resource with the specified name or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithName(const std::string &rName) const { for(const auto &r : table) { if(r.getName() == rName) { return &r; } } return nullptr; } /** * Get resource by name ID * @param rId Name ID of the resource to get * @return Pointer to resource with specified name ID or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithName(std::size_t rId) const { std::size_t tmpId; for(const auto &r : table) { if(r.getNameId(tmpId) && tmpId == rId) { return &r; } } return nullptr; } /** * Get resource by type * @param rType Type of the resource to get * @return Pointer to resource with the specified type or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithType(const std::string &rType) const { for(const auto &r : table) { if(r.getType() == rType) { return &r; } } return nullptr; } /** * Get resource by type ID * @param rId Type ID of the resource to get * @return Pointer to resource with specified type ID or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithType(std::size_t rId) const { std::size_t tmpId; for(const auto &r : table) { if(r.getTypeId(tmpId) && tmpId == rId) { return &r; } } return nullptr; } /** * Get resource by language * @param rLan Language of the resource to get * @return Pointer to resource with the specified language or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithLanguage(const std::string &rLan) const { for(const auto &r : table) { if(r.getLanguage() == rLan) { return &r; } } return nullptr; } /** * Get resource by language ID * @param rId Language ID of the resource to get * @return Pointer to resource with specified language ID or @c nullptr if such resource not found */ const Resource* ResourceTable::getResourceWithLanguage(std::size_t rId) const { std::size_t tmpId; for(const auto &r : table) { if(r.getLanguageId(tmpId) && tmpId == rId) { return &r; } } return nullptr; } /** * Get begin iterator * @return Begin iterator */ ResourceTable::resourcesIterator ResourceTable::begin() const { return table.begin(); } /** * Get end iterator * @return End iterator */ ResourceTable::resourcesIterator ResourceTable::end() const { return table.end(); } /** * Delete all records from table */ void ResourceTable::clear() { table.clear(); } /** * Add resource * @param newResource Resource which will be added */ void ResourceTable::addResource(Resource &newResource) { table.push_back(newResource); } /** * Find out if there are any resources * @return @c true if there are some resources, @c false otherwise */ bool ResourceTable::hasResources() const { return !table.empty(); } /** * Check if resource with name @a rName exists * @param rName Name of resource * @return @c true if has resource with name @a rName, @c false otherwise */ bool ResourceTable::hasResourceWithName(const std::string &rName) const { return getResourceWithName(rName); } /** * Check if resource with name ID @a rId exists * @param rId Name ID of resource * @return @c true if has resource with name ID @a rId, @c false otherwise */ bool ResourceTable::hasResourceWithName(std::size_t rId) const { return getResourceWithName(rId); } /** * Check if resource with type @a rType exists * @param rType Type of resource * @return @c true if has resource with type @a rType, @c false otherwise */ bool ResourceTable::hasResourceWithType(const std::string &rType) const { return getResourceWithType(rType); } /** * Check if resource with type ID @a rId exists * @param rId Type ID of resource * @return @c true if has resource with type ID @a rId, @c false otherwise */ bool ResourceTable::hasResourceWithType(std::size_t rId) const { return getResourceWithType(rId); } /** * Check if resource with language @a rLan exists * @param rLan Language of resource * @return @c true if has resource with language @a rLan, @c false otherwise */ bool ResourceTable::hasResourceWithLanguage(const std::string &rLan) const { return getResourceWithLanguage(rLan); } /** * Check if resource with language ID @a rId exists * @param rId Language ID of resource * @return @c true if has resource with language ID @a rId, @c false otherwise */ bool ResourceTable::hasResourceWithLanguage(std::size_t rId) const { return getResourceWithLanguage(rId); } /** * Dump information about all resources in table * @param dumpTable Into this parameter is stored dump of table in an LLVM style */ void ResourceTable::dump(std::string &dumpTable) const { std::stringstream ret; ret << "; ------------ Resources ------------\n"; ret << "; Number of resources: " << getNumberOfResources() << "\n"; ret << "; Declared size of resources: " << std::hex << getSizeInFile() << "\n"; ret << "; Loaded size of resources: " << getLoadedSize() << std::dec << "\n"; if(hasResources()) { std::size_t aux; ret << ";\n"; for(const auto &res : table) { auto sName = (res.hasEmptyName() && res.getNameId(aux)) ? numToStr(aux, std::dec) : res.getName(); auto sType = (res.hasEmptyType() && res.getTypeId(aux)) ? numToStr(aux, std::dec) : res.getType(); auto sLang = res.getLanguage(); if(sType.empty()) { sType = "-"; } if(sLang.empty()) { if(res.getLanguageId(aux)) { sLang = numToStr(aux, std::dec); if(res.getSublanguageId(aux)) { sLang += ":" + numToStr(aux, std::dec); } } else { sLang = "-"; } } const auto md5 = res.hasMd5() ? res.getMd5() : "-"; ret << "; " << sName << " (type: " << sType << ", language: " << sLang << ", offset: " << numToStr(res.getOffset(), std::hex) << ", declSize: " << numToStr(res.getSizeInFile(), std::hex) << ", loadedSize: " << numToStr(res.getLoadedSize(), std::hex) << ", md5: " << md5 << ")\n"; } } dumpTable = ret.str() + "\n"; } } // namespace fileformat } // namespace retdec
true
9258071f4d1f69c263ae02a6fce04d2dcecc0b70
C++
ji12345ba/CS225-UIUC
/mp7/DirectedEdge.h
UTF-8
264
3
3
[]
no_license
#pragma once #include "Vertex.h" #include "Edge.h" class DirectedEdge : public Edge { public: DirectedEdge(const Vertex & source, const Vertex & dest, double weight = 1) : Edge(source, dest, weight) { }; bool directed() const { return true; } };
true
38c397b2a70a47b41385ff1797341741b8326ce9
C++
anshumanvarshney/CODE
/Basic Implementation/linkedlist/no need/concatll.cpp
UTF-8
1,602
3.9375
4
[]
no_license
#include<iostream> using namespace std; class list { private: struct node { int data; node *link; }*p; //p always points to first element; public: list(); void append(int); void display(); void count(); void concat(list &l); ~list(); }; list::list() { p=NULL; } void list::append(int num) { node *temp,*r; if(p==NULL) { p=new node; p->data = num; p->link=NULL; } else { temp=p; while(temp->link!=NULL) // we can't use temp!=NULL because here we have to append through its address; temp=temp->link; r=new node; r->data=num; r->link=NULL; temp->link=r; } } void list::display() { node *temp; temp=p; cout<<"\n"; while(temp!=NULL) // here we can't use temp->link!=NULL because we have to display last value also; { cout<<temp->data<<" "; temp=temp->link; } } void list :: concat(list &l) { node *temp; if(p==NULL) //if first ll is empty { p=l.p;//l.p conatins b ll } else {//if both ll are non-empty if(l.p!=NULL) { temp=p; while(temp->link!=NULL) { temp=temp->link; } //concatenate second string after first temp->link=l.p; } } l.p=NULL; //(all time neccessary) } list::~list() { node *temp; temp=p; while(temp!=NULL) { temp=temp->link; delete p; p=temp; } } int main() { list a,b; a.append(2); a.append(3); a.append(4); a.append(5); a.display(); b.append(6); b.append(7); b.append(8); b.append(9); b.display(); a.concat(b); a.display(); }
true
8a71b6397b79c0946d4a27f31a2077cbc50fcecb
C++
Koura/sibot
/SIBot/StateMastermind.h
UTF-8
861
2.59375
3
[]
no_license
#pragma once #include <BWAPI.h> #include <vector> #include <sstream> #include <limits> class StateMastermind { public: StateMastermind(); ~StateMastermind(); void create(int enemyCount); void destroy(); int observe(BWAPI::Unit* hero, std::set<BWAPI::Unit*> enemies); void setPrevious(int value); int getPrevious(); void setPreviousA(int a); int getPreviousA(); int getEnemyHP(); void setAlliedHP(int value); int getAlliedHP(); int getStateSize(); private: int weaponCooldown(BWAPI::Unit* hero); int abilityCooldown(BWAPI::Unit* hero); int distanceToClosestEnemy(BWAPI::Unit *hero, std::set<BWAPI::Unit*> enemies); int enemiesInRange(BWAPI::Unit *hero, std::set<BWAPI::Unit*> enemies); int currentHealth(BWAPI::Unit *hero); std::vector<std::string> m_states; int m_previousState; int m_previousAction; int m_hpEnemies; int m_hpAllies; };
true
4a801d8e7da9c9da3f0cce8619391987cc23b090
C++
mathiasuy/p4-lab2
/src/logica/Sala.cpp
UTF-8
1,920
2.953125
3
[]
no_license
#include "../../include/logica/Sala.h" #include "../../include/logica/Cine.h" #include <iostream> int Sala::getID(){ return this->id; }; void Sala::setID(int id){ this->id = id; }; int Sala::getCapacidad(){ return capacidad; }; void Sala::setCapacidad(int capacidad){ this->capacidad = capacidad; }; bool Sala::agregarFuncion(Funcion* funcion){ //agrego puntero hacia funcion en el map con la clave igual al idfuncion this->funciones[funcion->getID()] = funcion; return true; }; bool Sala::quitarFuncion(Funcion* funcion){ //quitar puntero de funcion del map return this->funciones.erase(funcion->getID()); }; bool Sala::isEqual(Sala* sala){ return this->getID() == sala->getID(); }; DtSala Sala::getDt(){ Cine* cine = this->getCine(); return DtSala(this->getID(),this->getCapacidad(), cine->getDt()); }; void Sala::setOcupado(int dia,int hora){ this->ocupado[dia][hora] = true; }; void Sala::setOcupadolibre(int dia,int hora){ this->ocupado[dia][hora] = false; this->ocupado[dia][hora+1] = false; }; bool Sala::getOcupado(int dia, int hora){ return this->ocupado[dia][hora]; }; bool Sala::perteneceA(Cine* cine){ return this->cine->isEqual(cine); } string Sala::toString(){ //cout << "\nID Sala: _" << this->getID() << "_\n" ; return "Esta es la sala " + Utils::aString(this->getID());// + Utils::aString(this->getID()); }; Cine* Sala::getCine(){ return this->cine; }; Sala::Sala(int id, int capacidad, Cine* cine){ this->id = id; this->cine = cine; this->setCapacidad(capacidad); //creo map de punteros std::map<int, Funcion*> mymap; this->funciones = mymap; this->ocupado[31][24] = false; }; Sala::~Sala(){}; bool Sala::tieneFuncion(int id){ return this->funciones.find(id) != this->funciones.end(); } bool Sala::esDeCine(int idCine){ return this->getCine()->getID() == idCine; };
true
7044d2247e8227b29ff3e27896f7db385a06f029
C++
DHaythem/Competitive-Programming-Solutions
/Codeforces/800/A. Anton and Danik.cpp
UTF-8
439
2.5625
3
[]
no_license
//https://codeforces.com/problemset/problem/734/A #include<bits/stdc++.h> #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); cout.precision(30); using namespace std; int main() { IOS; int a=0,d=0,n; string s; cin>>n>>s; for(int i=0;i<s.size();i++){ if(s[i]=='A') a++; else d++; } if(a==d) cout<<"Friendship"; else if (a>d) cout<<"Anton"; else cout<<"Danik"; return 0; }
true
5c96a245324f4ffc80730c15a1b1db8cec697b30
C++
jjzhang166/WinNT5_src_20201004
/NT/inetsrv/iis/admin/snapin/svc.cpp
UTF-8
10,543
2.65625
3
[]
no_license
#include "stdafx.h" #include "common.h" #include "svc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif //---------------------------------------------------------------------------------------- //Routine Description: // This routine allocates a buffer for the specified service's configuration parameters, // and retrieves those parameters into the buffer. The caller is responsible for freeing // the buffer. //Remarks: // The pointer whose address is contained in ServiceConfig is guaranteed to be NULL upon // return if any error occurred. //----------------------------------------------------------------------------------------- DWORD RetrieveServiceConfig(IN SC_HANDLE ServiceHandle,OUT LPQUERY_SERVICE_CONFIG *ServiceConfig) { DWORD ServiceConfigSize = 0, Err; if (NULL == ServiceConfig) { return ERROR_INVALID_PARAMETER; } *ServiceConfig = NULL; while(TRUE) { if(QueryServiceConfig(ServiceHandle, *ServiceConfig, ServiceConfigSize, &ServiceConfigSize)) { //assert(*ServiceConfig); return NO_ERROR; } else { Err = GetLastError(); if(*ServiceConfig) {free(*ServiceConfig);*ServiceConfig=NULL;} if(Err == ERROR_INSUFFICIENT_BUFFER) { // Allocate a larger buffer, and try again. if(!(*ServiceConfig = (LPQUERY_SERVICE_CONFIG) malloc(ServiceConfigSize))) { return ERROR_NOT_ENOUGH_MEMORY; } } else { if (ServiceConfig) { *ServiceConfig = NULL; } return Err; } } } } // returns SVC_NOTEXIST if the service does not exist // returns SVC_DISABLED if the service is disabled // returns SVC_AUTO_START if the the service is auto start // returns SVC_MANUAL_START if the the service is not auto start int GetServiceStartupMode(LPCTSTR lpMachineName, LPCTSTR lpServiceName) { int iReturn = SVC_NOTEXIST; SC_HANDLE hScManager = NULL; SC_HANDLE hService = NULL; LPQUERY_SERVICE_CONFIG ServiceConfig=NULL; // check if lpMachineName starts with \\ // if it doesn't then make sure it does, or it's null (for local machine) LPTSTR lpNewMachineName = NULL; if (_tcsicmp(lpMachineName, _T("")) != 0) { DWORD dwSize = 0; // Check if it starts with "\\" if (_tcsncmp(lpMachineName, _T("\\\\"), 2) == 0) { dwSize = (_tcslen(lpMachineName) * sizeof(TCHAR)) + (1 * sizeof(TCHAR)); lpNewMachineName = (LPTSTR) LocalAlloc(LPTR, dwSize); if(lpNewMachineName != NULL) { _tcscpy(lpNewMachineName, lpMachineName); } } else { dwSize = ((_tcslen(lpMachineName) * sizeof(TCHAR)) + (3 * sizeof(TCHAR))); lpNewMachineName = (LPTSTR) LocalAlloc(LPTR, dwSize); if(lpNewMachineName != NULL) { _tcscpy(lpNewMachineName, _T("\\\\")); _tcscat(lpNewMachineName, lpMachineName); } } } if ((hScManager = OpenSCManager(lpNewMachineName, NULL, GENERIC_ALL )) == NULL || (hService = OpenService( hScManager, lpServiceName, GENERIC_ALL )) == NULL ) { // Failed, or more likely the service doesn't exist iReturn = SVC_NOTEXIST; goto IsThisServiceAutoStart_Exit; } if(RetrieveServiceConfig(hService, &ServiceConfig) != NO_ERROR) { iReturn = SVC_NOTEXIST; goto IsThisServiceAutoStart_Exit; } if(!ServiceConfig) { iReturn = SVC_NOTEXIST; goto IsThisServiceAutoStart_Exit; } // SERVICE_AUTO_START Specifies a device driver or service started by the service control manager automatically during system startup. // SERVICE_BOOT_START Specifies a device driver started by the system loader. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER. // SERVICE_DEMAND_START Specifies a device driver or service started by the service control manager when a process calls the StartService function. // SERVICE_DISABLED Specifies a device driver or service that can no longer be started. // SERVICE_SYSTEM_START Specifies a device driver started by the IoInitSystem function. This value is valid only if the service type is SERVICE_KERNEL_DRIVER or SERVICE_FILE_SYSTEM_DRIVER. if (SERVICE_DISABLED == ServiceConfig->dwStartType) { iReturn = SVC_DISABLED; } else if (SERVICE_DEMAND_START == ServiceConfig->dwStartType) { iReturn = SVC_MANUAL_START; } else { iReturn = SVC_AUTO_START; } IsThisServiceAutoStart_Exit: if (ServiceConfig) {free(ServiceConfig);} if (hService) {CloseServiceHandle(hService);} if (hScManager) {CloseServiceHandle(hScManager);} if (lpNewMachineName) {LocalFree(lpNewMachineName);} return iReturn; } // SERVICE_DISABLED // SERVICE_AUTO_START // SERVICE_DEMAND_START INT ConfigServiceStartupType(LPCTSTR lpMachineName, LPCTSTR lpServiceName, int iNewType) { INT err = 0; SC_HANDLE hScManager = NULL; SC_HANDLE hService = NULL; LPQUERY_SERVICE_CONFIG ServiceConfig = NULL; DWORD dwNewServiceStartupType = 0; BOOL bDoStuff = FALSE; // check if lpMachineName starts with \\ // if it doesn't then make sure it does, or it's null (for local machine) LPTSTR lpNewMachineName = NULL; if (_tcsicmp(lpMachineName, _T("")) != 0) { DWORD dwSize = 0; // Check if it starts with "\\" if (_tcsncmp(lpMachineName, _T("\\\\"), 2) == 0) { dwSize = (_tcslen(lpMachineName) * sizeof(TCHAR)) + (1 * sizeof(TCHAR)); lpNewMachineName = (LPTSTR) LocalAlloc(LPTR, dwSize); if(lpNewMachineName != NULL) { _tcscpy(lpNewMachineName, lpMachineName); } } else { dwSize = ((_tcslen(lpMachineName) * sizeof(TCHAR)) + (3 * sizeof(TCHAR))); lpNewMachineName = (LPTSTR) LocalAlloc(LPTR, dwSize); if(lpNewMachineName != NULL) { _tcscpy(lpNewMachineName, _T("\\\\")); _tcscat(lpNewMachineName, lpMachineName); } } } do { if ((hScManager = ::OpenSCManager( lpMachineName, NULL, GENERIC_ALL )) == NULL || (hService = ::OpenService( hScManager, lpServiceName, GENERIC_ALL )) == NULL ) { err = GetLastError(); if (ERROR_SERVICE_DOES_NOT_EXIST != err) { } break; } if(RetrieveServiceConfig(hService, &ServiceConfig) != NO_ERROR) { err = GetLastError(); break; } if(!ServiceConfig) { err = GetLastError(); break; } // only set this on non-kernel drivers if ( (ServiceConfig->dwServiceType & SERVICE_WIN32_OWN_PROCESS) || (ServiceConfig->dwServiceType & SERVICE_WIN32_SHARE_PROCESS)) { // default it incase someone changes code below and logic gets messed up dwNewServiceStartupType = ServiceConfig->dwStartType; // if this service is disabled, // they don't do anything, just leave it alone. if (!(dwNewServiceStartupType == SERVICE_DISABLED)) { if (iNewType == SERVICE_DISABLED) { dwNewServiceStartupType = SERVICE_DISABLED; bDoStuff = TRUE; } else if (iNewType == SERVICE_AUTO_START) { // if the service is already the type we want then don't do jack // SERVICE_AUTO_START // SERVICE_BOOT_START // SERVICE_DEMAND_START // SERVICE_DISABLED // SERVICE_SYSTEM_START if (SERVICE_AUTO_START == dwNewServiceStartupType || SERVICE_BOOT_START == dwNewServiceStartupType || SERVICE_SYSTEM_START == dwNewServiceStartupType ) { // it's already auto start // we don't have to do anything } else { dwNewServiceStartupType = SERVICE_AUTO_START; bDoStuff = TRUE; } } else { // we want to make it manual start // check if it's already that way if (!(SERVICE_DEMAND_START == dwNewServiceStartupType)) { dwNewServiceStartupType = SERVICE_DEMAND_START; bDoStuff = TRUE; } } } else { if (iNewType == SERVICE_AUTO_START) { dwNewServiceStartupType = SERVICE_AUTO_START; bDoStuff = TRUE; } else { dwNewServiceStartupType = SERVICE_DEMAND_START; bDoStuff = TRUE; } } if (TRUE == bDoStuff) { if ( !::ChangeServiceConfig(hService, SERVICE_NO_CHANGE, dwNewServiceStartupType, SERVICE_NO_CHANGE, NULL, NULL, NULL, NULL, NULL, NULL, NULL) ) { err = GetLastError(); break; } } else { break; } } else { break; } } while ( FALSE ); if (ServiceConfig) {free(ServiceConfig);} if (hService) {CloseServiceHandle(hService);} if (hScManager) {CloseServiceHandle(hScManager);} if (lpNewMachineName) {LocalFree(lpNewMachineName);} return(err); }
true
f75ddc7489856032ed1b9d33fe426376b526f482
C++
talott/DijkstrasAlgorithm
/main.cpp
UTF-8
4,656
2.984375
3
[]
no_license
#include "graph.h" #include "util.h" #include "main.h" #include "stdlib.h" #include "string.h" VERTEX *V; int main(int argc, char *argv[]) { FILE *ifile; pNODE *A; pNODE node; char word[256]; char word2[256]; int n,m, directed_graph,i; int s, s_new, t, t_new, source, source_new, destination, destination_new; int u,v,edge_id, flag, flag_new; int v_scanf, v_fscanf; int r_value; float w; if (argc != 3) { printf("Command Format: %s <graph_file> <direction>\n", argv[0]); exit(1); } if(0 == strcmp(argv[2], "directed\0")) { directed_graph = 1; //printf("direct\n"); } if(0 == strcmp(argv[2], "undirected\0")) { directed_graph = 0; //printf("notdirect\n"); } //open network file for reading ifile = fopen(argv[1], "r"); if(!ifile) { printf("ErrorGLX1: cannot open file for reading.\n"); } //read in n=|V| and m=|E| v_fscanf = fscanf(ifile, "%d%d", &n, &m); if(v_fscanf < 2){ //printf("ErrorGLX2: fscanf returns %d. \n", v_fscanf); exit(1); } //printf("%d %d\n", n, m); //allocate memory for adjacent lists A = (pNODE *)calloc(n+1, sizeof (pNODE)); if(!A) { printf("Error: calloc failure.\n"); exit(1); } //read in edge and construct list for(i = 1; i<=m; i++) { v_fscanf = fscanf(ifile,"%d%d%d%f",&edge_id, &u, &v, &w); if(v_fscanf < 4) { printf("Error: fscanf returns %d.\n", v_fscanf); exit(1); } node = (pNODE)malloc(sizeof(NODE)); if(!node) { printf("Error: malloc failure.\n"); exit(1); } node->u = u; node->v = v; node->w = w; node->next = A[u]; A[u] = node; //Adds to both lists if undirected if(!directed_graph){ node = (pNODE)malloc(sizeof (NODE)); if(!node){ printf("Error: malloc failure.\n"); exit(1); } node->u = v; node->v = u; node->w = w; node->next = A[v]; A[v] = node; } } //close file fclose(ifile); source = 0; destination = 0; V = (VERTEX *) calloc(n+1, sizeof(VERTEX)); if(!V) { printf("Error: calloc failure.\n"); exit(1); } while(1) { r_value = nextWord(word); if(!r_value) { continue; } if(0 == strcmp(word, "stop")) { //STOP printf("Query: %s\n", word); break; } if(0 == strcmp(word, "find")) { //FIND v_scanf = scanf("%d%d%d", &source_new, &destination_new, &flag_new); if(v_scanf != 3) { continue; } else{ printf("Query: %s %d %d %d\n", word, source_new, destination_new, flag_new); if(source_new < 1 || source_new > n || flag_new < 0 || flag_new > 1) { printf("Error: invalid find query\n");//// } else { source = source_new; destination = destination_new; flag = flag_new; Dijkstra(n, A, source, destination, flag, V); continue; } } } else if (0 == strcmp(word, "write")) { r_value = nextWord(word2); if(!r_value) { continue; } if(0==strcmp(word2, "path")) { v_scanf = scanf("%d%d", &s_new, &t_new); if(v_scanf != 2){ continue; } else { printf("Query: %s %s %d %d\n", word, word2, s_new, t_new); if(source == 0){ printf("Error: no path computation done\n");//// } else if (s_new != source || t_new == s_new || t_new <1 || t_new >n){ printf("Error: invalid source destination pair\n");//// }else{ s = s_new; t = t_new; printPath(n, source, destination, s, t, V); } } } } else { continue; } } return 0; }
true
edd3a3b9a8283d81061521b1c077f5b5cb646bec
C++
lazyrun/kenay
/src/common/DirectMap/src/DirectMap.h
WINDOWS-1251
11,218
2.9375
3
[]
no_license
/*! \file DirectMap.h \date 15.05.2009 \brief "" QMap, \author Kiselev Kirill */ #ifndef DIRECTMAP_H #define DIRECTMAP_H /*! \class DirectMapIterator \brief DirectMapIterator */ class DirectMapIterator; #define Q_DECLARE_METATYPE_COMMA(...) \ QT_BEGIN_NAMESPACE \ template <> \ struct QMetaTypeId< __VA_ARGS__ > \ { \ enum { Defined = 1 }; \ static int qt_metatype_id() \ { \ static QBasicAtomicInt metatype_id = Q_BASIC_ATOMIC_INITIALIZER(0); \ if (!metatype_id) \ metatype_id = qRegisterMetaType< __VA_ARGS__ >( #__VA_ARGS__, \ reinterpret_cast< __VA_ARGS__ *>(quintptr(0))); \ return metatype_id; \ } \ }; \ QT_END_NAMESPACE \ /*! \class QVector \brief QVector */ /*! \class DirectMap \brief QMap */ template <class Key, class Value> class DirectMap : public QVector<QPair<Key, Value> > { //! friend class DirectMapIterator; public: //! typedef QVector<QPair<Key, Value> > VectorPair; //! DirectMap(); //! /*! \param vec */ DirectMap(const VectorPair & vec); //! /*! \param key \param value */ void append(const Key & key, const Value & value); //! /*! \return */ QVector<Key> keys() const; //! /*! \return */ QVector<Value> values() const; //! , /*! \param key \return */ QVector<Value> values(const Key & key) const; //! /*! \return */ int count() const { return VectorPair::count(); } //! /*! \param key \return */ bool contains(const Key & key) const; //! /*! \param row \return */ Key key(int row) const; //! /*! \param row \return */ Value value(int row) const; //! /*! \param key \return */ const Value value(Key key) const; //! /*! \param key \return */ const Value operator[](const Key & key) const; //! , /*! \param key \return */ Value & operator[](const Key & key); Value & operator[](int idx); //! /*! \param right */ void operator<<(const DirectMap<Key, Value> & right); //! QPair<Key, Value> & item(int idx); //! const QPair<Key, Value> & item(int idx) const; QMap<Key, Value> toMap() const; //DirectMap<Key, Value> & operator=(const DirectMap<Key, Value> &other); static DirectMap<Key, Value> fromMap(const QMap<Key, Value> & map); }; template <class Key, class Value> DirectMap<Key, Value>::DirectMap() : QVector<QPair<Key, Value> >() { } template <class Key, class Value> DirectMap<Key, Value>::DirectMap(const QVector<QPair<Key, Value> > & vec) : QVector<QPair<Key, Value> >(vec) { } template <class Key, class Value> void DirectMap<Key, Value>::append(const Key & key, const Value & value) { VectorPair::append(qMakePair(key, value)); } template <class Key, class Value> QVector<Key> DirectMap<Key, Value>::keys() const { QVector<Key> resKeys; for (int i = 0; i < VectorPair::count(); ++i) { resKeys.append(VectorPair::at(i).first); } return resKeys; } template <class Key, class Value> QVector<Value> DirectMap<Key, Value>::values() const { QVector<Value> resValues; for (int i = 0; i < VectorPair::count(); ++i) { resValues.append(VectorPair::at(i).second); } return resValues; } template <class Key, class Value> QVector<Value> DirectMap<Key, Value>::values(const Key & key) const { QVector<Value> resValues; for (int i = 0; i < VectorPair::count(); ++i) { if (VectorPair::at(i).first == key) resValues.append(VectorPair::at(i).second); } return resValues; } template <class Key, class Value> const Value DirectMap<Key, Value>::operator[](const Key & key) const { for (int i = 0; i < VectorPair::count(); ++i) { if (VectorPair::at(i).first == key) { return VectorPair::at(i).second; } } return Value(); } template <class Key, class Value> bool DirectMap<Key, Value>::contains(const Key & key) const { for (int i = 0; i < VectorPair::count(); ++i) { if (VectorPair::at(i).first == key) { return true; } } return false; } template <class Key, class Value> Value & DirectMap<Key, Value>::operator[](const Key & key) { for (int i = 0; i < VectorPair::count(); ++i) { if (VectorPair::at(i).first == key) { return VectorPair::operator[](i).second; } } append(key, Value()); return VectorPair::last().second; } template <class Key, class Value> Value & DirectMap<Key, Value>::operator[](int idx) { return VectorPair::operator[](idx).second; } template <class Key, class Value> void DirectMap<Key, Value>::operator<<(const DirectMap<Key, Value> & right) { foreach (QString key, right.keys()) { append(key, right[key]); } } template <class Key, class Value> Key DirectMap<Key, Value>::key(int row) const { QPair<Key, Value> pair = VectorPair::at(row); return pair.first; } template <class Key, class Value> Value DirectMap<Key, Value>::value(int row) const { QPair<Key, Value> pair = VectorPair::at(row); return pair.second; } template <class Key, class Value> const Value DirectMap<Key, Value>::value(Key key) const { return operator[](key); } template <class Key, class Value> QPair<Key, Value> & DirectMap<Key, Value>::item(int idx) { return VectorPair::operator[](idx); } template <class Key, class Value> const QPair<Key, Value> & DirectMap<Key, Value>::item(int idx) const { return VectorPair::at(idx); } template <class Key, class Value> QMap<Key, Value> DirectMap<Key, Value>::toMap() const { QMap<Key, Value> map; for (int i = 0; i < VectorPair::count(); ++i) { QPair<Key, Value> pair = item(i); QVariant value = QVariant::fromValue(pair.second); if (value.canConvert<DirectMap<Key, Value> >()) { DirectMap<Key, Value> submap = qvariant_cast<DirectMap<Key, Value> >(value); map.insert(pair.first, submap.toMap()); } else { map.insert(pair.first, pair.second); } } return map; } template <class Key, class Value> DirectMap<Key, Value> DirectMap<Key, Value>::fromMap(const QMap<Key, Value> & map) { DirectMap<Key, Value> dmap; foreach (Key key, map.keys()) { Value value = map.value(key); dmap.append(key, value); } return dmap; } /*! \class QVectorIterator \brief QVectorIterator */ /*! \class DirectIterator \brief DirectMap */ template <class Key, class Value> class DirectIterator : private QVectorIterator<QPair<Key, Value> > { public: //! /*! \param map */ DirectIterator(const QVector<QPair<Key, Value> > & map); //! /*! \param map */ DirectIterator(const DirectMap<Key, Value> & map); //! /*! \return */ bool hasNext() const; //! void next(); //! /*! \return */ Key key() const; //! /*! \return */ Value value() const; protected: //! - QPair<Key, Value> current_; }; template <class Key, class Value> DirectIterator<Key, Value>::DirectIterator(const QVector<QPair<Key, Value> > & map) : QVectorIterator<QPair<Key, Value> >(map) { } template <class Key, class Value> DirectIterator<Key, Value>::DirectIterator(const DirectMap<Key, Value> & map) : QVectorIterator<QPair<Key, Value> >((QVector<QPair<Key, Value> > &)map) { //QVectorIterator<QPair<Key, Value> >(()map) } template <class Key, class Value> bool DirectIterator<Key, Value>::hasNext() const { return QVectorIterator<QPair<Key, Value> >::hasNext(); } template <class Key, class Value> void DirectIterator<Key, Value>::next() { current_ = QVectorIterator<QPair<Key, Value> >::next(); }; template <class Key, class Value> Key DirectIterator<Key, Value>::key() const { return current_.first; }; template <class Key, class Value> Value DirectIterator<Key, Value>::value() const { return current_.second; }; typedef QPair<QString, QVariant> VariantPair; //! DirectVariantMap typedef DirectMap<QString, QVariant> DirectVariantMap; //! DirectStringMap typedef DirectMap<QString, QString> DirectStringMap; //! DirectVariantIterator typedef DirectIterator<QString, QVariant> DirectVariantIterator; Q_DECLARE_METATYPE_COMMA(QVector<QPair<QString, QVariant> >) Q_DECLARE_METATYPE(DirectVariantMap) Q_DECLARE_METATYPE_COMMA(QVector<QPair<QString, QString> >) Q_DECLARE_METATYPE_COMMA(DirectStringMap) #endif
true
21f525d9634ff49551f5edc5d6aef09b0a755b0b
C++
jtlai0921/AEL000500
/AEL000500_code (1)/ch11/ex11_3/ex11_3.cpp
UTF-8
722
3.859375
4
[]
no_license
// Program 11.3 Making use of a Person #include <iostream> using namespace std; #include "person.h" int main() { Person her = { { "Letitia", "Gruntfuttock" }, // Initializes Name member {1, 4, 1965 }, // Initializes Date member {212, 5551234 } // Initializes Phone member }; Person actress; actress = her; // Copy members of her her.show(); Date today = { 15, 3, 1998 }; cout << endl << "Today is "; today.show(); cout << endl; cout << "Today " << actress.name.firstname << " is " << actress.age(today) << " years old." << endl; return 0; }
true
d8ac947c806a19a806ad4d9948c3e9b7b93a1911
C++
santolucito/CCache
/LZOTester.cc
UTF-8
3,772
2.84375
3
[]
no_license
// LZOTester.cc // Scott F. Kaplan -- sfkaplan@cs.utexas.edu // August 1997 // A tester designed to work on the Lempel-Ziv-Oberhumer // compression/decompression algorithm. Note that we've chosen to use // the LZO1f variant--according to the results provided by Oberhumer, // that variant does best with short compression sources. using namespace std; #include <iostream> #include <stdlib.h> #include "LZOTester.hh" #include "lzo1f.h" #include <time.h> // Perform the actual task of timing the compression algorithm. void LZOTester::performCompressionTest (void* uncompressedData, unsigned int uncompressedBytes, unsigned int& returnCompressedSize, unsigned long long& returnCompressionTime) { lzo_byte compressionBuffer[2 * uncompressedBytes]; lzo_byte _workingMemory[LZO1F_MEM_COMPRESS + 16]; lzo_uint compressedSize = sizeof(compressionBuffer); int resultCode; // Initialize the working memory. lzo_byte* workingMemory = (lzo_byte*)LZO_ALIGN(_workingMemory, 16); // Surround a call to the compression routine with a timing // mechanism. //START_MYTIMER; //start struct timespec start, stop; long accum; clock_gettime(CLOCK_REALTIME, &start); //endstart resultCode = lzo1f_1_compress((lzo_byte*)uncompressedData, uncompressedBytes, compressionBuffer, &compressedSize, workingMemory); //stop clock_gettime(CLOCK_REALTIME, &stop); accum = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec); /// 1000000000.0; returnCompressionTime = accum; //endstop //STOP_MYTIMER; // Ensure that the compression was successful. if (resultCode != LZO_E_OK) { cerr << "LZO::performCompressionTest: " << "Compression failed = " << resultCode << endl; exit(-1); } // Set the return values. returnCompressedSize = compressedSize; } // Perform the actual task of timing the decompression algorithm. void LZOTester::performDecompressionTest (void* uncompressedData, unsigned int uncompressedBytes, unsigned int& returnPreDecompressionSize, unsigned long long& returnDecompressionTime) { lzo_byte compressionBuffer[2 * uncompressedBytes]; lzo_byte decompressionBuffer[uncompressedBytes]; lzo_byte _workingMemory[LZO1F_MEM_COMPRESS + 16]; lzo_uint compressedSize; lzo_uint decompressedSize; int resultCode; // Initialize the working memory. lzo_byte* workingMemory = (lzo_byte*)LZO_ALIGN(_workingMemory, 16); // Get a compressed copy of the page so that the decompression can // be timed. resultCode = lzo1f_1_compress((lzo_byte*)uncompressedData, uncompressedBytes, compressionBuffer, &compressedSize, workingMemory); // Ensure that the compression was successful. if (resultCode != LZO_E_OK) { cerr << "LZO::performDecompressionTest: " << "Compression failed = " << resultCode << endl; exit(-1); } // Surround a call to the decompression routine with a timing // mechanism. //START_TIMER; //start struct timespec start, stop; long accum; clock_gettime(CLOCK_REALTIME, &start); //endstart resultCode = lzo1f_decompress(compressionBuffer, compressedSize, decompressionBuffer, &decompressedSize, 0); //stop clock_gettime(CLOCK_REALTIME, &stop); accum = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec); /// 1000000000.0; returnDecompressionTime = accum; //endstop // STOP_TIMER(returnDecompressionTime); // Ensure that the decompression was successful. if (resultCode != LZO_E_OK) { cerr << "LZO::performDecompressionTest: " << "Decompression failed = " << resultCode << endl; exit(-1); } // Set the return values. returnPreDecompressionSize = compressedSize; }
true
fcaed18a05913fae66cbe89951b4b2babb1f9188
C++
chromium/chromium
/third_party/abseil-cpp/absl/functional/function_ref_test.cc
UTF-8
8,329
2.515625
3
[ "BSD-3-Clause", "GPL-1.0-or-later", "MIT", "LGPL-2.0-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright 2019 The Abseil Authors. // // 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 // // https://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. #include "absl/functional/function_ref.h" #include <functional> #include <memory> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/container/internal/test_instance_tracker.h" #include "absl/functional/any_invocable.h" #include "absl/memory/memory.h" namespace absl { ABSL_NAMESPACE_BEGIN namespace { void RunFun(FunctionRef<void()> f) { f(); } TEST(FunctionRefTest, Lambda) { bool ran = false; RunFun([&] { ran = true; }); EXPECT_TRUE(ran); } int Function() { return 1337; } TEST(FunctionRefTest, Function1) { FunctionRef<int()> ref(&Function); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, Function2) { FunctionRef<int()> ref(Function); EXPECT_EQ(1337, ref()); } int NoExceptFunction() noexcept { return 1337; } // TODO(jdennett): Add a test for noexcept member functions. TEST(FunctionRefTest, NoExceptFunction) { FunctionRef<int()> ref(NoExceptFunction); EXPECT_EQ(1337, ref()); } TEST(FunctionRefTest, ForwardsArgs) { auto l = [](std::unique_ptr<int> i) { return *i; }; FunctionRef<int(std::unique_ptr<int>)> ref(l); EXPECT_EQ(42, ref(absl::make_unique<int>(42))); } TEST(FunctionRef, ReturnMoveOnly) { auto l = [] { return absl::make_unique<int>(29); }; FunctionRef<std::unique_ptr<int>()> ref(l); EXPECT_EQ(29, *ref()); } TEST(FunctionRef, ManyArgs) { auto l = [](int a, int b, int c) { return a + b + c; }; FunctionRef<int(int, int, int)> ref(l); EXPECT_EQ(6, ref(1, 2, 3)); } TEST(FunctionRef, VoidResultFromNonVoidFunctor) { bool ran = false; auto l = [&]() -> int { ran = true; return 2; }; FunctionRef<void()> ref(l); ref(); EXPECT_TRUE(ran); } TEST(FunctionRef, CastFromDerived) { struct Base {}; struct Derived : public Base {}; Derived d; auto l1 = [&](Base* b) { EXPECT_EQ(&d, b); }; FunctionRef<void(Derived*)> ref1(l1); ref1(&d); auto l2 = [&]() -> Derived* { return &d; }; FunctionRef<Base*()> ref2(l2); EXPECT_EQ(&d, ref2()); } TEST(FunctionRef, VoidResultFromNonVoidFuncton) { FunctionRef<void()> ref(Function); ref(); } TEST(FunctionRef, MemberPtr) { struct S { int i; }; S s{1100111}; auto mem_ptr = &S::i; FunctionRef<int(const S& s)> ref(mem_ptr); EXPECT_EQ(1100111, ref(s)); } TEST(FunctionRef, MemberFun) { struct S { int i; int get_i() const { return i; } }; S s{22}; auto mem_fun_ptr = &S::get_i; FunctionRef<int(const S& s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(s)); } TEST(FunctionRef, MemberFunRefqualified) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; S s{22}; FunctionRef<int(S && s)> ref(mem_fun_ptr); EXPECT_EQ(22, ref(std::move(s))); } #if !defined(_WIN32) && defined(GTEST_HAS_DEATH_TEST) TEST(FunctionRef, MemberFunRefqualifiedNull) { struct S { int i; int get_i() && { return i; } }; auto mem_fun_ptr = &S::get_i; mem_fun_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(S && s)> ref(mem_fun_ptr); }, ""); } TEST(FunctionRef, NullMemberPtrAssertFails) { struct S { int i; }; using MemberPtr = int S::*; MemberPtr mem_ptr = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<int(const S& s)> ref(mem_ptr); }, ""); } TEST(FunctionRef, NullStdFunctionAssertPasses) { std::function<void()> function = []() {}; FunctionRef<void()> ref(function); } TEST(FunctionRef, NullStdFunctionAssertFails) { std::function<void()> function = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<void()> ref(function); }, ""); } TEST(FunctionRef, NullAnyInvocableAssertPasses) { AnyInvocable<void() const> invocable = []() {}; FunctionRef<void()> ref(invocable); } TEST(FunctionRef, NullAnyInvocableAssertFails) { AnyInvocable<void() const> invocable = nullptr; EXPECT_DEBUG_DEATH({ FunctionRef<void()> ref(invocable); }, ""); } #endif // GTEST_HAS_DEATH_TEST TEST(FunctionRef, CopiesAndMovesPerPassByValue) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 1); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, CopiesAndMovesPerPassByRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(const absl::test_internal::CopyableMovableInstance&)> ref(l); ref(instance); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 0); } TEST(FunctionRef, CopiesAndMovesPerPassByValueCallByMove) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](absl::test_internal::CopyableMovableInstance) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 2); } TEST(FunctionRef, CopiesAndMovesPerPassByValueToRef) { absl::test_internal::InstanceTracker tracker; absl::test_internal::CopyableMovableInstance instance(0); auto l = [](const absl::test_internal::CopyableMovableInstance&) {}; FunctionRef<void(absl::test_internal::CopyableMovableInstance)> ref(l); ref(std::move(instance)); EXPECT_EQ(tracker.copies(), 0); EXPECT_EQ(tracker.moves(), 1); } TEST(FunctionRef, PassByValueTypes) { using absl::functional_internal::Invoker; using absl::functional_internal::VoidPtr; using absl::test_internal::CopyableMovableInstance; struct Trivial { void* p[2]; }; struct LargeTrivial { void* p[3]; }; static_assert(std::is_same<Invoker<void, int>, void (*)(VoidPtr, int)>::value, "Scalar types should be passed by value"); static_assert( std::is_same<Invoker<void, Trivial>, void (*)(VoidPtr, Trivial)>::value, "Small trivial types should be passed by value"); static_assert(std::is_same<Invoker<void, LargeTrivial>, void (*)(VoidPtr, LargeTrivial &&)>::value, "Large trivial types should be passed by rvalue reference"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Types with copy/move ctor should be passed by rvalue reference"); // References are passed as references. static_assert( std::is_same<Invoker<void, int&>, void (*)(VoidPtr, int&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&>, void (*)(VoidPtr, CopyableMovableInstance&)>::value, "Reference types should be preserved"); static_assert( std::is_same<Invoker<void, CopyableMovableInstance&&>, void (*)(VoidPtr, CopyableMovableInstance &&)>::value, "Reference types should be preserved"); // Make sure the address of an object received by reference is the same as the // address of the object passed by the caller. { LargeTrivial obj; auto test = [&obj](LargeTrivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(LargeTrivial&)> ref(test); ref(obj); } { Trivial obj; auto test = [&obj](Trivial& input) { ASSERT_EQ(&input, &obj); }; absl::FunctionRef<void(Trivial&)> ref(test); ref(obj); } } TEST(FunctionRef, ReferenceToIncompleteType) { struct IncompleteType; auto test = [](IncompleteType&) {}; absl::FunctionRef<void(IncompleteType&)> ref(test); struct IncompleteType {}; IncompleteType obj; ref(obj); } } // namespace ABSL_NAMESPACE_END } // namespace absl
true
a4d47dad18741d3059e14be22bef18098dddbcce
C++
lintcoder/leetcode
/src/1114.cpp
UTF-8
740
3.015625
3
[]
no_license
class Foo { public: Foo() { flag1 = 0; flag2 = 0; } void first(function<void()> printFirst) { // printFirst() outputs "first". Do not change or remove this line. printFirst(); flag1 = 1; } void second(function<void()> printSecond) { // printSecond() outputs "second". Do not change or remove this line. while (flag1 == 0) ; printSecond(); flag2 = 1; } void third(function<void()> printThird) { // printThird() outputs "third". Do not change or remove this line. while (flag2 == 0) ; printThird(); } private: volatile int flag1; volatile int flag2; };
true
4b30aaaf4dfd26f9d1f716309631fb068c412d8f
C++
wtmitchell/challenge_problems
/include/project_euler/0001-0050/Problem7.h
UTF-8
1,196
2.734375
3
[ "MIT" ]
permissive
//===-- project_euler/Problem7.h --------------------------------*- C++ -*-===// // // Challenge Problem solutions by Will Mitchell // // This file is distributed under the MIT License. See LICENSE for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Problem 7: 10001st prime /// //===----------------------------------------------------------------------===// #ifndef PROJECT_EULER_PROBLEM7_H #define PROJECT_EULER_PROBLEM7_H #include <string> #include "../Problem.h" namespace project_euler { class Problem7 : public Problem { public: Problem7() : prime(0), solved(false) {} ~Problem7() = default; std::string answer(); std::string description() const; void solve(); /// Simple brute force solution unsigned bruteForce(const unsigned limit) const; /// Simple brute force solution unsigned bruteForce2(const unsigned limit) const; /// Simple brute force solution unsigned bruteForce3(const unsigned limit) const; /// Simple brute force solution unsigned bruteForce4(const unsigned limit) const; private: /// Cached answer unsigned prime; /// If cached answer is valid bool solved; }; } #endif
true
5123796ebeaa8f4acc8c239cd6b0582da2d2399c
C++
JustinLiu1998/ECNU-Online-Judge
/2853/main.cpp
UTF-8
1,218
2.78125
3
[]
no_license
// // main.cpp // 2853 // // Created by 刘靖迪 on 2017/11/29. // Copyright © 2017年 刘靖迪. All rights reserved. // #include <iostream> #include <set> #include <vector> using namespace std; set<int> a, b; vector<int> U, I, D; void print (vector<int> &x) { printf("{"); auto iter = x.begin(); printf("%d", *iter); iter++; while (iter != x.end()) { printf(",%d", *iter); iter++; } printf("}\n"); } void solve () { vector<int>::iterator iiter = set_intersection(a.begin(), a.end(), b.begin(), b.end(), I.begin()); I.resize(iiter - I.begin()); vector<int>::iterator uiter = set_union(a.begin(), a.end(), b.begin(), b.end(), U.begin()); U.resize(uiter - U.begin()); vector<int>::iterator diter = set_difference(a.begin(), a.end(), b.begin(), b.end(), D.begin()); D.resize(diter - D.begin()); print(I); print(U); print(D); } int main(int argc, const char * argv[]) { int n, m; scanf("%d%d", &m, &n); for (int i=0; i<m; i++) { int t; scanf("%d", &t); a.insert(t); } for (int i=0; i<n; i++) { int t; scanf("%d", &t); b.insert(t); } solve(); return 0; }
true
dc936a1e1b8fc33c1d2b06939f85915ba75b5e98
C++
meganfeichtel/ray-tracer-1
/RayTracer/Tracers/Tracer.cpp
UTF-8
483
2.6875
3
[]
no_license
// // Tracer.cpp // RayTracer // // Created by Megan Feichtel on 11/24/14. // Copyright (c) 2014 Megan Feichtel. All rights reserved. // #include "Tracer.h" Tracer::Tracer(void) : world_ptr(NULL) {} Tracer::Tracer(World* _worldPtr) : world_ptr(_worldPtr) {} Tracer::~Tracer(void) { if (world_ptr) world_ptr = NULL; } RGB Tracer::trace_ray(const Ray &ray) const { return (black); } RGB Tracer::trace_ray(const Ray ray, const int depth) const { return (black); }
true
f94ffa690b13e2327d3f0936b110317b5e7169bf
C++
Shreyansh0001/codes
/fibonacci_series.cpp
UTF-8
245
2.671875
3
[]
no_license
#include<iostream> using namespace std; int main() { int n; cin>>n; int a=1,b=1,c; cout<<a<<"\t"<<b <<"\t"; while(n>2) { c = a+b; a=b; b=c; cout<<c<<"\t"; n--; } return 0; }
true
5e2f8586c570d3f01960816ceb1e8347993d3a84
C++
abhishekreddy/Prac
/src/prac.cpp
UTF-8
1,376
2.859375
3
[]
no_license
/* * prac.cpp * * Prac file * * Copyright (C) 2016 Abhishek Reddy kondaveeti * * Contributor: Abhishek Reddy Kondaveeti <abhishek.kondaveeti@gmail.com> * * * This file is licensed under the terms of the GNU General Public License * version 2. This program is licensed "as is" without any warranty of any * kind, whether express or implied. * */ #include <iostream> #include <prac.h> using namespace std; prac::prac() { } prac::~prac() { } int prac::forward_list(struct singlenode *list) { int pos = 0; while (list != NULL) { if (list->data > 0) { break; } else { pos++; list = list->next; } } return pos; } #if 0 int prac::get_max_sum(struct singlenode *node, int *start_pos, int *end_pos) { struct singlenode *list = node; int max_sum = 0, cur_sum = 0, count = 0, start_max = 0, stop_max = 0; max_sum = list->data; start_max = 0; stop_max = 0; /* Find the first positive */ while (list != NULL) { if (list->data > 0) { max_sum = list->data; *start_pos = count; *end_pos = count; break; } else { if (max_sum < list->data) { max_sum = list->data; *start_pos = count; *end_pos = count; } list = list->next; count++; } } if (list == NULL) return max_sum; while (list->next != NULL) { cur_sum += list->data; if (cur_sum > max_sum) { max_sum = cur_sum; *end_pos = count; } if (cur_sum < 0 ) { } } return max_sum; } #endif
true
bb1448838cb4a728d3dfc1a515e8c065c88cee3e
C++
crpeter/Coms352_OperatingSystems
/Cody_Peter_Project2/alloc.cpp
UTF-8
3,546
2.859375
3
[]
no_license
/* * created by Cody Peter * for the purpose of allocating resources from the available map. */ #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <iostream> #include <errno.h> #include <sys/ipc.h> #include <sys/sem.h> #include "string.h" using namespace std; void readAllocMap(char* map, int* allocArr); void writeAllocMap(char* map, int* allocArr); #define KEY 0xAA11 struct sembuf p = { 0, -1, SEM_UNDO}; // semwait struct sembuf v = { 0, +1, SEM_UNDO}; // semsignal int semid; union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; int main(int argc, char* argv[]) { int res, quant; struct stat sb; semid = semget(KEY, 1, 0666 | IPC_CREAT); if(semid == -1) { perror("semget"); exit(1); } union semun u; u.val = 1; if(semctl(semid, 0, SETVAL, u) < 0) { perror("semctl"); exit(1); } int resFile = open("res.txt", O_RDWR); if (fstat(resFile, &sb) == -1) { perror("stat"); exit(EXIT_FAILURE); } // printf("File size: %lld bytes\n", // (long long) sb.st_size); // // if (lseek(resFile, 40, 0) == -1) { // perror("seek"); // exit(EXIT_FAILURE); // } char* map = (char*)mmap(0, 20, PROT_READ | PROT_WRITE, MAP_SHARED, resFile, 0); assert(map != MAP_FAILED); close(resFile); int *allocArr = (int*)malloc(5 * sizeof(int)); for (int k = 0; k < 5; k++) { allocArr[k] = 0; } while (true) { cout << "enter resource type and amount needed: "; cin >> res >> quant; if (res >= 0 && res < 5) { //Wait if(semop(semid, &p, 1) < 0) { perror("semop p"); exit(13); } readAllocMap(map, allocArr); if (allocArr[res] - quant >= 0) { allocArr[res] -= quant; writeAllocMap(map, allocArr); readAllocMap(map, allocArr); } else { cout << "Insufficient amount of resource: " << res << "\n"; res = -1; } //Signal if(semop(semid, &v, 1) < 0) { perror("semop p"); exit(14); } } else { break; } } if (munmap(map, sb.st_size) == -1) { perror("Error un-mmapping the file"); exit(EXIT_FAILURE); } exit(0); } /* * Read from #input(map) and write values to #output(allocArr) */ void readAllocMap(char* map, int* allocArr) { char c; bool index = true; int i, val; size_t iSize; for (iSize = 0, i = 0; iSize < 20; iSize++) { c = map[iSize]; if (c != ' ' && c != '\n') { if (index) { i = c - '0'; index = false; } else { val = c - '0'; allocArr[i] = val; index = true; } } } } /* * Write from #input(allocArr) and write values to #output(map) */ void writeAllocMap(char* map, int* allocArr) { size_t i; int index = 0; for (index = 0, i = 0; index < 5; index++) { map[i++] = index + '0'; map[i++] = ' '; map[i++] = allocArr[index] + '0'; map[i++] = '\n'; } if (msync((void *)map, 20, MS_SYNC) == -1) { perror("Could not sync to disk"); } }
true
494eb61081331164c24b34d345951f168631a8ec
C++
Nur47-blip/Random
/DSU dan DFS.cpp
UTF-8
1,358
2.59375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define pii pair<int, int> #define fi first #define se second #define trace(x) cout << '>' << #x << ':' << x << "\n" #define trace2(x,y) cout<< '>' << #x << ':' << x << " | " << #y << ':' << y << "\n" #define trace3(a,b,c) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<"\n" #define trace4(a,b,c,d) cout<<#a<<"="<<(a)<<", "<<#b<<"="<<(b)<<", "<<#c<<"="<<(c)<<", "<<#d<<"="<<(d)<<"\n" int dx[4] = {-1, 0, 1, 0}; int dy[4] = {0, -1, 0, 1}; int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n, q, e; cin >> n >> q >> e; vector<vector<int>> graf(n); for (int i = 0; i < e; i++){ int a, b; cin >> a >> b; graf[a].pb(b); graf[b].pb(a); } vector<bool> vis(n, false); vector<int> par(n); for (int i = 0; i < n; i++){ if (vis[i]==true) continue; par[i] = i; stack<int> s; s.push(i); while (!s.empty()){ int x = s.top(); s.pop(); par[x] = i; if (vis[x]) continue; vis[x] = true; for (int j = 0; j < graf[x].size(); j++){ int xx = graf[x][j]; if (vis[xx]) continue; s.push(xx); } } } for (int i = 0; i < q; i++){ int a, b; cin >> a >> b; if (par[a]==par[b]) cout << "Terhubung" << endl; else cout << "Tidak Terhubung" << endl; } return 0; }
true
f172f5e4de26943e01a94f4a3e1d614ec6ddac3b
C++
mgh3326/Major_Deeped_Lab1_hw3_Huffman
/Major_Deeped_Lab1_hw3_Huffman/HuffmanCodes.h
UTF-8
2,814
3.640625
4
[]
no_license
#pragma once // C++ program for Huffman Coding // This constant can be avoided by explicitly // calculating height of Huffman Tree // A Huffman tree node struct MinHeapNode { // One of the input characters unsigned char data; // Frequency of the character unsigned freq; // Left and right child of this node struct MinHeapNode *left, *right; }; // A Min Heap: Collection of // min heap (or Hufmman tree) nodes struct MinHeap { // Current size of min heap unsigned size; // capacity of min heap unsigned capacity; // Attay of minheap node pointers struct MinHeapNode** array; }; // A utility function allocate a new // min heap node with given character // and frequency of the character struct MinHeapNode* newNode(unsigned char data, unsigned freq); // A utility function to create // a min heap of given capacity struct MinHeap* createMinHeap(unsigned capacity); // A utility function to // swap two min heap nodes void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b); // The standard minHeapify function. void minHeapify(struct MinHeap* minHeap, int idx); // A utility function to check // if size of heap is 1 or not int isSizeOne(struct MinHeap* minHeap); // A standard function to extract // minimum value node from heap struct MinHeapNode* extractMin(struct MinHeap* minHeap); // A utility function to insert // a new node to Min Heap void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode); // A standard funvtion to build min heap void buildMinHeap(struct MinHeap* minHeap); // A utility function to print an array of size n void printArr(int arr[], int n, std::vector<int> myvector); // Utility function to check if this node is leaf int isLeaf(struct MinHeapNode* root); // Creates a min heap of capacity // equal to size and inserts all character of // data[] in min heap. Initially size of // min heap is equal to capacity struct MinHeap* createAndBuildMinHeap(unsigned char data[], int freq[], int size); // The main function that builds Huffman tree struct MinHeapNode* buildHuffmanTree(unsigned char data[], int freq[], int size); // Prints huffman codes from the root of Huffman Tree. // It uses arr[] to store codes void printCodes(struct MinHeapNode* root, int arr[], int top, std::vector<int> myvector[]); // The main function that builds a // Huffman Tree and print codes by traversing // the built Huffman Tree void HuffmanCodes(unsigned char data[], int freq[], int size, std::vector<int> myvector[]); // Driver program to test above functions //int main() //{ // // unsigned char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; // int freq[] = { 5, 9, 12, 13, 16, 45 }; // // int size = sizeof(arr) / sizeof(arr[0]); // // HuffmanCodes(arr, freq, size); // // return 0; //}
true
edcc3aae516558e0dd62a2042addb64fc459601e
C++
zivl/Crush-Around
/src/Core/MyContactListener.cpp
UTF-8
1,562
2.59375
3
[]
no_license
#include "MyContactListener.h" MyContactListener::MyContactListener(void) : m_contacts() { } MyContactListener::~MyContactListener(void) { } // Handle begin contact event. // The data from contact is copied because b2Contact passed in is reused void MyContactListener::BeginContact(b2Contact* contact) { if (!contact->IsTouching()) { return; } b2WorldManifold worldManifold; contact->GetWorldManifold(&worldManifold); b2Vec2 vel1 = contact->GetFixtureA()->GetBody()->GetLinearVelocityFromWorldPoint( worldManifold.points[0] ); b2Vec2 vel2 = contact->GetFixtureB()->GetBody()->GetLinearVelocityFromWorldPoint( worldManifold.points[0] ); b2Vec2* impactVelocityA = new b2Vec2(vel1); b2Vec2* impactVelocityB = new b2Vec2(vel2); b2Vec2* point = new b2Vec2(worldManifold.points[0]); MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB(), point, impactVelocityA, impactVelocityB }; this->m_contacts.push_back(myContact); } // Handle end contact event. void MyContactListener::EndContact(b2Contact* contact) { MyContact myContact = { contact->GetFixtureA(), contact->GetFixtureB() }; std::vector<MyContact>::iterator pos; pos = std::find(m_contacts.begin(), m_contacts.end(), myContact); if (pos != m_contacts.end()) { m_contacts.erase(pos); } } void MyContactListener::PreSolve(b2Contact* contact, const b2Manifold* oldManifold) { } void MyContactListener::PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { }
true
8dd5c338f5b8b1bdf9b00a2b3b4fc04564c61ddd
C++
solariums/Roc_proj
/study_src/toupper.cpp
UTF-8
613
3.203125
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <cctype> using std::cout; using std::cin; using std::endl; using std::string; using std::vector; int main() { vector<string> vecStr; string strTemp; while(cin>>strTemp){ vecStr.push_back(strTemp); //cin.clear(); //cin.sync(); } for(vector<string>::size_type i=0;i!=vecStr.size();++i) { if(!(i%8)) { cout<<endl; } for(string::size_type j=0;j!=vecStr[i].size();++j) { if(islower(vecStr[i][j])) { vecStr[i][j] =toupper(vecStr[i][j]); } } cout<<vecStr[i] <<endl; } return 0; }
true
1a7a000571546e416f2ba1f1f4b642b9e35dc737
C++
albertnez/uva-online-judge
/problems/452.cc
UTF-8
1,343
2.578125
3
[]
no_license
#include <iostream> #include <vector> #include <sstream> using namespace std; typedef vector<int> Vi; typedef vector<Vi> Mi; const int n = 27; Vi topo; Mi g; vector<bool> vis; void dfs(int u) { vis[u] = true; for (int i = 0; i < g[u].size(); ++i) { if (!vis[g[u][i]]) dfs(g[u][i]); } topo.push_back(u); } void topof() { vis.assign(n, false); topo.assign(0,0); for (int i = 0; i < n; ++i) if (!vis[i]) dfs(i); } int main() { int T; cin >> T; cin.ignore(); cin.ignore(); while (T--) { string s; Vi wts(n, 0); Vi act(n, 0); Vi ind(n, 0); int maxind = 0; g = Mi(n); while (getline(cin,s) and s != "") { istringstream ss(s); char c; ss >> c; int st = c-'A'; int weight; ss >> weight; wts[st] = weight; while (ss >> c) { int to = c-'A'; g[to].push_back(st); ++ind[st]; maxind = max(maxind, ind[st]); } } topof(); for (int i = n-1; i >= 0; --i) { int u = topo[i]; act[u] -= wts[u]; for (int j = 0; j < g[u].size(); ++j) { int v = g[u][j]; act[v] = min(act[v], act[u]); } } int ans = 0; for (int i = 0; i < n; ++i) ans = min(ans, act[i]); cout << -ans << endl; if (T) cout << endl; } }
true
b78e28952f2ffbf6fa6cdaca562033924d7f6557
C++
Cell-veto/postlhc
/tools.cpp
UTF-8
7,497
2.6875
3
[]
no_license
// (c) 2015-2018 Sebastian Kapfer <sebastian.kapfer@fau.de>, FAU Erlangen // various utilities. #include "tools.hpp" #include <cstdlib> #include <signal.h> #include <fstream> #include <stdexcept> #include <iomanip> #include <sstream> #include <sys/time.h> #include <sys/stat.h> #include <unistd.h> #include <boost/algorithm/string.hpp> uint64_t gclock () { static uint64_t base = time (0); struct timeval tv; gettimeofday(&tv, 0); return (tv.tv_sec-base) * 1000000ull + tv.tv_usec; } static bool sigterm_installed = false, sigterm_caught_flag; static void sigterm_handler (int) { sigterm_caught_flag = true; } bool sigterm_caught () { if (!sigterm_installed) { sigterm_caught_flag = false; sigterm_installed = true; signal (SIGTERM, sigterm_handler); } return sigterm_caught_flag; } void shell (string_ref command) { if (std::system (command.c_str ()) != 0) rt_error ("command failed: " + command); } bool file_is_readable (string_ref path) { struct stat stat_result; if (stat (path.c_str (), &stat_result) != 0) return false; return !! (stat_result.st_mode & S_IRUSR); } void rename_file (string_ref old_name, string_ref new_name) { if (::rename (old_name.c_str (), new_name.c_str ()) != 0) { rt_error ("rename " + old_name + " -> " + new_name + " failed"); } } bool remove_file (string_ref path, bool ignore_failure) { if (::unlink (path.c_str ()) != 0 && !ignore_failure) { rt_error ("unlink failed for " + path); return false; } else { return true; } } #ifndef HOST_NAME_MAX // for MacOS. 255 is the limit according to POSIX. #define HOST_NAME_MAX 255 #endif string hostname () { char buf[HOST_NAME_MAX+1]; gethostname (buf, HOST_NAME_MAX); buf[HOST_NAME_MAX] = 0; return buf; } void rt_error (string_ref msg) { throw std::runtime_error (msg); } std::vector <string> string_split (string_ref str) { std::vector <string> ret; boost::algorithm::split (ret, str, boost::is_any_of ("\t "), boost::token_compress_on); return ret; } std::ostream &operator<< (std::ostream &os, const AbortObject &) { os << std::endl; std::abort (); } static std::ostringstream cerr_buffer; static std::ofstream cerr_logfile; static std::ostream original_cerr_stream (0); void buffer_cerr () { // save the original stream buffer in case we need to restore it original_cerr_stream.rdbuf (std::cerr.rdbuf ()); // redirect cerr to cerr_buffer std::cerr.rdbuf (cerr_buffer.rdbuf ()); } void redirect_cerr (string_ref filename, bool append) { std::ios::openmode mode = std::ios::out; if (append) mode |= std::ios::app; cerr_logfile.open (filename, mode); if (!cerr_logfile) std::cerr << "cannot open log file " << filename << ABORT; // OK, assume the log is open. flush the buffer to the log std::cerr.flush (); cerr_logfile << cerr_buffer.str (); cerr_buffer.str (""); // redirect cerr to the log file std::cerr.rdbuf (cerr_logfile.rdbuf ()); } void dont_redirect_cerr () { // all in vain. std::cerr.flush (); original_cerr_stream << cerr_buffer.str (); cerr_buffer.str (""); // redirect cerr to the log file std::cerr.rdbuf (original_cerr_stream.rdbuf ()); } // argument helpers static std::pair <string, string> int_pop_arg (const char **argv) { assert (*argv); string kw = *argv++; if (!*argv) rt_error ("missing argument for kw " + kw); return std::make_pair (kw, string (*argv)); } template <> string read_arg (const char **argv) { string kw, value; std::tie (kw, value) = int_pop_arg (argv); return value; } template <> unsigned long read_arg (const char **argv) { string kw, value; std::tie (kw, value) = int_pop_arg (argv); try { return std::stoul (value); } catch (...) { rt_error ("cannot convert value " + value + " for keyword " + kw); } } template <> double read_arg (const char **argv) { string kw, value; std::tie (kw, value) = int_pop_arg (argv); try { return std::stod (value); } catch (...) { rt_error ("cannot convert value " + value + " for keyword " + kw); } } // RandomContext RandomContext::RandomContext () { #if RANDOM_EXPONENTIAL_BUFFER_SIZE != 0 num_exp_used_ = RANDOM_EXPONENTIAL_BUFFER_SIZE; #endif } void RandomContext::seed (unsigned seed) { e_.seed (seed); } // FIXME RandomContext::seed_from double RandomContext::real () { std::uniform_real_distribution<> dis (0, 1); return dis (e_); } double RandomContext::real (double high) { return high * real (); } double RandomContext::real (double low, double high) { assert (low < high); std::uniform_real_distribution<> dis (low, high); return dis (e_); } unsigned RandomContext::uint (unsigned max_excluded) { std::uniform_int_distribution <> dis (0, max_excluded-1u); return dis (e_); } // standard exponential (lambda = 1) double RandomContext::exponential () { return -std::log (1-real ()); } #if RANDOM_EXPONENTIAL_BUFFER_SIZE != 0 void RandomContext::refill_exp_buffer_ () { for (int i = 0; i != RANDOM_EXPONENTIAL_BUFFER_SIZE; ++i) exp_buffer_[i] = real (); for (int i = 0; i != RANDOM_EXPONENTIAL_BUFFER_SIZE; ++i) exp_buffer_[i] = -std::log (1-exp_buffer_[i]); num_exp_used_ = 0; } #endif double RandomContext::pareto (double paralpha, double minimum) { assert (paralpha > 0.); assert (minimum > 0.); double u = 1 - real (); return pow (u, -1/paralpha) * minimum; } template <> vector <2> RandomContext::unitbox () { return {{ real (-.5, .5), real (-.5, .5) }}; } template <> vector <3> RandomContext::unitbox () { return {{ real (-.5, .5), real (-.5, .5), real (-.5, .5) }}; } template <> vector <2> RandomContext::fromsphere <2> (double r) { double phi = real (2*M_PI); return {{ r*std::cos (phi), r*std::sin (phi) }}; } template <> vector <3> RandomContext::fromsphere <3> (double r) { double x = real (-1, 1); double y = real (-1, 1); double z = real (-1, 1); double s = pow (x*x + y*y + z*z, -0.5) * r; return {{ s*x, s*y, s*z }}; } template <> vector <2> RandomContext::fromball <2> (double r) { double x = real () + real (); if (x > 1.) x = 2-x; return fromsphere <2> (x*r); } template <> vector <3> RandomContext::fromball <3> (double r) { double s = std::cbrt (real ()); return fromsphere <3> (s*r); } template <size_t DIM> vector <DIM> RandomContext::fromshell (double rmin, double rmax) { assert (rmin >= 0.); assert (rmax > rmin); double dDIM = DIM; double u = real (pow (rmin, dDIM), pow (rmax, dDIM)); return fromsphere <DIM> (pow (u, 1/dDIM)); } // instantiate template vector <2> RandomContext::fromshell (double, double); template vector <3> RandomContext::fromshell (double, double); Histogram::Histogram (double bin_wid, double low, double high) : data_ ((high-low)/bin_wid, 0), bin_wid_ (bin_wid), low_ (low), num_sampl_ (0) { } Histogram::~Histogram () { } void Histogram::savetxt (string_ref filename) const { std::ofstream ofs (filename); ofs.exceptions (std::ios::failbit | std::ios::badbit); savetxt (ofs); } void Histogram::savetxt (std::ostream &os) const { for (unsigned i = 0; i != size (); ++i) os << bin_center (i) << ' ' << bin_density (i) << '\n'; }
true
9a380780b6d92de045a173b891beb5351ad52787
C++
ok-google/praktikum
/Praktikum/modul1.cpp
UTF-8
469
3.09375
3
[]
no_license
#include <iostream> using namespace std; void modul1() { float uangsila; float uangdidi; cout<<"Jumlah Uang Sila dan uang Didi adalah Rp 56.000 \n"; cout<<"Uang Sila lebih banyak Rp 600 dari uang Didi \n"; uangsila=(56000+600)/2; uangdidi=(56000-600)/2; cout<<"\nUang Sila = Rp "<<uangsila; cout<<endl; cout<<"Uang Didi = Rp "<<uangdidi; cout<<endl; cout<<"\nJadi uang Sila adalah Rp "<<uangsila; cout<<endl; }
true
552cc3bd9f3ba060823e2c87f90687e323602820
C++
usnistgov/OOF1
/XOOF/elementfunction.h
UTF-8
4,018
2.828125
3
[]
no_license
// -*- C++ -*- // $RCSfile: elementfunction.h,v $ // $Revision: 1.5 $ // $Author: langer $ // $Date: 2000-12-05 21:30:32 $ /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modifed * versions of this software, you first contact the authors at * oof_manager@ctcms.nist.gov. */ #ifndef ELEMENTFUNCTION_H #define ELEMENTFUNCTION_H // The ElementFunction classes define things that can be computed on // an Element. They are derived from this templated base class, which // takes care of things like putting the functions in the menus, and // making them accessible to the rest of the program. The derived // classes must look like this: // class StressXX : public ElementFunction<StressXX> { // public: // StressXX() {} // static CharString id() { return CharString("StressXX"); } // static double order() { return 1.0; } // virtual double operator()(Element &el) const { // return el.stresstensor()(0,0); // } // }; // template class ElementFunction<StressXX>; // Notes: // Although the ElementFunctions don't contain any non-static data, a // single instance of each function must be created, so that the // constructor can put each function in the menus, etc. In order to // do this in the base class, the type of the derived class is passed // to the base class (ElementFunction<>) as a template argument. That // means that the ElementFunction classes are all different types, so // the template ElementFunction<> is in turn derived from // ElementFunctionBase. ElementFunctionBase maintains the list of all // the ElementFunctions<>. // Because instances of these classes are created and used at startup // to construct the menus, they can't rely on static data for // initialization (there is no way to make sure that the // initialization data is created before the // ElementFunction). Therefore, instead of having a "static const // CharString name" data member, the classes have a function (id) // which returns the name. This function can't return a CharString&, // because to do that it would either have to return a reference to a // temporary, or the CharString would have to be a static member, and // we can't guarantee that *that* member would be constructed before // it's used. So, the derived class must return a plain old // CharString, which is inefficient. To relieve the inefficiency, // ElementFunction::name makes and stores a copy when needed, and returns a // reference to it. // The functions id() and order() must be static, because they are // used in the constructor of the ElementFunction<> base class. // The value returned by order() determines where this ElementFunction // will appear in menus. Lower orders come first. // Not all compilers catch the fact that these templates are actually // used, since they're not explicitly used anywhere: the only instance // of an object of the ElementFunction<StressXX> class is the static // instance declared within ElementFunction<StressXX>. The line // "template class ElementFunction<StressXX>" forces instantiation of // the template. // The SGI compiler can't seem to generate a default null constructor // and issues a warning if one isn't provided. Hence the line // "StressXX() {}" in the example above. #include "colordrawer.h" #include "elementfunctionbase.h" class CharString; template <class EF> class ElementFunction : public ElementFunctionBase { public: virtual ~ElementFunction(); virtual const CharString &name() const; virtual double operator()(Element&) const = 0; static const EF &instance(); virtual double order_() const; // order in menus protected: ElementFunction(); private: static const EF instance_; // the single instance }; #include "elementfunction.C" #endif // ELEMENTFUNCTION_H
true
4cb5946592fff3fdac324a46cfe48928f111bba4
C++
o-h-w-o-w/practice
/February 19, 2018 - [C++] Test Scores (structures)/TestScoreAndStructuresLab/src/TestScoreAndStructuresLab.cpp
UTF-8
3,060
3.859375
4
[]
no_license
/* Julian Mayugba * Professor A * February 19, 2018 * Test Scores [structures no functions] */ #include <iostream> #include <iomanip> #include <string> // Date Structure struct Date{ int Month, Day, Year; }; // Student Information Structure struct StudentInfo{ Date Grad; int Id; std::string FirstName, MiddleName, LastName; float TestOne, TestTwo, TestThree, TestAvg; }; // START OF MAIN FUNCTION int main() { short int noStudents; float classAverage = 0; // Introduction std::cout << "Class Average [Structure Ver]" << std::endl; // Number of Students Input for(;;){ std::cout << "\nEnter Number of Students: " << std::endl; if((std::cin >> noStudents) && (noStudents > 0)){ break; }else{ std::cout << "Invalid Input.\nPlease try again." << std::endl; std::cin.clear(); std::cin.ignore(80,'\n'); } } // Structure StudentInfo Student[noStudents]; // Input for(int i=0;i<noStudents;i++){ // Names Input std::cout << "Student No. " << i+1 << std::endl; std::cout << "Enter First Name: " << std::endl; std::cin >> Student[i].FirstName; std::cout << "Enter Middle Name: " << std::endl; std::cin >> Student[i].MiddleName; std::cout << "Enter Last Name: " << std::endl; std::cin >> Student[i].LastName; // Test Scores Input for(;;){ std::cout << "\nEnter Test Score 1: " << std::endl; if((std::cin >> Student[i].TestOne) && (Student[i].TestOne >= 0) && (Student[i].TestOne <= 100)){ break; }else{ std::cout << "Invalid Input.\nPlease try again." << std::endl; std::cin.clear(); std::cin.ignore(80,'\n'); } } for(;;){ std::cout << "\nEnter Test Score 2: " << std::endl; if((std::cin >> Student[i].TestTwo) && (Student[i].TestTwo >= 0) && (Student[i].TestTwo <= 100)){ break; }else{ std::cout << "Invalid Input.\nPlease try again." << std::endl; std::cin.clear(); std::cin.ignore(80,'\n'); } } for(;;){ std::cout << "\nEnter Test Score 3: " << std::endl; if((std::cin >> Student[i].TestThree) && (Student[i].TestThree >= 0) && (Student[i].TestThree <= 100)){ break; }else{ std::cout << "Invalid Input.\nPlease try again." << std::endl; std::cin.clear(); std::cin.ignore(80,'\n'); } } // Student Average Calc Student[i].TestAvg = (Student[i].TestOne + Student[i].TestTwo + Student[i].TestThree) / 3; // Class Average Accumulator classAverage += (Student[i].TestOne + Student[i].TestTwo + Student[i].TestThree); } // Class Average Calc classAverage = classAverage / (noStudents * 3); // Output std::cout << "F NAME\tM NAME\tL NAME\tTEST1\tTEST2\tTEST3\t AVG" << std::endl; std::cout << std::fixed << std::setprecision(2); for(int i=0;i<noStudents;i++){ std::cout << Student[i].FirstName << "\t" << Student[i].MiddleName.at(0) << "\t" << Student[i].LastName << "\t" << Student[i].TestOne << "\t" << Student[i].TestTwo << "\t" << Student[i].TestThree <<"\t" << Student[i].TestAvg << std::endl; } std::cout << "==========" << std::endl; std::cout << "Class Average: " << classAverage; return 0; }
true
bccf2463b099e396866d99a3b07e4e7241e7eb7e
C++
Shuaibahmed1/shuaib.github.io
/Website.cpp
UTF-8
196
3.28125
3
[]
no_license
#include <iostream> using namespace std; void swap (int a, int b){ int temp = b; b=a; a = b; } int main () { cout << endl; int a = 5, b = 10; swap(a,b) cout << a <<" " << b << endl; return 0; }
true
dfce56b97cdd6e8814a147d38a4f9b7068f2a8bb
C++
MatWiecz/AGH-C-
/lab-4/figure.h
UTF-8
445
2.71875
3
[]
no_license
// // Created by matthew on 11.04.19. // #ifndef LAB_4_FIGURE_H #define LAB_4_FIGURE_H #include "point.h" namespace lab4 { class Figure { protected: Point middle; string label; public: string description; double area; Figure ( const Point &, const string & ); virtual ~Figure ( ); void move ( const Point & ); virtual bool save ( ostream & ) const; virtual bool load ( istream & ); }; } #endif //LAB_4_FIGURE_H
true
72a60cce8138f8457b5392ac96a33510a52c5ecf
C++
dditota-esu/getThisBread
/CardAreaViewTest/RowOfStacks.h
UTF-8
1,064
2.859375
3
[]
no_license
//RowOfStacks header file #if !defined ROWOFSTACKS_H #define ROWOFSTACKS_H #include "IListOfLists.h" #include <vector> class Stack; class RowOfStacks : public IListOfLists { private: std::vector<Stack*> stackList; int currentList; public: RowOfStacks(); ~RowOfStacks(); // must implement all the methods in IListOfLists virtual ICardList* getFirstList(); virtual ICardList* getNextList(); virtual ICardList* getLastList(); virtual ICardList* getListAtIndex(int index); // Hof: I'm not sure what the following two methods are supposed to do. virtual int getListIndex(ICardList*); virtual int getCardIndex(int listIndex, ICard*); // mutator methods virtual void addToEnd(Stack*); virtual void addToBeginning(Stack*); virtual void addAtIndex(Stack*, int index); virtual Stack* removeAtEnd(); virtual Stack* removeAtBeginning(); virtual Stack* removeAtIndex(int index); void readFromFile(); // writes internal data to file void writeToFile(); // readss from file into internal data (attribs) }; #endif
true
4cb66901c59b1d9ab6805784155137f56594a721
C++
Tinwrks/TaiLeeCSC5
/Lab/TernaryOperator_With_A_Paycheck/main.cpp
UTF-8
965
3.203125
3
[]
no_license
/* * File: main.cpp * Author: Tai Lee * Purpose: Paycheck calculations with ternary operation * Created on June 23, 2016, 1:37 PM */ #include <iostream> #include <cstdlib> #include <iomanip> using namespace std; /* * */ int main(int argc, char** argv) { //declared variables float hrsWrkd=50;//Hours Worked float payRate=10;//$s/hr char ovrTime=40;//Overtume starts at 40 hours float payChck;//Paycheck in $'s //input data //process the data payChck=hrsWrkd<ovrTime?//Test hrsWrkd*payRate://True ovrTime*payRate+(hrsWrkd-ovrTime)*payRate*1.5; //output the processed data cout<<"Hours worked = "<<hrsWrkd<<"(hrs)"<<endl; cout<<"Pay Rate = $"<<payRate<<"/hr"<<endl; cout<<"Overtime starts at "<<static_cast<int>(ovrTime)<<"(hrs)"<<endl; cout<<fixed<<setprecision(2)<<showpoint; cout<<"Paycheck = $"<<payChck<<endl; //exit stage right! return 0; }
true
523d797da2ea6278ce4f46150578d9321160f6b1
C++
VasiPeycheva/Introduction-to-Programming--2017-2020
/04_scopes_nested_loops/practice/task_04.cpp
UTF-8
793
3.21875
3
[]
no_license
/**************************************************************************** * This file is part of the "Introduction to programming" course. FMI 2019/20 *****************************************************************************/ /** * @file task_04.cpp * @author Ivan Filipov * @author Kristian Krastev * @date 11.2019 * @brief Solution for task 4 from practice 4. */ #include <iostream> int main() { int number; for (int f_digit = 1; f_digit <= 9; f_digit++) { for (int s_digit = 0; s_digit <= 9; s_digit++) { for (int t_digit = 0; t_digit <= 9; t_digit++) { if (f_digit != s_digit && f_digit != t_digit && s_digit != t_digit) { number = 100 * f_digit + 10 * s_digit + t_digit; std::cout << number << std::endl; } } } } return 0; }
true
80b7aae057d842f22c7ac697fefc0d386fa0156f
C++
Felpat0/Matrix-Decomposition-AnalisiNumerica2
/householder.cpp
UTF-8
2,390
3.234375
3
[]
no_license
#include "algebra.h" int main(){ int n; cout<<"Insert the dimension of the matrix: "; cin>>n; Matrix m = Matrix(n); //Set the values of the matrix m.setMatrix(); int i = 0; for(int i = 0; i != m.dimension -1; i++){ myVector app = myVector(m.dimension); myVector temp = myVector(m.dimension - i); //Calculate the u tilde vector of this column app = m.getColumn(i); myVector u = myVector(m.dimension - i); for(int k = 0; k != m.dimension-i; k++){ u.myvector[k] = app.myvector[k + i]; } temp.myvector[0] = u.norm2(); u = u - temp; //Calculate alpha long double alpha = 2/(u.norm2()*u.norm2()); //Create the matrix of this step (initialized to all 0) Matrix householder = Matrix(m.dimension); //Calculate the matrix of dimension n-i, where i is the current step number //NOTES: //(Matrix(m.dimension - i, 'i') is the Identity Matrix with n-i dimension //Matrix(u, u) is u*u^t Matrix smallHouseHolder = (Matrix(m.dimension - i, 'i') - (Matrix(u, u) * alpha)); //Check if the current step is the first if(i > 0){ //If it is not, build the householder matrix starting from the small one //Insert the elements of the small matrix into the n dimension one for(int k = i; k != householder.dimension; k++){ for(int j = i; j != householder.dimension; j++){ householder.matrix[k][j] = smallHouseHolder.matrix[k - i][j - i]; } } //To not change the 0,..,i columns and the 0,...,i rows of the m matrix, make the Householder matrix (0,0),...,(i,i) elements be 1 //NB: the other elements of those columns/rows are already 1 for(int k = 0; k != i; k++){ householder.matrix[k][k] = 1; } //Apply the Householder matrix m = householder * m; }else{ //The step is the first, so smallHouseHolder equals HouseHolder m = smallHouseHolder * m; } //Put the right 0s (because of the not perfect precision) for(int j = i+1; j != m.dimension; j++){ m.matrix[j][i] = 0; } } m.printMatrix(); cout<<endl; system("pause"); return 0; }
true
1cdccd02cf6e92b9ee824629b864cde45b058218
C++
alonso804/POO-I-Asesorias
/Semana-5/unsolved/e3.cpp
UTF-8
963
3.84375
4
[]
no_license
#include <iostream> using namespace std; void print(int*, int); void insertionSort(int*&, int); int main(int argc, char *argv[]) { int tamano = 0; cout << "Ingrese tamaño: "; cin >> tamano; int* mi_array = new int[tamano]; for(int i = 0; i < tamano; i++) { cin >> *(mi_array + i); } cout << "Original: "; print(mi_array, tamano); insertionSort(mi_array, tamano); cout << "Ordenado: "; print(mi_array, tamano); delete [] mi_array; return 0; } void print(int* mi_array, int tamano) { cout << "{"; for(int i = 0; i < tamano; i++) { cout << *(mi_array + i) << ((i == tamano - 1) ? "" : ", "); } cout << "}\n"; } void insertionSort(int*& mi_array, int tamano) { int actual = 0; int j = 0; for(int i = 1; i < tamano; i++) { actual = *(mi_array + i); // actual = 3 j = i - 1; // j = 0 while(j >= 0 && *(mi_array + j) > actual) { *(mi_array + j + 1) = *(mi_array + j); j--; } *(mi_array + j + 1) = actual; } }
true
5df38ebbe0a923464ed4666dc50e6c0871a773fa
C++
Teddytws/111-Demos
/sets/demo.cpp
UTF-8
523
3.484375
3
[]
no_license
#include <set> #include <iostream> //insert //iterator - begin - end //empty //find //count using namespace std; int main() { set<int> myset; set<int>::iterator it; myset.insert(20); myset.insert(30); myset.insert(40); myset.insert(50); myset.insert(60); it = myset.find(50); if (it != myset.end()) cout << "found it" << endl; else cout << " nope" << endl; myset.erase(50); for (it = myset.begin(); it != myset.end(); it++) { cout << *it << endl; } return 0; }
true
a430fc5fd35ce6d6aa66f7846e6fb0f3e1d8c261
C++
Swire42/EasySDL
/EasySDL-key2char.cpp
UTF-8
14,864
2.640625
3
[ "MIT" ]
permissive
#include "EasySDL.hpp" #include "EasySDL-key2char.hpp" /// LETTERS -------------------------------------------------------------------------------------- void key2char::write_a() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="a"; } else { (*keyboardCharDest)+="A"; } } void key2char::write_b() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="b"; } else { (*keyboardCharDest)+="B"; } } void key2char::write_c() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="c"; } else { (*keyboardCharDest)+="C"; } } void key2char::write_d() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="d"; } else { (*keyboardCharDest)+="D"; } } void key2char::write_e() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="e"; } else { (*keyboardCharDest)+="E"; } } void key2char::write_f() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="f"; } else { (*keyboardCharDest)+="F"; } } void key2char::write_g() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="g"; } else { (*keyboardCharDest)+="G"; } } void key2char::write_h() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="h"; } else { (*keyboardCharDest)+="H"; } } void key2char::write_i() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="i"; } else { (*keyboardCharDest)+="I"; } } void key2char::write_j() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="j"; } else { (*keyboardCharDest)+="J"; } } void key2char::write_k() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="k"; } else { (*keyboardCharDest)+="K"; } } void key2char::write_l() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="l"; } else { (*keyboardCharDest)+="L"; } } void key2char::write_m() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="m"; } else { (*keyboardCharDest)+="M"; } } void key2char::write_n() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="n"; } else { (*keyboardCharDest)+="N"; } } void key2char::write_o() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="o"; } else { (*keyboardCharDest)+="O"; } } void key2char::write_p() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="p"; } else { (*keyboardCharDest)+="P"; } } void key2char::write_q() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="q"; } else { (*keyboardCharDest)+="Q"; } } void key2char::write_r() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="r"; } else { (*keyboardCharDest)+="R"; } } void key2char::write_s() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="s"; } else { (*keyboardCharDest)+="S"; } } void key2char::write_t() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="t"; } else { (*keyboardCharDest)+="T"; } } void key2char::write_u() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="u"; } else { (*keyboardCharDest)+="U"; } } void key2char::write_v() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="v"; } else { (*keyboardCharDest)+="V"; } } void key2char::write_w() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="w"; } else { (*keyboardCharDest)+="W"; } } void key2char::write_x() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="x"; } else { (*keyboardCharDest)+="X"; } } void key2char::write_y() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="y"; } else { (*keyboardCharDest)+="Y"; } } void key2char::write_z() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) { (*keyboardCharDest)+="z"; } else { (*keyboardCharDest)+="Z"; } } /// 1st line ------------------------------------------------------------------------------------- void key2char::write_world_18() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) (*keyboardCharDest)+="²"; } void key2char::write_ampersand() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (!upper) (*keyboardCharDest)+='&'; else (*keyboardCharDest)+='1'; } void key2char::write_world_73() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='~'; else if (!upper) (*keyboardCharDest)+=(char)(233); else (*keyboardCharDest)+='2'; } void key2char::write_quotedbl() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='#'; else if (!upper) (*keyboardCharDest)+='\"'; else (*keyboardCharDest)+='3'; } void key2char::write_quote() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='{'; else if (!upper) (*keyboardCharDest)+='\''; else (*keyboardCharDest)+='4'; } void key2char::write_leftparen() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='['; else if (!upper) (*keyboardCharDest)+='('; else (*keyboardCharDest)+='5'; } void key2char::write_minus() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='|'; else if (!upper) (*keyboardCharDest)+='-'; else (*keyboardCharDest)+='6'; } void key2char::write_world_72() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='`'; else if (!upper) (*keyboardCharDest)+=(char)(232); else (*keyboardCharDest)+='7'; } void key2char::write_underscore() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='\\'; else if (!upper) (*keyboardCharDest)+='_'; else (*keyboardCharDest)+='8'; } void key2char::write_world_71() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='^'; else if (!upper) (*keyboardCharDest)+=(char)(231); else (*keyboardCharDest)+='9'; } void key2char::write_world_64() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='@'; else if (!upper) (*keyboardCharDest)+=(char)(224); else (*keyboardCharDest)+='0'; } void key2char::write_rightparen() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+="]"; else if (!upper) (*keyboardCharDest)+=')'; else (*keyboardCharDest)+="°"; } void key2char::write_equals() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+='}'; else if (!upper) (*keyboardCharDest)+='='; else (*keyboardCharDest)+='+'; } void key2char::write_backspace() { if (!keyboardCharDest->empty()) keyboardCharDest->erase(keyboardCharDest->size()-1, 1); } /// 2nd line ------------------------------------------------------------------------------------- void key2char::write_tab() { (*keyboardCharDest)+=" "; } void key2char::write_caret() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; else if (!upper) (*keyboardCharDest)+='^'; else (*keyboardCharDest)+="¨"; } void key2char::write_dollar() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+="¤"; else if (!upper) (*keyboardCharDest)+='$'; else (*keyboardCharDest)+="£"; } void key2char::write_asterisk() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; else if (!upper) (*keyboardCharDest)+='*'; else (*keyboardCharDest)+="µ"; } /// 3rd line ------------------------------------------------------------------------------------- void key2char::write_world_89() { bool upper=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; else if (!upper) (*keyboardCharDest)+="ù"; else (*keyboardCharDest)+='%'; } void key2char::write_return() { (*keyboardCharDest)+='\n'; } /// KP ------------------------------------------------------------------------------------------- void key2char::write_kp0() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="0"; } else { keyDown[SDLK_INSERT](); } } void key2char::write_kp1() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="1"; } else { keyDown[SDLK_END](); } } void key2char::write_kp2() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="2"; } else { keyDown[SDLK_DOWN](); } } void key2char::write_kp3() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="3"; } else { keyDown[SDLK_PAGEDOWN](); } } void key2char::write_kp4() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="4"; } else { keyDown[SDLK_LEFT](); } } void key2char::write_kp5() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="5"; } } void key2char::write_kp6() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="6"; } else { keyDown[SDLK_RIGHT](); } } void key2char::write_kp7() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="7"; } else { keyDown[SDLK_HOME](); } } void key2char::write_kp8() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="8"; } else { keyDown[SDLK_UP](); } } void key2char::write_kp9() { bool num=false; if (SDL_GetModState() & KMOD_NUM) num=true; if (num) { (*keyboardCharDest)+="9"; } else { keyDown[SDLK_PAGEUP](); } } void key2char::write_kp_divide() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+=':'; else if (!upper) (*keyboardCharDest)+=(char)(247); else (*keyboardCharDest)+='/'; } void key2char::write_kp_multiply() { bool upper=false; bool graphic=false; if (SDL_GetModState() & KMOD_SHIFT) upper=true; if (SDL_GetModState() & KMOD_CAPS) upper=1-upper; if (SDL_GetModState() & KMOD_MODE) graphic=true; if (graphic) (*keyboardCharDest)+="·"; else if (!upper) (*keyboardCharDest)+="*"; } void key2char::write_kp_minus() { (*keyboardCharDest)+='-'; } void key2char::write_kp_plus() { (*keyboardCharDest)+='+'; } void key2char::write_kp_equals() { (*keyboardCharDest)+='='; } void key2char::write_kp_enter() { (*keyboardCharDest)+='\n'; }
true
a3f563ebcb2aa14e2fc68c59c1e9595943ef9c17
C++
echowsy/opengl_songho
/glWinSimple/src/ModelGL.h
UTF-8
1,293
2.828125
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// // ModelGL.h // ========= // Model component of OpenGL // // AUTHOR: Song Ho Ahn (song.ahn@gmail.com) // CREATED: 2006-07-10 // UPDATED: 2006-07-10 /////////////////////////////////////////////////////////////////////////////// #ifndef MODEL_GL_H #define MODEL_GL_H class ModelGL { public: ModelGL(); // ctor ~ModelGL(); // dtor void init(); // initialize OpenGL states void setCamera(float posX, float posY, float posZ, float targetX, float targetY, float targetZ); void setViewport(int width, int height); void draw(); void setMouseLeft(bool flag) { mouseLeftDown = flag; }; void setMouseRight(bool flag) { mouseRightDown = flag; }; void setMousePosition(int x, int y) { mouseX = x; mouseY = y; }; void rotateCamera(int x, int y); void zoomCamera(int dist); protected: private: // member functions void initLights(); // add a white light ti scene // members bool mouseLeftDown; bool mouseRightDown; int mouseX; int mouseY; float cameraAngleX; float cameraAngleY; float cameraDistance; }; #endif
true
4fdea9c7b1f28f08a17c1b6d6de6f2e87cf76db5
C++
zlpetersen/asteroids
/Asteroids/Bullet.cpp
UTF-8
1,254
3.109375
3
[]
no_license
#include "Bullet.h" #include <iostream> Bullet::Bullet(double rotation, sf::Vector2f pos) { rot = rotation; // assign instance rotation // create bullet texture // t = new sf::Texture; t->loadFromFile("Bullet.png"); t->setSmooth(true); // assign bullet texture and set origin, position, rotation // setTexture(*t); setOrigin(t->getSize().x / 2, t->getSize().y / 2); setPosition(pos); setRotation(rot); // set velocity based on rotation and speed // xvel = cos((rot * 3.14) / 180) * speed; yvel = sin((rot * 3.14) / 180) * speed; timer = 0; // start deletion timer at 0 } Bullet::~Bullet() { } void Bullet::update(sf::RenderWindow& w) { timer++; // add to deletion timer // move sprite move(xvel, yvel); // wrap around edges of screen // if (getPosition().x > w.getSize().x) setPosition(sf::Vector2f(-getTextureRect().width, getPosition().y)); if (getPosition().x < -getTextureRect().width) setPosition(sf::Vector2f(w.getSize().x, getPosition().y)); if (getPosition().y > w.getSize().y) setPosition(sf::Vector2f(getPosition().x, -getTextureRect().height)); if (getPosition().y < -getTextureRect().height) setPosition(sf::Vector2f(getPosition().x, w.getSize().y)); }
true
8a1698aea0783a90b9ea2bef491d9300fdb89a3c
C++
bajajtushar094/Competitive-Programming
/cp/prefix.cpp
UTF-8
784
2.65625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define ll long long int int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<ll> numbers; ll sum_suffix=0; for(int i=0;i<n;i++) { ll c; cin>>c; numbers.push_back(c); sum_suffix+=c; } ll sum_prefix = numbers[0]; ll tot_sum= sum_prefix+sum_prefix; int c=0; for(int i=1;i<n;i++) { sum_suffix-=numbers[i-1]; sum_prefix+=numbers[i]; ll sum_now=sum_prefix+sum_suffix; if(sum_now<tot_sum) { tot_sum=sum_now; c=i; } } cout<<c+1<<'\n'; } }
true
f0ef4394031e908bf6f0fbf89b6876821323f387
C++
adityeah8969/projects_cpp
/primsMST.cpp
UTF-8
2,224
3.125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; list<pair<int,int>> Adj[105]; int N; int key[105]; int parent[105]; bool mst[105]; priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> pq; void addEdge(int u,int v,int w){ Adj[u].push_back(make_pair(v,w)); Adj[v].push_back(make_pair(u,w)); return; } void init(int src){ for(int i=0;i<N;i++){ mst[i]=false; key[i]=INT_MAX; parent[i]=-1; } key[src]=0; mst[src]=true; return; } void primMst(int src, int V){ pq.push(make_pair(0,src)); int counter = 1; while(!pq.empty()){ int u=pq.top().second; pq.pop(); mst[u]=true; //mst[u] gets true only after its proven that the vertex //has been introduced via its least weight. if(counter>V){break;} counter++; for(auto it=Adj[u].begin();it!=Adj[u].end();it++){ int v =(*it).first; int weight=(*it).second; if(!mst[v] && key[v]>weight){ // we dont make mst[v] true inside because we want the key[v]=weight; // pair having vertex 'v' get inside the priority queue parent[v]=u; // via some of its edges. Then picking the pair with least pq.push(make_pair(key[v],v)); // key[v] possible using priority queue. } } } cout<<"parent -> child\n"; for(int i=1;i<N;i++){ cout<<" "<<parent[i]<<" -> "<<i<<"\n"; } return; } int main(){ N=9; addEdge(0, 1, 4); addEdge(0, 7, 8); addEdge(1, 2, 8); addEdge(1, 7, 11); addEdge(2, 3, 7); addEdge(2, 8, 2); addEdge(2, 5, 4); addEdge(3, 4, 9); addEdge(3, 5, 14); addEdge(4, 5, 10); addEdge(5, 6, 2); addEdge(6, 7, 1); addEdge(6, 8, 6); addEdge(7, 8, 7); int src=0; init(src); primMst(src, N); return 0; } // Time Complexity: O(V)*(O(logV)+O(Ev)*O(logV)) = O(ElogV)
true
20a9056cdf2f75d4ab567871806839de3b5cf8d6
C++
2020wmarvil/top-down-platformer
/include/tile.h
UTF-8
165
2.890625
3
[ "MIT" ]
permissive
#pragma once class Tile { private: int tile_id; public: Tile(int tile_id) { this->tile_id = tile_id; } ~Tile() {} int getTileID() const { return tile_id; } };
true
d06df89633cba66b9e2c243d7d3309ffbe0e9011
C++
genie97/ALGORITHM
/BOJ_ALGORITHM/1867_돌맹이 제거.cpp
UTF-8
608
2.515625
3
[]
no_license
#include<cstdio> #include<vector> #include<string.h> using namespace std; int n, k, bm[502]; bool visit[502]; vector <vector<int>> vt; bool dfs(int v){ if (visit[v]) return false; visit[v] = true; for (int next : vt[v]) { if (!bm[next] || dfs(bm[next])) { bm[next] = v; return true; } } return false; } int main() { scanf("%d %d", &n, &k); vt.resize(n + 1); for (int i = 1; i <= k; i++) { int a, b; scanf("%d %d", &a, &b); vt[a].push_back(b); } int res = 0; for (int i = 1; i <= n; i++) { memset(visit, false, sizeof(visit)); if (dfs(i)) res++; } printf("%d\n", res); }
true
23a36a9756db0866351b7432c3cf1bed5af5c600
C++
gatlinfarrington/summer21
/c++ work/assignment1.cpp
UTF-8
687
3.59375
4
[]
no_license
#include <iostream> #include "assignment1.hpp" #include <string> #include <cstring> class Movie{ private: std::string name; std::string Director; std::string releaseDate; std::string Rating; public: Movie(std::string n="", std::string d="", std::string r="", std::string rd=""){ name=n; Director=d; Rating=r; releaseDate=rd; } void print_movie(); }; void Movie::print_movie(){ std::cout << "Name: " << name << " Director: " << Director << " released: " << releaseDate << " Rating: " << Rating << std::endl; } int main(){ Movie m1("Titanic", "Steven Speilberg", "G", "Jan 29 2002"); m1.print_movie(); return 0; }
true
fafc9431013eccc0a7ece99c70b4d43f13423277
C++
namehao465/Essential-Cplusplus
/Essential C++/04 Object-Based Programming/main.cpp
UTF-8
1,075
3.40625
3
[]
no_license
#include<iostream> #include<istream> #include"Stack.h" #include"Triangular.h" #include"Matrix.h" #include<string> using namespace std; void fill_stack(Stack &stack,ostream &os = cout, istream &is = cin); void test_Stack(); void test_Triangular(); void test_Matrix(); int sum(Triangular &trian); int main() { //test_Stack(); test_Triangular(); //test_Matrix(); system("pause"); return 0; } void test_Matrix() { Matrix mat(5,5); Matrix mat2 = mat; Matrix mat3(mat); mat3 = mat; } void test_Triangular() { Triangular t5(); } int sum(Triangular &trian) { int } void test_Stack() { Stack stack; //stack.setMaxSize(10); fill_stack(stack); string str; cin >> str; if (stack.find(str)) { cout << "find it " << stack.count(str) << " times " << endl; } else { cout << "no" << endl; } } void fill_stack(Stack &stack, ostream &os, istream &is) { string str; while (is >> str && !stack.full() && str != "out") { stack.push(str); } os << stack.size() << endl; os << stack.maxSize() << endl; os << "Read in " << stack.size() << " elements\n" << endl; }
true
5a8d2fe04593722f1a041e12447b63cf1a098802
C++
Ketan-Suthar/Algorithms
/Greedy Algorithms/LargestPalindromicNumberPermutingDigits/GFG.cpp
UTF-8
895
3.609375
4
[]
no_license
#include <bits/stdc++.h> using namespace std; bool isPalindrome(int arr[]) { int odds=0; for(int i=0; i<9; ++i) { if(arr[i] != 0 && (arr[i] & 1)) ++odds; if(odds > 1) return false; } return true; } void largestPalindrome(string s) { int nums[10] = {0}; for(char x: s) nums[x - '0']++; if(!isPalindrome(nums)) { cout << "\ncannot form Palindrome"; return; } int len = s.size(); char largest[len]; int front = 0; for(int i=9; i>=0; --i) { if(nums[i] & 1) { largest[len/2] = char(i + 48); nums[i]--; } while(nums[i] > 0) { largest[front] = char(i + 48); largest[len - front - 1] = char(i + 48); ++front; nums[i] -= 2; } } cout << "\nlargest Palindrome number is: "; for (int i = 0; i < len; ++i) cout << largest[i]; } // Driver Code int main() { string s; cin >> s; largestPalindrome(s); return 0; }
true
addc6306fc3343206d75cd6698846150767f6ba6
C++
erich-gatejen/Arduino
/sketch_oct08b/sketch_oct08b.ino
UTF-8
358
2.625
3
[]
no_license
void setup() { // put your setup code here, to run once: pinMode(15, OUTPUT); pinMode(16, OUTPUT); pinMode(17, OUTPUT); } void loop() { // put your main code here, to run repeatedly: analogWrite(15, 200); analogWrite(16, 200); analogWrite(17, 200); delay(2000); analogWrite(15, 0); analogWrite(16,0); analogWrite(17, 0); }
true
8a7ebaed80d24849ef50d21a4e9595ce84bb7d20
C++
mikechen66/CPP-Programming
/CPP-Programming-Principles/chapter23-text/ex06_dates.cpp
UTF-8
1,266
3.609375
4
[]
no_license
// // Stroustrup - Programming Principles & Practice // // Chapter 23 Exercise 6 - Date Finder // // Write a program that finds dates in a text file. Write out each line that // contains at least one date. // #include <iostream> #include <stdexcept> #include <string> #include <regex> #include <fstream> bool has_date(const std::string& s) // pat1 = 12/24/2004 // pat2 = Mon(,) Feb 26 2018 (comma optional) // pat3 = January 12, 1995 { std::regex pat1 {R"(\d{2}/\d{2}/\d{4})"}; std::regex pat2 {R"(\b[A-Za-z]+,? [A-Za-z]+ \d{1,2} \d{4}\b)"}; std::regex pat3 {R"(\w+ \d{1,2}, \d{4}\b)"}; return std::regex_search(s, pat1) || std::regex_search(s, pat2) || std::regex_search(s, pat3); } int main() try { std::ifstream ifs {"input_dates.txt"}; if (!ifs) { std::cerr << "Could not read from input file\n"; return 1; } int lineno = 0; std::string line; while (ifs) { ++lineno; std::getline(ifs, line); if (has_date(line)) std::cout << lineno << ": " << line << '\n'; } } catch(std::exception& e) { std::cerr << "Exception: " << e.what() << '\n'; return 1; } catch(...) { std::cerr << "Unknown exception\n"; return 2; }
true
de5dfe58caea41ce40eb04944fadb02ee2155038
C++
abivlqz/Algoritmos
/Algoritmos/Tar01/tar01.cpp
UTF-8
1,904
3.875
4
[]
no_license
// // tar01.cpp // Algoritmos // // Abigail Guadalupe Velazquez Sanchez A01566592 Grupo1 // Creado el 13/02/2021 /* Este programa solicita al usuario un tipo de dato string que contenga varios caracteres duplicados y continuos con excepcion de un caracter, el programa encuentra y devuelve este caracter unico dentro del string */ #include <stdio.h> #include <iostream> #include <string> using namespace std; // Funcion findChar que recibe de parametro un string con caracteres repetidos excepto uno // y busca y despliega en pantalla ese unico caracter que no se repite void findChar(string str){ int low = 0; int high = (int(str.size())-1); bool found = false; while (low<= high && found == false ) { int central = (low+high)/2; //Si sus caracteres vecinos son distintos es el unico if (str[central] != str[central-1] && str[central] != str[central+1] ) { found = true; cout<<str[central]<<endl; } // Si su caracter vecino de la derecha es su pareja else if ( str[central] == str[central+1] ){ // Si la cantidad de caracteres a la derecha es impar, el caracter esta a la derecha de la pareja if ( (high-(central+2))%2 == 0 ) low = central +2; else // Si es par esta a la izquierda high = central -1; } // Si su caracter vecino de la izquierda es su pareja else{ // Si la cantidad de caracteres a la izquierda es impar, el caracter esta a la izquierda de la pareja if ( ((central-2)-low)%2 == 0 ) high = central -2; else // Si es par esta a la derecha low = central +1; } } } // Programa principal int main(){ string str; cout<<"Ingrese su string :"<<endl; getline(cin, str); findChar(str); return 0; }
true
b7f0bf57eb8a1b07f5f293358a7740c25570ac52
C++
MartinMueller-StudioMood/PFMCPP_Project3
/main.cpp
UTF-8
9,374
3.125
3
[]
no_license
/* Project 3 - Part 3 / 5 video: Chapter 2 - Part 8 Constructors tasks Create a branch named Part3 On this new branch: 1) Add a constructor for each User-Defined-Type. 2) amend some of your UDT's member functions to print out something interesting via std::cout 3) Instantiate 1 or 2 instances of each of your user-defined types in the main() function 4) call some of your UDT's amended member functions in main(). 5) add some std::cout statements in main() that print out your UDT's member variable values or values returned from your UDT member functions (if they return values) After you finish defining each type/function: click the [run] button. Clear up any errors or warnings as best you can. example: */ #include <iostream> namespace Example { struct UDT // my user defined type named 'UDT' { int a; //a member variable UDT(); //1) the constructor void printThing(); //the member function }; //the function definitions are outside of the class UDT::UDT() { a = 0; } void UDT::printThing() { std::cout << "UDT::printThing() " << a << std::endl; //2) printing out something interesting } int main() { UDT foo; //3) instantiating a UDT named 'foo' in main() foo.printThing(); //4) calling a member function of the UDT instance. //5) a std::cout statement accessing foo's member variable. //It also demonstrates a 'ternary expression', which is syntactic shorthand for an 'if/else' expression std::cout << "Is foo's member var 'a' equal to 0? " << (foo.a == 0 ? "Yes" : "No") << "\n"; return 0; } } //end namespace Example //insert Example::main() into main() of user's repo. #include <iostream> using namespace std; struct Delay { int timeKnob = 63; float feedback = 127.0f; int repeat = 10; double spread = 50.0; int dryWet = 100; struct Echo { bool isEnabled = false; float echoTime = 20.47f; double stereo = 10; void repeatSignal(double echoSpeed = 3.0); }; float repeatSignal( Echo echo ) { float speed = 10.8f + echo.echoTime / 360.0f; echo.repeatSignal(); return speed; } double calculateFeedback(double echoFeedback) { double feedbackSignal = echoFeedback * double(repeat)/7.89; return feedbackSignal; } double spreadSignal( Echo echo ) { if (echo.isEnabled) { echo.stereo += spread; } return echo.stereo; } Echo echoRunning; }; struct Filter { float frequenceKnob = 12456.58f; float resonanceKnob = 127.0f; float saturationValue = 23.9f; double modulationKnob = 127.0; int lfoKnob = 127; int filterTypKnob = 100; bool lfoFilter = false; struct Bandpass { bool isAnabled = false; float bandFrequency = 10.0f; double filterSignal(double resonanceAmount = 3.0); }; float cutSignal( Filter filter ) { float filterFrequence = filter.frequenceKnob + 10.3f; return filterFrequence; } float modulateFrequencies(float lfoFrequence, Filter filter) { float filterFrequence = 0.0f; if(lfoFilter) { filterFrequence = filter.frequenceKnob * lfoFrequence /100; } return filterFrequence; } float colorSound( Filter filter ) { float colorFrequency = filter.frequenceKnob * saturationValue; return colorFrequency; } Bandpass bandpassRunning; }; struct Phaser { double polesKnob = 5; float colorKnob = 127.0f; int envelopeKnob = 127; double lfoKnob = 127.0; int feedbackKnob = 127; int stereo = 127; int phasingSound(int phaseFrequence) { int phaseAmplitude = 0; int i = 0; while (i < 57) { phaseAmplitude = phaseFrequence * i / int(polesKnob) * feedbackKnob; i++; } return phaseAmplitude; } void stereoEffects(int frequence, int spread) { stereo = frequence * spread / 100; } double lfo(double time) { double lfoModulation = lfoKnob * double(envelopeKnob) / time; return lfoModulation; } }; struct DrumMachine { int bassdrum = 12; int snare = 8; int tom = 4; int hihat = 5; int sequencer = 127; void drumSounds(int sampleNumber) { switch (sampleNumber) { case 1: cout << "808"; break; case 2: cout << "909"; break; case 3: cout << "707"; break; case 4: cout << "606"; break; case 5: cout << "Linndrum"; break; case 6: cout << "505"; break; case 7: cout << "Oberheim"; break; } } int grooves(int shuffle) { for (int i = 0; i < 78; i++) { shuffle = i * rand() % 100; } return shuffle; } bool sendMidi(bool midiSend, bool midiInterface) { if(midiSend & midiInterface) { return true; } else { return false; } } }; struct Oscillator { int volume = 127; double sin = 127.0; double square = 23.0; double triangle = 27.0; float noise = 127.0f; double waveform(int waveform) { double modulatedWaveform = 0; if(waveform == 1) { modulatedWaveform = sin * 345; } else if(waveform == 2) { modulatedWaveform = square * 333; } else if(waveform == 3) { modulatedWaveform = triangle * 360; } return modulatedWaveform; } bool sounds(bool oscillatorOn) { if(oscillatorOn && sin >= 30) { oscillatorOn = true; } else { oscillatorOn = false; } return oscillatorOn; } int changeVolume(); }; struct Adsr { int attack = 127; int decay = 127; int sustain = 23; int release = 27; float amount = 127.0; int changeAttack(int knobValue) { attack = knobValue * int(amount)/100; return attack; } int changeDecay(int knobValue) { decay = knobValue * int(amount)*23; return decay; } int changeRelease(int knobValue) { release = knobValue/123*100; return release; } }; struct Midi { int value = 127; int channel = 127; int input = 127; int output = 127; bool syncType = true; struct MidiMessage { bool isEnabled = false; int midiChannel = 1; void sendSignal(int midiMessage); void getSignal(); }; void sendMidi(MidiMessage midiMessage) { if(midiMessage.isEnabled) { midiMessage.sendSignal(value); } } void receiveMidi(MidiMessage midiMessage) { if(midiMessage.isEnabled) { midiMessage.getSignal(); } } void enableMidi(bool enableMidi, MidiMessage midiMessage) { if(enableMidi) { midiMessage.isEnabled = true; } } }; struct Lfo { int rate = 127; int amount = 127; float waveform = 127.0; int adsr = 127; double retrigger = 127.0; void setRate(int value, int modulate) { rate = value + modulate; } int getAmount() { return amount; } double getRetrigger() { return retrigger * amount / rate; } }; struct Sampler { int retrigger = 127; int startSample = 127; bool isLooped = true; float loopLength = 127.0f; float loopSample = 0.0f; double fadeLengthInMilliseconds = 127.0; void playSample(bool play, int load) { if(play) { load = startSample*retrigger; } } void setStartPoint(int knobValue) { startSample = knobValue/100; } void loopSound(bool loop, int repeat) { if(loop) { loopSample = loopLength * float(repeat); } } }; struct Synthesizer { Oscillator oscillator; Adsr adsr; Filter filter; Midi midi; Lfo lfo; void createSounds(Oscillator oscillatorSynth, int waveform) { oscillatorSynth.waveform(waveform); } void sendMidi(Midi midiSynth, Midi::MidiMessage midiMessage) { midiSynth.sendMidi(midiMessage); } void manipulateSoundAdsr(Adsr adsrSynth, int parameter, int knobValue) { if(parameter == 0) { adsrSynth.changeAttack(knobValue); } else if(parameter == 1) { adsrSynth.changeDecay(knobValue); } else if(parameter == 2) { adsrSynth.changeRelease(knobValue); } } }; #include <iostream> int main() { Example::main(); std::cout << "good to go!" << std::endl; }
true
915bfb9240f82730242ec79b93901cef00b2dd54
C++
FabioVL/Treinamento---Maratona
/2015-2016 ACM-ICPC Pacific Northwest Regional Contest (Div. 2)/m.cpp
UTF-8
526
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { string op; int v,n,a[105],cont=0,p[105]; scanf("%d",&n); for(int i=1;i<=100;i++) a[i]=i, p[i]=0; for(int i=0;i<n;i++) { cin >> op >> v; for(int j=1;j<=100;j++) { if(op == "ADD") a[j] += v; else if(op == "SUBTRACT") { a[j] -= v; if(a[j]<0 and p[j]==0) cont++,p[j]=1; } else if(op == "MULTIPLY") a[j]*=v; else { if(a[j]%v != 0 and p[j]==0) cont++,p[j]=1; a[j]/=v; } } } printf("%d\n",cont); } /* */
true
0262bb98378b8946dfe37fbcad8eee6b4ce3498f
C++
ctrlMarcio/feup-cal-proj
/test/model/company_client/company_client_test.cpp
UTF-8
1,836
3.171875
3
[ "MIT" ]
permissive
#include <gtest/gtest.h> #include <model/company_client/company_client.h> using testing::Eq; CompanyClient createCompanyClient() { CompanyRepresentative companyRepresentative("nome", "email@email.com"); Location location(1, "a", 1, 1); CompanyClient companyClient("company", companyRepresentative, location); return companyClient; } TEST(company_client, contructor_default_test) { CompanyRepresentative companyRepresentative("nome", "email@email.com"); Location location(1, "a", 1, 1); CompanyClient companyClient("company", companyRepresentative, location); EXPECT_EQ(companyClient.getName(), "company"); EXPECT_EQ(companyClient.getHeadquarters(), location); EXPECT_EQ(companyClient.getRepresentative().getEmail(), companyRepresentative.getEmail()); } TEST(company_client, add_pickuppoints) { CompanyClient companyClient = createCompanyClient(); Location location1(2, "a", 1, 2); Location location2(3, "b", 1, 3); companyClient.addPickupPoint(location1); companyClient.addPickupPoint(location2); companyClient.addPickupPoint(location2); EXPECT_EQ(companyClient.getPickupPoints().size(), 2); } TEST(company_client, remove_pickuppoints) { CompanyClient companyClient = createCompanyClient(); Location location1(2, "a", 1, 2); Location location2(3, "b", 1, 3); companyClient.addPickupPoint(location1); companyClient.addPickupPoint(location2); companyClient.addPickupPoint(location2); companyClient.removePickupPoint(location1); EXPECT_EQ(companyClient.getPickupPoints().size(), 1); EXPECT_EQ(companyClient.getPickupPoints().at(0), location2); } TEST(company_client, change_vehicle_number) { CompanyClient companyClient = createCompanyClient(); companyClient.setVehicleNumber(3); EXPECT_EQ(companyClient.getVehicleNumber(), 3); }
true
feddc4fe34d194dee8cb31e2c5ba75e3adad5a3f
C++
a-ewais/Image-sharing-app
/profile.cpp
UTF-8
2,100
2.546875
3
[ "Apache-2.0" ]
permissive
#include "profile.h" #include "ui_profile.h" #include <QString> #include <QMessageBox> #include <QFileDialog> #include <opencv2/core.hpp> Profile::Profile(QWidget *parent, User* _user) : QMainWindow(parent), ui(new Ui::Profile) { ui->setupUi(this); user = _user; fillList(); } Profile::~Profile() { delete ui; delete info; delete peerProfile; delete request; } void Profile::fillList(){ std::vector<std::string> images= user->viewMyImages(); std::vector<std::string> online= user->viewOnlineUsers(); for (int i=0; i<images.size(); ++i) ui->images->addItem(QString::fromStdString(images[i])); for (int i=0; i<online.size(); ++i){ if(online[i]!=user->username) ui->onlineUsers->addItem(QString::fromStdString(online[i])); } } void Profile::on_upload_clicked() { QString filename= QFileDialog::getOpenFileName(this, tr("Choose Image"), "c://", "Image file (*.jpg *.png *.jpeg);;"); QMessageBox::information(this,tr("File Name"),filename); cv::Mat img = cv::imread(filename.toUtf8().constData(), cv::IMREAD_COLOR); user->uploadImage(filename.toUtf8().constData()); clear(); fillList(); // hide(); // request->show(); } void Profile::on_request_clicked() { request = new Requests(this,user); hide(); clear(); request->show(); } void Profile::on_logout_clicked() { user->down(); clear(); this->parentWidget()->show(); this->close(); } void Profile::on_images_itemDoubleClicked(QListWidgetItem *item) { QString image_name = item->text(); hide(); clear(); info = new ImageInformation(this,image_name,user); info->show(); } void Profile::on_onlineUsers_itemDoubleClicked(QListWidgetItem *item) { QString temp = item->text(); peerProfile = new PeerProfile(this,temp,user); if(peerProfile->isEmpty()) return; peerProfile->show(); hide(); clear(); } void Profile::clear(){ ui->onlineUsers->clear(); ui->images->clear(); } void Profile::on_refresh_clicked() { clear(); fillList(); }
true
8323d42f672baf48dd09d2783911bb8115d1fc63
C++
WHO-A-U/Programmers
/C++/리틀프렌즈사천성.cpp
UTF-8
2,785
2.859375
3
[]
no_license
#include <string> #include <vector> #include <cstring> #include <algorithm> #include <queue> #include <iostream> using namespace std; char map[101][101]; int rs,cs; int dx[]={1,-1,0,0}; int dy[]={0,0,1,-1}; // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요. bool isPossible(pair<int,int> cur){ int r = cur.first; int c = cur.second; char target = map[r][c]; bool visit[101][101]; memset(visit,false,sizeof(visit)); queue<pair< int,int> > q; q.push(cur); queue<pair<int,int>> tmp; for(int k=0;k<2;k++){ while(!q.empty()){ int cr = q.front().first; int cc = q.front().second; q.pop(); for(int i=0;i<4;i++){ int nr = cr+dx[i]; int nc = cc+dy[i]; while(nr>=0&&nr<rs&&nc>=0&&nc<cs){ if(!(nr==r&&nc==c)&&map[nr][nc]==target){ return true; } if(map[nr][nc]!='.'){ break; } visit[nr][nc]=true; tmp.push({nr,nc}); nr+=dx[i]; nc+=dy[i]; } } } q=tmp; } return false; } void mapErase(char c){ for(int i=0;i<rs;i++){ for(int j=0;j<cs;j++){ if(map[i][j]==c){ map[i][j]='.'; } } } } string solution(int m, int n, vector<string> board) { rs = m; cs = n; pair<int,int> v['Z'-'A'+1]; memset(map,0,sizeof(map)); string answer = ""; vector<char> node; for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ map[i][j]=board[i][j]; char cur = board[i][j]; if('A'<=cur&&cur<='Z'){ node.push_back(cur); v[cur-'A']={i,j}; } } } sort(node.begin(),node.end()); node.erase(unique(node.begin(),node.end()),node.end()); while(node.size()>0){ bool flag=false; for(int i=0;i<node.size();i++){ char cur =node[i]; if(isPossible(v[cur-'A'])){ mapErase(cur); answer+=cur; vector<char> tmp; for(int j=0;j<node.size();j++){ if(node[j]!=cur){ tmp.push_back(node[j]); } } node = tmp; flag=true; break; } } if(!flag){ answer = "IMPOSSIBLE"; break; } } return answer; }
true
9bfaf106202253c83f6c319e0889a90ccd19d95b
C++
iomeone/CSGOCheat
/Trace.h
UTF-8
1,019
2.59375
3
[]
no_license
#pragma once #include "EngineTrace.h" #include "RandomStuff.h" class ITraceEngine { public: int GetPointContents(const Vector &vecAbsPosition, int contentsMask = MASK_ALL, entity** ppEntity = NULL) { typedef int(__thiscall* original)(void*, const Vector&, int, entity**); return vfunction<original>(this, 0)(this, vecAbsPosition, contentsMask, ppEntity); } // Traces a ray against a particular entity void ClipRayToEntity(const Ray_t &ray, unsigned int fMask, entity *pEnt, trace_t *pTrace) { typedef void(__thiscall* original)(void*, const Ray_t&, unsigned int, entity*, trace_t*); vfunction<original>(this, 3)(this, ray, fMask, pEnt, pTrace); } // A version that simply accepts a ray (can work as a traceline or tracehull) void TraceRay(const Ray_t &ray, unsigned int fMask, ITraceFilter* pTraceFilter, trace_t* pTrace) { typedef void(__thiscall* original)(void*, const Ray_t&, unsigned int, ITraceFilter*, trace_t*); vfunction<original>(this, 5)(this, ray, fMask, pTraceFilter, pTrace); } };
true
4c860905515b3f8cc8c7323cf458ac3b3a062781
C++
imsong52/Q.solution
/leetcode/122.best-time-to-buy-and-sell-stock-ii.cpp
UTF-8
1,065
3.3125
3
[]
no_license
/* * [122] Best Time to Buy and Sell Stock II * * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii * * Easy (45.87%) * Total Accepted: 127430 * Total Submissions: 277759 * Testcase Example: '[]' * * Say you have an array for which the ith element is the price of a given * stock on day i. * * Design an algorithm to find the maximum profit. You may complete as many * transactions as you like (ie, buy one and sell one share of the stock * multiple times). However, you may not engage in multiple transactions at the * same time (ie, you must sell the stock before you buy again). */ class Solution { public: int maxProfit(vector<int>& prices) { int x = 0, head = 0; prices.push_back(numeric_limits<int>::min()); stack<int> s; for (auto p : prices) { if (!s.empty() && s.top() > p) { x += s.top() - head; while (!s.empty()) s.pop(); } if (s.empty()) head = p; s.push(p); } return x; } };
true
2ad78cacb446cc9ab379b3387c24fbcce7d17be6
C++
YoungWoo93/BOJ
/BOJ/cpp/15650 N과 M(2)/15650.cpp
UTF-8
881
2.953125
3
[]
no_license
#include <problem.h> #ifdef _15650_ /// /// problem /// https://www.acmicpc.net/problem/15650 /// /// solution /// /// #include <iostream> #include <vector> #include <algorithm> #include <numeric> #include <cmath> using namespace std; void process(int maxIndex, int curIndex, int targetSize, vector<int>& curArr, vector<vector<int>>& ret) { if (curArr.size() == targetSize) { ret.push_back(curArr); return; } if (curArr.size() + maxIndex - (curIndex - 1) < targetSize) return; for (int i = curIndex; i <= maxIndex; i++) { curArr.push_back(i); process(maxIndex, i + 1, targetSize, curArr, ret); curArr.pop_back(); } return; } int main() { int n, m; cin >> n >> m; vector<vector<int>> answer; vector<int> temp; process(n, 1, m, temp, answer); for (auto v : answer) { for (auto i : v) cout << i << " "; cout << endl; } } #endif
true
27a5e65fd1c9be30a34fbc17c5413e61e3c4f171
C++
477918269/C-cpp
/3.28/3.28/template.h
WINDOWS-1252
226
2.71875
3
[]
no_license
#pragma once template<class T> T Add(const T& a, const T& b);//ʾʵ int add(int a, int b); template int Add<int>(const int& a, const int&b); template<class T> T Add(const T&a, const T&b) { return a + b; }
true
15f8949201887adb5545db5356dceb18c64008d0
C++
sahib-pratap-singh/Placement-Series
/SDE Problems/Day6/IntersectionofTwoLinkedLists.cpp
UTF-8
299
3
3
[]
no_license
class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { ListNode * d1 =headA; ListNode * d2 =headB; while(d1!=d2){ d1 = d1==NULL?headB:d1->next; d2 = d2==NULL?headA:d2->next; } return d1; } };
true
832d79bfefd1a32d7ef5e8d171b68dbc104d6a2f
C++
coding-blocks-archives/Launchpad-LIVE-June-2017
/Lecture-20 BSTs and Heaps/bsts.cpp
UTF-8
6,002
3.703125
4
[]
no_license
#include<bits/stdc++.h> using namespace std; class node{ public: int data; node*left; node*right; node(int d){ data = d; left = NULL; right = NULL; } }; ///Print the tree level by level void levelOrderPrint2(node*root){ queue<node*> q; q.push(root); q.push(NULL); while(!q.empty()){ node* f = q.front(); if(f==NULL){ q.pop(); cout<<endl; if(!q.empty()){ q.push(NULL); } } else{ q.pop(); cout<<f->data<<" "; if(f->left){ q.push(f->left); } if(f->right){ q.push(f->right); } } } } void printPreorder(node*root){ if(root==NULL){ return; } cout<<root->data<<" "; printPreorder(root->left); printPreorder(root->right); } void printInorder(node*root){ if(root==NULL){ return; } printInorder(root->left); cout<<root->data<<" "; printInorder(root->right); } void postOrder(node*root){ if(root==NULL){ return; } postOrder(root->left); postOrder(root->right); cout<<root->data<<" "; } /// Builds a BST node* insertInBST(node*root,int data){ if(root==NULL){ root = new node(data); return root; } ///Rec Case if(data <= root->data){ root->left = insertInBST(root->left,data); } else{ root->right = insertInBST(root->right,data); } return root; } void takeInput(node*&root){ int data; cin>>data; while(data!=-1){ root = insertInBST(root,data); cin>>data; } } ostream& operator<<(ostream&os, node*root){ levelOrderPrint2(root); return os; } istream& operator>>(istream&is, node*&root){ takeInput(root); return is; } ///Time Complexity of the search function bool search(node*root,int data){ if(root==NULL){ return false; } if(root->data==data){ return true; } if(root->data < data){ return search(root->right,data); } return search(root->left,data); } /// Pair class myPair{ public: int height; bool balance; }; myPair isBalanced(node*root){ myPair p; if(root==NULL){ p.height = 0; p.balance = true; return p; } myPair leftTree = isBalanced(root->left); myPair rightTree = isBalanced(root->right); int diff = abs(leftTree.height - rightTree.height); if(diff<=1 && leftTree.balance && rightTree.balance){ p.balance = true; } else{ p.balance = false; } p.height = max(leftTree.height,rightTree.height) + 1; return p; } /// Count BST - HW - Catalan Number int countBSTs(int n){ } ///Min Node node* minNode(node*root){ while(root->left!=NULL){ root = root->left; } return root; } /// Delete in BST node* deleteNode(node *root,int key){ if(root==NULL){ return NULL; } if(root->data == key){ ///Three cases 0 child, 1 child, 2 children if(root->left==NULL && root->right==NULL){ // cout<<"Here "<<endl; delete root; return NULL; } /// Single Child if(root->left==NULL && root->right!=NULL){ node*temp = root->right; delete root; return temp; } if(root->left!=NULL && root->right==NULL){ node* temp = root->left; delete root; return temp; } /// 2 children /// find min node in right subtree node* replaceMent = minNode(root->right); root->data = replaceMent->data; root->right = deleteNode(root->right,replaceMent->data); return root; } else if(root->data > key){ root->left = deleteNode(root->left,key); return root; } else{ root->right = deleteNode(root->right,key); return root; } } node* arrayToBST(int *a,int s,int e){ if(s>e){ return NULL; } int mid = (s+e)/2; node* root = new node(a[mid]); root->left = arrayToBST(a,s,mid-1); root->right = arrayToBST(a,mid+1,e); return root; } bool isBST(node*root,int minV=INT_MIN, int maxV = INT_MAX){ if(root==NULL){ return true; } if(root->data >= minV && root->data <maxV && isBST(root->left,minV,root->data) && isBST(root->right,root->data,maxV)){ return true; } return false; } class LinkedList{ public: node*head; node*tail; }; LinkedList tree2LL(node*root){ LinkedList l; if(root==NULL){ l.head = l.tail = NULL; return l; } else if(root->left==NULL && root->right==NULL){ l.head = root; l.tail = root; } else if(root->left!=NULL && root->right==NULL){ LinkedList leftLL = tree2LL(root->left); leftLL.tail->right = root; l.head = leftLL.head; l.tail = root; } else if(root->left==NULL && root->right!=NULL){ LinkedList rightLL = tree2LL(root->right); root->right = rightLL.head; l.head = root; l.tail = rightLL.tail; } else{ LinkedList leftLL = tree2LL(root->left); LinkedList rightLL = tree2LL(root->right); leftLL.tail->right = root; root->right = rightLL.head; l.head = leftLL.head; l.tail = rightLL.tail; } return l; } int main(){ node*root = NULL; int a[] = {1,2,4,5,6,8,9,10}; int n = sizeof(a)/sizeof(int); root = arrayToBST(a,0,n-1); if(isBST(root)){ cout<<"Yes its bst"<<endl; } else{ cout<<"not a bst"<<endl; } cout<<root<<endl; LinkedList l = tree2LL(root); node*temp = l.head; while(temp!=NULL){ cout<<temp->data<<"->"; temp = temp->right; } cout<<"NULL"<<endl; return 0; }
true
b485ad778f52130298c9a0c30b08692d07ca4abf
C++
pluto16/leetcode
/102 Binary Tree Level Order Traversal.cpp
UTF-8
1,242
2.984375
3
[]
no_license
#include <iostream> #include <algorithm> #include <math> #include <string> typedef struct TreeNode{ TreeNode* left; TreeNode* right; int value; TreeNode(int x, ){} }TreeNode; class soluton{ public: vector<vector<int> > levelOrder(TreeNode* pRoot){ vector<vector<int> > res; if(pRoot==NULL) return res; queue<TreeNode*> Q; Q.push(pRoot); int count = 0; int levCount =1; vector<int> levNodeValue ; while(!Q.empty()) { TreeNode *cur = Q.front(); levNodeValue.push_back(cur->value); Q.pop(); levCount--; if(cur->lef){ Q.push(cur->left); count++; } if(cur->right){ Q.push(cur->right); count++; } if(levCount==0) { res.push_back(levlevNodeValue); levCount = cout; count = 0; levlevNodeValue.clear(); } } return res; }; };
true
9c9405b20cdc1e4b6f57bf5369b21b58b68a7703
C++
andreasfertig/notebookcpp-tips-and-tricks-with-templates
/21.03-codeBloat1/main.cpp
UTF-8
551
3.234375
3
[ "MIT" ]
permissive
// Copyright (c) Andreas Fertig. // SPDX-License-Identifier: MIT #include <cstdio> int Open() { return 1; } void Close(int) {} void write(int, const char*, size_t) {} namespace details { void Write(const char* data, const size_t size) { const int fd = Open(); // do some additional things write(fd, data, size); Close(fd); } } // namespace details template<size_t N> void Write(const char (&data)[N]) { details::Write(data, N); } int main() { char buffer[10]{}; Write(buffer); char buffer2[20]{}; Write(buffer2); }
true
933ed012d5e5db14995ecc6b69e0dfd728a77d21
C++
adarsh1github1/Competetive-codeforces-codechef-
/solving sudoku (backtracking).cpp
UTF-8
2,515
3.28125
3
[]
no_license
#include<bits/stdc++.h> using namespace std; #define n 9 #define unassigned 0 // this function check if any cell left is unsassigned or not.... if unassigned left then row and col values are assigned bool finsunassigned(int sudoku[n][n],int& row, int& col){ for(row =0;row<n;row++){ for(col=0;col<n;col++) if(sudoku[row][col] == unassigned) return true; } return false; } // checks in row bool isinrow(int sudoku[n][n],int row,int num){ for(int j=0;j<n;j++){ if(sudoku[row][j] == num) return true; } return false; } // checks in column bool isincol(int sudoku[n][n],int col,int num){ for(int i=0;i<n;i++){ if(sudoku[i][col] == num) return true; } return false; } // checks in 3 x 3 box bool isinbox(int sudoku[n][n], int rowstart, int colstart,int num){ for(int row =0;row<3;row++){ for(int col =0;col<3;col++){ if(sudoku[rowstart+row][colstart+col] == num) return true; } } return false; } bool issafe(int sudoku[n][n], int row,int col,int num){ // checks if the num is present in any that row or col or in the corresponding 3 x 3 box return !isinrow(sudoku,row,num) && !isincol(sudoku,col,num) && !isinbox(sudoku,row - row % 3,col - col % 3,num) && sudoku[row][col] == unassigned; } bool solvesudoku(int sudoku[n][n]){ int row,col; if(!finsunassigned(sudoku,row,col)){ return true; // no unassigne cell is left.. we are done } // we have row and column values for(int num=1;num<=9;num++){ if(issafe(sudoku,row,col,num)) { sudoku[row][col] = num; if(solvesudoku(sudoku)) return true; // if control reaches here means the num value isnot safe at that position sudoku[row][col] = unassigned; } } return false; } void printsudoku(int sudoku[n][n]){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++) cout<<sudoku[i][j]<<" "; cout<<endl; } } int main(){ int t; cin>>t; while(t){ int sudoku[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++){ cin>>sudoku[i][j]; } } if(solvesudoku(sudoku)) printsudoku(sudoku); else cout<<"No solution exists"; t--; } return 0; }
true
30b717c7d830c7df8e100e0988b0af8c496a46de
C++
lanChe-4869/acm-templateCode
/费用流.cpp
UTF-8
1,129
2.78125
3
[]
no_license
const int N const int M const int inf=0x3f3f3f3f; int head[N],cnt; struct edge{ int to,cap,cost,next; edge(){} edge(int to,int cap,int cost,int next):to(to),cap(cap),cost(cost),next(next){} }e[M]; void add(int u,int v,int cap,int w){ e[cnt]=edge(v,cap,w,head[u]); head[u]=cnt++; e[cnt]=edge(u,0,-w,head[v]); head[v]=cnt++; } int n,m; bool vis[N]; int dis[N],pre[N]; bool spfa(int s,int t){ memset(vis,false,sizeof vis); memset(dis,inf,sizeof dis); memset(pre,-1,sizeof pre); queue<int>que; dis[s]=0; que.push(s); vis[s]=1; while(!que.empty()){ int u=que.front(); que.pop(); vis[u]=false; for(int i=head[u];~i;i=e[i].next){ int v=e[i].to; if(e[i].cap>0&&dis[v]>dis[u]+e[i].cost){ dis[v]=dis[u]+e[i].cost; pre[v]=i; if(!vis[v]){ vis[v]=1; que.push(v); } } } } return dis[t]!=inf; } int mincost(int s,int t){ int mincost=0; while(spfa(s,t)){ int tmp=inf; for(int v=t;v!=s;v=e[pre[v]^1].to){ tmp=min(tmp,e[pre[v]].cap); } for(int v=t;v!=s;v=e[pre[v]^1].to){ e[pre[v]].cap-=tmp; e[pre[v]^1].cap+=tmp; } mincost+=dis[t]*tmp; } return mincost; }
true
0eb4f45e86a74ba26fde29946e1a7b3c36fcf5eb
C++
mochang2/cpp-practice
/Kutzner_c++_ta10.cpp
UTF-8
1,433
3.1875
3
[]
no_license
#include <iostream> #include <cstring> //#define _CRT_SECURE_NO_WARNINGS using namespace std; //template<typename T> //T add(T a, T b) //{ // return a + b; //} //template<typename T, typename U> //T add(T a, U b) ////U add(T a, U b) //{ // return a + b; //} //template<typename T> //T add(T a, T b) //{ // return a + b; //} //template<> //char* add(char* a, char* b) //{ // char* addchar = new char[strlen(a) + strlen(b) + 2]; // strcpy_s(addchar, sizeof(a), a); // strcat_s(addchar, sizeof(b), b); // return addchar; // /*strcat_s(a, sizeof(b), b); // return a;*/ //} //void cpy(char* dest, size_t num, const char* src, size_t data) //{ // if (data > num) // return; // num = -1; // while (++num < data) // { // *dest = *src; // src++; // dest++; // } // *dest = '\0'; //} int main() { /*int a = 10, b = 20; int c = add(a, b); double d = 1.1, e = 2.2; double f = add(d, e); cout << c << " " << f << endl;*/ /*double d = add((double)35, 2.4); cout << d << endl; double e = add(35, 2.4); cout << e << endl; double f = add(2.4, 35); cout << f << endl; char g = add('a', 34); cout << g << endl;*/ /*char str1[10] = "h"; char str2[5] = "ello"; char* str3 = add(str1, str2); cout << str3 << endl;*/ /*char arr[20] = "ABCDEFG"; char arr1[20]; cpy(arr1, sizeof(arr1), arr, 5); cout << arr1 << endl;*/ return 0; }
true
da22820ee79c826c876e28cea5a46bde6c8e0530
C++
walkccc/LeetCode
/solutions/0359. Logger Rate Limiter/0359-2.cpp
UTF-8
274
2.609375
3
[ "MIT" ]
permissive
class Logger { public: bool shouldPrintMessage(int timestamp, string message) { if (timestamp < okTime[message]) return false; okTime[message] = timestamp + 10; return true; } private: unordered_map<string, int> okTime; // {message: ok time} };
true
07d07d1964f306696719fb754b45f070d2b64b5e
C++
tomaz-cvetko/game-of-life
/src/window.h
UTF-8
590
2.78125
3
[]
no_license
#ifndef WINDOW_HANDLER_H #define WINDOW_HANDLER_H class WindowHandler{ public: //Starts up SDL and creates window bool init(); //Loads media bool loadMedia(); //Frees media and shuts down SDL void close(); //Loads individual image as texture SDL_Texture* loadTexture( std::string path ); private: //Screen dimension constants const int SCREEN_WIDTH = 640; const int SCREEN_HEIGHT = 480; //The window we'll be rendering to SDL_Window* gWindow = NULL; //The window renderer SDL_Renderer* gRenderer = NULL; }; #endif
true
95717a837361d74e4ac66387b76922932c896377
C++
HafizMuhammad-Farooq786/Data-Structure-Algorithms-PUCIT
/UB/HW6/HW6/Source.cpp
MacCentralEurope
2,673
3.390625
3
[]
no_license
#include<iostream> #include<fstream> using namespace std; struct AccountRecord{ int recNum; //Record number int acctID; //Student identifier char firstName[10]; //First name char lastName[10]; //Last name char program[10]; //degree program of a student double cgpa; //Students CGPA }; struct IndexEntry{ int acctID; //(Key) Account identifier long recNum; //Record number //Return key field int getKey() const{ return acctID; } }; class BTNode{ public: IndexEntry data; BTNode * left, *right; BTNode(IndexEntry d){ this->data = d; left = right = NULL; } }; class BST{ BTNode * root; long recordNum; public: BST(){ root = NULL; recordNum = 0; } void insert(IndexEntry ele){ ele.recNum = recordNum; root = insert(ele, root); recordNum++; } BTNode* insert(IndexEntry ele, BTNode* temp){ if (temp == NULL) temp = new BTNode(ele); else if (temp->data.acctID > ele.acctID) temp->left = insert(ele, temp->left); else if (temp->data.acctID < ele.acctID) temp->right = insert(ele, temp->right); return temp; } int retrieve(int accountID){ if (root != NULL){ return retrieve(accountID, root); } else return -99; } int retrieve(int accountID, BTNode* temp){ if (temp == NULL) return -99; if (temp->data.acctID == accountID) return temp->data.recNum; else if (temp->data.acctID > accountID) return retrieve(accountID, temp->left); else return retrieve(accountID, temp->right); } void show()const{ show(root); } void show(BTNode* temp)const{ if ( temp ){ show(temp->right); cout << temp->data.acctID <<endl; show(temp->left); } } }; AccountRecord searchFile(int recordNo){ AccountRecord student; fstream file; file.open("records.dat", ios::in | ios::binary); while (!file.eof()){ file.read(reinterpret_cast<char *>(&student), sizeof(student)); if (recordNo == student.recNum){ file.close(); return student; } } file.close(); } int main(){ BST t; AccountRecord student; fstream file; IndexEntry ie; int id, recordNo; file.open("records.dat", ios::in | ios::binary); while (!file.eof()){ file.read(reinterpret_cast<char *>(&student), sizeof(student)); ie.acctID = student.acctID; t.insert(ie); } file.close(); t.show(); cout << "Enter ID to search: "; cin >> id; recordNo = t.retrieve(id); if (recordNo == -99) cout << "NO RECORDS Found....\n"; else{ student = searchFile(recordNo); cout << "ID: " << student.acctID << endl; cout << "Name: " << student.firstName << " " << student.lastName << endl; cout << "Program: " << student.program << endl; cout << "CGPA: " << student.cgpa << endl; } return 0; }
true
dd47246b3a3e445afd080b35d19ab6df1f60254b
C++
lumt/cpp_intro
/exam/sonnet/sonnet.cpp
UTF-8
5,201
3.4375
3
[]
no_license
#include <iostream> #include <cstring> #include <cctype> #include <cassert> #include <map> #include <string> #include <fstream> using namespace std; #include "sonnet.h" /* PRE-SUPPLIED HELPER FUNCTIONS START HERE */ /* NOTE: It is much more important to understand the interface to and the "black-box" operation of these functions (in terms of inputs and outputs) than it is to understand the details of their inner working. */ /* get_word(...) retrieves a word from the input string input_line based on its word number. If the word number is valid, the function places an uppercase version of the word in the output parameter output_word, and the function returns true. Otherwise the function returns false. */ bool get_word(const char *input_line, int word_number, char *output_word) { char *output_start = output_word; int words = 0; if (word_number < 1) { *output_word = '\0'; return false; } do { while (*input_line && !isalnum(*input_line)) input_line++; if (*input_line == '\0') break; output_word = output_start; while (*input_line && (isalnum(*input_line) || *input_line=='\'')) { *output_word = toupper(*input_line); output_word++; input_line++; } *output_word = '\0'; if (++words == word_number) return true; } while (*input_line); *output_start = '\0'; return false; } /* char rhyming_letter(const char *ending) generates the rhyme scheme letter (starting with 'a') that corresponds to a given line ending (specified as the parameter). The function remembers its state between calls using an internal lookup table, such that subsequents calls with different endings will generate new letters. The state can be reset (e.g. to start issuing rhyme scheme letters for a new poem) by calling rhyming_letter(RESET). */ char rhyming_letter(const char *ending) { // the next rhyming letter to be issued (persists between calls) static char next = 'a'; // the table which maps endings to letters (persists between calls) static map<string, char> lookup; // providing a way to reset the table between poems if (ending == RESET) { lookup.clear(); next = 'a'; return '\0'; } string end(ending); // if the ending doesn't exist, add it, and issue a new letter if (lookup.count(end) == 0) { lookup[end]=next; assert(next <= 'z'); return next++; } // otherwise return the letter corresponding to the existing ending return lookup[end]; } /* START WRITING YOUR FUNCTION BODIES HERE */ // function to count words given in string line int count_words(const char* line) { int count = 1; char wordbuffer[100]; while(get_word(line, count, wordbuffer)) count++; return count - 1; } // function to find phonetic ending and puts in 'ending' // constructed by concatenating last phoneme of the word // which contains a vowel bool find_phonetic_ending(const char *word, char *ending) { ifstream in("dictionary.txt"); if (!in) { cerr << "dictionary.txt failed to load" << endl; return false; } // assumes length of line and wordbuffer char line[200], wordbuffer[50]; // uses linear search so may take some time while(in.getline(line, 200)) { // gets first word in line and store in wordbuffer get_word(line, 1, wordbuffer); // compare buffer to word if (!strcmp(wordbuffer, word)) { // count words given in string line int linecount = count_words(line); // find first phoneme of word starting with vowel int idx = linecount; while(get_word(line, idx, wordbuffer)) { if (isVowel(wordbuffer[0])) { strcpy(ending, wordbuffer); idx++; // concat the rest while(get_word(line, idx, wordbuffer)) { strcat(ending, wordbuffer); idx++; } break; } else { idx--; } } break; } } in.close(); return false; } // helper function to check if character is a vowel bool isVowel(char ch) { ch = tolower(ch); switch(ch) { case 'a': case 'e': case 'i': case 'o': case 'u': return true; default: return false; } } // function to find rhyme scheme of given sonnet bool find_rhyme_scheme(const char* filename, char* scheme) { ifstream in(filename); if (!in) { cerr << filename << " could not be opened" << endl; return false; } char line[200], word[50], ending[20], letter[2]; letter[1] = '\0'; int linecount; // reset rhyme sceme rhyming_letter(RESET); strcpy(scheme, "\0"); while(in.getline(line, 200)) { // get last word and get ending linecount = count_words(line); get_word(line, linecount, word); find_phonetic_ending(word, ending); letter[0] = rhyming_letter(ending); strcat(scheme, letter); } in.close(); if (scheme) return true; return false; } // function to identify type of sonnet by comparing schemes char* identify_sonnet(const char* filename) { char* type = new char[20]; char scheme[20]; strcpy(type, "Unknown"); if (find_rhyme_scheme(filename, scheme)) { if (strcmp(scheme, "ababcdcdefefgg") == 0) strcpy(type, "Shakespearean"); if (strcmp(scheme, "abbaabbacdcdcd") == 0) strcpy(type, "Petrarchan"); if (strcmp(scheme, "ababbcbccdcdee") == 0) strcpy(type, "Spenserian"); return type; } return type; }
true
615c7908d56944f315af29fb512f3df1ea23eb46
C++
jeremimucha/Project-Stubs
/C++/large_test/src/toplevel.cpp
UTF-8
297
2.78125
3
[]
no_license
#include <iostream> #include "toplevel.hpp" auto toplevel_function( gsl::span<int> ints ) noexcept -> void { auto first = true; for( auto i : ints ){ if( !first ){ std::cout << ", "; first = false; } std::cout << i; } }
true
e3f630a883aab29fc806937b5e0e54a2d529c282
C++
webturing/ACM-1
/按 OJ 分类/出处遗忘/f-乐视2017实习-兵临城下/f-乐视2017实习-兵临城下/main.cpp
UTF-8
872
2.546875
3
[]
no_license
// // main.cpp // f-乐视2017实习-兵临城下 // // Created by ZYJ on 2018/3/23. // Copyright © 2018年 ZYJ. All rights reserved. // #include <iostream> #include <cstring> #include <cstdio> using namespace std; const int MAXN = 6; int n, ans; string s[MAXN]; int vis[MAXN]; void dfs(int p) { if (p == n) { ans++; return ; } for (int i = 0; i < s[p].length(); i++) { if (vis[s[p][i] - '0'] == 0) { vis[s[p][i] - '0'] = 1; dfs(p + 1); vis[s[p][i] - '0'] = 0; } } } int main(int argc, const char * argv[]) { while (cin >> n) { ans = 0; memset(vis, 0, sizeof(vis)); for (int i = 0; i < n; i++) { cin >> s[i]; } dfs(0); cout << ans << endl; } return 0; }
true
d485acac333d3d3076cc48152e391965b6f1d3e9
C++
odeded/acRemoteControl
/src/Electra-AC-Remote-Encoder/electraAcRemoteEncoder.cpp
UTF-8
4,354
2.65625
3
[]
no_license
#include "electraAcRemoteEncoder.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> void initializeStruct (struct airCon* newAcPointer) { int i = 0; newAcPointer->fullState = FULL_STATE_MASK; newAcPointer->fan = FAN_MASK; newAcPointer->mode = MODE_MASK; newAcPointer->temp = TEMP_MASK; newAcPointer->swing = SWING_MASK; for (i = 0;i < TIMINGS_LENGTH;i++){ (newAcPointer->manchesterTimings)[i] = 0; } } void updateFan (int value,struct airCon* newAcPointer) { newAcPointer->fan &= (value-1); newAcPointer->fan = (newAcPointer->fan) << 28; newAcPointer->fullState |= newAcPointer->fan; } void updateMode (int value,struct airCon* newAcPointer) { newAcPointer->mode &= (value); newAcPointer->mode = (newAcPointer->mode) << 30; newAcPointer->fullState |= newAcPointer->mode; } void updateTemperature (int value,struct airCon* newAcPointer) { newAcPointer->temp &= (value-15); newAcPointer->temp = (newAcPointer->temp) << 19; newAcPointer->fullState |= newAcPointer->temp; } void updateSwing (int value,struct airCon* newAcPointer) { newAcPointer->swing &= (value); newAcPointer->swing = (newAcPointer->swing) << 25; newAcPointer->fullState |= newAcPointer->swing; } void updateParameter (acParameter parameter,int value,struct airCon* newAcPointer) { switch (parameter) { case fan: updateFan(value,newAcPointer); break; case mode: updateMode(value,newAcPointer); break; case temp: updateTemperature(value,newAcPointer); break; case swing: updateSwing(value,newAcPointer); break; } } void convertStateToBitStrings (struct airCon* newAcPointer) { int i = 0; uint64_t toggleMask = 1,fullStateCopy; fullStateCopy = newAcPointer->fullState; for (i = DATA_BITS_LENGTH-1;i >= 0;i--){ sprintf((newAcPointer->bitStrings)[i],"%d",fullStateCopy & toggleMask); fullStateCopy = fullStateCopy >> 1; } } void convertBitStringsToManchesterString (struct airCon* newAcPointer) { int i = 0; for (i = 0;i < DATA_BITS_LENGTH;i++){ if ((newAcPointer->bitStrings)[i][0] == '0'){ strcpy((newAcPointer->manchesterString) + 2*i,"01"); } else{ strcpy((newAcPointer->manchesterString) + 2*i,"10"); } } } void convertManchesterStringToManchesterTimings (struct airCon* newAcPointer) { int stringPointer = 0; int timingPointer = 0; int counter = 0; int i = 0; (newAcPointer->manchesterTimings)[timingPointer] = 3000; timingPointer++; if ((newAcPointer->manchesterString)[0] == '1'){ (newAcPointer->manchesterTimings)[timingPointer] = 4000; stringPointer++; } else{ (newAcPointer->manchesterTimings)[timingPointer] = 3000; } timingPointer++; for (stringPointer;stringPointer < DATA_BITS_LENGTH*2;stringPointer++){ while ((newAcPointer->manchesterString)[stringPointer] == '0'){ counter++; stringPointer++; } (newAcPointer->manchesterTimings)[timingPointer] = 1000*counter; counter = 0; timingPointer++; while ((newAcPointer->manchesterString)[stringPointer] == '1'){ counter++; stringPointer++; } (newAcPointer->manchesterTimings)[timingPointer] = 1000*counter; counter = 0; timingPointer++; stringPointer--; } (newAcPointer->manchesterTimings)[3*timingPointer] = 4000; for (i=0;i<timingPointer;i++){ (newAcPointer->manchesterTimings)[i+timingPointer] = (newAcPointer->manchesterTimings)[i]; (newAcPointer->manchesterTimings)[i+timingPointer*2] = (newAcPointer->manchesterTimings)[i]; } } int *getCodes (struct airCon* newAc,int fanV,int modeV,int tempV,int state,int swingV) { initializeStruct(newAc); updateParameter(fan,fanV,newAc); updateParameter(temp,tempV,newAc); updateParameter(mode,modeV,newAc); updateParameter(swing,swingV,newAc); convertStateToBitStrings(newAc); if (state == ON){ (newAc->bitStrings)[0][0] = '0'; } convertBitStringsToManchesterString(newAc); convertManchesterStringToManchesterTimings(newAc); return newAc->manchesterTimings; }
true
d00f8c40290ca07c5c5aad544ab8714411d6d4d7
C++
osdbms/vanakkam
/execsyscall.cpp
UTF-8
785
3.140625
3
[]
no_license
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> void main() { int choice; do { printf("select the option\n"); printf("1.Execute ls command \n"); printf("2.Execute pwd command \n"); printf("3.Execute whoami command \n"); printf("4.Sleep\n"); printf("0.exit"); printf("your choice: "); scanf("%d",&choice); switch(choice) { case 1: if (fork()) wait(0); else execlp("ls","ls",(char *)NULL); break; case 2: if (fork()) wait(0); else execlp ("pwd","pwd",(char *)NULL); case 3: if (fork()) wait(0); else execlp ("whoami","whoami",(char *)NULL); break; case 4: sleep(1); break; case 0: exit(0); break; default: printf("please enter only between 0 and 3\n"); } } while (choice != 0); }
true
f0dcf60ce26defb9ccd81f74e6cc045ed7e9832a
C++
nannancy/hyrise
/src/lib/operators/join_hash/join_hash_steps.hpp
UTF-8
43,432
2.578125
3
[ "MIT" ]
permissive
#pragma once #include <boost/container/small_vector.hpp> #include <boost/lexical_cast.hpp> #include <uninitialized_vector.hpp> #include "bytell_hash_map.hpp" #include "hyrise.hpp" #include "operators/multi_predicate_join/multi_predicate_join_evaluator.hpp" #include "resolve_type.hpp" #include "scheduler/abstract_task.hpp" #include "scheduler/job_task.hpp" #include "storage/create_iterable_from_segment.hpp" #include "storage/segment_iterate.hpp" #include "type_comparison.hpp" /* This file includes the functions that cover the main steps of our hash join implementation (e.g., build() and probe()). These free functions are put into this header file to separate them from the process flow of the join hash and to make the better testable. */ namespace opossum { // For semi and anti joins, we only care whether a value exists or not, so there is no point in tracking the position // in the input table of more than one occurrence of a value. However, if we have secondary predicates, we do need to // track all occurrences of a value as that first position might be disqualified later. enum class JoinHashBuildMode { AllPositions, SinglePosition }; using Hash = size_t; /* This is how elements of the input relations are saved after materialization. The original value is used to detect hash collisions. */ template <typename T> struct PartitionedElement { RowID row_id; T value; }; // Initializing the partition vector takes some time. This is not necessary, because it will be overwritten anyway. // The uninitialized_vector behaves like a regular std::vector, but the entries are initially invalid. template <typename T> using Partition = std::conditional_t<std::is_trivially_destructible_v<T>, uninitialized_vector<PartitionedElement<T>>, std::vector<PartitionedElement<T>>>; // Stores the mapping from HashedType to positions. Conceptually, this is similar to an (unordered_)multimap, but it // has some optimizations for the performance-critical probe() method. Instead of storing the matches directly in the // hashmap (think map<HashedType, PosList>), we store an offset. This keeps the hashmap small and makes it easier to // cache. template <typename HashedType> class PosHashTable { // In case we consider runtime to be more relevant, the flat hash map performs better (measured to be mostly on par // with bytell hash map and in some cases up to 5% faster) but is significantly larger than the bytell hash map. // // The hash table stores the relative offset of a SmallPosList (see below) in the vector of SmallPosLists. The range // of the offset does not limit the number of rows in the partition but the number of distinct values. If we end up // with a partition that has more values, the partitioning algorithm is at fault. using Offset = uint32_t; using HashTable = ska::bytell_hash_map<HashedType, Offset>; // The small_vector holds the first n values in local storage and only resorts to heap storage after that. 1 is chosen // as n because in many cases, we join on primary key attributes where by definition we have only one match on the // smaller side. using SmallPosList = boost::container::small_vector<RowID, 1>; public: explicit PosHashTable(const JoinHashBuildMode mode, const size_t max_size) : _hash_table(), _pos_lists(max_size), _mode(mode) { _hash_table.reserve(max_size); } // For a value seen on the build side, add its row_id to the table template <typename InputType> void emplace(const InputType& value, RowID row_id) { const auto casted_value = static_cast<HashedType>(value); const auto it = _hash_table.find(casted_value); if (it != _hash_table.end()) { if (_mode == JoinHashBuildMode::AllPositions) { auto& pos_list = _pos_lists[it->second]; pos_list.emplace_back(row_id); } } else { DebugAssert(_hash_table.size() < _pos_lists.size(), "Hash table too big for pre-allocated data structures"); auto& pos_list = _pos_lists[_hash_table.size()]; pos_list.push_back(row_id); _hash_table.emplace(casted_value, _hash_table.size()); DebugAssert(_hash_table.size() < std::numeric_limits<Offset>::max(), "Hash table too big for offset"); } } void shrink_to_fit() { _pos_lists.resize(_hash_table.size()); _pos_lists.shrink_to_fit(); for (auto& pos_list : _pos_lists) { pos_list.shrink_to_fit(); } // For very small hash tables, a linear search performs better. In that case, replace the hash table with a vector // of value/offset pairs. The boundary was determined experimentally and chosen conservatively. if (_hash_table.size() <= 10) { _values = std::vector<std::pair<HashedType, Offset>>{}; _values->reserve(_hash_table.size()); for (const auto& [value, offset] : _hash_table) { _values->emplace_back(std::pair<HashedType, Offset>{value, offset}); } _hash_table.clear(); } else { _hash_table.shrink_to_fit(); } } // For a value seen on the probe side, return an iterator into the matching positions on the build side template <typename InputType> const std::vector<SmallPosList>::const_iterator find(const InputType& value) const { const auto casted_value = static_cast<HashedType>(value); if (!_values) { const auto hash_table_iter = _hash_table.find(casted_value); if (hash_table_iter == _hash_table.end()) return end(); return _pos_lists.begin() + hash_table_iter->second; } else { const auto values_iter = std::find_if(_values->begin(), _values->end(), [&](const auto& pair) { return pair.first == casted_value; }); if (values_iter == _values->end()) return end(); return _pos_lists.begin() + values_iter->second; } } // For a value seen on the probe side, return whether it has been seen on the build side template <typename InputType> bool contains(const InputType& value) const { const auto casted_value = static_cast<HashedType>(value); if (!_values) { return _hash_table.find(casted_value) != _hash_table.end(); } else { const auto values_iter = std::find_if(_values->begin(), _values->end(), [&](const auto& pair) { return pair.first == casted_value; }); return values_iter != _values->end(); } } const std::vector<SmallPosList>::const_iterator begin() const { return _pos_lists.begin(); } const std::vector<SmallPosList>::const_iterator end() const { return _pos_lists.end(); } private: HashTable _hash_table; std::vector<SmallPosList> _pos_lists; JoinHashBuildMode _mode; std::optional<std::vector<std::pair<HashedType, Offset>>> _values{std::nullopt}; }; /* This struct contains radix-partitioned data in a contiguous buffer, as well as a list of offsets for each partition. The offsets denote the accumulated sizes (we cannot use the last element's position because we could not recognize empty first containers). This struct is used in two phases: - the result of the materialization phase, at this time partitioned by chunks as we parallelize the materialization phase via chunks - the result of the radix clustering phase As the radix clustering might be skipped (when radix_bits == 0), both the materialization as well as the radix clustering methods yield RadixContainers. */ template <typename T> struct RadixContainer { std::shared_ptr<Partition<T>> elements; std::vector<size_t> partition_offsets; // bit vector to store NULL flags std::shared_ptr<std::vector<bool>> null_value_bitvector; void clear() { elements = nullptr; partition_offsets.clear(); partition_offsets.shrink_to_fit(); null_value_bitvector = nullptr; } }; inline std::vector<size_t> determine_chunk_offsets(const std::shared_ptr<const Table>& table) { const auto chunk_count = table->chunk_count(); auto chunk_offsets = std::vector<size_t>(chunk_count); size_t offset = 0; for (ChunkID chunk_id{0}; chunk_id < chunk_count; ++chunk_id) { chunk_offsets[chunk_id] = offset; const auto chunk = table->get_chunk(chunk_id); Assert(chunk, "Physically deleted chunk should not reach this point, see get_chunk / #1686."); offset += chunk->size(); } return chunk_offsets; } template <typename T, typename HashedType, bool retain_null_values> RadixContainer<T> materialize_input(const std::shared_ptr<const Table>& in_table, ColumnID column_id, const std::vector<size_t>& chunk_offsets, std::vector<std::vector<size_t>>& histograms, const size_t radix_bits) { // Retrieve input row_count as it might change during execution if we work on a non-reference table auto row_count = in_table->row_count(); // Do not use in_table->chunk_count() as that might have increased since chunk_offsets was built auto chunk_count = chunk_offsets.size(); const std::hash<HashedType> hash_function; // list of all elements that will be partitioned auto elements = std::make_shared<Partition<T>>(row_count); [[maybe_unused]] auto null_value_bitvector = std::make_shared<std::vector<bool>>(); if constexpr (retain_null_values) { null_value_bitvector->resize(row_count); } // fan-out const size_t num_partitions = 1ull << radix_bits; // currently, we just do one pass size_t pass = 0; size_t mask = static_cast<uint32_t>(pow(2, radix_bits * (pass + 1)) - 1); // create histograms per chunk histograms.resize(chunk_count); std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(chunk_count); for (ChunkID chunk_id{0}; chunk_id < chunk_count; ++chunk_id) { if (!in_table->get_chunk(chunk_id)) continue; jobs.emplace_back(std::make_shared<JobTask>([&, in_table, chunk_id]() { const auto chunk_in = in_table->get_chunk(chunk_id); if (!chunk_in) return; // Get information from work queue auto output_offset = chunk_offsets[chunk_id]; auto output_iterator = elements->begin() + output_offset; auto segment = chunk_in->get_segment(column_id); [[maybe_unused]] auto null_value_bitvector_iterator = null_value_bitvector->begin(); if constexpr (retain_null_values) { null_value_bitvector_iterator += output_offset; } // prepare histogram auto histogram = std::vector<size_t>(num_partitions); auto reference_chunk_offset = ChunkOffset{0}; segment_with_iterators<T>(*segment, [&](auto it, const auto end) { using IterableType = typename decltype(it)::IterableType; if (radix_bits == 0) { // If we do not use partitioning, we will not increment the histogram counter in the loop, so we do it here. histogram[0] = std::distance(it, end); } while (it != end) { const auto& value = *it; ++it; if (!value.is_null() || retain_null_values) { /* For ReferenceSegments we do not use the RowIDs from the referenced tables. Instead, we use the index in the ReferenceSegment itself. This way we can later correctly dereference values from different inputs (important for Multi Joins). */ if constexpr (is_reference_segment_iterable_v<IterableType>) { *(output_iterator++) = PartitionedElement<T>{RowID{chunk_id, reference_chunk_offset}, value.value()}; } else { *(output_iterator++) = PartitionedElement<T>{RowID{chunk_id, value.chunk_offset()}, value.value()}; } // In case we care about NULL values, store the NULL flag if constexpr (retain_null_values) { if (value.is_null()) { *null_value_bitvector_iterator = true; } ++null_value_bitvector_iterator; } if (radix_bits > 0) { // TODO(anyone): static_cast is almost always safe, since HashType is big enough. Only for double-vs-long // joins an information loss is possible when joining with longs that cannot be losslessly converted to // double const Hash hashed_value = hash_function(static_cast<HashedType>(value.value())); const Hash radix = hashed_value & mask; ++histogram[radix]; } if (output_iterator == elements->end() && it != end) { // The last chunk has changed its size since we allocated elements. This is due to a concurrent insert // into that chunk. In any case, those inserts will not be visible to our current transaction, so we can // ignore them. Assert(in_table->row_count() > row_count, "Iterator out-of-bounds but table size has not changed"); break; } } // reference_chunk_offset is only used for ReferenceSegments if constexpr (is_reference_segment_iterable_v<IterableType>) { ++reference_chunk_offset; } } }); if constexpr (std::is_same_v<Partition<T>, uninitialized_vector<PartitionedElement<T>>>) { // NOLINT // Because the vector is uninitialized, we need to manually fill up all slots that we did not use because the // input values were NULL. Assert(output_iterator <= elements->end(), "output_iterator has written past the end"); auto output_offset_end = chunk_id < chunk_offsets.size() - 1 ? chunk_offsets[chunk_id + 1] : elements->size(); Assert(elements->begin() + output_offset_end <= elements->end(), "Corrupt pointer calculation"); while (output_iterator != elements->begin() + output_offset_end) { *(output_iterator++) = PartitionedElement<T>{}; } } histograms[chunk_id] = std::move(histogram); })); jobs.back()->schedule(); } Hyrise::get().scheduler()->wait_for_tasks(jobs); return RadixContainer<T>{elements, std::vector<size_t>{elements->size()}, null_value_bitvector}; } /* Build all the hash tables for the partitions of the build column. One job per partition */ template <typename BuildColumnType, typename HashedType> std::vector<std::optional<PosHashTable<HashedType>>> build(const RadixContainer<BuildColumnType>& radix_container, JoinHashBuildMode mode) { /* NUMA notes: The hash tables for each partition P should also reside on the same node as the two vectors buildP and probeP. */ std::vector<std::optional<PosHashTable<HashedType>>> hash_tables; hash_tables.resize(radix_container.partition_offsets.size()); std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(radix_container.partition_offsets.size()); for (size_t current_partition_id = 0; current_partition_id < radix_container.partition_offsets.size(); ++current_partition_id) { const auto build_partition_begin = current_partition_id == 0 ? 0 : radix_container.partition_offsets[current_partition_id - 1]; const auto build_partition_end = radix_container.partition_offsets[current_partition_id]; // make end non-inclusive const auto build_partition_size = build_partition_end - build_partition_begin; // Skip empty partitions, so that we don't have too many empty hash tables if (build_partition_size == 0) { continue; } jobs.emplace_back(std::make_shared<JobTask>( [&, build_partition_begin, build_partition_end, current_partition_id, build_partition_size]() { auto& build_partition = static_cast<Partition<BuildColumnType>&>(*radix_container.elements); auto hash_table = PosHashTable<HashedType>(mode, static_cast<size_t>(build_partition_size)); for (size_t partition_offset = build_partition_begin; partition_offset < build_partition_end; ++partition_offset) { auto& element = build_partition[partition_offset]; if (element.row_id == NULL_ROW_ID) { // Skip initialized PartitionedElements that might remain after materialization phase. continue; } hash_table.emplace(element.value, element.row_id); } hash_table.shrink_to_fit(); hash_tables[current_partition_id] = std::move(hash_table); })); jobs.back()->schedule(); } Hyrise::get().scheduler()->wait_for_tasks(jobs); return hash_tables; } template <typename T, typename HashedType, bool retain_null_values> RadixContainer<T> partition_radix_parallel(const RadixContainer<T>& radix_container, const std::vector<size_t>& chunk_offsets, std::vector<std::vector<size_t>>& histograms, const size_t radix_bits) { if constexpr (retain_null_values) { DebugAssert(radix_container.null_value_bitvector->size() == radix_container.elements->size(), "partition_radix_parallel() called with NULL consideration but radix container does not store any NULL " "value information"); } const std::hash<HashedType> hash_function; // materialized items of radix container const auto& container_elements = *radix_container.elements; [[maybe_unused]] const auto& null_value_bitvector = *radix_container.null_value_bitvector; // fan-out const size_t num_partitions = 1ull << radix_bits; // currently, we just do one pass size_t pass = 0; size_t mask = static_cast<uint32_t>(pow(2, radix_bits * (pass + 1)) - 1); // allocate new (shared) output auto output = std::make_shared<Partition<T>>(); output->resize(container_elements.size()); [[maybe_unused]] auto output_nulls = std::make_shared<std::vector<bool>>(); if constexpr (retain_null_values) { output_nulls->resize(null_value_bitvector.size()); } RadixContainer<T> radix_output; radix_output.elements = output; radix_output.partition_offsets.resize(num_partitions); radix_output.null_value_bitvector = output_nulls; /** * The following steps create the offsets that allow each concurrent job to write lock-less into the newly * created RadixContainer. The input RadixContainer is a list of materialized values in order of the input table. * The output of `partition_radix_parallel()` is single consecutive vector and its values are sorted by radix * clusters (which are defined by the offsets). * Input: * - `histograms` stores for each input chunk a histogram that counts the number of values per radix cluster. * - `chunk_offsets` stores the offsets -- denoting the number of elements of each chunk -- in the continuous * vector of materialized values. * * The process of creating the offset information consists of three steps. A previous commit used a single * loop and created multiple vectors. This approach has shown to be inefficient for very large inputs. * Consequently, we now use a large single vector and operate fully sequentially. This come at the cost of * iterating twice and introduces additional steps. However, the current approach should be faster. * * Simple example: * - histograms for chunks 0 and 1 [4 0 3] & [5 2 7] (i.e., first radix cluster has 4 + 5 values) * - first step: create offsets that denote write offsets per radix cluster and collect lengths * - result: offsets vectors are [0 0 0] [4 0 3] and lengths are [9 2 10] * - second step: create prefix sum vector of [9 2 10] >> [9 11 21] * - third step: adapt offset vectors to create the offsets that allow writing * all threads in parallel into a _single_ vector * - result: [0 9 11] [4 9 14] * - note: the third step would be superfluous when each radix cluster is written to a separate vector */ std::vector<size_t> output_offsets_by_chunk(chunk_offsets.size() * num_partitions); // Offset vector creation: first step auto prefix_sums = std::vector<size_t>(num_partitions); // stores the prefix sums for (auto chunk_id = ChunkID{0}; chunk_id < chunk_offsets.size(); ++chunk_id) { for (auto radix_cluster_id = size_t{0}; radix_cluster_id < num_partitions; ++radix_cluster_id) { const auto radix_cluster_size = histograms[chunk_id][radix_cluster_id]; output_offsets_by_chunk[chunk_id * num_partitions + radix_cluster_id] = prefix_sums[radix_cluster_id]; prefix_sums[radix_cluster_id] += radix_cluster_size; } } // Offset vector creation: second step for (auto position = size_t{1}; position < prefix_sums.size(); ++position) { prefix_sums[position] += prefix_sums[position - 1]; } // Offset vector creation: third step for (auto chunk_id = ChunkID{0}; chunk_id < chunk_offsets.size(); ++chunk_id) { // Skip the first item of the loop for (auto radix_cluster_id = size_t{1}; radix_cluster_id < num_partitions; ++radix_cluster_id) { const auto write_position = chunk_id * num_partitions + radix_cluster_id; output_offsets_by_chunk[write_position] += prefix_sums[radix_cluster_id - 1]; // In the last iteration, the offsets are written to the radix container. // Note: these offsets denote _the last element's ID_ per cluster if (chunk_id == (chunk_offsets.size() - 1)) { radix_output.partition_offsets[radix_cluster_id] = prefix_sums[radix_cluster_id]; } } } std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(chunk_offsets.size()); for (ChunkID chunk_id{0}; chunk_id < chunk_offsets.size(); ++chunk_id) { jobs.emplace_back(std::make_shared<JobTask>([&, chunk_id]() { const auto iter_output_offsets_start = output_offsets_by_chunk.begin() + chunk_id * num_partitions; const auto iter_output_offsets_end = iter_output_offsets_start + num_partitions; // Obtain modifiable offset vector used to store insert positions auto output_offsets = std::vector<size_t>(iter_output_offsets_start, iter_output_offsets_end); const size_t input_offset = chunk_offsets[chunk_id]; size_t input_size = container_elements.size() - input_offset; if (chunk_id < chunk_offsets.size() - 1) { input_size = chunk_offsets[chunk_id + 1] - input_offset; } for (size_t chunk_offset = input_offset; chunk_offset < input_offset + input_size; ++chunk_offset) { const auto& element = container_elements[chunk_offset]; // In case of NULL-removing inner-joins, we ignore all NULL values. // Such values can be created in several ways: join input already has non-phyiscal NULL values (non-physical // means no RowID, e.g., created during an OUTER join), a physical value is NULL but is ignored for an inner // join (hence, we overwrite the RowID with NULL_ROW_ID), or it is simply a remainder of the pre-sized // RadixPartition which is initialized with default values (i.e., NULL_ROW_IDs). if (!retain_null_values && element.row_id == NULL_ROW_ID) { continue; } const size_t radix = hash_function(static_cast<HashedType>(element.value)) & mask; // In case NULL values have been materialized in materialize_input(), // we need to keep them during the radix clustering phase. if constexpr (retain_null_values) { (*output_nulls)[output_offsets[radix]] = null_value_bitvector[chunk_offset]; } (*output)[output_offsets[radix]] = element; ++output_offsets[radix]; } })); jobs.back()->schedule(); } Hyrise::get().scheduler()->wait_for_tasks(jobs); return radix_output; } /* In the probe phase we take all partitions from the probe partition, iterate over them and compare each join candidate with the values in the hash table. Since build and probe are hashed using the same hash function, we can reduce the number of hash tables that need to be looked into to just 1. */ template <typename ProbeColumnType, typename HashedType, bool keep_null_values> void probe(const RadixContainer<ProbeColumnType>& probe_radix_container, const std::vector<std::optional<PosHashTable<HashedType>>>& hash_tables, std::vector<PosList>& pos_lists_build_side, std::vector<PosList>& pos_lists_probe_side, const JoinMode mode, const Table& build_table, const Table& probe_table, const std::vector<OperatorJoinPredicate>& secondary_join_predicates) { std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(probe_radix_container.partition_offsets.size()); /* NUMA notes: At this point both input relations are partitioned using radix partitioning. Probing will be done per partition for both sides. Therefore, inputs for one partition should be located on the same NUMA node, and the job that probes that partition should also be on that NUMA node. */ for (size_t current_partition_id = 0; current_partition_id < probe_radix_container.partition_offsets.size(); ++current_partition_id) { const auto partition_begin = current_partition_id == 0 ? 0 : probe_radix_container.partition_offsets[current_partition_id - 1]; const auto partition_end = probe_radix_container.partition_offsets[current_partition_id]; // make end non-inclusive // Skip empty partitions to avoid empty output chunks if (partition_begin == partition_end) { continue; } jobs.emplace_back(std::make_shared<JobTask>([&, partition_begin, partition_end, current_partition_id]() { // Get information from work queue auto& partition = static_cast<Partition<ProbeColumnType>&>(*probe_radix_container.elements); PosList pos_list_build_side_local; PosList pos_list_probe_local; if constexpr (keep_null_values) { DebugAssert( probe_radix_container.null_value_bitvector->size() == probe_radix_container.elements->size(), "Hash join probe called with NULL consideration but inputs do not store any NULL value information"); } if (hash_tables[current_partition_id]) { const auto& hash_table = hash_tables.at(current_partition_id).value(); // Accessors are not thread-safe, so we create one evaluator per job std::optional<MultiPredicateJoinEvaluator> multi_predicate_join_evaluator; if (!secondary_join_predicates.empty()) { multi_predicate_join_evaluator.emplace(build_table, probe_table, mode, secondary_join_predicates); } // simple heuristic to estimate result size: half of the partition's rows will match // a more conservative pre-allocation would be the size of the build cluster const size_t expected_output_size = static_cast<size_t>(std::max(10.0, std::ceil((partition_end - partition_begin) / 2))); pos_list_build_side_local.reserve(static_cast<size_t>(expected_output_size)); pos_list_probe_local.reserve(static_cast<size_t>(expected_output_size)); for (size_t partition_offset = partition_begin; partition_offset < partition_end; ++partition_offset) { auto& probe_column_element = partition[partition_offset]; if (mode == JoinMode::Inner && probe_column_element.row_id == NULL_ROW_ID) { // From previous joins, we could potentially have NULL values that do not refer to // an actual probe_column_element but to the NULL_ROW_ID. Hence, we can only skip for inner joins. continue; } const auto& primary_predicate_matching_rows = hash_table.find(static_cast<HashedType>(probe_column_element.value)); if (primary_predicate_matching_rows != hash_table.end()) { // Key exists, thus we have at least one hit for the primary predicate // Since we cannot store NULL values directly in off-the-shelf containers, // we need to the check the NULL bit vector here because a NULL value (represented // as a zero) yields the same rows as an actual zero value. // For inner joins, we skip NULL values and output them for outer joins. // Note, if the materialization/radix partitioning phase did not explicitly consider // NULL values, they will not be handed to the probe function. if constexpr (keep_null_values) { if ((*probe_radix_container.null_value_bitvector)[partition_offset]) { pos_list_build_side_local.emplace_back(NULL_ROW_ID); pos_list_probe_local.emplace_back(probe_column_element.row_id); // ignore found matches and continue with next probe item continue; } } // If NULL values are discarded, the matching probe_column_element pairs will be written to the result pos // lists. if (!multi_predicate_join_evaluator) { for (const auto& row_id : *primary_predicate_matching_rows) { pos_list_build_side_local.emplace_back(row_id); pos_list_probe_local.emplace_back(probe_column_element.row_id); } } else { auto match_found = false; for (const auto& row_id : *primary_predicate_matching_rows) { if (multi_predicate_join_evaluator->satisfies_all_predicates(row_id, probe_column_element.row_id)) { pos_list_build_side_local.emplace_back(row_id); pos_list_probe_local.emplace_back(probe_column_element.row_id); match_found = true; } } // We have not found matching items for all predicates. if constexpr (keep_null_values) { if (!match_found) { pos_list_build_side_local.emplace_back(NULL_ROW_ID); pos_list_probe_local.emplace_back(probe_column_element.row_id); } } } } else { // We have not found matching items for the first predicate. Only continue for non-equi join modes. // We use constexpr to prune this conditional for the equi-join implementation. // Note, the outer relation (i.e., left relation for LEFT OUTER JOINs) is the probing // relation since the relations are swapped upfront. if constexpr (keep_null_values) { pos_list_build_side_local.emplace_back(NULL_ROW_ID); pos_list_probe_local.emplace_back(probe_column_element.row_id); } } } } else { // When there is no hash table, we might still need to handle the values of the probe side for LEFT // and RIGHT joins. We use constexpr to prune this conditional for the equi-join implementation. if constexpr (keep_null_values) { // We assume that the relations have been swapped previously, so that the outer relation is the probing // relation. // Since we did not find a hash table, we know that there is no match in the build column for this partition. // Hence we are going to write NULL values for each row. pos_list_build_side_local.reserve(partition_end - partition_begin); pos_list_probe_local.reserve(partition_end - partition_begin); for (size_t partition_offset = partition_begin; partition_offset < partition_end; ++partition_offset) { auto& row = partition[partition_offset]; pos_list_build_side_local.emplace_back(NULL_ROW_ID); pos_list_probe_local.emplace_back(row.row_id); } } } pos_lists_build_side[current_partition_id] = std::move(pos_list_build_side_local); pos_lists_probe_side[current_partition_id] = std::move(pos_list_probe_local); })); jobs.back()->schedule(); } Hyrise::get().scheduler()->wait_for_tasks(jobs); } template <typename ProbeColumnType, typename HashedType, JoinMode mode> void probe_semi_anti(const RadixContainer<ProbeColumnType>& radix_probe_column, const std::vector<std::optional<PosHashTable<HashedType>>>& hash_tables, std::vector<PosList>& pos_lists, const Table& build_table, const Table& probe_table, const std::vector<OperatorJoinPredicate>& secondary_join_predicates) { std::vector<std::shared_ptr<AbstractTask>> jobs; jobs.reserve(radix_probe_column.partition_offsets.size()); [[maybe_unused]] const auto* probe_column_null_values = radix_probe_column.null_value_bitvector ? radix_probe_column.null_value_bitvector.get() : nullptr; for (size_t current_partition_id = 0; current_partition_id < radix_probe_column.partition_offsets.size(); ++current_partition_id) { const auto partition_begin = current_partition_id == 0 ? 0 : radix_probe_column.partition_offsets[current_partition_id - 1]; const auto partition_end = radix_probe_column.partition_offsets[current_partition_id]; // make end non-inclusive // Skip empty partitions to avoid empty output chunks if (partition_begin == partition_end) { continue; } jobs.emplace_back(std::make_shared<JobTask>([&, partition_begin, partition_end, current_partition_id]() { // Get information from work queue auto& partition = static_cast<Partition<ProbeColumnType>&>(*radix_probe_column.elements); PosList pos_list_local; if (hash_tables[current_partition_id]) { // Valid hash table found, so there is at least one match in this partition const auto& hash_table = hash_tables[current_partition_id].value(); // Accessors are not thread-safe, so we create one evaluator per job MultiPredicateJoinEvaluator multi_predicate_join_evaluator(build_table, probe_table, mode, secondary_join_predicates); for (size_t partition_offset = partition_begin; partition_offset < partition_end; ++partition_offset) { const auto& probe_column_element = partition[partition_offset]; if constexpr (mode == JoinMode::Semi) { // NULLs on the probe side are never emitted if (probe_column_element.row_id.chunk_offset == INVALID_CHUNK_OFFSET) { continue; } } else if constexpr (mode == JoinMode::AntiNullAsFalse) { // NOLINT - doesn't like else if constexpr // NULL values on the probe side always lead to the tuple being emitted for AntiNullAsFalse, irrespective // of secondary predicates (`NULL("as false") AND <anything>` is always false) if ((*probe_column_null_values)[partition_offset]) { pos_list_local.emplace_back(probe_column_element.row_id); continue; } } else if constexpr (mode == JoinMode::AntiNullAsTrue) { // NOLINT - doesn't like else if constexpr if ((*probe_column_null_values)[partition_offset]) { // Primary predicate is TRUE, as long as we do not support secondary predicates with AntiNullAsTrue. // This means that the probe value never gets emitted continue; } } auto any_build_column_value_matches = false; if (secondary_join_predicates.empty()) { any_build_column_value_matches = hash_table.contains(static_cast<HashedType>(probe_column_element.value)); } else { const auto primary_predicate_matching_rows = hash_table.find(static_cast<HashedType>(probe_column_element.value)); if (primary_predicate_matching_rows != hash_table.end()) { for (const auto& row_id : *primary_predicate_matching_rows) { if (multi_predicate_join_evaluator.satisfies_all_predicates(row_id, probe_column_element.row_id)) { any_build_column_value_matches = true; break; } } } } if ((mode == JoinMode::Semi && any_build_column_value_matches) || ((mode == JoinMode::AntiNullAsTrue || mode == JoinMode::AntiNullAsFalse) && !any_build_column_value_matches)) { pos_list_local.emplace_back(probe_column_element.row_id); } } } else if constexpr (mode == JoinMode::AntiNullAsFalse) { // NOLINT - doesn't like else if constexpr // no hash table on other side, but we are in AntiNullAsFalse mode which means all tuples from the probing side // get emitted. pos_list_local.reserve(partition_end - partition_begin); for (size_t partition_offset = partition_begin; partition_offset < partition_end; ++partition_offset) { auto& probe_column_element = partition[partition_offset]; pos_list_local.emplace_back(probe_column_element.row_id); } } else if constexpr (mode == JoinMode::AntiNullAsTrue) { // NOLINT - doesn't like else if constexpr // no hash table on other side, but we are in AntiNullAsTrue mode which means all tuples from the probing side // get emitted. That is, except NULL values, which only get emitted if the build table is empty. const auto build_table_is_empty = build_table.row_count() == 0; pos_list_local.reserve(partition_end - partition_begin); for (size_t partition_offset = partition_begin; partition_offset < partition_end; ++partition_offset) { auto& probe_column_element = partition[partition_offset]; // A NULL on the probe side never gets emitted, except when the build table is empty. // This is because `NULL NOT IN <empty list>` is actually true if ((*probe_column_null_values)[partition_offset] && !build_table_is_empty) { continue; } pos_list_local.emplace_back(probe_column_element.row_id); } } pos_lists[current_partition_id] = std::move(pos_list_local); })); jobs.back()->schedule(); } Hyrise::get().scheduler()->wait_for_tasks(jobs); } using PosLists = std::vector<std::shared_ptr<const PosList>>; using PosListsByChunk = std::vector<std::shared_ptr<PosLists>>; /** * Returns a vector where each entry with index i references a PosLists object. The PosLists object * contains the position list of every segment/chunk in column i. * @param input_table */ // See usage in _on_execute() for doc. inline PosListsByChunk setup_pos_lists_by_chunk(const std::shared_ptr<const Table>& input_table) { DebugAssert(input_table->type() == TableType::References, "Function only works for reference tables"); std::map<PosLists, std::shared_ptr<PosLists>> shared_pos_lists_by_pos_lists; PosListsByChunk pos_lists_by_segment(input_table->column_count()); auto pos_lists_by_segment_it = pos_lists_by_segment.begin(); const auto input_chunks_count = input_table->chunk_count(); const auto input_columns_count = input_table->column_count(); // For every column, for every chunk for (ColumnID column_id{0}; column_id < input_columns_count; ++column_id) { // Get all the input pos lists so that we only have to pointer cast the segments once auto pos_list_ptrs = std::make_shared<PosLists>(input_table->chunk_count()); auto pos_lists_iter = pos_list_ptrs->begin(); // Iterate over every chunk and add the chunks segment with column_id to pos_list_ptrs for (ChunkID chunk_id{0}; chunk_id < input_chunks_count; ++chunk_id) { const auto chunk = input_table->get_chunk(chunk_id); Assert(chunk, "Physically deleted chunk should not reach this point, see get_chunk / #1686."); const auto& ref_segment_uncasted = chunk->get_segment(column_id); const auto ref_segment = std::static_pointer_cast<const ReferenceSegment>(ref_segment_uncasted); *pos_lists_iter = ref_segment->pos_list(); ++pos_lists_iter; } // pos_list_ptrs contains all position lists of the reference segments for the column_id. auto iter = shared_pos_lists_by_pos_lists.emplace(*pos_list_ptrs, pos_list_ptrs).first; *pos_lists_by_segment_it = iter->second; ++pos_lists_by_segment_it; } return pos_lists_by_segment; } /** * * @param output_segments [in/out] Vector to which the newly created reference segments will be written. * @param input_table Table which all the position lists reference * @param input_pos_list_ptrs_sptrs_by_segments Contains all position lists to all columns of input table * @param pos_list contains the positions of rows to use from the input table */ inline void write_output_segments(Segments& output_segments, const std::shared_ptr<const Table>& input_table, const PosListsByChunk& input_pos_list_ptrs_sptrs_by_segments, std::shared_ptr<PosList> pos_list) { std::map<std::shared_ptr<PosLists>, std::shared_ptr<PosList>> output_pos_list_cache; // We might use this later, but want to have it outside of the for loop std::shared_ptr<Table> dummy_table; // Add segments from input table to output chunk // for every column for every row in pos_list: get corresponding PosList of input_pos_list_ptrs_sptrs_by_segments // and add it to new_pos_list which is added to output_segments for (ColumnID column_id{0}; column_id < input_table->column_count(); ++column_id) { if (input_table->type() == TableType::References) { if (input_table->chunk_count() > 0) { const auto& input_table_pos_lists = input_pos_list_ptrs_sptrs_by_segments[column_id]; auto iter = output_pos_list_cache.find(input_table_pos_lists); if (iter == output_pos_list_cache.end()) { // Get the row ids that are referenced auto new_pos_list = std::make_shared<PosList>(pos_list->size()); auto new_pos_list_iter = new_pos_list->begin(); for (const auto& row : *pos_list) { if (row.chunk_offset == INVALID_CHUNK_OFFSET) { *new_pos_list_iter = row; } else { const auto& referenced_pos_list = *(*input_table_pos_lists)[row.chunk_id]; *new_pos_list_iter = referenced_pos_list[row.chunk_offset]; } ++new_pos_list_iter; } iter = output_pos_list_cache.emplace(input_table_pos_lists, new_pos_list).first; } auto reference_segment = std::static_pointer_cast<const ReferenceSegment>( input_table->get_chunk(ChunkID{0})->get_segment(column_id)); output_segments.push_back(std::make_shared<ReferenceSegment>( reference_segment->referenced_table(), reference_segment->referenced_column_id(), iter->second)); } else { // If there are no Chunks in the input_table, we can't deduce the Table that input_table is referencing to. // pos_list will contain only NULL_ROW_IDs anyway, so it doesn't matter which Table the ReferenceSegment that // we output is referencing. HACK, but works fine: we create a dummy table and let the ReferenceSegment ref // it. if (!dummy_table) dummy_table = Table::create_dummy_table(input_table->column_definitions()); output_segments.push_back(std::make_shared<ReferenceSegment>(dummy_table, column_id, pos_list)); } } else { output_segments.push_back(std::make_shared<ReferenceSegment>(input_table, column_id, pos_list)); } } } } // namespace opossum
true
2172395b9227036eb17a80f35067801f7d884c76
C++
375187588/DesignPatterns
/BehaviorPattern/Observer/Observer.h
UTF-8
7,073
2.609375
3
[]
no_license
#pragma once /*//////////////////////////////////////////////////// //说明:观察者模式类实例 //文件:Observer.h //日期:2020/6/30 //作者:coder //QQ:375187588 //修改: //版本: *////////////////////////////////////////////////////// //观察者 class CObserver; using LLObservers = std::list<CObserver*>; //主题对象 class CSubject { public: virtual ~CSubject() { delete m_pObserver; m_pObserver = nullptr; } CSubject() { m_pObserver = new LLObservers; } virtual void Attach(CObserver* obv) { m_pObserver->push_front(obv); } virtual void Detach(CObserver* obv) { if (m_pObserver != nullptr) { m_pObserver->remove(obv); } } virtual void Notify(); virtual void SetMessage(char* pMsg) = 0; virtual char* GetMessage() const = 0; private: LLObservers* m_pObserver; }; class CSubject1 :public CSubject { public: CSubject1() { m_pMessage = nullptr; } ~CSubject1() {} char* GetMessage() const { return m_pMessage; } void SetMessage(char* pMsg) { m_pMessage = pMsg; } private: char* m_pMessage; }; class CObserver { public: virtual ~CObserver() {} virtual void Update(CSubject* pSub) = 0; virtual void PrintInfo() = 0; protected: CObserver() {} char* m_pMessage; }; void CSubject::Notify() { auto it = m_pObserver->begin(); for (; it != m_pObserver->end(); it++) { (*it)->Update(this); } } class CObserver1 :public CObserver { public: virtual CSubject* GetSubject() { return m_pSubject; } CObserver1(CSubject* pSub) { m_pSubject = pSub; m_pSubject->Attach(this); } virtual ~CObserver1() { m_pSubject->Detach(this); } void Update(CSubject* pSub) { m_pMessage = pSub->GetMessage(); PrintInfo(); } void PrintInfo() { std::cout << "CObserver1 observer...." << m_pSubject->GetMessage() << std::endl; } void Release() { if (m_pSubject != nullptr) { delete m_pSubject; } } private: CSubject* m_pSubject; }; class CObserver2 :public CObserver { public: virtual CSubject* GetSubject() { return m_pSubject; } CObserver2(CSubject* pSub) { m_pSubject = pSub; m_pSubject->Attach(this); } virtual ~CObserver2() { m_pSubject->Detach(this); } void Update(CSubject* pSub) { m_pMessage = pSub->GetMessage(); PrintInfo(); } void PrintInfo() { std::cout << "CObserver2 observer.... " << m_pSubject->GetMessage() << std::endl; } void Release() { if (m_pSubject != nullptr) { delete m_pSubject; } } private: CSubject* m_pSubject; }; ///////////////////////////////////////////////////////////////// //实例2 C++用观察者模式实现MVC模式 struct IMessage { }; //检觉器 class IObservable; //观察者 class IObserver { public: IObserver() {} virtual ~IObserver() {} virtual void Update(IObservable* pObservable, IMessage* pMessage) = 0; }; //检觉器 class IObservable { public: IObservable() {} virtual ~IObservable() {} virtual void AddObserver(IObserver* pObserver) = 0; virtual void DeleteObserver(IObserver* pObserver) = 0; virtual void NotifyUpdate() = 0; virtual void NotifyUpdate(IMessage* pMessage) = 0; }; class CBaseModels; class IViewAction { public: IViewAction() {} virtual ~IViewAction() {} virtual void RefreshView(CBaseModels* pBaseModel, IMessage* pMessage) = 0; }; //通知模型接口 class IModelAction { public: IModelAction() {} virtual ~IModelAction() {} virtual void RequestData() = 0; }; using LObservers = std::list<IObserver*>; //模型实现 class CBaseModels : public IObservable, IModelAction { public: CBaseModels() { m_pObserversList = new LObservers; } ~CBaseModels() { delete m_pObserversList; m_pObserversList = nullptr; } //添加观察者 void AddObserver(IObserver* pObserver) { if (m_pObserversList == nullptr) { return; } m_pObserversList->push_back(pObserver); } void DeleteObserver(IObserver* pObserver) { if (m_pObserversList == nullptr || m_pObserversList->size() == 0) { return; } m_pObserversList->remove(pObserver); } void NotifyUpdate() { NotifyUpdate(nullptr); } void NotifyUpdate(IMessage* pMessage) { if (m_pObserversList == nullptr || m_pObserversList->size() == 0) { return; } auto it = m_pObserversList->begin(); for (; it != m_pObserversList->end(); it++) { (*it)->Update(this, pMessage); } } bool IsChanged() { return m_bChanged; } void SetChanged(bool bChanged) { this->m_bChanged = bChanged; } private: LObservers* m_pObserversList; bool m_bChanged; }; struct ModelMessage : public IMessage { std::string strName; std::string strAddr; }; //模型 class Model :public CBaseModels { public: std::string GetName() { return m_strName; } void SetName(std::string strName) { this->m_strName = strName; } void SetAddr(std::string strAddr) { this->m_strAddr = strAddr; } std::string GetAddr() { return m_strAddr; } void RequestData() { // 模拟Model更新 m_strName = "高宣帅"; m_strAddr = "人民南路"; m_message.strName = "白富美"; m_message.strAddr = "富贵街"; std::cout << "Model发生了改变,通知View更新" << std::endl; //设置改变 SetChanged(true); NotifyUpdate((ModelMessage*)(&m_message)); } private: std::string m_strName;// 名字 std::string m_strAddr;// 地址 ModelMessage m_message; }; class CBaseViews; //控制器 class CController { public: CController(CBaseViews* pView) { this->m_pView = pView; m_pModel = new Model(); // 将m_pView与m_pModel绑定 m_pModel->AddObserver((IObserver*)pView); } ~CController() { delete m_pModel; m_pModel = nullptr; } void DoNotifyMessage() { std::cout << "Controller响应View的界面操作事件,通知Model更新" << std::endl; ((Model*)m_pModel)->RequestData(); } private: CBaseViews* m_pView; CBaseModels* m_pModel; }; //视图 class CBaseViews : public IObserver, IViewAction { public: CBaseViews() { this->m_pController = new CController(this); } virtual ~CBaseViews() { delete m_pController; m_pController = nullptr; } void Update(IObservable* pObservable, IMessage* pMessage) { CBaseModels* pBaseModel = (CBaseModels*)pObservable; if (pBaseModel->IsChanged()) { RefreshView(pBaseModel, pMessage); } } protected: CController* m_pController;// 控制器 }; //视图 class CView :public CBaseViews { public: void DoTouchEvent() { std::cout << "模拟事件传给Controller处理" << std::endl; // 将事件传给Controller处理 m_pController->DoNotifyMessage(); } //刷新界面 void RefreshView(CBaseModels* pBaseModel, IMessage* pMessage) { std::cout << std::endl << std::endl; std::cout << "收到Model发来的通知数据,更新界面" << std::endl; ModelMessage* p = (ModelMessage*)pMessage; Model* m_pModel = (Model*)pBaseModel; std::string strName = m_pModel->GetName(); std::string strAddr = m_pModel->GetAddr(); std::cout << "住在:" << p->strAddr << "的:" << p->strName << " 约住在:" << strAddr << "的 名字:" << strName << "去看电影!" << std::endl; } };
true
e2855f2217979cd63f56ee883ddf0b033345c103
C++
huxiao1/algorithm
/bfs/Sequence Reconstruction/test.cpp
UTF-8
552
3.1875
3
[]
no_license
#include<iostream> #include<unordered_map> using namespace std; int main() { unordered_map<int, int> pos = {{1,3},{2,4},{3,5}}; unordered_map<int,int>::const_iterator got = pos.find(1); cout<<got->first << "is" << got->second<<endl; for ( auto it = pos.begin(); it != pos.end(); ++it ) cout << " " << it->first << ":" << it->second; cout<<endl; auto it = pos.begin(); cout<<it->first << ":" << it->second; //do not work auto it2 = pos.end(); cout<<it2->first << ":" << it2->second; }
true
5e53ea3fd25e95b193d31a849fae0faec19085de
C++
npo6ka/LedMatrix
/src/effect_list/libs/lib_led.cpp
UTF-8
3,972
2.59375
3
[]
no_license
#include "lib_led.h" // ************* НАСТРОЙКА МАТРИЦЫ ************** //hooks for old vertion #if (STRIP_DIRECTION == 2) # define STRIP_DIRECTION 0 #elif (STRIP_DIRECTION == 3) # define STRIP_DIRECTION 1 #endif #if (STRIP_DIRECTION == 0) # define _WIDTH WIDTH #elif (STRIP_DIRECTION == 1) # define _WIDTH HEIGHT #endif #if (CONNECTION_ANGLE == 0 && STRIP_DIRECTION == 0) # define THIS_X (HEIGHT - x - 1) # define THIS_Y y #elif (CONNECTION_ANGLE == 0 && STRIP_DIRECTION == 1) # define THIS_X y # define THIS_Y (HEIGHT - x - 1) #elif (CONNECTION_ANGLE == 1 && STRIP_DIRECTION == 0) # define THIS_X x # define THIS_Y y #elif (CONNECTION_ANGLE == 1 && STRIP_DIRECTION == 1) # define THIS_X y # define THIS_Y x #elif (CONNECTION_ANGLE == 2 && STRIP_DIRECTION == 0) # define THIS_X x # define THIS_Y (WIDTH - y - 1) #elif (CONNECTION_ANGLE == 2 && STRIP_DIRECTION == 1) # define THIS_X (WIDTH - y - 1) # define THIS_Y x #elif (CONNECTION_ANGLE == 3 && STRIP_DIRECTION == 0) # define THIS_X (HEIGHT - x - 1) # define THIS_Y (WIDTH - y - 1) #elif (CONNECTION_ANGLE == 3 && STRIP_DIRECTION == 1) # define THIS_X (WIDTH - y - 1) # define THIS_Y (HEIGHT - x - 1) #else # define _WIDTH WIDTH # define THIS_X x # define THIS_Y y # pragma message "Wrong matrix parameters! Set to default" #endif extern CRGB leds[LEDS_CNT]; /* инициализация библиотеки FastLed и * установка цветовой коррекции светодиодов */ void led_setup(void) { FastLED.addLeds<WS2812B, DATA_PIN, COLOR_ORDER>(leds, LEDS_CNT).setCorrection(TypicalLEDStrip); FastLED.setMaxPowerInVoltsAndMilliamps(5, CURRENT_LIMIT); FastLED.clear(); } // получить номер пикселя в ленте по координатам static uint16_t getPixNum(uint8_t x, uint8_t y) { // x - номер строки (в циклах ассоциируется с HEIGHT) // y - номер столбца (в циклах ассоциируется с WIDTH) // матрица нумеруется сверху вниз по x, слева направо по y (как все массивы в си) // 00 01 02 // 10 11 12 // 20 21 22 if (x < 0 || x >= HEIGHT || y < 0 || y >= WIDTH) { out("Value out of range in function getPixNum %d %d\n", x, y); return 0; } if (THIS_X % 2 == 0 || MATRIX_TYPE) { // если чётная строка return (THIS_X * _WIDTH + THIS_Y); } else { // если нечётная строка return (THIS_X * _WIDTH + _WIDTH - THIS_Y - 1); } } CRGB &getPix(const int x, const int y) { if (x < 0 || x >= HEIGHT || y < 0 || y >= WIDTH) { out("Value out of range in function getPix %d %d\n", x, y); return leds[0]; } return leds[getPixNum(x, y)]; } CRGB* getLeds(void) { return leds; } void fader(uint8_t step) { for (uint8_t i = 0; i < HEIGHT; i++) { for (uint8_t j = 0; j < WIDTH; j++) { fadePix(i, j, step); } } } void fadePix(uint8_t x, uint8_t y, uint8_t step) { getPix(x, y).fadeToBlackBy(step); } void drawLine(uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, CRGB color) { // Рисование линии по Алгоритму Брезенхэма uint8_t deltaX = abs((int16_t)x2 - x1); uint8_t deltaY = abs((int16_t)y2 - y1); uint8_t x1_ = x1; uint8_t y1_ = y1; int8_t signX = x1_ < x2 ? 1 : -1; int8_t signY = y1_ < y2 ? 1 : -1; int16_t error = deltaX - deltaY; int32_t error2; getPix(x2, y2) = color; while (x1_ != x2 || y1_ != y2) { getPix(x1_, y1_) = color; error2 = error * 2; if (error2 > -deltaY) { error -= deltaY; x1_ += signX; } if (error2 < deltaX) { error += deltaX; y1_ += signY; } } }
true
4f82703422970205020813d1f54dc0a86d1e5a67
C++
utkar-sh/Competitive-Programming
/code-cpp/longestIncreasingPath.cpp
UTF-8
1,525
3.3125
3
[]
no_license
#include <bits/stdc++.h> int inBounds(int i, int j, int n, int m) { return i >= 0 && i < n && j >= 0 && j < m; } int dir_x[4] = {1, -1, 0, 0}; int dir_y[4] = {0, 0, 1, -1}; //to avoid redundant dfs from every node, //store the max best path that is achievable at a node.. //next time we land on a node, if previously path had a better length //we do not solve it int dp[201][201] = {0}; int dfs(int i, int j, int n, int m, vector<vector<int>>& matrix) { if (dp[i][j] != 0) { return dp[i][j]; } for (int dir = 0; dir < 4; dir++) { int newX = i + dir_x[dir]; int newY = j + dir_y[dir]; if (inBounds(newX, newY, n, m) && matrix[newX][newY] > matrix[i][j]) { dp[i][j] = max(dp[i][j], dfs(newX, newY, n, m, matrix)); } } dp[i][j] = dp[i][j] + 1; return dp[i][j]; } int longestIncreasingPath(vector<vector<int>>& matrix) { int ans = 1; //from each cell, start a bfs if possible in an incr manner int n = matrix.size(); int m = matrix[0].size(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { std::cout << "DFS from " << i << ", " << j << ": "; int thisAns = dfs(i, j, n, m, matrix); ans = max(ans, thisAns); std::cout << thisAns << endl; } } return ans; } int main() { vector<vector<int>> matrix = { {9, 9, 4}, {6, 6, 8}, {2, 1, 1}}; std::cout << longestIncreasingPath(matrix) << std::endl; return 0; }
true
807d94cee2626e2355397e41ab5a1f3d69a48027
C++
lhy1229/lhy
/数据结构/串/串的基本运算.cpp
UTF-8
2,198
3.1875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #define MaxSize 100 typedef struct{ char data[MaxSize]; int length; }SqString; void StrAssign(SqString &s,char cstr[]){ int i; for(i=0;cstr[i]!='\0';i++){ s.data[i]=cstr[i]; } s.length=i; } void DestroyStr(SqString &s){ } bool StrEqual(SqString s,SqString t){ bool same=1; int i; if(s.length!=t.length) same=false; else{ for(i=0;i<s.length;i++){ if(s.data[i]!=t.data[i]){ same=false; break; } } } return same; } void StrCopy(SqString &s,SqString t){ int i; for(i=0;i<t.length;i++) s.data[i]=t.data[i]; s.length=t.length; } int StrLength(SqString s){ return s.length; } SqString Concat(SqString s,SqString t){ SqString str; int i; str.length=s.length+t.length; for(i=0;i<s.length;i++) str.data[i]=s.data[i]; for(i=0;i<t.length ;i++) str.data [s.length+i]=t.data[i]; return str; } SqString SubStr(SqString s,int i,int j){ int k; SqString str; str.length=0; if(i<=0||i>s.length||j<0||i+j-1>s.length) return str; for(k=i-1;k<i+j-1;k++) str.data[k-i+1]=s.data[k]; str.length=j; return str; } SqString InStr(SqString s1,int i,SqString s2){ int j; SqString str; str.length=0; if(i<=0||i>s1.length+1) return str; for(j=0;j<i-1;j++) str.data[j]=s1.data[j]; for(j=0;j<s2.length;j++) str.data[i+j-1]=s2.data[j]; for(j=i-1;j<s1.length;j++) str.data[s2.length+j]=s1.data[j]; return str; } SqString DelStr(SqString s,int i,int j){ int k; SqString str; str.length=0; if(i<=0||i>s.length||i+j>s.length+1) return str; for(k=0;k<i-1;k++) str.data[k]=s.data[k]; for(k=i+j-1;k<s.length;k++) str.data[k-j]=s.data[k]; str.length=s.length-j; return str; } SqString RepStr(SqString s,int i,int j,SqString t){ int k; SqString str; str.length=0; if(i<=0||i>s.length||i+j-1>s.length) return str; for(k=0;k<i-1;k++) str.data[k]=s.data[k]; for(k=0;k<t.length;k++) str.data[i+k-1]=t.data[k]; for(k=i+j-1;k<s.length ;k++) str.data[t.length+k-j]=s.data[k]; str.length=s.length-j+t.length ; return str; } void DispStr(SqString s){ int i; if(s.length>0){ for(i=0;i<s.length;i++) printf("%c",s.data[i]); printf("\n"); } }
true
8812230e5e64275fa8789d31e3ed5b5c3fa1be60
C++
A-suozhang/NUEDC-Code
/ESP32/I2SDACESP32.h
UTF-8
2,001
2.765625
3
[]
no_license
#pragma once // 预处理指令,能够保证cpp只会被编译一次 #include "./driver/ledc.h" #include "./driver/i2s.h" #include "./freertos/portmacro.h" #ifndef _I2SDACESP32_ #define _I2SDACESP32_ static i2s_config_t i2s_config_dac; static i2s_port_t i2s_num_dac=(i2s_port_t)0; // --------- Make A CLass ---------- class I2SDAC{ // Public Variables & Methdods(Inlcuding Building Function) public: unsigned long samplerate; unsigned char chn=0;//0:right 1:left // The Building Function I2SDAC(unsigned char chn_){ chn=chn_; } ~I2SDAC(){ i2s_driver_uninstall(i2s_num_dac); } void begin(unsigned long samplerate_){ samplerate=samplerate_; i2s_config_dac.mode=i2s_mode_t(I2S_MODE_MASTER|I2S_MODE_TX|I2S_MODE_DAC_BUILT_IN); i2s_config_dac.sample_rate=samplerate; i2s_config_dac.bits_per_sample = (i2s_bits_per_sample_t)16; if(chn==0) i2s_config_dac.channel_format=I2S_CHANNEL_FMT_ONLY_RIGHT; else i2s_config_dac.channel_format=I2S_CHANNEL_FMT_ONLY_LEFT; i2s_config_dac.communication_format=(i2s_comm_format_t)(I2S_COMM_FORMAT_I2S_MSB); i2s_config_dac.intr_alloc_flags=0; i2s_config_dac.dma_buf_count=8; i2s_config_dac.dma_buf_len=128; i2s_config_dac.use_apll=false; i2s_driver_install(i2s_num_dac,&i2s_config_dac,0,NULL); i2s_set_pin(i2s_num_dac,NULL); if(chn==0) i2s_set_dac_mode(I2S_DAC_CHANNEL_RIGHT_EN); else i2s_set_dac_mode(I2S_DAC_CHANNEL_LEFT_EN); i2s_set_sample_rates(i2s_num_dac,samplerate); } void write(unsigned char in){ unsigned short dat; dat=(unsigned short)in<<8; i2s_write_bytes(i2s_num_dac,(char*)(&dat),2,(TickType_t)portMAX_DELAY); } }; #endif // ----------------- Usage ------------------- // dac0 = I2SDAC(0) // dac0.begin(samplerate) // dac0.write(vol) // -------------------------------------------
true
63fd3f2c25366f9be80049e11d3bf802fcb6f6f9
C++
windy32/em-ray-tracing
/src/Engine/Sphere.h
UTF-8
505
2.703125
3
[]
no_license
#ifndef SPHERE_H #define SPHERE_H #include "Geometry.h" class Sphere : public Geometry { public: Point center; double radius; public: Sphere(const Point &center, double radius); virtual Point getCenter() const; virtual void getBoundingBox(Point &min, Point &max); virtual IntersectResult intersect(Ray &ray); }; class RxSphere : public Sphere { public: int index; public: RxSphere(const Point &center, double radius, int index); }; #endif
true
60ca52db72f02336eccc5e4a2f04e62b56b65a5f
C++
Ruthietta/Infinite-coders-competition
/Task 2/Solution 2/printVector.hpp
UTF-8
234
2.890625
3
[]
no_license
#pragma once #include <algorithm> #include <iostream> #include <iterator> #include <vector> int printVector(std::vector<int> vec) { std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, ", ")); return 0; }
true
b2b2761c8eb0866dddd7ea77ae06a3f97e2825e5
C++
tangjz/acm-icpc
/hackerrank/stone-piles.cpp
UTF-8
670
2.578125
3
[ "Apache-2.0" ]
permissive
#include <stdio.h> #include <cstring> const int maxn = 51, maxv = 101; int lim, sg[maxn]; bool vis[maxv]; void dfs(int rem, int last, int Xor) { if(!rem) { vis[Xor] = 1; return; } for(int i = last + 1; i <= rem && i < lim; ++i) dfs(rem - i, i, Xor ^ sg[i]); } int main() { memset(sg, -1, sizeof sg); sg[1] = 0; for(lim = 1; lim < maxn; ++lim) { memset(vis, 0, sizeof vis); dfs(lim, 0, 0); for(int j = 0; ; ++j) if(!vis[j]) { sg[lim] = j; break; } } int t, n, x; scanf("%d", &t); while(t--) { int SG = 0; scanf("%d", &n); while(n--) { scanf("%d", &x); SG ^= sg[x]; } puts(SG ? "ALICE" : "BOB"); } return 0; }
true
aee50786ef925b9212448066d584997a6fcf8da4
C++
Max850709/Leetcode_C
/reverseint/reverseint/main.cpp
UTF-8
769
3.78125
4
[]
no_license
/* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. */ #include <iostream> using namespace std; class solution{ public: int reverse(int x) { int ans=0; for(;x!=0;x/=10){ if(x>0){ if(ans > (INT_MAX - (x % 10)) / 10 )return 0; } else{ if(ans < (INT_MIN - (x % 10)) / 10 )return 0; } ans=10*ans+(x%10); //x=x/10; } return ans; } }; int main() { solution s1; int num; cin >> num; cout << s1.reverse(num); return 0; }
true