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
9af081729fd0d7b1dc0a0070b2071bfcb0db7a49
C++
SadSock/acm-template
/poj/poj1018.cpp
UTF-8
1,412
2.53125
3
[]
no_license
#include <cstdio> #include <iostream> #include <cstring> #include <cstdlib> #include <map> #include <vector> #include <climits> #include <iomanip> int t,n; int c[150]; int price[150][150],band[150][150]; int idx[10000]; int main(int argc ,char* argv[]) { //freopen("in.txt","r",stdin); std::cin>>t; while(t--) { std::cin >> n; std::map<int ,int> m; m.clear(); for(int i = 0 ; i < n ; i++) { std::cin >> c[i]; for(int j = 0 ; j < c[i] ; j++) { std::cin >> band[i][j]; std::cin >> price[i][j]; if(m.count(band[i][j]) == 0 ) { int size = m.size(); m[band[i][j]] = size; idx[size] = band[i][j]; } else { ; } } } double ret = 0; int flag = 0; for(int k = 0 ; k < m.size(); k++) { int cband = idx[k]; int total = 0; flag = 0; for(int a = 0 ; a < n ; a++) { int min = INT_MAX; for(int b = 0 ; b < c[a]; b++) { if(band[a][b] >= cband ) if( price[a][b] < min ) min = price[a][b]; //if(min == INT_MAX) // flag = 1; } if(min == INT_MAX) flag = 1; if(flag == 1) break; total = total + min; } if(flag == 1) continue; if( (double)cband / total > ret) ret = (double)cband / total; } std::cout<< std::setiosflags(std::ios::fixed)<<std::setprecision(3)<<ret<<std::endl; } return 0; }
true
141b9350b82022155e17687731d0b00e846c328d
C++
VictorinaVicka/CPP_Module
/CPP_Module06/ex00/main.cpp
UTF-8
1,590
2.84375
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tfarenga <tfarenga@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/08 16:03:47 by tfarenga #+# #+# */ /* Updated: 2020/12/08 19:31:51 by tfarenga ### ########.fr */ /* */ /* ************************************************************************** */ #include "Cast.hpp" int main(int argc, char **argv) { if (argc != 2) { std::cout << "Wrong number of arguments" << std::endl; } else { Cast cast(argv[1]); std::string str(argv[1]); if (str.length() == 1 && isprint(str[0]) && !isdigit(str[0])) { std::cout << "int: " << static_cast<int>(str[0]) << std::endl; std::cout << "float: " << std::fixed << std::setprecision(1) << static_cast<float>(str[0]) << "f" << std::endl; std::cout << "double: " << std::fixed << std::setprecision(1) << static_cast<double>(str[0]) << std::endl; std::cout << "char: " << "'" << str[0] << "'" << std::endl; } else { cast.getInt(); cast.getFloat(); cast.getDouble(); cast.getChar(); } } }
true
9354b78393d909dfe8295e163013d4869a849175
C++
Mogball/jeffniu.com
/src/strutil.cpp
UTF-8
365
3.0625
3
[]
no_license
#include "strutil.hpp" #include <algorithm> #include <utility> using namespace std; bool ends_with(const string &val, const string &end) { if (end.size() > val.size()) { return false; } return equal(end.rbegin(), end.rend(), val.rbegin()); } void force_move(string &dst, string &src) { dst.~string(); ::new(&dst) string(move(src)); }
true
b9f5c6d18901479f0660fee760ef2b4f2c0d141d
C++
eduherminio/Academic_ArtificialIntelligence
/9_Sudoku_CSP/src/sudoku.cpp
UTF-8
2,275
3.171875
3
[ "MIT" ]
permissive
#include "../header/sudoku.h" #include <iostream> #include <stdexcept> #include <algorithm> namespace sudoku { void Sudoku::inicializa_dominio() { dominio = std::vector<std::vector<unsigned>>(num_variables, std::vector<unsigned>(dim, 0)); for (unsigned i = 0; i != num_variables; ++i) { for (unsigned j = 0; j != dim; ++j) { dominio[i].at(j) = j + 1; } } for (unsigned i = 0; i != dim; ++i) { columna.push_back(std::set<unsigned>()); fila.push_back(std::set<unsigned>()); cuadrado.push_back(std::set<unsigned>()); } // LOOK UP TABLES para calculo rápido de la fila, columna y cuadrado // correspondiente a una variable calcula_get_fila(); calcula_get_columna(); calcula_get_cuadrado(); try { std::ifstream fichero(nombre_fichero); if (fichero) { fichero >> dim; //Dimension del Sudoku unsigned contador = 0; unsigned valor; for (unsigned i = 0; i != num_variables; ++i) { fichero >> valor; if (valor != 0) { dominio[contador].clear(); dominio[contador].push_back(valor); } ++contador; } } else { throw std::invalid_argument("Sudoku file doesn't exist.\nAn emptu Sudoku will be resolver.\n"); } } catch (const std::invalid_argument &mensaje) { std::cout << mensaje.what() << std::endl; } } void Sudoku::actualiza_estado(const std::pair<unsigned, unsigned> &asignacion) { auto variable = asignacion.first; auto valor = asignacion.second; fila[get_fila[variable]].insert(valor); columna[get_columna[variable]].insert(valor); cuadrado[get_cuadrado[variable]].insert(valor); } void Sudoku::restaura_estado(const std::pair<unsigned, unsigned> &asignacion) { auto variable = asignacion.first; auto valor = asignacion.second; fila[get_fila[variable]].erase(valor); columna[get_columna[variable]].erase(valor); cuadrado[get_cuadrado[variable]].erase(valor); } void imprime_solucion(std::vector<std::pair<unsigned, unsigned>>& solucion) { auto dim = sqrt(solucion.size()); std::sort(solucion.begin(), solucion.end()); unsigned contador = 0; for (auto v : solucion) { std::cout << v.second << " "; if (++contador == dim) { contador = 0; std::cout << std::endl; } } } }
true
998e34c300fd0cbc45af1b62125dda1a979c26d6
C++
Dblaze47/Problems-Solved---Category-Beginner
/UVA12403.cpp
UTF-8
377
2.890625
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; int main(){ int T, balance = 0, x; scanf("%d", &T); while(T--){ string str; cin>>str; if(str == "donate"){ cin>>x; balance += x; } else if (str == "report"){ cout<<balance<<endl; } } return 0; }
true
f6f1872dd9dcff2358b929d37ee0f587942a3d8b
C++
ganmacs/playground
/books/pc_data_structure/7/partition.cpp
UTF-8
1,270
3.28125
3
[]
no_license
#include <iostream> using namespace std; #define M 100000 int v[M]; int partition(int p, int r) { int x = v[r], i = p - 1, j = 0; for (j = p; j < r; j++) { if (v[j] <= x) { i++; swap(v[i], v[j]); } } swap(v[i + 1], v[r]); return i + 1; } void pp(int r) { for (int i = 0; i <= r; i++) { if (i != 0) cout << ' '; cout << v[i]; } cout << endl; } int solve(int l, int r) { int pi = r; swap(v[pi], v[l]); int x = v[l]; int ll = l + 1; int rr = r; int f = 0; while (ll < rr) { while(ll < rr && v[ll] <= x) ll++; while(ll < rr && v[rr] > x) rr--; swap(v[ll], v[rr]); } pp(r); if (v[ll] > x) f = 1; swap(v[ll - f], v[l]); return ll - f; } int partition2(int l, int r) { int pi = l - 1; int i = l; int t = v[r]; for (; i < r; i++) { if (v[i] <= t) { pi++; swap(v[pi], v[i]); } } swap(v[pi + 1], v[r]); return pi + 1; } int main(int argc, char *argv[]) { int n, i = 0; cin >> n; for (i = 0; i < n; i++) cin >> v[i]; int t = partition2(0, n-1); for (i = 0; i < n; i++) { if (i != 0) cout << ' '; if (t == i) { cout << '[' << v[i] << ']'; } else { cout << v[i]; } } cout << endl; return 0; }
true
0b4099e93341b0782c04e373ccda6bf4bc96372b
C++
tectronics/loki-engine
/Loki/include/core/viewsystem/IViewSystem.h
UTF-8
1,976
3.1875
3
[]
no_license
#pragma once #ifndef IVIEWSYSTEM_H #define IVIEWSYSTEM_H namespace loki { class IView; class IViewSystem { public: IViewSystem(); virtual ~IViewSystem() = 0; ////////////////////////////////////////////////////////////////////////// // Finds a view by name. Returns NULL if it doesn't exist. ////////////////////////////////////////////////////////////////////////// virtual IView* FindViewByName( const char* _ViewName ) const = 0; ////////////////////////////////////////////////////////////////////////// // Creates a new view. Returns NULL of _ViewName is already in use. ////////////////////////////////////////////////////////////////////////// virtual IView* CreateView( const char* _ViewName ) = 0; ////////////////////////////////////////////////////////////////////////// // Destroys the given view. If ////////////////////////////////////////////////////////////////////////// virtual void DestroyView( const char* _ViewName ) = 0; ////////////////////////////////////////////////////////////////////////// // Sets the currently active view from _View. ////////////////////////////////////////////////////////////////////////// virtual void SetActiveView( IView* _View ) = 0; ////////////////////////////////////////////////////////////////////////// // Sets the currently active view by name. If there is no view with // the passed name, returns false. Returns true otherwise. Note that // the active view is not modified if _ViewName can not be found. ////////////////////////////////////////////////////////////////////////// virtual bool SetActiveView( const char* _ViewName ) = 0; ////////////////////////////////////////////////////////////////////////// // Returns the currently active view. ////////////////////////////////////////////////////////////////////////// virtual IView* GetActiveView() const = 0; private: }; extern IViewSystem* g_ViewSystem; } #endif
true
2aea58c65885cd94b996332b72762c538be65ca6
C++
thinkmariale/Smoke-Simulation
/smoke_simulation/smoke_simulation/smokeParticle.h
UTF-8
1,132
2.8125
3
[]
no_license
#ifndef SMOKE_PARTICLE_H #define SMOKE_PARTICLE_H #include "glCanvas.h" class Ray; class Hit; class Material; class SmokeParticle { public: // CONSTRUCTORS SmokeParticle () { position = Vec3f(0,0,0); temperature = 0; density = 0; radius = .2; setMaterial(); } SmokeParticle (Vec3f pos, double temp, double dens) { position = pos; temperature = temp; density = dens; radius = .2; setMaterial(); } // accessor Material* getMaterial() const { return material; } Vec3f getPosition() const { return position; } double getTemperature() const { return temperature; } double getRadius() const { return radius; } Vec3f getCenter() const {return center;} double getDensity() const { return density; } // modifer void setPosition(Vec3f p) { position = p; center = p; } // for ray tracing bool intersect(const Ray &r, Hit &h); float DistanceEstimator(Vec3f p); private: // representation Vec3f position; double temperature; double density; double radius; Vec3f center; Material *material; void setMaterial(); }; // ==================================================================== #endif
true
e212414e7261cc354892bd2f5ecdea10d6b7ca57
C++
jovanSlavujevic96/CamH264CvMatStreaming_Cpp
/opencv_camera.cpp
UTF-8
636
2.578125
3
[]
no_license
#include <opencv2/opencv.hpp> #define LINK 0 #define WINDOW_NAME "OpenCV_CAM" int main() { cv::VideoCapture capture(LINK); if (!capture.isOpened()) { std::cerr << "Opening of capture with id = " << LINK << " has been failed\n."; std::cerr << "Exit app.\n"; return -1; } cv::Mat frame; char key; while (true) { capture >> frame; if (frame.empty()) { break; } cv::imshow(WINDOW_NAME, frame); key = cv::waitKey(1); if (key == 27 || key == 'q' || key == 'Q') { break; } } return 0; }
true
660244529ee17ed59b8746bc7266e1301e26b951
C++
cocokechun/Programming
/College/USACO/friday.cpp
UTF-8
1,321
2.828125
3
[]
no_license
/* ID: kmao1 PROG: friday LANG: C++ */ #include <iostream> #include <fstream> #include <string> using namespace std; #define MAX 7 int res[MAX]; bool is_leap(int y) { if (y % 4 == 0) { if (y % 100 == 0) { return y % 400 == 0; } else { return true; } } return false; } int main() { ofstream fout ("friday.out"); ifstream fin ("friday.in"); int n; fin >> n; int pre = 1; int days; for (int i = 0; i < n; i++) { for (int j = 1; j <= 12; j++) { if (j-1 == 0) { if (i == 0) days = 13-1; else days = 31 - 13 + 13; } else if (j-1 == 4 || j-1 == 6 || j-1 == 9 || j-1 == 11) { days = 30 - 13 + 13; } else if (j-1 == 2) { if (is_leap(i+1900)) { days = 29 - 13 + 13; } else { days = 28 - 13 + 13; } } else { days = 31 - 13 + 13; } pre = (pre + days) % 7; res[pre] += 1; } } for (int i = 0; i < 7; i++) { if (i != 6) { fout << res[(6+i)%7] << ' '; } else { fout << res[(6+i)%7] << endl; } } return 0; }
true
b5902d9271baeffa1a46cf1f31d0a5f9f9dc8e9f
C++
aznnobless85/ToyProject
/test/TestHashMap.cpp
UTF-8
2,325
3.359375
3
[]
no_license
// TestHashMap.cpp // // ICS 45C Winter 2014 // Project #3: Maps and Legends // // Write unit tests for your HashMap class here. I've provided one test already, // though I've commented it out, because it won't compile until you've implemented // three things: the HashMap constructor, the HashMap destructor, and HashMap's // size() member function. #include <gtest/gtest.h> #include "HashMap.hpp" namespace { unsigned int myHash(const std::string& key) { unsigned int sum = 0; for(unsigned int i = 0; i < key.length();i++) { char ch = key.at(i); sum += ch; } return sum; } } // Test default constructor TEST(TestHashMap, sizeOfNewlyCreatedHashMapIsZero) { HashMap empty; ASSERT_EQ(0, empty.size()); ASSERT_EQ(0, empty.loadFactor()); ASSERT_EQ(0, empty.maxBucketSize()); ASSERT_EQ(10, empty.bucketCount()); } //TestCase: test HashMap's constructor with a parameter. TEST(TestHashMap, hashMapConstructorWithOneParameter) { HashMap hashMap(myHash); ASSERT_EQ(0, hashMap.size()); ASSERT_EQ(0, hashMap.loadFactor()); ASSERT_EQ(0, hashMap.maxBucketSize()); ASSERT_EQ(10, hashMap.bucketCount()); } // Test copy constructor ?? TEST(TestHashMap, testCopyConstructor) { HashMap hm1; hm1.add("Hi","1234"); hm1.add("Google", "4321"); hm1.add("Naver","1234"); hm1.add("Go", "4321"); hm1.add("Boo","1234"); hm1.add("Foo", "4321"); const HashMap hm2 = hm1; EXPECT_EQ(hm1.size(), hm2.size()); EXPECT_EQ(hm1.bucketCount(), hm2.bucketCount()); } TEST(TestHashMap, testOperatorOverload) { HashMap hm1; hm1.add("Hi", "1234"); hm1.add("aa121", "1234"); hm1.add("bb441", "1234"); hm1.add("ccc11", "1234"); hm1.add("ddd121", "1234"); hm1.add("qqq441", "1234"); hm1.add("wew", "1234"); hm1.add("wewe1121", "1234"); hm1.add("Hi441", "1234"); HashMap hm2; hm2.add("Hias", "1234"); hm2.add("Hiqwq", "1234"); hm1 = hm2; EXPECT_EQ(hm1.size(), hm2.size()); EXPECT_EQ(hm1.bucketCount(), hm2.bucketCount()); } // TEST(TestHashMap, TestAddFunction) { // HashMap hm1; // hm1.add("HiThere123", "1234"); // hm1.add("123Foo", "1234"); // hm1.add("Booajfajfdksa;ffajlsdkfjasdlfjsakdfjda;skfjsadf", "abcd1234"); // ASSERT_EQ(3, hm1.size()); // }
true
f0a424a58a985fa30fa9de7b5a8d8732f5fbe6b5
C++
flopczak/win-based-dummy-os-cpp
/shell/Interfejs.h
UTF-8
8,281
2.6875
3
[]
no_license
#pragma once #ifndef Shell_H #define Shell_H #include <iostream> #include <vector> #include <string> #include <fstream> #include <ctime> #include <cstdio> #include <windows.h> #include <cstdlib> #include <time.h> using namespace std; class Interfejs { private: Memory *memory; Process_List *PL; User *user; Acl *acl; Disk *dysk; Procesor *procek; Sync *sync; public: struct met { string skrot; string opis; }; vector<met> metody; vector<string> kroki; Interfejs(Memory *memory , Process_List *PL, User *user, Acl *acl, Disk *dysk, Procesor *procek, Sync *sync) { this->procek = procek; this->memory = memory; this->PL = PL; this->user = user; this->acl = acl; this->dysk = dysk; this->procek = procek; this->sync = sync; } void DisplayLog(string msg) { kroki.push_back(msg); } /*void Wyswietl() { int ilosc=0; for (int i = 0; i < kroki.size(); i++) { cout << kroki[i] << endl; ilosc++; } kroki.erase(kroki.begin(), kroki.begin()+ilosc); cout << "Nacisnij dowolny klawisz aby kontynuowac..." << endl; cin.get(); }*/ void ChangeDisLog(vector<string> abc) { if (abc.size() > 2) { cout << "Za duzo parametrow, dostepne parametry to:\ntrue\nfalse" << endl; } string bulin = abc[0]; if (bulin == "true") { //dislog = true; //DisplayLog("zmienilem wartosc dislog"); } else if (bulin == "false") { //dislog = false; } else { cout << "Bledny parametr, dostepne parametry to:\ntrue\nfalse" << endl; } } void static DisplayLog(string msg); void DisplayMethods() { cout << "Metody dostepne dla uzytkownika:\n------------------------------- " << endl; int x = metody.size(); if (x == 0) { cout << "Brak metod dla uzytkownika" << endl; return; } for (int i = 0; i < x; i++) { cout << i + 1 << ". " << ToUp(metody[i].skrot) << " " << metody[i].opis << endl; } cout << endl; } void ZgrajZTxt() { ifstream plik; plik.open("metody.txt"); if (!plik.good()) { cout << "blad odczytu pliku" << endl; return; } int i = 0; string napis; int x; while (!plik.eof()) { getline(plik, napis); x = napis.size(); string delimiter = " "; string token = napis.substr(0, napis.find(delimiter)); met temp; temp.skrot = token; int a = token.size(); napis.erase(0, a + 1); temp.opis = napis; metody.push_back(temp); i++; } } void SetColor(vector<string> tab) { if (tab.size() > 2) { cout << "za duzo parametrow" << endl; return; } string color = tab[1]; HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); string kolor = tab[0]; int colour = stoi(color); if (colour >= 0 && colour < 16) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colour); } else { cout << "Nie ma takiego koloru.\n Dostepne kolory to green blue red white oraz liczby 0-15 " << endl; } } string Wczytaj() { string msg; getline(cin, msg); return msg; } void cls() { system("cls"); } void silnia(int x) { int wynik = 1; string str; for (int i = 1; i < x + 1; i++) { wynik *= i; str = to_string(wynik); DisplayLog(str); } } vector<string> Interpret(string msg) { if (msg == "") { cout << "Blad, pusta wiadomosc" << endl; vector<string> pusty; return pusty; } vector<string> tabmsg; //spacja ma kod ASCII 32 string temp = ""; int x = msg.size(); for (int i = 0; i < x; i++) { if (msg[i] != 32) { temp = temp + msg[i]; } if (msg[i] == 32) { tabmsg.push_back(temp); temp = ""; } } if (temp != "") { tabmsg.push_back(temp); } string polecenie = tabmsg[0]; x = tabmsg.size(); if (x > 1) { for (int i = 1; i < x; i++) { tabmsg.push_back(tabmsg[i]); } } return tabmsg; } void Time() { time_t czas; time(&czas); czas = czas % 86400; int h, m, s; h = czas / 3600; czas = czas - h * 3600; m = czas / 60; czas = czas - m * 60; s = czas; cout << h + 1 << ":" << m << ":" << s << endl; } string ToUp(string s) { setlocale(LC_CTYPE, "pl_PL.UTF-8"); for (int i = 0; i < s.size(); i++) { s[i] = toupper(s[i]); } return s; } string ToDown(string s) { for (int i = 0; i < s.size(); i++) { s[i] = tolower(s[i]); } return s; } void Wywolaj(vector<string> tab) { int x = tab.size(); if (x == 0) { cout << "Brak elementow do wywolania" << endl; return; } string polecenie = tab[0]; polecenie = ToUp(polecenie); vector<string> parametry; if (x > 1) { for (int i = 1; i < x; i++) { parametry.push_back(tab[i]); parametry[i - 1] = ToDown(parametry[i - 1]); } } if (polecenie == "HELP") { DisplayMethods(); return; } else if (polecenie == "GO") { return; } else if (polecenie == "COLOR") { SetColor(parametry); return; } else if (polecenie == "TK") { PL->findAndDisplayProcess(parametry); return; } else if (polecenie == "TKL") { PL->displayAll(); return; } else if (polecenie == "TKK") { PL->terminateProcess(parametry); } else if (polecenie == "SS") { PL->setStatus(parametry); return; } else if (polecenie == "EXIT") { cin.get(); exit(0); } else if (polecenie == "CLS") { cls(); return; } else if (polecenie == "CU") { user->createUser(); return; } else if (polecenie == "PCL") { user->printCurrentLoggedUser(); return; } else if (polecenie == "LOG") { user->logIn(); return; } else if (polecenie == "DU") { user->deleteUser(parametry); return; } else if (polecenie == "VUL") { user->viewUserList(); return; } else if (polecenie == "VSUG") { user->viewStandardUserGroup(); return; } else if (polecenie == "VAUG") { user->viewAdminUserGroup(); return; } else if (polecenie == "AUTS") { user->addUserToStandardUserGroup(parametry); return; } else if (polecenie == "AUTA") { user->addUserToAdminGroup(parametry); return; } else if (polecenie == "VAL") { acl->viewAclList(); return; } else if (polecenie == "VFA") { acl->viewFileAcl(parametry); return; } else if (polecenie == "SAP") { acl->setAdditionalPermissions(parametry); return; } else if (polecenie == "WZP") { memory->WypiszZasobPamieci(); return; } else if (polecenie == "WF") { memory->WydrukujFIFO(); return; } /*else if (polecenie == "DD" && parametry.size()==0) { dysk.dodajDane(); return; }*/ else if (polecenie == "PB") { //dysk->pobierzBlok(parametry); return; } else if (polecenie == "DD") { dysk->dodajDane(parametry); return; } else if (polecenie == "DP") { //dysk->dodajPlik(parametry); return; } else if (polecenie == "WB") { dysk->wypiszBlok(parametry); return; } else if (polecenie == "WD") { dysk->wypiszDysk(); return; } else if (polecenie == "WP") { dysk->wypiszPlik(parametry); return; } else if (polecenie == "DDP") { dysk->dopiszDoPliku(parametry); return; } else if (polecenie == "UP") { dysk->usunPlik(parametry); return; } else if (polecenie == "NP") { dysk->nadpiszPlik(parametry); return; } else if (polecenie == "WBI") { dysk->wypiszBlokIndeksowy(parametry); return; } else if (polecenie == "WK") { dysk->wypiszKatalog(); return; } else if (polecenie == "FRMT") { //dysk->formatuj(); return; } else if (polecenie == "WPP") { procek->ramka(); return; } else if (polecenie == "CP") { cout << "stworzylem proces" << endl; PL->createProcess(parametry); return; } else if (polecenie == "SP") { cout << "ustawilem priorytet" << endl; PL->setPriority(parametry); return; } else if (polecenie == "TIME") { Time(); return; } else if (polecenie == "CHD") { ChangeDisLog(parametry); return; } else { DisplayMethods(); return; } } }; #endif
true
b0f141e202f320453ab1ff097b734d6330d0dee2
C++
azma1984/aggregatesdk
/src/com/tibbo/aggregate/common/datatable/validator/RegexValidator.cpp
UTF-8
2,005
2.921875
3
[]
no_license
#include "datatable/validator/RegexValidator.h" #include "datatable/FieldFormat.h" #include <regex> #include <boost/functional/hash.hpp> #include "datatable/ValidationException.h" const std::string RegexValidator::SEPARATOR = "^^"; const std::string RegexValidator::SEPARATOR_REGEX = "\\^\\^"; RegexValidator::RegexValidator(const std::string& source) { std::size_t found = source.find(SEPARATOR_REGEX); if (found != std::string::npos) { this->regex = source.substr(0, found); this->message = source.substr( found, source.length() - found); }else { this->regex = source; } } RegexValidator::RegexValidator(const std::string& regex, const std::string& message) { this->regex = regex; this->message = message; } bool RegexValidator::shouldEncode() { return true; } std::string RegexValidator::encode() { return regex + (message.length() != 0 ? SEPARATOR + message : ""); } char RegexValidator::getType() { return FieldFormat::VALIDATOR_REGEX; } AgObjectPtr RegexValidator::validate(AgObjectPtr value) { if (!std::regex_match(value->toString(), std::regex(regex))) { throw ValidationException("dtValueDoesNotMatchPattern, RegexValidator::validate"); } return value; } int RegexValidator::hashCode() { static int prime = 31; int result = 1; boost::hash<std::string> string_hash; result = prime * result + ((message.length() == NULL) ? 0 : string_hash(message)); result = prime * result + ((regex.length() == NULL) ? 0 : string_hash(regex)); return result; } bool RegexValidator::equals(AgObject* obj) { if (this == obj) { return true; } if (!AbstractFieldValidator::equals(obj)) { return false; } RegexValidator *other = dynamic_cast<RegexValidator*>(obj); if (!other) return false; if (message != other->message) { return false; } if (regex != other->regex) { return false; } return true; }
true
755a2c32fc04a748a92d3612938071ecfa8fe6c5
C++
AvihaiDidi/avidudu2017
/src/server/CloseGameCommand.cpp
UTF-8
926
3.078125
3
[]
no_license
#include "headersS/CloseGameCommand.h" /* * Constructor - Makes a new command for closing a game. */ CloseGameCommand::CloseGameCommand(GameManager *info): info(info) ,target(0){ handler = new SocketHandler(); } /* * Destructor - delete the handeler. */ CloseGameCommand::~CloseGameCommand() { delete handler; } /* * Sets the target socket for the game to be closed. */ void CloseGameCommand::setArgs(vector<string> args, int socket) { target = socket; } /* * close game command * return true, always closes thread * will get a player in a game and close his an his opponent's sockets */ bool CloseGameCommand::execute() { const char* killMsg = "SHUTDOWN"; int *players = info->getGame(target); handler->passString(players[0], 8, killMsg); close(players[0]); handler->passString(players[1], 8, killMsg); close(players[1]); delete []players; info->closeGame(target); //stop getting input return false; }
true
d475bfd3cbe51d6e8cdcc5de20a7cb43edfdbdc0
C++
xavierm02/PROG1-projet-3
/src/Vector.hpp
UTF-8
844
3
3
[]
no_license
#include <iostream> #ifndef VECTOR_H #define VECTOR_H class Vector { protected: double x; double y; double z; public: Vector(); Vector(double x, double y, double z); double get_x() const; double get_y() const; double get_z() const; bool operator==(const Vector& other) const; Vector operator+(const Vector& other) const; Vector operator^(const Vector& other) const; double operator|(const Vector& other) const; double norm() const; friend Vector operator-(const Vector& vector); friend Vector operator-(const Vector& left, const Vector& right); friend Vector operator*(double scalar, const Vector& vector); friend Vector operator/(const Vector& vector, double scalar); }; std::ostream& operator<<(std::ostream &output_stream, const Vector& vector); #endif
true
3a603b7b04ed919a400d637acece6939c1e135cc
C++
nguyenluminhhang/Siv3D-Reference
/Programming Guide/Headers/Siv3D/AnimatedGIFWriter.hpp
UTF-8
2,704
2.65625
3
[ "MIT" ]
permissive
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <memory> # include "Fwd.hpp" namespace s3d { /// <summary> /// GIF アニメーション書き出し /// </summary> class AnimatedGIFWriter { private: class CAnimatedGIFWriter; std::shared_ptr<CAnimatedGIFWriter> pImpl; public: /// <summary> /// デフォルトコンストラクタ /// </summary> AnimatedGIFWriter(); AnimatedGIFWriter(const FilePath& path, int32 width, int32 height, bool dither = true, bool hasAlpha = true); AnimatedGIFWriter(const FilePath& path, const Size& size, bool dither = true, bool hasAlpha = true); /// <summary> /// アニメーション GIF の作成を終了し、保存します。 /// </summary> ~AnimatedGIFWriter(); bool open(const FilePath& path, int32 width, int32 height, bool dither = true, bool hasAlpha = true); bool open(const FilePath& path, const Size& size, bool dither = true, bool hasAlpha = true); /// <summary> /// アニメーション GIF の作成を終了し、保存します。 /// </summary> /// <remarks> /// 新しいアニメーション GIF を作成するには、再度 open() する必要があります。 /// </remarks> /// <returns> /// アニメーション GIF の保存に成功したら true, 失敗したら false /// </returns> bool close(); /// <summary> /// 書き出し用ファイルがオープンされているかを返します。 /// </summary> /// <returns> /// ファイルがオープンされている場合 true, それ以外の場合は false /// </returns> bool isOpened() const; /// <summary> /// 書き出し用ファイルがオープンされているかを返します。 /// </summary> /// <returns> /// ファイルがオープンされている場合 true, それ以外の場合は false /// </returns> explicit operator bool() const { return isOpened(); } /// <summary> /// フレームを書き出します。 /// </summary> /// <param name="image"> /// 書き出すフレームの画像 /// </param> /// <param name="delay"> /// アニメーションの間隔 [100 分の 1 ミリ秒] /// </param> /// <remarks> /// image は動画と同じサイズでなければいけません。 /// </remarks> /// <returns> /// フレームの書き出しに成功したら true, 失敗したら false /// </returns> bool writeFrame(const Image& image, int32 delay = 6); uint32 frameCount() const; Size imageSize() const; }; }
true
bebfe6f5d576c5c4df4b827a91db0df3b1837e17
C++
alepharchives/dxr
/tests/json-test/HelloWorld/BitField.h
UTF-8
1,339
3.3125
3
[ "MIT" ]
permissive
#include <stdint.h> #include <string.h> #include <assert.h> #include <limits.h> /** Representation of a BitField, well really, just some annoying part of it */ class BitField { private: /** Definition of underlying type for the bitfield*/ typedef unsigned int _word; /** Number of bits per word */ static const size_t _bitsPerWord = CHAR_BIT * sizeof(_word); /** Number of words for size */ size_t _words() const{ return (_size + _bitsPerWord - 1) / _bitsPerWord; } /** Underlying word array */ _word* _bits; size_t _size; public: /** Create a new empty bitfield */ BitField(size_t size){ _size = size; _bits = new _word[_words()]; } /** Copy create a bitfield from another */ BitField(const BitField& bf){ _size = bf._size; _bits = new _word[_words()]; for(size_t i = 0; i < _words(); i++) _bits[i] = bf._bits[i]; } /** Destructor */ ~BitField(){ if(_bits){ delete[] _bits; _bits = NULL; } } BitField& operator= (const BitField& rhs){ for(size_t i = 0; i < _words(); i++) _bits[i] = rhs._bits[i]; return *this; } BitField& operator&= (const BitField& rhs){ for(size_t i = 0; i < _words(); i++) _bits[i] &= rhs._bits[i]; return *this; } }; inline BitField operator&(const BitField& lhs, const BitField& rhs){ BitField retval(lhs); retval &= rhs; return retval; }
true
8518340ea7dd425f41614062dd714a18e4491b3e
C++
jonwa/Nukes-of-the-Patriots-v2
/Nukes of the patriots/TimerHandler.cpp
UTF-8
1,588
3.140625
3
[]
no_license
#include "TimerHandler.h" #include "Timer.h" TimerHandler::TimerHandler() : mVecTimers(){} TimerHandler::~TimerHandler(){ clear(); } void TimerHandler::addTimer(Timer* timer) { mVecTimers.push_back(timer); } void TimerHandler::clear() { mVecTimers.clear(); } void TimerHandler::removeTimer(Timer* timer) { for(std::vector<Timer*>::size_type it = 0; it < mVecTimers.size(); it++) { if(mVecTimers[it] == timer) { mVecTimers[it] = NULL; // Elements are not going to be deleted here break; } } } bool TimerHandler::isTimer(Timer* timer) { for(std::vector<Timer*>::size_type it = 0; it < mVecTimers.size(); it++) { if(mVecTimers[it] == timer) return true; } return false; } //void TimerHandler::tick() //{ // for(std::vector<Timer*>::size_type it = 0; it < mVecTimers.size(); it++) // { // if(mVecTimers[it] == NULL) // { // delete mVecTimers[it]; // mVecTimers.erase(mVecTimers.begin() + it); // } // else // { // if(!mVecTimers[it]->tick()) // { // if(mVecTimers[it] != NULL) // { // delete mVecTimers[it]; // mVecTimers.erase(mVecTimers.begin() + it); // } // } // } // } //} void TimerHandler::tick() { for(std::vector<Timer*>::size_type it = 0; it < mVecTimers.size();it++) { if(!mVecTimers[it]->isAlive()) { delete mVecTimers[it]; mVecTimers.erase(mVecTimers.begin() + it); } else { mVecTimers[it]->tick(); } } } TimerHandler* TimerHandler::mInstance = NULL; TimerHandler* TimerHandler::getInstance() { if(mInstance == NULL) mInstance = new TimerHandler(); return mInstance; }
true
b94a252da250e0594da61a27f16bbc01ee1c467b
C++
metaphysis/Code
/UVa Online Judge/volume102/10203 Snow Clearing/program.cpp
UTF-8
1,210
2.640625
3
[]
no_license
// Snow Clearing // UVa ID: 10203 // Verdict: Accepted // Submission Date: 2017-08-21 // UVa Run Time: 0.000s // // 版权所有(C)2017,邱秋。metaphysis # yeah dot net #include <bits/stdc++.h> using namespace std; int main(int argc, char *argv[]) { cin.tie(0), cout.tie(0), ios::sync_with_stdio(false); string line; getline(cin, line); int cases = stoi(line); getline(cin, line); for (int c = 0; c < cases; c++) { getline(cin, line); double x1, y1, x2, y2; double trail = 0.0; while (getline(cin, line), line.length() > 0) { istringstream iss(line); iss >> x1 >> y1 >> x2 >> y2; trail += sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)); } double time = trail * 3.0 / 500.0; stringstream ss; string total; ss << fixed << setprecision(0) << time; ss >> total; int minutes = stoi(total); int hours = minutes / 60; minutes %= 60; if (c > 0) cout << '\n'; cout << hours << ':'; if (minutes < 10) cout << '0'; cout << minutes << '\n'; } return 0; }
true
3806694d90eccaa00d8d0173cf617fbe18df5908
C++
leonheuler/ProjectEuler
/71/main.cpp
UTF-8
924
3.265625
3
[]
no_license
#include <iostream> #include <cmath> #include <ctime> using namespace std; int properFractions(int d) { double dist_min = 1.0; int res = 0; for (int den = 2; den <= d; den++) { for (int nom = den / 2; nom > 0; nom--) { if (double(nom)/den < 1/3.0) break; double dist = 3.0/7 - double(nom)/double(den); if (dist > 0) { if (dist > dist_min) break; else { res = nom; dist_min = dist; } } } } return res; } int main() { const int n = 1000000; unsigned int start_time = clock(); cout << properFractions(n) << endl; unsigned int end_time = clock(); cout << "Runtime: " << (end_time - start_time) / CLOCKS_PER_SEC << " sec" << endl; // 146 sec system("pause"); return 0; }
true
2b9c58d4c8e38ada8561503c8d4c62abb8afaee3
C++
SunNEET/LeetCode
/E22_E27/684. Redundant Connection.cpp
UTF-8
1,091
3.296875
3
[]
no_license
class Solution { // 複習一下disjoint set, 或叫union find // 都是以前ACM時用的寫法, 合併時是讓p[u]->p[v] // // 這題只要發現邊連接的兩端屬於同個set就是會變cycle了 public: vector<int> findRedundantConnection(vector<vector<int>>& edges) { vector<int> ans; for(int i=1;i<=edges.size();i++) parent[i]=i; for(auto e:edges) { int u=e[0], v=e[1]; if(!isSameSet(findSet(u), findSet(v))) { Union(parent[u],parent[v]); } else { ans = e; } } return ans; } private: int parent[2048]; int findSet(int u) { if(parent[u]==u) return u; else return parent[u]=findSet(parent[u]); } void Union(int a,int b){ int pa = findSet(a); int pb = findSet(b); if(pa!=pb){ parent[pa]=pb; } } bool isSameSet(int a,int b) { if(parent[a]==parent[b]) return true; else return false; } };
true
a3319316e4d4f275a37b34521df407db1f2c9a33
C++
ramonjunquera/GlobalEnvironment
/Android/04 appsIOT/03 RGB/Platformio/ledRGB/src/main.cpp
UTF-8
2,876
3.28125
3
[]
no_license
/* Tema: Servidor socket tcp con led RGB Autor: Ramón Junquera Fecha: 20210513 Se crea un servidor socket para la recepción de colores que se aplicarán a un led RGB. Un color estará definido por 3 bytes con la información de cada uno de los canales de color. El valor 255 se considera el comando para resetear la cuenta de canales de color. El cliente (Android) es el encargado de abrir y cerrar la comunicación. Mientras la comunicación se mantiene abierta se pueden recibir comandos. Se crea un punto de acceso WiFi. Por defecto la ip del servidor es 192.168.4.1 Los bytes se reciben de uno en uno. Llevamos la cuenta de cuántos bytes hemos recibido para el color actual. Cuando se completa un color, se muestran sus canales y se aplica. */ #include <Arduino.h> #include <ESP8266WiFi.h> //Definición de constantes globales const char* wifiSSID = "wifiServer"; const char* wifiPassword = "wifiServer"; const uint16_t port=12345; //Pinout RGB const byte pins[3]={D0,D1,D2}; WiFiServer server(port); //Creamos un servidor wifi void setup() { Serial.begin(115200); WiFi.mode(WIFI_AP); //Modo: punto de acceso WiFi.softAP(wifiSSID,wifiPassword); //Nombre y contraseña server.begin(); //Arrancamos el servidor Serial.print("\nServer running on "); Serial.print(WiFi.softAPIP()); Serial.print(":"); Serial.println(port); } void loop() { WiFiClient client=server.available(); //Anotamos si hay algún cliente if(client) { //Si hay alguno... Serial.println(String(millis())+" Cliente conectado"); byte channelIndex=0; //Indice del canal de color a recibir uint16_t color[3]; //Canales de color while(client.connected()) { //Mientras tengamos el cliente conectado... if(client.available()) { //Si tenemos información pendiente... byte b=client.read(); //Leemos el siguiente byte if(b==255) { //Si es un comando reset... channelIndex=0; //Reseteamos el índice de canales (nuevo color) Serial.print("R "); //Indicamos que hemos recibido un reset } else { //No es un comando reset //Guardamos el byte leido en el canal que corresponde //Aumentamos el índice de canal para el siguiente ciclo color[channelIndex++]=b; if(channelIndex==3) { //Si hemos completado el color... channelIndex=0; //Reseteamos el canal //Mostramos el color recibido Serial.printf("%i,%i,%i\n",color[0],color[1],color[2]); //Aplicamos los canales a cada led //Convertimos de 8bits a 10bits //Tomamos su negativo, porque el led RGB tiene ánodo común for(byte i=0;i<3;i++) analogWrite(pins[i],1023-(color[i])*4); } } } yield(); //Permitimos que se ejecuten las tareas de fondo } Serial.println("Cliente desconectado"); } }
true
1e1c2dfe3bd824795c217640e383954e41a0b136
C++
manjurrashed/coding-solution
/c_plus_plus/LeetCode/BinaryTrees/559_LC_Maximum_depth_of_n-ary_tree.cpp
UTF-8
763
3.34375
3
[]
no_license
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: void helper(Node* root, int depth, int &max_depth) { depth++; if (root->children.size() == 0) { max_depth = (depth > max_depth) ? depth : max_depth; return; } for (auto child : root->children) { helper(child, depth, max_depth); } } int maxDepth(Node* root) { if (!root) return 0; int max_depth = 0; helper(root, 0, max_depth); return max_depth; } };
true
b13f53bec0c8e71cefac28fc65aa250aaf502efc
C++
amit96321/projecteuler
/P14LongestCollatzSequence.cpp
UTF-8
966
3.359375
3
[]
no_license
/*Problem: Which starting number, under one million, produces the longest chain in Collatx series? Author: Amit Kumar(kumaramit96321@gmail.com) If n is even, then n → n/2 ⇒ Collatz(n) = Collatz(n/2) + 1. Therefore Collatz(2k) > Collatz(k) for all k, and we do not need to compute the chain for any k ≤ LIMIT /2. In this case, we do not need to compute the chain for any k below 500000. If n is odd, then 3n + 1 is even, and n → 3n + 1 → (3n+1)/2 So, We can save a step by giving Collatz(n) = Collatz( (3n+1)2) + 2. */ #include<bits/stdc++.h> using namespace std; //1000000 map<long long,long long> m; long long collatz(long long n){ if(m[n]) return m[n]; if(n==1) return 1; if(n%2==0) m[n]=collatz(n/2)+1; else m[n]=collatz((3*n+1)/2)+2; return m[n]; } int main(){ long long i,val=INT_MIN,result; for(i=500000;i<1000000;i++){ if(collatz(i)>val){ val=collatz(i); result=i; } } cout<<result<<"\n"; }
true
55cef13c75dcac82ac761b9eec90f936530d3231
C++
NaMoAr/CS170_Project1_Puzzle
/CS170_Puzzle/Node.h
UTF-8
830
3.484375
3
[]
no_license
#pragma once #include <iostream> #include <vector> using namespace std; /* This class allows the creation of the Node object which will continously update each time the state is being executed */ struct Node { vector<vector<int>> problem; //at most a blank tile can move in four directions, so with a given node, there would be 4 chidren at most Node* parent = nullptr; Node* child_1 = nullptr; Node* child_2 = nullptr; Node* child_3 = nullptr; Node* child_4 = nullptr; int uniform_cost; double heuristic_cost; double total_cost; string steps; //constructors Node(vector<vector<int>> p); Node(vector<vector<int>> p, int uniformCost); void print(); }; // to compare the total cost of two nodes struct compare { bool operator()(const Node& l, const Node& r) { return l.total_cost > r.total_cost; } };
true
adde3630387f7d04b267fe54bb3ce12822247d4d
C++
superdyzio/PWR-Stuff
/AIR-ARR/SCR - Systemy Operacyjne/szeregowanie/lab9.cpp
WINDOWS-1250
5,314
3.046875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <string> #include <queue> #include <fstream> #include <cstdlib> #include <cstdio> using namespace std; //co to jest ile na procku - ile ju si wkonywa // procesor jest tablic 10 elementow zada // czy czas to kwant czasu class Zadanie { public: int przybycie, trwanie, id, priorytet, pozostalo; bool wykonuje_sie, zakonczone; int ile_na_procku; Zadanie(int t, int i, int p, int r) { this->przybycie = t; this->id = i; this->priorytet = p; this->trwanie = r; this->pozostalo = r; this->wykonuje_sie = false; this->zakonczone = false; this->ile_na_procku = 0; } }; vector<Zadanie*> zadania; //wektor zada Zadanie* procesor[10]; //procesor jest tablic zada z iloci komrek rwn iloci rdzeni int czas_wywlaszczenia = 2; //kwant czasu dla procesu int ilosc_rdzeni = 1; //ilo rdzeni int czas = 1; //czas wykonywania programu int algorytm = 6; //algorytm wykorzystywany przez planer /* 0fcfs bez OK 1sjf bez OK 2SRTF z OK 3 Round Robin z - jest problem z wywaszczeniem bo nie przerzuca pomidzy procesami tylko leci jak lecia 4 prirytetowe FCFS wywaszaczenie 5.priorytetowe SRTF wywaszaczenie 6. proprytetowe bez wywaszecznia SRTF OK czyta z pliku procesy zapisuje do wektora procesor[ilo rdzeni] */ void WczytajZadaniaIncjalizujProcesor() { ifstream in; in.open("zadaniaWitold.txt"); if(!in.is_open()) {cout << "Bledna nazwa pliku z zadaniami\n"; exit(-1);} int t, i, pi, ri; while(1) { in >> t; while(!(in.peek() == '\r' || in.peek() == '\n' || in.peek() == EOF)) { in >> i; in >> pi; in >> ri; Zadanie* z = new Zadanie(t,i,pi,ri); zadania.push_back(z); } if(in.peek() == EOF) break; } in.close(); for(int i = 0; i < ilosc_rdzeni; i++) procesor[i] = NULL; } /* tmp zadania 0 1 tego wyszy bool CzyWyzszyPriorytet(const tmp, const Zadania) jeeli ok to zamienia { if(rozne priorytet) return zadanie.priorytet > tmp.priorytet; else return zadanie.przybycie < tmp.przybycie; } */ //znajdz pierwszy znajduje pierwszy niewykonujacy sie proces //i dodaje go Zadanie* ZnajdzPierwszy(bool (*fun) (const Zadanie& p1, const Zadanie& p2)) { Zadanie* tmp = NULL; for(int i = 0; i < zadania.size(); i++) { if(!zadania[i]->zakonczone && zadania[i]->przybycie <= czas && !zadania[i]->wykonuje_sie) { if(tmp == NULL) tmp = zadania[i]; else { if(fun(*tmp,*zadania[i])) tmp = zadania[i]; } } } return tmp; } void UstawProcesy(bool (*fun) (const Zadanie& p1, const Zadanie& p2)) { for(int i = 0; i < ilosc_rdzeni; i++) { if(procesor[i] == NULL) { Zadanie* z = ZnajdzPierwszy(fun); if(z != NULL) { procesor[i] = z; z->wykonuje_sie = true; z->ile_na_procku = 0; } } } } void Wywlaszcz() { for(int i = 0; i < ilosc_rdzeni; i++) { if(procesor[i] != NULL) { if(procesor[i]->ile_na_procku >= czas_wywlaszczenia) { Zadanie* z = procesor[i]; procesor[i] = NULL; z->wykonuje_sie = false; cout<<"\nWywlaszcz\n"; } } } } //////////////////////////////////////////////////////////////// // NAPISAC RR //////////////////////////////////////////////////////////////// bool CzyWykonalPrzydzial(const Zadanie& p1, const Zadanie& p2) { return p2.trwanie < p1.trwanie; } bool CzyKrotszy(const Zadanie& p1, const Zadanie& p2) { return p2.trwanie < p1.trwanie; } bool CzyMniejZostalo(const Zadanie& p1, const Zadanie& p2) { return p2.pozostalo < p1.pozostalo; } bool CzyWczesniejszy(const Zadanie& p1, const Zadanie& p2) { return p2.przybycie < p1.przybycie; } bool CzyWyzszyPriorytet(const Zadanie& p1, const Zadanie& p2) //realizuje od razu FCFS { if(p1.priorytet != p2.priorytet) return p2.priorytet < p1.priorytet;// byo > wic na odwrt else return p2.przybycie < p1.przybycie; } int main() { bool koniec=false; WczytajZadaniaIncjalizujProcesor(); while(1) { switch(algorytm) { case 0: //fcfs OK UstawProcesy(CzyWczesniejszy); break; case 1://sjf OK UstawProcesy(CzyKrotszy); break; case 2://srtf z OK Wywlaszcz(); UstawProcesy(CzyMniejZostalo); break; case 3:// RR z NIE MA Wywlaszcz(); UstawProcesy(CzyWykonalPrzydzial); break; case 4: //priorytet te same fcfs z Wywlaszcz(); UstawProcesy(CzyWczesniejszy); break; case 5://priorytet te same srtf z Wywlaszcz(); UstawProcesy(CzyMniejZostalo); break; case 6://priorytet te same FCFS BEZ OK Wywlaszcz(); UstawProcesy(CzyWyzszyPriorytet); break; } cout << czas << ": "; for(int i = 0; i < ilosc_rdzeni; i++) { if(procesor[i] != NULL) //jeeli co robi - Update { cout << procesor[i]->id << " "; procesor[i]->pozostalo--; procesor[i]->ile_na_procku++; if(procesor[i]->pozostalo == 0) { procesor[i]->zakonczone = true; procesor[i]->wykonuje_sie = false; procesor[i] = NULL; } } else // jeeli nie wywietla upeine { cout << "-1 "; } } cout << "\n"; czas++; koniec = true; for(int i = 0; i < zadania.size(); i++) if(!zadania[i]->zakonczone) koniec = false; if(koniec) break; } }
true
3a322e912e87d226c84dea3bfee0be5ae9bfaba2
C++
tectronics/infinite-bounty
/InfiniteBounty_Game/InfiniteBounty_Project/Source/BombPack.h
UTF-8
590
2.640625
3
[]
no_license
#ifndef BOMBPACK_H_ #define BOMBPACK_H_ #include "IPlayerWeapon.h" #include "Bomb.h" #include <vector> using namespace std; class CBombPack : public IPlayerWeapon { public: CBombPack(void); virtual ~CBombPack(void); virtual void Init( WeaponTypes Type ); virtual void Release( void ); virtual void Update( float fDelta ); virtual bool Attack( int direction, int x, int y ); virtual void Render( void ); virtual void CleanUp( void ); private: vector<CBomb*> Bombs; float BombTimeLength; void CreateNewBomb( int x, int y ); }; #endif
true
8e9192b323cb8d88da395cedd7a88ab625c120f8
C++
LanghuaYang/origin
/singleton/main.cpp
UTF-8
186
2.515625
3
[]
no_license
#include "Singleton.h" int main() { //get_instance() is a static function, so we could use it //without creating a instance. SINGLETON::get_insatance()->dosomething(); return 0; }
true
34e34dffcb02e4bfcc4a5fb4344b69780ffa5e41
C++
p10dibb/linuxDungon_Crawl
/DC/Items/Armor/Armor.h
UTF-8
1,278
2.78125
3
[]
no_license
#pragma once #include "../Item/Item.h" class Armor :public Item { friend class Item; private: //Armor's Level int Level; //the total resistance percentage int TotalResistance; //the armor type of this piece ArmorType_enum Type; //class (light, normal, or heavy) ArmorClass_enum Class; //items rarity ItemRarity_enum Rarity; //all of the resistances map<Effects_enum,ActiveEffects> ResistanceTypes; public: Armor(); Armor(int def, int lvl, ArmorType_enum type, ArmorClass_enum c); int getLevel(); void setLevel(int l); ItemRarity_enum getRarity(); void setRarity(ItemRarity_enum rarity); ArmorType_enum getType(); void setType(ArmorType_enum t); ArmorClass_enum getClass(); void setClass(ArmorClass_enum c); vector<ActiveEffects> getResistanceTypes(); void setResistanceTypes(map<Effects_enum,ActiveEffects> types); bool addResistanceType(ActiveEffects resistance); //return the string equivilent of rarity string getRarity_text(); //returns the string equivilent of Type (Armor Type) string getType_text(); //returns the string equivilent of Class (Armor Class) string getClass_text(); //Displays all relevent Armor details void DisplayDetails(); int getTotalResistance(); };
true
3a5ac10786871ed6cfa7fe3be2536a8fb5c8cc18
C++
tuduweb/LeetCode
/programming/3.无重复字符的最长子串.cpp
UTF-8
6,882
3.390625
3
[]
no_license
/* * @lc app=leetcode.cn id=3 lang=cpp * * [3] 无重复字符的最长子串 */ class Solution { public: int lengthOfLongestSubstring(string s) { //map<char,int> charMap; #if 0 int len = 0; for(string::iterator it = s.begin();it != s.end();++it) { string::iterator itb = it; for(string::iterator it2 = it;it2 != s.end();++it2) { if( (*it2 == *itb) && it2 - itb > len ) { len = it2 - itb; itb = it2; } } } return len; #endif #if 0 map<char,int> charMap; int len = 0,subLen = 0,right = 0; //对于取出来的数有两种情况.. //Case 1 : 没有出现过 -> 更新Map len++ //Case 2 : 出现过 -> 得到出现的位置 .. 当前位置 减去 上次出现的位置.. 得到一个长度subLen. 跟 len比较 for(string::iterator it = s.begin();it != s.end();++it) { map<char,int>::iterator itr = charMap.find(*it); //如果找到了相同的 那么跟当前的最大值比一下.. //如果没找到 就加到map里面 if ((itr == charMap.end()) )//&& (itr->second != i) { //没有出现过 则插入到Map中.并且长度++ charMap.insert({*it,it - s.begin() });//value,当前位置 ++subLen; }else{ //找到了相同的.那么计算subLen 并更新出现位置... if(subLen > len) len = subLen;//更新一下len 到 subLen if(right > itr->second) { subLen = (it - s.begin()) - right;//当前位置 - 上次位置.sub长度.. }else{ subLen = (it - s.begin()) - itr->second;//当前位置 - 上次位置.sub长度.. } right = itr->second;//右界 itr->second = it - s.begin(); //啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊 } } #endif #if 0//垃圾方法 毁我青春 //2019-5-1 16:37:55 把上面的Map改成数组的方式..看看效率上的区别. //卒卒卒 不能用数组 int charMap[127] = {-1};//最长就是26个字母了 int currentLen = 0,leftLimit = 0,maxLen = 0; for(string::iterator it = s.begin(); it != s.end(); ++it) { if(charMap[*it] == -1) { ++currentLen; charMap[*it] = it - s.begin(); }else{ if(charMap[*it] >= leftLimit) { leftLimit = charMap[*it]; currentLen = it - s.begin() - leftLimit; } else { ++currentLen; } charMap[*it] = it - s.begin(); } if(currentLen > maxLen) maxLen = currentLen; } #endif #if 0 /*这是小王第一次使用Map和Iterator做题..记录一下 √ Accepted √ 987/987 cases passed (32 ms) √ Your runtime beats 79.45 % of cpp submissions √ Your memory usage beats 77.47 % of cpp submissions (10.9 MB) */ //记录出现过的字母的位置.. map<char,int> charMap; int currentLen = 0,maxLen = 0,leftLimit = 0; for(string::iterator it = s.begin(); it != s.end(); ++it) { //查找当前字符串位置的值是否出现过? map<char,int>::iterator itChar = charMap.find(*it); //搜索到了底部还没有出现过..那么就是全新的字符.. //对于这一串新的字符串的影响就是应该..增加当前字符串的计数大小. if( itChar == charMap.end() ) { // ++currentLen; //leftLimit = it - s.begin(); //把这个字符添加到Map中 表示已经出现过了.. charMap.insert({*it,it - s.begin()});//字符串迭代器 取字符串的值/填位置值. }else{ //当前的字符以前出现过.. //更新最后出现的位置..在边界的右边..那么肯定是要更新边界了.. //it-s.begin 是当前位置..当前位置. //itChar->second 是上次的位置..如果上次的位置在边界右边.那么 if(itChar->second >= leftLimit)//itChar..才是找到的位置.用找到的位置跟边界进行对比才对 { leftLimit = itChar->second; //最新位置在更右边.那么肯定是要更新limit的 currentLen = it - s.begin() - leftLimit; } else { //最新的位置在界限的左边.代表可以忽略掉. ++currentLen; } //到了这里就算截止了..后面再长似乎也不会超过这里! //现在有一个currentLen..需要随着这里做变化.. //currentLen 更新到maxLen 暂时放在每个循环都处理吧.. itChar->second = it - s.begin(); } //更新最长 if(currentLen > maxLen) maxLen = currentLen; } #endif #if 0 /* //把字符串迭代器改成了数组取值方式.效率提高了一些 √ Accepted √ 987/987 cases passed (28 ms) √ Your runtime beats 83.1 % of cpp submissions √ Your memory usage beats 80.32 % of cpp submissions (10.7 MB) */ map<char,int> charMap; int currentLen = 0,maxLen = 0,leftLimit = 0; for(int i = 0;i < s.length();++i) { map<char,int>::iterator itChar = charMap.find(s[i]); if( itChar == charMap.end() ) { ++currentLen; charMap.insert({s[i],i});//字符串迭代器 取字符串的值/填位置值. }else{ if(itChar->second >= leftLimit) { leftLimit = itChar->second; currentLen = i - leftLimit; }else{ ++currentLen; } itChar->second = i; } if(currentLen > maxLen) maxLen = currentLen; } #endif #if 999 /*leetCode-cn 高票 √ Accepted √ 987/987 cases passed (28 ms) √ Your runtime beats 83.1 % of cpp submissions √ Your memory usage beats 83.93 % of cpp submissions (10.4 MB) */ vector<int> dict(256, -1); int maxLen = 0, start = -1; for (int i = 0; i != s.length(); i++) { if (dict[s[i]] > start) start = dict[s[i]]; dict[s[i]] = i; maxLen = max(maxLen, i - start); } #endif return maxLen; } };
true
7e0e3319bf415e7c8be9ae8cfdab86e80ceb828d
C++
Tcochr/CppBasicsReview
/ifstream.cpp
UTF-8
975
3.375
3
[]
no_license
// // Created by Cochr on 4/16/2020. // #include<iostream> #include <string> #include <fstream> using namespace std; int main(){ string filename = "..\\letters.txt"; ifstream input; input.open(filename); cout << input.is_open() << endl; string data, longWord; //start longestCount at -1 since count and countTotal start at zero int count = 0, countTotal = 0, longestCount = -1; //The extraction operator returns true as long as it retrieves data while (input >> data) { cout << data << endl; count++; int wordlength = data.length(); countTotal += wordlength; if (wordlength > longestCount) { longestCount = wordlength; longWord = data; } } cout << "avg: " << (double)(countTotal)/(count) << endl; cout << "longest: " << longWord << endl; cout << "count: " << count << endl; input.close(); return 0; }
true
5440104fe7f932ca47718221935acb1a0cecdd39
C++
ans-hub/gdm_framework
/framework/data/abstract_image.cc
UTF-8
1,790
2.84375
3
[ "MIT" ]
permissive
// ************************************************************* // File: abstract_image.cc // Author: Novoselov Anton @ 2018 // URL: https://github.com/ans-hub/gdm_framework // ************************************************************* #include <cassert> #include "abstract_image.h" // --public gdm::AbstractImage::AbstractImage(const AbstractImage::StorageType& raw, int width, int height, int depth) : width_{width} , height_{height} , depth_{depth} , data_{raw} { } gdm::AbstractImage::AbstractImage(int width, int height, int depth, float r, float g, float b, float a) : width_{width} , height_{height} , depth_{depth} , data_{} { assert(depth == 24 || depth == 32); r = r < 0.f ? 0.f : (r > 1.f ? 1.f : r); g = g < 0.f ? 0.f : (g > 1.f ? 1.f : g); b = b < 0.f ? 0.f : (b > 1.f ? 1.f : b); a = a < 0.f ? 0.f : (a > 1.f ? 1.f : a); unsigned char color[4]; color[0] = static_cast<unsigned char>(255 * r); color[1] = static_cast<unsigned char>(255 * g); color[2] = static_cast<unsigned char>(255 * b); color[3] = static_cast<unsigned char>(255 * a); int color_comps = depth_ / 8; int image_size = width_ * height_ * depth_ / 8; data_.resize(image_size); for (unsigned short i = 0; i < image_size; i += depth_ / 8) for (int k = 0; k < color_comps; ++k) data_[i+k] = color[k]; } unsigned gdm::AbstractImage::GetWidth() const { return static_cast<unsigned>(width_); } unsigned gdm::AbstractImage::GetHeight() const { return static_cast<unsigned>(height_); } unsigned gdm::AbstractImage::GetDepth() const { return static_cast<unsigned>(depth_); } auto gdm::AbstractImage::GetWHD() const -> Vec3u { return Vec3u(width_, height_, depth_); } auto gdm::AbstractImage::GetRaw() const -> const StorageType& { return data_; }
true
1e0c18dd48e6a8141fda220a2db9f5b41202b8e3
C++
WangsirCode/C-test-code
/sqlite3.cpp
UTF-8
3,086
3.125
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #include<iostream> #include <fstream> #include <sstream> #include <cstdlib> using namespace std; static std::function<void(void *data, int argc, char **argv, char **azColName)> func; static int callback(void *data, int argc, char **argv, char **azColName){ func(data, argc, argv, azColName); return 0; } class SqliteClass { public: sqlite3 *db; std::string SN; bool is_bounded; std::string phone; SqliteClass(){ }; ~SqliteClass(){ sqlite3_close(db); }; void InitDataBase() { func = [this](void *data, int argc, char **argv, char **azColName) { int i; fprintf(stderr, "%s: ", (const char*)data); for(i=0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } this->is_bounded = atoi(argv[1]); this->phone = argv[2]; cout<<this->phone<<endl; cout<<this->is_bounded<<endl; printf("\n"); }; SN = "MavicAir"; char *zErrMsg = 0; int rc; /* Open database */ rc = sqlite3_open("test.db", &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); exit(0); }else{ fprintf(stdout, "Opened database successfully\n"); } char table_sql[] = "CREATE TABLE BindingRecording(SN TEXT PRIMARY KEY NOT NULL, STATE INT NOT NULL, PHONE TEXT );"; sqlite3_exec(db, table_sql, nullptr, 0, nullptr); }; void UpdatePhone(bool is_bounded, std::string phone) { char insert_sql[100]; sprintf(insert_sql, "INSERT INTO BindingRecording (SN,STATE,PHONE) " \ "VALUES ('%s', %d, '%s' ); ",SN.c_str(), is_bounded, phone.c_str()); printf("%s", insert_sql); int res = sqlite3_exec(db, insert_sql, callback, 0, nullptr); if(res != SQLITE_OK) { printf("SN exist !"); char update_sql[100]; sprintf(update_sql, "UPDATE BindingRecording SET STATE = %d, PHONE = '%s' WHERE SN = '%s';", is_bounded, phone.c_str(), SN.c_str() ); int res = sqlite3_exec(db, update_sql, callback, 0, nullptr); } }; void GetBindingStateFromCache() { char *zErrMsg = 0; char select_sql[100]; sprintf(select_sql, "select * from BindingRecording where SN = '%s'",SN.c_str()); int res = sqlite3_exec(db, select_sql, callback, 0, nullptr); if( res != SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); }else{ fprintf(stdout, "Operation done successfully\n"); } } }; int main(int argc, char* argv[]) { SqliteClass sqlite = SqliteClass(); sqlite.InitDataBase(); sqlite.GetBindingStateFromCache(); sqlite.UpdatePhone(0, "138329956777"); sqlite.GetBindingStateFromCache(); // printf("begin"); return 0; }
true
7becdb0056decb4be4a6d54625ad023291ae1f14
C++
zerefwayne/data-structure-and-algorithms
/data_structures/graphs/algorithms/Topological.cpp
UTF-8
2,446
3.640625
4
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; class Graph { public: vector<vector<int>> adj; int V; Graph(int _V) { V = _V; adj.resize(V); } void addEdge(int src, int dest, bool isUnidirectional) { if (src >= 0 && src < V && dest >= 0 && dest < V && dest != src) { if (find(adj[src].begin(), adj[src].end(), dest) == adj[src].end()) { adj[src].emplace_back(dest); } if (isUnidirectional == false) { if (find(adj[dest].begin(), adj[dest].end(), src) == adj[dest].end()) { adj[dest].emplace_back(src); } } } } void printGraph() { for (int i = 0; i < V; i++) { cout << i << "->"; for (auto &vertex : adj[i]) { cout << vertex << "->"; } cout << '\n'; } cout << '\n'; } void topologicalSortUtil(int node, vector<bool> &visited, stack<int> &result) { visited[node] = true; for (auto &conn : adj[node]) { if (visited[conn] = false) { topologicalSortUtil(conn, visited, result); } } result.push(node); } void topologicalSort(int startNode) { vector<bool> visited(V, false); stack<int> result; if (startNode < 0 || startNode >= V) return; topologicalSortUtil(startNode, visited, result); for (int i = 0; i < V; i++) { if (visited[i] == false) { topologicalSortUtil(i, visited, result); } } cout << "Topological Sort:\n\n"; vector<int> result_array; while (!result.empty()) { result_array.emplace_back(result.top()); result.pop(); } reverse(result_array.begin(), result_array.end()); for (auto &node : result_array) { cout << node << '\n'; } cout << '\n'; } }; int main() { Graph newGraph = Graph(5); newGraph.addEdge(0, 2, true); newGraph.addEdge(1, 2, true); newGraph.addEdge(1, 3, true); newGraph.addEdge(2, 4, true); newGraph.printGraph(); newGraph.topologicalSort(0); return 0; }
true
d5ff72fbaa061f2c466ff9fa9480d29d6229254a
C++
Jungjaewon/ProblemSolving
/17140_2d_array_operation/17140_2d_array_operation/17140_2d_array_operation.cpp
UTF-8
4,003
2.953125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <map> #include <unordered_map> using namespace std; /* 1시간 넘게 걸렸음 R operation이면 col이 줄어들고 C operation이면 row가 줄어들고 하는 것을 놓침 그리고 연산전 새로운 결과를 업데이트하기 전에 이전것을 0으로 초기화하는 것을 깜빡함. cmp_fun 만들때 오류를 냄 // 멘붕옴 run-time error 발생시킬 수 있음. 틀렸을때 디버깅할 수 없는 문제이고 로직에서 에러를 찾아야함. R,C 연산 후 col, row가 줄어들 때, 원래 이전에 있던 것을 제거해야한다. 새로생긴 것과 아닌것의 갭때문에 문제를 일으킨다. */ typedef struct item { int digit; int count; item() :digit(0),count(0){} item(int i_digit, int i_count) :digit(i_digit),count(i_count){} } item_s; int R, C, K; int row = 3; int col = 3; int temp_row; int temp_col; int arr[101][101]; int ans; int temp; unordered_map<int, int> sort_map; unordered_map<int, int>::iterator iter; bool cmp_func(item_s a, item_s b) { if (a.count < b.count) return true; else if (a.count == b.count) { if (a.digit < b.digit) return true; else if (a.digit == b.digit) return true; else return false; } else return false; } void RC_operation(vector<int> input_arr, const int idx, bool mode) { // mode true R // mode false C vector<item_s> result_arr; for (int i = 0; i < input_arr.size(); ++i) { if (input_arr[i] == 0) continue; if (sort_map.count(input_arr[i]) == 0 ) { sort_map[input_arr[i]] = 1; } else { sort_map[input_arr[i]] += 1; } } for (iter = sort_map.begin(); iter != sort_map.end(); ++iter) { result_arr.push_back(item_s(iter->first,iter->second)); } stable_sort(result_arr.begin(), result_arr.end(), cmp_func); /* for (int i = 0; i < result_arr.size(); ++i) { printf("%d %d,",result_arr[i].digit, result_arr[i].count); } printf("\n"); */ if (mode) { // R mode temp_col = max(temp_col, int(result_arr.size() * 2)); int cnt = 1; for (int i = 1; i <= col; ++i) { arr[idx][i] = 0; } for (int i = 0; i < result_arr.size(); ++i) { arr[idx][cnt] = result_arr[i].digit; arr[idx][cnt + 1] = result_arr[i].count; cnt += 2; } } else { // C mode temp_row = max(temp_row, int(result_arr.size() * 2)); int cnt = 1; for (int i = 1; i <= row; ++i) { arr[i][idx] = 0; } for (int i = 0; i < result_arr.size(); ++i) { arr[cnt][idx] = result_arr[i].digit; arr[cnt + 1][idx] = result_arr[i].count; cnt += 2; } } sort_map.clear(); } void processing() { int sec = 0; if (arr[R][C] == K) { ans = sec; return; } while (true) { vector<int> input_arr; if (row >= col) { for (int i = 1; i <= row; ++i) { for (int j = 1; j <= col; ++j) { input_arr.push_back(arr[i][j]); } RC_operation(input_arr, i, true); input_arr.clear(); } col = temp_col; temp_col = 0; } else { for (int i = 1; i <= col; ++i) { for (int j = 1; j <= row; ++j) { input_arr.push_back(arr[j][i]); } RC_operation(input_arr, i, false); input_arr.clear(); } row = temp_row; temp_row = 0; } /* printf("row : %d, col %d\n",row,col); for (int i = 1; i <= row; ++i) { for (int j = 1; j <= col; ++j) { printf("%d ",arr[i][j]); } printf("\n"); } printf("\n"); */ ++sec; if (arr[R][C] == K) { ans = sec; return; } else if (sec >= 99) { ans = -1; return; } } } int main() { freopen("input.txt", "r", stdin); scanf("%d %d %d",&R, &C, &K); for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) { scanf("%d", &temp); arr[i][j] = temp; } } processing(); printf("%d",ans); return 0; }
true
5f7caa19ef0b4a27325c5c776ef098a755e7875c
C++
poseidn/KungFoo-legacy
/src/DescentEngine/src/Input/MultiplexedInput.h
UTF-8
1,252
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#pragma once #include <boost/noncopyable.hpp> #include "../Cpp11.h" #include "InputSystemBase.h" #include "InputContainer.h" #include "NullInput.h" // this class will allow two input system to operate on the // same InputContainer instead of one, // can be used to have dummy input from the application fed back // to the whole game stack template<class TInputA, class TInputB = NullInput, class TInputC = NullInput> class MultiplexedInput: public InputSystemBase { public: MultiplexedInput(TInputA * iA, TInputB * iB = nullptr, TInputC * iC = nullptr) : m_inputA(iA), m_inputB(iB), m_inputC(iC) { } virtual void updateContainer(float deltaT) CPP11_OVERRIDE { auto & cont(getContainers()); for (auto & c : cont) { c.second.resetKeypress(); } // hand to the sub inputs if (m_inputA) m_inputA->updateContainer(cont, deltaT); if (m_inputB) m_inputB->updateContainer(cont, deltaT); if (m_inputC) m_inputC->updateContainer(cont, deltaT); } DeviceList availableInputDevices() const { DeviceList dlOne = m_inputA->availableInputDevices(); return dlOne; } size_t maxInputDevices() const { return m_inputA->maxInputDevices(); } private: TInputA * m_inputA; TInputB * m_inputB; TInputC * m_inputC; };
true
fcdbab6e89c75ae733836546e7ae60d1cdf9c424
C++
RapdElzo/Flask
/source/util.cpp
UTF-8
3,394
2.53125
3
[ "MIT" ]
permissive
#include "shared.h" #include <jansson.h> std::vector<char *> split(char * string, char * delim) { std::vector<char *> array; char * token = strtok(string, delim); while (token != NULL) { array.push_back(token); token = strtok(NULL, delim); } return array; } void downloadFile(char * url, char * filename) { httpcContext httpContext; Result returnResult = 0; u8 * buffer; u32 statusCode; u32 size; returnResult = httpcOpenContext(&httpContext, HTTPC_METHOD_GET, url, 1); if (returnResult != 0) displayError("Failed to request url."); returnResult = httpcSetSSLOpt(&httpContext, SSLCOPT_DisableVerify); if (returnResult != 0) displayError("Failed to Disable SSL Verification."); returnResult = httpcBeginRequest(&httpContext); if (returnResult != 0) displayError("Failed to begin http:C request"); returnResult = httpcGetResponseStatusCode(&httpContext, &statusCode, 0); if (statusCode != 200) displayError("Invalid status code"); returnResult = httpcGetDownloadSizeState(&httpContext, NULL, &size); if (returnResult != 0) displayError("Failed to get download size of file."); /*if (size == fsize("sdmc:/flask/flask.json")) { httpcCloseContext(&httpContext); return; }*/ buffer = (u8 *)malloc(size); if (buffer == NULL) displayError("Could not malloc httpc buffer."); memset(buffer, 0, size); returnResult = httpcDownloadData(&httpContext, buffer, size, NULL); if (returnResult != 0) displayError("Failed to download file."); char * sdmcPath = "sdmc:/flask/"; char * fullpath = (char *)malloc(strlen(sdmcPath) + strlen(filename) + 1); strcpy(fullpath, sdmcPath); strcat(fullpath, filename); FILE * downloadedFile = fopen(fullpath, "w"); fwrite(buffer, size, 1, downloadedFile); fflush(downloadedFile); fclose(downloadedFile); httpcCloseContext(&httpContext); free(fullpath); } void cacheData() { downloadFile("https://3ds.intherack.com/flask/list", "flask.json"); json_t * flaskJson = json_load_file("sdmc:/flask/flask.json", JSON_DECODE_ANY, NULL); size_t arrayIndex; json_t * arrayValue; const char * objectKey; json_t * objectValue; json_array_foreach(flaskJson, arrayIndex, arrayValue) { json_t * jsonObject = json_array_get(flaskJson, arrayIndex); json_object_foreach(jsonObject, objectKey, objectValue) { Application temp(24, 24 + (arrayIndex * 64)); if (strcmp(objectKey, "name") == 0) { temp.setName(json_string_value(objectValue)); } else if (strcmp(objectKey, "author") == 0) { temp.setAuthor(json_string_value(objectValue)); } else if (strcmp(objectKey, "description") == 0) { temp.setDescription(json_string_value(objectValue)); } else if (strcmp(objectKey, "url") == 0) { temp.setDownloadURL(json_string_value(objectValue)); } //because we're not doing icons yet with cia stuff. . sf2d_texture * noneImage = sfil_load_PNG_file("graphics/none.png", SF2D_PLACE_RAM); Image * noneIcon = new Image(noneImage); temp.setIcon(noneIcon); applications->push_back(temp); } } } int fsize(const char * file) { struct stat st; stat(file, &st); return st.st_size; } void strstor(char * destination, const char * source) { if (destination) free(destination); destination = (char *)malloc(strlen(source) + 1); strcpy(destination, source); }
true
0bec01aec1c713c4a5b1ba78ebc9d60a9b8c242e
C++
ku-alps/cse17_keunbum
/Baekjoon/solved/10866/cpp/sol.cpp
UTF-8
1,242
2.859375
3
[]
no_license
#include <iostream> #include <deque> using namespace std; deque<int> a; int main() { ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; while (n--) { string cmd; cin >> cmd; char c = cmd[0]; switch (c) { case 'p': int v; if (cmd[1] == 'u') { cin >> v; if (cmd[5] == 'f') a.push_front(v); else a.push_back(v); } else { if (cmd[4] == 'f') { if (!a.empty()) { v = a.front(); a.pop_front(); } else v = -1; cout << v << '\n'; } else { if (!a.empty()) { v = a.back(); a.pop_back(); } else v = -1; cout << v << '\n'; } } break; case 's': cout << a.size() << '\n'; break; case 'e': cout << (a.empty() ? 1 : 0) << '\n'; break; case 'f': cout << (a.empty() ? -1 : a.front()) << '\n'; break; case 'b': cout << (a.empty() ? -1 : a.back()) << '\n'; break; default: break; } } //cerr << (float)clock()/CLOCKS_PER_SEC << " seconds." << '\n'; return 0; }
true
60fde854d235fe1a95fd1303ab9342fa058e6ce3
C++
JJJackZhen/leetcode-workspace
/14.longest-common-prefix.cpp
UTF-8
734
2.96875
3
[]
no_license
/* * @lc app=leetcode id=14 lang=cpp * * [14] Longest Common Prefix */ #include <vector> #include <string> using namespace std; class Solution { public: string longestCommonPrefix(vector<string>& strings) { if (strings.empty()) { return string(); } string tmp = strings[0]; for (int i = tmp.size(); i >= 0; --i) { string prefix = tmp.substr(0, i); bool flag = true; for (const auto &str: strings) { if (str.find(prefix) != 0) { flag = false; break; } } if (flag) { return prefix; } } return ""; } };
true
6944acb8755adaa49047879c21a5d5aaad3191dd
C++
ThiagoTassinari/Mini_Curso_Ceuma_Arduino
/Aula_04/N_025/N_025.ino
UTF-8
3,769
3.015625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
/* Projeto Nº 25 -> Simulação de servo motor + LEDs * * Author: Thiago Santos Tassinari * Data: 06/10/2020 * Descrição do Projeto: <!---------------------Simulação de transferidor com servo motor + LEDs-----------------------------> // Os LEDs acesos indicam o seguinte: // Verde, motor abriendo la valvula; // Vermelho, válvula de fechamento do motor; // Amarelo, motor em funcionamento. <----------------------------------------------------------------------------------> <!-----------------------Componentes necessários-------------------------------------> - 1 Arduino Uno; - 1 Protoboard; - 3 LEDs ; - 3 resistor de 470Ohms e 3 Resistor de 10KOhm; - 1 Servo motor CC; - 1 Acionador de motor de ponte H; - 1 Button; - 2 Interruptores deslizantes; - 1 Bateria de 9V; - Jumpers <-------------------------------------------------------------------------------------> */ // Variáveis: // Pressione o botão para alterar o status: int button = 0; // Pressione o botão para abrir ou fechar a válvula int interrupt_open = 0; // Chave limitadora de válvula aberta int interrupt_close = 0; // Chave de limite de válvula fechada int estado_valv = 0; // Status da válvula, 0 inicial, 1 aberta e 2 fechada // Integrado L293 que precisa de diodos de proteção ou o L293D que já os incorpora // L293D pin 2 -> D8 -> LED vermelho fechar // L293D pin 7 -> D9 -> LED verde abrir // L293D pin 1 -> D10 -> LED amarelo funcionando o motor void abrir(){ digitalWrite(8, LOW); // LED vermelho digitalWrite(9, HIGH); // LED verde digitalWrite(10, HIGH); // LED amarelo } void fechar(){ digitalWrite(8, HIGH); // LED vermelho digitalWrite(9, LOW); // LED verde digitalWrite(10, HIGH); // LED amarelo } void parar(){ digitalWrite(8, LOW); // LED vermelho digitalWrite(9, LOW); // Led verde digitalWrite(10, LOW); // Led amarelo } void setup() { Serial.begin(9600); for (int i = 8 ; i<11 ; i++) // Inicia-se os pinos de saída pinMode( i, OUTPUT); for (int j = 4 ; j<7 ; j++) // Inicia-se os pinos de entrada pinMode( j, INPUT); } void loop() { button = digitalRead(4); // Leitura digital do pin 4 interrupt_open = digitalRead(5); // Leitura digital do pin 5 interrupt_close = digitalRead(6); // Leitura digital do pin 6 Serial.print("Estado da válvula: "); Serial.println(estado_valv); // Estado inicial 0 if (estado_valv == 0){ if (interrupt_close == LOW && interrupt_open == HIGH){ Serial.println("Valvula abierta en estado inicial, no hace nada"); parar(); estado_valv = 1; } if (interrupt_close == LOW && interrupt_open == LOW){ Serial.println("Valvula a medio recorrido en estado inicial, debe abrirse"); abrir(); estado_valv = 1; } if (interrupt_open == LOW && interrupt_close == HIGH){ Serial.println("Valvula cerrada en estado inicial, debe abrirse"); abrir(); estado_valv = 1; } } // Recibe orden de cambiar el estado if (button == HIGH){ if (interrupt_open == HIGH && interrupt_close == LOW){ Serial.println("Valvula abierta y recibe orden de fechar"); fechar(); estado_valv = 2; } if (interrupt_open == LOW && interrupt_close == HIGH){ Serial.println("Valvula cerrada y recibe orden de abrir"); abrir(); estado_valv = 1; } } // Parar el motor cuando llegue al final de carrera if (estado_valv == 1 && interrupt_open == HIGH){ parar(); } // Parar el motor cuando llegue al final de carrera if (estado_valv == 2 && interrupt_close == HIGH){ parar(); } }
true
4e8cfa137ab1c19eb7038eb262813c9480978f05
C++
Catnip0709/CodeStudy
/剑指offer/构建乘积数组.cpp
UTF-8
1,452
3.265625
3
[]
no_license
/* Author: Catnip Date: 2020/02/17 From: 剑指offer Link: https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking */ /* Q 给定一个数组A[0,1,...,n-1] 请构建一个数组B[0,1,...,n-1] 其中B中的元素B[i]=A[0]*A[1]*...*A[i-1]*A[i+1]*...*A[n-1]。 不能使用除法。(注意:规定B[0]和B[n-1] = 1) */ /* A B[i]的值可以看作下图的矩阵中每行的乘积。 B0 = 1 A1 A2 ... A(n-2) A(n-1) B1 = A0 1 A2 ... A(n-2) A(n-1) B2 = A0 A1 1 ... A(n-2) A(n-1) ... = A0 A1 ... 1 A(n-2) A(n-1) B(n-2) = A0 A1 ... A(n-3) A(n-2) A(n-1) B(n-1) = A0 A1 ... A(n-3) A(n-2) 1 对于下三角(B[i]中的一部分):B[i] = B[i-1] * A[i-1]; 然后倒过来按上三角中的分布规律,把另一部分也乘进去。 */ #include<iostream> #include<vector> using namespace std; vector<int> multiply(const vector<int>& A) { int length = A.size(); vector<int> B; if (length != 0) { B.push_back(1); //从上向下,计算下三角连乘 for (int i = 1; i < length; i++) { B.push_back(B[i - 1] * A[i - 1]); } //从下向上,补充上三角连乘 int temp = 1; for (int j = length - 2; j >= 0; j--) { temp *= A[j + 1]; B[j] *= temp; } } return B; }
true
69a7a29d300019f0487c6c39a6d8b55fff08c93f
C++
mmtobi/dp
/Visitor.h
UTF-8
834
2.75
3
[]
no_license
#ifndef Visitor_h #define Visitor_h #include "Node.h" class Visitor { public: virtual void visit(const Leaf_Node& leaf_node) = 0; virtual void visit(const Add_Node& add_node) = 0; virtual void visit(const Subtract_Node& subtract_node) = 0; virtual void visit(const Multiply_Node& multiply_node) = 0; virtual void visit(const Divide_Node& divide_node) = 0; virtual void visit(const Negate_Node& negate_node) = 0; }; class Print_Visitor : public Visitor { public: virtual void visit(const Leaf_Node& leaf_node); virtual void visit(const Add_Node& add_node); virtual void visit(const Subtract_Node& subtract_node); virtual void visit(const Multiply_Node& multiply_node); virtual void visit(const Divide_Node& divide_node); virtual void visit(const Negate_Node& negate_node); }; #endif
true
47e3f86fe1b69e557aba39a638fc1340ca1abe8b
C++
Emadon13/RPGQuest
/Depressia/gui/frame/itemframe.cpp
UTF-8
6,812
2.609375
3
[]
no_license
#include "itemframe.h" #include "gui/clickable/clickablelabel.h" //////////////////////////////////////////////////////// /// /// /// ItemFrame /// /// /// //////////////////////////////////////////////////////// /*! \class ItemFrame Cette classe */ ItemFrame::ItemFrame(GameWindow *g) { game=g; map=game->GetMap(); int WindowWidth(game->GetGame()->getWindowWidth()); int WindowHeight(game->GetGame()->getWindowHeight()); double ratio(game->GetGame()->getRatio()); int BoutonWidth(int(96/ratio)); int BoutonHeight(int(96/ratio)); int BoutonMarge(int(100/ratio)); int ImageWidth(int(250/ratio)); int ImageHeight(int(250/ratio)); int InfoWidth(int(750/ratio)); int InfoHeight(int(200/ratio)); int TitleWidth(int(500/ratio)); int TitleHeight(int(100/ratio)); QLabel *back = new QLabel(game); back->setPixmap(QPixmap("../ressources/images/hud/background-game-3.png").scaled(WindowWidth,WindowHeight)); back->setFixedSize(WindowWidth,WindowHeight); back->move(0,0); back->show(); ClickableLabel *item = new ClickableLabel(game); item->setPixmap(QPixmap("../ressources/images/hud/coffre.png").scaled(ImageWidth,ImageWidth)); item->setFixedSize(ImageWidth,ImageHeight); item->installEventFilter(game); item->move((WindowWidth-ImageWidth)/2,(WindowHeight-ImageHeight)/2); item->setCursor(QCursor(QPixmap("../ressources/images/hud/cursor.png"), 0, 0)); item->show(); QObject::connect(item, SIGNAL(clicked()), game, SLOT(afficheItem())); if(map->existUp()) { ClickableLabel *boutonHaut = new ClickableLabel(game); boutonHaut->setPixmap(QPixmap("../ressources/images/hud/fleche-haut.png").scaled(BoutonWidth,BoutonHeight)); boutonHaut->setFixedSize(BoutonWidth,BoutonHeight); boutonHaut->installEventFilter(game); boutonHaut->move((WindowWidth-BoutonWidth)/2,BoutonMarge); boutonHaut->setCursor(QCursor(QPixmap("../ressources/images/hud/cursor.png"), 0, 0)); boutonHaut->show(); QObject::connect(boutonHaut, SIGNAL(clicked()), game, SLOT(GoUp())); } if(map->existDown()) { ClickableLabel *boutonBas = new ClickableLabel(game); boutonBas->setPixmap(QPixmap("../ressources/images/hud/fleche-bas.png").scaled(BoutonWidth,BoutonHeight)); boutonBas->setFixedSize(BoutonWidth,BoutonHeight); boutonBas->installEventFilter(game); boutonBas->move((WindowWidth-BoutonWidth)/2,(WindowHeight-BoutonHeight-BoutonMarge)); boutonBas->setCursor(QCursor(QPixmap("../ressources/images/hud/cursor.png"), 0, 0)); boutonBas->show(); QObject::connect(boutonBas, SIGNAL(clicked()), game, SLOT(GoDown())); } if(map->existRight()) { ClickableLabel *boutonDroite = new ClickableLabel(game); boutonDroite->setPixmap(QPixmap("../ressources/images/hud/fleche-droite.png").scaled(BoutonWidth,BoutonHeight)); boutonDroite->setFixedSize(BoutonWidth,BoutonHeight); boutonDroite->installEventFilter(game); boutonDroite->move((WindowWidth-BoutonWidth-BoutonMarge),(WindowHeight-BoutonHeight)/2); boutonDroite->setCursor(QCursor(QPixmap("../ressources/images/hud/cursor.png"), 0, 0)); boutonDroite->show(); QObject::connect(boutonDroite, SIGNAL(clicked()), game, SLOT(GoRight())); } if(map->existLeft()) { ClickableLabel *boutonGauche = new ClickableLabel(game); boutonGauche->setPixmap(QPixmap("../ressources/images/hud/fleche-gauche.png").scaled(BoutonWidth,BoutonHeight)); boutonGauche->setFixedSize(BoutonWidth,BoutonHeight); boutonGauche->installEventFilter(game); boutonGauche->move(BoutonMarge,(WindowHeight-BoutonHeight)/2); boutonGauche->setCursor(QCursor(QPixmap("../ressources/images/hud/cursor.png"), 0, 0)); boutonGauche->show(); QObject::connect(boutonGauche, SIGNAL(clicked()), game, SLOT(GoLeft())); } ClickableLabel *teamInfo = new ClickableLabel(game); teamInfo->setFixedSize(InfoWidth,InfoHeight); teamInfo->installEventFilter(game); teamInfo->move(WindowWidth-InfoWidth,WindowHeight-InfoHeight); teamInfo->setAlignment(Qt::AlignCenter); teamInfo->show(); QLabel *zoneInfoText = new QLabel(game); zoneInfoText->setFixedSize(InfoWidth,InfoHeight); zoneInfoText->setText(QString::fromStdString(map->getCurrentPosition().getText())); zoneInfoText->setAlignment(Qt::AlignCenter); zoneInfoText->move(0,WindowHeight-InfoHeight); zoneInfoText->setWordWrap(true); zoneInfoText->show(); QLabel *zoneTitleText = new QLabel(game); zoneTitleText->setFixedSize(TitleWidth,TitleHeight); zoneTitleText->setText(QString::fromStdString(map->getCurrentPosition().getName())); zoneTitleText->setAlignment(Qt::AlignCenter); zoneTitleText->move(0,0); zoneTitleText->setStyleSheet("QLabel{color:white;}"); zoneTitleText->setWordWrap(true); zoneTitleText->show(); QLabel *parametre = new QLabel(game); parametre->setFixedSize(TitleWidth,TitleHeight); parametre->setAlignment(Qt::AlignCenter); parametre->move(WindowWidth-TitleWidth,0); parametre->show(); QString styleBoutonRond = "QPushButton {color:white; background-color: #302514;" "border-style: outset; border-width: 1px;" "border-radius: 25px; border-color: beige;" "font: bold 14px; padding: 6px;}" "QPushButton:pressed {color:white; background-color: #000000;" "border-style: inset;}"; int tailleBouton(50); settings = new QPushButton("P", game); settings->setFixedSize(tailleBouton,tailleBouton); settings->move(WindowWidth-TitleWidth/2,20); settings->show(); settings->setStyleSheet(styleBoutonRond); inventory = new QPushButton("I", game); inventory->setFixedSize(tailleBouton,tailleBouton); inventory->move(WindowWidth-TitleWidth/2-50,20); inventory->show(); inventory->setStyleSheet(styleBoutonRond); QObject::connect(inventory, SIGNAL(clicked()), game, SLOT(afficheItemList())); QObject::connect(settings, SIGNAL(clicked()), game, SLOT(afficheParametre())); int espacementUI(5); int tailleUI((teamInfo->width()/4)-espacementUI*5); for (int i=0 ; i < Fight::nb_e ; i=i+1) { allie=game->GetGame()->getTeam()->getHeroes()[i]; if(allie != nullptr) { teamUI[i] = new TeamUI(game,allie,teamInfo->x()+espacementUI*(i+1)+tailleUI*i,teamInfo->y()+teamInfo->height()/2-tailleUI/2,tailleUI,tailleUI); } else { teamUI[i]=nullptr; } } }
true
9d4abdedd3497663414bfd266b3cba3754686137
C++
kotrenn/c8
/c8/interpret/binaryexp.cpp
UTF-8
1,700
3.15625
3
[]
no_license
#include "binaryexp.h" BinaryExp::BinaryExp(const string &op, Exp *lhs, Exp *rhs) :m_op(op), m_lhs(lhs), m_rhs(rhs) { } BinaryExp::~BinaryExp() { delete m_lhs; delete m_rhs; } Data BinaryExp::eval(VarTable *vars, FuncTable *funcs, bool *retstat) { //printf("BinaryExp::eval(\"%s\")\n", m_op.c_str()); Data lhs = m_lhs->eval(vars, funcs, retstat); Data rhs = m_rhs->eval(vars, funcs, retstat); Data ret; if (lhs.get_type().get_type() == "float" || rhs.get_type().get_type() == "float") { float lval = lhs.get_float(); float rval = rhs.get_float(); float val = 0.0; if (m_op == "+") val = lval + rval; if (m_op == "-") val = lval - rval; if (m_op == "*") val = lval * rval; if (m_op == "/") { if (rval == 0) { printf("Error: divide by zero\n"); exit(1); } val = lval / rval; } if (m_op == "%") { printf("Error: cannod modulo a float\n"); exit(1); } ret.set_type(DataType("float", 0)); ret.set_float(val); } else // ints { int lval = lhs.get_int(); int rval = rhs.get_int(); int val = 0; if (m_op == "+") val = lval + rval; if (m_op == "-") val = lval - rval; if (m_op == "*") val = lval * rval; if (m_op == "/") { if (rval == 0) { printf("Error: divide by zero\n"); exit(1); } val = lval / rval; } if (m_op == "%") { if (rval == 0) { printf("Error: modulo by zero\n"); printf("%d %% %d\n", lval, rval); exit(1); } val = lval % rval; } ret.set_type(DataType("int", 0)); ret.set_int(val); } return ret; }
true
21f5bc0bf493ade870cbc15c6fef3aaff21dd7e5
C++
cathook/PTTArticleRecommender
/src/article_analysis/utils/funcs-test.cc
UTF-8
882
3.21875
3
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include <string> #include <gtest/gtest.h> #include "utils/funcs.h" using std::string; namespace { TEST(FormatStr, IsCorrect) { int a = 7; std::string s("def"); EXPECT_EQ(utils::FormatStr("%d %d %s %s %s", a, 8, "abc", s, std::string("ghi")), "7 8 abc def ghi"); } TEST(TransformFromStr, int) { string a = "123 "; EXPECT_EQ(utils::TransformFromStr<int>(a), 123); EXPECT_EQ(utils::TransformFromStr<int>(move(a)), 123); } TEST(TransformFromStr, double) { string b = "123.4"; EXPECT_DOUBLE_EQ(utils::TransformFromStr<double>(b), 123.4); EXPECT_DOUBLE_EQ(utils::TransformFromStr<double>(move(b)), 123.4); } TEST(TransformFromStr, string) { string c = "meow meow"; EXPECT_EQ(utils::TransformFromStr<string>(c), "meow meow"); EXPECT_EQ(utils::TransformFromStr<string>(move(c)), "meow meow"); } } // namespace
true
3c5f35e3ad2882feb94e7ff5e19276eddfbc2fe5
C++
pfiorentino/Modelisation3D
/sphere.h
UTF-8
331
2.71875
3
[]
no_license
#ifndef SPHERE_H #define SPHERE_H #include "point3d.h" #include "implicitobject.h" #include <math.h> class Sphere : public ImplicitObject { public: Sphere(const Point3D &center, const int radius); virtual float getDistance(const Point3D& pt) const; private: Point3D _center; float _radius; }; #endif // SPHERE_H
true
f4a661a3f3fb6f230b3cc64bbe210d1b95005fb1
C++
3BodyProblem/QYAuthModule
/QYAuthModule/Infrastructure/Hash.cpp
GB18030
7,078
2.5625
3
[]
no_license
#include "Hash.h" CollisionHash::CollisionHash() : m_nUsedNumOfCollisionBucket( 0 ) { Clear(); } void CollisionHash::Clear() { m_nUsedNumOfCollisionBucket = 0; std::for_each( m_BucketOfHash, m_BucketOfHash+MAX_BUCKET_SIZE, std::mem_fun_ref(&T_ListNode::Clear) ); std::for_each( m_CollisionBucket, m_CollisionBucket+MAX_DATATABLE_NUM, std::mem_fun_ref(&T_ListNode::Clear) ); } int CollisionHash::NewKey( unsigned __int64 nKey, int nDataPos, unsigned __int64 nSeqNo ) { unsigned __int64 nKeyPos = nKey % MAX_BUCKET_SIZE; struct T_ListNode* pNode = m_BucketOfHash + nKeyPos; if( m_nUsedNumOfCollisionBucket >= (MAX_DATATABLE_NUM-1) ) { char pszError[128*2] = { 0 }; ::sprintf( pszError, "CollisionHash::NewKey() : data buffer is full : %u >= %u", m_nUsedNumOfCollisionBucket, (MAX_DATATABLE_NUM-1) ); throw std::runtime_error( pszError ); } if( true == pNode->IsNull() ) { pNode->nHashKey = nKey; pNode->nDataPos = nDataPos; pNode->nUpdateSequence = nSeqNo; pNode->pPrevNode = NULL; pNode->pNextNode = NULL; return 1; } while( true ) { if( nKey == pNode->nHashKey ) { return 0; } if( false == pNode->HasNext() ) { struct T_ListNode* pNewNodeOfCollision = m_CollisionBucket+m_nUsedNumOfCollisionBucket++; pNewNodeOfCollision->nHashKey = nKey; pNewNodeOfCollision->nDataPos = nDataPos; pNewNodeOfCollision->nUpdateSequence = nSeqNo; pNewNodeOfCollision->pPrevNode = pNode; pNewNodeOfCollision->pNextNode = NULL; pNode->pNextNode = pNewNodeOfCollision; return 1; } pNode = (struct T_ListNode*)(pNode->pNextNode); } return -1; } bool CollisionHash::CoordinateCollisionBucketPtr( struct T_ListNode* pNode2Erase ) { struct T_ListNode* pFirstCopyNode = pNode2Erase + 1; int nOffset = ((char*)pNode2Erase - (char*)m_CollisionBucket); unsigned int nErasePos = nOffset/sizeof(struct T_ListNode); ///< Ƶм䱻Ƴڵıռռ䣨ͨڴƶ+ָ¼ƫƣ ::memmove( pNode2Erase, pFirstCopyNode, (m_nUsedNumOfCollisionBucket - nErasePos - 1)*sizeof(T_ListNode) ); m_nUsedNumOfCollisionBucket -= 1; ///< ڸڱƳڵַԪָ붼ǰsizeof(struct T_ListNode) for( unsigned int n = 0; n < m_nUsedNumOfCollisionBucket; n++ ) { struct T_ListNode& refNode = m_CollisionBucket[n]; if( refNode.pPrevNode >= m_CollisionBucket && refNode.pPrevNode <= (m_CollisionBucket + m_nUsedNumOfCollisionBucket) ) { if( refNode.pPrevNode > pNode2Erase ) { refNode.pPrevNode = ((char*)(refNode.pPrevNode)) - sizeof(struct T_ListNode); } } if( refNode.pNextNode >= m_CollisionBucket && refNode.pNextNode <= (m_CollisionBucket + m_nUsedNumOfCollisionBucket) ) { if( refNode.pNextNode > pNode2Erase ) { refNode.pNextNode = ((char*)(refNode.pNextNode)) - sizeof(struct T_ListNode); } } } return true; } bool CollisionHash::CoordinateHashBucketPtr( struct T_ListNode* pEraseNodeInCollisionBucket ) { for( int n = 0; n < MAX_BUCKET_SIZE; n++ ) { struct T_ListNode& refNode = m_BucketOfHash[n]; if( refNode.pNextNode > pEraseNodeInCollisionBucket ) { refNode.pNextNode = ((char*)(refNode.pNextNode)) - sizeof(struct T_ListNode); } } return true; } void CollisionHash::CoordinateNodeIndex( struct T_ListNode* pNodeArray, unsigned int nNodeCount, int nEraseIndex ) { for( unsigned int n = 0; n < nNodeCount; n++ ) { struct T_ListNode& refNode = pNodeArray[n]; if( refNode.nDataPos > nEraseIndex ) { refNode.nDataPos -= 1; } } } void CollisionHash::CoordinateNodePtr( int nOffset ) { for( int n = 0; n < MAX_BUCKET_SIZE; n++ ) { T_ListNode& refNode = m_BucketOfHash[n]; if( refNode.pNextNode ) { refNode.pNextNode = (char*)(refNode.pNextNode) + nOffset; } if( refNode.pPrevNode ) { refNode.pPrevNode = (char*)(refNode.pPrevNode) + nOffset; } } for( int n = 0; n < MAX_DATATABLE_NUM; n++ ) { T_ListNode& refNode = m_CollisionBucket[n]; if( refNode.pNextNode ) { refNode.pNextNode = (char*)(refNode.pNextNode) + nOffset; } if( refNode.pPrevNode ) { refNode.pPrevNode = (char*)(refNode.pPrevNode) + nOffset; } } } int CollisionHash::DeleteKey( unsigned __int64 nKey ) { struct T_ListNode* pNode = m_BucketOfHash + (nKey % MAX_BUCKET_SIZE); while( false == pNode->IsNull() ) { if( nKey == pNode->nHashKey ) ///< ҵڵλ { struct T_ListNode* pEraseNodeInCollisionBucket = pNode; unsigned int nPosInDataArray = pNode->nDataPos; ///< ýڵָλ bool bNodeInHashBucket = (pNode >= (m_BucketOfHash+0) && pNode < (m_BucketOfHash+MAX_BUCKET_SIZE)); bool bNodeInCollisionBucket = (pNode >= (m_CollisionBucket+0) && pNode < (m_CollisionBucket+MAX_DATATABLE_NUM)); if( false == bNodeInHashBucket && false == bNodeInCollisionBucket ) { return -1; } ///< λ(ǰ) + ڵָ(ǰ) CoordinateNodeIndex( m_BucketOfHash, MAX_BUCKET_SIZE, nPosInDataArray ); CoordinateNodeIndex( m_CollisionBucket, m_nUsedNumOfCollisionBucket, nPosInDataArray ); if( true == bNodeInHashBucket ) ///< ڵڹϣͰ(ͷڵ) { if( NULL == pNode->pNextNode ) { ///< ޺ڵ pNode->Clear(); return 1; } ///< кڵ㣬轫ײͰеĹڵcopyͰ pEraseNodeInCollisionBucket = (struct T_ListNode*)(pNode->pNextNode); ::memcpy( pNode, pEraseNodeInCollisionBucket, sizeof(struct T_ListNode) ); pNode->pPrevNode = NULL; } else if( true == bNodeInCollisionBucket ) ///< ڵײͰ(ͷڵ) { pNode->Delete(); } ///< ϣͰУnextָڱƶڵĵַǰ CoordinateHashBucketPtr( pEraseNodeInCollisionBucket ); ///< ײͰУɾڵǰƣڵеָλֵ) CoordinateCollisionBucketPtr( pEraseNodeInCollisionBucket ); ///< ѵײͰĽڵǰڵ㣬ָhashͰַ if( NULL != pNode->pNextNode && true == bNodeInHashBucket ) { ((struct T_ListNode*)(pNode->pNextNode))->pPrevNode = pNode; } return 1; } else if( true == pNode->HasNext() ) { pNode = (struct T_ListNode*)(pNode->pNextNode); continue; } break; } return 0; } struct T_ListNode* CollisionHash::operator[]( unsigned __int64 nKey ) { unsigned __int64 nKeyPos = nKey % MAX_BUCKET_SIZE; struct T_ListNode* pNode = m_BucketOfHash + nKeyPos; while( false == pNode->IsNull() ) { if( nKey == pNode->nHashKey ) { return pNode; } else if( true == pNode->HasNext() ) { pNode = (struct T_ListNode*)(pNode->pNextNode); } else { break; } } return NULL; }
true
06ff16755f977998ab6e555f3751d58aaaa718e6
C++
DanikNik/univer
/file.cpp
UTF-8
1,371
3.28125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; bool isin(int num, int * arr, int len){ for(int i; i < len; i++){ if(num == arr[i]){ return 1; } } return 0; } int * append(int num, int * arr, int len){ int * temp1 = new int [len+1]; for (int i = 0; i < len; i++) { temp1[i] = arr[i]; } temp1[len] = num; return temp1; } int * makeset(int * myarr, int len, int &setlen){ int * temp; setlen = 0; for (size_t i = 0; i < len; i++) { if(isin(myarr[i], temp, setlen) == false){ temp = append(myarr[i], temp, setlen); setlen++; } } return temp; } int main(int argc, char const *argv[]) { fstream myfile("data.txt", ios_base::in); int a; int len = 0; int * arr; while (myfile >> a){ arr = append(a, arr, len); len++; } int setlen = 0; int * set = makeset(arr, len, setlen); int * counter = new int [setlen]; for (size_t i = 0; i < setlen; i++) { counter[i] = 0; } for (size_t i = 0; i < len; i++) { for (size_t j = 0; j < setlen; j++) { if (set[j] == arr[i]){ counter[j] ++; } } } for (size_t i = 0; i < setlen; i++) { cout << set[i] << " x" << counter[i] << endl; } return 0; }
true
9b4c2750446dd52e26c27ed2d93a56d0e5b169c7
C++
SoaringhawkCheng/thedesignandanalysisofalgorithm
/thedesignandanalysisofalgorithms/p90.cpp
UTF-8
2,515
3.21875
3
[]
no_license
// // p90.cpp // thedesignandanalysisofalgorithms // // Created by 追寻梦之碎片 on 2017/5/18. // Copyright © 2017年 追寻梦之碎片. All rights reserved. // #include <iostream> #include <iterator> #include <vector> #include <map> using namespace std; struct UndirectedGraphNode{ map<UndirectedGraphNode *,int> neighbors; }; class Solution{ public: vector<vector<int>> shortestcircuit(vector<UndirectedGraphNode> &graph){ vector<int> nums={0,1,2,3}; vector<vector<int>> result; int minpath=INT_MAX; do{ int path=countpath(graph, nums); if(path<minpath){ minpath=path; result.clear(); result.push_back(nums); } else if(path==minpath) result.push_back(nums); }while (next_permutation(nums)); return result; } private: bool next_permutation(vector<int> &nums){ auto pos=nums.rbegin(); do{ advance(pos, 1); }while(pos!=prev(nums.rend())&&*pos>=*prev(pos)); if(pos==prev(nums.rend())) return false; auto change=find_if(nums.rbegin(), pos, bind1st(less<int>(),*pos)); iter_swap(pos, change); reverse(nums.rbegin(), pos); return true; } int countpath(vector<UndirectedGraphNode> &graph,vector<int> &nums){ int path=0; for(int i=0;i<nums.size();++i){ path+=graph[nums[i]].neighbors[&graph[nums[(i+1)%nums.size()]]]; } return path; } }; int main(int argc,const char *argv[]){ vector<UndirectedGraphNode> graph(4); graph[0].neighbors.insert(make_pair(&graph[1], 2)); graph[0].neighbors.insert(make_pair(&graph[2], 5)); graph[0].neighbors.insert(make_pair(&graph[3], 7)); graph[1].neighbors.insert(make_pair(&graph[2], 8)); graph[1].neighbors.insert(make_pair(&graph[3], 3)); graph[2].neighbors.insert(make_pair(&graph[3], 1)); graph[1].neighbors.insert(make_pair(&graph[0], 2)); graph[2].neighbors.insert(make_pair(&graph[0], 5)); graph[3].neighbors.insert(make_pair(&graph[0], 7)); graph[2].neighbors.insert(make_pair(&graph[1], 8)); graph[3].neighbors.insert(make_pair(&graph[1], 3)); graph[3].neighbors.insert(make_pair(&graph[2], 1)); Solution s; vector<vector<int>> result; result=s.shortestcircuit(graph); for(auto res:result){ for(auto r:res) cout<<r<<" "; cout<<endl; } return 0; }
true
9494036928cd9659cf3f7a104ecfad448957b53d
C++
s-nandi/contest-problems
/dynamic-programming/general/twisty_movement.cpp
UTF-8
1,402
3.0625
3
[]
no_license
//dynamic programming, longest increasing subsequence with reversal //http://codeforces.com/contest/934/problem/C #include <iostream> #include <vector> #include <cstring> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int n; cin>>n; vector <int> a(n); for (int i = 0; i < n; i++) { cin>>a[i]; } int dp[2][n + 1][n + 1]; memset(dp, 0, sizeof(dp)); for (int i = 0; i < n; i++) { int oneTwos = 0, ones = 0; for (int j = i; j < n; j++) { if (a[j] == 1) { ones++; } else { oneTwos = max(oneTwos + 1, ones + 1); } dp[0][i][j] = max(oneTwos, ones); } } for (int i = n - 1; i >= 0; i--) { int oneTwos = 0, ones = 0; for (int j = i; j >= 0; j--) { if (a[j] == 1) { ones++; } else { oneTwos = max(oneTwos + 1, ones + 1); } dp[1][j][i] = max(oneTwos, ones); } } int sol = 0; for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { sol = max(sol, dp[0][0][i] + dp[1][i + 1][j] + dp[0][j + 1][n - 1]); } } cout<<sol<<'\n'; return 0; }
true
2e4160ee20d72945f37afe779e3f9c5267bbe35e
C++
zibas/futz
/src/futz/models/Model.cpp
UTF-8
4,453
2.765625
3
[ "MIT" ]
permissive
#include <cstring> #include <sstream> #include <iostream> #include <string> #include "Model.h" #include "../Futz.h" Model::Model(string name) { filename = name; size_t found; found = filename.find_last_of("/\\"); path = filename.substr(0,found+1); } void Model::Statistics(){ stringstream ss; ss << "Model loaded: "+filename + "\n\tTriangles: " << triangles.size() << "\n\tVertices: " << vertices.size() << "\n\tNormals: " << normals.size() << "\n\tTexture Coordinates: " << textureCoords.size() << "\n\tMaterials: " << materials.size() << "\n\tIndex Length: " << indexLength; Futz::Log(ss.str()); /* for(std::vector<Vector3>::iterator it = vertices.begin(); it != vertices.end(); ++it) { //(*it).Print(); } for (int i = 0; i < vertices.size() * 3; i += 3) { //printf("Vertex Array %d: %g, %g, %g\n",i,vertexArray[i],vertexArray[i+1],vertexArray[i+2]); } */ } void Model::ConvertTrianglesToBuffers(){ vertexArray = new float[triangles.size() * 9]; indexArray = new unsigned short[triangles.size() * 3]; colorArray = new float[triangles.size() * 3 * 4]; normalArray = new float[triangles.size() * 9]; textureCoordsArray = new float[triangles.size() * 3 * 2]; indexLength = 0; int submeshVertexCount = 0; string currentMaterialName = triangles[0].materialName; for (int i = 0; i < triangles.size(); i++) { Triangle t = triangles[i]; if(currentMaterialName != t.materialName && (materials[t.materialName].textureIndex != materials[currentMaterialName].textureIndex) ){ vertexGroups.push_back(pair<Material*, int>(&materials[t.materialName],submeshVertexCount)); cout << "Pushing " << currentMaterialName << endl; submeshVertexCount = 0; currentMaterialName = t.materialName; } int j = i * 9; vertexArray[j] = vertices[t.v1].x; j++; vertexArray[j] = vertices[t.v1].y; j++; vertexArray[j] = vertices[t.v1].z; j++; vertexArray[j] = vertices[t.v2].x; j++; vertexArray[j] = vertices[t.v2].y; j++; vertexArray[j] = vertices[t.v2].z; j++; vertexArray[j] = vertices[t.v3].x; j++; vertexArray[j] = vertices[t.v3].y; j++; vertexArray[j] = vertices[t.v3].z; j++; submeshVertexCount += 3; j = i * 9; normalArray[j] = normals[t.n1].x; j++; normalArray[j] = normals[t.n1].y; j++; normalArray[j] = normals[t.n1].z; j++; normalArray[j] = normals[t.n2].x; j++; normalArray[j] = normals[t.n2].y; j++; normalArray[j] = normals[t.n2].z; j++; normalArray[j] = normals[t.n3].x; j++; normalArray[j] = normals[t.n3].y; j++; normalArray[j] = normals[t.n3].z; j++; j = i * 3; indexArray[j] = j; j++; indexArray[j] = j; j++; indexArray[j] = j; j++; indexLength += 3; j = i * 6; if(materials[currentMaterialName].hasTexture){ textureCoordsArray[j] = textureCoords[t.tex1].x; j++; textureCoordsArray[j] = textureCoords[t.tex1].y; j++; textureCoordsArray[j] = textureCoords[t.tex2].x; j++; textureCoordsArray[j] = textureCoords[t.tex2].y; j++; textureCoordsArray[j] = textureCoords[t.tex3].x; j++; textureCoordsArray[j] = textureCoords[t.tex3].y; j++; } else { textureCoordsArray[j] = 0; j++; textureCoordsArray[j] = 0; j++; textureCoordsArray[j] = 0; j++; textureCoordsArray[j] = 0; j++; textureCoordsArray[j] = 0; j++; textureCoordsArray[j] = 0; j++; } j = i * 3 * 4; colorArray[j] = t.rgba[0]; j++; colorArray[j] = t.rgba[1]; j++; colorArray[j] = t.rgba[2]; j++; colorArray[j] = t.rgba[3]; j++; colorArray[j] = t.rgba[0]; j++; colorArray[j] = t.rgba[1]; j++; colorArray[j] = t.rgba[2]; j++; colorArray[j] = t.rgba[3]; j++; colorArray[j] = t.rgba[0]; j++; colorArray[j] = t.rgba[1]; j++; colorArray[j] = t.rgba[2]; j++; colorArray[j] = t.rgba[3]; j++; } if(submeshVertexCount > 0){ vertexGroups.push_back(pair<Material*, int>(&materials[currentMaterialName],submeshVertexCount)); submeshVertexCount = 0; } } void Model::LoadTexturesForMaterials(){ map<string,Material>::iterator pair; int i = 0; for ( pair=materials.begin() ; pair != materials.end(); pair++ ){ if((*pair).second.hasTexture){ LoadImage((*pair).second.textureFilename, i); materials[(*pair).first].textureIndex = i; i++; } } } void Model::LoadImage(string filename, int textureIndex){ Futz::Instance()->renderer->LoadImage(this, filename, textureIndex); } int Model::PolyCount(){ return triangles.size(); } void Model::Load() { } Model::~Model() { // free(vertexArray); }
true
32a8deb726ff1527e95b47a016712c5a01052d28
C++
s0mnaths/amfoss-tasks
/task-15/euler003.cpp
UTF-8
794
2.890625
3
[]
no_license
#include <cmath> #include <iostream> using namespace std; int main(){ int t; cin >> t; long largest[t]={0}; for(int a0 = 0; a0 < t; a0++) { long n; cin >> n; while (n % 2 == 0) { largest[a0]=2; n = n/2; } for (int i = 3; i <= sqrt(n); i = i + 2) { while (n % i == 0) { if(i>largest[a0]) largest[a0]=i; n = n/i; } } if (n > 2) if(n>largest[a0]) largest[a0]=n; } for(int a0=0;a0<t;a0++) { cout<<largest[a0]<<endl; } return 0; }
true
7947b95a250dd956dcf8f0794101befeb9c9cfe6
C++
AleGrins/CPP_assignemt3
/unit_tests.cpp
UTF-8
1,485
3.40625
3
[]
no_license
#include <iostream> using namespace std; #include "Member.cpp" int main() { Member a; cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 0 0 cout << "Member count: " << Member::count() << endl; // 1 Member b; cout << "Member count: " << Member::count() << endl; // 2 int aID = a.getID(); int bID = b.getID(); cout << "ID of a: " << aID << " ID of b: " << bID << endl; a.follow(b); cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 0 1 cout << "Members following b: " << b.numFollowers() << " Members b is following: " << b.numFollowing() << endl; // 1 0 a.follow(b); // duplicate follow has no effect cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 0 1 a.unfollow(b); cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 0 1 Member c,d,e; cout << "Member count: " << Member::count() << endl; // 5 a.follow(b); a.follow(c); a.follow(d); a.follow(e); b.follow(a); c.follow(a); d.follow(a); e.follow(a); cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 4 4 a.follow(a); //can't follow yourself cout << "Members following a: " << a.numFollowers() << " Members a is following: " << a.numFollowing() << endl; // 4 4 }
true
f9269c7fa924c935504cad06e08bb3b590f587e2
C++
richardsplit/C_plus_plus_-_VSCode
/02_19_2021_push/Moving.cpp
UTF-8
1,177
2.765625
3
[]
no_license
#include<iostream> //#include <cmath> //#include<ostream> //#include<vector> //#include<<sum<string> //#include <climits> //#include <algorithm> #include<string> //#include <memory> //#include <sstream> using namespace std; //using std::cout; //using std::endl; //smart pointer is a wrapper around a pointer //dont have to call new and delete  int main (){  int width_free_space,lenght_free_space,height_free_space; cin>>width_free_space>>lenght_free_space>>height_free_space;    int volume =width_free_space*lenght_free_space*height_free_space;        string input;    cin>>input;      while(input!="Done"){          int boxes=stoi(input);          volume -=boxes;          if(volume<=0){              break;          }          cin>>input;      }     // std::cout.setf(ios::fixed);     // std::cout.precision(2);     if(volume<=0){         std::cout<<"No more free space! You need " <<volume * -1 <<" Cubic meters more."<<std::endl;     }else{     std::cout<<volume<<" Cubic meters left."<<std::endl;     } }
true
da9f82ed2f415f06d29b123db0b26ba8f4bc0153
C++
adrianpoplesanu/personal-work
/cpp/repl/big-numbers2/parser.cpp
UTF-8
737
2.84375
3
[]
no_license
#include "parser.h" Parser::Parser() { } Parser::~Parser() { } void Parser::load(std::string source) { lexer.load(source); nextToken(); nextToken(); } void Parser::nextToken() { currentToken = peekToken; peekToken = lexer.nextToken(); } void Parser::buildProgramStatements(AstProgram program) { while(currentToken.getType() != TT_EOF) { std::cout << currentToken.toString() << "\n"; AstNode* stmt = parseStatement(); if (stmt) program.statements.push_back(stmt); nextToken(); } } AstNode* Parser::parseStatement() { if (currentToken.getType == TT_LET) { //... return parseLetStatement(); } //... return ParseExpressionStatement(); return NULL; }
true
75d987bfd286bb8fe107cbdd9df141fcc0769dd5
C++
AndrewShkrob/Courses
/Coursera/Art of Development in Modern C++ Specialization/Red Belt/Week2/training/booking.cpp
UTF-8
2,037
3.265625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; struct Event { string hotel_name; int64_t time; size_t client_id; size_t room_count; }; struct Hotel { size_t booked_rooms = 0; map<size_t, size_t> clients; void addEvent(const Event &event) { booked_rooms += event.room_count; clients[event.client_id] += event.room_count; } }; class HotelManager { public: size_t Clients(const string &hotel_name) { return hotels[hotel_name].clients.size(); } size_t Rooms(const string &hotel_name) { return hotels[hotel_name].booked_rooms; } void Book(const Event &event) { adjust(event.time); hotels[event.hotel_name].addEvent(event); events.push(event); } private: static const int64_t day_time = 86400; map<string, Hotel> hotels; queue<Event> events; void adjust(int64_t current_time) { while (!events.empty() && current_time - events.front().time >= day_time) { auto &event = events.front(); auto &hotel = hotels[event.hotel_name]; hotel.booked_rooms -= event.room_count; hotel.clients[event.client_id] -= event.room_count; if (hotel.clients[event.client_id] == 0) hotel.clients.erase(event.client_id); events.pop(); } } }; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); HotelManager m; int q; cin >> q; for (int i = 0; i < q; i++) { int64_t time; uint client_id; size_t room_count; string command, hotel_name; cin >> command; if (command == "CLIENTS") { cin >> hotel_name; cout << m.Clients(hotel_name) << '\n'; } else if (command == "ROOMS") { cin >> hotel_name; cout << m.Rooms(hotel_name) << '\n'; } else { cin >> time >> hotel_name >> client_id >> room_count; m.Book({hotel_name, time, client_id, room_count}); } } }
true
6d961d3f28548ede674b35f92ade807fd10720bb
C++
guille31794/AAED
/Practica 4/polinom/e_s_polinom.h
UTF-8
811
2.859375
3
[]
no_license
//Cabeceras de es_polinom.cpp #include "polinom.h" using namespace std; //Grado maximo de un polinomio const unsigned gradoMax = 3; //Función que inicializa los polinomios void introducirPolinomio(polinomio &p1, polinomio &p2); //Funcion que añade los coeficientes a los polinomios void introducirCoeficientes(polinomio &p, int g); //Función que permite establecer el grado del polinomio int introducirGrado(); //Realiza la suma de dos polinomios dados void suma(polinomio const &p1, polinomio const &p2); //Realiza la resta de dos polinomios void resta(polinomio const &p1, polinomio const &p2); //Realiza el producto de dos polinomios void producto(polinomio const &p1, polinomio const &p2); //Realiza la derivada de un polinomio void derivada(polinomio const &p1, polinomio const &p2);
true
52d11b2c1c493294598e530ed04776dad206905f
C++
Edekheh/JarvisOS
/JarvisOS.ino
UTF-8
608
2.921875
3
[]
no_license
#include "menu.h" #include <Arduino.h> void (*menu)(int,String);//menu variable String str="";//serial input variable void setup() { // put your setup code here, to run once: menu=mainMenu;//initialize menu pointer on main menu Serial.begin(115200);//initialize serial communication with 115200 bps setUpOledDisplay(); } void loop() { // put your main code here, to run repeatedly: while(Serial.available()>0) { str=Serial.readString(); } if(str[0]-48>-1 && str[0]-48<10) { menu(str[0]-48,str); str[0]='x'; } else if(str.length()>2) { menu(9,str); str="x"; } }
true
0ff1f607ea8772a7e598790ba8ad928a86b43177
C++
vishmohan/inline_assembly_examples
/factorial/factorial.cpp
UTF-8
674
3.265625
3
[]
no_license
#include <iostream> using namespace std; int fact(int n); int main() { int num; cout << "Enter num: " << endl; cin >> num ; cout << fact(num) << endl; return 0; } int fact(int n) { int result; //rcx has the input number asm volatile("movq %0, %%rcx\n" ::"m"(n)); //rax = 1 asm volatile("movq $1, %rax\n"); //handle special case when n = 0 asm volatile("cmp $0, %rcx\n"); asm volatile("cmove %rax, %rcx\n"); //if n=0 then make rcx = 1 //rdx:rax = rcx * rax asm volatile("continue: imul %%rcx\n":"=A"(result)::); // rcx = rcx - 1 ; if rcx != 0 then continue multiplication asm volatile("loop continue"); asm volatile("done: "); return result; }
true
da88b4de26de8bc4faaad9192ce9bcc77553d6b8
C++
Barne1/AIGunner
/Source/AIGunner/FGHealthComponent.cpp
UTF-8
680
2.53125
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "FGHealthComponent.h" // Sets default values for this component's properties UFGHealthComponent::UFGHealthComponent() { } // Called when the game starts void UFGHealthComponent::BeginPlay() { Super::BeginPlay(); CurrentHealth = MaxHealth; } float UFGHealthComponent::GetHealthPercentage() { return CurrentHealth/MaxHealth; } void UFGHealthComponent::TakeDamage(int Damage) { if(!bAlive) return; OnTakeDamage.Broadcast(Damage); CurrentHealth -= Damage; CurrentHealth = FMath::Max(0, CurrentHealth); if(CurrentHealth <= 0) { bAlive = false; OnDeath.Broadcast(); } }
true
40859af143ac58d8d36b26786033f2744e10f96a
C++
terz99/course-algorithms-data-structures
/hw10/fullhw/p1.cpp
UTF-8
1,644
3.40625
3
[]
no_license
/** * Problem 1 * @author: Dushan Terzikj 30001357 * @since: 29.04.2018 */ #include <bits/stdc++.h> using namespace std; int *dp; /** * The algorithm for getting the longest increasing * subsequence. * @param arr the full sequence * @param n the size of the full sequence (arr) */ int solve(int arr[], int n){ for(int i = 0; i < n; i++){ /* Each number is a increasing subsequence of length 1 with itself */ dp[i] = 1; } for(int i = 1; i < n; i++){ for(int j = 0; j < i; j++){ if(arr[i] > arr[j] && dp[i] < dp[j]+1){ dp[i] = dp[j] + 1; } } } /* Getting the biggest result, i.e., the longest increasing subsequence */ int res = 0; for(int i = 0; i < n; i++){ res = max(res, dp[i]); } return res; } int main(){ /* Input an initialization */ int n; cin >> n; int arr[n+2]; dp = new int[n+2]; int longest = solve(arr, n); // call the algorithm /* Path reconstruction */ int lastPos = longest; vector<int> seq(longest, -1); for(int i = n-1; i >= 0; i--){ if(lastPos == dp[i] && arr[i] > seq[lastPos-1]){ if(lastPos == longest){ seq[lastPos-1] = arr[i]; } else if(arr[i] < seq[lastPos]){ seq[lastPos-1] = arr[i]; } } else if(lastPos-1 == dp[i]){ lastPos--; seq[lastPos-1] = arr[i]; } } /* Output */ for(unsigned int i = 0; i < seq.size(); i++){ cout << seq[i] << " "; } cout << endl; delete[] dp; // Memory dealloc return 0; }
true
8370ecc96b6805aa97a6783eb0ac38b2b7073851
C++
Quartzeee/cppThreadPool
/threadPool.cpp
UTF-8
2,898
3.203125
3
[ "MIT" ]
permissive
#include "threadPool.h" /** * Default constructor - this ctor will initialize the pool to contain the number of hardware threads on the machine. */ ThreadPool::ThreadPool() : bAlive(true) { this->initThreads(thread::hardware_concurrency()); }; /** * Constructor for caller to specify the number of threads it would like the pool to contain. * @param iNumThreads */ ThreadPool::ThreadPool(const unsigned int& iNumThreads) : bAlive(true) { this->initThreads(iNumThreads); }; /** * Destructor - dtor will stop the daemon and join all working threads. */ ThreadPool::~ThreadPool() { this->kill(); // Stop processing for(auto &t : this->vThreads) t.join(); // Join all of the threads before destructing } /** * This is our delegated thread initializer. * @param iNumThreads */ void ThreadPool::initThreads(const unsigned int& iNumThreads) { for(unsigned int i = 0; i <= iNumThreads; i++) { this->vThreads.emplace_back(&ThreadPool::processJobs, this); } } /** * Use this method to pass bound functions or functors to the pool of threads for processing. * * For example: threadPool.addJob(bind( voidFuncName, param1, param2, ... )); * @param tNewJob */ void ThreadPool::addJob(function<void()> &&tNewJob) { lock_guard<mutex> lck(this->_jobsQueueMtx); // Obtain a lock on the jobs queue this->qJobs.emplace(move(tNewJob)); // Once that lock is obtained, move our function object into the queue this->cvJobs.notify_one(); // Notify a waiting thread that work is available } /** * This method is used by the threads to wait and listen for more work. When work arrives, * one of the waiting threads is notified and processes a single job. It then waits for more * work or to be signaled to stop by the kill() method. */ void ThreadPool::processJobs() { while(this->bAlive) // Daemon flag { function<void()> job; // job storage { unique_lock<mutex> lck(this->_jobsQueueMtx); // Obtain a lock on the jobs queue this->cvJobs.wait(lck, [&]{ return (!bAlive || !this->qJobs.empty()); }); // Wait for lock, the predicate returns false to continue waiting on spurious wake-ups if(!bAlive) return; // If our daemon has been killed then we are going to exit job = move(this->qJobs.front()); // grab the job of our locked queue this->qJobs.pop(); // Remove the job from the queue } // release lock job(); // Process job (if you have a different signature that accepts a param, it would go here. i.e. void(int) = job(1)) } } /** * This method will stop the daemon and notify all waiting threads to stop processing. * This will not join the threads, they will just cease processing. */ void ThreadPool::kill() { this->bAlive = false; // Flip our daemon flag this->cvJobs.notify_all(); // Notify all threads to stop waiting and exit }
true
5d090716fd525e0401a9b31ab179c635659b40ca
C++
MacManus88/Microcontroller-Sources
/ultrasonic_candle.ino
UTF-8
853
2.640625
3
[]
no_license
//Mehr Infos auf: http://www.pascals-koenigreich.de/2013/04/led-kerze-mit-unterschiedlichen.html #include <NewPing.h> #define TRIGGER_PIN 12 #define ECHO_PIN 11 #define MAX_DISTANCE 15 NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); int ledPin = 9; int last_value = pow(MAX_DISTANCE, 2)-50; void setup() { pinMode(ledPin, OUTPUT); Serial.begin(115200); } void loop() { unsigned int uS = sonar.ping(); int cm = uS / US_ROUNDTRIP_CM; Serial.print("Ping: "); Serial.print(cm); Serial.println("cm"); int i; if (cm == 0) { i = last_value; } else if (cm <= 8) { i = pow(cm, 2); last_value=i; } else if (cm <= MAX_DISTANCE) { i = pow(cm, 2)-50; last_value=i; } Serial.print("LED-Value: "); Serial.println(i); analogWrite(ledPin, random(50)+i); delay(random(50,100)); }
true
3a68d49415188e2c43c7525d9ac8c3f56fd48b81
C++
m0178/legoino
/arduino/Arduino v105.app/Contents/Resources/Java/libraries/ChibiOS_AVR/examples/chMutex/chMutex.ino
UTF-8
1,732
2.796875
3
[]
no_license
// Example of mutex to prevent print calls from being scrambled #include <ChibiOS_AVR.h> // declare and initialize a mutex for limiting access to threads MUTEX_DECL(demoMutex); // data structures and stack for thread 2 static WORKING_AREA(waTh2, 100); // data structures and stack for thread 3 static WORKING_AREA(waTh3, 100); //------------------------------------------------------------------------------ void notify(const char* name, int state) { // wait to enter print region chMtxLock(&demoMutex); // only one thread in this region while doing prints Serial.print(name); Serial.write(": "); Serial.println(state); // exit protected region chMtxUnlock(); } //------------------------------------------------------------------------------ msg_t thdFcn(void *args) { while (true) { notify((const char*)args, 0); chThdSleep(1000); notify((const char*)args, 1); chThdSleep(1000); } } //------------------------------------------------------------------------------ void setup() { Serial.begin(9600); // wait for USB Serial while (!Serial) {} // initialize and start ChibiOS chBegin(chSetup); // should not return while(1); } //------------------------------------------------------------------------------ void chSetup() { // schedule thread 2 chThdCreateStatic(waTh2, sizeof(waTh2), NORMALPRIO, thdFcn, (void*)"Th 2"); // schedule thread 3 chThdCreateStatic(waTh3, sizeof(waTh3), NORMALPRIO, thdFcn, (void*)"Th 3"); // main thread is thread 1 at NORMALPRIO thdFcn((void*)"Th 1"); } //------------------------------------------------------------------------------ void loop() {/* not used */}
true
c1731e4f00dabeec41168f2e21e81bc50d5d1bd6
C++
ptryfon/loxim-stats
/Protogen/loxim_protocol/cpp/protocol/packages_data/Uint32Package.h
UTF-8
730
2.578125
3
[]
no_license
#ifndef UINT32PACKAGE_H_ #define UINT32PACKAGE_H_ #include <stdint.h> #include "../ptools/Package.h" #include "../ptools/CharArray.h" #include "../enums/enums.h" namespace protocol{ #define ID_Uint32Package 5 class Uint32Package : public Package { private: uint32_t value; public: Uint32Package(); ~Uint32Package(); Uint32Package( uint32_t a_value ); virtual bool equals(Package* _package); uint32_t getValue(){return value;}; void setValue(uint32_t a_value){value=a_value;}; uint8_t getPackageType(){return ID_Uint32Package;}; protected: void serializeW(PackageBufferWriter *writter); bool deserializeR(PackageBufferReader *reader); };//class }//namespace #endif /*define UINT32PACKAGE_H_*/
true
b026caf8fc41f4ec2b20707f31318ee19cb7ab27
C++
amaliujia/velox
/velox/common/serialization/Registry.h
UTF-8
3,720
2.625
3
[ "Apache-2.0" ]
permissive
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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. */ // fork from CAFFE2 registry #pragma once #include <algorithm> #include <cstdio> #include <cstdlib> #include <functional> #include <memory> #include <mutex> #include <string_view> #include <unordered_map> #include <glog/logging.h> #include "folly/Preprocessor.h" #include "velox/common/base/Exceptions.h" #include "velox/core/Metaprogramming.h" namespace facebook { namespace velox { /** * @brief A template class that allows one to register function objects by keys. * * The keys are usually a string specifying the name, but can be anything that * can be used in a std::map. * It provides `Create` function to directly call with key and arguments. */ template <class KeyType, class FunctionSignature> class Registry { public: using Creator = std::function<FunctionSignature>; using CreatorMap = std::unordered_map<KeyType, Creator>; Registry() : Create(creatorMap_) {} void Register( const KeyType& key, Creator creator, std::optional<std::string_view> helpMsg = std::nullopt) { std::lock_guard<std::mutex> lock(registerutex_); creatorMap_[key] = std::move(creator); if (helpMsg) { helpMessage_[key] = *helpMsg; } } inline bool Has(const KeyType& key) const { return (creatorMap_.count(key) != 0); } /** * Returns the keys currently registered as a vector. */ std::vector<KeyType> Keys() const { std::vector<KeyType> keys; for (const auto& it : creatorMap_) { keys.push_back(it.first); } return keys; } const std::unordered_map<KeyType, std::string>& HelpMessage() const { return helpMessage_; } const char* HelpMessage(const KeyType& key) const { auto it = helpMessage_.find(key); if (it == helpMessage_.end()) { return nullptr; } return it->second.c_str(); } private: CreatorMap creatorMap_; std::unordered_map<KeyType, std::string> helpMessage_; std::mutex registerutex_; Registry(const Registry& other) = delete; public: template <typename T> struct CreateFunction; template <class ReturnType, class... ArgTypes> struct CreateFunction<ReturnType(ArgTypes...)> { CreateFunction(const CreatorMap& creatorMap) : creatorMap_(creatorMap) {} ReturnType operator()(const KeyType& key, ArgTypes... types) const { const auto it = creatorMap_.find(key); if (it == creatorMap_.end()) { if constexpr (facebook::velox::util::is_smart_pointer< ReturnType>::value) { return nullptr; } VELOX_UNSUPPORTED( typeid(ReturnType).name(), " is not nullable return type"); } return it->second(types...); } private: const CreatorMap& creatorMap_; }; // Provide Create function as a function object // If there is no key found, it will: // Smart pointer types: return nullptr // Value types : throw invalid_argument exception. // // Function signature: // ReturnType Create(const KeyType& key, ArgTypes...); const CreateFunction<FunctionSignature> Create; }; } // namespace velox } // namespace facebook
true
16d518b613a23aa3fadb4814ea6fee04a664404e
C++
JCP92/Cplusplus-Programs
/tic tac toe.cpp
UTF-8
1,639
3.171875
3
[]
no_license
#include<iostream> #include<iomanip> #include<string> #include<ctime> #include<math.h> #include<array> using namespace std; const short int ROW = 3; const short int COLUMN = 3; //const short int X = 1; //const short int O = -1; const char Player1 = 'X'; const char Player2 = 'O'; short int turn = 0; char board[ROW][COLUMN] = {}; short int locate1, locate2; void gameBoard(int row1, int column1, int player); void coordinateDisplay(); void verificationCheck(); int main() { coordinateDisplay(); for (int turn = 0; turn < 9; turn++) { if (turn % 2 == 0) { cout << "Player 1's turn: \nPlease input the coordinates to place the X value: " << endl; cin >> locate1 >> locate2; board[locate1][locate2] = Player1; gameBoard(locate1, locate2, Player1); } else { cout << "Player 2's turn: \nPlease input the coordinates to place the X value: " << endl; cin >> locate1 >> locate2; board[locate1][locate2] = Player2; gameBoard(locate1, locate2, Player2); } } return 0; } void gameBoard(int row1, int column1, int player) { for (int i = 0; i < ROW; i++) { for (int n = 0; n < COLUMN; n++) { board[row1][column1] = player; if (n < 2) { cout << setw(2) << board[i][n] << " |"; } else cout << setw(2) << board[i][n]; } cout << endl; } } void coordinateDisplay() { for (int i = 0; i < 3; i++) { for (int n = 0; n < 3; n++) { if (n < 2) { cout << setw(2) << "(" << i << "," << n << ")" << " |"; } else { cout << setw(2) << "(" << i << "," << n << ")"; } } cout << endl; } }
true
13f3301dc212ee93754d01e776d04ef04bb21833
C++
vigansub/StructureAwareShapeTemplates
/Src/Light.h
UTF-8
2,311
2.59375
3
[]
no_license
#ifndef LIGHT_H #define LIGHT_H #include "Headers.h" #include "Geometry.h" #ifndef WIN32 typedef unsigned long DWORD; typedef unsigned short WORD; typedef unsigned int UNINT32; #endif class CameraManager; class VertexBufferObject; class Shader; class FrameBufferObject; class Scene; class Light { public: struct Path { QString name; vector<vec3> positions; }; enum Type { SPOT_LIGHT = 0, DIRECTIONAL_LIGHT }; Light(Scene *scene, Type type, const vec3 &color, const vec3 &pos, const vec3 &dir = vec3(), const vec3 &intensity = vec3(1.0f, 1.0f, 1.0f), const vec4 &cone = vec4(), vec3 attenuation = vec3()); ~Light(); void blurShadowMap(); void renderLightView(mat4 &lightView); void render(const Transform &trans); void setPosition(const vec3 &pos); void move(CameraManager *camManager, float diffX, float diffY); void loadPaths(); void savePaths(); void recordPath(bool record); void autoMove(); void toggleMode(); bool hasMoved(); vec3 position() const; vec3 direction() const; vec3 intensity() const; vec4 cone() const; vec3 attenuation() const; vec3 color() const; Type type() const; void setIntensity(float intensity); void setDirection(const vec3 &dir); void update(float delta); GLuint shadowMapId() const; GLuint shadowMapBlurredId() const; bool m_moved; private: vec3 m_position; vec3 m_direction; vec3 m_intensity; vec4 m_cone; vec3 m_attenuation; vec3 m_color; Type m_type; float m_renderSize; vector<Path> m_paths; Path m_curPath; bool m_record; bool m_first; bool m_saved; DWORD m_oldTime; int m_moveMode; float m_height; float m_angle; float m_radius; vec3 m_oldPosition; Spline m_spline; float m_time; float m_speed; float m_distance; float m_movement; VertexBufferObject *m_vbo; VertexBufferObject *m_vboBlur; GLuint m_shadowMapID; GLuint m_shadowMapBlurredID; public: FrameBufferObject *m_fboLight; FrameBufferObject *m_fboBlurV; FrameBufferObject *m_fboBlurH; int m_bufferWidth; int m_bufferHeight; float m_fcpLight; float m_ncpLight; float m_fovLight; Scene *m_scene; mat4 m_lightView; }; #endif
true
2d9bad268e3a8fb5f0cc8f1937de22c83b68519e
C++
MiChuan/Leetcode
/LCCI/lcci1704 1~n中缺失的数字(等差求和)/res.cpp
UTF-8
229
2.765625
3
[]
no_license
class Solution { public: int missingNumber(vector<int>& nums) { int n = nums.size(); int count = n * (1 + n) / 2; for(int num : nums){ count -= num; } return count; } };
true
6a9150b2968ee858d542987b0a8533d5c006c972
C++
RPI-Game-Architecture-Spring-2020/final-projecct-LionLin27
/src/ga1-core/physics/ga_intersection.h
UTF-8
3,051
2.8125
3
[ "MIT" ]
permissive
#pragma once /* ** RPI Game Architecture Engine ** ** Portions adapted from: ** Viper Engine - Copyright (C) 2016 Velan Studios - All Rights Reserved ** ** This file is distributed under the MIT License. See LICENSE.txt. */ #include "math/ga_mat4f.h" #include "math/ga_vec3f.h" #include <vector> struct ga_shape; struct ga_plane; class ga_rigid_body; /* ** Information returned when a collision is detected. ** Includes the point of collision, the normal at the collision point, and ** the amount the two objects are interpenetrating. */ struct ga_collision_info { ga_vec3f _point; ga_vec3f _normal; float _penetration; }; /* ** Compute the distance from a point in 3d space to a plane. */ float distance_to_plane(const ga_vec3f& point, const ga_plane* plane); /* ** Compute the distance from a point in 3d space to a line segment. */ float distance_to_line_segment(const ga_vec3f& point, const ga_vec3f& a, const ga_vec3f& b); /* ** Compute the closest points on two lines. ** @returns True if the points lie with the bounds provided for each segment. */ bool closest_points_on_lines( const ga_vec3f& start_a, const ga_vec3f& end_a, const ga_vec3f& start_b, const ga_vec3f& end_b, ga_vec3f& point_a, ga_vec3f& point_b); /* ** Compute the point farthest along a directional vector. */ ga_vec3f farthest_along_vector(const std::vector<ga_vec3f>& points, const ga_vec3f& vector); /* ** Stub function for unimplemented collision algorithms. */ bool intersection_unimplemented(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between sphere and plane. */ bool sphere_vs_plane(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between bounding box and plane. */ bool oobb_vs_plane(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between two sphere shapes. */ bool sphere_vs_sphere(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between two capsule shapes. */ bool capsule_vs_capsule(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between two axis-aligned bounding boxes. */ bool aabb_vs_aabb(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between two oriented bounding boxes. */ bool separating_axis_test(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info); /* ** Check for a collision between two arbitrary convex hulls. */ bool gjk(const ga_shape* a, const ga_mat4f& transform_a, const ga_shape* b, const ga_mat4f& transform_b, ga_collision_info* info);
true
40f5924cad6da347756e5050c5cd93b7e392fac1
C++
DmitryYurov/qt-mvvm
/tests/viewmodel/TestPropertiesRowStrategy.cpp
UTF-8
4,308
2.78125
3
[]
no_license
#include "google_test.h" #include "propertiesrowstrategy.h" #include "sessionitem.h" #include "sessionmodel.h" #include "vectoritem.h" #include "viewdataitem.h" #include "test_utils.h" using namespace ModelView; class TestPropertiesRowStrategy : public ::testing::Test { public: ~TestPropertiesRowStrategy(); }; TestPropertiesRowStrategy::~TestPropertiesRowStrategy() = default; TEST_F(TestPropertiesRowStrategy, initialState) { PropertiesRowStrategy strategy({}); EXPECT_EQ(strategy.constructRow(nullptr).size(), 0); EXPECT_EQ(strategy.horizontalHeaderLabels(), QStringList()); } //! Checks row construction for standard top level item. It shouldn't generate any rows. TEST_F(TestPropertiesRowStrategy, topLevelItem) { SessionItem item("model_type"); PropertiesRowStrategy strategy({}); auto items = strategy.constructRow(&item); EXPECT_EQ(items.size(), 0); EXPECT_EQ(strategy.horizontalHeaderLabels(), QStringList()); TestUtils::clean_items(items); } //! Checks row construction for property item. It shouldn't generate any rows. TEST_F(TestPropertiesRowStrategy, propertyItem) { SessionItem item("model_type"); item.setData(42.0); PropertiesRowStrategy strategy({}); auto items = strategy.constructRow(&item); EXPECT_EQ(items.size(), 0); EXPECT_EQ(strategy.horizontalHeaderLabels(), QStringList()); TestUtils::clean_items(items); } //! Checks row construction for vector item. //! There should be 3 view items looking to x, y, z properties. TEST_F(TestPropertiesRowStrategy, vectorItem) { VectorItem item; EXPECT_EQ(item.property(VectorItem::P_X).toDouble(), 0.0); EXPECT_EQ(item.property(VectorItem::P_Y).toDouble(), 0.0); EXPECT_EQ(item.property(VectorItem::P_Z).toDouble(), 0.0); PropertiesRowStrategy strategy({"a", "b", "c"}); auto items = strategy.constructRow(&item); EXPECT_EQ(items.size(), 3); EXPECT_EQ(strategy.horizontalHeaderLabels(), QStringList() << "a" << "b" << "c"); // views should look at 3 property items auto view_x = dynamic_cast<ViewDataItem*>(items.at(0)); ASSERT_TRUE(view_x != nullptr); EXPECT_EQ(view_x->item(), item.getItem(VectorItem::P_X)); auto view_y = dynamic_cast<ViewDataItem*>(items.at(1)); ASSERT_TRUE(view_y != nullptr); EXPECT_EQ(view_y->item(), item.getItem(VectorItem::P_Y)); auto view_z = dynamic_cast<ViewDataItem*>(items.at(2)); ASSERT_TRUE(view_z != nullptr); EXPECT_EQ(view_z->item(), item.getItem(VectorItem::P_Z)); TestUtils::clean_items(items); } //! Row construction for rootItem with single item inserted. Shouldn't generate any row. TEST_F(TestPropertiesRowStrategy, baseItemInModelContext) { SessionModel model; PropertiesRowStrategy strategy({}); auto items = strategy.constructRow(model.rootItem()); EXPECT_EQ(items.size(), 0); TestUtils::clean_items(items); model.insertItem<SessionItem>(); items = strategy.constructRow(model.rootItem()); EXPECT_EQ(items.size(), 0); TestUtils::clean_items(items); } //! Row construction for rootItem with single item inserted. Shouldn't generate any row. TEST_F(TestPropertiesRowStrategy, propertyItemTree) { SessionModel model; auto parent = model.insertItem<SessionItem>(); parent->registerTag(TagInfo::universalTag("universal_tag")); parent->registerTag(TagInfo::propertyTag("property_tag", Constants::PropertyType)); model.insertItem<SessionItem>(parent, "universal_tag"); model.insertItem<PropertyItem>(parent, "property_tag"); PropertiesRowStrategy strategy({}); auto items = strategy.constructRow(model.rootItem()); // root item doesn't have properties EXPECT_EQ(items.size(), 0); TestUtils::clean_items(items); // parent has one registered property. items = strategy.constructRow(parent); EXPECT_EQ(items.size(), 1); TestUtils::clean_items(items); } //! Row construction for rootItem when vectorItem is present. Shouldn't generate any row. TEST_F(TestPropertiesRowStrategy, vectorItemInModelContext) { SessionModel model; model.insertItem<VectorItem>(); PropertiesRowStrategy strategy({}); auto items = strategy.constructRow(model.rootItem()); EXPECT_EQ(items.size(), 0); TestUtils::clean_items(items); }
true
4e2d1add58cad2da2d3d92a4b710bd415a4dff8d
C++
Vladimir-ai/Generic-B-Tree
/B-Tree/MyBTree.h
UTF-8
3,411
3.078125
3
[]
no_license
#pragma once #include <vector> #include <string> #include <stdexcept> #include <functional> #include <ostream> #include <algorithm> template<typename T> class MyBTree { private: template <typename T = T> struct BTreeNode { BTreeNode<T>* _parent; std::vector<T> _keys; std::vector<BTreeNode<T>*> _children; BTreeNode<T>(unsigned int order, BTreeNode<T>* parent = nullptr) { if (order < 3) throw std::invalid_argument("Order must be greater or equal than 2"); _parent = parent; _keys.reserve(order); _children.reserve(order); }; BTreeNode<T>* find(T key) { //assume that lists are if correct order; if (std::find(_keys.begin(), _keys.end(), key) != _keys.end()) return this; int idx = findMinIndGreaterThanKey(key); if (_children.size() && idx <= _keys.size()) return _children[idx]->find(key); return nullptr; }; int findMinIndGreaterThanKey(T key) { auto res = upper_bound(_keys.begin(), _keys.end(), key, MyBTree<T>::_comparisonFunc); int ret = res - _keys.begin(); //for debug return ret; }; int findChild(BTreeNode<T>* child) { int res = std::find(_children.begin(), _children.end(), child) - _children.begin(); if (res == _children.size()) return -1; return res; }; void clearChildList() { _children.clear(); }; T getSuccesor() { if (_children.size()) return _children[0]->getSuccesor(); return _keys[0]; }; T getPredecessor() { if (_children.size()) return _children.back(); return _keys.back(); }; void insert(T value) { auto index = findMinIndGreaterThanKey(value); _keys.insert(index + _keys.begin(), value); }; ~BTreeNode() { for (auto chld : _children) { delete chld; } _children.clear(); _keys.clear(); }; }; const static inline std::function<bool(const T&, const T&)> _comparisonFunc = [](const T& left, const T& right) {return left < right; }; unsigned int _order; unsigned int _min; unsigned int _size; BTreeNode<T> *_rootNode; void splitChild(BTreeNode<T>* childToSplit, BTreeNode<T>* parent = nullptr); bool removeFromInner(BTreeNode<T>* node, T keyToRemove); bool removeFromLeaf(BTreeNode<T>* node, T keyToRemove); void fixChildSize(BTreeNode<T>* childToFix, BTreeNode<T>* parent = nullptr); bool mergeChilden(BTreeNode<T>* parent, unsigned int leftChildIdx); void mergeLeaf(BTreeNode<T>* parent, unsigned int leftChildIdx); bool isCorrectKeysAmount(BTreeNode<T>* nodeToCheck); bool removeFromPredecessorNode(BTreeNode<T>* nodeToInsert, unsigned int pos, BTreeNode<T>* const node); bool removeFromSuccesorNode(BTreeNode<T>* nodeToInsert, unsigned int pos, BTreeNode<T>* const node); bool leftRotate(BTreeNode<T>* parent, BTreeNode<T>* leftNode, BTreeNode<T>* rightNode); bool rightRotate(BTreeNode<T>* parent, BTreeNode<T>* leftNode, BTreeNode<T>* rightNode); void printTree(std::ostream& strm, BTreeNode<T>* node, int nChild = 0, std::string prevString = ""); std::string printNode(std::ostream& strm, BTreeNode<T>* node, int nChild, std::string prevString); friend std::ostream& operator<<(std::ostream& strm, MyBTree<T>& tree) { tree.printTree(strm, tree._rootNode); return strm; } public: MyBTree(unsigned int order); ~MyBTree(); void add(std::vector<T> elements); void add(T elem); bool remove(T elem); bool find(T elem); int size(); };
true
5e0fd6d853204e76e68706feabd6fb734b656eb9
C++
ayushsengupta1991/algorithmic-programming-practice
/CodeChef/May_14/anudtc.cpp
UTF-8
516
2.59375
3
[]
no_license
#include<iostream> #include<cstdio> using namespace std; int main() { long t; scanf("%ld",&t); while(t--) { long long int n; scanf("%lld",&n); // 1 if(n>360) printf("n "); else if(360%n!=0) printf("n "); else printf("y "); //2 if(n>360) printf("n "); else printf("y "); //3 if(n>=360) printf("n "); else { long long int x=(n*(n-1))/2; if(x>360) printf("n "); else if(360-x<=n-1) printf("n "); else printf("y "); } printf("\n"); } return 0; }
true
a84ec416c527da827a79d0e32c8347c0b28c6467
C++
ashwinaj/Programs
/ClosestPowerOf2.cc
UTF-8
684
3.140625
3
[]
no_license
#include<cstdio> #include<iostream> using namespace std; int main() { int number = 64; int closestNumber = 0; int dummy = 1; while(number > 0) { if(dummy >= number) { // Check if closentNumber is closer to the number than dummy if((dummy-number)<(number-closestNumber)) printf("closest number is: %u", dummy); else printf("closest number is: %u", closestNumber); break; } else { closestNumber = dummy; dummy = dummy << 1; } } return 0; }
true
9db4eb98303622b1e5fa61a71bcadce2d289168c
C++
yikliu/ArithmeticExpressionParser
/ArithmeticExpressionParser/postfix/Calculator.cpp
UTF-8
1,525
2.921875
3
[]
no_license
#ifndef CALCULATOR_CPP_ #define CALCULATOR_CPP_ #include "Calculator.h" /// Default constructor template<typename T> Calculator<T>::Calculator(void) :p_postfix_array_(0), p_iter_(0), p_parser_(0), p_evaluator_(0), p_factory_(0) { p_postfix_array_ = new Array<Expr_Command<T> *>(); p_iter_ = new Array_Iterator<Expr_Command<T> *>(*p_postfix_array_); p_parser_ = new Infix_Postfix_Parser<T>(); p_evaluator_ = new Postfix_Evaluator<T>(); p_factory_ = new Stack_Expr_Command_Factory<T>(); } /// Destructor template<typename T> Calculator<T>::~Calculator(void) { if(p_postfix_array_ != 0) delete p_postfix_array_; if(p_iter_ != 0) delete p_iter_; if(p_parser_ != 0) delete p_parser_; if(p_evaluator_ != 0) delete p_evaluator_; if(p_factory_ != 0) delete p_factory_; } /// do_calculation template<typename T> bool Calculator<T>::do_calculation(std::istream & source, T & result) { std::string infix; getline(source, infix); // infix-to-postfix conversion if(!p_parser_->inflix_to_postfix(infix, *p_factory_, *p_postfix_array_)) { return false; } // evaluate the postfix to get the result if(!p_evaluator_->postfix_evalute(*p_iter_, result)) { return false; } return true; } /// get_postfix template<typename T> std::string & Calculator<T>::get_postfix() const { return p_parser_->get_postfix(); } /// reset template<typename T> void Calculator<T>::reset() { p_postfix_array_->clear(); p_iter_->clear(); p_parser_->clear_postfix_string(); } #endif // calculator_h__
true
5279b159b85ffcc4832685ec73bfa404619eb3d6
C++
jingwang9302/Cpp
/Practice Setter and Getter/src/Practice Setter and Getter.cpp
UTF-8
547
2.984375
3
[]
no_license
//============================================================================ // Name : Practice.cpp // Author : Zoe // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include "Cat.h" using namespace std; int main() { Cat cat1; cout<< "name before setter: "<< cat1.getName()<< endl; cat1.setName("Nancy"); cout<< "name after setter: "<< cat1.getName()<< endl; return 0; }
true
b34f3d5dda8664e69afcad2dd01d8645ff01a313
C++
b6t/focus
/components/Clock.cpp
UTF-8
2,452
3.5
4
[]
no_license
#include <string> #include <ncurses.h> #include "Clock.h" using std::string; // Constructor Clock // A constructor that instantiates a clock object then passes the input on // to the inherited component class Clock::Clock( string title, int height, int width, int verticalPos, int horizontalPos, bool outline): Component(title, height, width, verticalPos, horizontalPos, outline) {}; // Function draw // A virtual function from the Components class that is used to draw the // window and its contents to the users terminal void Clock::draw() { WINDOW *compWin = getWin(); update(); string font = "rounded"; const int start = 2; int position = start; for (int i = 0; i <= 7; i++) { if (i == 2 || i == 5) { mvwprintw(compWin, 1, position , " "); mvwprintw(compWin, 2, position , " [] "); mvwprintw(compWin, 3, position , " "); mvwprintw(compWin, 4, position , " [] "); mvwprintw(compWin, 5, position , " "); position = position + 5; } else { int digit = i + 1; if (i > 2 && i < 5) { digit-=1; } else if (i >= 5) { digit-=2; } int value = getPositionValue(digit); for (int i = 0; i < 5; i++) { mvwprintw(compWin, (i + 1), position , format(font, value, i, "") .c_str()); } position = position + 7; } } wrefresh(compWin); } // Function getPostionValue // A function that retrieves the value of the digit of a digital clock. // For example, if the time is 1650 an input of 1 returns 1, 2 returns 6, // 3 returns 5 and so on int Clock::getPositionValue(int position) { if (position == 1) { return positionOne; } else if (position == 2) { return positionTwo; } else if (position == 3) { return positionThree; } else if (position == 4) { return positionFour; } else if (position == 5) { return positionFive; } else if (position == 6) { return positionSix; } else { return 0; } } // Function update // A function that uses the updateTime function inherited from the // Time class to update the stored time data members. Then parses // the time into its position void Clock::update() { updateTime(); positionOne = getHours()/ 10 %10; positionTwo = getHours() %10; positionThree = getMinutes()/ 10 %10; positionFour = getMinutes() %10; positionFive = getSeconds() / 10 %10; positionSix = getSeconds() %10; }
true
52b02b64aa7699ed3191e78a1720c267cf85afc6
C++
IvanAli/ACMICPC2017Training
/LATAM11/m/m.cpp
UTF-8
987
2.6875
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int m; int n; int mask; int dp[(1<<15)]; void trans(int bitmask) { for(int i = m; i >= 1; --i) if(bitmask&(1<<i)) cout<<'1'; else cout<<'0'; cout<<endl; } int dfs(int bitmask) { int &ans = dp[bitmask]; if(ans != -1) return ans; if(bitmask&(1<<m)) { //cout<<"looser: "<<bitmask<<endl; return 0; } bool fl = true; for(int i = 1; i <= m; ++i) { if(bitmask&(1<<i)) { for(int j = i+1; j <= m; ++j) { if((bitmask&(1<<j))==0) { int temp = bitmask; temp |= (1<<j); temp ^= (1<<i); int r = dfs(temp); if(r == 0) fl = false; } } } } if(!fl) { cout<<"winner: "; trans(bitmask); return ans = 1; } //cout<<"looser: "<<bitmask<<endl; return ans = 0; } int main() { cin>>m>>n; int num; mask = 0; memset(dp,-1,sizeof dp); for(int i = 0; i < n; ++i) { cin>>num; mask |= (1<<num); } dfs(mask); }
true
7546a2b6a7792830a287a5c05260936cde01dcbd
C++
mrDIMAS/32k-shooter
/particlesystem.h
UTF-8
804
2.59375
3
[]
no_license
#pragma once #include "scenenode.h" class Particle { public: Math::Vector3 mPosition; Math::Vector3 mSpeed; int mLifeTime; Math::Color mColor; float mSize; Particle(); }; class ParticleSystem : public SceneNode { public: Particle * mParticles; int mParticleCount; int mAliveParticles; Math::Vector3 mEmitDirectionMax; Math::Vector3 mEmitDirectionMin; float mRadius; float mParticleSize; bool mAutoResurrection; bool mLifeTimeAlpha; int mParticleLifeTime; Math::Color mColor; explicit ParticleSystem( int particleCount, float radius ); virtual ~ParticleSystem(); void Render(); void Update(); void Resurrect( Particle & p ); void ResurrectParticles(); static ParticleSystem * CreateFire( float length ); static ParticleSystem * CreateTrail( float radius, float length ); };
true
35438a23f1faf60a41f7867a3ce00a2280d517de
C++
joshsarath/Fall-13-CSC-281-Project-8
/project 8/project 8/Automobile.cpp
UTF-8
1,282
3.09375
3
[]
no_license
// // Automobile.cpp // project 8 // // Created by Josh Sarath on 11/4/13. // Copyright (c) 2013 Josh Sarath. All rights reserved. // #include "Automobile.h" using namespace std; Automobile::Automobile(string m, string b, string c, int cy, long mile, long dist, long cost, long price) {/* constructor for class automobile this takes inputs of all info about the automobile and sets the initialized private data members */ make = m; bodyStyle = b; color= c; cylinders = cy; cityMileage = mile; distanceMileage = dist; dealerCost = cost; manufacturersPrice = price; } string Automobile::getMake() { //returns the make return make; } string Automobile::getBodyStyle() { //returns the body style return bodyStyle; } string Automobile::getColor() { //returns color return color; } int Automobile::getCylinders() { //returns number fo cylinders return cylinders; } long Automobile::getCityMileage() { //returns city mpg return cityMileage; } long Automobile::getDistanceMileage() { //returns highway mpg return distanceMileage; } long Automobile::getDealerCost() { //returns cost to dealer return dealerCost; } long Automobile::getManufacturersPrice() { //returns price to customer return manufacturersPrice; }
true
aa41fe967eadcaa65f2e971a70d8d87ffdf2150d
C++
StraToN/stratego
/ListPiece.h
UTF-8
546
2.84375
3
[]
no_license
# ifndef H_LISTPIECE # define H_LISTPIECE # include "Piece.h" # include <list> class ListPiece{ private: // attributs list<Piece*>* pieces; public: // constructeurs et destructeur ListPiece(); ListPiece(int size); ~ListPiece(); // methodes int size(); void add(Piece* p); Piece* remove(); void fill(int qte,int type,bool col); Piece* get(int index); void clear(); // exception class BadIndexException{}; }; # endif
true
85430fc9384067b58613e14a15c2ad032aa2e574
C++
harimohanraj89/SoniScan
/ControlBlock.cpp
UTF-8
16,585
2.96875
3
[]
no_license
// // ControlBlock.cpp // SoniScan_2_0 // // Created by Hariharan Mohanraj on 11/30/12. // Copyright (c) 2012 Hariharan Mohanraj. All rights reserved. // #include "ControlBlock.h" #include "Constants.h" #include <iostream> #include <fstream> #include <vector> #include <string> #include <math.h> // =========================== // UTILITY FUNCTIONS // =========================== int ControlBlock::ArrayMax(int* argArray, int argLength) { if (argLength < 1) { std::cout << "Empty array argument to ArrayMax(). 0 returned by default.\n"; return 0; } int max = argArray[0]; for (int i=1; i<argLength; i++) { if (argArray[i] > max) { max = argArray[i]; } } return max; } int ControlBlock::ArrayMin(int* argArray, int argLength) { if (argLength < 1) { std::cout << "Empty array argument to ArrayMin(). 0 returned by default.\n"; return 0; } int min = argArray[0]; for (int i=1; i<argLength; i++) { if (argArray[i] < min) { min = argArray[i]; } } return min; } void ControlBlock::ClearMasterData() { for (int x=0; x<masterDataSize[0]; x++) { for (int y=0; y<masterDataSize[1]; y++) { delete [] masterData[x][y]; } delete [] masterData[x]; } if (masterData != 0) { delete [] masterData; } } void ControlBlock::InitMasterData(int argX, int argY, int argZ) { ClearMasterData(); masterData = new float**[argX]; for (int x=0; x<argX; x++) { masterData[x] = new float*[argY]; for (int y=0; y<argY; y++) { masterData[x][y] = new float[argZ]; for (int z=0; z<argZ; z++) { masterData[x][y][z] = -1; } } } masterDataSize[0] = argX; masterDataSize[1] = argY; masterDataSize[2] = argZ; } // =========================== // PARAMETER FUNCTIONS // =========================== // SetSelectionArea() - Overloaded function to define selectionArea // One name-value pair void ControlBlock::SetSelectionArea(std::string parameterName1, int parameterValue1) { // Match parameterName1 and assign parameterValue1 accordingly if(parameterName1.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName1.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName1.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName1.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } } void ControlBlock::SetSelectionArea(std::string parameterName1, int parameterValue1, std::string parameterName2, int parameterValue2) { // Check for duplicate parameter names if(parameterName1 == parameterName2) { std::cout << "Duplicate parameter names. SetSelectionArea call ignored."; return; } // Match parameterName1 and assign parameterValue1 accordingly if(parameterName1.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName1.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName1.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName1.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } // Match parameterName1 and assign parameterValue1 accordingly if(parameterName2.compare("x1") == 0) { selectionVolume.x1 = parameterValue2; } if(parameterName2.compare("x2") == 0) { selectionVolume.x2 = parameterValue2; } if(parameterName2.compare("y1") == 0) { selectionVolume.y1 = parameterValue2; } if(parameterName2.compare("y2") == 0) { selectionVolume.y2 = parameterValue2; } } void ControlBlock::SetSelectionArea(std::string parameterName1, int parameterValue1, std::string parameterName2, int parameterValue2, std::string parameterName3, int parameterValue3) { // Check for duplicate parameter names if(parameterName1 == parameterName2 || parameterName1 == parameterName3 || parameterName2 == parameterName3) { std::cout << "Duplicate parameter names. SetSelectionArea call ignored."; return; } // Match parameterName1 and assign parameterValue1 accordingly if(parameterName1.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName1.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName1.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName1.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } // Match parameterName2 and assign parameterValue2 accordingly if(parameterName2.compare("x1") == 0) { selectionVolume.x1 = parameterValue2; } if(parameterName2.compare("x2") == 0) { selectionVolume.x2 = parameterValue2; } if(parameterName2.compare("y1") == 0) { selectionVolume.y1 = parameterValue2; } if(parameterName2.compare("y2") == 0) { selectionVolume.y2 = parameterValue2; } // Match parameterName3 and assign parameterValue3 accordingly if(parameterName3.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName3.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName3.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName3.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } } void ControlBlock::SetSelectionArea(std::string parameterName1, int parameterValue1, std::string parameterName2, int parameterValue2, std::string parameterName3, int parameterValue3, std::string parameterName4, int parameterValue4) { // Check for duplicate parameter names if(parameterName1 == parameterName2 || parameterName1 == parameterName3 || parameterName1 == parameterName4 || parameterName2 == parameterName3 || parameterName2 == parameterName4 || parameterName3 == parameterName4) { std::cout << "Duplicate parameter names. SetSelectionArea call ignored."; return; } // Match parameterName1 and assign parameterValue1 accordingly if(parameterName1.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName1.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName1.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName1.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } // Match parameterName2 and assign parameterValue2 accordingly if(parameterName2.compare("x1") == 0) { selectionVolume.x1 = parameterValue2; } if(parameterName2.compare("x2") == 0) { selectionVolume.x2 = parameterValue2; } if(parameterName2.compare("y1") == 0) { selectionVolume.y1 = parameterValue2; } if(parameterName2.compare("y2") == 0) { selectionVolume.y2 = parameterValue2; } // Match parameterName3 and assign parameterValue3 accordingly if(parameterName3.compare("x1") == 0) { selectionVolume.x1 = parameterValue1; } if(parameterName3.compare("x2") == 0) { selectionVolume.x2 = parameterValue1; } if(parameterName3.compare("y1") == 0) { selectionVolume.y1 = parameterValue1; } if(parameterName3.compare("y2") == 0) { selectionVolume.y2 = parameterValue1; } // Match parameterName4 and assign parameterValue4 accordingly if(parameterName4.compare("x1") == 0) { selectionVolume.x1 = parameterValue4; } if(parameterName4.compare("x2") == 0) { selectionVolume.x2 = parameterValue4; } if(parameterName4.compare("y1") == 0) { selectionVolume.y1 = parameterValue4; } if(parameterName4.compare("y2") == 0) { selectionVolume.y2 = parameterValue4; } } void ControlBlock::SetSelectionVolume(int argX1, int argX2, int argY1, int argY2, int argZ1, int argZ2) { int temp; int localArgX1 = argX1; int localArgX2 = argX2; int localArgY1 = argY1; int localArgY2 = argY2; int localArgZ1 = argZ1; int localArgZ2 = argZ2; // Ensure that arg 1 is less than arg 2 if (localArgX1 > localArgX2) { temp = localArgX1; localArgX1 = localArgX2; localArgX2 = temp; } if (localArgY1 > localArgY2) { temp = localArgY1; localArgY1 = localArgY2; localArgY2 = temp; } if (localArgZ1 > localArgZ2) { temp = localArgZ1; localArgZ1 = localArgZ2; localArgZ2 = temp; } // Clip all arg values to between 0 and masterDataSize[i]-1 if (localArgX1 < 0) localArgX1 = 0; if (localArgX1 > masterDataSize[0]-1) localArgX1 = masterDataSize[0]-1; if (localArgX2 < 0) localArgX2 = 0; if (localArgX2 > masterDataSize[0]-1) localArgX2 = masterDataSize[0]-1; if (localArgY1 < 0) localArgY1 = 0; if (localArgY1 > masterDataSize[0]-1) localArgY1 = masterDataSize[0]-1; if (localArgY2 < 0) localArgY2 = 0; if (localArgY2 > masterDataSize[0]-1) localArgY2 = masterDataSize[0]-1; if (localArgZ1 < 0) localArgZ1 = 0; if (localArgZ1 > masterDataSize[0]-1) localArgZ1 = masterDataSize[0]-1; if (localArgZ2 < 0) localArgZ2 = 0; if (localArgZ2 > masterDataSize[0]-1) localArgZ2 = masterDataSize[0]-1; // Assign all args to selectionVolume selectionVolume.x1 = localArgX1; selectionVolume.x2 = localArgX2; selectionVolume.y1 = localArgY1; selectionVolume.y2 = localArgY2; selectionVolume.z1 = localArgZ1; selectionVolume.z2 = localArgZ2; } void ControlBlock::SetRangeMin(float value) { rangeMin = value; } void ControlBlock::SetRangeMax(float value) { rangeMax = value; } void ControlBlock::SetShift(float value) { shift = value; } void ControlBlock::SetVolume(float value) { if(volume < 0) std::cout << "Negative volume parameter. SetVolume call ignored"; else volume = value; } // ================================= // SONIFICATION ENGINE CONNECTORS // ================================= void ControlBlock::SetEngine(SonificationEngine* argEngine) { if (argEngine == 0) { std::cout << "Null argument received in SetEngine(). Setting engine to null.\n"; } engine = argEngine; } SonificationEngine* ControlBlock::GetEngine() { return engine; } // =========================== // DATA INPUT/OUTPUT FUNCTIONS // =========================== // Function to read file into masterData // ------------------------------------- void ControlBlock::ReadFile(char* argFilename) { char dataLine[MAX_SCORELINE_LENGTH]; sprintf(dataLine,TEST_DATA_PATH "%s.txt", argFilename); std::string str; int curr; int nums[4] = {0,0,0,0}; int exp = 0; int pos; int index = 4; int lineCount = 0; int currLine; std::cout << "Reading file...\n"; std::ifstream inputFile; // Calculate line count // -------------------- inputFile.open(dataLine); if(!inputFile.good()) { std::cout << "Error opening file!\n"; return; } while (getline(inputFile, str)) { lineCount++; } // Check for empty file // -------------------- if (lineCount < 1) { std::cout << "Empty file! FileRead() call ignored.\n"; return; } inputFile.close(); // Initialize arrays to hold data // ------------------------------ int* X = new int[lineCount]; int* Y = new int[lineCount]; int* Z = new int[lineCount]; int* vals = new int[lineCount]; inputFile.open(dataLine); if(!inputFile.good()) { std::cout << "Error opening file!"; return; } // Populate arrays with data from file // ----------------------------------- currLine = 0; while(getline(inputFile, str)) { pos = str.size() - 1; index = 3; exp = 0; nums[0] = 0; nums[1] = 0; nums[2] = 0; nums[3] = 0; while (index >= 0 && pos >= 0) { curr = int(str[pos]); if ( curr >= 48 && curr <= 57) // If curr is a number character { nums[index] += (curr-48) * pow(10,exp); exp++; } if (curr == 44) { index--; exp = 0; } pos--; } X[currLine] = nums[0]; Y[currLine] = nums[1]; Z[currLine] = nums[2]; vals[currLine] = nums[3]; currLine++; } int xMin; int xMax; int yMin; int yMax; int zMin; int zMax; xMin = ArrayMin(X,lineCount); xMax = ArrayMax(X,lineCount); yMin = ArrayMin(Y,lineCount); yMax = ArrayMax(Y,lineCount); zMin = ArrayMin(Z,lineCount); zMax = ArrayMax(Z,lineCount); InitMasterData(xMax-xMin+1, yMax-yMin+1, zMax-zMin+1); for (int i=0; i<lineCount; i++) { masterData[X[i]-1][Y[i]-1][Z[i]-1] = vals[i]; } TrimMasterData(); engine->SetMasterData(masterData,masterDataSize); delete [] X; delete [] Y; delete [] Z; delete [] vals; std::strcpy(dataFilename, argFilename); engine->SetDataFilename(dataFilename); } // Function to trim away all external data // --------------------------------------- void ControlBlock::TrimMasterData() { int absThreshold = TRIM_THRESHOLD * pow(2,DATA_BITDEPTH); int x; bool trimFlag; // Check whether data exists if (masterData == 0) { std::cout << "Dataset does not exist. TrimData() call ignored.\n"; return; } // Iterate through each slice of data for (int z=0; z<masterDataSize[2]; z++) { // Iterate through each row of slice for (int y=0; y<masterDataSize[1]; y++) { // Trim data from left trimFlag = true; x=0; while(trimFlag) { if (x >= masterDataSize[0]) { trimFlag = false; } else if (masterData[x][y][z] > absThreshold) { trimFlag = false; } else { masterData[x][y][z] = -1; } x++; } // Trim data from right trimFlag = true; x = masterDataSize[0] - 1; while(trimFlag) { if (x < 0) { trimFlag = false; } else if (masterData[x][y][z] > absThreshold) { trimFlag = false; } else { masterData[x][y][z] = -1; } x--; } } } } // Function to output current masterData // ------------------------------------- void ControlBlock::OutputData() { std::cout << "Current master data:\n"; for (int z=0; z<masterDataSize[2]; z++) { std::cout << "z = " << z+1 << "\n"; for (int y=0; y<masterDataSize[1]; y++) { for (int x=0; x<masterDataSize[0]; x++) { std::cout << masterData[x][y][z] << "\t"; } std::cout << "\n"; } std::cout << "\n"; } } // =========== // Const/Destr // =========== ControlBlock::ControlBlock() { masterDataSize[0] = 0; masterDataSize[1] = 0; masterDataSize[2] = 0; masterData = 0; } ControlBlock::~ControlBlock() { ClearMasterData(); }
true
e6ec856351f5da51bda37e018b1a201c58be4d86
C++
VSarabudla/spaceships-and-aliens
/src/core/character.cc
UTF-8
1,369
3.0625
3
[]
no_license
#include "core/character.h" shooter::Character::Character(const glm::vec2& position, float radius, float movement_speed, int health_points) : position_(position), radius_(radius), movement_speed_(movement_speed), health_points_(health_points) { } void shooter::Character::MoveUp() { position_ += glm::vec2(0, -movement_speed_); } void shooter::Character::MoveDown() { position_ += glm::vec2(0, movement_speed_); } void shooter::Character::MoveLeft() { position_ += glm::vec2(-movement_speed_, 0); } void shooter::Character::MoveRight() { position_ += glm::vec2(movement_speed_, 0); } void shooter::Character::HandleCollisions(std::vector<Bullet>* bullets, const ci::Color& bullet_color) { size_t i = 0; // check for bullets that have hit player for (Bullet& bullet : *bullets) { if (glm::distance(position_, bullet.GetPosition()) <= radius_ + bullet.GetRadius() && bullet.GetColor() == bullet_color) { bullets->erase(bullets->begin() + i); DecrementHealth(); continue; } i++; } } int shooter::Character::GetHealthPoints() const { return health_points_; } void shooter::Character::DecrementHealth() { health_points_--; } glm::vec2 shooter::Character::GetPosition() const& { return position_; }
true
faf075495a36fcaac68a77452995978059d0d1ff
C++
benel2606/ChainOfStoresManagement
/Senior_Salesman.cpp
UTF-8
1,775
3.078125
3
[]
no_license
/* Assignment: 4 Campus: Ashdod Author: Benel Aharon ID: 307908111 */ #define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include "Workers.h" #include "Senior_Salesman.h" using namespace std; void Senior_Salesman::print() const { cout << "<Senior_Salesman>" << endl; cout << "Name: " << name << endl; cout << "ID: " << id << endl; cout << "Job_percent: " << job_percent * 100 << endl; cout << "Basic salary: " << basic_salary << endl; cout << "Sales: " << endl; if (!sale_sum) cout << "There are no sales!"<<endl; else { for (int i = 0; i < sales_num; i++) cout << sale_sum[i] << endl; } cout << "Cancelation: " << endl; if (!cancelation) cout << "There are no cancelation!" << endl; else { for (int i = 0; i < cancel_num; i++) cout << cancelation[i] << endl; } } void Senior_Salesman::cancel(float cancel) { int count_cancel = 0; float* temp; if (!cancelation) // If the array is empty { cancelation = new float[1]; cancelation[0] = cancel; cancel_num++; } else { for (int i = 0; cancelation[i] != NULL; i++) // Count the cancel number in array count_cancel++; temp = new float[count_cancel]; for (int i = 0; i < count_cancel; i++) // Copy the array to temp array temp[i] = cancelation[i]; delete[]cancelation; // Delete array cancelation = new float[count_cancel + 1]; // Set array with new size cancelation[0] = cancel; // Add the new cancel to array for (int i = 1; i < count_cancel; i++) // Return the previous cancel cancelation[i] = temp[i - 1]; delete[]temp; //Delete temp array cancel_num++; } }
true
bbe7d8465c22d959ded4e1c4240856232e3641be
C++
chanfool21/Competitive-Coding
/summer_love/Practice Codes/Check/stack_lol.cpp
UTF-8
969
3.59375
4
[]
no_license
#include<iostream> using namespace std; int top = 0; #define MAX 10 void push(int i, int a[]) { if(top == MAX - 1) { cout<<"Stack Overflow"; } a[top++] = i; } int pop(int a[]) { if(top == -1) { cout<<"Stack is empty"; } int b = a[top--]; return b; } int peek(int a[]) { if(top == -1) { cout<<"Stack is empty"; } int b = a[top]; return b; } void traverse(int a[]) { cout<<"Elements in the stack are \n"; for(int i = 0; i < top; i++) { cout<<a[i]<<endl; } } int main() { int ab[10]; int n; int i; int a; while(1) { cout<<"Enter the choice \n"; cout<<"1- for push . 2- for pop . 3- peek . 4- traverse \n"; cin>>n; switch(n) { case 1 : cout<<"Enter the value to be pushed in the stack \n"; cin>>i; push(i,ab); break; case 2 : a = pop(ab); cout<<"Popped out value is "<<a; break; case 3: a = peek(ab); cout<<"Top most element is"<<a; break; case 4: traverse(ab); break; default : break; } } return 0; }
true
bd0a290a0b382a45283fd8b18c363d19810d9c41
C++
liuyihao18/QtBigHomework
/role.cpp
UTF-8
1,819
2.765625
3
[]
no_license
#include "role.h" Role::Role(QObject *parent) : BaseObject(parent), _HP(3) {} Role::Role(int x, int y, int width, int height, const QString& imgPath, int speed, int HP, int direction, QObject *parent) : BaseObject(x, y, width, height, imgPath, parent), MoveThing(x, y, width, height, direction, speed), _HP(HP), _originHP(HP), _invincible(false), _invincibleTimer(this) { _invincibleTimer.setInterval(1000); connect(&_invincibleTimer, SIGNAL(timeout()), this, SLOT(invincibleOver())); } void Role::initialize() { MoveThing::initialize(); returnOriginPos(); _HP = _originHP; } void Role::returnOriginPos() { MoveThing::returnOriginPos(); moveRect(_originX, _originY); } void Role::confirmPos() { MoveThing::confirmPos(); _rect = _tempPos; } void Role::cancelPos() { MoveThing::cancelPos(); _tempPos = _rect; } int Role::getHP() const { return _HP; } void Role::addHP(int x) { _HP += x; } void Role::reduceHP(int x) { if (!_invincible) { _HP -= x; if (_HP <= 0) { hide(); } _invincible = true; _invincibleTimer.start(); } } void Role::invincibleOver() { _invincible = false; _invincibleTimer.stop(); }
true
4c64636bb674f317d63d720feffd8d3d1dc692c5
C++
shrekwu/OpenS3D
/src/core/s3d/test/utilities/tests_stats.cpp
UTF-8
768
3.28125
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#include "gtest/gtest.h" #include "s3d/utilities/stats.h" #include <numeric> TEST(percentile, first_last_elements) { std::vector<float> v; v.resize(100); std::iota(std::begin(v), std::end(v), 0.0f); EXPECT_EQ(s3d::percentile(v, 0.00), 0.0f); EXPECT_EQ(s3d::percentile(v, 1.00), 99.0f); } TEST(percentile, median_tests) { // median std::vector<float> f = {15.0f, 20.0f, 35.0f, 40.0f, 50.0f}; EXPECT_FLOAT_EQ(s3d::percentile(f, 0.5), 35.0f); // median shuffled f = {7, 10, 1, 2, 3, 4}; EXPECT_FLOAT_EQ(s3d::percentile(f, 0.5), 3.5f); } TEST(percentile, other_tests) { std::vector<float> f = {15, 20, 35, 40, 50}; EXPECT_FLOAT_EQ(s3d::percentile(f, 0.40), 29.0f); f = {1, 2, 3, 4}; EXPECT_FLOAT_EQ(s3d::percentile(f, 0.75), 3.25f); }
true
3a3e5e22dfc4a4cd428cf28890a6df404c7363e4
C++
YoungJooYoo/For_Coding_Test
/LeetCode/find-the-difference/find-the-difference.cpp
UTF-8
325
2.890625
3
[]
no_license
class Solution { public: char findTheDifference(string s, string t) { sort(s.begin(),s.end()); sort(t.begin(),t.end()); for(size_t i = 0; i < t.length(); i++) { if(s[i] != t[i]) { return t[i]; } } return 'success'; } };
true
b9b7f4c3388fd4db9277309c277930f16021779d
C++
pratiksaha/practice
/algorithms/encodingFibonacciZeckendorf.cpp
UTF-8
1,106
3.390625
3
[]
no_license
//fibonacci encoding using Zeckendorf's theorem #include <bits/stdc++.h> using namespace std; #define N 30 int fib[N]; int zeckendorf(int n) { fib[0] = 1; fib[1] = 2; int i; for (i=2; fib[i-1]<=n; i++) fib[i] = fib[i-1] + fib[i-2]; return (i-2); } void reprFibonacci(int n) { while (n>0) { int f = fib[zeckendorf(n)]; cout<<f<<" "; n = n-f; } } char* encodeFibonacci(int n) { int index = zeckendorf(n); char *codeword = (char*)malloc(sizeof(char)*(index+3)); int i = index; while (n) { codeword[i] = '1'; n = n - fib[i]; i = i - 1; while (i>=0 && fib[i]>n) { codeword[i] = '0'; i = i - 1; } } codeword[index+1] = '1'; codeword[index+2] = '\0'; return codeword; } int main() { int n; n = 30; cout<<"Non-neighbouring Fibonacci Representation of "<<n<<" is :"; reprFibonacci(n); cout<<endl; n = 143; char *repr = encodeFibonacci(n); cout<<"Fibonacci code for "<<n<<" is "<<repr<<endl; free(repr); return 0; }
true
5f1dec39a5dfbe078ca8aa615cf0c6aef72742e8
C++
abdulilah1424/SocialMediaSimulate
/Client/src/connectionHandler.cpp
UTF-8
8,945
2.703125
3
[]
no_license
#include <connectionHandler.h> #include <algorithm> #include <string> using boost::asio::ip::tcp; using std::cin; using std::cout; using std::cerr; using std::endl; using std::string; ConnectionHandler::ConnectionHandler(string host, short port): host_(host), port_(port), io_service_(), socket_(io_service_){} ConnectionHandler::~ConnectionHandler() { close(); } bool ConnectionHandler::connect() { std::cout << "Starting connect to " << host_ << ":" << port_ << std::endl; try { tcp::endpoint endpoint(boost::asio::ip::address::from_string(host_), port_); // the server endpoint boost::system::error_code error; socket_.connect(endpoint, error); if (error) throw boost::system::system_error(error); } catch (std::exception& e) { std::cerr << "Connection failed (Error: " << e.what() << ')' << std::endl; return false; } return true; } bool ConnectionHandler::getBytes(char bytes[], unsigned int bytesToRead) { size_t tmp = 0; boost::system::error_code error; try { while (!error && bytesToRead > tmp ) { tmp += socket_.read_some(boost::asio::buffer(bytes+tmp, bytesToRead-tmp), error); } if(error) throw boost::system::system_error(error); } catch (std::exception& e) { std::cerr << "recv failed (Error: " << e.what() << ')' << std::endl; return false; } return true; } bool ConnectionHandler::sendBytes(const char bytes[], int bytesToWrite) { int tmp = 0; boost::system::error_code error; try { while (!error && bytesToWrite > tmp ) { tmp += socket_.write_some(boost::asio::buffer(bytes + tmp, bytesToWrite - tmp), error); } if(error) throw boost::system::system_error(error); } catch (std::exception& e) { std::cerr << "recv failed (Error: " << e.what() << ')' << std::endl; return false; } return true; } bool ConnectionHandler::getLine(std::string& line) { return getFrameAscii(line, '\n'); } bool ConnectionHandler::sendLine(std::string& line) { return sendFrameAscii(getOpeMessage(line), '\0'); } bool ConnectionHandler::getFrameAscii(std::string& frame, char delimiter) { char ch; int byteCount = 0; short opeCode = 0; short messgeOpeCode = 0; short numberOfusers = 0; short statShort = 0; short statShort2 = 0; short zeroCount = 0; std::string options = ""; bool runBytes = true; // Stop when we encounter the null character. // Notice that the null character is not appended to the frame string. try { do{ getBytes(&ch, 1); if(byteCount == 0){ opeCode = (short)((ch & 0xff) << 8); } if(byteCount == 1){ opeCode += (short)((ch & 0xff)); } if(opeCode == 10 || opeCode == 11){ if(byteCount == 2){ messgeOpeCode = (short)((ch & 0xff) << 8); } if(byteCount == 3){ messgeOpeCode += (short)((ch & 0xff)); if(messgeOpeCode == 1 || messgeOpeCode == 2 || messgeOpeCode == 3 || messgeOpeCode == 5 || messgeOpeCode == 6 || opeCode == 11 ) runBytes = false; } if((messgeOpeCode == 4 || messgeOpeCode == 8 || messgeOpeCode == 7) && byteCount == 4){ numberOfusers = (short)((ch & 0xff) << 8); } if((messgeOpeCode == 4 || messgeOpeCode == 8 || messgeOpeCode == 7) && byteCount == 5){ numberOfusers += (short)((ch & 0xff)); } if(messgeOpeCode == 8 && byteCount == 6){ statShort = (short)((ch & 0xff) << 8); } if(messgeOpeCode == 8 && byteCount == 7){ statShort += (short)((ch & 0xff)); } if(messgeOpeCode == 8 && byteCount == 8){ statShort2 = (short)((ch & 0xff) << 8); } if(messgeOpeCode == 8 && byteCount == 9){ statShort2 += (short)((ch & 0xff)); runBytes = false; } } if(opeCode == 9){ if(byteCount == 2){ messgeOpeCode += (short)(ch & 0xff); } } if(byteCount >= 4 && !((messgeOpeCode == 4 || messgeOpeCode == 7) && byteCount < 6) && opeCode != 9 && messgeOpeCode != 8) { if((messgeOpeCode == 4 || messgeOpeCode == 7) && ch == '\0') { ch = ' '; zeroCount++; if(zeroCount == numberOfusers) runBytes = false; } options.append(1, ch); } if(byteCount >= 3 && opeCode == 9) { if(ch == '\0') { ch = ' '; zeroCount++; if(zeroCount == 2) runBytes = false; } options.append(1, ch); } byteCount++; }while (runBytes); if(opeCode == 10){ frame = "ACK " + std::to_string(messgeOpeCode) + options; if(messgeOpeCode == 8){ frame = "ACK " + std::to_string(messgeOpeCode) + " " + std::to_string(numberOfusers) + " " + std::to_string(statShort) + " " + std::to_string(statShort2); } if(messgeOpeCode == 7 || messgeOpeCode == 4){ frame = "ACK " + std::to_string(messgeOpeCode) + " " + options; } } if(opeCode == 11){ frame = "ERROR " + std::to_string(messgeOpeCode); } if(opeCode == 9){ std::string notificationType = messgeOpeCode == 1 ? "POST " : "PM "; frame = "NOTIFICATION " + notificationType + options; } } catch (std::exception& e) { std::cerr << "recv failed (Error: " << e.what() << ')' << std::endl; return false; } return true; } bool ConnectionHandler::sendFrameAscii(const std::string& frame, char delimiter) { bool result=sendBytes(frame.c_str(),frame.length()); if(!result) return false; std::string token = frame.substr(1,2); if(token != "\003" && token != "\007"){ return sendBytes(&delimiter,1); } else { return true; } } // Close down the connection properly. void ConnectionHandler::close() { try{ socket_.close(); } catch (...) { std::cout << "closing failed: connection already closed" << std::endl; } } std::string ConnectionHandler::getOpeMessage(const std::string &input){ std::string delimiter = " "; std::string token = input.substr(0, input.find(delimiter)); std::string output; short index = 0; if(token == "REGISTER") { index = 1; output = input.substr(input.find(delimiter)+1,input.length()); std::replace( output.begin(), output.end(), ' ', '\0'); } if(token == "LOGIN"){ index = 2; output = input.substr(input.find(delimiter)+1,input.length()); std::replace( output.begin(), output.end(), ' ', '\0'); } if(token == "LOGOUT"){ index = 3; output = ""; } if(token == "FOLLOW"){ index = 4; output = input.substr(input.find(delimiter)+1,input.length()); bool follow = output.at(0) == '0'; output = output.substr(output.find(delimiter)+1,output.length()); std::string followNumberStr = output.substr(0,output.find(delimiter)); int followTotal = std::stoi(followNumberStr); output = output.substr(output.find(delimiter)+1,output.length()); char followa = (followTotal >> 8) & 0xFF; char followb = followTotal & 0xFF; std::replace( output.begin(), output.end(), ' ', '\0'); output = followb + output; output = followa + output; if(follow) output = '\001' + output; else output = '\0' + output; } if(token == "POST"){ index = 5; output = input.substr(input.find(delimiter)+1,input.length()); } if(token == "PM"){ index = 6; output = input.substr(input.find(delimiter)+1,input.length()); output.at(output.find(delimiter)) = '\0'; } if(token == "USERLIST"){ index = 7; output = ""; } if(token == "STAT"){ index = 8; output = input.substr(input.find(delimiter)+1,input.length()); } // replace all 'x' to 'y' char a = (index >> 8) & 0xFF; char b = index & 0xFF; output = b + output; output = a + output; return output; } void ConnectionHandler::shortToBytes(short num, char* bytesArr) { bytesArr[0] = static_cast<char>((num >> 8) & 0xFF); bytesArr[1] = static_cast<char>(num & 0xFF); }
true
d0efdc1adc6d8d91be5e2139d71737da91c64c28
C++
LamperEin/leetcode_exe
/algo_solver/LRUcache.cpp
UTF-8
1,491
3.171875
3
[]
no_license
#include <iostream> #include <algorithm> #include <unordered_map> #include <list> using namespace std; class LRUCache { private: int _cap; list<pair<int, int>> _cache; unordered_map<int, list<pair<int, int>>::iterator> _map; public: LRUCache(int capacity) { _cap = capacity; } int get(int key) { auto it = _map.find(key); //如果访问的key不存在 if(it == _map.end()) return -1; //key存在, 把(k, v)换到对头 pair<int, int> kv = *_map[key]; _cache.erase(_map[key]); _cache.push_front(kv); // 更新(key, value) 在 cache中的位置 _map[key] = _cache.begin(); return kv.second; } void put(int key, int value) { // 要先判断key是否存在 auto it = _map.find(key); if(it == _map.end()) { // key 不存在,判段 cacke 是否满了 if(_cache.size() == _cap) { auto lastpair = _cache.back(); int lastkey = lastpair.first; _map.erase(lastkey); _cache.pop_back(); } _cache.push_front(make_pair(key, value)); _map[key] = _cache.begin(); } else { // key already exists, update value and pop to the top _cache.erase(_map[key]); _cache.push_front(make_pair(key, value)); _map[key] = _cache.begin(); } } }; int main() { return 0; }
true
f2c41aededb0d04ec0419c21933e8b1a6551eb29
C++
Yumin-Kim/BaiscProgrammingKnowledge
/Unmanaged-C_CPP/ch01/ch08.cpp
UHC
2,265
3.5
4
[]
no_license
#include <stdio.h> /* Ϳ ޸ ǽ Ӽ >> Ŀ >> ּ Ǯ ǽϱ!! 300 16 ǥϰԵǸ 0x00 00 01 2C ޸𸮿 ǥǴ 2C 01 00 00 ̿ Byte Order̸ Littile Endian ̴!! Little Endian ü intel!! cpu intel Ǿ Little Endian ޸𸮿 !! ޸𸮷 Ǿ!! ޸𸮴 ּҸ &ڸ ȰϿ ּҸ Ȯ ִ!! & compile Time ̴!! ѹ compile ķδ Ű澲 ʴ ̴!! (޸𸮸 ߴٴ ǹ̴) !! Ȱ!! ؿ Ѱ ԵǸ npnData ּҰ nData ٸ ְ npnData ޸ nData ּҰ Little Endian ° ִ ѹ !! ͸ ϴ?? Լ 迭 ϴ κп شȭ ȴ!! Լ иǾ ȿ شȭȴ!! 츮 ϴ ޸𸮴 virtual Memorry ϰ ִ!! */ int main() { int nData = 300; int* pnData = &nData; //޸ ּҰ !! int ũ ŭ nData ּҰ 8byte ڿ ִ ޸ ּҰ ̵ϰԵȴ1!! pnData += 2; // ޸ ּҿ 300̶ ڰ 16 Little endian ߰ȴ!! *pnData = 300; //͸ Ȱ ϴ !! *((int*)0x0019FED8) = 100; int aList[4] = { 1,2,3,4 }; int* paList = aList; /* paList[4] = 10; *(paList + 1) = 100; //paList[1] ǹ̴!! */ int bList[5] = { 40,20,50,30,10 }; int nTotal = 0; for (int i = 0; i < 5; i++) nTotal += bList[i]; printf("%d\n", nTotal); nTotal = 0; int* pnData_ = bList; while (pnData_ < bList + 5) { nTotal += *pnData_; pnData_++; } printf("%d",nTotal); return 0; }
true
be3a27e43f3d4a70f82a28df0f17a0959c0dec4e
C++
tmd9760/cpp-bitcoin-block-parser
/main.cpp
UTF-8
2,702
2.796875
3
[]
no_license
#include <iostream> #include <vector> #include "picosha2.h" #include "Helpers.hpp" #include "Input.hpp" #include "Output.hpp" #include "Transaction.hpp" #include "BlockHeader.hpp" #include "Block.hpp" int main(int argc, char ** argv) { if (argc < 2) { std::cout << "Command: " << argv[0] << " FILENAME" << std::endl; return 0; } std::ifstream input(argv[1], std::ios::binary); uint32_t counter = 0; std::vector<Block> blocks; while (!input.eof()) { Block block(input); if (!input.fail()) { /*std::cout << block.getHeader().getHash() << std::endl; std::cout << std::dec << "Size: " << block.getSize() << std::endl; std::cout << "Output Satoshi: " << std::dec << block.getOutputsValue() << " in " << block.getTransactionCounter() << " transactions. " << std::endl; std::cout << "MR: " << std::dec << (int)(*block.getHeader().getMerkleRoot()) << std::endl; std::cout << input.tellg() << std::endl << std::endl;*/ blocks.push_back(block); counter++; } } input.close(); std::cout << std::dec << counter << " blocks" << std::endl; int blockNum = 0; while (true) { std::cout << "Pick one block: "; std::cin >> blockNum; if (blockNum < 0) break; Block block = blocks[blockNum]; std::cout << "BLOCK " << blockNum << std::endl; std::cout << "Hash: " << block.getHeader().getHashStr() << std::endl; std::cout << "Transactions: " << block.getTransactionCount() << std::endl; std::cout << "Pick one transaction: "; int transaction = 0; std::cin >> transaction; Transaction tr = block.getTransactions()[transaction]; std::cout << "TRANSACTION " << transaction << " IN BLOCK " << blockNum << std::endl; std::cout << "Inputs: " << tr.getInputsCount() << "\t" << "Outputs: " << tr.getOutputsCount() << std::endl; std::cout << "\tINPUTS" << std::endl; for (Input input : tr.getInputs()) { std::cout << "\tPrev TX: " << input.getPreviousTransaction().getHexString() << std::endl; std::cout << "\tTxOut Index: " << input.getTxOutIndex(); if (input.getTxOutIndex() == 0xFFFFFFFF) { std::cout << "(COINBASE)"; } std::cout << std::endl; } std::cout << "\tOUTPUTS" << std::endl; } std::cout << "Bye!" << std::endl; return 0; }
true
de4c5ad904e715873cbb5614dc400e6da6672d05
C++
confidentFeng/QtAppProject
/Rocker/widget.cpp
UTF-8
4,728
2.75
3
[]
no_license
#include "widget.h" Widget::Widget(QDialog *parent) : QDialog(parent) { Init(); //初始化函数 } Widget::~Widget() { } //初始化函数 void Widget::Init() { //设置窗口无边框且窗口显示在最顶层 //this->setWindowFlags(Qt::FramelessWindowHint | Qt::Tool | Qt::WindowStaysOnTopHint); //设置大圆圆心位置 SmallCir_xy.setX(300); SmallCir_xy.setY(300); //设置小圆圆心位置,与大圆相同 BigCir_xy=SmallCir_xy; //设置窗口固定大小为400*400 this->setFixedSize(400,400); //鼠标点击标志初始化 MousePressFlag=false; } //绘图事件:绘制地图、摇杆中的大圆和小圆 void Widget::paintEvent(QPaintEvent *event) { Q_UNUSED(event); //绘图画笔 QPainter painter(this); //抗锯齿 painter.setRenderHint(QPainter::Antialiasing, true); //消锯齿 painter.setRenderHints(QPainter::SmoothPixmapTransform); //绘制摇杆中的大圆 QPixmap bigCircle_Pixmap; bigCircle_Pixmap.load(":/new/prefix1/image/max.png"); painter.drawPixmap(SmallCir_xy.x()-BIG_CIRCLE_RADIUS,SmallCir_xy.y()-BIG_CIRCLE_RADIUS,\ BIG_CIRCLE_RADIUS*2,BIG_CIRCLE_RADIUS*2,bigCircle_Pixmap); //绘制摇杆中的小圆 QPixmap smallCircle_Pixmap; smallCircle_Pixmap.load(":/new/prefix1/image/min.png"); painter.drawPixmap(BigCir_xy.x()-SMALL_CIRCLE_RADIUS,BigCir_xy.y()-SMALL_CIRCLE_RADIUS,\ SMALL_CIRCLE_RADIUS*2,SMALL_CIRCLE_RADIUS*2,smallCircle_Pixmap); } //鼠标移动事件:实现摇杆功能 void Widget::mouseMoveEvent(QMouseEvent *e) { QPoint rocker_xy; //摇杆所在的实时坐标 QByteArray xy; xy.resize(2); int x,y; rocker_xy=e->pos(); if(MousePressFlag) //MousePressFlag为true,说明鼠标点击在了大圆内,才进行计算 { //小圆圆心出了大圆则在大圆上90-25=65 65*65=4225 if(pow((rocker_xy.x()-SmallCir_xy.x()),2)+pow((rocker_xy.y()-SmallCir_xy.y()),2)>8100) { x=int( 90*cos(atan2(abs(rocker_xy.y()-SmallCir_xy.y()),abs(rocker_xy.x()-SmallCir_xy.x()))) ); y=int( 90*sin(atan2(abs(rocker_xy.y()-SmallCir_xy.y()),abs(rocker_xy.x()-SmallCir_xy.x()))) ); //第一象限 if(rocker_xy.x()>SmallCir_xy.x()&&rocker_xy.y()>SmallCir_xy.y()) { BigCir_xy.setX(x+SmallCir_xy.x()); BigCir_xy.setY(y+SmallCir_xy.y()); } //第二象限 else if(rocker_xy.x()<SmallCir_xy.x()&&rocker_xy.y()>SmallCir_xy.y()) { BigCir_xy.setX(-x+SmallCir_xy.x()); BigCir_xy.setY(y+SmallCir_xy.y()); x=-x; } //第三象限 else if(rocker_xy.x()<SmallCir_xy.x()&&rocker_xy.y()<SmallCir_xy.y()) { BigCir_xy.setX(-x+SmallCir_xy.x()); BigCir_xy.setY(-y+SmallCir_xy.y()); x=-x; y=-y; } //第四象限 else if(rocker_xy.x()>SmallCir_xy.x()&&rocker_xy.y()<SmallCir_xy.y()) { BigCir_xy.setX(x+SmallCir_xy.x()); BigCir_xy.setY(-y+SmallCir_xy.y()); y=-y; } } else { BigCir_xy=rocker_xy; x=rocker_xy.x()-SmallCir_xy.x(); y=rocker_xy.y()-SmallCir_xy.y(); } xy[0]=char( x ); xy[1]=char( y ); //hex发送 //mycartcp->TCPSend(xy); qDebug()<<x<<y; update(); } MapRemov_Old=rocker_xy; } //鼠标释放事件:释放鼠标,则MousePressFlag复位,且小圆圆心设置为初始值,更新绘图事件后,重新绘图使小圆(摇杆)回到原处 void Widget::mouseReleaseEvent(QMouseEvent *e) { Q_UNUSED(e); //释放鼠标,则MousePressFlag复位 MousePressFlag=false; //小圆圆心设置为初始值,即大圆圆心值 BigCir_xy.setX(SmallCir_xy.x()); BigCir_xy.setY(SmallCir_xy.y()); this->update(); //更新绘图事件后,重新绘图使小圆(摇杆)回到原处 } //鼠标按下事件:获取摇杆所在的实时坐标 void Widget::mousePressEvent(QMouseEvent *e) { QPoint rocker_xy; //摇杆所在的实时坐标 rocker_xy=e->pos(); //获取摇杆所在的实时坐标 qDebug() <<"摇杆坐标: " <<rocker_xy; //鼠标点击,在大圆内才设置MousePressFlag if(pow((rocker_xy.x()-SmallCir_xy.x()),2)+pow((rocker_xy.y()-SmallCir_xy.y()),2)<=8100) //判断摇杆是否在大圆内 { MousePressFlag=true; } else { MapRemov_Old=rocker_xy; } }
true
2c8cbedc3d2633fcf1edc1a877a9b49e25b3bc92
C++
koshka-kartoshka/SPRINGS
/Spring.hpp
UTF-8
683
2.765625
3
[]
no_license
#include <SFML/Graphics.hpp> #include <iostream> class Spring { public: Vector2f length0Start; Vector2f length0End; Vector2f lengthStart; Vector2f lengthEnd; sf::Color color; float stiffness; void drawSpring(Spring spring, sf::RenderWindow* window) { sf::Vertex line[] = { sf::Vertex(sf::Vector2f(spring.lengthStart.x, spring.lengthStart.y)), sf::Vertex(sf::Vector2f(spring.lengthEnd.x, spring.lengthEnd.y)) }; line -> color = color; window->draw(line, 2, sf::Lines); } };
true
0af29464d7607c9d79b3580dbdc1a3bb394497c0
C++
EunSeong-Seo/coding_test
/codeup_c++/1084.cpp
UTF-8
239
2.796875
3
[]
no_license
#include <stdio.h> int main() { int r,g,b; int count=0; scanf("%d %d %d",&r,&g,&b); for(int i=0;i<r;i++) for (int j=0;j<g;j++) for (int k=0;k<b;k++) { printf("%d %d %d\n",i,j,k); count++; } printf("%d",count); }
true
6a345b540a575e2c7df8928eee2bd034f41d16f6
C++
xmlb88/algorithm
/leetcode/BFS/743.networkDelayTime.cpp
UTF-8
541
2.671875
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; // TODO: // https://leetcode-cn.com/problems/network-delay-time/solution/dirkdtra-by-happysnaker-vjii/ int networkDelayTime(vector<vector<int>>& times, int n, int k) { vector<vector<pair<int, int>>> edge(n + 1); for (auto& time : times) { edge[time[0]].push_back(make_pair(time[1], time[2])); } queue<pair<int, int>> q; vector<int> visited(n + 1, -1); q.push(make_pair(k, 0)); visited[k] = 0; while (!q.empty()) { } }
true
a7e6c8b6174513a5c3d2c97f66b204447ad5b1bc
C++
imaycen/Riemann
/main.cpp
UTF-8
3,920
3.40625
3
[]
no_license
// Author : Ivan de Jesus May-Cen // Email : imaycen@hotmail.com, imay@itsprogreso.edu.mx // Language : C++ // Environment : Linux // Compiler : g++ // Revisions : // Initial : 16.02.2017 // Last : // Este programa compila en la consola de linux mediante la orde // g++ main.cpp -o riemann // "sumatoria" es el nombre del ejecutable //Inclusion de librerias #include <iostream> #include <cmath> //Declaracion de funciones double funcion(double x, int opcion); double suma_inferior_riemann( double a, double b, int n, int opcion ); double suma_superior_riemann( double a, double b, int n, int opcion ); double minimo( double a0, double b0, int opcion); double maximo( double a0, double b0, int opcion); using namespace std; //Funcion principal int main( ) { double suma, a = 0.0, b = 1.0; int n = 1000, opcion = 4; //Llama a funcion que determina la suma de Riemann suma = suma_inferior_riemann( a, b, n, opcion ); //Imprime resultados cout << "La suma inferior es: " << suma << endl; //Llama a funcion que determina la suma de Riemann suma = suma_superior_riemann( a, b, n, opcion ); //Imprime resultados cout << "La suma superior es: " << suma << endl; return 0; } //******************************************************** // Se definen opciones para la funcion a evaluar // // Input : indice i, opcion de funcion // Output : evaluacion de la funcion en x //******************************************************** double funcion(double x, int opcion) { double valor; if(opcion == 1) valor = x; else if(opcion == 2) valor = x*x; else if(opcion == 3) valor = 3-x*x; if(opcion == 4) valor = sqrt(x); return valor; } //******************************************************** // Se definen opciones para suma inferior de Riemann // // Input : intervalo [a,b], indice n, opcion // Output : evaluacion de la suma de Riemann en indice n //******************************************************** double suma_inferior_riemann( double a, double b, int n, int opcion ) { double dx, xi, a0, b0, fun_mi, suma = 0.0; int i; //Tamano de las bases dx = (b - a) / n; for( i = 1; i <= n; ++i ) { a0 = a + (i-1)*dx; b0 = a + i*dx; //Minimo para suma inferior fun_mi = minimo(a0, b0, opcion); //Anade termino en suma de Riemann suma += fun_mi * dx; } return suma; } //******************************************************** // Se definen opciones para suma superior de Riemann // // Input : intervalo [a,b], indice n, opcion // Output : evaluacion de la suma de Riemann en indice n //******************************************************** double suma_superior_riemann( double a, double b, int n, int opcion ) { double dx, xi, a0, b0, fun_Mi, suma = 0.0; int i; //Tamano de las bases dx = (b - a) / n; for( i = 1; i <= n; ++i ) { a0 = a + (i-1)*dx; b0 = a + i*dx; //Maximo para suma inferior fun_Mi = maximo(a0, b0, opcion); //Anade termino en suma de Riemann suma += fun_Mi * dx; } return suma; } //******************************************************** // Funcion para calcular valor minimo de una funcion // // Input : intervalos [a0, b0], opcion de funcion // Output : valor minimo //******************************************************** double minimo( double a0, double b0, int opcion) { double min; //Calcula el valor minimo if( funcion(a0, opcion) <= funcion(b0, opcion) ) min = funcion(a0, opcion); else min = funcion(b0, opcion); return min; } //******************************************************** // Funcion para calcular valor maximo de una funcion // // Input : intervalos [a0, b0], opcion de funcion // Output : valor maximo //******************************************************** double maximo( double a0, double b0, int opcion) { double max; //Calcula el valor minimo if( funcion(a0, opcion) >= funcion(b0, opcion) ) max = funcion(a0, opcion); else max = funcion(b0, opcion); return max; }
true
731de04fa092e9d4473379809682e13449e76b11
C++
Charliechen1/EECS_coding_practice
/charliechen/in_post_tree/in_post_tree.cpp
UTF-8
1,590
3.359375
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return buildTreeHelper(inorder, postorder, 0, inorder.size(), 0, postorder.size()); } TreeNode* buildTreeHelper(vector<int>& inorder, vector<int>& postorder, uint32_t in_st, uint32_t in_ed, uint32_t po_st, uint32_t po_ed) { TreeNode *res = NULL; if (in_ed <= in_st || po_ed <= po_st || in_ed - in_st != po_ed - po_st) { return res; } // find out the middle one int mid = postorder[po_ed - 1]; res = new TreeNode(mid); uint32_t mid_in_idx = 0; for (uint32_t i=0; i<inorder.size(); i++) { if (inorder[i] == mid) { mid_in_idx = i; break; } } // subtree inorder index uint32_t l_in_st = in_st; uint32_t l_in_ed = mid_in_idx; uint32_t r_in_st = mid_in_idx + 1; uint32_t r_in_ed = in_ed; // subtree postorder index uint32_t sub_size = mid_in_idx - l_in_st; uint32_t l_po_st = po_st; uint32_t l_po_ed = po_st + sub_size; uint32_t r_po_st = po_st + sub_size; uint32_t r_po_ed = po_ed - 1; res->left = buildTreeHelper(inorder, postorder, l_in_st, l_in_ed, l_po_st, l_po_ed); res->right = buildTreeHelper(inorder, postorder, r_in_st, r_in_ed, r_po_st, r_po_ed); return res; }
true
e5613e8a9d29e67db84299857c6f1c57aed6db2b
C++
AnushkaDwivedi17/Data_Structures
/stack.cpp
UTF-8
749
3.890625
4
[]
no_license
#include<iostream> using namespace std; class Node{ public: int data; Node* next; Node(int data){ this->data = data; this->next = NULL; } }; class Stack{ public: Node* top; Stack(){ top = NULL; } void peek(){ if(top!=NULL) cout<<top->data; else cout<<"Empty"; } void push(int data){ Node* temp = new Node(data); temp -> next = top; top = temp; } void pop(){ if(top == NULL){ cout << "Empty"; } else{ Node *temp = top; top = top->next; cout<<temp->data; delete temp; } } }; int main(){ Stack obj; obj.push(1); obj.peek(); obj.push(2); obj.peek(); obj.pop(); }
true