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
3511b7be339195b92e287172043d841ea95ee0af
C++
s-nandi/contest-problems
/graph-theory/network-flow/maximal-matching/transportation_delegation.cpp
UTF-8
4,705
2.875
3
[]
no_license
// max flow (maximal matching) // https://open.kattis.com/problems/transportation // 2015 East-Central NA Regional #include <bits/stdc++.h> using namespace std; typedef long long ll; const int INF = 1231231234; struct edge{int to, id;}; typedef vector<vector<edge>> graph; typedef int flowT; struct dinic { int sz; graph g; vector <flowT> capacities, flow; vector <int> level, startEdge; dinic(int s) { sz = s, g.resize(sz); level.resize(sz), startEdge.resize(sz); } void addEdge(int from, int to, flowT capacity) { g[from].push_back({to, (int) flow.size()}); capacities.push_back(capacity), flow.push_back(0); g[to].push_back({from, (int) flow.size()}); capacities.push_back(0), flow.push_back(0); } flowT residual(int id){return capacities[id] - flow[id];} bool buildLevelGraph(int source, int sink) { queue <int> q; q.push(source); fill(level.begin(), level.end(), -1); level[source] = 0; while (!q.empty()) { int curr = q.front(); q.pop(); for (edge e: g[curr]) if (level[e.to] == -1 and residual(e.id) > 0) { q.push(e.to); level[e.to] = level[curr] + 1; } } return level[sink] != -1; } flowT blockingFlow(int curr, int sink, flowT sent = INF) { if (curr == sink) return sent; for (; startEdge[curr] < g[curr].size(); startEdge[curr]++) { edge e = g[curr][startEdge[curr]]; if (level[e.to] == level[curr] + 1 and residual(e.id) > 0) { flowT augment = blockingFlow(e.to, sink, min(sent, residual(e.id))); if (augment > 0) { flow[e.id] += augment; flow[e.id ^ 1] -= augment; return augment; } } } return 0; } flowT maxflow(int source, int sink) { flowT res = 0; while (buildLevelGraph(source, sink)) { fill(startEdge.begin(), startEdge.end(), 0); while (flowT delta = blockingFlow(source, sink)) res += delta; } return res; } }; template <typename T> bool contains(vector <T> &sorted, T i) { return binary_search(sorted.begin(), sorted.end(), i); } int numString = 0; map <string, int> mapping; int getIndex(const string &s) { if (!mapping.count(s)) { mapping[s] = numString++; return numString - 1; } else return mapping[s]; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int s, r, f, t; cin >> s >> r >> f >> t; vector <int> raw(r), factory(f); for (auto &elem: raw) { string str; cin >> str; elem = getIndex(str); } for (auto &elem: factory) { string str; cin >> str; elem = getIndex(str); } vector <vector<int>> transport(t); for (auto &elem: transport) { int sz; cin >> sz; elem.resize(sz); for (auto &e: elem) { string str; cin >> str; e = getIndex(str); } sort(elem.begin(), elem.end()); } int sz = r + f + 2 * t + 2; int source = sz - 2, sink = sz - 1; dinic dnc(sz); for (int i = 0; i < r; i++) { dnc.addEdge(source, i, 1); } for (int i = 0; i < f; i++) { dnc.addEdge(r + i, sink, 1); } for (int i = 0; i < t; i++) { dnc.addEdge(r + f + i, r + f + i + t, 1); } for (int i = 0; i < r; i++) { for (int j = 0; j < t; j++) { if (contains(transport[j], raw[i])) { dnc.addEdge(i, r + f + j, 1); } } } for (int i = 0; i < f; i++) { for (int j = 0; j < t; j++) { if (contains(transport[j], factory[i])) { dnc.addEdge(r + f + t + j, r + i, 1); } } } for (int i = 0; i < t; i++) { for (int j = i + 1; j < t; j++) { bool overlap = false; for (auto state: transport[i]) { if (contains(transport[j], state)) { overlap = true; break; } } if (overlap) { dnc.addEdge(r + f + t + i, r + f + j, 1); dnc.addEdge(r + f + t + j, r + f + i, 1); } } } cout << dnc.maxflow(source, sink) << '\n'; }
true
c970c58b74a835464cb3d8478f71d96b75cd4c5d
C++
tymonali/CPlusPlus
/Tree/Main.cpp
WINDOWS-1251
797
3
3
[]
no_license
#include"Tree.h" int main() { SetConsoleCP(1251); SetConsoleOutputCP(1251); system("color B0"); srand(time(0)); Tree tree; // tree.insert(100); tree.insert(50); tree.insert(90); tree.insert(88); tree.insert(11); tree.insert(7); tree.insert(-10); tree.insert(13); tree.insert(222); tree.insert(136); tree.insert(356); Leaf* min = tree.minimum(); Leaf* max = tree.maximum(); cout << "Min element = " << min->value << "\n"; cout << "Max element = " << max->value << "\n"; tree.print(tree.getRoot()); Leaf* srch = tree.search(tree.getRoot(), 11); if (srch) { //cout << "Search = " << srch->value << "\n"; cout << "SRCH: " << "\n"; tree.print(srch); } else { cout << "Not found!!!" << "\n"; } system("pause"); return 0; }
true
350336a6a9371ef3449810b709ebb8eef049c5ce
C++
thigiacmaytinh/TGMTcpp
/ConvertJpgToPng/WinMain.cpp
UTF-8
622
2.65625
3
[]
no_license
// Test.cpp : Defines the entry point for the console application. // #include <iostream> #include <opencv2/opencv.hpp> void main(int argc, char** argv) { cv::Mat mat = cv::imread("dog.jpg"); cv::Mat matGRBA; cv::cvtColor(mat, matGRBA, CV_BGR2BGRA); for (int y = 0; y < matGRBA.rows; y++) { for (int x = 0; x < matGRBA.cols; x++) { cv::Vec4b val = matGRBA.at<cv::Vec4b>(y, x); if (val[0] > 200 && val[1] > 200 && val[2] > 200) { matGRBA.at<cv::Vec4b>(y, x) = cv::Vec4b(0, 0, 0, 0); } } } cv::imwrite("dog_rgba.png", matGRBA); cv::imshow("dog", matGRBA); cv::waitKey(); getchar(); }
true
eaa212bc245989ed6bd7b749acf8cb42582c29b4
C++
chisom360/C
/Homework/KarelRobotAndWorld/KarelWorld.h
UTF-8
994
2.671875
3
[]
no_license
#ifndef KarelWorld_H #define KarelWorld_H #include "Intersect.h" #include <vector> #include <algorithm> class karelWorld { private: //std::vector<Intersection> list; //container for the newly created world(Karel intersection container) public: //karelWorld(); karelWorld(); std::vector<Intersection> list; //container for the newly created world(Karel intersection container) karelWorld(std::vector<Intersection> IntersectionList); bool hasCorner(int street, int avenue); int getBeeperCount(int street, int avenue); int incrementBeeperCount(int street, int avenue); int decrementBeeperCount(int street, int avenue); bool wallToNorth(int street, int avenue); bool wallToSouth(int street, int avenue); bool wallToEast(int street, int avenue); bool wallToWest(int street, int avenue); void print2(); // print all the corners void print(int street, int avenue); //prints information about a specfic street and corner void print(); }; #endif
true
d972396adaa31fb82fc74624631da1387998e26d
C++
kingsamchen/Eureka
/run-child-process/rcp/unique_handle.h
UTF-8
2,647
3.078125
3
[ "MIT" ]
permissive
#pragma once #ifndef RCP_UNIQUE_HANDLE_H_ #define RCP_UNIQUE_HANDLE_H_ #include <cstddef> #include <memory> #include "rcp/macros.h" #if defined(OS_WIN) #include <Windows.h> #else #include <unistd.h> #endif namespace rcp { // unique_handle doesn't actually own the `handle_`, instead, its unique_ptr specialization // does. template<typename Traits> class unique_handle { public: using handle_type = typename Traits::handle_type; unique_handle() noexcept = default; // implicit unique_handle(std::nullptr_t) noexcept {} // implicit unique_handle(handle_type handle) noexcept : handle_(handle) {} explicit operator bool() const noexcept { return Traits::is_valid(handle_); } // implicit operator handle_type() const noexcept { return handle_; } static void close(handle_type handle) noexcept { Traits::close(handle); } friend bool operator==(unique_handle lhs, unique_handle rhs) noexcept { return lhs.handle_ == rhs.handle_; } friend bool operator!=(unique_handle lhs, unique_handle rhs) noexcept { return !(lhs == rhs); } private: handle_type handle_{Traits::null_handle}; }; template<typename Traits> struct unique_handle_deleter { using pointer = unique_handle<Traits>; void operator()(pointer ptr) const { pointer::close(ptr); } }; #if defined(OS_WIN) struct win_handle_traits { using handle_type = HANDLE; static bool is_valid(handle_type handle) noexcept { return handle != nullptr && handle != INVALID_HANDLE_VALUE; } static void close(handle_type handle) noexcept { ::CloseHandle(handle); } static constexpr handle_type null_handle{nullptr}; }; using win_handle_deleter = unique_handle_deleter<win_handle_traits>; using unique_win_handle = std::unique_ptr<win_handle_traits::handle_type, win_handle_deleter>; inline unique_win_handle wrap_unique_win_handle(win_handle_traits::handle_type raw_handle) { return unique_win_handle(raw_handle); } #else struct fd_traits { using handle_type = int; static bool is_valid(handle_type handle) noexcept { return handle != fd_traits::null_handle; } static void close(handle_type handle) noexcept { ::close(handle); } static constexpr handle_type null_handle{-1}; }; using fd_deleter = unique_handle_deleter<fd_traits>; using unique_fd = std::unique_ptr<fd_traits::handle_type, fd_deleter>; inline unique_fd wrap_unique_fd(fd_traits::handle_type raw_fd) { return unique_fd(raw_fd); } #endif } // namespace rcp #endif // RCP_UNIQUE_HANDLE_H_
true
801a29ae3a4f6fe991a361b621bddef8e95ac31f
C++
Vinicius0li/dalacorte.github.io
/C++/Faculdade/Exemplo/Segundo Semestre/Exemplo3.cpp
UTF-8
154
2.765625
3
[]
no_license
#include <stdio.h> int main() { int dia, mes, ano; dia = 1; mes = 1; ano = 2000; printf("Hoje eh dia: %d/%d/%d. \n", dia, mes, ano); return 0; }
true
4fee5f5c44ed72dd30b3df4f33444c8cf580f22a
C++
dliang5/CS109_MachineReader
/sArgsException.cpp
UTF-8
244
2.609375
3
[]
no_license
#include "sArgsException.h" using namespace std; s_ArgsException::s_ArgsException(int x) : num(x){ } void s_ArgsException::print(){ std::cout << "why you gotta use " << num << " args?" << std::endl; } s_ArgsException::~s_ArgsException(){}
true
232b66a64d79e5d86b0f6eb32b0249c225883809
C++
lip23/growing
/数据结构/队列的顺序实现.cpp
GB18030
1,694
3.75
4
[]
no_license
#include <iostream.h> #include <malloc.h> typedef struct //еԴ洢ṹ { int* elem; int size; }sqqueue; void initsqqueue(sqqueue &q,int n)//ʼСΪnĶ { q.elem=(int*)malloc((n+10)*(sizeof(int))); if(!q.elem) cout<<"гʼʧ"<<endl; q.size=n; cout<<"ʼеԪ"<<endl; for(int i=1;i<=n;i++) cin>>q.elem[i]; cout<<"гʼɹ"<<endl; } void putout(sqqueue q) { cout<<"ǰеԪ"<<endl; for(int i=1;i<=q.size;i++) cout<<q.elem[i]<<" "; } void enqueue(sqqueue &q)//ԪeΪq¶βԪ { int e; cout<<endl<<"ҪӵԪe= "; cin>>e; cout<<endl; q.size++; q.elem[q.size]=e; } void dequeue(sqqueue &q)//вգɾqĶͷԪأeֵ { int e; if(q.size==0) { cout<<"Ϊ"<<endl; } else { e=q.elem[1]; q.size--; cout<<"ӵԪe= "<<e<<endl; for(int i=1;i<=q.size;i++) q.elem [i]=q.elem[i+1]; } } void main() { int n; char m; sqqueue q; cout<<"ҪĶеĴСn= "; cin>>n; initsqqueue(q,n); putout(q); do { cout<<endl<<"ҪִеIJ aԪ bԪس cֹ"<<endl; cin>>m; if(m=='a') { enqueue(q); putout(q); } else if(m=='b') { dequeue(q); if(q.size==0) { cout<<"ǰѿ,ֹ"<<endl; m='c'; } else { putout(q); } } else cout<<""<<endl; }while(m!='c'); }
true
c974bdb375d6d75cec1410b8d4cf192b1ad4752d
C++
hardikhere/competitive-programming
/Vectors/(GEEKSFORGEEKS)Print the left element.cpp
UTF-8
359
2.5625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int main() { //code int t; cin>>t; while(t--) { int n; cin>>n; int arr[n]; for(int i=0; i<n; i++) { cin>>arr[i]; } sort(arr,arr+n); if(n%2==0){ cout<<arr[(n/2)-1]<<endl; } else{ cout<<arr[n/2]<<endl; } } return 0; }
true
cdb887f8a1728d15cb81b16ebed7dbc4403dac91
C++
mke01/BasicC-
/Day 14_15/06 Virtual Destructor/Source01.cpp
UTF-8
921
3.15625
3
[]
no_license
#include <crtdbg.h> #include<iostream> using namespace std; class Base { public: Base() { cout<<"Base Constructor"<<endl; } ~Base() { cout<<"Base Destructor"<<endl; } }; class Derived:public Base { char *p; public: Derived() { p = new char; p[0] = 'a'; cout<<"Derived Constructor"<<endl; } ~Derived() { delete p; p=nullptr; cout<<"Derived Destructor"<<endl; } }; int main() { Base *pbase = new Derived; delete pbase; pbase = nullptr; _CrtDumpMemoryLeaks(); return 0; } /* In above program we noticed destructor call of derived class is getting missed and because of we are releasing memory resource in derived destructor and the destructor is not taking place, the memory is getting leaked out. Had the data member be scalar i.e. non-pointer then it doesn't cause memory leakage. This means, the object space is not leaked out. It is resource which is consumed is leaked out. */
true
841d6f4fadf7859d934792dcc3465b2e947faa1e
C++
Kartik-Mathur/StAndrews-CPP
/Lecture-18/RatInMazeAdvance.cpp
UTF-8
1,466
3.484375
3
[]
no_license
// RatInMazeAdvance #include <iostream> using namespace std; bool RatInMaze(char maze[][10],bool visited[][10],int sol[][10],int n,int m,int i,int j){ // base case if( i == n-1 and j == m-1){ sol[i][j] = 1; // Print the solution for(int i = 0 ; i < n ; i++){ for(int j = 0 ; j < m ; j++){ cout<<sol[i][j]<<' '; } cout<<endl; } cout<<endl; sol[i][j] = 0; return false; } // recursive case sol[i][j] = 1; visited[i][j] = true; // Check Right if(j+1<m and !visited[i][j+1] and maze[i][j+1]!='X'){ bool KyaRightSeMilla = RatInMaze(maze,visited,sol,n,m,i,j+1); if(KyaRightSeMilla){ return true; } } // Check down if(i+1<n and !visited[i+1][j] and maze[i+1][j]!='X'){ bool KyaNeecheRaastaMilla = RatInMaze(maze,visited,sol,n,m,i+1,j); if(KyaNeecheRaastaMilla){ return true; } } // check left if(j-1>=0 and !visited[i][j-1] and maze[i][j-1]!='X'){ bool KyaLeftSeRaastaMilla = RatInMaze(maze,visited,sol,n,m,i,j-1); if(KyaLeftSeRaastaMilla){ return true; } } // check top if(i-1>=0 and !visited[i-1][j] and maze[i-1][j]!='X'){ bool KyaTopSeRaastaMilla = RatInMaze(maze,visited,sol,n,m,i-1,j); if(KyaTopSeRaastaMilla){ return true; } } sol[i][j] = 0; visited[i][j] = false; return false; } int main(){ char maze[][10]={ "00000", "0XXX0", "000X0", "0X0X0", "000X0" }; bool visited[10][10]={0}; int sol[10][10]={0}; RatInMaze(maze,visited,sol,5,5,4,2); return 0; }
true
20f9e0de7b7ab80ba9ef8f0d1121dfb6a03e34eb
C++
nurlingo/Codeforces
/BadSequence.cpp
UTF-8
721
3.234375
3
[]
no_license
#include <iostream> #include <math.h> using namespace std; int main() { int n, openCount, closedCount, outOfOrderCount; cin >> n; openCount = 0; closedCount = 0; outOfOrderCount = 0; string answer = "Yes"; for (int i = 0; i < n; i++) { char bracket; cin >> bracket; // read input and build squares' size matrix if (bracket == '(') { openCount++; } else { closedCount++ } if (closedCount - openCount > outOfOrderCount { outOfOrderCount++; } } if (outOfOrderCount > 1 || openCount - closedCount != 0 ) answer = "No" cout << answer; return 0; }
true
58c5a30a6e67db27faae3f84c020161c4caa3b66
C++
osmarbraz/lista_sequencia_oo_cpp
/main.cpp
UTF-8
7,220
3.9375
4
[ "MIT" ]
permissive
/** * Implementação de Lista Sequencial de forma orientada a objeto. * */ //Declaração de bibliotecas #include <cstdlib> #include <iostream> #include <string> //Inclui o cabeçalho da classe Lista #include "Lista.h" using namespace std; /** * Realiza a leitura dos dados dos nós. * * @return O valor lido. */ int leitura() { cout << "\nDigite um valor: "; int valor = 0; cin >> valor; return valor; } /** * Programa principal. * * @param argc * @param argv */ int main(int argc, char** argv) { /** * Declara e instancia a lista. */ Lista lista; // Controla o menu da lista int opcao = -1; //Laço do menu de opções while (opcao != 99) { //Monta o menu de opções cout << "\n\t### Lista Sequencial ###\n" << "Selecione a opção desejada:\n" << " 1- Listar Nós\n" << " 2- Inserir Nó no início\n" << " 3- Inserir Nó em uma posição especifica\n" << " 4- Inserir Nó no fim\n" << " 5- Inserir Nó ordenado\n" << " 6- Remover Nó do início\n" << " 7- Remover Nó de uma posição específica\n" << " 8- Remover Nó do fim\n" << " 9- Remover Nó pelo valor\n" << "10- Procurar o dado de uma posição específica\n" << "11- Procurar a posição de um dado\n" << "12- Mostrar a quantidade de Nós\n" << "13- Está cheia?\n" << "14- Está vazia?\n" << "99- Sair\n" << " Opcao:"; cin >> opcao; switch (opcao) { case 1: { if (lista.estaVazia()) { cout << "\nLista vazia!" << endl; } else { cout << "\nListagem \n" << lista.listar() << endl; } break; } case 2: { //Preenche o valor do dado int dado = leitura(); if (lista.inserirInicio(dado) == true) { cout << "\nNó inserido no início com Sucesso!" << endl; } else { cout << "\nNó não inserido no início!" << endl; } break; } case 3: { int k; cout << "\nDigite a posição a ser inserido:"; cin >> k; //Preenche o valor do dado int dado = leitura(); if (lista.inserirPosicao(dado, k) == true) { cout << "\nNó inserido na posição " << k << " com Sucesso!" << endl; } else { cout << "\nNó não inserido na posição " << k << "!" << endl; } break; } case 4: { //Preenche o valor do dado int dado = leitura(); if (lista.inserirFim(dado) == true) { cout << "\nNó inserido no fim com Sucesso!" << endl; } else { cout << "\nNó não inserido no fim!" << endl; } break; } case 5: { //Preenche o valor do dado int dado = leitura(); if (lista.inserirOrdenado(dado) == true) { cout << "\nNó inserido ordenado com Sucesso!" << endl; } else { cout << "\nNó não inserido ordenado!" << endl; } break; } case 6: { if (lista.excluirInicio()) { cout << "\nNó do início foi excluído com Sucesso!" << endl; } else { cout << "\nNó do início não foi excluído!" << endl; } break; } case 7: { int k; cout << "\nDigite a posição a ser excluída:"; cin >> k; if (lista.excluirPosicao(k)) { cout << "\nO valor da posição " << k << " foi excluído com Sucesso!" << endl; } else { cout << "\nValor não foi excluído!" << endl; } break; } case 8: { if (lista.excluirFim()) { cout << "\nNó do fim foi excluído com Sucesso!" << endl; } else { cout << "\nNó do fim não foi excluído!" << endl; } break; } case 9: { //Preenche o valor do dado int dado; cout << "\nDigite o valor do dado a ser excluído:"; cin >> dado; if (lista.excluirValor(dado)) { cout << "\nO valor " << dado << " foi excluído com Sucesso!" << endl; } else { cout << "\nValor não foi excluído!" << endl; } break; } case 10: { int k; cout << "\nDigite a posição do dado a ser procurada:"; cin >> k; int dado = lista.procurarPosicao(k); if (dado != -1) { cout << "\nO valor da posição " << k << " possui o dado = " << dado << endl; } else { cout << "\nA posição " << k << " não está preenchida" << endl; } break; } case 11: { int chave; cout << "\nDigite o valor do dado a ser procurado:"; cin >> chave; int posicao = lista.procurarValor(chave); cout << "\nO valor " << chave << " esta na posição " << posicao << endl; break; } case 12: { cout << "\nQuantidade de Nós na lista : " << lista.getQuantidade() << endl; break; } case 13: { cout << "\nLista está cheia : " << lista.estaCheia() << endl; break; } case 14: { cout << "\nLista está vazia : " << lista.estaVazia() << endl; break; } //Opção de saída do programa case 99: { cout << "\nSaindo do programa!"; break; } //Opção inválida do menu default: { cout << "\nOpção inválida!"; break; } }//Fim switch }//Fim while return 0; }//Fim main
true
94e40e54e3103ce2f1641f523b4422e502598c81
C++
dmzld/algorithm
/BOJ/samsung/19236_청소년상어.cpp
UTF-8
2,184
3.125
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; pair<int, int> map[4][4]; // <number of fish, direction> pair<int, int> dir[8] = { { -1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 }, { 1, 0 }, { 1, 1 }, { 0, 1 }, { -1, 1 } }; // <dy, dx> int ans = 0; void rotateFish(int sy, int sx){ // current location of shark int y, x; // location of current fish // fish move by order for (int n = 1; n <= 16; n++){ y = -1, x = -1; // find current order fish for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) if (map[i][j].first == n) y = i, x = j; // if fish 'n' is already eaten, find next fish if (y == -1 && x == -1) continue; // find block where fish can move until one round for (int i = 0; i < 8; i++){ // 8 dir int cDir = (map[y][x].second + i) % 8; int ny = y + dir[cDir].first, nx = x + dir[cDir].second; // out of range, shark area if (ny < 0 || ny >= 4 || nx < 0 || nx >= 4 || (ny == sy&&nx == sx)) continue; // move & change pair<int, int> tmp = map[ny][nx]; map[ny][nx] = { map[y][x].first, cDir }; map[y][x] = tmp; break; } } return; } void dfs(int y, int x, int d, int tot){ // location (y,x) of shark, direction of shark, sum of the fish number eaten pair<int, int> cmap[4][4]; int ny = y, nx = x; if (ans < tot) ans = tot; // check of eaten fish map[y][x] = { -1, -1 }; rotateFish(y, x); // save current map for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) cmap[i][j] = map[i][j]; // find next fish ny += dir[d].first, nx += dir[d].second; while (ny >= 0 && ny < 4 && nx >= 0 && nx < 4){ // next dfs if (map[ny][nx].first != -1){ dfs(ny, nx, map[ny][nx].second, tot + map[ny][nx].first); // restore current map for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) map[i][j] = cmap[i][j]; } ny += dir[d].first, nx += dir[d].second; } return; } int main(){ ios::sync_with_stdio(0); cin.tie(0); for (int i = 0; i < 4; i++){ for (int j = 0; j < 4; j++){ int a, b; cin >> a >> b; map[i][j] = { a, b - 1 }; } } dfs(0, 0, map[0][0].second, map[0][0].first); cout << ans; return 0; }
true
81e25cda9b68725412ec854ea49e27fc7aa58078
C++
irfansofyana/cp-codes
/04 - Competitions/ngoding_Seru/C.cpp
UTF-8
987
2.53125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int idx,spasi,n,i,j; string s,temp,ans; bool cek(string s){ int it,angka; int kcl; angka = 0; kcl = 0; for (it = 0; it<s.size(); it++) { if (s[it]>='0' && s[it]<='9') angka++; else if (s[it]>='a' && s[it]<='z') kcl++; } if (kcl>=3 && angka>=1) return true; return false; } int main(){ getline(cin,s); spasi = s.find(" ",0); ans = "-1"; while (spasi>=0 && spasi<s.size()) { temp = s.substr(idx,spasi-1-idx+1); //cout << temp << '\n'; if (cek(temp)) { if (ans=="-1") ans = temp; else if ((int)temp.size()>(int)ans.size()) ans = temp; } idx = spasi+1; spasi = s.find(" ",idx); } temp = s.substr(idx,s.size()-1-idx+1); //cout << temp << '\n'; if (cek(temp)) { if (ans=="-1") ans = temp; else if ((int)temp.size()>(int)ans.size()) ans = temp; } if (ans=="-1") cout << "NO" << '\n'; else { cout << ans << '\n'; cout << ans.size() << '\n'; } return 0; }
true
fff06368956a1e1535b523ad62cc7fd73fa1a907
C++
vivekmalik2609/Golf-Cart
/Arduino Codes/Speed_Control_Rotary_Encoder_ROS/Speed_Control_Rotary_Encoder_ROS.ino
UTF-8
2,854
2.765625
3
[]
no_license
#include<SPI.h> #include <ros.h> #include <geometry_msgs/Twist.h> //Encoder interupt attachments int EncoderR_A = 0; //pin 2 int EncoderR_B = 5; //pin 18 int EncoderL_A = 1; //pin 3 int EncoderL_B = 4; //pin 19 volatile int CountR = 0; volatile int CountL = 0; float CountAvg = 0; //sampling rate int T = 10; //(millisecond) //diameters in inch float EncRatio = 3.400166; //ratio of wheel revolutions to encoder revolutions through calibration float CircumWheel = 1.372; //(m) //speeds float rpmEnc = 0; //(rpm) float rpmWheel = 0; //(rpm) float cartSpeed = 0; //(m/s) //PID control variables float desired; float kp = 20; float ki = 10; float kd = .1; //fake tuning float prev = 0; float integral; float time; //get speed from python variables int sp; //Output to motor variables byte address = 0x00; int chipsel = 53; //ros setup ros::NodeHandle nh; // initiating the callback function for the subscriber void messageCb( const geometry_msgs::Twist& msg){ desired=msg.linear.x; } //attaching the subscriber and publisher ros::Subscriber<geometry_msgs::Twist> sub("cmd_vel", messageCb ); geometry_msgs::Twist str_msg; ros::Publisher chatter("actual_speed", &str_msg); void setup() { //setup ISR for encoders attachInterrupt(EncoderR_A, ISRR, RISING); attachInterrupt(EncoderL_A, ISRL, RISING); //setup motor communication (digital potentiometer) pinMode(13, OUTPUT); Serial.begin(9600); pinMode(chipsel, OUTPUT); SPI.begin(); // ROS setup nh.initNode(); nh.subscribe(sub); nh.advertise(chatter); //Serial.println("Ready"); } void loop() { sp = motor_control(); //call motor control function to get new input speed writeToMotor(sp); //write to motor // storing the actual spped and publishing it on ROS str_msg.linear.x= cartSpeed; chatter.publish( &str_msg ); //rest nh.spinOnce(); } void writeToMotor(float sp){ Serial.println(sp); digitalWrite(chipsel, LOW); SPI.transfer(address); SPI.transfer(sp); digitalWrite(chipsel, HIGH); } float motor_control(){ float actual = measure(); float error = desired-actual; float dt = millis()/1000.0-time; integral = integral + error*dt; float der = (error-prev)/dt; int control = kp*error + ki*integral + kd*der; prev = error; time = millis()/1000.0; // control boundaries //MCP4151 IC is 7-bit: 0-127 //MCP4151 IC is 8-bit: 0-255 if (control > 127){ control = 127; } if (control < 0){ control = 0; } return control; } float measure(){ CountR = 0; CountL = 0; delay(T); CountAvg = (CountR+CountL)/2; //Serial.print(CountAvg); rpmEnc = 60.0*(CountAvg/1024.0)/(T/1000.0); rpmWheel = rpmEnc/(EncRatio); cartSpeed = rpmWheel*CircumWheel; return cartSpeed; } //ISR for left and right wheel void ISRL() { CountL++; } void ISRR(){ CountR++; }
true
7a5c81a7c73cb6a993397053f692a8635fbdd2e7
C++
zerozez/metricspp
/include/metricspp/modifier.hpp
UTF-8
1,617
3.265625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef L_METRICSPP_MODIFIER_HPP #define L_METRICSPP_MODIFIER_HPP #include <list> #include <memory> #include <string> // \brief Library namespace namespace metricspp { class MetricsModifierPrivate; /** MetricsModifier class * * Class for configuring a data queue for sending in databases. It allows * to simplify input over the same connection without write measurement * and it variables names everytime. * */ class MetricsModifier { public: MetricsModifier() = delete; /** MetricsModifier constructor * * General class constructor for \a measure name and it \a vqueue , * variable names queue. If vqueue is empty it will add default `value` * name in the list. * * Pass in invalid measure or variables names leads to throwing * std::invalid_argument * * @param measure Measurement name * @param vqueue List of measurement's variables. Order of them keeps the same * as it comes in. */ MetricsModifier(const std::string &measure, const std::initializer_list<std::string> &vqueue = {}); virtual ~MetricsModifier(); /** Measure method * * Get measure's name of this object. * * @return Name as a string */ std::string measure() const; /** Variables name queue * * Returns a queue of variables names of the metric * * @return List of variables names */ std::list<std::string> queue() const; private: std::string m_measure; ///< Measure name std::list<std::string> m_queue; ///< Measure's variables queue }; } #endif // L_METRICSPP_MODIFIER_HPP
true
70c5deb9bb685155ea29f71202991cec1f0ef243
C++
NorieM/tictactoe
/ttt.cpp
UTF-8
295
2.75
3
[]
no_license
#include <iostream> #include <vector> #include "functions.hpp" int main() { bool play_game=true; std::string play_again; while (play_game) { start_game(); std::cout<<"Do you want to play again (Y/N)?"; std::cin>>play_again; play_game = tolower(play_again[0])=='y'; } }
true
5372c62fcea53ee8455c11f4927ed68e26c57f5d
C++
jnxyatmjx/LeetCode
/submit/450.delete-node-in-a-bst.cpp
UTF-8
1,792
3.609375
4
[]
no_license
/* * @lc app=leetcode id=450 lang=cpp * * [450] Delete Node in a BST */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void delNode(TreeNode* root) { if(root == NULL) return; delete root;root = NULL; } TreeNode* findMin(TreeNode* root) { if(root == NULL) return NULL; while(root->left) root = root->left; return root; } TreeNode* deleteNode(TreeNode* root, int key) { if(root == NULL) return NULL; if(root->val == key) { //double leaves at this root if(root->left && root->right) { TreeNode* cur = findMin(root->right); //find minimum node of right subtree root->val = cur->val; root->right = deleteNode(root->right,root->val); }else // one or none leaf at this root { struct TreeNode* cur = root; if(cur->left == NULL) root = cur->right; if(cur->right == NULL) root = cur->left; delNode(cur); //recursive process can insert into the original tree } }else if(root->val > key) { root->left = deleteNode(root->left,key); }else{ root->right = deleteNode(root->right,key); } return root; } }; // @lc code=end
true
363498874d3b8a6571245f0bb83d4875aa2e9eac
C++
Sadia1116/CG
/CG lab/learn/main.cpp
UTF-8
6,998
2.640625
3
[]
no_license
/* * GLUT Shapes Demo * * Written by Nigel Stewart November 2003 * * This program is test harness for the sphere, cone * and torus shapes in GLUT. * * Spinning wireframe and smooth shaded shapes are * displayed until the ESC or q key is pressed. The * number of geometry stacks and slices can be adjusted * using the + and - keys. */ /* * GLUT Shapes Demo * * Written by Nigel Stewart November 2003 * * This program is test harness for the sphere, cone * and torus shapes in GLUT. * * Spinning wireframe and smooth shaded shapes are * displayed until the ESC or q key is pressed. The * number of geometry stacks and slices can be adjusted * using the + and - keys. */ #include<windows.h> #ifdef _APPLE_ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif #include <stdlib.h> void init() { glClearColor(0.0f,0.0f,0.0f,0.0f); glOrtho(-5,+5,-10,+10,-5,+5); } void myDisplay() { glClear(GL_COLOR_BUFFER_BIT); /* glPushMatrix(); glTranslated(0,7,0); glBegin(GL_POLYGON); //ghor er uporer part glVertex2d(1,0); glVertex2d(1,-1); glVertex2d(-1,-1); glVertex2d(-1,0); glEnd(); glPopMatrix(); //ghor er 2ndpart glPushMatrix(); glTranslated(0,6,0); glBegin(GL_POLYGON); glColor3f(0.22,0.38,0.80); glVertex2d(1,0); glColor3f(0.6,0.19,0.80); glVertex2d(1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,0); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0,4,0); glBegin(GL_POLYGON); //ghor er 3rd part glColor3f(0.74,0.74,0.74); glVertex2d(1,0); glVertex2d(1,-1); glVertex2d(-1,-1); glVertex2d(-1,0); glEnd(); glPopMatrix(); //ghor er 4thpart glPushMatrix(); glTranslated(0,3,0); glBegin(GL_POLYGON); glColor3f(0.22,0.38,0.80); glVertex2d(1,0); glColor3f(0.6,0.19,0.80); glVertex2d(1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,0); glEnd(); glPopMatrix(); //ghor er janala glPushMatrix(); glTranslated(-0.5,2,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.1,0.2); //glColor3f(0.93,0.22,0.54); glVertex2d(-0.1,0.2); //glColor3f(1,0.75,0.14); glVertex2d(-0.1,-0.2); //glColor3f(0.18,0.54,0.38); glVertex2d(0.1,-0.2); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0.5,2,0); glBegin(GL_POLYGON); //ghor er janala glColor3f(1,1,1); glVertex2d(0.1,0.2); glVertex2d(-0.1,0.2); glVertex2d(-0.1,-0.2); glVertex2d(0.1,-0.2); glEnd(); glPopMatrix(); //ghor er dorja glPushMatrix(); glTranslated(0,1,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.2,0.85); glVertex2d(-0.2,0.85); glColor3f(1,0.75,0.14); glVertex2d(-0.2,-0.85); glVertex2d(0.2,-0.85); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0,0.5,0); glBegin(GL_POLYGON); //ghor er 3rd part glColor3f(0.74,0.74,0.74); glVertex2d(1,0); glVertex2d(1,-1); glVertex2d(-1,-1); glVertex2d(-1,0); glEnd(); glPopMatrix(); //ghor er 2ndpart glPushMatrix(); glTranslated(0,0.01,0); glBegin(GL_POLYGON); glColor3f(0.22,0.38,0.80); glVertex2d(1,0); glColor3f(0.6,0.19,0.80); glVertex2d(1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,0); glEnd(); glPopMatrix(); //ghor er janala glPushMatrix(); glTranslated(-0.50,-1,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.1,0.2); glVertex2d(-0.1,0.2); glVertex2d(-0.1,-0.2); glVertex2d(0.1,-0.2); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0.50,-1,0); glBegin(GL_POLYGON); //ghor er janala glColor3f(1,1,1); glVertex2d(0.1,0.2); glVertex2d(-0.1,0.2); glVertex2d(-0.1,-0.2); glVertex2d(0.1,-0.2); glEnd(); glPopMatrix(); //ghor er dorja glPushMatrix(); glTranslated(0.0,-2,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.2,0.85); glVertex2d(-0.2,0.85); glColor3f(1,0.75,0.14); glVertex2d(-0.2,-0.85); glVertex2d(0.2,-0.85); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0.0,-2.85,0); glBegin(GL_POLYGON); //ghor er 3rd part glColor3f(0.74,0.74,0.74); glVertex2d(1,0); glVertex2d(1,-1); glVertex2d(-1,-1); glVertex2d(-1,0); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0,-3.55,0); glBegin(GL_POLYGON); glColor3f(0.22,0.38,0.80); glVertex2d(1,0); glColor3f(0.6,0.19,0.80); glVertex2d(1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,-3); glColor3f(0.6,0.19,0.80); glVertex2d(-1,0); glEnd(); glPopMatrix(); glPushMatrix(); glTranslated(0.0,-5.70,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.4,0.85); glVertex2d(-0.4,0.85); glColor3f(1,0.75,0.14); glVertex2d(-0.4,-0.85); glVertex2d(0.4,-0.85); glEnd(); //ghor er dorja glPushMatrix(); glTranslated(0,10.5,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(0.2,0.85); glVertex2d(-0.2,0.85); glColor3f(1,0.75,0.14); glVertex2d(-0.2,-0.85); glVertex2d(0.2,-0.85); glEnd();*/ //rectangle glPushMatrix(); glTranslated(-2,2,0); glBegin(GL_QUADS); glColor3f(1,1,0); glVertex2d(1,0); glVertex2d(2,0); glVertex2d(2,2); glVertex2d(1,2); glEnd(); glPushMatrix(); glTranslated(-3,2,0); glBegin(GL_POLYGON); glColor3f(1,1,1); glVertex2d(1,0); glVertex2d(1.5,2); glVertex2d(1,2); glEnd(); glPopMatrix(); glFlush(); } int main() { glutInitWindowSize(1200,800); glutInitWindowPosition(10,10); glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE); glutCreateWindow("First Lab"); init(); glutDisplayFunc(myDisplay); glutMainLoop(); return 0; }
true
f80f45925df371a05a666d8d6f34ba05437409ec
C++
Khairul-Anam-Mubin/LightOJ-Solutions
/Number Theory/1109 - False Ordering.cpp
UTF-8
839
2.703125
3
[]
no_license
#include <bits/stdc++.h> using namespace std ; #define mxN 1000 long long v[mxN + 5] ; void DivSieve() { for(int i = 1 ; i <= mxN ; i++) { for(int j = i ; j <= mxN ; j += i) { v[j]++ ; // counting number of divisors of j } } } bool cmp(pair<int, int> &a , pair<int , int> &b) { if(a.first == b.first) return (a.second > b.second) ; else return (a.first < b.first) ; } int main() { DivSieve() ; vector <pair <int , int>> vec ; for(int i = 1 ; i <= mxN ; i++) { vec.push_back(make_pair(v[i] , i)) ; } sort(vec.begin() , vec.end() , cmp) ; int tc , test = 0 ; cin >> tc ; while(tc--) { long long n ; cin >> n ; cout << "Case " << ++test << ": " ; cout << vec[n - 1].second << "\n" ; } return 0 ; }
true
7c6f7c5e14855fe4342065fa35726687262f3cd7
C++
schiebermc/CP_Lib
/HackerRank/Practice/InterviewPrep/DynamicProgramming/MaxArraySum/code.cpp
UTF-8
1,224
2.75
3
[]
no_license
//#include <bits/stdc++.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <math.h> #include <map> #include <set> #include <climits> using namespace std; typedef long long int ll; void solution(ll n, vector<ll> a){ map<ll, ll> stuff; // init the first two. if(n >= 1) stuff[0] = a[0]; if(n >= 2) stuff[1] = a[1]; // get a starting point ll best; if(n >= 2) best = max(stuff[0], stuff[1]); else best = stuff[0]; // O(N) for(ll i=2; i<n; i++) { // get the best sum up to this point ll tmp = LONG_MIN; for(ll j=i-3; j<=i-2; j++) { // check only the back two if(j < 0) continue; if(stuff[j] > tmp) tmp = stuff[j]; } stuff[i] = max(a[i], a[i] + tmp); // apply the best stuff[i] = max(stuff[i], tmp); best = max(best, stuff[i]); } printf("%lld\n", best); } int main() { // variables ll n; cin >> n; vector<ll> arr; arr.resize(n); for(ll i=0; i<n; i++) { scanf("%lld", &arr[i]); } //validation(0, 10, 10) solution(n, arr); return 0; }
true
94b76f5efcf7a21edb0b44ce13e4b16b75ea236c
C++
gunner14/old_rr_code
/main_project/feed/cwf_feed/dynalib.h
UTF-8
409
2.546875
3
[]
no_license
#ifndef CWF_DYNAMIC_LIBRARY_H__ #define CWF_DYNAMIC_LIBRARY_H__ #include <string> namespace cwf { struct DynamicLibrary { public: DynamicLibrary(const std::string& filename) : filename_(filename) , handle_(0) {} bool Load(); void Close(); void* GetProc(const char* name); private: std::string filename_; void* handle_; }; } #endif // CWF_DYNAMIC_LIBRARY_H__
true
9c92c0435c71be46f33b2146d5c68170e58c8a9f
C++
joseAugustoCR/CG-T4
/src/Carro.h
ISO-8859-1
2,350
2.921875
3
[]
no_license
/** TRABALHO 4 DE COMPUTACAO GRFICA: AUTORAMA USANDO BPLINE 3D JOS AUGUSTO COMIOTTO ROTTINI - 201120279 ENGENHARIA DE COMPUTAO - UFSM Classe para criao e configurao carro. **/ #include <gl/glut.h> //gl utility toolkit #include <gl/gl.h> //gl utility #include <math.h> #include "Ponto3D.h" #include "Vetor.h" class Carro{ public: int indexPosicaoCarro; Ponto3D posicaoDoCarroNaPista; float velocidade; float deslocamentoLateral; float r,g,b; Carro() { indexPosicaoCarro=0; posicaoDoCarroNaPista=Ponto3D(0,0,0); velocidade=0; deslocamentoLateral=0; } void setCor(float red, float green, float blue){ r = red; g = green; b = blue; } void setVelocidade(int v){ velocidade = v; } void draw() { glColor3f(r,g,b); glBegin(GL_QUADS); // Face posterior glNormal3f(0.0, 0.0, -1.0); // Normal da face glVertex3f(5.0, 5.0, -10.0); glVertex3f(-5.0, 5.0, -10.0); glVertex3f(-5.0, -5.0, -10.0); glVertex3f(5.0, -5.0, -10.0); glEnd(); glBegin(GL_QUADS); // Face frontal glNormal3f(0.0, 0.0, 1.0); // Normal da face glVertex3f(5.0, 5.0, 10.0); glVertex3f(-5.0, 5.0, 10.0); glVertex3f(-5.0, -5.0, 10.0); glVertex3f(5.0, -5.0, 10.0); glEnd(); glBegin(GL_QUADS); // Face lateral esquerda glNormal3f(1.0, 0.0, 0.0); // Normal da face glVertex3f(5.0, 5.0, -10.0); glVertex3f(5.0, 5.0, 10.0); glVertex3f(5.0, -5.0, 10.0); glVertex3f(5.0, -5.0, -10.0); glEnd(); glBegin(GL_QUADS); // Face lateral direita glNormal3f(-1.0, 0.0, 0.0); // Normal da face glVertex3f(-5.0, 5.0, -10.0); glVertex3f(-5.0, 5.0, 10.0); glVertex3f(-5.0, -5.0, 10.0); glVertex3f(-5.0, -5.0, -10.0); glEnd(); glBegin(GL_QUADS); // Face superior glNormal3f(0.0, 1.0, 0.0); // Normal da face glVertex3f(-5.0, 5.0, -10.0); glVertex3f(-5.0, 5.0, 10.0); glVertex3f(5.0, 5.0, 10.0); glVertex3f(5.0, 5.0, -10.0); glEnd(); glBegin(GL_QUADS); // Face inferior glNormal3f(0.0, -1.0, 0.0); // Normal da face glVertex3f(-5.0, -5.0, -10.0); glVertex3f(-5.0, -5.0, 10.0); glVertex3f(5.0, -5.0, 10.0); glVertex3f(5.0, -5.0, -10.0); glEnd(); } };
true
03454231921d38bb8638afd9a6ec5da7aa548150
C++
DNovotny1/CIS2013_Week3_Quiz01
/quiz1.cpp
UTF-8
493
4.40625
4
[]
no_license
/* ask for 2 numbers, ask if + or*, print output, repeat*/ #include<iostream> using namespace std; int main() { //hold numeric values and sign for operator int num1, num2; char sign; while(true) { cout << "Enter first digit."; cin >> num1; cout << "Enter Second digit."; cin >> num2; cout << "Would you like to add or multiply(+ or *)" ; cin >> sign; if (sign == '+') { cout << num1 + num2 << "\n"; } if (sign == '*') { cout << num1 * num2 << "\n"; } } }
true
5e99bad63a009737cf79783dd27f99a11b0b1d49
C++
GSGroup/stingraykit
/stingraykit/string/StringUtils.cpp
UTF-8
732
2.625
3
[ "ISC" ]
permissive
#include <stingraykit/string/StringUtils.h> namespace stingray { std::string::size_type EditDistance(const std::string& s1, const std::string& s2) { if (s1 == s2) return 0; if (s1.empty()) return s2.size(); if (s2.empty()) return s1.size(); std::vector<std::string::size_type> v0(s2.size() + 1); std::vector<std::string::size_type> v1(s2.size() + 1); for (std::string::size_type i = 0; i < v0.size(); ++i) v0[i] = i; for (std::string::size_type i = 0; i < s1.size(); ++i) { v1[0] = i + 1; for (std::string::size_type j = 0; j < s2.size(); ++j) v1[j + 1] = std::min(std::min(v1[j] + 1, v0[j + 1] + 1), v0[j] + (s1[i] == s2[j] ? 0 : 1)); v0 = v1; } return v1[s2.size()]; } }
true
72606cd8395e6c32eee9fa75111356a251ab8529
C++
GregWagner/Modern-Cplusplus-Programming-with-Test-Driven-Development
/Chapter_02_Test_Driven_Development_A_First_Example/oldSoundex/src/Soundex.hpp
UTF-8
1,045
2.90625
3
[]
no_license
#ifndef SOUNDEX_H #define SOUNDEX_H #include <string> #include <unordered_map> class Soundex { public: std::string encode(const std::string &word) const; std::string encodedDigit(char letter) const; private: static size_t const MAX_CODE_LENGTH{4}; const std::string NOT_A_DIGIT{"*"}; std::string head(const std::string &word) const; std::string tail(const std::string &word) const; std::string upperFront(const std::string &word) const; char lower(char c) const; std::string encodedDigits(const std::string &word) const; void encodeHead(std::string &encoding, const std::string &word) const; void encodeTail(std::string &encoding, const std::string &word) const; void encodeLetter(std::string &encoding, char letter, char lastLetter) const; bool isVowel(char letter) const; std::string lastDigit(const std::string &encoding) const; bool isComplete(const std::string &encoding) const; std::string zeroPad(const std::string &word) const; }; #endif
true
6cd6cab494076009f6b5d6c955e17fba4f8cb68a
C++
connor-brooks/Wobbler
/midi.cpp
UTF-8
905
2.59375
3
[]
no_license
#include <rtMidi.h> #include "midi.h" Midi::Midi() { has_connection = false; midi_in = new RtMidiIn(); num_ports = midi_in->getPortCount(); if(num_ports == 0) { has_connection = false; return; } else { midi_in->openPort(0); midi_in->ignoreTypes(false, false, false); has_connection = true; } } void Midi::get_messages() { if(!has_connection) return; midi_in->getMessage(&msgs); num_bytes = msgs.size(); } void Midi::handle_messages() { if(num_bytes > 0 ) { if(msgs[0] == 144) { printf("NOTE %d DOWN\n", msgs[1]); keydown_callback(msgs[1]); } if(msgs[0] == 128) { printf("NOTE %d UP\n", msgs[1]); keyup_callback(msgs[1]); } } } void Midi::set_keydown_callback(std::function<void (int)> callb){ keydown_callback = callb; } void Midi::set_keyup_callback(std::function<void (int)> callb){ keyup_callback = callb; }
true
1c9caf961ac3b3cfe073d77c32a18070f5c79177
C++
liulin2012/myLeetcode
/PalindromePartitioning.cpp
UTF-8
922
3.15625
3
[]
no_license
class Solution { public: vector<vector<string>> partition(string s) { vector<vector<string>> res; if (s.empty()) return res; BFS(s, 0, res, {}); return res; } void BFS(string s, int begin, vector<vector<string>>& res, vector<string> one) { if (begin == s.size()) res.push_back(one); else { for (int i = begin; i < s.size(); i++) { if (isPalindrome(s, begin, i)) { // string tmp(s[begin], s[i + 1]); one.push_back(s.substr(begin, i - begin + 1)); BFS(s, i + 1, res, one); one.pop_back(); } } } } bool isPalindrome(const string& s, int start, int end) { while(start <= end) { if(s[start++] != s[end--]) return false; } return true; } };
true
ff8619e191b64355c0d5ce8827cd2984fff9f5eb
C++
bjut-hz/basics
/leetcode_c++/230.kth-smallest-element-in-a-bst.cpp
UTF-8
1,363
3.640625
4
[]
no_license
/* * @lc app=leetcode id=230 lang=cpp * * [230] Kth Smallest Element in a BST */ // @lc code=start /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: // int kthSmallest(TreeNode* root, int k) { // int cnt = 0; // int res = 0; // inoder(root, cnt, res, k); // return res; // } // void inoder(TreeNode* root, int& cnt, int& res, int target) { // if(NULL == root) return; // inoder(root->left, cnt, res, target); // ++cnt; // if(cnt == target) { // res = root->val; // return; // } // inoder(root->right, cnt, res, target); // } // divide and conquer int kthSmallest(TreeNode* root, int k) { int left_cnt = count(root->left); if(k <= left_cnt) { return kthSmallest(root->left, k); } else if(k > left_cnt + 1) { return kthSmallest(root->right, k - left_cnt - 1); } return root->val; } int count(TreeNode* root) { if(NULL == root) return 0; return 1 + count(root->left) + count(root->right); } }; // @lc code=end
true
5b76540f11c69e2a443adcce9d76da2b38cdb02d
C++
yay/cpp
/lambdas_adv/main.cpp
UTF-8
1,312
3.734375
4
[]
no_license
#include <iostream> #include <functional> #include <array> #include <cstdlib> // for malloc() and free() // On clang++ the size of all std::function is always 48 bytes (used to be 32 as of early 2016). // It uses what is called `small size optimization`, much like std::string does on many // implementations. This basically means that for small objects std::function can keep them // as part of its memory, but for bigger objects it defers to dynamic memory allocation. // Replace operator new and delete to log allocations. void *operator new(std::size_t n) { std::cout << "Allocating " << n << " bytes" << std::endl; return malloc(n); } void operator delete(void *p) throw() { free(p); } int main() { std::array<char, 24> arr1; auto lambda1 = [arr1](){}; std::cout << "Assigning lambda1 of size " << sizeof(lambda1) << std::endl; std::function<void()> f1 = lambda1; std::array<char, 25> arr2; auto lambda2 = [arr2](){}; std::cout << "Assigning lambda2 of size " << sizeof(lambda2) << std::endl; std::function<void()> f2 = lambda2; // Output: // Assigning lambda1 of size 24 // Assigning lambda2 of size 25 // Allocating 40 bytes // 24 bytes is the threshold beyond which std::function reverts to dynamic allocation // (on clang). }
true
722443468297268ab10cf177c8e16e3dafbcc11a
C++
Tijovanth/CompetitiveProgramming
/BinarySearchTreeUsingLinkedList.cpp
UTF-8
6,351
3.8125
4
[]
no_license
# include <iostream> # include <stdio.h> using namespace std; struct Node{ int data; struct Node * leftchild; struct Node * rightchild; }*root = NULL; struct Stack{ Node ** data; int top; int size; }; int isStackEmpty(struct Stack st){ if(st.top == -1) return 1; else return 0; } Node * stackTop(struct Stack st){ if(isStackEmpty(st)) return NULL; else return st.data[st.top]; } int isStackFull(struct Stack st){ if(st.top == st.size - 1) return 1; else return 0; } void push(struct Stack *st, Node * num){ if(isStackFull(*st)) cout << "Stack Over flow " << endl; else{ st->top++; st->data[st->top] = num; } } Node * pop(struct Stack *st){ if(isStackEmpty(*st)){ cout << "Stack Under Flow " << endl; return NULL; } else{ Node * x = st -> data[st ->top--]; // st -> top--; return x; } } //Recursive version Node * insertBinarySearchTree(struct Node *p, int key){ if(p == NULL){ Node *t = new Node; t -> data = key; t -> leftchild = t -> rightchild = NULL; return t; } if(key < p->data) p -> leftchild = insertBinarySearchTree(p -> leftchild,key); else if(key > p -> data) p -> rightchild = insertBinarySearchTree(p -> rightchild,key); return p; } //Iterative version void insertBinarySearchTreeIterative(struct Node * p, int key){ Node *t = NULL, *q = NULL; if(root == NULL){ t = new Node; t -> data = key; t -> leftchild = t -> rightchild = NULL; root = t; return; } while(p != NULL){ q = p; if(p -> data == key) return; else if(p -> data > key) p = p -> leftchild; else if(p -> data < key) p = p -> rightchild; } t = new Node; t -> data = key; t -> leftchild = t -> rightchild = NULL; if(key < q -> data) q -> leftchild = t; else q -> rightchild = t; } void DisplaySearchTreeInInorder(struct Node *p){ if(p == NULL) return; DisplaySearchTreeInInorder(p ->leftchild); cout << p -> data << " "; DisplaySearchTreeInInorder(p -> rightchild); } //Recursive version Node * SearchInBinarySearchTree(struct Node *p,int key){ if( p == NULL) return NULL; if(p -> data == key) return p; if(key < p -> data) return SearchInBinarySearchTree(p -> leftchild,key); else return SearchInBinarySearchTree(p -> rightchild,key); } int CountLevelOfNodes(struct Node *t){ int x,y; if(t != NULL){ x = CountLevelOfNodes(t -> leftchild); y = CountLevelOfNodes(t -> rightchild); if(x > y) return x + 1; else return y + 1; } return 0; } Node * InPre(struct Node * p){ while(p && p -> rightchild != NULL) p = p -> rightchild; return p; } Node * InSucc(struct Node * p){ while(p && p -> leftchild != NULL) p = p -> leftchild; return p; } //Deleting from Binary Search Tree Node * DeleteInBinarySearchTree(struct Node *p, int key){ struct Node * q; if(p == NULL) return NULL; if(p -> leftchild == NULL && p -> rightchild == NULL) { if(root == p) root = NULL; delete p; return NULL; } if(key < p -> data) p -> leftchild = DeleteInBinarySearchTree(p -> leftchild,key); else if(key > p -> data) p -> rightchild = DeleteInBinarySearchTree(p -> rightchild,key); else{ if(CountLevelOfNodes(p -> leftchild) > CountLevelOfNodes(p -> rightchild)){ q = InPre(p -> leftchild); p -> data = q -> data; p -> leftchild = DeleteInBinarySearchTree(p -> leftchild,q -> data); }else{ q = InSucc(p -> rightchild); p -> data = q -> data; p -> rightchild = DeleteInBinarySearchTree(p -> rightchild,q -> data); } } return p; } //My version void GenerateBinarySearchTree(int * a, int n){ struct Node * t = NULL; struct Node * p = NULL;struct Node * temp = NULL; int i = 1; struct Stack st; st.size = 100; st.top = -1; st.data = new Node *[100]; t = new Node; t -> data = a[0]; t -> leftchild = t -> rightchild = NULL; root = p = t; for(int i = 1; i < n; i++){ if(a[i] < p -> data){ t = new Node; t -> data = a[i]; t -> leftchild = t -> rightchild = NULL; p -> leftchild = t; push(&st,p); p = t; }else if(a[i] > p -> data){ int k = 0; while(k == 0){ temp = stackTop(st); if(temp != NULL && a[i] >temp -> data ){ p = pop(&st); }else{ k = 1; } } t = new Node; t -> data = a[i]; t -> leftchild = t -> rightchild = NULL; if(a[i] > p -> data){ p -> rightchild = t; p = t; } else{ p -> leftchild = t; push(&st,p); p = t; } }else{ continue; } } } int main(){ // struct Node * temp; // root = insertBinarySearchTree(root,30); // root = insertBinarySearchTree(root,20); // root = insertBinarySearchTree(root,40); // root = insertBinarySearchTree(root,35); // root = insertBinarySearchTree(root,25); // insertBinarySearchTreeIterative(root,30); insertBinarySearchTreeIterative(root,20); insertBinarySearchTreeIterative(root,40); // insertBinarySearchTreeIterative(root,35); // insertBinarySearchTreeIterative(root,25); // insertBinarySearchTreeIterative(root,36); // DisplaySearchTreeInInorder(root); // temp = SearchInBinarySearchTree(root,31); // if(temp) // cout << temp -> data << " " << endl; // else // cout << "No data like that " << endl; DeleteInBinarySearchTree(root,40); DisplaySearchTreeInInorder(root); // int a[] = {30,20,10,15,25,40,50,45,8}; // GenerateBinarySearchTree(a,9); // DisplaySearchTreeInInorder(root); }
true
615f63ce96ecf9ea0eec83556e8f82e6b210893f
C++
nicokinazoko/prak-algo-lanjut
/Record-Struct/program-2-4.cpp
UTF-8
606
3.40625
3
[]
no_license
#include <iostream> using namespace std; struct data_tgl { int tanggal, bulan, tahun; }; void cetak_info_tgl(struct data_tgl unit_tgl); int main() { struct data_tgl saat_proses = {13, 1, 1987}; cetak_info_tgl(saat_proses); } void cetak_info_tgl(struct data_tgl unit_tgl) { static char const *nama_bln[] = { "Kode bulan salah!", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"}; cout << unit_tgl.tanggal << " " << nama_bln[unit_tgl.bulan] << " " << unit_tgl.tahun << endl; }
true
91473a8065d25899674c005a618560130472ad71
C++
Bygius/OOP_arcade_2019
/core/include/Error.hpp
UTF-8
1,089
2.515625
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** OOP_nanotekspice_2019 ** File description: ** Error */ #ifndef ERROR_HPP_ #define ERROR_HPP_ #include <exception> #include <string> class Error: public std::exception { public: Error(const std::string &msg); virtual ~Error() throw(){} virtual const char *what() const throw(); protected: std::string error_msg; }; class LibError: public Error { public: LibError(const std::string &msg); virtual ~LibError() throw(){} virtual const char *what() const throw(); protected: std::string error_msg; }; class CoreError: public Error { public: CoreError(const std::string &msg); virtual ~CoreError() throw(){} virtual const char *what() const throw(); protected: std::string error_msg; }; class GameError: public Error { public: GameError(const std::string &msg); virtual ~GameError() throw(){} virtual const char *what() const throw(); protected: std::string error_msg; }; #endif /* !ERROR_HPP_ */
true
1bf54b3058437828415867c17cd62259d745db2c
C++
qigaiwangguilai/Algorithm-Description
/Sort_Algorithm/HeapSort.cpp
UTF-8
491
3.53125
4
[]
no_license
//堆排序 inline int childIndex(int i) { return 2*i+1; } void percolateDown(int a[],int hole,int N) { int tmp; int child; for(tmp=a[hole];childIndex(hole)<N;hole=child) { child=childIndex(hole); if(child!=N-1&&a[child]<a[child+1]) child++; if(tmp<a[child]) a[hole]=a[child]; else break; } a[hole]=tmp; } void HeapSort(int a[],int N) { for(int i=N/2;i>=0;i--) percolateDown(a,i,N); for(int j=N-1;j>0;j--) { swap(a[0],a[j]); percolateDown(a,0,j); } }
true
202a99110601f0d3de8dcf91f242c3b32381790e
C++
QinHaoChen97/VS_C
/Hot100/399.除法求值.cpp
UTF-8
2,825
3.328125
3
[]
no_license
/* * @lc app=leetcode.cn id=399 lang=cpp * * [399] 除法求值 */ // @lc code=start #include <vector> #include <unordered_map> #include <string> using namespace std; class Union //因为题解的 { private: vector<int> parent; vector<double> weight; public: //构造函数 Union(int n) { parent.resize(n); weight.resize(n); for (int i = 0; i < n; i++) { parent[i] = i; weight[i] = 1.0; } } void unionfun(int x, int y, double value) { int root_x = findp(x); int root_y = findp(y); if (root_x == root_y) //两者的根节点一样,不需要合并 { return; } //合并根节点 parent[root_x] = root_y; // 让x的根节点指向y的根节点,这样会产生一条新路径 weight[root_x] = value * weight[y] / weight[x]; // 计算新路径的值 } int findp(int id) { if (parent[id] == id) //如果一个人的根节点是自己 { return parent[id]; } int root = findp(parent[id]); //递归找到根节点 weight[id] = weight[parent[id]] * weight[id]; parent[id] = root; return parent[id]; } double isconnected(int x, int y) { int root_x = findp(x); int root_y = findp(y); if (root_x == root_y) // 属于同一个集合中,x和y可以算出倍数关系 { return weight[x] / weight[y]; } else { return -1.0; } } }; class Solution { public: vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, vector<vector<string>> &queries) { unordered_map<string, int> m; int id = 0; Union u(2 * equations.size()); for (int i = 0; i < equations.size(); i++) { if (m.find(equations[i][0]) == m.end()) { m[equations[i][0]] = id++; } if (m.find(equations[i][1]) == m.end()) { m[equations[i][1]] = id++; } u.unionfun(m[equations[i][0]], m[equations[i][1]], values[i]); //合并集,合并操作里面包含路径压缩 } vector<double> ans; // 查询 for (int i = 0; i < queries.size(); i++) { string var0 = queries[i][0]; string var1 = queries[i][1]; if (m.find(var0) == m.end() || m.find(var1) == m.end()) // 该字母存在于equations中 { ans.push_back(-1.0); } else { ans.push_back(u.isconnected(m[var0], m[var1])); } } return ans; } }; // @lc code=end
true
2bdf36f26b536ce75e24b118eacb9a9c6d850bdc
C++
mrpandya/DBMS_from_scratch
/constants/tokenizeQuery.cpp
UTF-8
488
3.046875
3
[]
no_license
using namespace std; vector<string> tokenizeString(string query, string del = " ") { int start = 0; int end = query.find(del); vector<string> tokens; while (end != -1) { tokens.push_back(query.substr(start, end - start)); start = end + del.size(); end = query.find(del, start); } tokens.push_back(query.substr(start, end - start)); return tokens; } string stripParanthesis(string query){ return query.substr(1,query.length()-2); }
true
904ef91c4aa540fc4643d746d0ab55024d6ae41e
C++
arpitarik/arpita.lab5
/lab5_q25.cpp
UTF-8
205
2.9375
3
[]
no_license
//using library #include<iostream> using namespace std; //using main function int main (){ //declaring variables int a = 1,b; //using loop while (a < 100){ if (a % 2 == 0){ cout << a << endl; } a++; } }
true
dae2bbc62aa1e6ab5fa3a5afdf11b5dbadd761fd
C++
edenhub/SwordOffer
/CPPImple/inter20.cpp
UTF-8
950
3.453125
3
[]
no_license
#include <iostream> using namespace std; void dumpMatrix(int* data,int rows,int cols){ for(int i=0;i<cols;i++){ for(int j=0;j<rows;j++) cout<<*(data+cols*i+j)<<" "; cout<<endl; } } void dump(int* data,int rows,int cols){ int n = cols-1; int s1 = 0, e1 = n; int s2 = 1, e2 = n; int s3 = n-1, e3 = 0; int s4 = n-1, e4 = 1; while(s1<=rows/2){ for(int i=s1;i<=e1;i++) cout<<*(data+cols*s1+i)<<" "; for(int i=s2;i<=e2;i++) cout<<*(data+cols*i+e1)<<" "; for(int i=s3;i>=e3;i--) cout<<*(data+cols*e2+i)<<" "; for(int i=s4;i>=e4;i--) cout<<*(data+cols*i+e3)<<" "; s1++; e1--; s2++; e2--; s3--; e3++; s4--; e4++; } } int main(){ int data[]={1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16}; dump(data,4,4); return 0; }
true
0a1d50ce9944cb6eeb2e6a95e952f478712ffc9b
C++
EdgrFA/Algoritmia
/EjerciciosEstructuras/listas/reverseLinkedList.cpp
UTF-8
579
3.390625
3
[]
no_license
//https://www.hackerrank.com/challenges/reverse-a-linked-list/problem #include <bits/stdc++.h> using namespace std; struct SinglyLinkedListNode { int data; SinglyLinkedListNode* next; }; SinglyLinkedListNode* reverse(SinglyLinkedListNode* head) { if(head == NULL) return head; SinglyLinkedListNode* auxNode = NULL; SinglyLinkedListNode* auxHead = head->next; head->next = NULL; while(auxHead){ auxNode = auxHead; auxHead = auxHead->next; auxNode->next = head; head = auxNode; } return head; }
true
247e20e8a68059b9dbc86b74fcbe87c715d8920c
C++
tfcpanda/cBaseExercises
/cBasicExercises13/ecperiment_1.cpp
GB18030
924
3.671875
4
[]
no_license
#include <stdio.h> #include<math.h> /* ҪʵһжһλNǷ ȫƽλͬ144676ȡ */ int IsTheNumber ( int n); int main() { int n1, n2, i, cnt; scanf("%d %d", &n1, &n2); cnt = 0; for ( i=n1; i<=n2; i++ ) { if ( IsTheNumber(i)!=0) cnt++; } printf("%d\n",cnt); return 0; } int IsTheNumber ( int n) { int N=n; int b; int p[10]={0}; //һ int m=sqrt(N); // if(m*m==n){ //жǷΪȫƽ while(n){ //n1ѭȥ b=n%10; //ȡһλ p[b]++; //0~9Ӧּ1 n/=10; //ȥһλ } for(int i=0;i<=9;i++){ //ijһλ1˵λͬ if(p[i]>1) return 1; } } return 0; }
true
dcaabf3ea33d458120ea0369a3eb224a7e71d650
C++
SeanArmstrong/GameDev
/GameDev/ShaderManager.cpp
UTF-8
869
2.859375
3
[]
no_license
#include "ShaderManager.h" ShaderManager::ShaderManager() { } ShaderManager::~ShaderManager() { for (map<string, Shader*>::iterator i = shaders.begin(); i != shaders.end(); ++i){ delete i->second; } } Shader* ShaderManager::GetShader(const std::string shaderName){ map<string, Shader*>::iterator i = shaders.find(shaderName); if (i != shaders.end()){ return i->second; } return NULL; } Shader* ShaderManager::AddShader(const std::string shaderName, const std::string vertex, const std::string fragment, const std::string geometry, const std::string tcs, const std::string tes){ Shader* shader = GetShader(shaderName); if (shader == NULL){ const string PATH = "assets/Shaders/"; // TODO: Allow for geo, tcs and tes shader = new Shader(PATH + vertex, PATH + fragment); shaders.insert(make_pair(shaderName, shader)); } return shader; }
true
d9ca89482b368dac27f5d11d3202e58d01fda3d6
C++
jacobhmurphy/cpp-esst-careerchangers
/oddnumbers.cpp
UTF-8
222
2.546875
3
[]
no_license
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { for (auto i = 0; i <= 100; i++) { if (i % 2 != 0) { cout << i << " "; } } return 0; }
true
8e337590166bf0862a4fc6b5a9c52cea519dda48
C++
heyzqq/Cpp-Back-Syntax
/3Class/27 - 动态绑定 .cpp
UTF-8
920
3.84375
4
[]
no_license
#include <iostream> using namespace std; /* 动态绑定(多态) * 从派生类到基类的转换 * 引用或指针既可以指向基类对象, 也可以指向派生类对象 * 只有通过引用或指针调用虚函数才会发生动态绑定 */ class Father { public : void func_1(){ cout << "Father: func_1" << endl; } virtual void Func_2(){ cout << "Father: func_2" << endl; } }; class Sun : public Father { public : void func_1(){ cout << "Sun: func_1" << endl; } virtual void Func_2(){ cout << "Sun: func_2" << endl; } }; int main() { Father *f = new Father; Father *s = new Sun; // 普通函数, 导致名称遮掩 f->func_1(); s->func_1(); cout << endl; // 虚函数才使用的是动态绑定,其他的全部是静态绑定。 f->Func_2(); s->Func_2(); return 0; }
true
311722a571721f6f2589a94d912ec4fc0102da15
C++
RedOni3007/Itsukushima
/Itsukushima/Resource/Model.h
UTF-8
1,322
2.5625
3
[]
no_license
/* * mesh + material + other data for rendering * todo:write a better description, it's hard * * @author: Kai Yang */ #ifndef MODEL_H #define MODEL_H #include <Core/CoreHeaders.h> #include <Game/GameObjectComponent.h> #include <Resource/Mesh.h> #include <Render/RenderManager_Defines.h> class Model : public GameObjectComponent { public: Model(); virtual ~Model(); public: void SetMesh(RefCountPtr<Mesh> pMesh); Mesh* GetMesh();//weak link void SetMaterialIndex(uint32 uMaterialIndex); void SetMaterial(const char* pszName); int32 GetMaterialIndex(); std::vector<Vector3>* GetVerticesCache(); virtual void LogicUpdate(); virtual void GraphicUpdate(); virtual const char* GetName(); static const char* ClassName(); void SetTransparency(float32 fTransparency); float32 GetTransparency(); void SetTintColor(Vector4 vColor); Vector4 GetTintColor(); bool IsRenderPassEnabled(RenderPass nPass); void SetRenderPass(RenderPass nPass, bool bEnable); private: bool m_bVerticesCached; std::vector<Vector3> m_meshVerticesCache; RefCountPtr<Mesh> m_pMesh; uint32 m_uMaterialIndex; //contorl color over material, so same material object can be in different color Vector4 m_vTintColor;//alpha only working in transparent pass int32 m_nRenderPassFlags; void RecalculteVerticesCache(); }; #endif
true
f22359ad7edafe49b8865fbb9663d56fe83fd2ce
C++
yw14218/C-Compiler
/include/Function_call/functioncall.hpp
UTF-8
4,863
2.671875
3
[]
no_license
#ifndef FUNCTIONCALL_HPP #define FUNCTIONCALL_HPP #include"Statement.hpp" #include"Statementlist.hpp" extern std::string Funcnameadd; extern std::vector<std::string> Funcname; extern int NumVariables; extern bool mainflag; class functioncall : public Statement{ public: virtual ~functioncall(){}; functioncall(Statementptr p1){left = p1;} functioncall(Statementptr p1, Statementptr p2){left = p1 ; right = p2;} Statementptr get_id(){return left;} Statementptr get_argument(){return right;} virtual void translate(std::ostream &dst,std::string indent, bool &addglobal, std::vector<std::string> &globalvariables)const override{ if(right!=NULL){ dst << indent; left -> translate(dst,"",addglobal,globalvariables); dst << "("; right -> translate(dst,"",addglobal,globalvariables); dst << ")"; } else{dst << indent; left -> translate(dst,indent,addglobal,globalvariables); dst << "()";} } virtual void treeprint(std::ostream &dst, std::string indent)const override { dst<<indent<<"<Functioncall> ["<<'\n'; left->treeprint(dst, indent+" "); if(right != NULL) {right->treeprint(dst, indent+" ");} dst<<indent<<"]"<<'\n'; }; virtual void compile(Context &input, int p = 2)const override{} virtual double evaluate()const override{} private: Statementptr left; Statementptr right; }; class functiondefinition : public Statement{ public: virtual ~functiondefinition(){}; functiondefinition(Statementptr p1, Statementptr p2, Statementptr p3){left = p1 ; mid = p2;right = p3; if(Funcnameadd!="main"){Funcname.push_back(Funcnameadd); mainflag = false;Funcnameadd = "";} else{mainflag = true;} } functiondefinition(Statementptr p1, Statementptr p2){mid = p1 ; right = p2;} Statementptr get_id(){return left;} Statementptr get_argument(){return right;} Statementptr get_mid(){return mid;} virtual void translate(std::ostream &dst,std::string indent, bool &addglobal, std::vector<std::string> &globalvariables)const override{ dst << "def "; mid -> translate(dst,"",addglobal,globalvariables); dst << std::endl; if(globalvariables.size() != 0) { for(int i=0;i<globalvariables.size();i++) { dst<<" "<<"global "<<globalvariables[i]<<std::endl; } } right ->translate(dst,"",addglobal,globalvariables); dst << std::endl; } virtual void treeprint(std::ostream &dst, std::string indent)const override { dst<<indent<<"<Function definition>"<<" ["<<'\n'; if(left != NULL) {left->treeprint(dst, indent+" ");} mid->treeprint(dst, indent+" "); right->treeprint(dst, indent+" "); dst<<indent<<"]"<<'\n'; }; virtual void compile(Context &input, int p = 2)const override{ int offset = NumVariables*4; if(mainflag == false){ input.current_offset = offset; input.print() <<"\t.global\t" << Funcname[0] << std::endl; input.print() <<"\t.ent\t" << Funcname[0] << std::endl; input.print() << Funcname[0]<<":"<<std::endl; input.print() <<"\taddiu\t" << "$sp,$sp,-" << offset << std::endl; input.print() <<"\tsw\t" << "$fp,"<< offset-4<< "($sp)" << std::endl; input.print() <<"\tmove\t" << "$fp,$sp" << std::endl; mid->compile(input,p); right->compile(input,p); input.print() <<"\tmove\t" << "$sp,$fp" << std::endl; input.print() <<"\tlw\t" <<"$fp," << offset-4 << "($sp)" << std::endl; input.print() <<"\taddiu\t" << "$sp,$sp," << offset << std::endl; input.print()<<"\tj\t" <<"$31" << std::endl; input.print() <<"\tnop"<< std::endl; input.print() << std::endl; Funcname.erase(Funcname.begin()); input.print() <<"\t.end "<<Funcname[0] << std::endl; } else{ input.print() <<"\t.global\t" << "main" << std::endl; input.print() <<"\t.ent\t" << "main" << std::endl; input.print() << "main" <<":"<<std::endl; input.print() <<"\taddiu\t" << "$sp,$sp,-" << offset+8 << std::endl; input.print() <<"\tsw\t" << "$31,"<< offset+4<< "($sp)" << std::endl; input.print() <<"\tsw\t" << "$fp,"<< offset << "($sp)" << std::endl; input.print() <<"\tmove\t" << "$fp,$sp" << std::endl; mid->compile(input,p); right->compile(input,p); input.print() <<"\tmove\t" << "$sp,$fp" << std::endl; input.print() <<"\tlw\t" << "$31,"<< offset+4<< "($sp)" << std::endl; input.print() <<"\tlw\t" <<"$fp," << offset << "($sp)" << std::endl; input.print() <<"\taddiu\t" << "$sp,$sp," << offset+8 << std::endl; input.print()<<"\tj\t" <<"$31" << std::endl; input.print() <<"\tnop"<< std::endl; input.print() << std::endl; input.print() <<"\t.end\t" << "main" << std::endl; input.print() <<"\t.end main" << std::endl; } } virtual double evaluate()const override{} private: Statementptr left; Statementptr mid; Statementptr right; }; #endif
true
ad94c5925bdcc41a861936c7d1cb0f53e4456748
C++
harnen/airtnt
/client-ocr/isv_app/processing.h
UTF-8
1,724
2.9375
3
[]
no_license
// ============================================================================ // processing.h // Image processing / OCR functions. // // ============================================================================ #ifndef PROCESSING_H_ #define PROCESSING_H_ #include <vector> #include "Letter.h" using namespace std; // store letters matrix sizes // ugly -- should stay in a file create by 'create_template' // also used by image_util.h const int sizes[26][2] = { {62, 79}, {48, 79}, {51, 81}, {49, 79}, {41, 79}, {42, 79}, {52, 81}, {45, 79}, {36, 79}, {39, 80}, {55, 79}, {43, 79}, {50, 79}, {47, 79}, {54, 81}, {45, 79}, {56, 94}, {53, 79}, {44, 81}, {57, 79}, {45, 80}, {62, 79}, {63, 79}, {60, 79}, {58, 79}, {48, 79} }; /* * character_recognition * perform OCR on an input image. * Note: the image is input as a int** double pointer for edger8r compilation. */ void character_recognition(int** input, int rows, int cols, int** letters_c, int letters_rows, int letters_col, char *output_letters, int *length); /* * find_letters * find all letters in a 2d vector image. */ vector<Letter> find_letters(const int& threshold, const vector< vector<int> > matrix); /* * match_letter * search for the better matching letter. */ void match_letter(const Letter to_match, const vector<Letter> letters, Letter *best_match); /* * scale_Matrix_to * scale a 2d vector matrix A to match the size of a matrix B. */ vector< vector<int> > scale_Matrix_to(int width, int height, vector< vector<int> > oldMatrix); /* * compare_matrices * return the distance between two matrices A and B. */ double compare_matrices(vector< vector<int> > matrixA, vector< vector<int> > matrixB); #endif // PROCESSING_H_
true
b26c75bb61aff385accf6319d82ae7e5ee467605
C++
grant-cai/cs16projects
/vowels.cpp
UTF-8
1,037
3.125
3
[]
no_license
#include <iostream> #include <string> #include <cctype> #include <algorithm> using namespace std; int countVowels(string s) { int len = s.length(); if(s.empty()){ return 0; } else { return (toupper(s[0]) == 'A' || toupper(s[0]) == 'E' || toupper(s[0]) == 'I' || toupper(s[0]) == 'O' || toupper(s[0]) == 'U') + countVowels(s.substr(1, len - 1)); } } int main() { string et = "E.T. phone home"; string shining = "All work and no play makes Jack a dull boy"; string oz = "Toto, I've a feeling we're not in Kansas anymore"; string podBayDoors = "Open the pod bay doors, please, HAL"; cout << "There are " << countVowels(et) << " vowels in " << '\"' << et << '\"' << endl; cout << "There are " << countVowels(shining) << " vowels in " << '\"' << shining << '\"' << endl; cout << "There are " << countVowels(oz) << " vowels in " << '\"' << oz << '\"' << endl; cout << "There are " << countVowels(podBayDoors) << " vowels in " << '\"' << podBayDoors << '\"' << endl; }
true
3286a4805dcf183bc93a3d69be8992369ecd2f24
C++
vslavik/poedit
/deps/boost/libs/log/test/run/util_formatting_ostream.cpp
UTF-8
15,472
2.6875
3
[ "GPL-1.0-or-later", "MIT", "BSL-1.0" ]
permissive
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file util_formatting_ostream.cpp * \author Andrey Semashev * \date 26.05.2013 * * \brief This header contains tests for the formatting output stream wrapper. */ #define BOOST_TEST_MODULE util_formatting_ostream #include <locale> #include <string> #include <iomanip> #include <sstream> #include <iostream> #include <algorithm> #include <boost/config.hpp> #include <boost/test/unit_test.hpp> #include <boost/utility/string_view.hpp> #include <boost/log/utility/formatting_ostream.hpp> #include "char_definitions.hpp" #if defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T) #define BOOST_UTF8_DECL #define BOOST_UTF8_BEGIN_NAMESPACE namespace { #define BOOST_UTF8_END_NAMESPACE } #include <boost/detail/utf8_codecvt_facet.hpp> #include <boost/detail/utf8_codecvt_facet.ipp> #endif // defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T) namespace logging = boost::log; namespace { struct unreferencable_data { unsigned int m : 2; unsigned int n : 6; enum my_enum { one = 1, two = 2 }; // The following static constants don't have definitions, so they can only be used in constant expressions. // Trying to bind a reference to these members will result in linking errors. static const int x = 7; static const my_enum y = one; unreferencable_data() { m = 1; n = 5; } }; template< typename CharT > struct test_impl { typedef CharT char_type; typedef test_data< char_type > strings; typedef std::basic_string< char_type > string_type; typedef std::basic_ostringstream< char_type > ostream_type; typedef logging::basic_formatting_ostream< char_type > formatting_ostream_type; template< typename StringT > static void width_formatting() { // Check that widening works { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC(); strm_fmt.flush(); ostream_type strm_correct; strm_correct << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } // Check that the string is not truncated { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << strings::abc() << std::setw(1) << (StringT)strings::abcd() << strings::ABC(); strm_fmt.flush(); ostream_type strm_correct; strm_correct << strings::abc() << std::setw(1) << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } } template< typename StringT > static void fill_formatting() { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << strings::abc() << std::setfill(static_cast< char_type >('x')) << std::setw(8) << (StringT)strings::abcd() << strings::ABC(); strm_fmt.flush(); ostream_type strm_correct; strm_correct << strings::abc() << std::setfill(static_cast< char_type >('x')) << std::setw(8) << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } template< typename StringT > static void alignment() { // Left alignment { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << strings::abc() << std::setw(8) << std::left << (StringT)strings::abcd() << strings::ABC(); strm_fmt.flush(); ostream_type strm_correct; strm_correct << strings::abc() << std::setw(8) << std::left << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } // Right alignment { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << strings::abc() << std::setw(8) << std::right << (StringT)strings::abcd() << strings::ABC(); strm_fmt.flush(); ostream_type strm_correct; strm_correct << strings::abc() << std::setw(8) << std::right << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) template< typename StringT > static void rvalue_stream() { string_type str_fmt; formatting_ostream_type(str_fmt) << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC() << std::flush; ostream_type strm_correct; strm_correct << strings::abc() << std::setw(8) << (StringT)strings::abcd() << strings::ABC(); BOOST_CHECK(equal_strings(str_fmt, strm_correct.str())); } #endif static void output_unreferencable_data() { unreferencable_data data; { string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); strm_fmt << data.m << static_cast< char_type >(' ') << data.n << static_cast< char_type >(' ') << unreferencable_data::x << static_cast< char_type >(' ') << unreferencable_data::y; strm_fmt.flush(); ostream_type strm_correct; strm_correct << static_cast< unsigned int >(data.m) << static_cast< char_type >(' ') << static_cast< unsigned int >(data.n) << static_cast< char_type >(' ') << static_cast< int >(unreferencable_data::x) << static_cast< char_type >(' ') << static_cast< int >(unreferencable_data::y); BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) { string_type str_fmt; formatting_ostream_type(str_fmt) << data.m << static_cast< char_type >(' ') << data.n << static_cast< char_type >(' ') << unreferencable_data::x << static_cast< char_type >(' ') << unreferencable_data::y << std::flush; ostream_type strm_correct; strm_correct << static_cast< unsigned int >(data.m) << static_cast< char_type >(' ') << static_cast< unsigned int >(data.n) << static_cast< char_type >(' ') << static_cast< int >(unreferencable_data::x) << static_cast< char_type >(' ') << static_cast< int >(unreferencable_data::y); BOOST_CHECK(equal_strings(str_fmt, strm_correct.str())); } #endif } }; } // namespace // Test support for width formatting BOOST_AUTO_TEST_CASE_TEMPLATE(width_formatting, CharT, char_types) { typedef test_impl< CharT > test; test::BOOST_NESTED_TEMPLATE width_formatting< const CharT* >(); test::BOOST_NESTED_TEMPLATE width_formatting< typename test::string_type >(); test::BOOST_NESTED_TEMPLATE width_formatting< boost::basic_string_view< CharT > >(); } // Test support for filler character setup BOOST_AUTO_TEST_CASE_TEMPLATE(fill_formatting, CharT, char_types) { typedef test_impl< CharT > test; test::BOOST_NESTED_TEMPLATE fill_formatting< const CharT* >(); test::BOOST_NESTED_TEMPLATE fill_formatting< typename test::string_type >(); test::BOOST_NESTED_TEMPLATE fill_formatting< boost::basic_string_view< CharT > >(); } // Test support for text alignment BOOST_AUTO_TEST_CASE_TEMPLATE(alignment, CharT, char_types) { typedef test_impl< CharT > test; test::BOOST_NESTED_TEMPLATE alignment< const CharT* >(); test::BOOST_NESTED_TEMPLATE alignment< typename test::string_type >(); test::BOOST_NESTED_TEMPLATE alignment< boost::basic_string_view< CharT > >(); } #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) // Test support for rvalue stream objects BOOST_AUTO_TEST_CASE_TEMPLATE(rvalue_stream, CharT, char_types) { typedef test_impl< CharT > test; test::BOOST_NESTED_TEMPLATE rvalue_stream< const CharT* >(); test::BOOST_NESTED_TEMPLATE rvalue_stream< typename test::string_type >(); test::BOOST_NESTED_TEMPLATE rvalue_stream< boost::basic_string_view< CharT > >(); } #endif // Test output of data to which a reference cannot be bound BOOST_AUTO_TEST_CASE_TEMPLATE(output_unreferencable_data, CharT, char_types) { typedef test_impl< CharT > test; test::output_unreferencable_data(); } namespace my_namespace { class A {}; template< typename CharT, typename TraitsT > inline std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, A const&) { strm << "A"; return strm; } class B {}; template< typename CharT, typename TraitsT > inline std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, B&) { strm << "B"; return strm; } class C {}; template< typename CharT, typename TraitsT > inline std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, C const&) { strm << "C"; return strm; } enum E { eee }; template< typename CharT, typename TraitsT > inline std::basic_ostream< CharT, TraitsT >& operator<< (std::basic_ostream< CharT, TraitsT >& strm, E) { strm << "E"; return strm; } } // namespace my_namespace // Test operator forwarding BOOST_AUTO_TEST_CASE_TEMPLATE(operator_forwarding, CharT, char_types) { typedef CharT char_type; typedef std::basic_string< char_type > string_type; typedef std::basic_ostringstream< char_type > ostream_type; typedef logging::basic_formatting_ostream< char_type > formatting_ostream_type; string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); const my_namespace::A a = my_namespace::A(); // const lvalue my_namespace::B b; // lvalue strm_fmt << a << b << my_namespace::C(); // rvalue strm_fmt << my_namespace::eee; strm_fmt.flush(); ostream_type strm_correct; strm_correct << a << b << my_namespace::C() << my_namespace::eee; BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } namespace my_namespace2 { class A {}; template< typename CharT, typename TraitsT, typename AllocatorT > inline logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& operator<< (logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, A const&) { strm << "A"; return strm; } class B {}; template< typename CharT, typename TraitsT, typename AllocatorT > inline logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& operator<< (logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, B&) { strm << "B"; return strm; } class C {}; template< typename CharT, typename TraitsT, typename AllocatorT > inline logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& operator<< (logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, C const&) { strm << "C"; return strm; } class D {}; template< typename CharT, typename TraitsT, typename AllocatorT > inline logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& operator<< (logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) D&& #else D const& #endif ) { strm << "D"; return strm; } enum E { eee }; template< typename CharT, typename TraitsT, typename AllocatorT > inline logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& operator<< (logging::basic_formatting_ostream< CharT, TraitsT, AllocatorT >& strm, E) { strm << "E"; return strm; } } // namespace my_namespace2 // Test operator overriding BOOST_AUTO_TEST_CASE_TEMPLATE(operator_overriding, CharT, char_types) { typedef CharT char_type; typedef std::basic_string< char_type > string_type; typedef std::basic_ostringstream< char_type > ostream_type; typedef logging::basic_formatting_ostream< char_type > formatting_ostream_type; string_type str_fmt; formatting_ostream_type strm_fmt(str_fmt); const my_namespace2::A a = my_namespace2::A(); // const lvalue my_namespace2::B b; // lvalue strm_fmt << a << b << my_namespace2::C() << my_namespace2::D(); // rvalue strm_fmt << my_namespace2::eee; strm_fmt.flush(); ostream_type strm_correct; strm_correct << "ABCDE"; BOOST_CHECK(equal_strings(strm_fmt.str(), strm_correct.str())); } #if defined(BOOST_LOG_USE_CHAR) && defined(BOOST_LOG_USE_WCHAR_T) namespace { const char narrow_chars[] = "\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82, \xd0\xbc\xd0\xb8\xd1\x80!"; const wchar_t wide_chars[] = { 0x041f, 0x0440, 0x0438, 0x0432, 0x0435, 0x0442, L',', L' ', 0x043c, 0x0438, 0x0440, L'!', 0 }; template< typename StringT > void test_narrowing_code_conversion() { std::locale loc(std::locale::classic(), new utf8_codecvt_facet()); // Test rvalues { std::string str_fmt; logging::formatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); strm_fmt << (StringT)wide_chars; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::string(narrow_chars))); } // Test lvalues { std::string str_fmt; logging::formatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); StringT wstr = StringT(wide_chars); strm_fmt << wstr; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::string(narrow_chars))); } // Test const lvalues { std::string str_fmt; logging::formatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); const StringT wstr = StringT(wide_chars); strm_fmt << wstr; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::string(narrow_chars))); } } template< typename StringT > void test_widening_code_conversion() { std::locale loc(std::locale::classic(), new utf8_codecvt_facet()); // Test rvalues { std::wstring str_fmt; logging::wformatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); strm_fmt << (StringT)narrow_chars; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::wstring(wide_chars))); } // Test lvalues { std::wstring str_fmt; logging::wformatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); StringT str = StringT(narrow_chars); strm_fmt << str; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::wstring(wide_chars))); } // Test const lvalues { std::wstring str_fmt; logging::wformatting_ostream strm_fmt(str_fmt); strm_fmt.imbue(loc); const StringT str = StringT(narrow_chars); strm_fmt << str; strm_fmt.flush(); BOOST_CHECK(equal_strings(str_fmt, std::wstring(wide_chars))); } } } // namespace // Test character code conversion BOOST_AUTO_TEST_CASE(character_code_conversion) { test_narrowing_code_conversion< const wchar_t* >(); test_widening_code_conversion< const char* >(); test_narrowing_code_conversion< std::wstring >(); test_widening_code_conversion< std::string >(); test_narrowing_code_conversion< boost::wstring_view >(); test_widening_code_conversion< boost::string_view >(); } #endif
true
032acf1813e8eceac75b1e519ed2d0116cc46023
C++
dave98/2019_01
/RC_1_Basic_Chat/client.cpp
UTF-8
1,446
2.6875
3
[]
no_license
/* Client code in C */ #include <iostream> #include <string> #include <string.h> #include <strings.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <fstream> using namespace std; int main(){ int port = 4000; char msg[1024]; struct hostent* host = gethostbyname("127.0.0.1"); sockaddr_in client_Adress; bzero((char*)&client_Adress, sizeof(client_Adress)); client_Adress.sin_family = AF_INET; client_Adress.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*)*host->h_addr_list)); client_Adress.sin_port = htons(port); int status_cli = socket(AF_INET, SOCK_STREAM, 0); //Iniciando la conexion int status_conect = connect(status_cli, (sockaddr*)&client_Adress, sizeof(client_Adress)); if(status_conect < 0){ cout<<"Fallo conexion al servidor"<<endl; exit(0);} cout<<"Conexion establecida"<<endl; while(1){ string my_message;//Enviamos nuestro mensaje cin>>my_message; memset(msg, 0, sizeof(msg));//Buffer limpio strcpy(msg, my_message.c_str()); send(status_cli, (char*)&msg, sizeof(msg), 0); //Esperamos respuesta del servidor memset(&msg, 0, sizeof(msg));//Buffer limpio para respuesta del server recv(status_cli, (char*)&msg, sizeof(msg), 0); cout<<"Server: [ "<<msg<<" ]"<<endl; } return 0; }
true
02eb8ae4fdaa85260ed6799084c9556890db6b36
C++
yull2310/book-code
/www.cplusplus.com-20180131/reference/unordered_set/unordered_set/load_factor/load_factor.cpp
UTF-8
416
2.875
3
[]
no_license
// unordered_set hash table stats #include <iostream> #include <unordered_set> int main () { std::unordered_set<int> myset; std::cout << "size = " << myset.size() << std::endl; std::cout << "bucket_count = " << myset.bucket_count() << std::endl; std::cout << "load_factor = " << myset.load_factor() << std::endl; std::cout << "max_load_factor = " << myset.max_load_factor() << std::endl; return 0; }
true
fec0e268c763cdf0186c26bbbc3a01bdf1533d19
C++
beunprogrammeur/basic-nes-emulator
/lib/nes/include/nes/cpu/instructions/iinstruction.h
UTF-8
1,141
2.921875
3
[ "MIT" ]
permissive
#pragma once #include <nes/cpu/registers.h> #include <nes/cpu/bus/bus.h> #include <string> namespace nes::cpu::instructions { enum class AddressingMode { // Unknown: not defined. No addresing mode. UNK, // Absolute addressing ABS, // Absolute indexed X addressing ABSX, // Absolute indexed Y addressing ABSY, // Accumulator addressing ACC, // Indirect absolute addressing IABS, // Indirect absolute indexed X addressing IABSX, // Indirect Indexed addressing IIND, // Indirect Indexed X addressing IINDX, // Indirect Indexed Y addressing IINDY, // Immediate addressing IMM, // Implied addressing IMP, // Relative addressing REL, // Zero page addressing ZP, // Zero page indexed X addressing ZPX, // Zero page indexed Y addressing ZPY, }; class IInstruction { public: // executes the current instruction. // returns the number of ticks this instruction costs virtual uint8_t execute(nes::cpu::Registers& registers, nes::cpu::bus::IBus& bus) = 0; virtual const std::string& name() const = 0; }; }
true
a8fa91d535baaa1195be191ca23c180ac4ab7ecc
C++
ikraduya/tubes-oop
/products/HorseMeat.cpp
UTF-8
440
2.875
3
[]
no_license
/** * @file HorseMeat.cpp * @author Al Terra * @date 2019-03-20 */ #include "HorseMeat.h" const long HorseMeat::price = 20000; /** * @brief Kelas HorseMeat yang diturunkan dari FarmProducts */ /** * @brief ctor default */ HorseMeat::HorseMeat() : FarmProducts("Horse Meat"){} /** * @brief getter price * * @return long price dari produk farm tersebut */ long HorseMeat::getPrice(){return price;}
true
40c2abc33d7c2a497d10afa97ae9bbdabe05545a
C++
cth103/toast
/src/util.cc
UTF-8
2,603
2.6875
3
[]
no_license
#include "util.h" #include "toast_socket.h" #include "config.h" #ifdef TOAST_HAVE_WIRINGPI #include <wiringPi.h> #endif #include <cstring> using std::string; using std::shared_ptr; using std::pair; void put_int16(uint8_t*& p, uint8_t* e, int16_t v) { assert(e > (p + 2)); *p++ = v & 0xff; *p++ = (v & 0xff00) >> 8; } int16_t get_int16(uint8_t*& p) { int16_t v = *p++; v |= (*p++) << 8; return v; } void put_float(uint8_t*& p, uint8_t* e, float f) { put_int16(p, e, static_cast<int16_t>(f * 16)); } float get_float(uint8_t*& p) { return get_int16(p) / 16.0; } void put_string(uint8_t*& p, uint8_t* e, string s) { assert(e > (p + 1 + s.length())); *p++ = s.length(); strncpy(reinterpret_cast<char *>(p), s.c_str(), s.length()); p += s.length(); } string get_string(uint8_t*& p) { int const N = *p++; string s; for (int i = 0; i < N; ++i) { s += *p++; } return s; } int64_t get_int64(uint8_t*& p) { int64_t o = *p++; o |= (*p++ << 8); o |= (*p++ << 16); o |= (*p++ << 24); o |= ((int64_t) *p++) << 32; o |= ((int64_t) *p++) << 40; o |= ((int64_t) *p++) << 48; o |= ((int64_t) *p++) << 56; return o; } void put_int64(uint8_t*& p, uint8_t* e, int64_t v) { assert(e > (p + 8)); *p++ = v & 0xff; *p++ = (v & 0xff00) >> 8; *p++ = (v & 0xff0000) >> 16; *p++ = (v & 0xff000000) >> 24; *p++ = (v & 0xff00000000) >> 32; *p++ = (v & 0xff0000000000) >> 40; *p++ = (v & 0xff000000000000) >> 48; *p++ = (v & 0xff00000000000000) >> 56; } void put_datum(uint8_t*& p, uint8_t* e, Datum d) { put_int64(p, e, d.time()); put_float(p, e, d.value()); } void write_with_length(shared_ptr<Socket> socket, uint8_t const * data, int length) { uint8_t len[4]; len[0] = (length & 0xff000000) >> 24; len[1] = (length & 0x00ff0000) >> 16; len[2] = (length & 0x0000ff00) >> 8; len[3] = (length & 0x000000ff) >> 0; socket->write(len, 4); socket->write(data, length); } pair<shared_ptr<uint8_t[]>, uint32_t> read_with_length(shared_ptr<Socket> socket) { uint8_t len[4]; if (socket->read(len, 4) != 4) { return make_pair(shared_ptr<uint8_t[]>(), 0); } uint32_t length = (len[0] << 24) | (len[1] << 16) | (len[2] << 8) | len[3]; shared_ptr<uint8_t[]> data(new uint8_t[length]); if (socket->read(data.get(), length) != static_cast<int>(length)) { return make_pair(shared_ptr<uint8_t[]>(), 0); } return make_pair(data, length); } #ifdef TOAST_HAVE_WIRINGPI void set_boiler_on(bool s) { digitalWrite(Config::instance()->boiler_gpio(), s ? HIGH : LOW); } #else void set_boiler_on(bool) { } #endif struct tm now() { time_t const t = time(0); return *localtime(&t); }
true
c82d510809c57f1d1974be8636fc2ae806bf931a
C++
Vancasola/DataStructure
/exam/2017冬/3.cpp
UTF-8
1,135
2.578125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstdlib> #include <string> #include <vector> #include <cstring> #include <cmath> #include <map> #include <stack> #include <unordered_map> #include <set> #include <algorithm> using namespace std; int n; int in[50005],pre[50005]; struct node{ int x; node*lc,*rc; node(){ lc=rc=NULL; } node(int d){ x=d; lc=rc=NULL; } }; node* create(int prel,int prer,int inl,int inr){ if(prel>prer){ return NULL; } node* r=new node(pre[prel]); if(prel==prer)return r; int p=0; for(int i=inl;i<=inr;i++){ if(in[i]==pre[prel]){ p=i; break; } } r->lc=create(prel+1,prel+p-inl,inl,p-1); r->rc=create(prel+p-inl+1,prer,p+1,inr); //7 //1 2 3 4 5 6 7 //2 3 1 5 4 7 6 return r; } bool f=false; void postorder(node* r){ if(f)return; if(r->lc)postorder(r->lc); if(f)return; if(r->rc)postorder(r->rc); if(!f)printf("%d",r->x); f=true; return; } int main(){ cin>>n; for(int i=0;i<n;i++)scanf("%d",&pre[i]); for(int i=0;i<n;i++)scanf("%d",&in[i]); node* r=create(0,n-1,0,n-1); postorder(r); return 0; }
true
c5419e6eaf0466458b9d35b4f87a969c2ad39175
C++
fossabot/InnocenceEngine
/source/engine/component/BaseComponent.h
UTF-8
461
2.515625
3
[ "MIT" ]
permissive
#pragma once #include "interface/IComponent.h" #include "entity/InnoMath.h" class BaseComponent : public IComponent { public: BaseComponent() : m_parentEntity(nullptr) {}; virtual ~BaseComponent() {}; IEntity* getParentEntity() const override; void setParentEntity(IEntity* parentEntity) override; const objectStatus& getStatus() const override; protected: objectStatus m_objectStatus = objectStatus::SHUTDOWN; private: IEntity* m_parentEntity; };
true
00068e39bd835fdc35640c5b5ad33014706387e3
C++
matzmz/pfs
/sample/enum_fd.cpp
UTF-8
3,013
2.59375
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2020-present Daniel Trugman * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "enum.hpp" #include "format.hpp" #include "log.hpp" #include "pfs/procfs.hpp" template <typename T> void add_sockets(const std::vector<T>& sockets, std::unordered_map<ino_t, std::string>& output) { for (auto& socket : sockets) { std::ostringstream out; out << socket; output.emplace(socket.inode, out.str()); } } std::unordered_map<ino_t, std::string> enum_sockets(const pfs::net& net) { std::unordered_map<ino_t, std::string> sockets; add_sockets(net.get_icmp(), sockets); add_sockets(net.get_icmp6(), sockets); add_sockets(net.get_raw(), sockets); add_sockets(net.get_raw6(), sockets); add_sockets(net.get_tcp(), sockets); add_sockets(net.get_tcp6(), sockets); add_sockets(net.get_udp(), sockets); add_sockets(net.get_udp6(), sockets); add_sockets(net.get_udplite(), sockets); add_sockets(net.get_udplite6(), sockets); add_sockets(net.get_unix(), sockets); add_sockets(net.get_netlink(), sockets); return sockets; } void enum_task_fds(const pfs::task& task) { try { LOG("fds (total: " << task.count_fds() << ")"); LOG("---"); auto sockets = enum_sockets(task.get_net()); for (auto& iter : task.get_fds()) { auto num = iter.first; auto& fd = iter.second; auto st = fd.get_target_stat(); auto inode = st.st_ino; std::ostringstream out; out << "target[" << fd.get_target() << "] "; auto socket = sockets.find(inode); if (socket != sockets.end()) { out << socket->second; } LOG(num << ": " << out.str()); } LOG(""); } catch (const std::runtime_error& ex) { LOG("Error when printing task[" << task.id() << "] fds:"); LOG(TAB << ex.what()); } } int enum_fds(std::vector<std::string>&& args) { pfs::procfs pfs; if (args.empty()) { for (const auto& process : pfs.get_processes()) { for (const auto& thread : process.get_tasks()) { enum_task_fds(thread); } } } else { for (const auto& task : args) { auto id = std::stoi(task); enum_task_fds(pfs.get_task(id)); } } return 0; }
true
947014743245bc0b0b24a652a9277ebd3b808219
C++
vital228/Algorithm
/ifmo c/ifmo c/dfs.cpp
UTF-8
2,202
2.515625
3
[]
no_license
#include <iostream> #include <fstream> #include<vector> #include<queue> using namespace std; vector<int> gr[100000]; queue<pair<int, int>> q; int a[1000][1000]; int main() { ifstream fin("input.txt"); ofstream fout("output.txt"); int n, m; fin >> n >> m; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { a[i][j] = -1; } } pair<int, int> f(0,0),s(0,0); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { char a1; fin >> a1; if (a1 == '.') a[i][j] = 0; if (a1 == 'S') { q.push(make_pair(i, j)); s = make_pair(i, j); a[i][j] = 0; } if (a1 == 'T') { f = make_pair(i, j); a[i][j] = 0; } } } if (f.first == 0 && f.second == 0) { fout << -1; return 0; } while (!q.empty()) { pair<int, int> v = q.front(); if (a[v.first + 1][v.second] == 0) { a[v.first + 1][v.second] = a[v.first][v.second] + 1; q.push(make_pair(v.first + 1, v.second)); } if (a[v.first][v.second + 1] == 0) { a[v.first][v.second + 1] = a[v.first][v.second] + 1; q.push(make_pair(v.first, v.second + 1)); } if (a[v.first - 1][v.second] == 0) { a[v.first - 1][v.second] = a[v.first][v.second] + 1; q.push(make_pair(v.first - 1, v.second)); } if (a[v.first][v.second - 1] == 0) { a[v.first][v.second - 1] = a[v.first][v.second] + 1; q.push(make_pair(v.first, v.second - 1)); } q.pop(); } a[s.first][s.second] = 0; if (a[f.first][f.second] > 0) { fout << a[f.first][f.second] << endl; int k = a[f.first][f.second]; pair<int, int> v = f; vector<char> ans; while (k > 0) { if (a[v.first + 1][v.second] == k - 1) { v = make_pair(v.first + 1, v.second); ans.push_back('U'); } else { if (a[v.first][v.second + 1] == k - 1) { v = make_pair(v.first, v.second + 1); ans.push_back('L'); } else { if (a[v.first][v.second - 1] == k - 1) { v = make_pair(v.first, v.second - 1); ans.push_back('R'); } else { v = make_pair(v.first - 1, v.second); ans.push_back('D'); } } } k=a[v.first][v.second]; } for (int i = ans.size()-1; i>=0; i--) { fout << ans[i]; } } else { fout << -1; } return 0; }
true
697a3e3a6b0bb871377eea44d4d06cb7e6beac4b
C++
dpinol/SDL_test
/model/Jewel.h
UTF-8
828
2.578125
3
[]
no_license
/************************************************************************** ** Qt Creator license header template ** Special keywords: dpinol 03/03/2014 2014 ** Environment variables: ** To protect a percent sign, use '%'. **************************************************************************/ #ifndef JEWEL_H #define JEWEL_H #include "BoardPos.h" class Board; class Jewel { public: typedef short COLOR; /** * @brief Jewel by default it has color NO_COLOR */ Jewel(); static constexpr short NUM_COLORS = 5; static constexpr COLOR NO_COLOR = -1; void setColor(COLOR color) { m_color = color;} COLOR getColor() const { return m_color;} //BoardPos const getBoardPos() const { return m_boardPos;} private: friend class Board; COLOR m_color; // BoardPos m_boardPos; }; #endif // JEWEL_H
true
f585e07d0d04f3b450eb5588677f61ff2b1cd4c8
C++
Sciencegeek123/AntColonyEvolution
/testing/compilertest/helloworld.cpp
UTF-8
194
2.828125
3
[]
no_license
#include <iostream> #include <memory> using namespace std; int main() { shared_ptr<int> id(new int(0)); while (*id < 10) { (*id)++; } cdebug << "Hello world!" << endl; }
true
bd4f8c4270cee864c352b7aff0f1921880858da9
C++
Adarshkumarmaheshwari/SI-AlgoDS-Practice
/C++ Practice(DSalgo)/DP/EqualSubsetSum.cpp
UTF-8
1,215
3.15625
3
[]
no_license
#include "bits/stdc++.h" using namespace std; bool isSubsetSum(int set[], int n, int sum) { if (sum % 2 != 0) { return false; } else if(sum%2==0) { sum = sum / 2; bool subset[n + 1][sum + 1]; for (int i{0}; i < n; i++) { subset[i][0] = true; } for (int i{1}; i <= sum; i++) { subset[0][i] = false; } for (int i{1}; i <= n; i++) { for (int j{1}; j <= sum; j++) { if (set[i - 1] <= j) { subset[i][j] = subset[i - 1][j - set[i - 1]] || subset[i - 1][j]; } else { subset[i][j] = subset[i - 1][j]; } } } return subset[n][sum]; } } int main() { int set[] = {1, 5, 11, 5}; int n = sizeof(set) / sizeof(set[0]); int sum = 0; for (int i{0}; i < n; i++) { sum += set[i]; } if (isSubsetSum(set, n, sum) == true) cout << "TRUE" << endl; else cout << "FALSE" << endl; return 0; }
true
332d86cf27c3d794b15a9acdb0d86dfca376f101
C++
manjurulhoque/problem-solving
/Codeforces/1271A.cpp
UTF-8
625
2.890625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { int a, b, c, d, e, f, sum = 0; cin>>a>>b>>c>>d>>e>>f; if(f > e) { int second = min({b, c, d}); sum += (second * f); d -= second; if(d > 0) { int first = min(a, d); sum += (first * e); } cout<<sum<<endl; } else { int first = min(a, d); sum += (first * e); d -= first; if(d > 0) { int second = min({b, c, d}); sum += (second * f); } cout<<sum<<endl; } return 0; }
true
2671f65b896960ab9b1a1db9f42a9ffad8e3d879
C++
gilzilberfeld/tic-tac-toe
/cpp/T3Cpp/Code/Game.cpp
UTF-8
800
2.9375
3
[]
no_license
#include "..\pch.h" #include "PlayerType.h" #include "IllegalMove.h" #include "IMoveHandler.h" #include "Player.h" #include "Board.h" #include "Game.h" Game::Game() { playerX = new Player(X, (IMoveHandler*) this); playerO = new Player(O, (IMoveHandler*) this); nextPlayer = playerX; } bool Game::IsOver() { return false; } Player * Game::GetPlayerX() { return playerX; } Player * Game::GetPlayerO() { return playerO; } Player * Game::GetNextPlayer() { return nextPlayer; } void Game::Move(PieceType type, int row, int column) { if (PlayingAgain(type)) throw IllegalMove(); board.Place(type, row, column); nextPlayer = playerO; } bool Game::PlayingAgain(PieceType type) { return type != GetNextPlayer()->GetType(); } Player * Game::GetCurrentPlayer() { return GetNextPlayer(); }
true
13f1488e8f814e534e3148a9379497b879bb9198
C++
TruVortex/Competitive-Programming
/DMOJ/pwindsor18p3.cpp
UTF-8
346
2.671875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; bool prime(int n) { for (int x = 2; x <= sqrt(n); x++) if (n%x == 0) return false; return true; } int main() { int n; scanf("%i", &n); int cnt = 0, a; while (n--) { scanf("%i", &a); cnt += !prime(a); } printf("%i\n", cnt); }
true
3c40b9fc609ce6785d82febc6c4b160caf1037b1
C++
arangodb/arangodb
/3rdParty/V8/v7.9.317/src/base/flags.h
UTF-8
5,978
2.640625
3
[ "Apache-2.0", "BSD-3-Clause", "ICU", "Zlib", "GPL-1.0-or-later", "OpenSSL", "ISC", "LicenseRef-scancode-gutenberg-2020", "MIT", "GPL-2.0-only", "CC0-1.0", "BSL-1.0", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "Bison-exception-2.2", "LicenseRef-scancode...
permissive
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_BASE_FLAGS_H_ #define V8_BASE_FLAGS_H_ #include <cstddef> #include "src/base/compiler-specific.h" namespace v8 { namespace base { // The Flags class provides a type-safe way of storing OR-combinations of enum // values. The Flags<T, S> class is a template class, where T is an enum type, // and S is the underlying storage type (usually int). // // The traditional C++ approach for storing OR-combinations of enum values is to // use an int or unsigned int variable. The inconvenience with this approach is // that there's no type checking at all; any enum value can be OR'd with any // other enum value and passed on to a function that takes an int or unsigned // int. template <typename T, typename S = int> class Flags final { public: using flag_type = T; using mask_type = S; constexpr Flags() : mask_(0) {} constexpr Flags(flag_type flag) // NOLINT(runtime/explicit) : mask_(static_cast<S>(flag)) {} constexpr explicit Flags(mask_type mask) : mask_(static_cast<S>(mask)) {} constexpr bool operator==(flag_type flag) const { return mask_ == static_cast<S>(flag); } constexpr bool operator!=(flag_type flag) const { return mask_ != static_cast<S>(flag); } Flags& operator&=(const Flags& flags) { mask_ &= flags.mask_; return *this; } Flags& operator|=(const Flags& flags) { mask_ |= flags.mask_; return *this; } Flags& operator^=(const Flags& flags) { mask_ ^= flags.mask_; return *this; } constexpr Flags operator&(const Flags& flags) const { return Flags(mask_ & flags.mask_); } constexpr Flags operator|(const Flags& flags) const { return Flags(mask_ | flags.mask_); } constexpr Flags operator^(const Flags& flags) const { return Flags(mask_ ^ flags.mask_); } Flags& operator&=(flag_type flag) { return operator&=(Flags(flag)); } Flags& operator|=(flag_type flag) { return operator|=(Flags(flag)); } Flags& operator^=(flag_type flag) { return operator^=(Flags(flag)); } constexpr Flags operator&(flag_type flag) const { return operator&(Flags(flag)); } constexpr Flags operator|(flag_type flag) const { return operator|(Flags(flag)); } constexpr Flags operator^(flag_type flag) const { return operator^(Flags(flag)); } constexpr Flags operator~() const { return Flags(~mask_); } constexpr operator mask_type() const { return mask_; } constexpr bool operator!() const { return !mask_; } Flags without(flag_type flag) { return *this & (~Flags(flag)); } friend size_t hash_value(const Flags& flags) { return flags.mask_; } private: mask_type mask_; }; #define DEFINE_OPERATORS_FOR_FLAGS(Type) \ inline Type operator&( \ Type::flag_type lhs, \ Type::flag_type rhs)ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator&(Type::flag_type lhs, Type::flag_type rhs) { \ return Type(lhs) & rhs; \ } \ inline Type operator&( \ Type::flag_type lhs, \ const Type& rhs)ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator&(Type::flag_type lhs, const Type& rhs) { \ return rhs & lhs; \ } \ inline void operator&(Type::flag_type lhs, \ Type::mask_type rhs)ALLOW_UNUSED_TYPE; \ inline void operator&(Type::flag_type lhs, Type::mask_type rhs) {} \ inline Type operator|(Type::flag_type lhs, Type::flag_type rhs) \ ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator|(Type::flag_type lhs, Type::flag_type rhs) { \ return Type(lhs) | rhs; \ } \ inline Type operator|(Type::flag_type lhs, const Type& rhs) \ ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator|(Type::flag_type lhs, const Type& rhs) { \ return rhs | lhs; \ } \ inline void operator|(Type::flag_type lhs, Type::mask_type rhs) \ ALLOW_UNUSED_TYPE; \ inline void operator|(Type::flag_type lhs, Type::mask_type rhs) {} \ inline Type operator^(Type::flag_type lhs, Type::flag_type rhs) \ ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator^(Type::flag_type lhs, Type::flag_type rhs) { \ return Type(lhs) ^ rhs; \ } \ inline Type operator^(Type::flag_type lhs, const Type& rhs) \ ALLOW_UNUSED_TYPE V8_WARN_UNUSED_RESULT; \ inline Type operator^(Type::flag_type lhs, const Type& rhs) { \ return rhs ^ lhs; \ } \ inline void operator^(Type::flag_type lhs, Type::mask_type rhs) \ ALLOW_UNUSED_TYPE; \ inline void operator^(Type::flag_type lhs, Type::mask_type rhs) {} \ inline Type operator~(Type::flag_type val)ALLOW_UNUSED_TYPE; \ inline Type operator~(Type::flag_type val) { return ~Type(val); } } // namespace base } // namespace v8 #endif // V8_BASE_FLAGS_H_
true
3b47e78411a3913203f327eab6c6fbffd66bef2c
C++
AmrHendy/http-protocol
/HTTP Server/src/server.cpp
UTF-8
5,268
3.109375
3
[ "MIT" ]
permissive
// // Created by Amr Hendy on 11/16/2018. // #include "server.h" #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <thread> #include <mutex> using namespace std; // Steps: // 1) init the server with the host address and port number // 2) start server by listening on the server socket // 3) if there is any connection then accept it and make a new thread handling this connection individually // 4) handle the connection void handle_request(int client_fd); int waitForRequest(int client_fd); void handle_connection(int client_fd); void init_server(int port_number); const int SERVER_CONNECTION_QUEUE_SIZE = 10; const int MAX_ALLOWED_CONNECTIONS = 20; const int MAX_ALLOWED_REQUESTS_PER_CONNECTION = 30; int server_socketfd; // number of clients can be used as counter to handle number of current connections. int clients; std::mutex mtx; void start_server(int port_number){ init_server(port_number); int status; /* start listening on this port */ status = listen(server_socketfd, SERVER_CONNECTION_QUEUE_SIZE); /* if error happened print it*/ if(status){ perror("error in listening"); exit(EXIT_FAILURE); } printf("Server is waiting for connections\n"); struct sockaddr_storage client_addr; /* client address info */ socklen_t sock_size; int client; /* client socket descriptor */ while(1) { /* server main loop */ sock_size = sizeof(client_addr); client = accept(server_socketfd, (struct sockaddr *)&client_addr, &sock_size); /* accept connection */ if(client == -1){ perror("accept error "); continue; } printf("Successfully Established Connection with a Client has fd = %d \n",client); /* * handle the connection, by creating new thread and send it all the information needed * and the function which will handle the connection */ printf("Thread Started for the new client.\n"); if(clients == MAX_ALLOWED_CONNECTIONS){ printf("Reached the max limit number of connections, So server can't handle that client connection\n"); continue; } std::thread t(handle_connection, client); t.detach();//this will allow the thread run on its own see join function in docs for more information clients++; } } void init_server(int port_number){ struct sockaddr_in address; //initialize number of clients clients = 0; address.sin_family = AF_INET; // Creating socket file descriptor for the server if ((server_socketfd = socket(address.sin_family, SOCK_STREAM, 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } int opt = 1; // Check if it is used and forcefully attaching socket to our desired address and port if (setsockopt(server_socketfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port_number); int ret = bind(server_socketfd, (struct sockaddr *)&address, sizeof(address)); if (ret < 0) { perror("bind failed"); exit(EXIT_FAILURE); } } // Handle connection/client void handle_connection(int client_fd) { // That thread will serve the single client int requests_count = 0; while(1){ // serving the requests int status = waitForRequest(client_fd); if(status == -1){ printf("No more requests from client with fd = %d within the last 5 seconds, So the server will close the client connection\n",client_fd); break; } handle_request(client_fd); } mtx.lock(); clients--; mtx.unlock(); } // return status : 1 in case of received request or -1 in case of not receiving so timeout int waitForRequest(int client_fd){ struct timeval tv; /* wait up to 5 seconds. */ tv.tv_sec = 5; tv.tv_usec = 0; fd_set rfds; FD_ZERO(&rfds); FD_SET(client_fd, &rfds); int retval = select(1, &rfds, NULL, NULL, &tv); return (retval!= -1) ? 1 : -1; } void handle_request(int client_fd){ const int request_size = 10000; char* buffer = (char*) malloc(request_size); int val_read = recv(client_fd , buffer, request_size, MSG_PEEK); int index = 0; int start = -1; int end = -1; while(index < val_read){ if(strncmp(buffer + index, "GET", 3) == 0){ if(start == -1){ start = index; }else if(end == -1){ end = index - 1; printf("%d %d\n",start, end); receiveRequest(buffer, end - start + 1, client_fd); start = end + 1; end = -1; } }else if (strncmp(buffer, "POST", 4) == 0){ start = -1; receiveRequest(buffer, val_read, client_fd); break; } index++; } if(start != -1){ end = val_read - 1; receiveRequest(buffer, end - start + 1, client_fd); } }
true
ac917f0dc44d27f66a3ea24246d38d585bb176ea
C++
biggysmith/advent_of_code_2019
/src/day13/day13.cpp
UTF-8
5,200
2.625
3
[]
no_license
#include <vector> #include <numeric> #include <algorithm> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <set> #include <emmintrin.h> #include <smmintrin.h> #include <chrono> #include <conio.h> #define NOMINMAX #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <thread> std::vector<long long> parse_input(const std::string& file){ std::vector<long long> input; std::ifstream file_stream(file); std::string line; std::getline(file_stream, line); std::stringstream ss(line); std::string number_str; while(std::getline(ss, number_str, ',')){ input.push_back(std::stoll(number_str)); } return input; } void gotoxy(int x, int y) { COORD pos = {(short)x, (short)y}; HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(output, pos); } void main() { auto input = parse_input("../src/day13/day13_input.txt"); int width = 35; int height = 23; std::vector<int> screen(width*height,0); auto print_screen = [&]{ for(int y=0; y<height; ++y){ for(int x=0; x<width; ++x){ std::cout << screen[y*width+x]; } std::cout << "\n"; } std::cout << "\n"; std::cout.flush(); }; auto find_tile_pos = [&](int t){ auto it = std::find(screen.begin(), screen.end(), t); int pos = (int)std::distance(screen.begin(), it); return std::make_pair(pos % width, pos / width); }; int score = 0; auto run = [&](bool print,bool free_to_play){ auto& prog = input; if(free_to_play){ prog[0] = 2; } int x = 0; int y = 0; int cmd_num = 0; long long i = 0; long long relative_base = 0; auto code = [&](long long p) -> auto&{ if(p >= (long long )prog.size()){ prog.insert(prog.end(), p+1-prog.size(), 0); } return prog[p]; }; int out_count = 0; while (code(i) != 99) { std::stringstream ss; ss << std::setfill('0') << std::setw(5) << code(i); std::string str = ss.str(); int op_code = std::stoi(str.substr(3,5)); auto mode = [&](long long p){ return str[3-p]; }; auto param = [&](long long p) -> auto&{ if(mode(p)=='0'){ return code(code(i+p)); }else if(mode(p)=='1'){ return code(i+p); }else /*if(mode(p)=='2')*/{ return code(relative_base+code(i+p)); } }; if (op_code == 1) { param(3) = param(1) + param(2); i += 4; }else if (op_code == 2) { param(3) = param(1) * param(2); i += 4; }else if (op_code == 3) { auto paddle_pos = find_tile_pos(3); auto ball_pos = find_tile_pos(4); if(paddle_pos.first > ball_pos.first){ param(1) = -1; }else if(paddle_pos.first == ball_pos.first){ param(1) = 0; }else{ param(1) = 1; } if(print){ gotoxy(0,0); print_screen(); } i += 2; }else if (op_code == 4) { if(cmd_num == 0){ x = (int)param(1); }else if(cmd_num == 1){ y = (int)param(1); }else if(cmd_num == 2){ if(x==-1 && y==0){ score = (int)param(1); if(std::count_if(screen.begin(), screen.end(), [](auto& tile){ return tile == 2; }) <= 0){ return; } }else{ screen[y*width+x] = (int)param(1); } } cmd_num = (cmd_num + 1) % 3; i += 2; }else if (op_code == 5) { if(param(1) != 0){ i = param(2); }else{ i += 3; } }else if (op_code == 6) { if(param(1) == 0){ i = param(2); }else{ i += 3; } }else if (op_code == 7) { param(3) = param(1) < param(2); i += 4; }else if (op_code == 8) { param(3) = param(1) == param(2); i += 4; }else if (op_code == 9) { relative_base += param(1); i += 2; }else { std::cout << "ErRoR!" << std::endl; } } }; // part 1 { run(false, false); std::cout << "part1: " << std::count_if(screen.begin(), screen.end(), [](auto& tile) { return tile == 2; }) << std::endl; } // part 2 { run(false, true); std::cout << "part2: " << score << std::endl; } }
true
a1458ccdc381a8ccf9c788fd6ceb195aa16b80e2
C++
946336/Watchdog
/src/main.cpp
UTF-8
1,035
2.734375
3
[ "MIT" ]
permissive
#ifndef WATCHDOG_DEBUG #define WATCHDOG_DEBUG true #endif #include <watchdog.hpp> #include <iostream> void usage(const std::string &invokedAs) { std::cerr << "Usage: " << invokedAs << " [path]\n"; } int main(int argc, char *argv[]) { if (argc != 2) { usage(argv[0]); return 0; } std::string path(argv[1]); /* Watch::Dog watcher(path); // Watch nonrecursively */ Watch::Pen watcher(path); // Watch recursively std::cout << "Watching " << path << std::endl; // Examine all filesystem events supported by inotify watcher.add_callback([](Watch::Event *ev, std::string path) { auto names = Watch::Flags::get_names(ev->mask, Watch::Flags::Names::All); printf("From %s:\n", Watch::join_paths(path, std::string(ev->name, ev->len)).c_str()); for (const auto &name : names) { std::cout << name << std::endl; } }, Watch::On::All); watcher.listen(); return 0; }
true
f8c07388a6cfca7d4443987a13ea5153da84cb4b
C++
cqw5/CodingTraining
/LeetCodeOJ/Solution/061/rotateRight.cpp
UTF-8
1,950
3.765625
4
[]
no_license
/*! Source: https://leetcode.com/problems/rotate-list/ *! Author: qwchen *! Date : 2016-12-07 * Solution 为该文件最优的方案 * test数据只用于测试是否语法错误,完整的测试见LeetCode。 */ #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} ListNode(int x, ListNode* theNext) : val(x), next(theNext) {} }; /* * 思路: * 求链表的长度,对让k对链表长度取模,结果k就会小于链表长度了 * 当k == 0,就不用翻转了 * 否则找到倒数第k个结点的前一个结点(正数第(lenOfList - k)个结点) * 时间复杂度:O(n) * 空间复杂度:O(1) */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr || k < 1) { return head; } ListNode dummp(0); dummp.next = head; int lenOfList = 0; ListNode* p = &dummp; while(p->next != nullptr) { lenOfList++; p = p->next; } k = k % lenOfList; if (k > 0) { ListNode* q = &dummp; for (int i = 0; i < lenOfList - k; i++) { q = q->next; } p->next = head; head = q->next; q->next = nullptr; } return head; } }; void testSolution() { ListNode* p5 = new ListNode(5); ListNode* p4 = new ListNode(4, p5); ListNode* p3 = new ListNode(3, p4); ListNode* p2 = new ListNode(2, p3); ListNode* head = new ListNode(1, p2); for (ListNode* p = head; p != nullptr; p=p->next) { cout << p->val << " "; } cout << endl; int k = 2; Solution sol; head = sol.rotateRight(head, k); for (ListNode* p = head; p != nullptr; p=p->next) { cout << p->val << " "; } cout << endl; } int main() { testSolution(); return 0; }
true
3aad3eae63b59d935268ba7adeb72f9834a2c95c
C++
gastonorqueda/AyE
/.vscode/Modulo5/Ejercicio 9.cpp
UTF-8
1,146
3.671875
4
[]
no_license
#include<iostream> #include<conio.h> using namespace std; struct Nodo { int info; Nodo *sgte; }; Nodo *obtenerUltimo(Nodo *lista) { while (lista && lista->sgte) lista= lista->sgte; return lista; } void sacarCola(Nodo *&cola,int &n){ Nodo *aux = cola; n = aux->info; cola = aux->sgte; delete aux; } void AgregarNodoAlFinal(Nodo *&lista, int x) { Nodo *paux; if (lista) { paux= obtenerUltimo(lista); paux->sgte= new Nodo(); paux= paux->sgte; paux->info= x; paux->sgte=NULL; } else { lista= new Nodo(); lista->info=x; lista->sgte=NULL; } return; } void queue(Nodo *&cola, int elemento) { AgregarNodoAlFinal(cola,elemento); } int main() { Nodo *cola=NULL; int x; int cantNodo=0; int dato; do{ cout << "Ingrese un elemento. Ingrese un valor negativo para finalizar" << endl; cin >> x; if (x>=0){ queue(cola,x); } }while (x>=0); while(cola != NULL){ sacarCola(cola,dato); cantNodo++; } cout << "La cola tiene " << cantNodo << " nodos." << endl; }
true
add47c618f78f6d1b7f5366e2e930797dc6ad534
C++
aabedraba/tabu-and-local-search
/src/Greedy.cpp
UTF-8
2,473
2.609375
3
[]
no_license
// // Created by aabedraba on 23/10/19. // #include "Greedy.h" Greedy::Greedy(Airport *airport) : _airport(airport) { auto start = std::chrono::steady_clock::now(); initializeVectors(); quickSort(_fluxSum, _fluxIndex, 0, _sizeVectors); quickSort(_distanceSum, _distanceIndex, 0, _sizeVectors); orderVectors(); _solutionCost = Utils::solutionCost(_solutionVector, _airport->getFluxMatrix(), _airport->getDistanceMatrix(), _airport->isSimetric()); auto end = std::chrono::steady_clock::now(); std::chrono::duration<float> diff = end - start; _executionTime = diff.count(); } Greedy::~Greedy() { } void Greedy::initializeVectors() { _sizeVectors = _airport->getNumDoors(); int fluxSum = 0; int distanceSum = 0; for (int i = 0; i < _sizeVectors; ++i) { for (int j = 0; j < _sizeVectors; ++j) { distanceSum += _airport->getDistanceMatrix()[i][j]; fluxSum += _airport->getFluxMatrix()[i][j]; } _fluxSum.push_back(fluxSum); _distanceSum.push_back(distanceSum); _fluxIndex.push_back(i); _distanceIndex.push_back(i); fluxSum = 0; distanceSum = 0; } } int Greedy::partition(vector<int> &arr, vector<int> &ind, int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; swap(arr[i], arr[j]); swap(ind[i], ind[j]); } } swap(arr[i + 1], arr[high]); swap(ind[i + 1], ind[high]); return (i + 1); } void Greedy::quickSort(vector<int> &arr, vector<int> &ind, int low, int high) { if (low < high) { int pi = partition(arr, ind, low, high); quickSort(arr, ind, low, pi - 1); quickSort(arr, ind, pi + 1, high); } } void Greedy::orderVectors() { _solutionVector.resize(_sizeVectors); for (int i = _sizeVectors - 1; i >= 0; --i) _solutionVector[_fluxIndex[i]] = _distanceIndex[_sizeVectors - 1 - i]; } const vector<int> &Greedy::getSolutionVector() const { return _solutionVector; } int Greedy::getSolutionCost() const { return _solutionCost; } const string Greedy::getLog() const { return Utils::getLog("Greedy", _log, _executionTime, _airport->getAirportName(), _sizeVectors, _solutionVector, _solutionCost); }
true
6e5bf9775a5ebb58f64edeb19557e42a37791908
C++
julianferres/concuSat
/logger/Logger.cpp
UTF-8
2,226
3.109375
3
[]
no_license
// // Created by julian on 10/27/20. // #include "Logger.h" using namespace std; //Declaro las variables de clase string Logger::rutaArchivoLog = "concuSat.log"; ofstream Logger::outstream; vector<string> Logger::stringsLoggerType; int Logger::modoDebug; void Logger::iniciar(int _modoDebug) { stringsLoggerType = {"INFO", "DEBUG"}; rutaArchivoLog = "concuSat.log"; outstream.open(rutaArchivoLog, ios::out); LOG_INFO("Iniciando log."); LOG_DEBUG("Iniciando log DEBUG."); modoDebug = _modoDebug; } //Cierro el archivo que tengo abierto para log, y termino void Logger::terminar() { LOG_DEBUG("Terminando log DEBUG."); LOG_INFO("Terminando log."); outstream.close(); } void Logger::escribir(int _modoDebug, string msg, string archivo, long linea) { //Cuando estamos en modo normal los LOG_DEBUG no tienen efecto if (modoDebug < _modoDebug) return; // En esta parte calculo todas las constantes de padding, para poder // alinear [INFO] y [DEBUG], el nombre y linea de archivo // la hora y el mensaje string timestamp = obtenerTimestamp(); string nombreArchivo = limpiarPathArchivo(archivo); //Sumas de longitudes para poder acomodar el padding int largoMetadata = stringsLoggerType[_modoDebug].size() + nombreArchivo.size() + (linea >= 100); string padding(AJUSTE - largoMetadata + _modoDebug, ' '); outstream << "[" << stringsLoggerType[_modoDebug] << "]" << " "[_modoDebug]; outstream << " " << limpiarPathArchivo(nombreArchivo) << ":" << to_string(linea); outstream << padding; outstream << "(" << timestamp << ") ||"; outstream << " " << msg << "\n"; } string Logger::obtenerTimestamp() { time_t tiempoAct = time(nullptr); struct tm *tiempoInfo; char buff[100]; time(&tiempoAct); tiempoInfo = localtime(&tiempoAct); strftime(buff, sizeof(buff), "%H:%M:%S", tiempoInfo); return string(buff); } string Logger::limpiarPathArchivo(const string &pathArchivo) { string nombreArchivo; for (char c: pathArchivo) { nombreArchivo += c; if (c == '/') nombreArchivo = ""; //Desecho lo anterior al caracter separador de carpetas en linux } return nombreArchivo; }
true
23c882c9d295c2aafa5c6f09d726be407364816e
C++
uselessboy-7/laba3_Akhmaev
/AVLTree.hpp
UTF-8
13,088
3.34375
3
[]
no_license
#ifndef LAB3_CLION_AVLTREE_HPP #define LAB3_CLION_AVLTREE_HPP #include <utility> #include <stdexcept> template<typename T> T max(T &&a, T &&b) { return a > b ? a : b; } template<typename T, typename V> class AVLTree { public: using traversalType = void (*)(void *&, void *&, void *&); private: struct Node { public: Node(T k, V v) : key(k), val(v), height(1), left(nullptr), right(nullptr) {} explicit Node(Node *node); explicit Node(const Node *node); T key; V val; unsigned int height; Node *left, *right; ~Node(); }; int _height(Node *) const; void _updateHeight(Node *); int _balanceFactor(Node *) const; Node *_rotateRight(Node *); Node *_rotateLeft(Node *); Node *_balance(Node *); Node *_insert(Node *, T, V); Node *_get(Node *, T); Node *_findMin(Node *) const; Node *_findMax(Node *) const; Node *_find(Node *, T) const; Node *_removeMin(Node *); Node *_remove(Node *, T); void _assertEmpty() const; template<typename func> void _traversal(Node *, Node *, traversalType, func); template<typename func> void _constTraversal(Node *, Node *, traversalType, func) const; size_t _sumSize(Node *) const; Node *_root; int _size; public: AVLTree() : _root(nullptr), _size(0) {} AVLTree(const AVLTree<T, V> &Tree); AVLTree &operator=(const AVLTree<T, V> &Tree); void insert(T, V); void erase(T key) { _assertEmpty(); _root = _remove(_root, key); --_size; } V &get(T); Node *getRoot(); bool canFind(T key) { return _find(_root, key) != nullptr; } std::pair<const T &, V &> find_min() const { _assertEmpty(); Node *min_node = _findMin(_root); return {min_node->key, min_node->val}; } std::pair<const T &, V &> find_max() const { _assertEmpty(); Node *max_node = _findMax(_root); return {max_node->key, max_node->val}; } template<typename func> void traversal(traversalType type, func foo) { _traversal(_root, nullptr, type, foo); } template<typename func> void constTraversal(traversalType type, func foo) const { _constTraversal(_root, nullptr, type, foo); } size_t size() const noexcept { return _size; } int height() const noexcept { return _root->height; } AVLTree<T, V> *subTree(T key) const; bool areIdentical(Node *, Node *); bool isSubtree(Node *, Node *); V &operator[](T key); void clear(); ~AVLTree(); // Traversals static void RtLR(void *&n1, void *&n2, void *&n3) { std::swap(n1, n2); } static void RtRL(void *&n1, void *&n2, void *&n3) { std::swap(n2, n3); std::swap(n1, n3); } static void LRRt(void *&n1, void *&n2, void *&n3) { std::swap(n2, n3); } static void LRtR(void *&n1, void *&n2, void *&n3) {} static void RLRt(void *&n1, void *&n2, void *&n3) { std::swap(n1, n3); std::swap(n2, n3); } static void RRtL(void *&n1, void *&n2, void *&n3) { std::swap(n1, n3); } }; template<typename T, typename V> AVLTree<T, V>::Node::Node(const AVLTree::Node *node) : key(node->key), val(node->val), height(node->height) { if (node->left != nullptr) left = new Node(node->left); else left = nullptr; if (node->right != nullptr) right = new Node(node->right); else right = nullptr; } template<typename T, typename V> AVLTree<T, V>::Node::Node(AVLTree::Node *node) : key(node->key), val(node->val), height(node->height) { if (node->left != nullptr) left = new Node(node->left); else left = nullptr; if (node->right != nullptr) right = new Node(node->right); else right = nullptr; } template<typename T, typename V> AVLTree<T, V>::Node::~Node() { delete left; delete right; } template<typename T, typename V> inline int AVLTree<T, V>::_height(Node *node) const { return node ? node->height : 0; } template<typename T, typename V> inline void AVLTree<T, V>::_updateHeight(Node *node) { node->height = max(_height(node->left), _height(node->right)) + 1; } template<typename T, typename V> inline int AVLTree<T, V>::_balanceFactor(Node *node) const { return _height(node->right) - _height(node->left); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_rotateRight(Node *node) { Node *buff = node->left; node->left = buff->right; buff->right = node; _updateHeight(node); _updateHeight(buff); return buff; } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_rotateLeft(Node *node) { Node *buff = node->right; node->right = buff->left; buff->left = node; _updateHeight(node); _updateHeight(buff); return buff; } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_balance(Node *node) { _updateHeight(node); if (_balanceFactor(node) == 2) { if (_balanceFactor(node->right) < 0) node->right = _rotateRight(node->right); node = _rotateLeft(node); } if (_balanceFactor(node) == -2) { if (_balanceFactor(node->left) > 0) node->left = _rotateLeft(node->left); node = _rotateRight(node); } return node; } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_insert(Node *node, T key, V val) { if (node == nullptr) { return new Node(key, val); } if (node->key == key) { node->val = key; } if (key < node->key) node->left = _insert(node->left, key, val); else node->right = _insert(node->right, key, val); _updateHeight(node); _size++; return _balance(node); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_get(Node *node, T key) { if (node == nullptr) throw std::out_of_range("AVL_Tree out of range!"); if (key == node->key) return node; if (key < node->key) return _get(node->left, key); else return _get(node->right, key); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_findMin(Node *node) const { return node->left ? _findMin(node->left) : node; } template<typename T, typename V> inline void AVLTree<T, V>::insert(T key, V val) { if (_root == nullptr) { _root = new Node(key, val); } else { _root = _insert(_root, key, val); } } template<typename T, typename V> inline V &AVLTree<T, V>::get(T key) { return _get(_root, key)->val; } template<typename T, typename V> AVLTree<T, V>::~AVLTree() { delete _root; _size = 0; } template<typename T, typename V> AVLTree<T, V>::AVLTree(const AVLTree<T, V> &Tree) : _root(Tree._root ? new Node(Tree._root) : nullptr), _size(Tree._size) {} template<typename T, typename V> AVLTree<T, V> &AVLTree<T, V>::operator=(const AVLTree<T, V> &Tree) { delete _root; _root = new Node(Tree._root); _size = Tree._size; return *this; } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_find(AVLTree::Node *node, T key) const { if (node == nullptr) return nullptr; if (key == node->key) return node; if (key < node->key) return _find(node->left, key); if (key > node->key) return _find(node->right, key); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_remove(AVLTree::Node *node, T key) { if (node == nullptr) throw std::out_of_range("AVLTree out of range!"); if (key < node->key) node->left = _remove(node->left, key); else if (key > node->key) node->right = _remove(node->right, key); else { Node *left = node->left; Node *right = node->right; node->left = nullptr; node->right = nullptr; delete node; if (right == nullptr) return left; Node *min = _findMin(right); min->right = _removeMin(right); min->left = left; return _balance(min); } return _balance(node); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_removeMin(AVLTree::Node *node) { if (node->left == nullptr) return node->right; node->left = _removeMin(node->left); return _balance(node); } template<typename T, typename V> V &AVLTree<T, V>::operator[](T key) { if (!canFind(key)) { insert(key, V()); } return get(key); } template<typename T, typename V> template<typename func> void AVLTree<T, V>::_traversal(AVLTree::Node *node, AVLTree::Node *parent, AVLTree::traversalType type, func foo) { if (node == nullptr) return; if (node == parent) { foo(node->key, node->val); } else { void *n1 = node->left, *n2 = node, *n3 = node->right; type(n1, n2, n3); _traversal((Node *) n1, node, type, foo); _traversal((Node *) n2, node, type, foo); _traversal((Node *) n3, node, type, foo); } } template<typename T, typename V> void AVLTree<T, V>::_assertEmpty() const { if (_root == nullptr) throw std::logic_error("AVLTree assert empty"); } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::_findMax(AVLTree::Node *node) const { return node->right ? _findMax(node->right) : node; } template<typename T, typename V> template<typename func> void AVLTree<T, V>::_constTraversal(AVLTree::Node *node, AVLTree::Node *parent, AVLTree::traversalType type, func foo) const { if (node == nullptr) return; if (node == parent) { foo(node->key, node->val); } else { void *n1 = node->left, *n2 = node, *n3 = node->right; type(n1, n2, n3); _constTraversal((Node *) n1, node, type, foo); _constTraversal((Node *) n2, node, type, foo); _constTraversal((Node *) n3, node, type, foo); } } template<typename T, typename V> AVLTree<T, V> *AVLTree<T, V>::subTree(T key) const { const Node *node = _find(_root, key); auto *res = new AVLTree(); res->_root = new Node(node); res->_size = res->_sumSize(res->_root); return res; } template<typename T, typename V> size_t AVLTree<T, V>::_sumSize(AVLTree::Node *node) const { if (node == nullptr) return 0; else return _sumSize(node->left) + _sumSize(node->right) + 1; } template<typename T, typename V> void AVLTree<T, V>::clear() { delete _root; _root = nullptr; } template<typename T, typename V> typename AVLTree<T, V>::Node *AVLTree<T, V>::getRoot() { return _root; } template<typename T, typename V> bool AVLTree<T, V>::areIdentical(AVLTree::Node *root1, AVLTree::Node *root2) { if (root1 == NULL && root2 == NULL) return true; if (root1 == NULL || root2 == NULL) return false; return (root1->val == root2->val && areIdentical(root1->left, root2->left) && areIdentical(root1->right, root2->right)); } template<typename T, typename V> bool AVLTree<T, V>::isSubtree(AVLTree::Node *root1, AVLTree::Node *root2) { if (root2 == NULL) return true; if (root1 == NULL) return false; if (areIdentical(root1, root2)) return true; return isSubtree(root1->left, root2) || isSubtree(root1->right, root2); } template<typename T, typename V, typename func> AVLTree<T, V> map(const AVLTree<T, V> &tree, func foo) { AVLTree<T, V> res = tree; res.traversal(res.LRtR, [foo](const T &key, V &val) { val = foo(val); }); return res; } template<typename T, typename V, typename func> AVLTree<T, V> where(const AVLTree<T, V> &tree, func foo) { AVLTree<T, V> res; tree.constTraversal(tree.LRtR, [&foo, &res](const T &key, const V &val) { if (foo(val)) { res.insert(key, val); } }); return res; } template<typename T, typename V, typename func> V reduce(const AVLTree<T, V> &tree, V init, func foo, typename AVLTree<T, V>::traversalType t_type = AVLTree<T, V>::LRtR) { V res = init; tree.constTraversal(t_type, [&foo, &res](const T &key, const V &val) { res = foo(val, res); }); return res; } #endif //LAB3_CLION_AVLTREE_HPP
true
07a8baca87dc63909c99602a150bc687a24ffe9a
C++
MaxMade/ARMOS
/inc/kernel/cpu_local.h
UTF-8
1,048
2.9375
3
[]
no_license
#ifndef _INC_KERNEL_CPU_LOCAL_H_ #define _INC_KERNEL_CPU_LOCAL_H_ #include <cstdlib.h> #include <kernel/cpu.h> #include <kernel/config.h> /** * @file kernel/cpu_local.h * @brief CPU local data */ /** * @class cpu_local * @brief CPU local data */ template<typename T> class cpu_local { private: /** * @var t * @brief CPU local data */ T t[MAX_NUM_CPUS]; public: /** * @fn cpu_local() * @brief Default initialization */ cpu_local() { } cpu_local(const cpu_local& other) = delete; cpu_local(cpu_local&& other) = delete; /** * @fn cpu_local(const T& other) * @brief Initialize with defaut value */ cpu_local(const T& other) { for (size_t i = 0; i < MAX_NUM_CPUS; i++) t = other; } /** * @fn T& get() * @brief Get CPU local data */ T& get() { return t[CPU::getProcessorID()]; } /** * @fn const T& get() const * @brief Get CPU local data */ const T& get() const { return t[CPU::getProcessorID()]; } }; #endif /* ifndef _INC_KERNEL_CPU_LOCAL_H_ */
true
2311426408da57a8ec8af09db39b037d5b9e2dba
C++
Computer-engineering-FICT/Computer-engineering-FICT
/V семестр/Паралельне програмування/Редько/labs/palevo/3/Dima7/Dima7/funcs.cpp
WINDOWS-1251
3,796
2.65625
3
[]
no_license
/* * , -91 * . 7. MPI * 1.16 d=(A+B)*C * 2.17 a = MAX(MA - MB) * 3.11 D = SORT(A - M)*TRANS(MC)*/ #include "StdAfx.h" #include "funcs.h" #include <iostream> #include <fstream> int* PLUS(int ARG1[], int ARG2[]){ static int RESULT[N]; for(int i=0; i < N; i++) RESULT[i] = ARG1[i] + ARG2[i]; return RESULT; } int MUL(int ARG1[], int ARG2[]){ int RESULT = 0; for(int i=0; i < N; i++) RESULT += ARG1[i] * ARG2[i]; return RESULT; } int MAX(int ARG[]){ int RESULT = 0; for (int i=0; i<N; i++) if (RESULT<ARG[i]) RESULT = ARG[i]; return RESULT; } int MAX (Matrix ARG){ int RESULT = 0; for (int i=0; i<N; i++) for (int j=0; j<N; j++) if (RESULT<ARG.mas[i][j]) RESULT = ARG.mas[i][j]; return RESULT; } Matrix MINUS(Matrix ARG1, Matrix ARG2){ static Matrix RESULT; for(int i=0; i < N; i++) for(int j=0; j < N; j++) RESULT.mas[i][j] = ARG1.mas[i][j] - ARG2.mas[i][j]; return RESULT; } Matrix MUL(Matrix ARG1, Matrix ARG2){ static Matrix RESULT; for(int i=0; i<N; i++) for(int j=0; j<N; j++) { RESULT.mas[i][j]=0; for(int k=0; k<N; k++) RESULT.mas[i][j] += ARG1.mas[i][k] * ARG2.mas[k][j]; } return RESULT; } Matrix SORT(Matrix ARG){ for(int i=0; i<N; i++) for(int j=0; j<N; j++){ for(int k=j+1; k<N; k++) if (ARG.mas[i][j] < ARG.mas[i][k]){ int t = ARG.mas[i][j]; ARG.mas[i][j] = ARG.mas[i][k]; ARG.mas[i][k] = t; } for(int k=i+1; k<N; k++) for(int m=0; m<N; m++) if (ARG.mas[i][j] < ARG.mas[k][m]){ int t = ARG.mas[i][j]; ARG.mas[i][j] = ARG.mas[k][m]; ARG.mas[k][m] = t; } } return ARG; } Matrix TRANS(Matrix ARG){ Matrix Buf; for (int i=0; i<N; i++) for (int j=0; j<N; j++) Buf.mas[i][j]=ARG.mas[j][i]; return Buf; } Vector MUL(Matrix ARG1, Vector ARG2){ static Vector RESULT; for(int i=0; i<N; i++){ RESULT.mas[i] = 0; for(int j=0; j<N; j++) RESULT.mas[i] += ARG1.mas[i][j] * ARG2.mas[j]; } return RESULT; } Vector SORT(Vector ARG){ for(int i=0; i<N-1; i++) for(int j=i+1; j<N; j++) if (ARG.mas[i] > ARG.mas[j]){ int t = ARG.mas[j]; ARG.mas[j] = ARG.mas[i]; ARG.mas[i] = t; } return ARG; } Vector MINUS(Vector ARG1, Vector ARG2){ static Vector RESULT; for (int i=0; i<N; i++) RESULT.mas[i]=ARG1.mas[i]-ARG2.mas[i]; return RESULT; } void F1(int A[], int B[], int C[]){ int d = MUL(PLUS(A,B),C); std:: ofstream out("F1.txt"); out << "" << d; out.close(); } void F2(Matrix MA, Matrix MB){ int a = MAX(MINUS(MA,MB)); std:: ofstream out("F2.txt"); out << "" << a; out.close(); } void F3(Matrix MC, Vector A, Vector M){ Vector D=SORT(MUL(TRANS(MC),MINUS(A,M))); std:: ofstream out("F3.txt"); out << "" << std::endl; for(int i = 0; i < N; i++) out << D.mas[i] << ' '; out << std::endl; out.close(); }
true
ba0784ff576ea08ac9b41733d81a615b11ce8f57
C++
skishore/skewed
/skewed/basic_server_factory.h
UTF-8
575
2.859375
3
[ "MIT" ]
permissive
// If your protocol has a default constructor, you can use BasicServerFactory: // class MyProtocol : Protocol { ... } // BasicServerFactory<MyProtocol> server; // server.run(8000); #ifndef LIB_SKEWED_BASIC_SERVER_FACTORY #define LIB_SKEWED_BASIC_SERVER_FACTORY #include "protocol.h" #include "server_factory.h" namespace skewed { template <class P> class BasicServerFactory : public ServerFactory { public: Protocol* build_protocol(const Address& address) override { return new P(); } }; } // namespace skewed #endif // LIB_SKEWED_BASIC_SERVER_FACTORY
true
b48c8592f529beb2026510b04a7ace265c21358d
C++
0x1F9F1/mem
/include/mem/hasher.h
UTF-8
2,473
2.65625
3
[ "MIT" ]
permissive
/* Copyright 2018 Brick Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef MEM_HASHER_BRICK_H #define MEM_HASHER_BRICK_H #include "defines.h" namespace mem { class hasher { private: std::uint32_t hash_; public: hasher(std::uint32_t seed = 0) noexcept; void update(const void* data, std::size_t length) noexcept; template <typename T> void update(const T& value) noexcept; std::uint32_t digest() const noexcept; }; MEM_STRONG_INLINE hasher::hasher(std::uint32_t seed) noexcept : hash_(seed) {} MEM_STRONG_INLINE void hasher::update(const void* data, std::size_t length) noexcept { std::uint32_t hash = hash_; for (std::size_t i = 0; i < length; ++i) { hash += static_cast<const std::uint8_t*>(data)[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash_ = hash; } template <typename T> MEM_STRONG_INLINE void hasher::update(const T& value) noexcept { static_assert(std::is_integral<T>::value, "Invalid Type"); update(&value, sizeof(value)); } MEM_STRONG_INLINE std::uint32_t hasher::digest() const noexcept { std::uint32_t hash = hash_; hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } } // namespace mem #endif // MEM_HASHER_BRICK_H
true
f365c1aa28867b1d384384e6b51223c67736a0ab
C++
danache/coding
/剑指offer/二叉搜索树与双向链表/二叉搜索树与双向链表/main.cpp
UTF-8
1,150
3.109375
3
[]
no_license
// // main.cpp // 二叉搜索树与双向链表 // // Created by 萧天牧 on 17/5/16. // Copyright © 2017年 萧天牧. All rights reserved. // #include <iostream> #include <vector> #include <stack> using namespace std; struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } }; TreeNode* Convert(TreeNode* pRootOfTree){ if(!pRootOfTree) return pRootOfTree; TreeNode* p = pRootOfTree; TreeNode* pre = NULL; stack<TreeNode*> sta; //sta.push(pRootOfTree); bool first = true; while(p || !sta.empty()){ while(p){ sta.push(p); p = p -> left; } p = sta.top(); sta.pop(); if(first){ first = false; pRootOfTree = p; pre = p; } else{ pre -> right = p; p -> left = pre; pre = p; } p = p -> right; } return pRootOfTree; } int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
true
ea91b547446f265f370d07079073877a402524dc
C++
XinweiC/Small-Projects
/ThreadsTransform2D/threadDFT2d.cc
UTF-8
6,521
3.265625
3
[]
no_license
// Threaded two-dimensional Discrete FFT transform // Xinwei Chen // ECE8893 Project 2 #include <iostream> #include <string> #include <math.h> #include <pthread.h> #include "Complex.h" #include "InputImage.h" // You will likely need global variables indicating how // many threads there are, and a Complex* that points to the // 2d image being transformed. using namespace std; int nThreads=16; long width; long height; string s="Tower.txt"; InputImage image(s.c_str()); pthread_mutex_t mutex; pthread_mutex_t mutex1d; pthread_cond_t cond; int count; Complex * h; // Function to reverse bits in an unsigned integer // This assumes there is a global variable N that is the // number of points in the 1D transform. // unsigned ReverseBits(unsigned v) { // Provided to students unsigned n = width; // Size of array (which is even 2 power k value) unsigned r = 0; // Return value for (--n; n > 0; n >>= 1) { r <<= 1; // Shift return value r |= (v & 0x1); // Merge in next bit v >>= 1; // Shift reversal value } return r; } // GRAD Students implement the following 2 functions. // Undergrads can use the built-in barriers in pthreads. // Call MyBarrier_Init once in main void MyBarrier_Init()// you will likely need some parameters) { count=nThreads; pthread_mutex_init(&mutex,0); pthread_mutex_init(&mutex1d,0); pthread_cond_init(&cond, 0); } // Each thread calls MyBarrier after completing the row-wise DFT void MyBarrier() // Again likely need parameters { pthread_mutex_lock(&mutex); count = count - 1; if(count == 0){ pthread_cond_broadcast(&cond); count=nThreads; } else pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } void RTransform1D(Complex* h, int N) { pthread_mutex_lock(&mutex1d); for(unsigned i=0;i<N;i++) { if(i<ReverseBits(i)) { Complex temp = h[i]; h[i]=h[ReverseBits(i)]; h[ReverseBits(i)]=temp; } } for(int np=2;np<=N;np=np*2) for(int w=0;w<N/np;w++) for(int k=0;k<np/2;k++) { Complex wn; wn.real = cos(2 * M_PI * k / np); wn.imag = sin(2 * M_PI * k / np); int index = np*w+k; int pair = np*w+k+np/2; Complex temp = h[index]; h[index]=h[index]+h[index+np/2]*wn; h[pair]=temp-h[index+np/2]*wn; } for(int i=0;i<N;i++) h[i]=h[i]*((double) 1/ N); pthread_mutex_unlock(&mutex1d); } void Transform1D(Complex* h, int N) { pthread_mutex_lock(&mutex1d); for(unsigned i=0;i<N;i++) { if(i<ReverseBits(i)) { Complex temp = h[i]; h[i]=h[ReverseBits(i)]; h[ReverseBits(i)]=temp; } } for(int np=2;np<=N;np=np*2) for(int w=0;w<N/np;w++) for(int k=0;k<np/2;k++) { Complex wn; wn.real = cos(2 * M_PI * k / np); wn.imag = -sin(2 * M_PI * k / np); int index = np*w+k; int pair = np*w+k+np/2; Complex temp = h[index]; h[index]=h[index]+h[index+np/2]*wn; h[pair]=temp-h[index+np/2]*wn; } pthread_mutex_unlock(&mutex1d); } void T(Complex * h1, Complex * h2, long width, long height) { for (long i = 0; i < width; i++) for (long j = 0; j < height; j++) { h2[width * j + i] = h1[width * i + j]; } } void* Transform2DTHread(void* v) { // This is the thread startign point. "v" is the thread number // Calculate 1d DFT for assigned rows // wait for all to complete // Calculate 1d DFT for assigned columns // Decrement active count and signal main if all complete long myrank=(long)v; for (long i = myrank * height / nThreads; i < myrank * height / nThreads + height / nThreads; i++) { Transform1D(&h[width * i], width); } MyBarrier(); if(myrank==0) { Complex* array = new Complex[width*height]; T(h, array, width, height); h = array; } MyBarrier(); for (long i = myrank * height / nThreads; i < myrank * height / nThreads + height / nThreads; i++) { Transform1D(&h[width * i], width); } MyBarrier(); if(myrank==0) { Complex* array = new Complex[width*height]; T(h, array, width, height); h = array; image.SaveImageData("Tower-DFT2D.txt", h, width, height); } MyBarrier(); for (long i = myrank * height / nThreads; i < myrank * height / nThreads + height / nThreads; i++) { RTransform1D(&h[width * i], width); } MyBarrier(); if(myrank==0) { Complex* array = new Complex[width*height]; T(h, array, width, height); h = array; } MyBarrier(); // Complex * temp = new Complex[width*height]; for (long i = myrank * height / nThreads; i < myrank * height / nThreads + height / nThreads; i++) { RTransform1D(&h[width * i], width); } MyBarrier(); if(myrank==0) { Complex* array = new Complex[width*height]; T(h, array, width, height); h = array; } if(myrank==0) { image.SaveImageData("MyAfterInverse.txt", h, width, height); /* ifstream out; string str = "Tower-DFT2DInverse.txt"; out.open(str.c_str(), ios::in); string line; while (!out.eof()) { std::getline(out, line); cout << line << endl; } out.close(); */ } return 0; } void Transform2D(const char* inputFN) { // Do the 2D transform here MyBarrier_Init(); // Create the helper object for reading the image // Create the global pointer to the image array data image =*( new InputImage(inputFN)); width = image.GetWidth(); height = image.GetHeight(); // 2) Use MPI to find how many CPUs in total, and which one // // this process is // MPI_Comm_size(MPI_COMM_WORLD, &nCpus); // MPI_Comm_rank(MPI_COMM_WORLD, &myrank); h=image.GetImageData(); pthread_t * pt=new pthread_t[nThreads]; for (long i = 0; i < nThreads; ++i) { // pThread variable (output param from create) pthread_create((pt)+i, 0, Transform2DTHread, (void*)i); } for (long i = 0; i < nThreads; ++i) { // pthread_t pt; // pThread variable (output param from create) pthread_join(*(pt+i),NULL); } // pthread_join(thread1_id, NULL); // Create 16 threads // Wait for all threads complete // Write the transformed data } int main(int argc, char** argv) { string fn("Tower.txt"); // InputImage image(inputFN); // default file name if (argc > 1) fn = string(argv[1]); // if name specified on cmd line // MPI initialization here Transform2D(fn.c_str()); // Perform the transform. }
true
5736421a76f1d1e0a5001eb7fd2de32293d27699
C++
doughodson/mat4-utils
/src/writer.cpp
UTF-8
1,640
2.765625
3
[]
no_license
//------------------------------------------------------- // writes a valid matlab version 4 file //------------------------------------------------------- #include <iostream> #include <fstream> #include <cstdlib> #include <string> #include <cstdint> #include "utils.hpp" int main(int argc, char** argv) { std::cout << "Num of args : " << argc << std::endl; std::cout << "argv[0] : " << argv[0] << std::endl; if (argc > 1) { std::cout << "argv[1] : " << argv[1] << std::endl; } else { std::cout << "writer <filename>\n"; std::exit(0); } std::ofstream ofs; ofs.open(argv[1], std::ofstream::binary); if (ofs.fail()) { std::cout << "can't open <filename>\n"; } // define and write matrix header information MAT4Header header{0000, 1, 1, 1, 2}; ofs.write(reinterpret_cast<const char*>(&header.mopt), sizeof(header.mopt)); ofs.write(reinterpret_cast<const char*>(&header.nrows), sizeof(header.nrows)); ofs.write(reinterpret_cast<const char*>(&header.ncols), sizeof(header.ncols)); ofs.write(reinterpret_cast<const char*>(&header.imagf), sizeof(header.imagf)); ofs.write(reinterpret_cast<const char*>(&header.namelen), sizeof(header.namelen)); // variable name const char* pname{"x"}; ofs.write(pname, sizeof(char)+1); // matrix data const double real_data{1.0}; const double imag_data{2.0}; const int mn{header.nrows * header.ncols}; ofs.write(reinterpret_cast<const char*>(&real_data), sizeof(double)); if (header.imagf) { ofs.write(reinterpret_cast<const char*>(&imag_data), sizeof(double)); } ofs.close(); return 0; }
true
9fa04bb55ffb1178d0e4e8c5d04b64c0b7fec4d6
C++
ChrisYoungGH/LeetCode
/tag/Tree/SameTree.cc
UTF-8
2,407
3.859375
4
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <climits> using namespace std; /** * Definition for a binary tree node. */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void preorder(TreeNode *node) { if (node == NULL) { return; } cout << node->val << " "; preorder(node->left); preorder(node->right); } void inorder(TreeNode *node) { if (node == NULL) { return; } inorder(node->left); cout << node->val << " "; inorder(node->right); } void postorder(TreeNode *node) { if (node == NULL) { return; } postorder(node->left); postorder(node->right); cout << node->val << " "; } void display(TreeNode *node) { cout << "Preorder: "; preorder(node); cout << endl; cout << "Inorder: "; inorder(node); cout << endl; cout << "Postorder: "; postorder(node); cout << endl; } TreeNode* build_tree(std::vector<int> vec) { int n = vec.size(); TreeNode **nodes = new TreeNode*[n]; for (int i = 0; i < n; i++) { TreeNode *&node = nodes[i]; if (vec[i] != -1) { node = new TreeNode(vec[i]); } else { node = NULL; } } for (int i = 0; i < n; i++) { TreeNode *&node = nodes[i]; int leftId = i * 2 + 1; int rightId = i * 2 + 2; if (leftId < n) { node->left = nodes[leftId]; } if (rightId < n) { node->right = nodes[rightId]; } } return nodes[0]; } void free_tree(TreeNode *root) { if (!root) { return; } free_tree(root->left); free_tree(root->right); delete root; } bool isSameTree(TreeNode* p, TreeNode* q) { if (!p && !q) { return true; } if (!p || !q) { return false; } if (p->val != q->val) { return false; } return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); } int main() { int a[] = {1,2,1}; int b[] = {1,1,2}; vector<int> va(a, a + sizeof(a) / sizeof(int)); vector<int> vb(b, b + sizeof(b) / sizeof(int)); TreeNode *p = build_tree(va); TreeNode *q = build_tree(vb); cout << isSameTree(p, q) << endl; free_tree(p); free_tree(q); return 0; }
true
65ccfbc93d7eb4edac7d5f23fd4921afb42143df
C++
amadues2013/Arduino
/Heatbeat/applet/Heatbeat.cpp
UTF-8
4,391
2.90625
3
[]
no_license
/* Heartbeat :: I <3 Lilypad This is the code for creating a Heartbeat using textile buttons and blinking it back with a textile Perfboard heart. by troykyo http://www.troykyo.net */ #include "WProgram.h" void setup(); void loop (); void loop (); const int buttonPin1 = 15; // the number of the pushbutton pin const int buttonPin2 = 16; // the number of the pushbutton pin const int ledPin[] = {-1,2,13,0,1,3,4,5,6,7,8,9,10,11,12,14,14,14,14}; // Array for Led heart pin, change starting from 1 int buttonState = 0; // variable for reading the pushbutton status int whichBeat; // Counter for the beat array int timer = 500; //time per beat int beattimer; //time per beat //int x; //counter for the beat loop void setup() { // initialize the LED pin as an output: // pinMode(ledPin, OUTPUT); // init LED output pin pinMode(buttonPin1, INPUT); //init input button pin pinMode(buttonPin2, INPUT); //init input button pin } void loop () { Serial.begin(9600); // serial comm, data rate: 9600 bps Serial.println("Begin"); //blink the assigned pattern using the array, keep blinking until a new pattern array is entered whichBeat = 0; //beat counter reset buttonState = digitalRead(buttonPin1); //read the button state //while(buttonState == LOW){ //Blink the array pattern until the Serial.println("go"); //if (whichBeat < 0){ whichBeat = 0; //if the end of the array is reached, return to the begining //} for (whichBeat = 0; whichBeat < 16; whichBeat ++){// build up the heart buttonState = digitalRead(buttonPin1); //read the button state //Serial.print(whichBeat); if (buttonState == HIGH){ // bail out on button sensor detect whichBeat = 0; //reset the beat break; } digitalWrite(ledPin[whichBeat], HIGH); // turn LED on if (whichBeat < 2){ //Skip this the first two times digitalWrite(ledPin[(whichBeat-2)], LOW); // turn the LED three times ago off } Serial.print(whichBeat); delay (timer); } //} for (whichBeat = 16; whichBeat > 0; whichBeat --){// build up the heart buttonState = digitalRead(buttonPin1); //read the button state if (buttonState == HIGH){ // bail out on button sensor detect whichBeat = 0; //reset the beat break; digitalWrite(ledPin[whichBeat], HIGH); // turn LED on if (whichBeat > 15){ //Skip this the first two times digitalWrite(ledPin[(whichBeat-2)], LOW); // turn the LED three times ago off delay (timer); } } // } buttonState = digitalRead(buttonPin1); //read the button state } /* Start Recording timer = millis(); beattimer = millis(); whichBeat = 0; // reset the array position for (x = 0; x < 42; x ++) { //reset the array beats[x] = 0; } while ((timer - beattimer) < 3000){ // keep recording as long as there is no break longer than 3 seconds buttonState = digitalRead(buttonPin1); // check the button beattimer = millis(); // set the time of the beat if (buttonState == HIGH){ // read in time on sensor detect buttonState = digitalRead(buttonPin1); //read the button state whichBeat++; //move to the next number in the array // next beat of the beat cycle beats[whichBeat] = (beattimer-timer); // record the pause length into the array while(buttonState == HIGH){ // bail out when the button is let go. digitalWrite(ledPin, HIGH); //turn the led on in time with the beat buttonState = digitalRead(buttonPin1); //read the button state } timer = beattimer(); // reset the time delay whichBeat++; //move to the next number in the array // next beat of the beat cycle beattimer = millis(); // set the time of the beat Serial.print (beattimer); // testing line Serial.print (", "); beats[whichBeat] = (beattimer-timer); // record the beat length into the array } }*/ int main(void) { init(); setup(); for (;;) loop(); return 0; }
true
68f7a2fa184a0dad83a2297c61618d7307328ce3
C++
Lemmibl/TCPChatServer
/TCPChatServer/Network/PacketTypes/UserDataPacket.cpp
UTF-8
2,295
2.90625
3
[ "MIT" ]
permissive
#include "UserDataPacket.h" UserDataPacket::UserDataPacket(CEGUI::String text, CEGUI::argb_t color, UserID senderID) : Packet(PacketType::USER_DATA, (sizeof(color)+text.size()), senderID) { Serialize(text, color); } UserDataPacket::UserDataPacket(char* inData, int dataSize, UserID senderID) : Packet(PacketType::USER_DATA, dataSize, senderID) { dataVector.resize(dataSize); memcpy(dataVector.data(), inData, dataSize); } UserDataPacket::~UserDataPacket() { } void UserDataPacket::Serialize(CEGUI::String text, CEGUI::argb_t color) { size_t textSize = text.size(); size_t structSize = textSize+sizeof(CEGUI::argb_t); //Have to cast to call ntohl(). unsigned int colorVal = static_cast<unsigned int>(color); colorVal = ntohl(colorVal); //Setup header too...? //header.Serialize(USERDATA, structSize); //I dont think I've identified any case where I need to do this dataVector.resize(structSize); //First we copy raw text data into our vector memcpy(dataVector.data(), text.data(), textSize); //Then we fill the last four bytes with color data memcpy(dataVector.data()+textSize, &colorVal, sizeof(CEGUI::argb_t)); } void UserDataPacket::Deserialize(char* inData, int dataSize, CEGUI::String* outUserName, CEGUI::argb_t* outUserTextColor ) { //Since this packet will contain username(string) plus user text color(CEGUI::argb_t) we calculate that once now and reuse value. Also makes it more readable. size_t textSize = dataSize-sizeof(CEGUI::argb_t); unsigned int colorVal(0); //Create a new string with data *outUserName = CEGUI::String(inData, textSize); //Fill color memcpy(&colorVal, inData+textSize, sizeof(CEGUI::argb_t)); *outUserTextColor = ntohl(colorVal); } void UserDataPacket::Deserialize(CEGUI::String* outUserName, CEGUI::argb_t* outUserTextColor) { //Since this packet will contain username(string) plus user text color(CEGUI::argb_t) we calculate that once now and reuse value. Also makes it more readable. size_t textSize = dataVector.size()-sizeof(CEGUI::argb_t); unsigned int colorVal(0); //Create a new string with data *outUserName = CEGUI::String((const CEGUI::utf8*)dataVector.data(), textSize); //Fill color memcpy(&colorVal, dataVector.data()+textSize, sizeof(CEGUI::argb_t)); *outUserTextColor = ntohl(colorVal); }
true
d4693565db5bbf668d0ca023660e1e24ca20451d
C++
sshjj/note
/leetcode/剑指offer/48最长不含重复字符的子字符串.cpp
UTF-8
708
3.65625
4
[]
no_license
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 示例 2: 输入: "bbbbb" 输出: 1 解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。 class Solution { public: int lengthOfLongestSubstring(string s) { unordered_map<char,int>hash; int res = 0; for(int i =0 ,j =0;j<s.size();j++){ hash[s[j]]++; while(hash[s[j]]>1){ hash[s[i++]]--; } res = max(res,j-i+1); } return res; } };
true
85818aba3db85e47be38e070de93fce4c988d241
C++
heis125/Grafy
/Grafy/Grafy.cpp
UTF-8
1,600
2.53125
3
[]
no_license
// // #include "pch.h" int main() { clock_t start; long double czas_trwania; srand((int)time(NULL)); double gestosc = 0.5; // gestość grafu watrość od 0 do 1 ! int ile_wierzcholkow = 25; // ilosc wierzchołków grafu int ile_krawedzi = (int)((ile_wierzcholkow*(ile_wierzcholkow - 1))*gestosc); // liczenie ile jest krawedzi przy zadanej gęstości int ilosc = 10; // ilosc grafów ofstream sasiedzi("sasiedzi.txt"); // tworzenie nowego pliku do zapisu macierzy sasiedztwa luc listy sasiedztwa ofstream wynik("wynik.txt"); // tworzenie nowego pliku do zapisu wyników Graf_L* A = new Graf_L[ilosc]; // Graf na liscie sąsiedztwa //Graf_M* A = new Graf_M[ilosc]; // Graf na macierzy sasiedztwa pliki(sasiedzi, wynik); for (int i = 0; i < ilosc; i++) // petla tworzeca grafy { tworzenie_pliku(ile_krawedzi, ile_wierzcholkow); // Tworzenie pliku z danymi potrabnymi do zbudowania grafu wczytywanie_z_pliku(A, i); A[i].zapisz(sasiedzi); // zapisywanie macierzy sąsiedztwa lub listy sąsiedztwa do pliku //A[i].wyswietl(); // wyświetlenie macierzy sąsiedztwa lub listy sąsiedztwa } start = clock(); // włączenie odliczania czasu for (int i = 0; i < ilosc; i++) // petla wykonujaca główny algorytm { A[i].dikstra(wynik); } czas_trwania = (clock() - start) / (double)CLOCKS_PER_SEC; // przeliczenia cykli zegara na sekundy cout << "Czas wykonania " << czas_trwania << "s" << endl; // wyświetlenie ile czasu sortował algorytm delete A; // usniecie grafów //system("PAUSE"); // pauza systemu potrzebna przy używaniu pliku wykonawczego }
true
1d7fc3fd741e5f9e40f29ef9ec6fbe53d01dfafd
C++
avinashvrm/Data-Structure-And-algorithm
/Dynamic Programming/Minimum Cost to Cut a Stick.cpp
UTF-8
2,094
3.75
4
[]
no_license
/*Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a stick of length 6 is labelled as follows: Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. You should perform the cuts in order, you can change the order of the cuts as you wish. The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of their lengths is the length of the stick before the cut). Return the minimum total cost of the cuts. Input: n = 7, cuts = [1,3,4,5] Output: 16 Explanation: Using cuts order = [1, 3, 4, 5] as in the input leads to the following scenario: The first cut is done to a rod of length 7 so the cost is 7. The second cut is done to a rod of length 6 (i.e. the second part of the first cut), the third is done to a rod of length 4 and the last cut is to a rod of length 3. The total cost is 7 + 6 + 4 + 3 = 20. Rearranging the cuts to be [3, 5, 1, 4] for example will lead to a scenario with total cost = 16 (as shown in the example photo 7 + 4 + 3 + 2 = 16).*/ class Solution { public: int solve(vector<int> &cuts,int st_i,int en_i,int startValue,int endValue,vector<vector<int>> &dp) { if(st_i>en_i) return 0; if(dp[st_i][en_i]!=-1) return dp[st_i][en_i]; int res = INT_MAX; int curr_cost = endValue - startValue; for(int k = st_i;k<=en_i;k++) { int first_half = solve(cuts,st_i,k-1,startValue,cuts[k],dp); int second_half = solve(cuts,k+1,en_i,cuts[k],endValue,dp); int temp = curr_cost + first_half + second_half; res = min(res,temp); } return dp[st_i][en_i] = res; } int minCost(int n, vector<int>& cuts) { int m = cuts.size(); sort(cuts.begin(),cuts.end()); vector<vector<int>> dp(m,vector<int>(m,-1)); return solve(cuts,0,m-1,0,n,dp); } };
true
3557830949e02057066d6a5b03cc48d1d7f59bb0
C++
roiser/libcxx
/test/std/utilities/time/time.cal/time.cal.ymd/time.cal.ymd.members/ok.pass.cpp
UTF-8
2,274
2.875
3
[ "NCSA", "MIT" ]
permissive
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <chrono> // class year_month_day; // constexpr bool ok() const noexcept; // Returns: m_.ok() && y_.ok(). #include <chrono> #include <type_traits> #include <cassert> #include "test_macros.h" int main() { using year = std::chrono::year; using month = std::chrono::month; using day = std::chrono::day; using year_month_day = std::chrono::year_month_day; constexpr month January = std::chrono::January; ASSERT_NOEXCEPT( std::declval<const year_month_day>().ok()); ASSERT_SAME_TYPE(bool, decltype(std::declval<const year_month_day>().ok())); static_assert(!year_month_day{year{-32768}, month{}, day{}}.ok(), ""); // All three bad static_assert(!year_month_day{year{-32768}, January, day{1}}.ok(), ""); // Bad year static_assert(!year_month_day{year{2019}, month{}, day{1}}.ok(), ""); // Bad month static_assert(!year_month_day{year{2019}, January, day{} }.ok(), ""); // Bad day static_assert(!year_month_day{year{-32768}, month{}, day{1}}.ok(), ""); // Bad year & month static_assert(!year_month_day{year{2019}, month{}, day{} }.ok(), ""); // Bad month & day static_assert(!year_month_day{year{-32768}, January, day{} }.ok(), ""); // Bad year & day static_assert( year_month_day{year{2019}, January, day{1}}.ok(), ""); // All OK for (unsigned i = 0; i <= 50; ++i) { year_month_day ym{year{2019}, January, day{i}}; assert( ym.ok() == day{i}.ok()); } for (unsigned i = 0; i <= 50; ++i) { year_month_day ym{year{2019}, month{i}, day{12}}; assert( ym.ok() == month{i}.ok()); } const int ymax = static_cast<int>(year::max()); for (int i = ymax - 100; i <= ymax + 100; ++i) { year_month_day ym{year{i}, January, day{12}}; assert( ym.ok() == year{i}.ok()); } }
true
5920b9495f3bac752db833dd8c524944b4332e4d
C++
Johannyjm/c-pro
/AtCoder/abc/abc187/old/e2.cpp
UTF-8
1,831
2.546875
3
[]
no_license
#include <bits/stdc++.h> #define rep(i, n) for(int i = 0; i < (n); ++i) #define rep1(i, n) for(int i = 1; i < (n); ++i) using namespace std; using ll = long long; int n; vector<vector<int>> g; vector<bool> seen; vector<int> rooted_tree(){ vector<int> ret(n); ret[0] = -1; seen.assign(n, false); seen[0] = true; stack<int> st; st.push(0); while(!st.empty()){ int v = st.top(); st.pop(); seen[v] = true; for(auto nv: g[v]){ if(seen[nv]) continue; st.push(nv); ret[nv] = v; } } return ret; } vector<ll> res; void dfs(int v){ seen[v] = true; for(auto nv: g[v]){ if(seen[nv]) continue; res[nv] += res[v]; dfs(nv); } } int main(){ cin.tie(nullptr); ios::sync_with_stdio(false); cin >> n; vector<ll> a(n-1), b(n-1); g.resize(n); rep(i, n-1){ cin >> a[i] >> b[i]; --a[i]; --b[i]; g[a[i]].push_back(b[i]); g[b[i]].push_back(a[i]); } vector<int> parent = rooted_tree(); // for(auto e: parent) cout << e << " "; // cout << endl; int q; cin >> q; res.resize(n, 0); while(q--){ int t, e, x; cin >> t >> e >> x; --e; // a is parent if(parent[b[e]] == a[e]){ if(t == 1){ res[0] += x; res[b[e]] -= x; } else{ res[b[e]] += x; } } // b is parent else{ if(t == 1){ res[a[e]] += x; } else{ res[0] += x; res[a[e]] -= x; } } } seen.assign(n, false); dfs(0); for(auto e: res) cout << e << endl; return 0; }
true
1b43648187e60bf6399105bc04a36434357caf67
C++
baxton/test
/test_lr.cpp
UTF-8
4,457
2.625
3
[]
no_license
// // g++ -DTESTS --std=c++0x -W -Wall -Wno-sign-compare -O2 -s -pipe -mmmx -msse -msse2 -msse3 proto.cpp -o proto.exe // g++ -DEMUL --std=c++0x -W -Wall -Wno-sign-compare -O2 -s -pipe -mmmx -msse -msse2 -msse3 proto.cpp -o proto.exe // #include <cstdlib> #include <cmath> #include <ctime> #include <vector> #include <algorithm> #include <iterator> #include <memory> #include <fstream> #include <iostream> #include <string> typedef double value_t; namespace rnd { void seed() { ::srand(time(NULL)); } value_t rand() { return (value_t)::rand() / RAND_MAX; } } namespace linalg { value_t dot(const value_t* v1, const value_t* v2, int size) { value_t r = 0.; for (int i = 0; i < size; ++i) { r += v1[i] * v2[i]; } return r; } void mul_scalar(value_t scalar, const value_t* v, value_t* r, int size) { for (int i = 0; i < size; ++i) { r[i] = v[i] * scalar; } } } namespace stat { template<typename T> void get_stat_online(const T* vec, size_t size, value_t& m, value_t& v, value_t& s, value_t& k) { value_t n, M1, M2, M3, M4; value_t delta, delta_n, delta_n2, term1; // init n = M1 = M2 = M3 = M4 = 0.; // process for (size_t i = 0; i < size; ++i) { value_t n1 = n++; delta = value_t(vec[i]) - M1; delta_n = delta / n; delta_n2 = delta_n * delta_n; term1 = delta * delta_n * n1; M1 += delta_n; M4 += term1 * delta_n2 * (n * n - 3 * n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3; M3 += term1 * delta_n * (n - 2) - 3 * delta_n * M2; M2 += term1; } m = M1; v = M2 / (n - 1.0); s = ::sqrt(n) * M3 / ::pow(M2, 1.5); k = n * M4 / (M2 * M2) - 3.0; } } namespace optimize { value_t reg_h(const value_t* theta, const value_t* x, int columns) { value_t r = linalg::dot(x, theta, columns); return r; } value_t reg_cost(const value_t* theta, const value_t* x, value_t* grad_x, value_t y, int columns) { // calc logistic val value_t h = reg_h(theta, x, columns); // calc cost part value_t delta = h - y; value_t cost = delta * delta / 2.; // calc gradient part linalg::mul_scalar(delta, x, grad_x, columns); return cost; } void minimize_gc(value_t* theta, const value_t* x, int columns, const value_t y, int max_iterations) { value_t grad[columns]; value_t e = 0.0001; value_t a = .5; value_t cost = reg_cost(theta, x, grad, y, columns); int cur_iter = 0; while (cost > e && cur_iter < max_iterations) { ++cur_iter; for (int i = 0; i < columns; ++i) { theta[i] = theta[i] - a * grad[i]; } value_t new_cost = reg_cost(theta, x, grad, y, columns); if (cost < new_cost) a /= 2.; cost = new_cost; } } inline value_t predict(const value_t* theta, const value_t* x, int columns) { return reg_h(theta, x, columns); } } value_t poli(value_t x1, value_t x2, value_t x3) { value_t y = 2. - x1 + 3. * x2 * x2 - 2.5 * x3 * x3 * x3; return y; } int main() { rnd::seed(); std::vector<value_t> X; std::vector<value_t> Y; size_t N = 2000; for (size_t n = 0; n < N; ++n) { X.push_back(1.); value_t x = rnd::rand() - .5; X.push_back(x); X.push_back(x*x); X.push_back(x*x*x); size_t idx = n * 4; value_t y = poli(x,x,x); // / 2000.; Y.push_back(y); std::cout << X[n*4] << " " << X[n*4+1] << " " << X[n*4+2] << " " << X[n*4+3] << " = " << Y[n] << std::endl; } std::vector<value_t> theta; for (size_t i = 0; i < 4; ++i) theta.push_back(rnd::rand() - .5); // for (size_t e = 0; e < 10; ++e) { for (size_t r = 0; r < 1500; ++r) { size_t idx = r * 4; optimize::minimize_gc(&theta[0], &X[idx], 4, Y[r], 1); } } // size_t count = 0; value_t s = 0; for (size_t r = 1500; r < N; ++r) { size_t idx = r * 4; value_t p = optimize::predict(&theta[0], &X[idx], 4); s = (p - Y[r]) * (p - Y[r]); count += 1; std::cout << p << "\t" << Y[r] << std::endl; } std::cout << theta[0] << " " << theta[1] << " " << theta[2] << " " << theta[3] << std::endl; std::cout << "2 (-1) 3 (-2.5)" << std::endl; std::cout << "AVR ERR: " << (s / count) << std::endl; }
true
cd0c102a30bbc683865ef9d8eb0e831b43835dfc
C++
waxsf/ctci
/1_21.cpp
UTF-8
282
3.359375
3
[]
no_license
#include<iostream> using namespace std; void reverse(char *s) { char *p = s,*q = s; char c; while(*q) { q++; } q--; while(p < q) { cout<<c<<endl; c = *p; *p = *q; *q = c; q--; p++; } } int main() { char s[] = "1234567"; reverse(s); cout<<s<<endl; }
true
fbd360aa4520afb930a513ac777b9c62374c4589
C++
AaronBui-gif/GroupAssn2SED
/GroupAssn2SED/AccountList.h
UTF-8
710
2.671875
3
[]
no_license
#pragma once #include <iostream> #include <string> #include <vector> #include "Account.h" using namespace std; enum AccountType { Regular, Guest, Vip }; class AccountList { private: vector<Account*> accountList; int numAccount; string filename; AccountType accountType; int id; public: AccountList(); AccountList(string filename); AccountList(vector<Account*> accountList, int numAccount, int id, AccountType accountType); ~AccountList(); int getNumAccount(); vector<Account*> getAccountList(); void addAccount(Account* account); bool updateAccount(Account* account); bool validateAccount(string input); bool promoteAccount(enum AccountType); bool getDatas(); void displayAllAccount(); };
true
95c80f97dd93e337fdb921cb7543bbaeda28e0ab
C++
ledungsbacken/linkedList
/LinkedList.cpp
UTF-8
1,370
3.515625
4
[]
no_license
#include "LinkedList.h" void LinkedList::add(string data) { this->cursor = new Node(data); if(this->getNumberOfNodes() > 0) { this->tail->setNext(this->cursor); } else { this->head = this->cursor; } this->tail = this->cursor; this->numberOfNodes++; } void LinkedList::remove(Node* node) { this->moveToHead(); this->temp = this->cursor; bool isFound = false; for(int i = 0; i < this->getNumberOfNodes() && !isFound; i++) { if(this->cursor == node) { this->moveToNext(); this->temp->setNext(this->cursor); delete node; this->numberOfNodes--; isFound = true; } this->temp = this->cursor; this->moveToNext(); } } Node* LinkedList::get(int index) { this->cursor = this->head; for(int i = 0; i < this->getNumberOfNodes(); i++) { if(i == index) { return this->cursor; } this->moveToNext(); } } Node* LinkedList::current() { return this->cursor; } void LinkedList::moveToNext() { if(this->cursor->getNext() != NULL) { this->cursor = this->cursor->getNext(); } } void LinkedList::moveToHead() { this->cursor = this->head; } void LinkedList::moveToTail() { this->cursor = this->tail; }
true
c31c3c5936d5bcee5c0a42f92046eaa694623335
C++
jasy/gcj
/gcj2010QRA.cpp
UTF-8
290
2.578125
3
[]
no_license
#include <iostream> #include <string> int main () { int T; std::cin >> T; for (int x=1; x<=T; ++x) { unsigned long N,K; std::cin >> N >> K; unsigned long l = (1ul<<N)-1; std::string y = (K & l)==l? "ON": "OFF"; std::cout << "Case #" << x << ": " << y << "\n"; } return 0; }
true
28ac880ab90d329d92256c6c1ba8193ae627a0db
C++
WhiZTiM/coliru
/Archive2/fa/759f6207e206a2/main.cpp
UTF-8
769
4.0625
4
[]
no_license
#include <iostream> int main( int, char** ) { using namespace std; // The lambda function is what appears on the right side of the equals // sign, but the type of "fn" is called a closure. Important to remember // what a closure is. auto fn1 = []{}; // We can call it like a regular function: fn1(); // The stuff between the curly braces is the function body. We can put // anything in the body that we could put in the body of a normal function: // This is the same syntax, just split across multiple lines: auto fn2 = [] { cout << "You called the lambda function via a closure object!" << endl; }; // It get's evaluated, just like a normal function! fn2(); return 0; }
true
7fcf78145088895f6bde619e9a4ce387d6d8e350
C++
sailesh2/CompetitiveCode
/2020/lcContest147B.cpp
UTF-8
1,638
2.984375
3
[]
no_license
class Solution { private: pair<int,int> getPos(char alphabet){ return make_pair((alphabet-'a')/5,(alphabet-'a')%5); } public: string alphabetBoardPath(string target) { int r=0,c=0; string ans=""; for(int i=0;i<target.length();i++){ pair<int,int> dest=getPos(target[i]); int r1=dest.first; int c1=dest.second; if(target[i]!='z'){ if(r1>r){ for(int j=0;j<r1-r;j++) ans.push_back('D'); }else if(r1<r){ for(int j=0;j<r-r1;j++) ans.push_back('U'); } if(c1>c){ for(int j=0;j<c1-c;j++) ans.push_back('R'); }else if(c1<c){ for(int j=0;j<c-c1;j++) ans.push_back('L'); } }else{ if(c1>c){ for(int j=0;j<c1-c;j++) ans.push_back('R'); }else if(c1<c){ for(int j=0;j<c-c1;j++) ans.push_back('L'); } if(r1>r){ for(int j=0;j<r1-r;j++) ans.push_back('D'); }else if(r1<r){ for(int j=0;j<r-r1;j++) ans.push_back('U'); } } ans.push_back('!'); r=r1; c=c1; } return ans; } };
true
9040e960201e2a078b6824e35a3ca40c7c69c096
C++
vgeirnaert/arduino_test
/TickableService.cpp
UTF-8
479
2.8125
3
[]
no_license
#include "TickableService.h" void TickableService::setInterval(unsigned int tickIntervalMillis) { interval = tickIntervalMillis; } void TickableService::tick(Context context) { // handle overflow after x time if(context.currentTime < previousTickMillis) { previousTickMillis = 0; } // trigger onTick only at the appropriate time if(context.currentTime - previousTickMillis > interval) { previousTickMillis = context.currentTime; onTick(context); } }
true
dafe86315aa3bfeff532d464614d280fbbe9fac6
C++
shrey/templates_cpp
/ConceptsAndQuestions/graphs/shortest_path_prime.cpp
UTF-8
2,565
3.03125
3
[]
no_license
//https://www.geeksforgeeks.org/shortest-path-reach-one-prime-changing-single-digit-time/ //Shrey Dubey //Contact Me at wshrey09@gmail.com #include<iostream> #include<string> #include<algorithm> #include<map> #include<unordered_map> #include<vector> #include<set> #include<list> #include<iomanip> #include<queue> #include<stack> #include <math.h> #define prDouble(x) cout<<fixed<<setprecision(10)<<x //to print decimal numbers #define pb push_back #define F first #define S second #define umap unordered_map #define fo(n) for(int i = 0; i<n; i++) #define fnd(stl, data) find(stl.begin(), stl.end(), data) using namespace std; typedef long long ll; int modulo = 1e9 + 7; vector<bool> generatePrimes(); class Graph{ umap<int,list<int> > adjlist; public: void addEdge(int x, int y){ adjlist[x].pb(y); adjlist[y].pb(x); } int bfs(int start, int dest){ umap<int,bool> visited; umap<int,int> dist; dist[start] = 0; queue<int> q; q.push(start); while(!q.empty()){ int p = q.front(); q.pop(); for(auto it: adjlist[p]){ if(!visited[it]){ q.push(it); visited[it] = true; dist[it] = dist[p]+1; } if(it == dest){ return dist[it]; } } } return -1; } }; vector<bool> generatePrimes(){ int n = 9999; vector<bool> prime(10000, true); for(int p = 2; p*p<=n; p++){ if(prime[p]){ for(int i = (p*p); i<=n; i+=p){ prime[i] = false; } } } return prime; } bool isEdge(int a, int b){ string s1 = to_string(a); string s2 = to_string(b); int c = 0; if(s1[0] != s2[0]){ c++; } if(s1[1] != s2[1]){ c++; } if(s1[2] != s2[2]){ c++; } if(s1[3] != s2[3]){ c++; } if(c == 1){ return true; } return false; } void solve(int s, int e){ vector<bool> prime = generatePrimes(); if(s == e){ cout<<0<<endl; return; } Graph g; for(int i = s; i<e; i++){ for(int j = i+1; j<=e; j++){ if(prime[i] && prime[j] && isEdge(i,j)){ g.addEdge(i,j); } } } cout<<g.bfs(s,e)<<endl; } int main(){ int s,e; cin>>s>>e; solve(s,e); }
true
6f23e03f378a13cacca5434f99df22b653b22305
C++
Lukaviy/problem-agitator
/engine.h
UTF-8
10,215
3.140625
3
[]
no_license
#pragma once #include <vector> #include <ostream> template <typename T> T constrain(T min, T max, T val) { return val > max ? max : val < min ? min : val; } template <typename T> int cmp_range(T min, T max, T val) { return val > max ? 1 : val < min ? -1 : 0; } namespace GameEngine { class GameEngineException {}; class BadMap : public GameEngineException {}; class BadScreamAreaSize : public GameEngineException {}; class BadArg : public GameEngineException {}; class PlayerAlreadyMakedMove : public GameEngineException {}; class InternalError : public GameEngineException {}; enum MOVE { NONE, LEFT, RIGHT, UP, DOWN, STOP }; struct Point_t { int x, y; Point_t(int x, int y) : x(x), y(y) {} Point_t() : x(0), y(0) {} Point_t operator+(const Point_t& b) const { return Point_t(x + b.x, y + b.y); } Point_t operator-(const Point_t& b) const { return Point_t(x - b.x, y - b.y); } }; struct Player_t { int score; Point_t pos; int id; int place; MOVE last_move; bool alive; Player_t() : score(0), id(0), place(0), last_move(NONE), alive(true) { } Player_t(int x, int y, int id) : score(0), pos(x, y), id(id), place(id), last_move(NONE), alive(true) { } Player_t(Point_t p, int id) : score(0), pos(p), id(id), place(id), last_move(NONE), alive(true) { } char letter() const { return 'A' + id; } }; struct Players_t { private: std::vector<Player_t> _players; std::vector<int> _player_places; int _players_count; int _players_alive; public: Players_t(int players_count) : _players_count(players_count), _players_alive(players_count) { _players.resize(players_count); _player_places.resize(players_count); for (int i = 0; i < players_count; i++) { _player_places[i] = i; } } Players_t() : _players_count(0), _players_alive(_players_count) {} Player_t& by_place(int place) { if (place < 0 || place >= _players_count) { throw InternalError(); } return _players[_player_places[place]]; } Player_t& by_id(int id) { if (id < 0 || id >= _players_count) { throw InternalError(); } return _players[id]; } void inc_score(int id) { if (id < 0 || id >= _players_count) { throw InternalError(); } int new_id = id; int new_score = ++_players[id].score; while (--new_id >= 0 && _players[new_id].score < new_score); std::swap(_player_places[id], _player_places[new_id + 1]); std::swap(_players[id].place, _players[new_id + 1].place); } void kill_player(int id) { if (id < 0 || id >= _players_count) { throw InternalError(); } if (_players[id].alive) { _players[id].alive = false; _players_alive--; } } int player_count() const { return _players_count; } int players_alive() const { return _players_alive; } void clear_moves() { for (int i = 0; i < _players_count; i++) { _players[i].last_move = NONE; } } }; class Map_t { private: char* _data; int _x_size, _y_size; public: Map_t(int x_size, int y_size, char* ptr = nullptr) { _x_size = x_size; _y_size = y_size; _data = new char[_x_size * _y_size + 1]; if (ptr) { memcpy(_data, ptr, _x_size * _y_size); } _data[_x_size * _y_size] = 0; } Map_t(Map_t& e) { _x_size = e._x_size; _y_size = e._y_size; _data = new char[_x_size * _y_size + 1]; memcpy(_data, e._data, _x_size * _y_size); _data[_x_size * _y_size] = 0; } ~Map_t() { delete[] _data; } char& at(int x, int y) const { if (x < 0 || x >= _x_size || y < 0 || y > _y_size) { throw InternalError(); } return *(_data + _x_size * y + x); } char& at(Point_t p) const { return at(p.x, p.y); } char& safe_at(int x, int y) const { return at(constrain(0, _x_size - 1, x), constrain(0, _y_size - 1, y)); } void clear(char val = char()) const { memset(_data, val, _x_size * _y_size); } int x_size() const { return _x_size; } int y_size() const { return _y_size; } bool is_valid_point(int x, int y) const { return x >= 0 && x < _x_size && y >= 0 && y < _y_size; } bool is_valid_point(Point_t p) const { return is_valid_point(p.x, p.y); } const char* data() const { return _data; } friend std::ostream& operator<<(std::ostream& os, const Map_t& map) { for (int y = 0; y < map._y_size; y++) { for (int x = 0; x < map._x_size; x++) { os << map.at(x, y); } os << std::endl; } return os; } }; class GameEngine_t { private: Map_t _map; Map_t _scream_areas_mask; int _scream_area_size; int _people_count; int _current_people_count; int _current_step; int _max_steps; Players_t _players; public: GameEngine_t(Map_t map, int scream_area_size, int max_steps = INT_MAX) : _map(map), _scream_areas_mask(map.x_size(), map.y_size()), _people_count(0), _current_people_count(0), _current_step(0), _max_steps(max_steps) { if (scream_area_size < 1) { throw BadScreamAreaSize(); } _scream_area_size = scream_area_size; static const int max_player_count = 'Z' - 'A' + 1; struct PlayerInfo_t { Point_t pos; int player_id; bool finded; } players[max_player_count]; memset(players, 0, sizeof players); for (int y = 0; y < map.y_size(); y++) { for (int x = 0; x < map.x_size(); x++) { char cell = map.at(x, y); if (cell != '.' && (cell < '0' || cell > '9') && (cell < 'A' || cell > 'Z')) { throw BadMap(); } if (cell >= 'A' && cell <= 'Z') { int player_id = cell - 'A'; PlayerInfo_t& player = players[player_id]; if (player.finded) { throw BadMap(); } player = PlayerInfo_t{ Point_t(x, y), player_id, true }; } if (cell >= '0' && cell <= '9') { _people_count++; } } } _current_people_count = _people_count; bool ended = false; int player_count = 0; for (int i = 0; i < max_player_count; i++) { if (!players[i].finded) { ended = true; } else { if (ended) { throw BadMap(); } player_count++; } } if (player_count < 1 || player_count > max_player_count) { throw BadMap(); } _players = Players_t(player_count); for (int i = 0; i < player_count; i++) { _players.by_id(players[i].player_id) = Player_t(players[i].pos, players[i].player_id); } } int players_count() const { return _players.player_count(); } int players_alive() const { return _players.players_alive(); } int current_step() const { return _current_step; } void make_move(int player_id, MOVE move) { if (_players.by_id(player_id).last_move != NONE) { throw PlayerAlreadyMakedMove(); } _players.by_id(player_id).last_move = move; } bool step() { if (_current_step > _max_steps || _players.by_place(0).score > _people_count / 2|| _players.players_alive() == 0) { return false; } //if (_players.players_alive() == 1 && ) _scream_areas_mask.clear(); for (int player_id = 0; player_id < _players.player_count(); player_id++) { Player_t& player = _players.by_id(player_id); if (!player.alive) { continue; } for (int y = -_scream_area_size; y <= _scream_area_size; y++) { if (cmp_range(0, _scream_areas_mask.y_size() - 1, player.pos.y + y)) { continue; } for (int x = -(_scream_area_size - abs(y)); x <= _scream_area_size - abs(y); x++) { if (cmp_range(0, _scream_areas_mask.x_size() - 1, player.pos.x + x)) { continue; } char& t = _scream_areas_mask.at(player.pos + Point_t(x, y)); t = t == 0 ? player_id + 1 : -1; } } } for (int y = 0; y < _map.y_size(); y++) { for (int x = 0; x < _map.x_size(); x++) { int mask = _scream_areas_mask.at(x, y); char& cell = _map.at(x, y); if (cell >= '0' && cell <= '9') { if (mask > 0) { if (cell == '9') { cell = '.'; _players.inc_score(mask - 1); _current_people_count--; } else { cell++; } } else { cell = '0'; } } } } for (int player_id = 0; player_id < _players.player_count(); player_id++) { Player_t& player = _players.by_id(player_id); if (!player.alive) { continue; } Point_t d = player.last_move == LEFT ? Point_t(-1, 0) : player.last_move == UP ? Point_t(0, -1) : player.last_move == RIGHT ? Point_t(1, 0) : player.last_move == DOWN ? Point_t(0, 1) : Point_t(0, 0); Point_t next_pos = player.pos + d; if (_map.is_valid_point(next_pos) && _map.at(next_pos) == '.') { _map.at(player.pos) = '.'; player.pos = next_pos; _map.at(next_pos) = 'A' + player_id; } } for (int y = 0; y < _map.y_size(); y++) { for (int x = 0; x < _map.x_size(); x++) { char& cell = _map.at(x, y); int mask = _scream_areas_mask.at(x, y); if (cell < '0' || cell > '9' || mask <= 0) { continue; } Player_t& p = _players.by_id(mask - 1); if (x < p.pos.x && _map.at(x + 1, y) == '.') { _map.at(x + 1, y) = cell; cell = '.'; _scream_areas_mask.at(x + 1, y) = 0; } else if (x > p.pos.x && _map.at(x - 1, y) == '.') { _map.at(x - 1, y) = cell; cell = '.'; _scream_areas_mask.at(x - 1, y) = 0; } else if (y < p.pos.y && _map.at(x, y + 1) == '.') { _map.at(x, y + 1) = cell; cell = '.'; _scream_areas_mask.at(x, y + 1) = 0; } else if (y > p.pos.y && _map.at(x, y - 1) == '.') { _map.at(x, y - 1) = cell; cell = '.'; _scream_areas_mask.at(x, y - 1) = 0; } } } _players.clear_moves(); _current_step++; return true; } const Map_t& map() const { return _map; } Player_t& player_by_id(int player_id) { if (player_id < 0 || player_id >= _players.player_count()) { throw BadArg(); } return _players.by_id(player_id); } Player_t& player_by_place(int place) { if (place < 0 || place >= _players.player_count()) { throw BadArg(); } return _players.by_place(place); } void kill_player(int player_id) { _players.kill_player(player_id); } }; }
true
f636e7a48822e0c97d6d1254b1ef2f6ffc000965
C++
VictorAlvizo/Ventura
/Ventura/src/Camera.h
UTF-8
1,291
3.265625
3
[ "MIT" ]
permissive
#pragma once #include "Vendor/glm/glm.hpp" #include "Vendor/glm/gtc/matrix_transform.hpp" #include "Entity.h" class Camera { public: //Default constructer of the camera, should not use it if planning to use Camera(); //Provide the position, the window size, and an entity to follow (if there is one) Camera(glm::vec2 pos, glm::vec2 windowSize, Entity * entity = nullptr); ~Camera(); //Move the camera to the position void Move(glm::vec2 pos); //transPos is the vector of the direction to move, deltaTime keeps it moving in that direction gradually. void Translate(glm::vec2 transPos, float deltaTime); //Set an entity for the camera to follow void SetEntity(Entity * entity); //If there is an entity attached to this camera, stop following it void Disconnect(); //Retrive the view matrix the camera provides glm::mat4 UpdateView(); //Get the position of the camera inline glm::vec2 getPos() const { return m_Pos; } //Get the window size. Needed for when wanting to get the area covered by the camera inline glm::vec2 getWindowSize() const { return m_WindowSize; } //Returns true if their is currently an entity it's following inline bool isEntityConnected() const { return m_FollowEntity; } private: glm::vec2 m_Pos, m_WindowSize; Entity * m_FollowEntity; };
true
41fc0c12f9232ad24be3816bcf274943ef047ba2
C++
jameskr97/etterna
/src/archutils/Darwin/DarwinThreadHelpers.h
UTF-8
814
3.0625
3
[ "MIT", "GPL-1.0-or-later", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef DARWIN_THREAD_HELPERS_H #define DARWIN_THREAD_HELPERS_H /** * @brief Attempt to suspend the specified thread. * @param threadHandle the thread to suspend. * @return true if the thread is suspended, false otherwise. */ bool SuspendThread(uint64_t threadHandle); /** * @brief Attempt to resume the specified thread. * @param threadHandle the thread to resume. * @return true if the thread is resumed, false otherwise. */ bool ResumeThread(uint64_t threadHandle); /** * @brief Retrieve the current thread ID. * @return the current thread ID. */ uint64_t GetCurrentThreadId(); /** * @brief Set the precedence for the thread. * * Valid values for the thread are from 0.0f to 1.0f. * 0.5f is the default. * @param prec the precedence to set. */ std::string SetThreadPrecedence(float prec); #endif
true