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
1d21457482907290fcc6aa89dcb29d8dde13af85
C++
Microbot-it/Microbot-WiFi-Relay-Shield
/src/microbot_wifi_relay_shield.cpp
UTF-8
1,669
2.765625
3
[ "MIT" ]
permissive
/*#################################################################### FILE: microbot_wifi_relay_shield.h VERSION: 1.0 PURPOSE: WiFi Relay Shield library for Arduino HISTORY: Mirko Prosseda - Original version (20/07/2020) #######################################################################*/ #include "microbot_wifi_relay_shield.h" // Initialize the Motor Shield hardware void microbotWiFiRelayShield::begin() { // initializes the digital pin as an output pinMode(out1, OUTPUT); pinMode(out2, OUTPUT); pinMode(out3, OUTPUT); pinMode(out4, OUTPUT); // reset digital pins and disables both channels digitalWrite(out1, LOW); digitalWrite(out2, LOW); digitalWrite(out3, LOW); digitalWrite(out4, LOW); } // Set direction and speed for a specific motor channel void microbotWiFiRelayShield::setRelay(uint8_t ch) { switch(ch) { // ch parameter must be 1 to 4 case 1: digitalWrite(out1, HIGH); break; case 2: digitalWrite(out2, HIGH); break; case 3: digitalWrite(out3, HIGH); break; case 4: digitalWrite(out4, HIGH); break; } } // Set direction and speed for a specific motor channel void microbotWiFiRelayShield::unsetRelay(uint8_t ch) { switch(ch) { // ch parameter must be 1 to 4 case 1: digitalWrite(out1, LOW); break; case 2: digitalWrite(out2, LOW); break; case 3: digitalWrite(out3, LOW); break; case 4: digitalWrite(out4, LOW); break; } }
true
514faa386bf996d9b2b52ffcd4fd455b025841bc
C++
mikerainey/pbbslib
/examples/bfs.h
UTF-8
1,307
2.859375
3
[]
no_license
#pragma once #include "sequence.h" #include "ligra.h" // ************************************************************** // BFS edge_map structure // ************************************************************** namespace pbbs { using vertex = ligra::vertex; struct BFS_F { sequence<vertex> Parents; vertex n; BFS_F(vertex n) : Parents(sequence<vertex>(n, n)), n(n) { } inline bool updateAtomic (vertex s, vertex d) { return atomic_compare_and_swap(&Parents[d], n , s); } inline bool update (long s, long d) { Parents[d] = s; return true;} inline bool cond (long d) { return (Parents[d] == n); } }; // ************************************************************** // Run BFS, returning number of levels, and number of vertices // visited // ************************************************************** std::pair<size_t,size_t> bfs(ligra::graph const &g, vertex start) { auto BFS = BFS_F(g.num_vertices()); BFS.Parents[start] = start; ligra::vertex_subset frontier(start); //creates initial frontier size_t levels = 0, visited = 0; while(!frontier.is_empty()) { //loop until frontier is empty visited += frontier.size(); levels++; frontier = ligra::edge_map(g, frontier, BFS); } return std::make_pair(levels, visited); } } // end namespace
true
83ea297d1d139b33bf0a9673472496026905bae0
C++
Pacman29/OOP_3
/canvas/graphical_sys.cpp
UTF-8
734
2.515625
3
[]
no_license
#include "graphical_sys.h" #include "model/model.h" void Graphical_sysImpl::Draw_model(base_painter* pntr, base_model &mod, base_camera &cam) { size_t line_count = mod.line_count(); if(!line_count) throw graphic_sys_error::model_empty(); for(size_t i = 0; i<line_count; ++i) { line tmp = mod.get_line(i); vector<double> start = mod.get_vertex(tmp.start()).to_vector(); vector<double> end = mod.get_vertex(tmp.end()).to_vector(); matrix<double> view = cam.GetViewMatrix(); start = start * view; end = end * view; pntr->draw_line(point(start),point(end)); } } void Graphical_sysImpl::clear_scene(base_painter *pntr) { pntr->clear_scene(); }
true
789d1189350c4cba0c42573d6e7eb8fd15b31394
C++
rcory/drake
/math/wrap_to.h
UTF-8
988
3.203125
3
[ "BSD-3-Clause" ]
permissive
#pragma once #include <cmath> #include "drake/common/double_overloads.h" #include "drake/common/drake_assert.h" namespace drake { namespace math { /// For variables that are meant to be periodic, (e.g. over a 2π interval), /// wraps `value` into the interval `[low, high)`. For example: /// wrap_to(.1, 0, 1) = .1 /// wrap_to(1, 0, 1) = 0 /// wrap_to(-.1, 0, 1) = .9 /// wrap_to(2.1, 0, 1) = .1 /// wrap_to(-1.1, 0, 1) = .9 /// wrap_to(6, 4, 8) = 6 /// wrap_to(2, 4, 8) = 6 template <class T1, class T2> T1 wrap_to(const T1& value, const T2& low, const T2& high) { DRAKE_ASSERT(low < high); using std::fmod; const T1 rem = fmod(value - low, high - low); return if_then_else(rem >= T1(0), low + rem, high + rem); // TODO(russt): Consider an alternative implementation for symbolic (that // avoids explicit branching): // const T2 range = high - low; // return value - range * floor((value - low) / range); } } // namespace math } // namespace drake
true
68b9aa0a107aab37a4748859f030d1f978b3688a
C++
sidoh/Join-Compression
/compression/Compressor.cpp
UTF-8
3,948
2.671875
3
[]
no_license
/* * Compressor.cpp * * Created on: Jul 24, 2011 * Author: mullins */ #include "Compressor.h" #include <EncodedFileHeader.h> #include <DictionaryDefinition.h> #include <StringDictionary.h> #include <IndexDictionary.h> #include <ColumnDictionaryEntry.h> #include <IndexEntry.h> #include <InnerDictionaryEntry.h> #include <LeafDictionaryEntry.h> void Compressor::compress(JoinTable *table, ostream & out, int dict_entries) { JoinTree *tree = table->get_join_tree(); out << EncodedFileHeader(dict_entries, table->num_cols(), tree->get_length()); write_dictionary_definitions(tree, out); // Initialize dictionaries vector<StringDictionary*> *column_dicts = StringDictionary::get_array( table->num_cols(), dict_entries); vector<IndexDictionary*> *index_dicts = IndexDictionary::get_array( tree->get_length(), dict_entries); Row *row; int i = 0; while ((row = table->next_row()) != NULL) { encode_row(row, column_dicts, index_dicts, tree, tree->get_length(), out); delete row; if ((i % 1000) == 0) { cerr << "."; fflush(stdout); } i++; } cerr << "Done! Compressed " << i << " rows." << endl; delete column_dicts; delete index_dicts; } void Compressor::write_dictionary_definitions(JoinTree *tree, ostream & out) { if (tree->get_left() == NULL) { DictionaryDefinition( DictionaryDefinition::TYPE_LEAF, tree->get_index(), tree->get_range()->get_left(), tree->get_range()->get_count()) .write(out); } else { write_dictionary_definitions(tree->get_left(), out); write_dictionary_definitions(tree->get_right(), out); DictionaryDefinition( DictionaryDefinition::TYPE_INNER, tree->get_index(), tree->get_left()->get_index(), tree->get_right()->get_index()) .write(out); } } const unsigned long Compressor::encode_row(Row *row, vector<StringDictionary*> *col_dictionaries, vector<IndexDictionary*> *join_dictionaries, JoinTree *join_tree, const int join_tree_len, ostream & out) { const Range *rng = join_tree->get_range(); // Base case: this is a leaf node in the join tree if (join_tree->get_left() == NULL) { // Build a collection of column indexes. vector<unsigned long> col_indexes; for (int i = rng->get_left(); i <= rng->get_right(); i++) { StringDictionary *dict = col_dictionaries->at(i); const string& value = row->get_column(i); if (! dict->contains(value)) { IndexEntry::write((i + join_tree_len), out); ColumnDictionaryEntry(value) .write(out); dict->push(value); } col_indexes.push_back(dict->lookup(value)); } IndexDictionary *dict = join_dictionaries->at(join_tree->get_index()); if (! dict->contains(col_indexes)) { IndexEntry::write(join_tree->get_index(), out); LeafDictionaryEntry(col_indexes) .write(out); dict->push(col_indexes); } return dict->lookup(col_indexes); } else { // Build a recursive dictionary vector<unsigned long> dict_indexes; IndexDictionary *dict = join_dictionaries->at(join_tree->get_index()); dict_indexes.push_back( encode_row(row, col_dictionaries, join_dictionaries, join_tree->get_left(), join_tree_len, out)); dict_indexes.push_back( encode_row(row, col_dictionaries, join_dictionaries, join_tree->get_right(), join_tree_len, out)); // If this is the root, just write and exit. We do this because we assume that not // very many repeated rows will occur, so maintaining a top-level dictionary would // be a waste. if (join_tree->is_root()) { InnerDictionaryEntry(join_tree->get_index(), dict_indexes[0], dict_indexes[1]) .write(out); return 0; } // Otherwise, behave normally. if (! dict->contains(dict_indexes)) { IndexEntry::write(join_tree->get_index(), out); InnerDictionaryEntry(join_tree->get_index(), dict_indexes[0], dict_indexes[1]) .write(out); dict->push(dict_indexes); } return dict->lookup(dict_indexes); } }
true
61ca2c068e60e7a9872e07944debb8a27dc2ad5b
C++
alexanderlvarfolomeev/ITMO
/Algorithms and Data Structures/StackQueueDisjoinedSet/CountingExp.cpp
UTF-8
1,308
2.703125
3
[]
no_license
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <cstdlib> #include <cmath> #include <string> #include <utility> #include <stack> using namespace std; int p[200001]; int r[200001]; long gexp[200001]; int get(int x) { if (p[x]!=x) { int root = get(p[x]); if (p[x]!=root) { gexp[x]+=gexp[p[x]]; } p[x]=root; } return p[x]; } void unite(int x, int y) { x = get(x); y = get(y); if (x!=y) { if (r[y]<r[x]) swap(x,y); p[x] = y; if (r[x]==r[y]) r[y]++; gexp[x]-=gexp[y]; } } int ex(int x) { int res = 0; while (x!=p[x]) { res += gexp[x]; x=p[x]; } res+=gexp[x]; return res; } int main() { int n, m; int k, l; string s; cin >> n >> m; for (int i = 0; i<=n; i++) { p[i]=i; r[i] = 0; gexp[i] = 0; } for (int i = 0; i<m; i++) { cin >> s; if (s == "join") { cin >> k >> l; unite(k,l); } if (s=="get") { cin >> k; cout << ex(k) << '\n'; } if (s=="add") { cin >> k >> l; k = get(k); gexp[k]+=l; } } return 0; }
true
e76dce9bd6ee87033d07cf8fba4570d97f41221a
C++
NguyenTrongLuan/KTLT-Assignment02
/Book.h
UTF-8
2,328
2.5625
3
[]
no_license
// // Created by hvlpro98 on 02/05/2017. // #ifndef ASSIGNMENT2_BOOK_H #define ASSIGNMENT2_BOOK_H #include <iostream> #include <fstream> #include <string> #include "Date.h" #define TYPE_SIZE 50 #define AUTHOR_SIZE 100 #define TITLE_SIZE 100 #define SUM_SIZE 400 class Book { public: Book(std::string = "", std::string = "", std::string = "", std::string = "", int = 0, long = 0, long = 0); // Constructor, it dung std::string getName() const; // Tra ve ten sach std::string getAuthor() const; // Tra ve ten tac gia long getTimeAccess() const; // Tra ve so luot xem sach do long getBookID() const; // Tra ve ma so sach void setTitle(std::string); // Gan ten sach void setAuthor(std::string); // Gan ten tac gia void setBookID(long); // Gan ma so sach void setTimesAcess(long); // Gan so luot truy cap long getNumOfBook(); // Doc file, tra ve so sach da duoc luu void setNumOfBook(long); // Ghi file, sua so sach duoc luu int getYear() const; // Tra ve nam xuat ban std::string getType() const; // Tra ve the loai void setType(std::string); // Gan the loai void setSummary(std::string); // Gan tom tat cho sach void outputSummary(); // In ra tom tat theo form, co thut dau dong, xuong hang... void outputMainInfo(); // Xuat ra thong tin co ban, dung khi tim kiem sach, chiem 1 hang void setAmount(int); // Gan so luong cua loai sach do int getAmount() const; // Tra ve so luong loai sach do void readData(long); // Dua vao id, doc file luu thong tin vao doi tuong de dung void saveData(); // Luu du lieu vao file, tu dong lay ma so sach hien tai de xac dinh vi tri luu void saveData(long);; // Xuat ra thong tin cu the, dung khi nguoi dung muon xem sach chi tiet, chiem man hinh nhieu hon (~ 7 hang) void setDateAdd(); Date getDateAdd() const; void changeInfo(); void setYear(int); void outputSpecific() ; private: size_t my_strlen(const char *str); long bookID; // Ma so sach char bookTitle[TITLE_SIZE]; // Ten sach char bookAuthor[AUTHOR_SIZE]; // Tac gia char type[TYPE_SIZE]; // The loai char summary[SUM_SIZE]; // Tom tat int year; // Nam san xuat long amount; // So luong cua loai sach do long timesAccess; // So lan truy cap sach do Date dateAdd; }; #endif //ASSIGNMENT2_BOOK_H
true
2c853cfb0c51efd4ff683d75b20eed521e4d0d66
C++
sherlock-coding/LeetCode
/SqrtX.cpp
UTF-8
812
4
4
[]
no_license
/* * 69 Sqrt(x) * Implement int sqrt(int x). * * Compute and return the square root of x. * */ #include <iostream> using namespace std; int mySqrt(int x) { if (x == 0) return 0; if (x == 1 || x == 2 || x == 3) return 1; int low = 0, high = x; while (low < high) { long long mid = low + (high - low) / 2; long long tmp = mid * mid; if (tmp == x) return mid; if (tmp > x) high = mid - 1; else low = mid + 1; } long long ret = low; if (ret * ret > x) return ret - 1; return low; } int main() { cout << mySqrt(2147395599) << endl; cout << mySqrt(10) << endl; cout << mySqrt(225) << endl; cout << mySqrt(2) << endl; cout << mySqrt(8) << endl; }
true
145fb7e645be4b62a70a9ee03e14ed7b8aab37ea
C++
Coracaos/demo-game
/src/Game.cpp
UTF-8
2,374
3.390625
3
[]
no_license
#include "Game.h" #include <iostream> using namespace std; Game::Game() { } void Game::updateScreen(Tank * tank, vector <Bullet>& bullets){ // Set clear color glClearColor(0,1,0,1); // Clear screen glClear(GL_COLOR_BUFFER_BIT); tank->drawTank(); for(int i=0; i<bullets.size(); i++){ bullets[i].drawBullet(); } // Change buffer // Render buffer in the screen glutSwapBuffers(); } void Game::keyPressGame(unsigned char key, Tank *tank){ switch(key){ case 'a': tank->left = true; break; case 'd': tank->right = true; break; case 'w': tank->up = true; break; case 's': tank->down = true; break; default: break; } } void Game::keyReleaseGame(unsigned char key, Tank *tank){ switch(key){ case 'a': tank->left = false; break; case 'd': tank->right = false; break; case 'w': tank->up = false; break; case 's': tank->down = false; break; default: break; } } void Game::checkEventsGame(Tank * tank, std::vector<Bullet>& bullets, Settings settings){ checkEventsTank(tank, bullets, settings); checkEventsBullet(bullets, settings); } void Game::checkEventsTank(Tank * tank, vector<Bullet>& bullets, Settings settings){ if((tank->right && tank->left) || (tank->up && tank->down)){ }else if(tank->right){ tank->x += tank->speed; }else if(tank->left){ tank->x -= tank->speed; }else if(tank->up){ tank->y += tank->speed; }else if(tank->down){ tank->y -= tank->speed; } if(tank->shoot){ Bullet new_bullet(settings, *tank); bullets.push_back(new_bullet); tank->shoot = false; } } void Game::checkEventsBullet(vector <Bullet>& bullets, Settings settings){ for(int i = 0; i< bullets.size(); i++){ bullets[i].x += 5.0*cos(bullets[i].direction); bullets[i].y += 5.0*sin(bullets[i].direction); if(abs(bullets[i].x) > settings.screen_right || abs(bullets[i].y) > settings.screen_top){ bullets.erase(bullets.begin() + i); } } } Game::~Game() { //dtor }
true
96e9212f3efe32cf09f3f7a1be7fca3504bbe209
C++
wjb127/Algorithm_Code_Note
/자료 구조/스택/3015 오아시스 재결합.cpp
UTF-8
1,438
3.046875
3
[]
no_license
#include<iostream> #include<cstdio> #include<vector> #include<algorithm> #include<memory.h> #include<string> #include<cmath> #define f(n) for(int i=0;i<n;i++) #define p(a) cout<<a<<endl #define pb push_back using namespace std; int n; int a[500000]; int main() { // 입력 받기 scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } // 스택 2개 만들기(1개는 개수 세기) vector<int> stack; vector<int> count; // 답 long long ans = 0; // 입력값 검색 for (int i = 0; i < n; i++) { // 동일한 값의 개수 int cnt = 1; // 스택에 내용물이 있을 때 while (!stack.empty()) { // 스택의 마지막보다 입력값이 클 때 if (stack.back() <= a[i]) { // 답에 값의 개수 세기 @@@@@@@@@@@@@@@@@@@@@ ans += (long long)count.back(); // 만약 같은 값이 나온다면 @@@@@@@@@@@@@@@@@@@ if (stack.back() == a[i]) { // 개수를 추가 @@@@@@@@@@@@@@@@@@@@ cnt += count.back(); } // 스택과 카운트 하나씩 제거 @@@@@@@@@@@@@@ stack.pop_back(); count.pop_back(); } //만약 스택의 마지막보다 입력값이 작을 때 else { break; } } // 만약 스택이 비어있지 않다면 앞 원소와의 연결도 세기 if (!stack.empty()) { ans += 1; } // 스택 2개에 값 저장 stack.pb(a[i]); count.pb(cnt); } printf("%lld\n", ans); return 0; }
true
dde2f076928fe4a912160db2a3e40cdc81955cb2
C++
feliperubin/Newton-Image-Interpolation
/Code/app.cpp
UTF-8
20,768
2.734375
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> // #include <vector> #include <iostream> #include <png.h> #include <math.h> // #define DEBUG using namespace std; typedef struct{ unsigned char** data; unsigned int width; unsigned int height; unsigned int bitdepth; unsigned int channels; unsigned int color_type; }ImageData; // typedef struct{ unsigned int valid; float value; }FiniteTableValue; typedef struct{ FiniteTableValue *column; unsigned int length; }FiniteTableRow; typedef struct{ FiniteTableRow *row; unsigned int length; }FiniteTable; typedef struct{ FiniteTable *tables; unsigned int length; }FiniteTableList; // ImageData original, result; float mult; // float **finitetable; FiniteTableList *ftl; int quantos; void printFiniteTablex(/*FiniteTableList ftl*/) { int i,j,k = 0; for(i = 0; i < ftl->length; i++){ printf("FiniteTableList[%d] size: %u\n",i,ftl->tables[i].length); for(j = 0; j < ftl->tables[i].length; j++){ for(k = 0; k < ftl->tables[i].row[j].length; k++){ printf("[%f,%u], ",ftl->tables[i].row[j].column[k].value,ftl->tables[i].row[j].column[k].valid); } printf("\n"); } } } void printOriginal() { for(int i = 0; i < original.height; i++){ unsigned char *row = original.data[i]; for(int j = 0; j < original.width; j++){ if(j+1 < original.width) printf("%u, ",row[j]); else printf("%u",row[j]); } cout << "\n"; } } void printResult() { for(int i = 0; i < result.height; i++){ unsigned char *row = result.data[i]; for(int j = 0; j < result.width; j++){ if(j+1 < result.width) printf("%u, ",row[j]); else printf("%u",row[j]); } cout << "\n"; } } void deallocate_table_list(FiniteTableList *tablelist) { for(int i = 0; i < tablelist->length; i++){ FiniteTable table = tablelist->tables[i]; for(int j = 0; j < table.length; j++){ FiniteTableRow row = table.row[j]; free(row.column); } free(table.row); } free(tablelist->tables); free(tablelist); } /* ftl.length == original.heigh ftl.tables[i].length == original.width ftl.table[i].row[j].length ==original.width kyrill's answer to my question: (Although a little wrong, helped) https://stackoverflow.com/questions/47241718/what-is-the-correct-way-to-allocate-this-nested-structures/47242140#47242140 */ /* Assuming every table in the list will have num_rows rows and num_columns columns. */ FiniteTableList * allocate_table_list (int num_rows, int num_columns, int num_tables) { FiniteTableList * res = (FiniteTableList*)malloc (sizeof *res); res->tables = (FiniteTable*)malloc (num_tables * sizeof (*res->tables)); res->length = num_tables; for (int t = 0; t < num_tables; t++) { FiniteTable *table = &res->tables[t]; table->row = (FiniteTableRow*)malloc (num_rows * sizeof (*table->row)); table->length = num_rows; for (int r = 0; r < num_rows; r++) { FiniteTableRow *row = &table->row[r]; // row->column = (FiniteTableValue*)malloc (num_columns * sizeof (*row->column)); row->column = (FiniteTableValue*)calloc(num_columns,sizeof (*row->column)); row->length = num_columns; } } return res; } void writeResult() { FILE *fp = fopen("result.png", "wb"); if(!fp) abort(); png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png){ png_destroy_read_struct(&png, NULL, NULL); fclose(fp); // abort(); return; } png_infop info = png_create_info_struct(png); if (!info){ // abort(); png_destroy_read_struct(&png, &info, NULL); fclose(fp); return; } if (setjmp(png_jmpbuf(png))){ png_destroy_read_struct(&png, &info, NULL); fclose(fp); return; } png_init_io(png, fp); // Output is 8bit depth, RGBA format. png_set_IHDR( png, info, result.width, result.height, 8, // PNG_COLOR_TYPE_RGBA, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); png_write_info(png, info); png_write_image(png,result.data); png_write_end(png, NULL); fclose(fp); return; } void writeOriginal() { // int y; FILE *fp = fopen("original.png", "wb"); if(!fp) abort(); png_structp png = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (!png){ png_destroy_read_struct(&png, NULL, NULL); fclose(fp); // abort(); return; } png_infop info = png_create_info_struct(png); if (!info){ // abort(); png_destroy_read_struct(&png, &info, NULL); fclose(fp); return; } if (setjmp(png_jmpbuf(png))){ png_destroy_read_struct(&png, &info, NULL); fclose(fp); return; } png_init_io(png, fp); // Output is 8bit depth, RGBA format. png_set_IHDR( png, info, original.width, original.height, 8, // PNG_COLOR_TYPE_RGBA, PNG_COLOR_TYPE_GRAY, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT ); png_write_info(png, info); png_write_image(png,original.data); png_write_end(png, NULL); fclose(fp); return; } // https://stackoverflow.com/questions/2703255/need-help-using-libpng-to-read-an-image?rq=1 int readImage(string image_name) { png_structp png_ptr; png_infop info_ptr; FILE *fp; if ((fp = fopen(image_name.c_str(), "rb")) == NULL) { cout << "Error no file found with that name\n"; cout << "Maybe you forgot '.png' on image.png ?\n"; return -1; } png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); if (png_ptr == NULL) { cout << "No idea what happened, bad file buffer probably\n"; png_destroy_read_struct(&png_ptr, NULL, NULL); fclose(fp); return -1; } info_ptr = png_create_info_struct(png_ptr); if (info_ptr == NULL) { png_destroy_read_struct(&png_ptr, NULL, NULL); fclose(fp); cout << "No idea what happened, bad file chunks probably\n"; cout <<"Error info_ptr == null\n"; return -1; } if (setjmp(png_jmpbuf(png_ptr))) { png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); cout <<"Error setjmp\n"; return -1; } png_init_io(png_ptr, fp); png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_STRIP_16 | PNG_TRANSFORM_SWAP_ALPHA | PNG_TRANSFORM_EXPAND, NULL); //////////////////////////////////////////////////////////////////// //IDHR CHUNK original.width = png_get_image_width(png_ptr, info_ptr); original.height = png_get_image_height(png_ptr, info_ptr); original.bitdepth = png_get_bit_depth(png_ptr, info_ptr); original.channels = png_get_channels(png_ptr, info_ptr); original.color_type = png_get_color_type(png_ptr, info_ptr); ///////////////////////////////////////////////////////////////////// if(original.color_type == PNG_COLOR_TYPE_GRAY){ cout << "It is grayscale\n"; original.data = (unsigned char**)malloc(sizeof(char**) * original.height); png_bytepp aux = png_get_rows(png_ptr,info_ptr); for(int i = 0; i < original.height;i++){ original.data[i] = (unsigned char*)malloc(sizeof(char) * original.width); memcpy(original.data[i], aux[i], original.width*sizeof(unsigned char)); } // original.data = png_get_rows(png_ptr, info_ptr); }else if(original.color_type == PNG_COLOR_TYPE_RGBA || original.color_type == PNG_COLOR_TYPE_RGB){ cout << "Converting to grayscale...\n"; png_bytepp colored_rows = png_get_rows(png_ptr, info_ptr); // original.data = (unsigned char**)malloc(sizeof(unsigned char*) * original.height); original.data = (unsigned char**)malloc(sizeof(char**) * original.height); int pxsize = 3; //RGB R G B if(original.color_type == PNG_COLOR_TYPE_RGBA) pxsize = 4; //RGBA R G B A png_bytep px; for(int i = 0; i < original.height; i++){ // original.data[i] = (unsigned char*)malloc(sizeof(unsigned char*)*original.width); original.data[i] = (unsigned char*)malloc(sizeof(char)*original.width); unsigned char *row = colored_rows[i]; unsigned char *originalRow = original.data[i]; for(int j = 0; j < original.width ;j++){ px = &(row[j * pxsize]); // Generic one... // originalRow[j] = (unsigned int)(0.299 * px[0] + 0.587 * px[1] + 0.114 * px[2]); //Use as reference for later // The Rehabilitation of Gamma Charles Poynthon // Sometimes called Lumma (Luminosity) // It gives more weight to the Green, taking into account // what color weights more to the human eye. // originalRow[j] = (unsigned int)(0.2126 * px[0] + 0.7152 * px[1] + 0.0722 * px[2]); // originalRow[j] = (unsigned char)round((float)(0.2126 * px[0] + 0.7152 * px[1] + 0.0722 * px[2])); float pxvalue = round((float)(0.2126 * (float)px[0] + 0.7152 * (float)px[1] + 0.0722 * (float)px[2])); if(pxvalue >= 255) originalRow[j] = 255; else if(pxvalue <= 0) originalRow[j] = 0; else originalRow[j] = pxvalue; } } }else{ cout << "I don't know this type of color...\n"; cout << "I just know GRAYSCALE, RGB, RGBA please try again with one of them.\n"; return -1; } // ISSO DAQUI SE EU DESCOMENTAR LIBERA ORIGINAL.DATA... png_destroy_read_struct(&png_ptr, &info_ptr, NULL); fclose(fp); return 0; } // p(x) = y0 + (x-x0)*(Deltay0/(1!*h^1))+(x-x0)(x-x1)*(Deltay1/(2!*h^2)).. void freeTable(FiniteTable *table) { for(int i = 0; i < table->length; i++){ FiniteTableRow *rows = table->row; for(int j = 0; j < rows->length; j++){ FiniteTableValue *columns = rows->column; free(columns); } free(rows); } free(table); } void nearest_neighbors(float x,int min,int max,int n,int *ptr){ int xround = round(x); int inicio = 0; if((xround - x) > 0){ //Se arredondou para cima if(n%2 == 0){//Se for par inicio = xround - ((n/2) -1); }else{//Impar inicio = xround - ((n-1)/2); } }else{ if(n%2 == 0){ inicio = xround - (n/2); }else{ inicio = xround - ((n-1)/2); } } if(inicio < min){ inicio = min; } // else if(inicio > max){ else if(inicio+n-1 > max){ inicio = max - n +1; } int i = 0; // printf("\n"); // printf("X: %f\n",x); // printf("round(x): %d\n",xround); // printf("N: %d\n",n); // printf("Min: %d\n",min); // printf("Max: %d\n",max); // printf("inicio: %d\n",inicio); // printf("\nX: %f\nround(X): %d\nN: %d\n",x,xround,n); for(i = 0; i < n; i++){ // printf("ptr[%d]: %d\n",i,inicio+i); ptr[i] = inicio+i; } } /* Esse initialRow eh o q eu vou usar p/ table->row[initialRow].column[]... No caso de de interpolar uma tabela da ftl original, estaria correto usar neighborCols[0] como index, mas depois que ja interpolei cada uma das linhas vizinhas, os index de row[.] nao sao por exemplo 4,5,6,7 e sim 0,1,2,3 */ void interpolate1D(FiniteTable *table, float *x,int *neighborCols,float *value,int initialRow) { // FiniteTableRow prevrow = table.row[j-1]; // for(int k = 0; k < tablerow.length-j;k++){ // tablerow.column[k].value = prevrow.column[j+1].value - prevrow.column[j].value; // tablerow.column[k].empty = 0; // } int i = 0; //Primeiro faz os deltas float add = 0.0; float mult_a = 1.0; float mult_b = 1.0; // for(i = 0; i < quantos; i++){ // table->row[neighborCols[i]] // } // FiniteTableRow *tablerow = &table->row[neighborCols[0]]; // add = tablerow->column[0].value; // for(i = 1; i < quantos; i++){ // mult_a *= (*x - (float)neighborCols[i]); // if(mult_a == 0)break; // mult_b *= ((float)i+1); // 1! , 2! , 3! .... // add += (mult_a * tablerow->column[i].value/mult_b); // } // printf("\n"); // add = table->row[0].column[0].value; // Esse row[neighborCols[0]] ta dando problema!!! // pq o indice de row ta correto quando se trata de uma tabela de ftl, // mas Ñ quando ja interpolei as linhas.. // add = table->row[neighborCols[0]].column[0].value; add = table->row[initialRow].column[0].value; // printf("BEGI:[add, %f]--[table.length,%d]--[x,%f]--[value,%f]\n",add,table->length,*x,*value); // printf("BEGI:[add, %f]--[table.length,%d]--[x,%f]--[value,%f]\n",add,quantos,*x,*value); // printf("BEGI:"); // for(i = 0; i < quantos; i++)printf("[neighborCols[%d],%d]",i,neighborCols[i]); // printf("\n"); // for(i = 1; i < table->length;i++){ // for(i = 1; i < table->length;i++){ for(i = 1; i < quantos; i++){ mult_a = mult_a * (*x - (float)neighborCols[i-1]); if(mult_a == 0) break; mult_b = mult_b * ((float)i); // add += (mult_a * table->row[0].column[i].value/mult_b); // add += (mult_a * table->row[neighborCols[0]].column[i].value/mult_b); add += (mult_a * table->row[initialRow].column[i].value/mult_b); // printf("FORI[i, %d]--[neightborCols[i-1],neightborCols[%d]]--[mult_a,%f]--[mult_b,%f]--[add,%f]\n",i,i-1,mult_a,mult_b,add); } // printf("STOP:[i, %d]--[neightborCols[i-1],neightborCols[%d]]--[mult_a,%f]--[mult_b,%f]--[add,%f]\n",i,i-1,mult_a,mult_b,add); *value = add; // printf("Value: %f\n",*value); } void interpolate2D(unsigned char *coordptr, float *x, float *y, int *neighborRows, int *neighborCols) { // cout << "TUTS TUTS\n"; // int num_rows, int num_columns, int num_tables FiniteTableList *interplist = allocate_table_list(quantos,quantos,1); FiniteTable table = interplist->tables[0]; #ifdef DEBUG printf("Table Length Interplist: %u\n",table.length); printf("neighborRows{%d,%d,%d,%d}\n",neighborRows[0],neighborRows[1],neighborRows[2],neighborRows[3]); printf("neighborCols{%d,%d,%d,%d}\n",neighborCols[0],neighborCols[1],neighborCols[2],neighborCols[3]); #endif int i,j = 0; //gero os Yi's referentes a cada linha for(i = 0; i < table.length; i++){ interpolate1D(&ftl->tables[neighborRows[i]],x,neighborCols,&table.row[i].column[0].value,neighborCols[0]); table.row[i].column[0].valid = 1; // printf("Value pos-interp: %f\n",table.row[i].column[0].value); // table.row[i].length = quantos; } //computando a tabela de colunas interpoladas #ifdef DEBUG printf("PRE-POINT(%f,%f)\n",*y,*x); for(int j = 0; j < table.length; j++){ FiniteTableRow row = table.row[j]; for(int k = 0; k < row.length; k++){ FiniteTableValue tablevalue = row.column[k]; if(tablevalue.valid == 1) printf("[%f,%d]",tablevalue.value,tablevalue.valid); } printf("\n"); } printf("Table Length: %d\n",table.length); #endif for(int i = 1; i < table.length; i++){ for(j = 0; j < table.length-i;j++){ table.row[j].column[i].value = table.row[j+1].column[i-1].value - table.row[j].column[i-1].value; table.row[j].column[i].valid = 1; } } #ifdef DEBUG printf("POS-POINT(%f,%f)\n",*y,*x); for(int j = 0; j < table.length; j++){ FiniteTableRow row = table.row[j]; for(int k = 0; k < row.length; k++){ FiniteTableValue tablevalue = row.column[k]; if(tablevalue.valid == 1) printf("[%f,%d]",tablevalue.value,tablevalue.valid); } printf("\n"); } #endif float coordptrAux = 0.0; #ifdef DEBUG printf("neighborRows{%d,%d,%d,%d}\n",neighborRows[0],neighborRows[1],neighborRows[2],neighborRows[3]); printf("neighborCols{%d,%d,%d,%d}\n",neighborCols[0],neighborCols[1],neighborCols[2],neighborCols[3]); printf("Pre(%f,%f)-->coordptrAux = %f\n",*y,*x,coordptrAux); #endif interpolate1D(&table,y,neighborRows,&coordptrAux,0); #ifdef DEBUG printf("Pos(%f,%f)-->coordptrAux = %f\n",*y,*x,coordptrAux); #endif coordptrAux = round(coordptrAux); if(coordptrAux > 255) *coordptr = (unsigned char)255; else if(coordptrAux < 0) *coordptr = (unsigned char)0; else *coordptr = (unsigned char)coordptrAux; #ifdef DEBUG printf("%d\n",(int)coordptrAux); #endif // deallocate_table_list(interplist); deallocate_table_list(interplist); } void finite_newtonx() { result.height = round((float)original.height * mult * 0.01); result.width = round((float)original.width * mult * 0.01); printf("result height: %u\n",result.height); printf("result width: %u\n",result.width); float actualMultHeight = ((float)result.height)/((float)original.height); float actualMultWidth = ((float)result.width)/((float)original.width); printf("ActualMultHeight %f\n",actualMultHeight); printf("ActualMultWidth %f\n",actualMultWidth); int i,j = 0; // TA CORRETO ISSO? char** ? result.data = (unsigned char**)malloc(sizeof(char**) * result.height); int *neighborRows = (int*)malloc(sizeof(int) * quantos); int *neighborCols = (int*)malloc(sizeof(int) * quantos); //P/ cada linha // FiniteTable *table; for(i = 0; i < result.height; i++){ result.data[i] = (unsigned char*)malloc(sizeof(char) * result.width); float y = ((((float)i)+1.0)/actualMultHeight)-1.0; nearest_neighbors(y,0,original.height-1,quantos,neighborRows); for(j = 0; j < result.width;j ++){ float x = ((((float)j)+1.0)/actualMultWidth)-1.0; nearest_neighbors(x,0,original.width-1,quantos,neighborCols); //Para cada Linha interpolate2D(&(result.data[i][j]),&x,&y,neighborRows,neighborCols); } } free(neighborRows); free(neighborCols); } void finitediffx() { ftl->length = original.height; cout << "ftl.length "<<ftl->length <<"\n"; int i,j = 0; FiniteTable *tables = ftl->tables; for(i = 0; i < ftl->length; i++){ //Para cada linha da imagem original tables[i].length = original.width; FiniteTableRow *rows = tables[i].row; for(j = 0; j < tables[i].length; j++){ rows[j].length = tables[i].length; rows[j].column[0].value = (float)original.data[i][j]; rows[j].column[0].valid = 1; } for(int j = 1; j < rows[i].length; j++){ for(int k = 0; k < rows[j].length-j; k++){ rows[k].column[j].value = rows[k+1].column[j-1].value - rows[k].column[j-1].value; rows[k].column[j].valid = 1; } } } #ifdef DEBUG for(int i = 0; i < ftl->length; i++){ FiniteTable table = ftl->tables[i]; printf("####FiniteTable %d #####\n\n",i); for(int j = 0; j < table.length; j++){ FiniteTableRow row = table.row[j]; for(int k = 0; k < row.length; k++){ FiniteTableValue tablevalue = row.column[k]; if(tablevalue.valid == 1) printf("[%f,%d]",tablevalue.value,tablevalue.valid); // printf("....\n"); // else // printf("0\n"); } printf("\n"); } } #endif } int main(int argc, const char **argv) { if(argc < 4){ cout << "./app <imagem.png> <grau> <percentage>\n"; return -1; } string filename = argv[1]; quantos = atoi(argv[2])+1; mult = atof(argv[3]); cout << "mult: " << mult <<"\n"; original = ImageData(); int i = readImage(filename); if(i == -1){ cout << "Error, please check the information given and try again\n"; return -1; }else{ cout << "Ok, loaded image information in memory.\n"; #ifdef DEBUG printOriginal(); #endif } result = ImageData(); ftl = allocate_table_list(original.width,original.width,original.height); finitediffx(); #ifdef DEBUG printFiniteTablex(); #endif // finite_newton(); finite_newtonx(); #ifdef DEBUG printResult(); #endif writeOriginal(); writeResult(); for(int i = 0; i < original.height; i++){ // for(int j = 0; j < original.width; j++) unsigned char* originalRow = original.data[i]; // free(original.data[i]); free(originalRow); } free(original.data); for(int i = 0; i < result.height; i++){ // for(int j = 0; j < result.width; j++) unsigned char* resultRow = result.data[i]; // free(result.data[i]); free(resultRow); } free(result.data); for(int i = 0; i < ftl->length; i++){ FiniteTable table = ftl->tables[i]; for(int j = 0; j < table.length; j++){ FiniteTableRow row = table.row[j]; free(row.column); // for(int k = 0; k < row.length; k++){ // FiniteTableValue column = row.column[k]; // free(column); // } } free(table.row); } free(ftl->tables); free(ftl); }
true
b78eac98b09d25184135213a43e36a068f77a4b2
C++
tac-kit/LeetCodeCpp
/1143-Longest-Common-Subsequence.cpp
UTF-8
962
3.21875
3
[]
no_license
/* Solution 1: DP */ #include<iostream> #include<vector> #include<string> #include<algorithm> using namespace std; class Solution { public: int longestCommonSubsequence(string text1, string text2) { vector<vector<int>> dp(text2.length()+1, vector<int>(text1.length()+1, 0)); for (int idx2=0; idx2<text2.length(); ++idx2) { for (int idx1=0; idx1<text1.length(); ++idx1) { if (text1[idx1] == text2[idx2]) { dp[idx2+1][idx1+1] = dp[idx2][idx1] + 1; }else { dp[idx2+1][idx1+1] = max({dp[idx2][idx1+1], dp[idx2][idx1], dp[idx2+1][idx1]}); } } } return dp[text2.length()][text1.length()]; } }; int main() { Solution s; cout << s.longestCommonSubsequence("abcde", "ace") << endl; cout << s.longestCommonSubsequence("abc", "abc") << endl; cout << s.longestCommonSubsequence("abc", "def") << endl; }
true
6c3614b756f73d2efd200d9126d65d8f2d60f564
C++
shreyaasridhar/SimpleCodes
/Random/Maximum sum.cpp
UTF-8
896
2.59375
3
[]
no_license
\\Maximum sum such that no two elements are adjacent #include <bits/stdc++.h> #define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end))) #define printA(s) for (auto& it: s) cout << it << ' '; #define what(x) cout<< #x << " is " << x << endl; #define mp make_pair #define eb emplace_back #define ff first #define ss second using namespace std; typedef long long ll; typedef vector< pair < int , int > > vpii; typedef vector < int > vi; typedef vector < ll > vll; #define all(v) v.begin(),v.end() void _main(); int main() {cin.tie(0);ios::sync_with_stdio(false); _main(); return 0; } void _main(){ int x; vi a; while(cin>>x) a.emplace_back(x); int incl=a[0],exc=0,temp; for (int i=1;i<a.size();i++){ temp=(incl>exc)?incl:exc; incl=exc+a[i]; exc=temp; } cout<<((incl>exc)?incl:exc); }
true
88b2b28f0dd740e77e5ea76a11a36aed3819f8b7
C++
Lbrewbaker/SchoolProjects
/CS161/Projects/Final - Library Simulator/Library.cpp
UTF-8
9,552
3.15625
3
[]
no_license
/******************************** Author: Luke Brewbaker Date: 11/28/14 Modified: 11/28/14 File: Overview: Input: Output: *******************************/ #include "Library.h" #include "Book.h" #include "Patron.h" #include <string> #include <iostream> #include <vector> #include <iomanip> using namespace std; //Default Constructor Library::Library() { currentDate = 0; //vector<Book> holdings; //vector<Patron> members; holdings.reserve(100); members.reserve(100); } //Overload Constructor Library::Library(int dcurrent) { currentDate = dcurrent; } //Destructor Library::~Library(){}; //Current date int Library::getCurrentDate(){return currentDate;} //Set current date void Library::setCurrentDate(int dcurrent) { cout << "What would you like to set the current date too? (Single numbers only) "; cin >> dcurrent; currentDate = dcurrent; } void Library::incrementCurrentDate(int dcurrent) { Book *b; //set the current date up int incdate; cout << "How many days would you like to increment the date? "; cin >> incdate; dcurrent = incdate + dcurrent; double fine = incdate * DAILY_FINE; //check for checked out books for (int i = 0; i < members.size(); i++) { members[i].amendFine(fine); } } //Fill my books void Library::addBook() { string t, a, idc; locale location; //prompt for book info cout << "What is the title of the book? "; cin >> t; cout << "Who is the author of the book? "; cin >> a; cout << "What is the ID code for the book? "; cin >> idc; //add to holdings vector Book newBook(idc, t, a); holdings.push_back(newBook); } //Add member void Library::addMember() { string idn, n; double fine; cout << "What is the name of the new member? "; cin >> n; //enter the user ID number and check if it is used bool usedid = true; cout << "What is your ID number? "; cin >> idn; //set fine to 0 fine = 0; //adds to members vector Patron newMember(idn, n, fine); members.push_back(newMember); } //Check out book void Library::checkOutBook(string patronID, string bookID) { Patron *p; //patron pointer Book *book; bool goodMember = false; bool goodTitle = false; string pid, bid; locale location; //int dcurrent; //Check if member id is correct do { cout << "What is your memberID? "; cin >> pid; for(int i = 0; i < members.size(); i ++) { if(pid == members[i].getIdNum()) { //p = members[i].getIdNum(); //sets P to the ID number specified, if that number is valid goodMember = true; } else cout << "That is not a valid ID number, please try again. " << endl; } } while (!goodMember); //Check if the book title is correct do { cout << "What is the ID of the book you would like? "; cin >> bid; for(int i = 0; i < holdings.size(); i ++) { if(holdings[i].getIdCode() == bid) { //book = holdings[i]; goodTitle = true; } else cout << "There are no books with that ID code. Please enter another. " << endl; } } while (!goodTitle); //check if book checked out bool bookchecked = false; for(int i = 0; i<holdings.size(); i ++) { if (bid == holdings[i].getIdCode()) if (holdings[i].getLocation() == CHECKED_OUT) { cout << "That book is currently checked out to "; bookchecked = true; } } //check if book reserved bool booknotreserved = true; for(int i = 0; i<holdings.size(); i ++) { if (bid == holdings[i].getIdCode()) if (holdings[i].getLocation() == ON_HOLD) { cout << "That book is currently reserved."; booknotreserved = false; } } if (goodMember == true && goodTitle == true && bookchecked == true && booknotreserved == true) { for(int i = 0; i < members.size(); i++) { if (bid == members[i].getIdNum()) { book->setCheckedOutBy(p); //set checked out by book->setLocation(CHECKED_OUT); //set book to checked out book->setDateCheckedOut(currentDate);//set current date p->addBook(book); //adds book to Patrons checked out books } } } cout << "\n\nThank you for using our Library. " << endl; } void Library::viewPatrons() { for(int i = 0; i < members.size(); i ++) { cout << "Member name: " <<members[i].getName() << endl; cout << "Member ID Number: " << members[i].getIdNum() << endl; } } void Library::viewBooks() { //loop holdings vector to print books for (int i = 0; i < holdings.size(); i ++) { cout << "Book title: " << holdings[i].getTitle() << endl; cout << "Book Author: " << holdings[i].getAuthor() << endl; cout << "Book ID Number: " << holdings[i].getIdCode() << endl; cout << "Location: " << holdings[i].getLocation() << endl; } } void Library::viewPatronInfo(string patronID) { Patron *p;//patron pointer bool ispatron = false; cout << "Please enter the ID of the patron you would like to view: "; cin >> patronID; do { for (int i = 0; i < members.size(); i ++) { if (patronID == members[i].getIdNum()) { cout << "Member name: " << members[i].getName() << endl; cout << "Member ID: " << members[i].getIdNum() << endl; cout << "Fine amount: " << members[i].getFineAmount() << setprecision(2) << endl; ispatron = true; } else cout << "No patron by that ID code. Please try again." << endl; } } while (ispatron = false); } void Library::viewBookInfo(string bookID) { bool isbook = false; cout << "Please enter the ID of the book you would like to display info on " << endl; cin >> bookID; do { //loop holdings vector to print specific book info for (int i = 0; i < holdings.size(); i ++) { if (bookID == holdings[i].getIdCode()) { cout << "Book title: " << holdings[i].getTitle() << endl; cout << "Book Author: " << holdings[i].getAuthor() << endl; cout << "Book ID Number: " << holdings[i].getIdCode() << endl; cout << "Book location: " << holdings[i].getLocation() << endl; isbook = true; } else cout << "Invalid ID, please try again. " << endl; } } while (!isbook); } void Library::requestBook (string patronID, string bookID) { Patron *p; Book *b; bool goodid = false; bool goodbook = false; //enter book id cout << "What book ID would you like to check out? "; cin >> bookID; for (int i = 0; i < holdings.size(); i++) if (bookID == holdings[i].getIdCode()) goodbook = true; //if book is in the library return true bool if (goodbook = false) cout << "That book is not in the library. " << endl; //enter patron id cout << "What is your user ID? "; cin >> patronID; for (int i = 0; i < members.size(); i++) if (patronID == members[i].getIdNum()) goodid = true; if (goodid = false) cout << "There is not member by that number. " << endl; //check if book on hold bool bookavail = true; for (int i = 0; i < holdings.size(); i ++) { if (holdings[i].getLocation() == ON_HOLD) { bookavail = false; } } //if all bools = true set book on hold. if (goodid == true && goodbook == true && bookavail == true) { b->setLocation(ON_HOLD); b->setRequestedBy(p); cout << "Your requested book is now on hold" << endl; } } void Library::returnBook(string bookID) { bool bookgood = false; //string bookID; cout << "What book would you like to return? "; cin >> bookID; //check if book id is good for (int i = 0; i < holdings.size(); i ++) { if (holdings[i].getIdCode() == bookID) { bookgood = true; holdings[i].setLocation(ON_SHELF); cout << "Your book is now checked in. " << endl; } else if (holdings[i].getIdCode() != bookID) cout << "There is no book by that ID Code. " << endl; } } void Library::payFine(string patronID, double fine) { Patron *p; //patron pointer bool goodpatron = false; cout << "Please enter your ID: "; cin >> patronID; for (int i = 0; i < members.size(); i++) { if (patronID == members[i].getIdNum()) { goodpatron = true; fine = 0; p->amendFine(fine); cout << "Thank you for paying your fine. " << endl; } } if (goodpatron = false) { cout << "That is not a valid ID. " << endl; } }
true
7fe4c0ffb05a5ce3bb597dd43f1f53e30ace8937
C++
gauthiier/Plank
/software/apps/Music/Up_and_down/Up_and_down.ino
UTF-8
1,386
2.65625
3
[]
no_license
// This needs to be in all sketches at the moment #include <stdint.h> // The Music and Midi objects are automatically instantiated when the header file is included. // Make calls to the Music and Midi objects with "Music.function(args)" and "Midi.function(args)" // You still need to call Music.init() and Midi.init() in the setup() function below. #include <Music.h> // variables for this sketch boolean noteIsOn = false; int n = 0; int dir = 1; int rootNote = 48; int note[] = {0,2,3,5,7,9,10,12,14}; long time = 0; long lastTime = 0; long beatTime = 100; void setup() { // We initialise the sound engine by calling Music.init() which outputs a tone Music.init(); // enabling the envelope lets us define an gain envelope for the synth // without having to specify it in our loop() or physics code. Music.enableEnvelope(); Music.setAttack(0x00FF); Music.setDecay(0x0008); Music.setSustain(0x00FF); Music.setRelease(0x0008); } void loop() { // This short routine loops note over and over again time = millis(); if(time - lastTime > beatTime) { if(!noteIsOn) { Music.noteOn(rootNote+note[n]); noteIsOn = true; n = n + dir; if(n > 7) { dir = -1; } else if(n < 1) { dir = 1; } } else { Music.noteOff(); noteIsOn = false; } lastTime = time; } }
true
81a9672c9e14dbdb645b6c99259c3b08a87a93b7
C++
nikhilyadv/UVA
/Problem Solving Paradigms/Dynamic Programming/10684 - The jackpot.cpp
UTF-8
690
2.640625
3
[]
no_license
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); int n; while(cin >> n , n){ vector<int> a(n); for(int i = 0 ; i < n ; i++) cin >> a[i]; int sum = 0, ans = 0; for(int i = 0 ; i < n ; i++){ sum += a[i]; if (sum >= ans) ans = sum; if (sum <= 0) sum = 0; } if(ans == 0) cout << "Losing streak.\n"; else cout << "The maximum winning streak is " << ans << ".\n"; } return 0; }
true
c5305e1d1eb2c543aacde22ca6b8afb855efa7fb
C++
dereksodo/codeforces
/954E_my_understand.cpp
UTF-8
857
2.875
3
[]
no_license
#include <iostream> #include <algorithm> #include <cmath> #include <cstdio> using namespace std; typedef struct{ double a; double t; }tap; bool cmp(tap a,tap b) { return a.t < b.t; } int main() { int n,T; cin>>n>>T; tap tp[n]; for(int i = 0;i < n; ++i) { cin>>tp[i].a; } double cur = 0; for(int i = 0;i < n; ++i) { cin>>tp[i].t; tp[i].t -= T; cur += tp[i].a * tp[i].t; } if(cur < 0)//全部装入如果小于零,装入温度高的水,如果大于零则先装入温度低的水 { for(int i = 0;i < n; ++i) { tp[i].t = T-tp[i].t; } } sort(tp,tp + n,cmp); double sum = 0,ans = 0; //value = (ai*xi)/xi for(int i = 0;i < n; ++i) { if(sum + tp[i].a * tp[i].t <= 0) { sum += tp[i].a * tp[i].t; ans += tp[i].a; } else { ans -= sum / (tp[i].t); break; } } printf("%.12lf\n",fabs(ans)); return 0; }
true
ef9155deef09826e3e4595a7ad61a34f28371694
C++
jcnast/SimpleVersus
/Collision.h
UTF-8
655
2.9375
3
[ "Zlib", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "Libpng", "LicenseRef-scancode-unknown-license-reference", "IJG", "libtiff" ]
permissive
#ifndef COLLISION_H #define COLLISION_H // include game objects // include necessary libraries class Object; class Collision{ // collision objects Object *obj_1; Object *obj_2; // collision location float xPos; float yPos; // collision velocity float obj_1_xVel; float obj_1_yVel; float obj_2_xVel; float obj_2_yVel; public: // constructor Collision(Object *obj_1, Object *obj_2, float xPos, float yPos,\ float obj_1_xVel, float obj_1_yVel, float obj_2_xVel, float obj_2_yVel); ~Collision(); // get collision information float GetXPos(); float GetYPos(); float GetXVel(Object *object); float GetYVel(Object *object); }; #endif
true
5360f0b93664b940e120fe4c3122f76e988746b0
C++
lizhiwill/LeetCodeStudy
/算法/1002_查找常用字符/Solution01.cpp
UTF-8
1,519
2.625
3
[]
no_license
class Solution { public: vector<string> commonChars(vector<string>& A) { vector<string> vs ; map<char,int> mci ; vector<map<char,int>> vmci ; int len = A.size() ; for(char i = 'a' ; i <= 'z';i++) { mci[ (char)('a'+i) ] = 0; } /*统计*/ for(int i = 0 ; i < len ; i++) { vmci.push_back(mci); for(int j=0;j<A[i].size();j++) { vmci[i][A[i][j]] += 1; } } /*找交集*/ for( char i='a' ; i<= 'z' ; i++) { int minCount = vmci[0][i]; for(int j = 1 ; j < A.size(); j++) { if(minCount > vmci[j][i]) { minCount = vmci[j][i]; } } for(int j = 0 ; j < minCount ; j++) { vs.push_back(string(1,i)); } } /*返回*/ return vs; } }; /* 执行结果: 通过 显示详情 执行用时 :52 ms, 在所有 cpp 提交中击败了8.64%的用户 内存消耗 :20.1 MB, 在所有 cpp 提交中击败了5.22%的用户 */
true
b927728810b2b373ef9c1a6a4b3324b07d0482e1
C++
SamAlexe/OpenGl-Texture-Program
/Model/ model.h
UTF-8
736
2.5625
3
[]
no_license
#ifndef __MODEL_H__ #define __MODEL_H__ class model { public: model(string modelFilename, string textureFilename); void initrendering(); void drawscene(); void handlekeypress(unsigned char key, int x, int y); void handleResize(int w, int h); float getCenterX() { return m_CenterX; } float getCenterY() { return m_CenterY; } float getCenterZ() { return m_CenterZ; } void SetCenterX(float x) { m_CenterX = x; } void SetCenterY(float y) { m_CenterY = y; } void SetCenterZ(float z) { m_CenterZ = z; } GLuint loadTexture(string filename); private: string m_ModelFilename; string m_TextureName; GLuint textureId; float m_CenterX, m_CenterY, m_CenterZ; }; #endif
true
392c09ead1cd9c374c6000fc6e60b9d1f2bb8f85
C++
Algue-Rythme/ACM
/louisB_10616.cpp
UTF-8
2,337
2.546875
3
[]
no_license
#include <algorithm> #include <cstdint> #include <iostream> #include <vector> #define _DEBUG_ using namespace std; const unsigned int nbNumbersMax = 200; const unsigned int nbChoosenMax = 10; const int64_t DMax = 20; uint64_t dyna[nbNumbersMax+1][nbChoosenMax+1][DMax+1]; int64_t numbers[nbNumbersMax+1]; int main() { cin.tie(0); ios::sync_with_stdio(false); unsigned int nbNumbers, nbQueries; unsigned int nbTests = 1; while (cin >> nbNumbers >> nbQueries) { if (nbNumbers == 0 && nbQueries == 0) return 0; cout << "SET " << nbTests << ":\n"; nbTests += 1; for (unsigned int number = 0; number < nbNumbers; ++number) { cin >> numbers[number]; } for (unsigned int query = 1; query <= nbQueries; ++query) { int64_t D; unsigned M; cin >> D >> M; for (unsigned int n = 0; n <= nbNumbers; ++n) { for (unsigned int m = 0; m <= nbChoosenMax; ++m) { for (int64_t d = 0; d < DMax; ++d) { dyna[n][m][d] = 0; } } } for (unsigned int n = 0; n <= nbNumbers; ++n) dyna[n][0][0] = 1; for (unsigned int n = 1; n <= nbNumbers; ++n) { #ifdef DEBUG cout << "n = " << n << " | " << numbers[n-1] << "\n"; #endif for (unsigned int m = 1; m <= min(M, n); ++m) { #ifdef DEBUG cout << "m = " << m << " | "; #endif for (int64_t d = 0; d < D; ++d) { uint64_t dontTakeIt = dyna[n-1][m][d]; int64_t pred = D + d + (numbers[n-1]%D); uint64_t takeIt = dyna[n-1][m-1][pred % D]; dyna[n][m][d] += (dontTakeIt + takeIt); #ifdef DEBUG cout << dyna[n][m][d] << " "; #endif } #ifdef DEBUG cout << "\n"; #endif } } uint64_t answer = dyna[nbNumbers][M][0]; cout << "QUERY " << query << ": " << answer << "\n"; } } }
true
3fbd779df2a0cbc8af66aa6f572d266c8f9296a2
C++
0xDkXy/GenshinWaterFriendsTeamTemplate
/女生自用板子拆分/LCA.cpp
UTF-8
2,008
2.8125
3
[]
no_license
#include "Headers.cpp" #include "foreach.cpp" /* 从1到n都可用,0是保留字 5b4026638a0f469f91d26a4ff0dee4bf */ struct LCA { std::vector<std::vector<int>> fa; std::vector<int> dep, siz; std::vector<std::vector<int>> &E; /* 构造函数分配内存,传入边数组 */ LCA(int _siz, std::vector<std::vector<int>> &_E) : E(_E) { _siz++; fa.assign(_siz, vector<int>(log2int(_siz) + 1, 0)); dep.assign(_siz, 0); siz.assign(_siz, 0); } void dfs(int x, int from) { fa[x][0] = from; dep[x] = dep[from] + 1; siz[x] = 1; for (auto i : range(1, log2int(dep[x]) + 1)) fa[x][i] = fa[fa[x][i - 1]][i - 1]; for (auto &i : E[x]) if (i != from) { dfs(i, x); siz[x] += siz[i]; } } /* 传入边 */ void prework(int root) { // dep[root] = 1; dfs(root, 0); siz[0] = siz[root]; // for (auto &i : E[root]) // dfs(i, root); } /* LCA查找 */ int lca(int x, int y) { if (dep[x] < dep[y]) swap(x, y); while (dep[x] > dep[y]) x = fa[x][log2int(dep[x] - dep[y])]; if (x == y) return x; for (auto k : range(log2int(dep[x]), -1, -1)) if (fa[x][k] != fa[y][k]) x = fa[x][k], y = fa[y][k]; return fa[x][0]; } /* 拿x所在father的子树的节点数 */ int subtree_size(int x, int father) { if (x == father) return 0; for (auto i : range(fa[x].size() - 1, -1, -1)) x = (dep[fa[x][i]] > dep[father] ? fa[x][i] : x); return siz[x]; } /* 判断tobechk是否在from -> to的路径上 */ bool on_the_way(int from, int to, int tobechk) { int k = lca(from, to); return ((lca(from, tobechk) == tobechk) or (lca(tobechk, to) == tobechk)) and lca(tobechk, k) == k; } };
true
d20b0871f56896eee2c29ecf5a1cbc83fd9004d0
C++
JuliaNortman/LabWorksSem2
/LabWork2/Lab2/Source code/matrix.cpp
UTF-8
1,632
2.75
3
[]
no_license
#include "matrix.h" #include "ui_matrix.h" Cell::Cell() { //set cell styles setFixedSize(35, 28); setValidator(new QIntValidator(-1000, 1000)); setStyleSheet("QLineEdit { border: 2px solid gray;" "border-radius: 5px;}"); setText("0"); } Matrix::Matrix(const int &dim, QWidget *parent) : QDialog(parent), ui(new Ui::Matrix), n(dim) { //set window size and style ui->setupUi(this); setWindowTitle("Matrix"); setFixedSize(30 + 41*n + 30, 34*n + 100); ui->OKPushButton->move(30+41*n-80, 34*n+100-28); ui->error->move(30+20*n-48, 3); //create the input fields cells.resize(n); for(int i = 0; i < n; ++i) { cells[i].resize(n); for(int j = 0; j < n; ++j) { cells[i][j] = new Cell; ui->matrix->addWidget(cells[i][j], i, j); } } } Matrix::~Matrix() { //delete cells for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { delete cells[i][j]; } } delete ui; } void Matrix::warning() { ui->error->setText("Please, fill all cells"); } void Matrix::on_OKPushButton_clicked() { matr.resize(n); for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { /*if cell is empty*/ if(cells[i][j]->text() == "") { warning(); //show warning return; } matr[i].resize(n); matr[i][j] = cells[i][j]->text().toInt(); } } this->close(); emit(matrix(matr)); }
true
050ecf68483bd9bf8391008eac9e625bc965c10b
C++
derek-zr/leetcode
/Solution/352-data-stream-as-disjoint-intervals/data-stream-as-disjoint-intervals.cpp
UTF-8
1,698
3.4375
3
[]
no_license
// Given a data stream input of non-negative integers a1, a2, ..., an, ..., summarize the numbers seen so far as a list of disjoint intervals. // // For example, suppose the integers from the data stream are 1, 3, 7, 2, 6, ..., then the summary will be: // // // [1, 1] // [1, 1], [3, 3] // [1, 1], [3, 3], [7, 7] // [1, 3], [7, 7] // [1, 3], [6, 7] // // //   // // Follow up: // // What if there are lots of merges and the number of disjoint intervals are small compared to the data stream's size? // class SummaryRanges { public: SummaryRanges() {} void addNum(int val) { vector<int> newInterval{val, val}; //找相交的intervals,overlap表示相交的数目 int i = 0, overlap = 0, n = intervals.size(); for (; i < n; ++i) { if (newInterval[1] + 1 < intervals[i][0]) break; //不相交 if (newInterval[0] <= intervals[i][1] + 1) { newInterval[0] = min(newInterval[0], intervals[i][0]); newInterval[1] = max(newInterval[1], intervals[i][1]); ++overlap; } } //去除相交的部分 if (overlap > 0) { intervals.erase(intervals.begin() + i - overlap, intervals.begin() + i); } //插入新合并的部分 intervals.insert(intervals.begin() + i - overlap, newInterval); } vector<vector<int>> getIntervals() { return intervals; } private: vector<vector<int>> intervals; }; /** * Your SummaryRanges object will be instantiated and called as such: * SummaryRanges* obj = new SummaryRanges(); * obj->addNum(val); * vector<vector<int>> param_2 = obj->getIntervals(); */
true
a87dbf14078e5fc4e97ff2d337ab42f3cedc3ac5
C++
bell0136/TIL
/C12/pointer1.cpp
UTF-8
165
2.546875
3
[]
no_license
#include <stdio.h> int main(void) { const char* strarr[3] = { "simple","string","array" }; printf("%p\n%p\n%p", &strarr[0], &strarr[1], &strarr[2]); return 0; }
true
dad0b133c7b5b5003a0cae87201b23408cb3328a
C++
kingsmad/leetcode_2017
/131.palindrome-partitioning.cpp
UTF-8
1,642
2.640625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; const int maxn = 1e3 + 10; class Solution { map<string, vector<vector<string>>> ms; vector<vector<int>> pal; public: vector<vector<string>> partition(string s) { ms.clear(); int n = s.size(); pal = vector<vector<int>>(n + 1, vector<int>(n + 1, 0)); calc_pal(s); return calc(0, n, s); } void calc_pal(const string& s) { int n = s.size(); for (int i = 0; i < n; ++i) pal[i][i] = 1; for (int i = 0; i < n; ++i) pal[i][i + 1] = 1; for (int es = 2; es <= n; ++es) { for (int i = 0; i + es <= n; ++i) { if (s[i] != s[i + es - 1]) pal[i][i + es] = 0; else pal[i][i + es] = pal[i + 1][i + es - 1]; } } } vector<vector<string>> calc(int st, int ed, const string& s) { if (st == ed) return vector<vector<string>>(); const string& sub = s.substr(st, ed - st); if (ms.count(sub)) return ms.at(sub); vector<vector<string>> ans; if (pal[st][ed]) ans.push_back({sub}); /*handle whole interval independently*/ for (int i = st + 1; i < ed; ++i) { if (pal[i][ed]) { vector<vector<string>> r = calc(st, i, s); for (vector<string>& vs : r) { vs.push_back(s.substr(i, ed - i)); ans.push_back(vs); } } } ms.emplace(sub, ans); return ans; } }; #ifdef ROACH_ONLINE_JUDGE int main(int, char**) { Solution sol; string s; cin >> s; vector<vector<string>> ans = sol.partition(s); for (const vector<string>& vs : ans) { for (const string& s : vs) { cout << s << " "; } cout << endl; } } #endif
true
4daabbd5b5dc59e6c9f20658d15c6798077b672c
C++
memory4963/CCpp2016
/practices/cpp/level1/p04_cppScoreManagement/Student.h
UTF-8
871
3.453125
3
[]
no_license
#pragma once #include<iostream> #include<string> class Student { public: Student(); ~Student(); void set_name(std::string str); void set_ID(int ID); void set_score(int score); std::string get_name(); int get_ID(); int get_score(); private: std::string name; int ID; int score; }; Student::Student() { std::string str; int his_ID; std::cout << "Please input the name and ID of the student" << std::endl << ":"; std::cin >> str >> his_ID; set_name(str); set_ID(his_ID); } Student::~Student() { } inline void Student::set_name(std::string str) { name = str; } inline void Student::set_ID(int ID) { Student::ID = ID; } inline void Student::set_score(int score) { Student::score = score; } inline std::string Student::get_name() { return name; } inline int Student::get_ID() { return ID; } inline int Student::get_score() { return score; }
true
717f91937ff4e107a3429e0b4cdaf33628bacb51
C++
ddouup/COMP2012H
/project4/brute.cpp
UTF-8
1,250
3.375
3
[]
no_license
#include "brute.h" #include <algorithm> using namespace std; brute::brute(){} brute::brute(const vector<point> p) :points(p) {} brute::~brute(){} vector<vector<point> > brute::searchColinearPoints() { vector<vector<point> > lines; vector<point> line; sort(points.begin(), points.end()); int n = points.size(); int i, j, p, q; for (i = 0; i < n - 3; i++) { for (j = i + 1; j < n - 2; j++) { for (p = j + 1; p < n - 1; p++) { for (q = p + 1; q < n; q++) { if (check(i, j, p, q)) { line.clear(); line.push_back(points[i]); line.push_back(points[j]); line.push_back(points[p]); line.push_back(points[q]); lines.push_back(line); } } } } } print(lines); return lines; } bool brute::check(int i, int j, int p, int q) { double slope1 = points[j].getSlope(points[i]); double slope2 = points[p].getSlope(points[i]); double slope3 = points[q].getSlope(points[i]); if (slope1 == slope2 && slope1 == slope3) return true; else return false; } void brute::print(vector<vector<point> > p) { int i,j; for (i = 0; i < p.size(); i++){ cout << p[i].size() << ":"; for (j = 0; j < p[i].size(); j++){ if (j != 0) cout << "->"; cout << p[i][j]; } cout << endl; } }
true
41677105a7c767d1f5c30bdb18e549e55466ab45
C++
anniepap/projject-1
/Part2/ArrayStack.cpp
UTF-8
443
3.375
3
[]
no_license
#include "ArrayStack.h" Stack::Stack(uint32_t size_of_stack): size_of_stack(size_of_stack), size(0){ array= new uint32_t[size_of_stack]; } Stack::~Stack(){ delete[] array; } void Stack::push(uint32_t element){ array[size++]=element; } uint32_t Stack::pop(){ if (size==0){ return NONE; } return array[--size]; } uint32_t Stack::top_(){ if (size==0) return NONE; return array[size-1]; } bool Stack::empty(){ return size==0; }
true
43ddb117ec89162316e7256df9ab105f387234c9
C++
ititandev/onlinejudge
/DSA/testcase/TEST/program/sort.cpp
UTF-8
708
2.984375
3
[]
no_license
#include "sort.h" #include <iostream> #include <fstream> #include <string> #include <sstream> #include <iomanip> using namespace std; int N=-1; double *arr; void swap(double& a, double& b) { double tmp=a; a=b; b=tmp; } void Input(fstream& f) { string str; getline(f,str); N=stoi(str); arr=new double[N]; getline(f,str); stringstream ss(str); for(int i=0;i<N;++i) { ss>>arr[i]; } } void Output(fstream& f) { for(int i=0;i<N;++i) { f<<setw(8)<<setprecision(4)<<arr[i]; if((i+1)%5==0) f<<endl; } } void sort() { int i, j; double temp; for (i = 1; i < N; i++) { j = i - 1; temp = arr[i]; while(arr[j] > temp && j >= 0) { arr[j+1] = arr[j]; j--; } arr[j+1] = temp; } }
true
64367e7d6a1ad15c60107330d3b48db8a2bdbab7
C++
jensecj/code-challenges
/hackerrank/general-programming/basic-programming/easy-grading-students.cpp
UTF-8
648
3.953125
4
[]
no_license
/* tags: loop, round task: given an array of numbers, if a number is above 38, and is less than 3 from its nearest multiple of 5 (upwards), round the number up to that multiple of 5 */ #include <iostream> #include <vector> using namespace std; int main() { int n; // the number of grades cin >> n; vector<int> grades(n); for (int i = 0; i < n; i++) cin >> grades[i]; for (int i = 0; i < n; i++) { if(grades[i] < 38) continue; for (int j = 0; j < 3; j++) { if((grades[i]+j) % 5 == 0) { grades[i] += j; break; } } } for (int i = 0; i < n; i++) cout << grades[i] << endl; }
true
56893cf3c7b83120c1440c77859da9265e072743
C++
krujeen/C-Programming
/Day01_08_max_n.cpp
UTF-8
265
2.59375
3
[]
no_license
#include <iostream> #include <stdio.h> using namespace std; int main() { int i,n; int x,max_x; cin>>n; cin>>max_x; for (i=2;i<=n;i++) { cin>>x; if (max_x > x) max_x = x; } cout<<max_x; return 0; }
true
d3ce4a8d75241e3bcf7a42b593328eaedc1fd7ee
C++
EidosMedia/infobright-core
/cpp/infobright_jni/com_infobright_NamedPipe.cpp
UTF-8
5,604
2.546875
3
[ "MIT" ]
permissive
#include "jniutils.h" #include <windows.h> #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* * Class: com_infobright_io_WindowsNamedPipe * Method: serverCreate * Signature: (Ljava/lang/String;ZZIJ)J */ JNIEXPORT jlong JNICALL Java_com_infobright_io_WindowsNamedPipe_serverCreate (JNIEnv *env , jclass clazz, jstring jPipeName, jboolean allowWrite, jboolean allowRead, jint bufsize, jlong timeout) { string pipeName = getString(env, jPipeName); // setup access mode DWORD pipeAccess /*= PIPE_ACCESS_DUPLEX*/; if (allowWrite && allowRead) pipeAccess = PIPE_ACCESS_DUPLEX; else if (allowWrite) pipeAccess = PIPE_ACCESS_OUTBOUND; else if (allowRead) pipeAccess = PIPE_ACCESS_INBOUND; /* If you attempt to create multiple instances of a pipe with this flag, creation of the first instance succeeds, but creation of the next instance fails with ERROR_ACCESS_DENIED. Windows 2000/NT: This flag is not supported until Windows 2000 SP2 and Windows XP. */ //pipeAccess |= FILE_FLAG_FIRST_PIPE_INSTANCE; // setup access mode DWORD pipeMode = 0; /* Data is written to the pipe as a stream of bytes. This mode cannot be used with PIPE_READMODE_MESSAGE. */ pipeMode |= PIPE_TYPE_BYTE; /* Data is read from the pipe as a stream of bytes. This mode can be used with either PIPE_TYPE_MESSAGE or PIPE_TYPE_BYTE. */ pipeMode |= PIPE_READMODE_BYTE; /* Blocking mode is enabled. When the pipe handle is specified in the ReadFile, WriteFile, or * ConnectNamedPipe function, the operations are not completed until there is data to read, * all data is written, or a client is connected. Use of this mode can mean waiting indefinitely * in some situations for a client process to perform an action. */ pipeMode |= PIPE_WAIT; // now create the pipe! HANDLE hPipe; hPipe = CreateNamedPipe(pipeName.c_str(), pipeAccess, pipeMode, PIPE_UNLIMITED_INSTANCES, // max. instances bufsize, // output buffer size bufsize, // input buffer size (DWORD) timeout, // client time-out NULL); // no security attribute if (hPipe == INVALID_HANDLE_VALUE) { throwJavaExceptionFromLastWindowsError(env, "java/io/IOException", "Could not create named pipe: "); } return (jlong) hPipe; } /* * Class: com_infobright_io_WindowsNamedPipe * Method: fileRead * Signature: (J[BII)I */ #define BUFSIZE 1024 JNIEXPORT jint JNICALL Java_com_infobright_io_WindowsNamedPipe_fileRead (JNIEnv *env, jclass clazz, jlong hPipe, jbyteArray bytes, jint offset, jint len) { DWORD bytesRead = 0; signed char stackBuf[BUFSIZE]; int maxlen = env->GetArrayLength(bytes); if (offset+len>maxlen) len=maxlen-offset; // if the target length is less than our default (stack-allocated) buffer, then // dynamically allocate a new buffer to use. signed char* buf; if (len > BUFSIZE) buf = new signed char[len]; else buf = stackBuf; if (!ReadFile((HANDLE) hPipe, buf, len, &bytesRead, NULL)) { throwJavaExceptionFromLastWindowsError(env, "java/io/IOException", "Named pipe read failed: "); } else { env->SetByteArrayRegion(bytes, offset, bytesRead, (const jbyte*) buf); } if (len > BUFSIZE) delete [] buf; // delete the buffer if we had to allocate it. return (jint) bytesRead; } /* * Class: com_infobright_io_WindowsNamedPipe * Method: fileWrite * Signature: (J[BII)I */ JNIEXPORT jint JNICALL Java_com_infobright_io_WindowsNamedPipe_fileWrite (JNIEnv *env, jclass clazz, jlong hPipe, jbyteArray bytes, jint offset, jint len) { DWORD bytesWritten; signed char stackBuf[BUFSIZE]; int maxlen = env->GetArrayLength(bytes); if (offset+len>maxlen) len=maxlen-offset; // if the target length is less than our default (stack-allocated) buffer, then // dynamically allocate a new buffer to use. signed char* buf; if (len > BUFSIZE) buf = new signed char[len]; else buf = stackBuf; // move the bytes from the java array to our local one env->GetByteArrayRegion(bytes, offset, len, (jbyte*) buf); if (!WriteFile((HANDLE) hPipe, buf, len, &bytesWritten, NULL)) { throwJavaExceptionFromLastWindowsError(env, "java/io/IOException", "Named pipe write failed: "); } if (len > BUFSIZE) delete [] buf; // delete the buffer if we had to allocate it. return bytesWritten; } /* * Class: com_infobright_io_WindowsNamedPipe * Method: fileClose * Signature: (J)V */ JNIEXPORT void JNICALL Java_com_infobright_io_WindowsNamedPipe_fileClose (JNIEnv *env, jclass clazz, jlong handle) { if (!CloseHandle((HANDLE) handle)) { throwJavaExceptionFromLastWindowsError(env, "java/io/IOException", "Could not close named pipe: "); } } /* * Class: com_infobright_io_WindowsNamedPipe * Method: clientCreate * Signature: (Ljava/lang/String;)J */ JNIEXPORT jlong JNICALL Java_com_infobright_io_WindowsNamedPipe_clientCreate (JNIEnv *env , jclass clazz, jstring jPipeName) { string pipeName = getString(env, jPipeName); HANDLE hFile = CreateFile(pipeName.c_str(), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if(hFile == INVALID_HANDLE_VALUE) { throwJavaExceptionFromLastWindowsError(env, "java/io/IOException", "Could not open client pipe for writing: "); } return (jlong) hFile; } #ifdef __cplusplus } #endif
true
69079c8462e888e66a91a743be6f4498faf97834
C++
tiger1710/didactic-octo-funicular
/source/c++(c)-code/acmicpc.net/2206.cpp
UTF-8
2,165
2.828125
3
[]
no_license
#include <iostream> #include <vector> #include <queue> #include <algorithm> using namespace std; #define endl '\n' #define ALL(x) (x).begin(), (x).end() #define REP(i, from, to) for (int i = (from); i < (to); i++) using point = tuple<int, int, char>; vector<string> map; vector<vector<vector<int> > > visited; const int dr[4] = { 1, -1, 0, 0 }; const int dc[4] = { 0, 0, -1, 1 }; int N, M; void input(void) { cin >> N >> M; map.resize(N); visited = vector<vector<vector<int> > >(N, vector<vector<int> >(M, vector<int>(2, false))); for (string& row : map) { cin >> row; } } bool condition(const point& p) { int r, c; bool b; tie(r, c, b) = p; return (0 <= r and r < N and 0 <= c and c < M) and not visited[r][c][b] and map[r][c] == '0'; } bool break_condition(const point& p) { int r, c; bool b; tie(r, c, b) = p; return (0 <= r and r < N and 0 <= c and c < M) and not visited[r][c][1] and map[r][c] == '1'; } int bfs(void) { queue<point> q; q.push(make_tuple(0, 0, 0)); visited[0][0][0] = 1; while (not q.empty()) { const point curr = q.front(); q.pop(); int r, c, b; tie(r, c, b) = curr; if (r == N - 1 and c == M - 1) { return visited[r][c][b]; } /* cout << "r, c, b: " << r << ", " << c << ", " << b << endl; cout << "visited[r][c][b]: " << visited[r][c][b] << endl; */ REP (i, 0, 4) { const int nextr = r + dr[i], nextc = c + dc[i], nextb = b; point next(nextr, nextc, nextb); //cout << "nextr, nextc, nextb: " << nextr << ", " << nextc << ", " << nextb << endl; if (condition(next)) { q.push(next); visited[nextr][nextc][nextb] = visited[r][c][b] + 1; } if (not nextb and break_condition(next)) { q.push(point(nextr, nextc, 1)); visited[nextr][nextc][1] = visited[r][c][b] + 1; } } } return -1; } int main(void) { ios_base::sync_with_stdio(false); cin.tie(NULL); input(); cout << bfs() << endl; return 0; }
true
768b392f970092431c6df5587e83681bd1567ca5
C++
ordonezt/vcart
/Arduino/Motores_Serial/Motores_Serial.ino
UTF-8
2,651
2.625
3
[]
no_license
#define X_STEP_PIN 54 #define X_DIR_PIN 55 #define X_ENABLE_PIN 38 #define X_MIN_PIN 3 #define X_MAX_PIN 2 #define Y_STEP_PIN 60 #define Y_DIR_PIN 61 #define Y_ENABLE_PIN 56 #define Y_MIN_PIN 14 #define Y_MAX_PIN 15 #define Z_STEP_PIN 46 #define Z_DIR_PIN 48 #define Z_ENABLE_PIN 62 #define Z_MIN_PIN 18 #define Z_MAX_PIN 19 #define E_STEP_PIN 26 #define E_DIR_PIN 28 #define E_ENABLE_PIN 24 #define Q_STEP_PIN 36 #define Q_DIR_PIN 34 #define Q_ENABLE_PIN 30 #define DELAY_PASO 40 char vectorChar[3]; void setup() { // put your setup code here, to run once: pinMode(X_STEP_PIN , OUTPUT); pinMode(X_DIR_PIN , OUTPUT); pinMode(X_ENABLE_PIN , OUTPUT); pinMode(Y_STEP_PIN , OUTPUT); pinMode(Y_DIR_PIN , OUTPUT); pinMode(Y_ENABLE_PIN , OUTPUT); pinMode(Z_STEP_PIN , OUTPUT); pinMode(Z_DIR_PIN , OUTPUT); pinMode(Z_ENABLE_PIN , OUTPUT); digitalWrite(X_ENABLE_PIN , LOW); digitalWrite(Y_ENABLE_PIN , LOW); digitalWrite(Z_ENABLE_PIN , LOW); digitalWrite(13,HIGH); digitalWrite(X_DIR_PIN , HIGH); digitalWrite(Y_DIR_PIN , HIGH); digitalWrite(Z_DIR_PIN , HIGH); // Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: if(Serial.available()>0){ String str = Serial.readStringUntil('\n'); String cadena=str.substring(4); cadena.toCharArray(vectorChar,3); int n=atoi(vectorChar); switch (str[0]) { case '1': //do something when var equals 1 //Serial.println("Motor 1"); if(str[2]=='1'){ digitalWrite(X_DIR_PIN , HIGH); }else{ digitalWrite(X_DIR_PIN , LOW); } for(int a=0; a<n;a++){ digitalWrite(X_STEP_PIN , HIGH); //Serial.print("va") delay(DELAY_PASO); digitalWrite(X_STEP_PIN , LOW); } Serial.println("<OK>"); break; case '2': Serial.println("Motor 2"); if(str[2]=='1'){ digitalWrite(E_DIR_PIN , HIGH); digitalWrite(Z_DIR_PIN , HIGH); }else{ digitalWrite(E_DIR_PIN , LOW); digitalWrite(Z_DIR_PIN , HIGH); } for(int a=0; a<n;a++){ digitalWrite(E_STEP_PIN , HIGH); digitalWrite(Z_STEP_PIN , HIGH); delay(DELAY_PASO); digitalWrite(E_STEP_PIN , LOW); digitalWrite(Z_STEP_PIN , LOW); } Serial.println("<OK>"); break; case '3': Serial.println("Motor 3"); if(str[2]=='1'){ digitalWrite(Y_DIR_PIN , HIGH); }else{ digitalWrite(Y_DIR_PIN , LOW); } for(int a=0; a<n;a++){ digitalWrite(Y_STEP_PIN , HIGH); delay(DELAY_PASO); digitalWrite(Y_STEP_PIN , LOW); } Serial.println("<OK>"); break; default: // if nothing else matches, do the default // default is optional Serial.println("Error"); break; } } }
true
5e667b546c194574b0d23c2f9833eb03b879a9fc
C++
chubbymaggie/irreg-simd
/spmm-float-and-double/spmm-float/seq/seq.cpp
UTF-8
1,992
2.796875
3
[]
no_license
#include "../tools/csr_loader.h" #include "../tools/fast_hash.h" #include "util.h" #include <atomic> #include <unordered_map> #include <iostream> #include <vector> #include <x86intrin.h> using namespace std; template<class ValueType> Csr<ValueType>* SpMM(const Csr<ValueType>* m1, const Csr<ValueType>* m2, vector<FastHash<int, ValueType>* >& result_map) { cout << "Starting SpMM..." << endl; float a; double before = rtclock(); for (int i = 0; i < m1->num_rows; ++i) { for (int j = m1->rows[i]; j < m1->rows[i+1]; ++j) { int col = m1->cols[j]; ValueType val = m1->vals[j]; for (int k = m2->rows[col]; k < m2->rows[col+1]; ++k) { int col2 = m2->cols[k]; ValueType val2 = m2->vals[k]; ValueType mul = val * val2; a += mul; result_map[i]->Reduce(col2, mul); } } } double after = rtclock(); cout << "a: " << a << endl; cout << RED << "[****Result****] ========> *Serial* time: " << after - before << " secs." << RESET << endl; // Recover csr from hash table. Csr<ValueType>* res = new Csr<ValueType>(result_map, m1->num_rows, m2->num_cols); return res; } int main(int argc, char** argv) { cout << "Using input: " << argv[1] << endl; cout << "Loading input..." << endl; Csr<float>* m1 = CsrLoader<float>::Load(argv[1]); cout << "m1 load done." << endl; cout << "m1 nnz: " << m1->nnz << endl; Csr<float>* m2 = CsrLoader<float>::Load(argv[1]); cout << "m2 load done." << endl; cout << "Total rows: " << m1->num_rows << endl; vector<FastHash<int, float >* > row_results(m1->num_rows); for (auto& v : row_results) { v = new FastHash<int, float>(atoi(argv[2])); } // Do the SpMM computation. Csr<float>* res = SpMM(m1, m2, row_results); cout << "Result size: " << res->nnz << endl; cout << "Done." << endl; // Free row_results. for (auto& v : row_results) { delete v; } delete m1; delete m2; delete res; return 0; }
true
4e0c866bec1374d0bf07cecb0237fb34b312e837
C++
georgerapeanu/c-sources
/A. Quasi-palindrome/main.cpp
UTF-8
273
2.65625
3
[]
no_license
#include <iostream> using namespace std; string a; int main() { cin>>a; int dr=a.size()-1; while(a[dr]=='0'&&dr)dr--; int st=0; while(st<dr) { if(a[st]!=a[dr]){cout<<"NO";return 0;} st++;dr--; } cout<<"YES"; return 0; }
true
6fb8702c99f915d5f56f9a316665b12256bd0a8a
C++
Ella-Han/algorithm
/baekjoon/baekjoon/Sorting.cpp
UTF-8
2,508
3.28125
3
[]
no_license
// // Sorting.cpp // baekjoon // // Created by 한아름 on 2021/03/29. // Copyright © 2021 Ella-Han. All rights reserved. // #if 0 #include <stdio.h> #include <algorithm> #include <limits.h> using namespace std; #define SIZE 10 int sequence[10] = {10, 3, 2, 1, 9, 8, 7, 5, 6, 4}; void selectionSort() { for (int i=0; i<SIZE-1; i++) { int minIdx = i; for (int j=i+1; j<SIZE; j++) { if (sequence[minIdx] > sequence[j]) { minIdx = j; } swap(sequence[i], sequence[minIdx]); } } } void insertionSort() { for (int i=1; i<SIZE; i++) { for (int j=i; j>0; j--) { if (sequence[j-1] > sequence[j]) { swap(sequence[j-1], sequence[j]); } else { break; } } } } void quickSort(int start, int end) { if (start >= end) { return; } int pivot = start; int left = start + 1; int right = end; while (left <= right) { while (left <= end && sequence[left] <= sequence[pivot]) left++; while (right > start && sequence[right] >= sequence[pivot]) right--; if (left > right) { swap(sequence[pivot], sequence[right]); } else { swap(sequence[left], sequence[right]); } } quickSort(start, right-1); quickSort(right+1, end); } int temp[SIZE]; void merge(int start, int mid, int end, int* temp) { for (int i=start; i<=end; i++) { temp[i] = sequence[i]; } int part1 = start; int part2 = mid + 1; int index = start; while (part1 <= mid && part2 <= end) { if (temp[part1] <= temp[part2]) { sequence[index] = temp[part1]; part1++; } else { sequence[index] = temp[part2]; part2++; } index++; } for (int i=part1; i<=mid; i++) { sequence[index] = temp[i]; index++; } } void mergeSort(int start, int end) { if (start >= end) { return; } int mid = (start+end)/2; mergeSort(start, mid); mergeSort(mid+1, end); merge(start, mid, end, temp); } int main() { // 선택 정렬 selectionSort(); // 삽입 정렬 // insertionSort(); // // // 퀵 정렬 // quickSort(0, SIZE-1); // // // 병합 정렬 // mergeSort(0, SIZE-1); for (int i=0; i<10; i++) { printf("%d\n", sequence[i]); } return 0; } #endif
true
c525b3fb514145210fa3df393caaa76c1d24a80c
C++
egandunning/learn-crypto
/CapstoneCryptography/src/bruteforcefactor.cpp
UTF-8
1,014
2.921875
3
[ "MIT" ]
permissive
#include <headers/bruteforcefactor.h> BruteForceFactor::BruteForceFactor() { name = "Brute force"; } /** * Trial division starting with 2. * @brief Factor::bruteForceFactor * @param composite number to factor * @return A point (number of digits, time to Factor(milliseconds)) */ QPointF BruteForceFactor::factor(mpz_class composite) { QElapsedTimer timer; timer.start(); mpz_class i, upperBound; upperBound = sqrt(composite) + 1; if(composite % 2 == 0) { p1 = i; p2 = composite / i; } else { for(i = 3; i < upperBound; i+=2 ) { if(kill) { p1 = 0; p2 = 0; long elapsed = timer.elapsed(); return QPointF(composite.get_str(10).length(), elapsed); } if(composite % i == 0) { //i divides composite, so i is a factor. p1 = i; p2 = composite / i; break; } } } long elapsed = timer.elapsed(); return QPointF(composite.get_str(10).length(), elapsed); }
true
a0936e417aa2928899c9edd0e7717b3362ca18d9
C++
EEAIC/Baekjoon-Online-Judge
/10814/10814.cpp
UTF-8
677
3.265625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; pair<int, string> *members; bool compare_age(pair<int, string> i, pair<int, string> j) { return (i.first < j.first); } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int N, age; string name; cin >> N; members = new pair<int, string>[N]; for (int i = 0; i < N; i++) { cin >> age >> name; members[i].first = age; members[i].second = name; } stable_sort(members, members + N, compare_age); for (int i = 0; i < N; i++) { cout << members[i].first << " "; cout << members[i].second << "\n"; } return 0; }
true
d43b75111c0328453c601ac7364384f4d6898660
C++
DahamChoi/ModernCpp-DesignPattern
/structural/decorater/TransparentShape.h
UTF-8
584
3.3125
3
[]
no_license
#pragma once #include "Shape.h" #include <sstream> template <typename T> class TransparentShape : public T { static_assert(std::is_base_of<Shape, T>::value, "Template argument musb be a Shape"); public: uint8_t transparency; public: template<typename...Args> TransparentShape(uint8_t transparency, Args ...args) : T(std::forward<Args>(args)...), transparency{ transparency } {} std::string str() const override { std::ostringstream oss; oss << static_cast<float>(transparency) / 255.f * 100.f << "% transparency" << std::endl; return T::str() + oss.str(); } };
true
34e300f205617696682cdbe8c85eec4fa3c4c742
C++
gaurikadam/farm_monitoring
/motor/motor.ino
UTF-8
731
2.890625
3
[]
no_license
int motor_Pin = 9; int m = 0; void setup() { // put your setup code here, to run once: pinMode(motor_Pin,OUTPUT); Serial.begin(9600); } void loop() { // serial read section while (Serial.available()) // this will be skipped if no data present, leading to // the code sitting in the delay function below { delay(30); //delay to allow buffer to fill if (Serial.available() >0) { m = 1; //char c = Serial.read(); //gets one byte from serial buffer //readString += c; //makes the string readString } } if( m==1) { digitalWrite(motor_Pin, HIGH); //num =0; } else { digitalWrite(motor_Pin, LOW); } }
true
f071977d6001d24dc277d2dffa4d8fbccbf576c7
C++
zzdqqqq/MyCode
/MyCode3_pointandreference/main.cpp
UTF-8
315
2.671875
3
[]
no_license
// // main.cpp // MyCode3_pointandreference // // Created by Zidong Zhang on 1/12/19. // Copyright © 2019 Zidong Zhang. All rights reserved. // #include <iostream> using namespace std; int main() { int i = 1; cout << "Value: " << i << endl << "Address: " << &(i) << endl \ << "Value: " << *(&(i)) << endl; }
true
eebde77c1fc9318068dbcd8b1e1de60e93349c61
C++
ADKosm/Design-Patterns
/Strategy/EstimateByMean.cpp
UTF-8
391
2.65625
3
[]
no_license
// // Created by alex on 16.07.16. // #include "EstimateByMean.h" EstimateByMean::EstimateByMean() { } EstimateByMean::~EstimateByMean() { } float EstimateByMean::run(std::vector<float>::iterator begin, std::vector<float>::iterator end) { float sum = 0; float count = 0; for(;begin!=end; begin++) { sum += *begin; count += 1; } return 2*sum/count; }
true
3024503720b3b2d934763bfbbbf7318d56e4ef90
C++
BrodySchulke/MovieStore
/src/person.h
UTF-8
1,323
3.578125
4
[]
no_license
#ifndef PERSON_H #define PERSON_H #include <string> #include <iostream> #include <fstream> using namespace std; //--------------------------------------------------------------------------- // Person class: contains a first and last name for Customers, and is the // parent class for Customer // // Implementation and Assumptions // -- Contains two strings for first and last name // -- Can set data by passing an ifstream reference // -- Assumes valid parameters are passed // -- Only default constructor, setData used for initialization of data // members //--------------------------------------------------------------------------- class Person { //Overloaded ostream operator to print the Person informations friend ostream& operator<<(ostream&, const Person&); public: Person(); //Pure virtual desctructor for base classes to implement virtual ~Person() = 0; //Pure virtual print method used by the ostream operator //for base classes to implement virtual void print(ostream& os) const = 0; //Virtual setData function using an ifstream reference virtual bool setData(ifstream&) = 0; //getter methods for first and last name string getFirstName() const; string getLastName() const; protected: //Protected data members for first and last name string firstName; string lastName; }; #endif
true
4c58a799d37e5383eb299618007a10a7d7c2754c
C++
simunova/mtl4
/libs/numeric/linear_algebra/test/concept_map_test.cpp
UTF-8
1,093
3.296875
3
[ "MTLL" ]
permissive
#include <concepts> #include <iostream> #include <string> #if 0 // Crashes ConceptGCC :-! concept CExplicit<typename T> { requires std::CopyConstructible<T>; requires std::CopyAssignable<T>; // How do I request printability???? std::ostream& operator<<(std::ostream& os, T const& t); } template <CExplicit<T> > void f(const T& x) { std::cout << "In f with x = " << x << "\n"; } #endif concept CExplicit<typename T> { requires std::CopyConstructible<T>; requires std::CopyAssignable<T>; } template <CExplicit T> void f(const T& x, const char* xc) { T y(x); std::cout << "In f with x = " << xc << "\n"; } // Now faking concept_map auto concept CAuto<typename T> { //requires std::CopyConstructible<T>; //requires std::CopyAssignable<T>; } template <CAuto T> concept_map CExplicit<T> {} int main() { f(3, "3"); f(3.14, "3.14"); #if 0 // Another crash source in ConceptGCC f("Godmorgen. Har du sove godt?", "Godmorgen. Har du sove godt?"); #endif f(std::string("Jeg kan ikke klage."), "Jeg kan ikke klage."); return 0; }
true
8f49b5e654ca35c9683aaaeee8c39ce483827c75
C++
katherine0504/POJ
/1325.cpp
UTF-8
1,310
2.921875
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <vector> #define MAX 110 using namespace std; int n, m, k, x, y, out; bool used[MAX]; int llink[MAX], rlink[MAX]; vector <int> edge[MAX]; bool DFS(int r); int Bipartite(int nL, int nR); int main () { int i, j; while (scanf("%d", &n) != EOF) { if (n == 0) { break; } memset(used, false, sizeof(used)); for (i = 0; i < MAX; ++i) { edge[i].clear(); } scanf("%d %d", &m, &k); for (i = 1; i <= k; ++i) { scanf("%d %d %d", &j, &x, &y); if (!x || !y) { continue; } else { edge[x].push_back(y); } } out = Bipartite(n,m); printf("%d\n", out); } return 0; } bool DFS(int r) { int i, nxt; for(i = 0; i < (int)edge[r].size(); ++i) { nxt = edge[r][i]; if(!used[nxt]) { used[nxt] = true; if(!rlink[nxt] || DFS(rlink[nxt])) { llink[r] = nxt; rlink[nxt] = r; return true; } } } return false; } int Bipartite(int nL, int nR) { int i, ans = 0; memset(llink, 0, (nL+1)*sizeof(int)); memset(rlink, 0, (nR+1)*sizeof(int)); for(i = 1; i <= nL; ++i) { memset(used, false, (nR+1)*sizeof(bool)); if(DFS(i)) { ++ans; } } return ans; }
true
3ff6e3a21c7078b1e28299c89ff7de7237782247
C++
alexandraback/datacollection
/solutions_2464487_0/C++/xfighter/bullseye.cpp
UTF-8
519
3.015625
3
[]
no_license
#include <iostream> using namespace std; bool check(long long r, long long t, long long k) { if (k > t) return false; return k * (2 * r - 1 + 2 * k) <= t; } int main () { int T; cin >> T; for (int c = 1; c <= T; c++) { long long r, t; cin >> r >> t; long long l = 1, h = 1000000000; while (l < h) { long long mid = (l + h + 1) / 2; if (check(r, t, mid)) { l = mid; } else { h = mid - 1; } } cout << "Case #" << c << ": " << l << endl; } }
true
e16aa4130ad66c0e17e24603caf3175890de8d03
C++
Yac836/leetcode
/MaximumProductSubarray.cpp
UTF-8
728
3.90625
4
[]
no_license
/* Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int maxProduct(vector<int>& nums) { if (nums.size() == 0) return 0; int tmax = nums[0], tmin = nums[0], maxAns = nums[0]; for (int i = 1; i < nums.size(); i++) { int mx = tmax, mn = tmin; tmax = max(max(nums[i], mx * nums[i]), mn * nums[i]); tmin = min(min(nums[i], mx * nums[i]), mn * nums[i]); maxAns = max(tmax, maxAns); } return maxAns; } int main() { vector<int> iv = { 2,3,-2,3 }; cout << maxProduct(iv); }
true
21b6f61a292e4fc5ba112581c1d713f7d48d29f6
C++
HyungseobKim/Hon
/hon_source/Asterisk/C_RigidBody.cpp
UTF-8
2,063
2.546875
3
[]
no_license
/******************************************************************************/ /*! \file C_RigidBody.cpp \author Jooho Jeong \par email: jooho556 \@ gmail.com \date 2019/01/15 \copyright All content 2019 DigiPen (USA) Corporation, all rights reserved. */ /******************************************************************************/ #include "C_RigidBody.h" void C_RigidBody::ReadIn(std::stringstream & sstream) { sstream >> m_force >> m_maxvelocity.x >> m_maxvelocity.y >> m_jump_speed; } void C_RigidBody::AddVelocity(const vec3 vel) { if (m_velocity.x > m_maxvelocity.x && vel.x <= 0) m_velocity.x += vel.x; else if (m_velocity.x < -m_maxvelocity.x && vel.x >= 0) m_velocity.x += vel.x; else { m_velocity.x += vel.x; if (m_velocity.x > m_maxvelocity.x) m_velocity.x = m_maxvelocity.x; else if (m_velocity.x < -m_maxvelocity.x) m_velocity.x = -m_maxvelocity.x; } if (m_velocity.y > m_maxvelocity.y && vel.y <= 0) m_velocity.y += vel.y; else if (m_velocity.y < -m_maxvelocity.y && vel.y >= 0) m_velocity.y += vel.y; else { m_velocity.y += vel.y; if (m_velocity.y > m_maxvelocity.y) m_velocity.y = m_maxvelocity.y; else if (m_velocity.y < -m_maxvelocity.y) m_velocity.y = -m_maxvelocity.y; } } void C_RigidBody::SetVelocity(const vec3 vel) { m_velocity = vel; } void C_RigidBody::ApplyFriction(float x, float y) { if (m_velocity.x != 0 && m_acceleration.x == 0) { if (abs(m_velocity.x) - abs(x) < 0) m_velocity.x = 0; else { if (m_velocity.x < 0) m_velocity.x += x; else m_velocity.x -= x; } } if (m_velocity.y != 0) { if (abs(m_velocity.y) - abs(y) < 0) m_velocity.y = 0; else { if (m_velocity.y < 0) m_velocity.y += y; else m_velocity.y -= y; } } }
true
613d4ee1ac8387d81c18ca47f9ad35689513cf38
C++
ArmandAgopian/CompsciSpring2018
/src/Lab04-Functions/TestFunctionPrototype.cpp
UTF-8
948
4.25
4
[ "MIT" ]
permissive
#include <iostream> using namespace std; // Return the max between two int values int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } // Find the max between two double values double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } // Return the max among three double values double max(double num1, double num2, double num3) { return max(max(num1, num2), num3); } int main() { // Invoke the max function with int parameters cout << "The maximum between 3 and 4 is " << max(3, 4) << endl; // Invoke the max function with the double parameters cout << "The maximum between 3.0 and 5.4 is " << max(3.0, 5.4) << endl; // Invoke the max function with three double parameters cout << "The maximum between 3.0, 5.4, and 10.14 is " << max(3.0, 5.4, 10.14) << endl; return 0; }
true
66c9376e82851541a490526fa49aa42394d019a3
C++
timeflies1113/learnToProgram
/language/cppPrimer/src/ch03/ex3_36b.cpp
UTF-8
652
3.453125
3
[]
no_license
/* * @Author: Wang Yi * @Github: https://github.com/timeflies1113 * @Date: 2019-11-19 19:22:58 * @LastEditors: Wang Yi * @LastEditTime: 2019-11-19 19:28:06 * @FilePath: \cppPrimer\src\ch03\ex3_36b.cpp * @Description: vector可以直接使用==查看是否相等 */ #include <iostream> #include <vector> using namespace std; int main() { vector<int> vec1(10, 5), vec2(10, 6); cout << "vec1: "; for (auto i : vec1) cout << i << " "; cout << "vec2: "; for (auto i : vec1) cout << i << " "; cout << endl; if (vec1 == vec2) { cout << "equal!"; } else { cout << "Not equal!"; } return 0; }
true
defbff82002faec7611ec55f8d0135a58e535904
C++
temple-engr-ece3822/examples
/example_15/foo.cc
UTF-8
1,247
3.4375
3
[]
no_license
#include <stdio.h> bool jp_test(float x); bool jp_test(float* x); bool jp_test2(float* x); int main (int argc, char** argv) { // call by value // fprintf(stdout, "call by value:\n"); float x = 27; fprintf(stdout, " x before = %f\n", x); jp_test(x); fprintf(stdout, " x after = %f\n", x); fprintf(stdout, " ***> note the value in the calling program is not changed\n"); // call by reference // fprintf(stdout, "call by reference:\n"); x = 27; fprintf(stdout, " x before = %f\n", x); jp_test(&x); fprintf(stdout, " x after = %f\n", x); fprintf(stdout, " ***> note the value in the calling program IS changed\n"); // call by reference // x = 27; fprintf(stdout, " x before = %f (memory: %lu)\n", x, (unsigned long)&x); jp_test2(&x); fprintf(stdout, " x after = %f (memory: %lu)\n", x, (unsigned long)&x); fprintf(stdout, " ***> note the value of the pointer is not changed\n"); } bool jp_test(float arg) { arg = -1; return true; } bool jp_test(float* arg) { *arg = -1; return true; } bool jp_test2(float* arg) { arg = (float*)-1; // I could do *arg = 57, but that is dangerous because // we don't know what memory location -1 points to. // we will get a seg fault. return true; }
true
ec20b0d46e88bb9be992c8e201f8db07df20e286
C++
agrbin/msa
/src/GappedLine.cpp
UTF-8
4,747
2.71875
3
[]
no_license
#include "GappedLine.hpp" #include <iostream> #include <algorithm> #include <cassert> namespace acgt { using std::vector; using std::pair; using std::cout; using std::endl; using std::sort; GappedLine::GappedLine( const vector<string_t> fragments, const vector<off_t> offsets) : size_(0), words_(fragments) { assert(offsets.size() == fragments.size()); // sort fragments by offsets vector<size_t> ord(offsets.size()); for (size_t i = 0; i < ord.size(); ++i) ord[i] = i; sort(ord.begin(), ord.end(), [&offsets] (size_t a, size_t b) { return offsets[a] < offsets[b]; }); // create gaps size_t cum_offset = 0; for (size_t j = 0; j < fragments.size(); ++j) { gaps_.emplace_back(cum_offset, offsets[ord[j]] - size_); cum_offset += fragments[ord[j]].second; size_ = offsets[ord[j]] + fragments[ord[j]].second; } gaps_.emplace_back(cum_offset, 0); // merge all gaps_ pointing to same position. gaps_t::iterator last_it; for (auto it = gaps_.begin(); it != gaps_.end(); ++it) { if (it != gaps_.begin()) { assert(last_it->offset <= it->offset); if (last_it->offset == it->offset) { it->length += last_it->length; gaps_.erase(last_it); } } last_it = it; } } void GappedLine::debug() const { cout << "size: " << size_ << endl; for (auto &t : gaps_) { cout << t.offset << ' ' << t.length << endl; } cout << endl; } size_t GappedLine::size() const { return size_; } GappedLine::iterator GappedLine::begin() { return iterator(*this, true); } GappedLine::iterator GappedLine::end() { return iterator(*this, false); } GappedLine::reverse_iterator GappedLine::rbegin() { return reverse_iterator(*this, true); } GappedLine::reverse_iterator GappedLine::rend() { return reverse_iterator(*this, false); } GappedLine::iterator_traits::iterator_traits( GappedLine &line, bool in_gap, size_t gaps_to_read) : line_(line), in_gap_(in_gap), gaps_to_read_(gaps_to_read) { } GappedLine::iterator::iterator(GappedLine &line, bool start) : iterator_traits( line, start ? true : false, start ? line.gaps_.front().length : 0), wit_(start ? line.words_.begin() : line.words_.end()), git_(start ? line.gaps_.begin() : line.gaps_.end()), gaps_start_(line.gaps_.begin()) { if (start && !gaps_to_read_) { in_gap_ = false; ++git_; } } GappedLine::reverse_iterator::reverse_iterator(GappedLine &line, bool start) : iterator_traits( line, start ? true : false, start ? line.gaps_.back().length : 0 ), wit_(start ? line.words_.rbegin() : line.words_.rend()), git_(start ? line.gaps_.rbegin() : line.gaps_.rend()), gaps_start_(line.gaps_.rbegin()) { if (start && !gaps_to_read_) { in_gap_ = false; ++git_; } } void GappedLine::iterator::addGap(size_t size) { if (!size) { return; } line_.size_ += size; // if currently in gap, just extend that gap. if (in_gap_) { gaps_to_read_ += size; git_->length += size; if (!gaps_to_read_) { ++ git_; in_gap_ = false; } } else { bool dont_insert = false; // otherwise we are definetly in the gap now, and // gaps to read is size. in_gap_ = true; gaps_to_read_ = size; // just need to updated gaps_ list accordingly. // special case if we just went out from a gap, // return us inside. if (git_ != gaps_start_) { --git_; if (git_->offset == wit_.offset()) { git_->length += size; dont_insert = true; } else { ++git_; } } if (!dont_insert) { emplaceGap(size); } } } void GappedLine::reverse_iterator::addGap(size_t size) { if (!size) { return; } line_.size_ += size; // if currently in gap, just extend that gap. if (in_gap_) { gaps_to_read_ += size; git_->length += size; if (!gaps_to_read_) { ++ git_; in_gap_ = false; } } else { bool dont_insert = false; // otherwise we are definetly in the gap now, and // gaps to read is size. in_gap_ = true; gaps_to_read_ = size; // just need to updated gaps_ list accordingly. // special case if we just went out from a gap, // return us inside. if (git_ != gaps_start_) { --git_; if (git_->offset == wit_.offset()) { git_->length += size; dont_insert = true; } else { ++git_; } } if (!dont_insert) { emplaceGap(size); } } } void GappedLine::iterator::emplaceGap(size_t size) { line_.gaps_.emplace(git_, wit_.offset(), size, true); --git_; } void GappedLine::reverse_iterator::emplaceGap(size_t size) { line_.gaps_.emplace(git_.base(), wit_.offset(), size, true); } } // namespace
true
ab415e258cbbbd071b077ed654b489a8584735cf
C++
rostam/PreCol
/Orderings/LargestFirstOrderingDegrees.h
UTF-8
1,101
2.796875
3
[]
no_license
// // Created by rostam on 19.07.16. // #ifndef PRECOL_LARGESTFIRSTORDERINGDEGREES_H #define PRECOL_LARGESTFIRSTORDERINGDEGREES_H #include "Ordering.h" /** * \brief Order vertices based on the degrees * * In this ordering, the vertex with the largest degree comes first * * A specific preordering for the coloring */ class LargestFirstOrderingDegrees : public Ordering { bool OrderGivenVertexSubset(const Graph &G_b, vector<unsigned int> &V, bool restricted) { list<pair<int, int>> VertexDegree; //Compute Distance2Neighbors-degree for all vertices in V for (vector<unsigned int>::iterator v = V.begin(); v != V.end(); ++v) { VertexDegree.push_back(pair<int, int>(*v, neighbors::Distance2NeighborsRestricted(G_b, *v).size())); } //Sort after degree //ge_degree because of compability with matlab alg, otherwise gt_degree VertexDegree.sort(ge_degree); V.clear(); for(auto pii : VertexDegree) V.push_back(pii.first); return EXIT_SUCCESS; } }; #endif //PRECOL_LARGESTFIRSTORDERINGDEGREES_H
true
b1beb7f3e0b1f608b6432d1e217e54c000b40101
C++
Huangyan0804/luogu
/P1223/P1223/P1223.cpp
UTF-8
521
2.828125
3
[]
no_license
#include <iostream> #include <algorithm> #include<cstdio> using namespace std; struct n { int time; int num; }man[1005]; bool cmp(n a, n b) { return a.time < b.time; } int main() { int n, k; double sum = 0; cin >> n; for (int i = 1; i <= n; i++) { cin >> man[i].time; man[i].num = i; } sort(man + 1, man + 1 + n, cmp); for (int i = 1; i <= n; i++) cout << man[i].num << ' '; cout << endl; for (int j = n - 1; j >= 1; j--) { k = n - j; sum += man[k].time * j; } printf("%.2f", sum/n); return 0; }
true
bbce68b74a7060a1e85b9787c1066790c216440c
C++
emtsdmr/C-and-Cpp-Exercises
/C++/LinkedList/Main.cpp
UTF-8
251
2.859375
3
[]
no_license
#include <iostream> #include "LinkedList.h" #include <string> using namespace std; int main() { LinkedList list; list.add(1); list.add(2); list.add(3); list.insert(1, 4); list.remove(0); cout << list << endl; return 0; }
true
2aa97d67a7ee3b32dbddca82dcfd531623f7974a
C++
wu-yakun/CPP_TensorRT_YOLOV3TINY
/utils/post_process.cpp
UTF-8
2,641
2.9375
3
[]
no_license
// // Created by 吴子凡 on 2020/7/13. // #include "post_process.h" namespace post_process{ float sigmoid(float in) { return 1.f / (1.f + exp(-in)); } float exponential(float in) { return exp(in); } float arg_max(vector<float> &label_list){ float ret_id = 0; float last_max = 0; for(int i=0;i<label_list.size();i++){ if(label_list[i]>last_max){ last_max=label_list[i]; ret_id = i; } } return ret_id; } void DoNms(vector<DetectionRes>& detections, float nmsThresh){ auto iouCompute = [](DetectionRes &lbox, DetectionRes &rbox) { float interBox[] = { max(lbox.x1, rbox.x1), //x1 max(lbox.y1, rbox.y1), //y1 min(lbox.x2, rbox.x2), //x2 min(lbox.y2, rbox.y2), //y2 }; if (interBox[1] >= interBox[3] || interBox[0] >= interBox[2]) return 0.0f; float interBoxS = (interBox[2] - interBox[0] + 1) * (interBox[3] - interBox[1] + 1); float lbox_area = (lbox.x2-lbox.x1+1)*(lbox.y2-lbox.y1+1); float rbox_area = (rbox.x2-rbox.x1+1)*(rbox.y2-rbox.y1+1); float extra = 0.00001; return interBoxS / (lbox_area+rbox_area-interBoxS+extra); }; vector<DetectionRes> result; for (unsigned int m = 0; m < detections.size(); ++m) { result.push_back(detections[m]); for (unsigned int n = m + 1; n < detections.size(); ++n) { if (iouCompute(detections[m], detections[n]) > nmsThresh) { detections.erase(detections.begin() + n); --n; } } } detections = move(result); } DetectionRes rescale(DetectionRes box, int height,int width,int current_dim){ float pad_x = max(height-width,0)*(1.0*current_dim/max(height,width)); float pad_y = max(width-height,0)*(1.0*current_dim/max(height,width)); float unpad_h = current_dim - pad_y; float unpad_w = current_dim - pad_x; box.x1 = ((box.x1-(pad_x/2))/unpad_w)*width; box.y1 = ((box.y1-(pad_y/2))/unpad_h)*height; box.x2 = ((box.x2-(pad_x/2))/unpad_w)*width; box.y2 = ((box.y2-(pad_y/2))/unpad_h)*height; return box; } float* merge(float* out1, float* out2, int bsize_out1, int bsize_out2) { /** * 合并两个输出 */ float* out_total = new float[bsize_out1 + bsize_out2]; for (int j = 0; j < bsize_out1; ++j) { int index = j; out_total[index] = out1[j]; } for (int j = 0; j < bsize_out2; ++j) { int index = j + bsize_out1; out_total[index] = out2[j]; } return out_total; } }
true
bc05ca4b7d823985d2ce6024278fcb1f60eff8f3
C++
MrJookie/AGE
/Plugins/Physics/Bullet/BulletBoxCollider.hpp
UTF-8
1,002
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#pragma once #include "BoxColliderInterface.hpp" #include "BulletCollider.hpp" #pragma warning(push) #pragma warning(disable: 4250) namespace AGE { namespace Physics { class BulletBoxCollider final : public BoxColliderInterface, public BulletCollider { // Friendships friend ObjectPool < BulletBoxCollider > ; public: // Constructors BulletBoxCollider(void) = delete; BulletBoxCollider(WorldInterface *world, Private::GenericData *data); BulletBoxCollider(const BulletBoxCollider &) = delete; // Assignment Operators BulletBoxCollider &operator=(const BulletBoxCollider &) = delete; private: // Attributes glm::vec3 center; // Destructor ~BulletBoxCollider(void) = default; // Inherited Methods void setCenter(const glm::vec3 &center) override final; glm::vec3 getCenter(void) const override final; void setSize(const glm::vec3 &size) override final; glm::vec3 getSize(void) const override final; }; } } #pragma warning(pop)
true
f9a7e6c6ba3714369b3d7f997c7278458fe966b4
C++
jiabailie/Algorithm
/daily-practice/2013/13102401.cpp
UTF-8
3,300
3.28125
3
[]
no_license
/* * Largest Independent Set * References : mp.weixin.qq.com/mp/appmsg/show?__biz=MjM5ODIzNDQ3Mw==&amp;appmsgid=10000312&amp;itemidx=1&amp;sign=0e53a19fb344fb7e09292a2e40e3ffab */ #include <cstdio> #include <iostream> #include <vector> #include <queue> #include <stack> #define DEBUG #undef DEBUG using namespace std; template<typename T> inline T imax(T a, T b) { return a > b ? a : b; } struct treeNode { int data; treeNode* left; treeNode* right; int c[2]; treeNode() : data(0), left(0), right(0) { c[0] = c[1] = 0; } }; inline void createBinaryTree(treeNode*& root) { int v = 0; cin >> v; if(v > -1) { root = new treeNode; root->data = v; createBinaryTree(root->left); createBinaryTree(root->right); if(!root->left && !root->right) { root->c[1] = 1; } } } inline void destroyBinaryTree(treeNode*& root) { if(!root) { return; } destroyBinaryTree(root->left); destroyBinaryTree(root->right); delete root; } inline void postOrderTraverseBinaryTree(treeNode*& root) { if(!root) { cout << "The root is null." << endl; return; } treeNode* pre = 0; treeNode* top = 0; stack<treeNode*> istack; istack.push(root); while(!istack.empty()) { top = istack.top(); if((!top->left && !top->right) || (top->right && pre == top->right) || (top->left && !top->right && pre == top->left)) { #ifdef DEBUG cout << top->data << " "; #endif istack.pop(); pre = top; top->c[0] = (top->left ? imax(top->left->c[0], top->left->c[1]) : 0) + (top->right ? imax(top->right->c[0], top->right->c[1]) : 0); top->c[1] = (top->left ? top->left->c[0] : 0) + (top->right ? top->right->c[0] : 0) + 1; continue; } if(top->right) { istack.push(top->right); } if(top->left) { istack.push(top->left); } } } inline void displayBinaryTreeByLevel(treeNode*& root) { if(!root) { cout << "The root is null." << endl; return; } int size = 0, i = 0; treeNode* front = 0; queue<treeNode*> iqueue; iqueue.push(root); while(!iqueue.empty()) { size = iqueue.size(); for(i = 0; i < size; i++) { front = iqueue.front(); cout << front->data << " "; iqueue.pop(); if(front->left) { iqueue.push(front->left); } if(front->right) { iqueue.push(front->right); } } cout << endl; } } int main() { treeNode* root = 0; createBinaryTree(root); displayBinaryTreeByLevel(root); #ifdef DEBUG cout << "Test post order traverse binary tree." << endl; #endif postOrderTraverseBinaryTree(root); cout << endl << imax(root->c[0], root->c[1]) << endl; destroyBinaryTree(root); return 0; }
true
d6457506fd49ee90b77b45484876130f81d1da57
C++
Arniox/Game-Programming-Work
/COMP710-2019-S2/students/nikkolas.diehl/Assignment 1 - Personal Game Project/FWT - 16945724/Really Warm/Really Warm/Walls.h
UTF-8
824
2.609375
3
[]
no_license
#pragma once #include "backbuffer.h" #include "entity.h" #include "Article.h" // Library includes: #include <cassert> #include <cmath> class Walls: public Article { public: Walls(); ~Walls(); //Wall Creation void UpdateWall(float x1, float y1, float x2, float y2); void Draw(BackBuffer& backBuffer); void CreateWall(BackBuffer* backBuffer, float x1, float y1, float x2, float y2); float* GetPoint1(); float* GetPoint2(); //Physics calculations float GetWallAngle(); int GetDxl(); int GetDyl(); protected: void SetCenter(float x, float y); private: //Positions float mx_arr_point1[2]; float mx_arr_point2[2]; //Rotation float mx_f_wallAngleDeg; float mx_f_wallAngleRad; //Imaging float mx_f_imageCenterX; float mx_f_imageCenterY; int mx_i_wallLength; //Position float xPos; float yPos; };
true
1d8abb641d43d9be381d4502036d280dcb7de910
C++
sanyaade-g2g-repos/opensynth
/headers/WaveForm.h
UTF-8
3,380
3.203125
3
[]
no_license
/** \file Waveform.h Header for WaveForm Object * \author Samuel L. Banina 901278567 CSE21212.02 * * This file declares the WaveForm class which is the fundamental * unit in the heirarchy of the synthesizer. It dynamically creates * samples of the specified waveform and returns the next sample scaled * to the appropriate values for the position in the envelope. */ #ifndef WAVEFORM_H #define WAVEFORM_H #include <QObject> #include <QString> #include <QMutex> enum wavetype { SIN, SQR, TRI, SAW }; class WaveForm:public QObject { Q_OBJECT friend class AudioBuffer; public: /** \brief Constructor which generates the sample * * This function sets all the private variables of the WaveForm class. * It then computes the length (in samples) of one wavelength of the * waveform. Then depending on the type of waveform makes it from a function. * * \param n, QString, name of the WaveForm * \param f, int, frequency of the WaveForm * \param wt, wavetype, type of the waveform (sine, square, etc.) * \param aa, int, attack time in ms * \param dd, int, decay time in ms * \param ss, int, sustain level in percentage of max volume * \param rr, int release time in ms */ WaveForm(QString n, int f, wavetype, int aa = 500, int dd = 250, int ss = 75, int rr = 0); WaveForm(QString n); /** \brief Destructor for WaveForm * * This function deletes the dynamically generated sample * */ ~WaveForm(); /** \brief Returns next sample scaled to appropriate volume * * This function looks to see if the note has been released. * If so, it turns down the volume until it's less than zero, * then emits a signal that it's ready to be deleted. Otherwise * it tests for whether it is in the attack, decay, or sustain * phases and increases, decreases, and set the volume appropriately. * * \param void * \return double, current sample */ double nextSample(void); /** \brief Slot which sets key to release mode * * This set release to true, resets the envelope * count, and set the starting value for the * envelope fade out to the current volume, otherwise * it would jump to the max volume to fade out * \param void * \return void */ void releaseIt(void); signals: /** \brief Signal denoting end of fade-out * * This signal is triggered when the volume goes to zero and * is caught by the AudioBuffer handling the WaveForm, which * then deletes it. */ void finished(QString); private: QMutex mutex; //pointer to array of samples double * sample; //size of a wavelength (and of samples array) int size; //double version of above (used in calculations) double dsize; //current index in sample int index; //frequency of the waveform int frequency; //name of the waveform QString name; //waveform type wavetype wt; //maximum volume for use by envelope int maxvol; int a,d,s,r; //a -> time to reach full volume (ms) //d -> time to decay to sustained volume //s -> sustained volume //r -> time to fade out from sustain //counts number of times nextSample has been called int envcount; //hold scaled volume int tempvol; //flag indicating release of the key bool release; //starting volume for release fadeout int relvol; }; #endif
true
6d9c9302c646bc306779ba56d0862b3eaa759807
C++
ssizova/Trajectory
/config.cpp
UTF-8
6,067
2.9375
3
[]
no_license
#include "config.h" namespace { bool section_find(ifstream& in, const string& sectname) { string line; while (getline(in, line) && line.find(sectname) != 0); if (in.eof()) { ostringstream msg; msg << "EOF while looking for " << sectname << " section" << endl; throw runtime_error(msg.str()); } return true; } bool check_out_of_numeric_limits(id_t x) { if (x >= numeric_limits<id_t>::max()) { ostringstream msg; msg << "Format id_t is too small to handle" << endl; throw runtime_error(msg.str()); } return false; } } void io_file_manager(int argc, char** argv) { if (--argc > 0) input_path() = argv[1]; else { cerr << "WARNING expected first console argument. "; const string default_input_name = "input.txt"; cerr << "Replacing with " << default_input_name << " . . ." << endl; input_path() = move(default_input_name); } if (--argc > 0) output_path() = argv[2]; else { cerr << "WARNING expected second console argument. "; const string default_output_name = "output.txt"; cerr << "Replacing with " << default_output_name << " . . ." << endl; output_path() = move(default_output_name); } if (--argc > 0) { cerr << "WARNING too many arguments : last arguments in input ignored" << endl; } } string& input_path() { static string res{}; return res; } string& output_path() { static string res{}; return res; } void parse_map( sommet* const start, sommet* const finish, vector<obstacle>* const obstacles ) { // Create input stream, constructor (5) from here: // https://en.cppreference.com/w/cpp/io/basic_ifstream/basic_ifstream ifstream conf(input_path()); //Check file consistency if (!conf.good()) { ostringstream msg; msg << "Cannot open map file" << endl; throw runtime_error(msg.str()); } double x, y, r; //Parse $Start section section_find(conf, "[$Start]"); conf >> x >> y >> r; *start = sommet{ x,y }; //Parse $Finish section section_find(conf, "[$Finish]"); conf >> x >> y; *finish = sommet{ x,y }; //Parse $Obstacles section section_find(conf, "[$NumObstacles]"); id_t num_obstacles; conf >> num_obstacles; check_out_of_numeric_limits(num_obstacles); obstacles->reserve(num_obstacles); // Parse $Nodes section section_find(conf, "[$PtsObstacles]"); for (id_t i = 0; i < num_obstacles; i++) { obstacles->emplace_back(obstacle{}); auto* const vertices_of_i = &((*obstacles)[i].vertices); id_t num_nodes_i; conf >> num_nodes_i; check_out_of_numeric_limits(num_nodes_i); if (num_nodes_i < 3) { ostringstream msg; msg << "Invalid number of nodes in obstacle " << i << endl; throw runtime_error(msg.str()); } // here we introduce a simple algorithm how to parse a graph // this lambda not only checks whether segments of construction are parallel // but also parses to the obstacle object as many nodes of a construction as needed auto segments_analyzer = [&](vector<sommet>* const vertices, sommet* const prev, sommet* const curr, const sommet& next) { auto n1 = segment{ *prev, *curr }.outer_normal(); auto n2 = segment{ *curr, next }.outer_normal(); double sin_phi = det(n1, n2); // sin of angle between n1 and n2 constexpr double tol = 1e-12; if (abs(sin_phi) >= tol) { // ok, segments are not parallel, thus, its intersection // is significant // we consider 2 cases if (sin_phi < 0.) { // polygon obstacle_i is concave in vertex curr // no smooth reconstruction of the // boundary needed // we adjust boundary on radius r double cos_phi = prod(n1, n2); double k = sin_phi / (1. + cos_phi); sommet inner_angle_shift = r * sommet{ n1.x() - k * n1.y(), k * n1.x() + n1.y() }; vertices->emplace_back(*curr + inner_angle_shift); // curr + shift = new angle point } else { // polygon obstacle_i is convex in vertex curr // compute smooth arc betwenn 2 successive shifts of curr if (r < tol) vertices->emplace_back(*curr); else { constexpr double arc_0 = 1e-2; // relative length to consider auto phi = acos(prod(n1, n2)); int num_parts = (int)(r * phi / arc_0) + 1; for (auto k = 0; k <= num_parts; k++) { double phi_k = k * phi / num_parts; sommet outer_angle_shift = r * sommet{ cos(phi_k) * n1.x() - sin(phi_k) * n1.y(), sin(phi_k) * n1.x() + cos(phi_k) * n1.y() }; vertices->emplace_back(*curr + outer_angle_shift); } } } *prev = *curr; } *curr = next; // we do a step forward in our cycle }; conf >> x >> y; sommet prev{ x,y }; // read first vertex conf >> x >> y; sommet curr{ x,y }; // read second vertex sommet first = prev; sommet second = curr; // memorize them in special variables // we will get back to them later auto reading_segment = bind(segments_analyzer, vertices_of_i, &prev, &curr, placeholders::_1); for (id_t j = 3; j <= num_nodes_i; j++) { conf >> x >> y; sommet next{ x,y }; // read next vertex reading_segment(next); } // but there are still two missing constructions to consider reading_segment(first); reading_segment(second); // all the nodes of this obstacle processed } // all obstacles processed conf.close(); } void write_obstacles(vector<obstacle> const& obstacles) { ofstream out("obstacles.txt"); out << "[$NumObstacles]" << endl; out << obstacles.size(); out << "[$PtsObstacles]" << endl; for (auto const& obstacle : obstacles) { out << obstacle.vertices.size() << endl; for (auto const& vertex : obstacle.vertices) out << vertex.x() << " " << vertex.y() << endl; } out.close(); }
true
88aad2db3d8234cdfa97c5d2b164b8f7e8be5d4e
C++
shirosweets/Soluc11
/Guia11E4.cpp
UTF-8
769
3.1875
3
[ "MIT" ]
permissive
#include <iostream> #include <fstream> using namespace std; // SOLUCIONARIO DE EJERCICIOS // // // Ejercicio Guia 11 N4 const int N=100; const int M=3; int main() { ifstream entrada; int n=0; int matriz[N][M]; entrada.open("Numeros.txt"); while( entrada >> matriz[n][0] >> matriz[n][1] >> matriz[n][2] ) n++; entrada.close(); /* Muestra los datos almacenados for( int i=0;i<n;i++ ) { cout << endl; for( int j=0;j<M;j++ ) cout << setw(6) << matriz[i][j]; } */ cout << "\n\nHay " << n << " filas y por lo tanto, la cantidad de datos es " << n*3 << endl; system("PAUSE"); return 0; }
true
85cede29a515f38feab27db6b047444f6ea11c30
C++
ssicard/programming-digital-media
/hardware1/morsecode/morsecode.ino
UTF-8
3,197
3.609375
4
[]
no_license
//**************************************************// // Type the String to Convert to Morse Code Here // //**************************************************// String message = "Hi LEEZ"; // Create variable to define the output pins int led13 = 13; int dotLen = 100; // length of the morse code 'dot' int dashLen = dotLen * 3; // length of the morse code 'dash' int elemPause = dotLen; // length of the pause between elements of a character int spaces = dotLen * 3; // length of the spaces between characters int wordPause = dotLen * 7; // length of the pause between words void setup() { pinMode(led13, OUTPUT); message.toLowerCase(); } void loop() { for (int i = 0; i < message.length() - 1; i++) { Output(message.charAt(i)); } // At the end of the string long pause before looping and starting again off(8000); } void dot() { digitalWrite(led13, HIGH); // turn the LED on delay(dotLen); // hold in this position off(elemPause); } void dash() { digitalWrite(led13, HIGH); // turn the LED on delay(dashLen); // hold in this position off(elemPause); } void off(int delayTime) { digitalWrite(led13, LOW); // turn the LED off delay(delayTime); // hold in this position } void Output(char letter) { switch (letter) { case 'a': dot(); dash(); break; case 'b': dash(); dot(); dot(); dot(); break; case 'c': dash(); dot(); dash(); dot(); break; case 'd': dash(); dash(); dot(); break; case 'e': dot(); break; case 'f': dot(); dot(); dash(); dot(); break; case 'g': dash(); dash(); dot(); break; case 'h': dot(); dot(); dot(); dot(); break; case 'i': dot(); dot(); break; case 'j': dot(); dash(); dash(); dash(); break; case 'k': dash(); dot(); dash(); break; case 'l': dot(); dash(); dot(); dot(); break; case 'm': dash(); dash(); break; case 'n': dash(); dot(); break; case 'o': dash(); dash(); dash(); break; case 'p': dot(); dash(); dash(); dot(); break; case 'q': dash(); dash(); dot(); dash(); break; case 'r': dot(); dash(); dot(); break; case 's': dot(); dot(); dot(); break; case 't': dash(); break; case 'u': dot(); dot(); dash(); break; case 'v': dot(); dot(); dot(); dash(); break; case 'w': dot(); dash(); dash(); break; case 'x': dash(); dot(); dot(); dash(); break; case 'y': dash(); dot(); dash(); dash(); break; case 'z': dash(); dash(); dot(); dot(); break; default: off(spaces); } }
true
fe2e2edaf4c70fc3c51f853c1b47f7fb32b09058
C++
menglecho/Kattis
/artichoke.cpp
UTF-8
710
2.90625
3
[]
no_license
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> using namespace std; vector<double> price; double f(int p, int a, int b, int c, int d, int k){ return p * (sin(a * k + b) + cos(c * k + d) + 2); } int main(void){ int p, a, b, c, d, n; double dec; cin >> p >> a >> b >> c >> d >> n; double max = 0.0, diff = 0.0, res = 0.0, val; for(int i = 1; i <= n; i++){ val = f(p,a,b,c,d,i); if(max < val) max = val; else if(max > val && i > 1){ diff = max - val; if(res < diff) res = diff; } } if(res == 0.0) cout << "0.000000" << endl; else printf("%.6f\n",res); return 0; }
true
488b4701c3355c7aeed3887fc468a1d3c94744f0
C++
chencaf/KrigingManifoldData
/src/Model.hpp
UTF-8
3,837
2.921875
3
[]
no_license
#ifndef _MODEL_HPP_ #define _MODEL_HPP_ #include <vector> #include <iostream> #include <string> #include <utility> #include <Eigen/IterativeLinearSolvers> #include <memory> #include "Helpers.hpp" /*! \file @brief Model class */ namespace model_fit { /*! @brief Class to compute and store the linear model on the tangent space */ class Model { private: /*! BigMatrix of the data on the tangent space */ const std::shared_ptr<const MatrixXd> _data_tspace; /*! Design matrix for the data in the cell (used to compute the beta) */ const std::shared_ptr<const MatrixXd> _design_matrix_model; /*! Design matrix for all the data in the domain (used ti compute the residuals) */ const std::shared_ptr<const MatrixXd> _design_matrix_tot; /*! Name of the metric on the manifold */ const std::string _distance_Manifold_name; /*! Number of stations in the cell */ const unsigned int _N; /*! Dimension of the matrices on the manifold */ const unsigned int _p; /*! Number of covariates in the model */ const unsigned int _num_cov; /*! Number of significant entries in a symmetric \f$ \left(\text{\_p}*\text{\_p}\right) \f$ matrix. \f$ \text{\_num\_coeff} = \frac{\text{\_p}*\left( \text{\_p}+1\right)}{2} \f$ */ const unsigned int _num_coeff; /*! \f$ \left(\text{\_num\_cov}*\text{\_num\_coeff}\right) \f$ matrix where the \f$i^{th}\f$ row contains the upper triangular part of \f$ \beta_{..i} \f$, the \f$i^{th}\f$ coefficient of the tangent space linear model */ MatrixXd _beta_matrix; /*! \f$ \left(\text{N\_tot}*\text{\_num\_coeff}\right) \f$ matrix where the \f$i^{th}\f$ row contains the upper triangular part of the matrix fitted in the \f$i^{th}\f$ location on the tangent space by the linear model. \f$ \mbox{\_fitted\_values} = \left(*\left(\mbox{\_design\_matrix\_tot}\right)\right)*\mbox{\_beta\_matrix} \f$ */ MatrixXd _fitted_values; /*! \f$ \left(\text{N\_tot}*\text{\_num\_coeff}\right) \f$ matrix where the \f$i^{th}\f$ row contains the upper triangular part of the residual matrix in the \f$i^{th}\f$ location. \f$ \mbox{\_residuals} = \left(*\left(\mbox{\_data\_tspace}\right)\right)-\mbox{\_fitted\_values} \f$ */ MatrixXd _residuals; public: /*! @brief Constructor */ Model(const std::shared_ptr<const MatrixXd> data_tspace, const std::shared_ptr<const MatrixXd> design_matrix_model, unsigned int p, const std::string& distance_Manifold_name): // EQUAL WEIGHTS _data_tspace(data_tspace), _design_matrix_model(design_matrix_model), _design_matrix_tot(design_matrix_model), _distance_Manifold_name(distance_Manifold_name), _N(design_matrix_model->rows()), _p(p), _num_cov(_design_matrix_model->cols()), _num_coeff((_p*(_p+1))/2), _beta_matrix(_num_cov, _num_coeff){}; /*! @brief Constructor */ Model(const std::shared_ptr<const MatrixXd> data_tspace, const std::shared_ptr<const MatrixXd> design_matrix_model, const std::shared_ptr<const MatrixXd> design_matrix_tot, unsigned int p, const std::string& distance_Manifold_name): // KERNEL _data_tspace(data_tspace), _design_matrix_model(design_matrix_model), _design_matrix_tot(design_matrix_tot), _distance_Manifold_name(distance_Manifold_name), _N(design_matrix_model->rows()), _p(p), _num_cov(_design_matrix_model->cols()), _num_coeff((_p*(_p+1))/2), _beta_matrix(_num_cov, _num_coeff){}; /*! @brief Update `_beta_matrix`, `_fitted_values` and `_residuals` according to the new covariogram matrix @param gamma_matrix Covariogram matrix */ void update_model(const MatrixXd& gamma_matrix); /*! @brief Return `_beta_matrix` */ MatrixXd get_beta() const; /*! @brief Return `_residuals` */ MatrixXd get_residuals() const; /*! @brief Return `_fitted_values` */ MatrixXd get_fitted_values() const; }; } #endif //_MODEL_HPP_
true
dd431025a1abee275ee3563cd8d632e1567705f0
C++
arponbasu/CS154_Labs_2ndSem
/CS154_Labs_2ndSem/Lab4/Game.cpp
UTF-8
6,791
2.765625
3
[]
no_license
/* #include <bits/stdc++.h> #include <FL/Fl.H> // needed in every fltk program #include <FL/Fl_Window.H> // needed to use the Fl_Window class #include <FL/Fl_Button.H> // needed to use the Fl_Box class using namespace std; char* int2charstar (int v) { char *s = new char[sizeof(int)]; sprintf(s,"%d",v); return s; }; void swap (const char*& x, const char*& y){ const char* temp = x; x = y; y = temp; } class MyButton : public Fl_Button { int count; public: MyButton (int x, int y, int w, int h, const char *l); int handle(int e); // e is incoming mouse event of different kinds int getCount (); void setCount (int); void whenClicked(MyButton***, void*); }; MyButton :: MyButton (int x,int y, int w, int h, const char *l) : Fl_Button (x,y,w,h,l) { count = 0; } int MyButton :: handle (int e) { if(e == FL_PUSH) count++; return 1; } int MyButton :: getCount () { return count; } void MyButton :: setCount (int cnt) { count = cnt; } void MyButton::whenClicked(MyButton*** buttons) { for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ if(buttons[i][j]->getCount() > 0){ const char* var; var = buttons[i][j]->label(); const char* empty = ""; if (i > 0 && buttons[i-1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i-1][j]->label(var); } else if (buttons[i+1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i+1][j]->label(var); } else if (buttons[i][j+1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j+1]->label(var); } else if (j > 0 && buttons[i][j-1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j-1]->label(var); } } buttons[i][j]->setCount(0); break; } } } int main(int argc, char *argv[]) { Fl_Window *window; window = new Fl_Window (600,600,"DEMO"); // outer window MyButton* buttons[4][4]; for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ int a = i+4*j+1; if (a != 16) { buttons[i][j] = new MyButton(50*(2*i+1),50*(2*j+1),100,100,"Err"); buttons[i][j]->label(int2charstar(a)); // buttons[i][j]->when(FL_WHEN_CHANGED); // buttons[i][j]->callback(( Fl_Callback* ) click_callback); } else { buttons[i][j] = new MyButton(50*(2*i+1),50*(2*j+1),100,100,"Err"); buttons[i][j]->label(""); // buttons[i][j]->callback(( Fl_Callback* ) click_callback); } } } for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ buttons[i][j]->whenClicked(buttons); } } //MyButton->callback(whenClicked); /* for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ if(buttons[i][j]->getCount() > 0){ const char* var; var = buttons[i][j]->label(); const char* empty = ""; if (i > 0 && buttons[i-1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i-1][j]->label(var); } else if (buttons[i+1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i+1][j]->label(var); } else if (buttons[i][j+1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j+1]->label(var); } else if (j > 0 && buttons[i][j-1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j-1]->label(var); } } buttons[i][j]->setCount(0); break; } } window->color(FL_WHITE); window->end(); window->show(); int retval = Fl::run(); cout << "Exiting...\n"; return retval; // the process waits from here on for events } static void button_cb(Fl_Button* buttonptr,void* userdata){ cout<<(const char*)userdata<<buttonptr->label() <<endl; if (buttonptr->color() == FL_BLUE) { buttonptr->color(FL_RED); //toggle }else { buttonptr->color(FL_BLUE);//toggle } } */ #include <bits/stdc++.h> #include <FL/Fl.H> // needed in every fltk program #include <FL/Fl_Window.H> // needed to use the Fl_Window class #include <FL/Fl_Button.H> // needed to use the Fl_Box class using namespace std; char* int2charstar (int v) { char *s = new char[sizeof(int)]; sprintf(s,"%d",v); return s; }; //Fl_Button* buttons[4][4]; class MyWindow : public Fl_Window { public: MyWindow(int width, int height, const char* title=0) : Fl_Window(width,height,title){ color(FL_WHITE); // Begin adding children to this window begin(); //Create a button - x , y , width, height, label Fl_Button* buttons[4][4]; for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ int a = i+4*j+1; if(a != 16){ buttons[i][j] = new Fl_Button(50*(2*i+1),50*(2*j+1),100,100,""); buttons[i][j]->label(int2charstar(a)); //buttons[i][j]->callback((Fl_Callback*)button_cb,(void *)"My Button"); } else{ buttons[i][j] = new Fl_Button(50*(2*i+1),50*(2*j+1),100,100,""); // buttons[i][j]->callback((Fl_Callback*)button_cb,(void *)"My Button"); } } } for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ buttons[i][j]->callback((Fl_Callback*)button_cb,(void *)buttons); break; } } // Set color of button to red //button1->color(FL_RED); // Stop adding children to this window end(); // Display the window show(); } static void button_cb(Fl_Button* buttonptr,void* userdata){ Fl_Button*** buttons; buttons = (Fl_Button***)userdata; const char* var; var = buttons[i][j]->label(); const char* empty = ""; if (i > 0 && buttons[i-1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i-1][j]->label(var); } else if (buttons[i+1][j]->label() == empty) { buttons[i][j]->label(""); buttons[i+1][j]->label(var); } else if (buttons[i][j+1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j+1]->label(var); } else if (j > 0 && buttons[i][j-1]->label() == empty) { buttons[i][j]->label(""); buttons[i][j-1]->label(var); } } } }; int main() { MyWindow win(600,600,"Game Window"); return Fl::run(); }
true
b5b9d113237312dfd81962829509f8c27ee16e1a
C++
russellim/Algorithm
/BeakJoon/14426_이모티콘.cpp
UTF-8
1,404
3.375
3
[]
no_license
// 21.06.04. 금 // 14426: 이모티콘 https://www.acmicpc.net/problem/14426 // DP. #include <iostream> #include <vector> #include <algorithm> using namespace std; namespace BOJ_14226 { vector<int> dp; // 나눠 떨어지는 수에서 복붙하면?. void FindMin(int num) { for (int i = num / 2; i >= 2; --i) { if (num % i == 0) { dp[num] = min(dp[num], dp[i] + (num / i)); } } } void Solution() { int s; cin >> s; if (s <= 5) { cout << s; return; } dp.assign(1005, 100); // 소수는 짝수번 먼저 구하고 홀수번을 구한다. (그래서 검사 끝을 다르게). // +2 는 구한 값이 전전값까지 영향을 줄 수 있기 때문. int end = (s % 2 == 0 ? s : s + 1) + 2; // 2~5. for (int i = 2; i <= 5; ++i) dp[i] = i; // 6~ 기본값 세팅 ( 2개로 붙여넣기 ) for (int i = 6; i <= end; i += 2) { dp[i] = dp[i - 2] + 1; } // 6~. for (int i = 6; i <= end; i += 2) { FindMin(i); dp[i - 1] = min(dp[i - 1], dp[i] + 1); FindMin(i - 1); // 구한 i-1 값이 i-3 까지 영향을 줄 수 있음 (삭제로). if (dp[i - 1] < dp[i - 2]) { dp[i - 2] = dp[i - 1] + 1; dp[i - 3] = min(dp[i - 3], dp[i - 2] + 1); } } // output. cout << dp[s]; //for (int i = 2; i <= 1000; ++i) // cout << i << " " << dp[i] << "\n"; } } int main() { BOJ_14226::Solution(); return 0; }
true
b55a6d99be1624f4d3620520715012f89d8d20c6
C++
JaceRiehl/Cheat
/test/CheatControllerTest.cpp
UTF-8
3,463
2.6875
3
[]
no_license
#include "CheatControllerTest.h" TEST_F(CheatControllerTest,testStartGame) { ASSERT_TRUE(true); EXPECT_CALL(*deckMock,shuffle()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,welcomeMessage()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,chooseNumPlayers(_)) .Times(1) .WillOnce(Return(2)); controller->startGame(); } TEST_F(CheatControllerTest,testInitalDeal) { EXPECT_CALL(*deckMock,shuffle()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,welcomeMessage()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,chooseNumPlayers(_)) .Times(1) .WillOnce(Return(2)); EXPECT_CALL(*deckMock,getSize()) .Times(2) .WillRepeatedly(Return(5)); Card c1(ace); EXPECT_CALL(*deckMock,drawCard()) .Times(4) .WillRepeatedly(Return(c1)); EXPECT_CALL(*p1Mock,receiveCard(_)) .Times(2) .WillRepeatedly(Return()); EXPECT_CALL(*p2Mock,receiveCard(_)) .Times(2) .WillRepeatedly(Return()); vector<Card> cTemp = {Card(two)}; EXPECT_CALL(*deckMock,getDeck()) .Times(1) .WillOnce(Return(cTemp)); controller->startGame(); controller->initalDeal(); } TEST_F(CheatControllerTest,testGame) { EXPECT_CALL(*deckMock,shuffle()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,welcomeMessage()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*viewMock,chooseNumPlayers(_)) .Times(1) .WillOnce(Return(2)); EXPECT_CALL(*deckMock,getSize()) .Times(2) .WillRepeatedly(Return(11)); Card c1(ace); EXPECT_CALL(*deckMock,drawCard()) .Times(10) .WillRepeatedly(Return(c1)); EXPECT_CALL(*p1Mock,receiveCard(_)) .Times(10) .WillRepeatedly(Return()); EXPECT_CALL(*p2Mock,receiveCard(_)) .Times(9) .WillRepeatedly(Return()); vector<Card> cTemp = {Card(ace)}; EXPECT_CALL(*deckMock,getDeck()) .Times(1) .WillOnce(Return(cTemp)); EXPECT_CALL(*viewMock,clearTerminal()) .Times(2) .WillRepeatedly(Return()); EXPECT_CALL(*viewMock,displayTurn(_)) .Times(2) .WillRepeatedly(Return()); EXPECT_CALL(*p1Mock,sortHand()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*p1Mock,getHandSize()) .Times(8) .WillRepeatedly(Return(5)); EXPECT_CALL(*p1Mock,takeCard(_)) .Times(4) .WillRepeatedly(Return(c1)); EXPECT_CALL(*viewMock,displayPlayersHand(_)) .Times(12) .WillRepeatedly(Return()); EXPECT_CALL(*viewMock,displayCard(_)) .Times(2) .WillRepeatedly(Return()); EXPECT_CALL(*p1Mock,getHand()) .Times(6) .WillRepeatedly(Return(cTemp)); EXPECT_CALL(*viewMock,continueDiscarding()) .Times(6) .WillRepeatedly(Return(true)); EXPECT_CALL(*viewMock,chooseCard(_)) .Times(8) .WillRepeatedly(Return(1)); EXPECT_CALL(*p2Mock,sortHand()) .Times(1) .WillOnce(Return()); EXPECT_CALL(*p2Mock,getHandSize()) .Times(8) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(2)) .WillOnce(Return(0)); EXPECT_CALL(*viewMock,callCheat(_,_)) .Times(2) .WillOnce(Return(0)) .WillOnce(Return(1)); EXPECT_CALL(*p2Mock,takeCard(_)) .Times(4) .WillRepeatedly(Return(c1)); EXPECT_CALL(*p2Mock,getHand()) .Times(6) .WillRepeatedly(Return(cTemp)); EXPECT_CALL(*viewMock,endTurn()) .Times(2) .WillRepeatedly(Return()); EXPECT_CALL(*viewMock,endingMessage(_)) .Times(1) .WillOnce(Return()); controller->startGame(); controller->initalDeal(); controller->runGame(); }
true
cb505d95d16fcc02b0651f020d53c7e5e5e87ff6
C++
aurelienjoncour/Bombercraft
/lib/gameEngine/src/EntityManager/EntityManager.hpp
UTF-8
6,778
2.8125
3
[]
no_license
/* ** EPITECH PROJECT, 2021 ** gameEngine ** File description: ** 27/05/2021 EntityManager.hpp.h */ #ifndef ENTITYMANAGER_HPP #define ENTITYMANAGER_HPP #include <array> #include <algorithm> #include <memory> #include "entity.hpp" #include "IComponentTypeRegister.hpp" #include "EntityContainer/EntityRegister.hpp" #include "ComponentTypeRegister/ComponentTypeRegister.hpp" #include "Component/Component.hpp" #include "SaveManager/SaveManager.hpp" namespace Engine { class SystemManager; class EntityManager { public: explicit EntityManager(SystemManager &sysManager); ~EntityManager() = default; template <typename T> void registerComponent(); void allocate(std::size_t size); Entity createEntity(); void removeEntity(Entity entity); bool hasEntity(Entity entity); template <typename T> bool hasComponent(Entity entity); SystemManager &getSystemManager(); template <typename... Ts> bool hasComponents(Entity entity); template <typename T> T &getComponent(Entity entity); template <typename... Ts> std::tuple<Ts &...> getComponents(Entity entity); template <typename T, typename... Args> void addComponent(Entity entity, Args &&...args); template <typename T> void removeComponent(Entity entity); template <typename T> Entity getOwner(const T &component) const; template <typename T, class Function> void foreachComponent(Function fn); /** * @brief Allow user to access low level save, * managing it as he wants, * not saving everything, for example */ SaveManager saveManager{"Engine_Save"}; private: std::array<std::shared_ptr<IComponentTypeRegister>, MAX_COMPONENT> _componentRegisters; EntityRegister _entities; SystemManager &_systemManager; template <typename T> void checkComponentType() const; template <typename... Ts> void checkComponentTypes() const; template <typename T> ComponentTypeRegister<T> *getComponentContainer(); template <typename T> ComponentTypeRegister<T> *getComponentContainer() const; }; } // namespace Engine #include "SystemManager/SystemManager.hpp" namespace Engine { template <typename T> void EntityManager::registerComponent() { this->template checkComponentType<T>(); _componentRegisters[T::type] = std::make_shared<ComponentTypeRegister<T>>(_entities.getEntitySignatures()); } template <typename T> bool EntityManager::hasComponent(Entity entity) { this->checkComponentType<T>(); return _entities.getSignature(entity)[T::type]; } template <typename... Ts> bool EntityManager::hasComponents(Entity entity) { (this->checkComponentTypes<Ts>(), ...); auto requirements = Signature(); (requirements.set(Ts::type), ...); return (requirements & _entities.getSignature(entity)) == requirements; } template <typename T> T &EntityManager::getComponent(Entity entity) { this->checkComponentType<T>(); if (this->hasComponent<T>(entity) == false) { std::cerr << "EntityManager::getComponent Entity " << entity << " request " << T::type << " component." << std::endl; throw std::invalid_argument("EntityManager::getComponent The entity don't have the requested component."); } return this->getComponentContainer<T>()->get(entity); } template <typename... Ts> std::tuple<Ts &...> EntityManager::getComponents(Entity entity) { this->checkComponentTypes<Ts...>(); if (this->hasComponents<Ts...>(entity) == false) { ((std::cerr << "EntityManager::getComponents Entity " << entity << " request " << Ts::type << " component." << std::endl), ...); throw std::invalid_argument("EntityManager::getComponents The entity don't have the requested components."); } return std::tie(this->getComponentContainer<Ts>()->get(entity)...); } template <typename T, typename... Args> void EntityManager::addComponent(Entity entity, Args &&...args) { this->checkComponentType<T>(); if (_componentRegisters[T::type] == nullptr) { throw std::invalid_argument("Invalid component type (not registered?)"); } if (this->hasComponent<T>(entity)) { std::cerr << "EntityManager::addComponent : Entity " << (uint) entity << " => Component N " << T::type << std::endl; throw std::invalid_argument("EntityManager::addComponent, Same component added several time on an entity."); } this->getComponentContainer<T>()->add(entity, std::forward<Args>(args)...); // Send message to system const Signature &signature = _entities.getSignature(entity); this->_systemManager.onEntityUpdated(entity, signature); } template <typename T> void EntityManager::removeComponent(Entity entity) { this->checkComponentType<T>(); if (this->hasComponent<T>(entity) == false) { throw std::invalid_argument("EntityManager::removeComponent, the entity don't have T component."); } this->getComponentContainer<T>()->remove(entity); // Send message to systems const auto &signature = _entities.getSignature(entity); this->_systemManager.onEntityUpdated(entity, signature); } template <typename T> Entity EntityManager::getOwner(const T &component) const { this->checkComponentType<T>(); return this->getComponentContainer<T>()->getOwner(component); } template <typename T> void EntityManager::checkComponentType() const { static_assert(std::is_base_of<Component<T>, T>::value, "Invalid component type"); } template <typename... Ts> void EntityManager::checkComponentTypes() const { (this->template checkComponentType<Ts>(), ...); } template <typename T> ComponentTypeRegister<T> *EntityManager::getComponentContainer() { return static_cast<ComponentTypeRegister<T> *>(_componentRegisters[T::type].get()); } template <typename T> ComponentTypeRegister<T> *EntityManager::getComponentContainer() const { return static_cast<ComponentTypeRegister<T> *>(_componentRegisters[T::type].get()); } template <typename T, class Function> void EntityManager::foreachComponent(Function fn) { this->checkComponentType<T>(); std::vector<T> &components = this->getComponentContainer<T>()->getComponents(); std::for_each(components.begin(), components.end(), fn); } } // namespace Engine #endif // ENTITYMANAGER_HPP
true
171dfc9bd44f8dec07492af899ec6e777cfd5ba7
C++
anthony-phillips/utoledo-ieeextreme-12
/snakes_and_ladders/snl.cpp
UTF-8
2,706
3.109375
3
[]
no_license
#include<iostream> #include<iomanip> #include<tuple> #include<map> #include<fstream> #define files 1 using namespace std; //as reference - how to access elements //cout <<"head at (" <<std::get<0>(std::get<0>(snakes[i])) <<',' <<std::get<1>(std::get<0>(snakes[i])) <<")\n"; int board_size; class link{ public: tuple<int, int> data; int type; link *node; }; void append(link a, link* to_add) { while (a.node!=NULL) a=*a.node; //cout <<get<0>(a.data) <<'\n'; } void process(std::map<int, link> m, int d[], int d_size, int players) { std::map<int, link>::iterator it; int tiles=board_size*board_size-1; int player_list[players]; for (int i=0; i < players; ++i) player_list[i]=0; bool moved=false; for (int i=0; i < d_size; ++i) { if (player_list[i%players]==-1) continue; player_list[i%players]+=d[i]; moved=true; if (player_list[i%players] > tiles-1) { player_list[i%players]=-1; cout <<(i%players)+1 <<" winner\n"; } while (moved) { it=m.find(player_list[i%players]); if (it != m.end()) player_list[i%players]=get<1>(it->second.data); else moved=false; } } return; } int main() { cin >>board_size; int temp[4]; int player_size; cin >>player_size; std::map<int, link> list; link temp_l; std::map<int, link>::iterator it; //read in snakes int snake_size; cin >>snake_size; //cout <<"snake size is " <<snake_size <<'\n'; for (int i=0; i < snake_size; ++i) { cin >>temp[0] >>temp[1] >> temp[2] >>temp[3]; temp[0]=temp[0]*board_size+temp[1]-1; temp[2]=temp[2]*board_size+temp[3]-1; //cout <<"making node at " << temp[0] <<'\n'; temp_l={std::make_tuple(temp[0], temp[2]), 1, new link}; it=list.find(temp[0]); if (it !=list.end()) append(it->second, &temp_l); else list[temp[0]]=temp_l; } //read in ladders int ladder_size; cin >>ladder_size; for (int i=0; i < ladder_size; ++i) { cin >>temp[0] >>temp[1] >> temp[2] >>temp[3]; temp[0]=temp[0]*board_size+temp[1]-1; temp[2]=temp[2]*board_size+temp[3]-1; //cout <<"making node at " <<temp[2] <<'\n'; temp_l={make_tuple(temp[2],temp[0]), 2, new link}; it=list.find(temp[2]); if (it !=list.end()) append(it->second, &temp_l); else list[temp[2]]=temp_l; } //dice rolls int num_dice; cin >>num_dice; int dice[num_dice]; for (int i=0; i < num_dice; ++i) { cin >>temp[0] >>temp[1]; dice[i]=temp[0]+temp[1]; } process(list, dice, num_dice, player_size); }
true
114957333f1266a543c91cac554eb911f3ba34dc
C++
rilianx/manto3D
/manto/base/spaces/spaces3/Vector3.cpp
UTF-8
1,136
3.078125
3
[]
no_license
// // Created by Braulio Lobo on 9/18/19. // #include <iostream> #include "Vector3.h" #include "../../figures/figures3/Figure3.h" Vector2 Vector3::getProjection(const int PROJECTION_PLANE) { switch (PROJECTION_PLANE){ case Figure3::PROJECTION_XY: return {this->x, this->y}; case Figure3::PROJECTION_XZ: return {this->x, this->z}; case Figure3::PROJECTION_YZ: return {this->y, this->z}; default: std::cout << "Posible error 001" << std::endl; return {this->x, this->y}; } } float Vector3::getX() const { return x; } float Vector3::getY() const { return y; } float Vector3::getZ() const { return z; } Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) {} Vector3::Vector3() { this->x = 0; this->y = 0; this->z = 0; } Vector3::~Vector3() { } void Vector3::setX(float x) { Vector3::x = x; } void Vector3::setY(float y) { Vector3::y = y; } void Vector3::setZ(float z) { Vector3::z = z; } void Vector3::print() { std::cout << "(" << x << ", " << y << ", " << z << ")" << std::endl; }
true
a15bd07e3f6242a65f453cb24124dc5d2736606c
C++
JMarianczuk/SmallSorters
/sorters/StdSortWrapper.cpp
UTF-8
3,504
2.640625
3
[]
no_license
#include "StdSortWrapper.h" #include "Quicksort_Copy.h" #include "Quicksort_Copy2.h" #include "../StructHelpers.generated.h" #include "ska_sort.h" #include "radix_sort_thrill.h" namespace measurement { template <typename ValueType> bool NormalCompare(ValueType& left, ValueType& right) { return left < right; } template <typename ValueType> bool IteratorCompare(ValueType* left, ValueType* right) { return *left < *right; } template <typename ValueType> bool KeySortableCompare(uint64_t& key, ValueType& value) { return key < GetKey(value); } void StdSortWrapper( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left, SortableRef right)) { std::sort(first, last, compareFunc); } void QuicksortCopyWrapper( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left, SortableRef right)) { quicksortcopy2::sort(first, last, compareFunc); } // void QuicksortCopyMsvcWrapper( // SortableRef* first, // SortableRef* last, // bool(*compareFunc)(SortableRef left, SortableRef right)) // { // quicksortcopy::Quicksort_Copy_Msvc<conditional_swap::CS_Default>(first, last, compareFunc, sortFunc); // } template <> void RadixSortThrillWrapper<static_sorters::SampleSort>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left,SortableRef right)) { thrill::common::RadixSort<static_sorters::SampleSort, SortableRef, 8> sorter(256); sorter(first, last, compareFunc); } template <> void RadixSortThrillWrapper<static_sorters::StdSort>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left,SortableRef right)) { thrill::common::RadixSort<static_sorters::StdSort, SortableRef, 8> sorter(256); sorter(first, last, compareFunc); } template <> void RadixSortThrillWrapper<static_sorters::InsertionSortPred<insertionsort::InsertionSort_Default>>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left, SortableRef right)) { thrill::common::RadixSort<static_sorters::InsertionSortPred<insertionsort::InsertionSort_Default>, SortableRef, 8> sorter(256); sorter(first, last, compareFunc); } template <> void SkaSortWrapper<static_sorters::SampleSort>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left,SortableRef right)) { skasort::ska_sort<static_sorters::SampleSort>(first, last, [](SortableRef& item) {return item.key;}); } template <> void SkaSortWrapper<static_sorters::StdSort>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left,SortableRef right)) { skasort::ska_sort<static_sorters::StdSort>(first, last, [](SortableRef& item) {return item.key;}); } template <> void SkaSortWrapper<static_sorters::InsertionSortPred<insertionsort::InsertionSort_Default>>( SortableRef* first, SortableRef* last, bool(*compareFunc)(SortableRef left, SortableRef right)) { skasort::ska_sort<static_sorters::InsertionSortPred<insertionsort::InsertionSort_Default>>(first, last, [](SortableRef& item) {return item.key;}); } } // namespace measurement
true
a260e7d337f4f976e16a9f4ba78583318c0321e3
C++
jflcarvalho/FEUP-AEDA
/utils.h
UTF-8
6,944
3.34375
3
[]
no_license
/** * @file C:\Users\ineeve\Documents\GitHub\aeda-casino\utils.h * * @brief Declares the utilities. */ #pragma once #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <fstream> #include <iomanip> #include <time.h> using namespace std; /** * @struct Card * * @brief A card. * * @author Renato Campos * @date 19/11/2016 */ struct Card { /** @brief The rank. */ string rank; /** @brief The suits. */ string suits; /** @brief The score. */ unsigned int score; /** * @fn bool operator==(const Card &a) const * * @brief Equality operator. * * @author Renato Campos * @date 19/11/2016 * * @param a The Card to process. * * @return True if the parameters are considered equivalent. */ bool operator==(const Card &a) const { return (this->rank == a.rank); } /** * @fn bool operator==(const string &a) const * * @brief Equality operator. * * @author Renato Campos * @date 19/11/2016 * * @param a The rank to process. * * @return True if the parameters are considered equivalent. */ bool operator==(const string &a) const { return (this->rank == a); } ostream& operator<<(ostream& out) { out << this->rank; if (this->suits == "Heart") { out << (char)3; } if (this->suits == "Diamond") { out << (char)4; } if (this->suits == "Club") { out << (char)5; } if (this->suits == "Spade") { out << (char)6; } return out; } }; /** * @fn std::ostream& operator<<(std::ostream& out, const Card& c); * * @brief Stream insertion operator. * Makes the display of a card on the terminal. * @author Renato Campos * @date 19/11/2016 * * @param [in,out] out The outstream. * @param c The Card to process. * * @return The ostream produced. */ std::ostream& operator<<(std::ostream& out, const Card& c); /** * @fn std::ostream& operator<<(std::ostream& out, const vector<Card>& v); * * @brief Stream insertion operator. * * @author Renato Campos * @date 19/11/2016 * * @param [in,out] out The outstream. * @param v The vector of cards to process. * * @return The ostream produced. */ std::ostream& operator<<(std::ostream& out, const vector<Card>& v); /** * @fn vector <Card> createDeck(); * * @brief Creates the deck. * * @author Renato Campos * @date 19/11/2016 * * @return The new deck. */ vector <Card> createDeck(); /** * @fn string getHumanPlay(); * * @brief Gets human play. * * @author Renato Campos * @date 19/11/2016 * * @return The human play. */ string getHumanPlay(); /** * @fn unsigned short int readUnsignedIntBetween(unsigned int minValue, unsigned int maxValue); * * @brief Reads unsigned int between a minimum and a maximum values. * Ask for user input. * @author Renato Campos * @date 19/11/2016 * * @param minValue The minimum value. * @param maxValue The maximum value. * * @return A unsigned int between the parameters set. */ unsigned short int readUnsignedIntBetween(unsigned int minValue, unsigned int maxValue); /** * @fn int readIntBetween(int min, int max); * * @brief Reads int between a minimum and a maximum values. * Ask for user input. * @author Renato Campos * @date 19/11/2016 * * @param min The minimum. * @param max The maximum. * * @return The int between the parameters set. */ int readIntBetween(int min, int max); /** * @fn unsigned int readUnsignedInt(); * * @brief Reads unsigned int. * Asks for user input. * @author Renato Campos * @date 19/11/2016 * * @return The unsigned int. */ unsigned int readUnsignedInt(); /** * @fn int readInt(); * * @brief Reads a int value. * Asks for user input. * * @author Renato Campos * @date 19/11/2016 * * @return The int inserted by the user. */ int readInt(); /** * @fn int readBinary(); * * @brief Reads a 0 or a 1 from user input. * * @author Renato Campos * @date 19/11/2016 * * @return The user input. */ int readBinary(); /** * @fn float readFloat(); * * @brief Reads a float from user input. * * @author Renato Campos * @date 19/11/2016 * * @return The float inputed by the user. */ float readFloat(); /** * @fn char readCharYorN(); * * @brief Reads character "y" or "n". * Case insensitive. * * @author Renato Campos * @date 19/11/2016 * * @return The character inserted by the user: "y" or "n". */ char readCharYorN(); /** * @fn void Users(vector <int> &usersVEC, int &user); * * @brief Reads and parses the users file to usersVec. * * @author Renato Campos * @date 19/11/2016 * * @param [in,out] usersVEC The users vector. * @param [in,out] user The user id. */ void Users(vector <int> &usersVEC, int &user); /** * @fn void FileCopy(string filetxt, string filetxt_temp); * * @brief Copies text between files. * * @author Renato Campos * @date 19/11/2016 * * @param filetxt The file name; * @param filetxt_temp The temporary file name; */ void FileCopy(string filetxt, string filetxt_temp); /** * @fn bool FileExist(string filetxt_temp); * * @brief Checks if the file with name filetxt_temp exists. * * @author Renato Campos * @date 19/11/2016 * * @param filetxt_temp The temporary file name; * * @return True if it exists, false otherwise. */ bool FileExist(string filetxt_temp); /** * @fn int BinaryInt(int id, vector <int> VEC); * * @brief Performs a binary search of id in VEC. * * @author Renato Campos * @date 19/11/2016 * * @param id The identifier. * @param VEC The vector. * * @return The index of id in Vec, or -1 if id was not found. */ int BinaryInt(int id, vector <int> VEC); /** * @fn int saveChanges(vector <int> &usersVEC, int &user, pair <int, int> xy, int &save); * * @brief Asks user to save the current status when exiting. * * @author Renato Campos * @date 19/11/2016 * * @param [in,out] usersVEC The users vector. * @param [in,out] user The user id. * @param xy Pair with horizontal and vertical lengths of the terminal. * @param [in,out] save Boolean that holds user option to save or not the changes made. * * @return 0 in case of operation success. */ int saveChanges(vector <int> &usersVEC, int &user, pair <int, int> xy, int &save); /** * @fn int readNameOfFile(string &fileName); * * @brief Ask user to input a file name. * * @author Renato Campos * @date 19/11/2016 * * @param [in,out] fileName A string that will be updated with the user input. * * @return 0 in case of success. */ int readNameOfFile(string &fileName); /** * @fn void waitXTime(unsigned int time); * * @brief Sleeps for a given time. * * @author Renato Campos * @date 20/11/2016 * * @param time The time in seconds. * */ void waitXTime(unsigned int time);
true
cb886e1c6fd938dc9455035e0e143d7be793fc4e
C++
qzhongwood/CppRpcDemo
/src/RemotingCommand.cpp
UTF-8
4,009
2.609375
3
[]
no_license
#include "StdAfx.h" #include "RemotingCommand.h" #include "Buffer.h" AtomicCounter RemotingCommand::counter; RemotingCommand::RemotingCommand(void) : resultCode(0) , releasePayload(false) { ++counter; } RemotingCommand::RemotingCommand(BufferPtr buffer) : releasePayload(true) { ++counter; buffer2Command(buffer); } RemotingCommand::~RemotingCommand(void) { int n = --counter; rpcprintf("RemotingCommand destruction: <%x>, counter <%d>\n", this, n); if (releasePayload) { delete [] payload; } } string RemotingCommand::getOpCode() { return opCodeString; } void RemotingCommand::setOpCode(string opCodeString) { this->opCodeString = opCodeString; } size_t RemotingCommand::getIndex() { return index; } void RemotingCommand::setIndex(size_t idx) { this->index = idx; } map<string, string>& RemotingCommand::getHeader() { return header; } void RemotingCommand::setHeader(const map<string, string>& header) { this->header = header; } void RemotingCommand::setPayload(char* payload, unsigned long payloadLength) { this->payload = payload; this->payloadLength = payloadLength; } char* RemotingCommand::getPayload() { return payload; } size_t RemotingCommand::getPayloadLength() { return payloadLength; } char RemotingCommand::getResultCode() { return resultCode; } void RemotingCommand::setResultCode(char resultCode) { this->resultCode = resultCode; } void RemotingCommand::buffer2Command(BufferPtr source) { source->setOffset(0); source->deserialize(opCodeString); source->deserialize((char*)&index, sizeof(index)); source->deserialize((char*)&resultCode, sizeof(resultCode)); size_t headerSize; source->deserialize((char*)&headerSize, sizeof(headerSize)); for (size_t i = 0; i < headerSize; ++i) { string key; string value; source->deserialize(key); source->deserialize(value); header[key] = value; } source->deserialize((char*)&payloadLength, sizeof(payloadLength)); releasePayload = true; payload = new char[payloadLength + 1]; payload[payloadLength] = '\0'; source->deserialize(payload, payloadLength); } BufferPtr RemotingCommand::command2Buffer() { size_t headerSize = header.size(); size_t length = sizeof(opCodeString.length()); length += opCodeString.length(); length += sizeof(index); length += sizeof(resultCode); length += sizeof(headerSize); map<string, string>::iterator it = header.begin(); for (; it != header.end(); ++it) { length += sizeof(it->first.length()); length += it->first.length(); length += sizeof(it->second.length()); length += it->second.length(); } length += sizeof(payloadLength); length += payloadLength; BufferPtr buf = new Buffer(sizeof(length) + length); buf->serialize(length); buf->serialize(opCodeString); buf->serialize(index); buf->serialize((char*)&resultCode, sizeof(resultCode)); buf->serialize(headerSize); it = header.begin(); for (; it != header.end(); ++it) { buf->serialize(it->first); buf->serialize(it->second); } buf->serialize((char*)&payloadLength, sizeof(payloadLength)); buf->serialize(payload, payloadLength); return buf; } string RemotingCommand::toString() { char buf[10240]; string headerString; map<string, string>::iterator it = header.begin(); for (; it != header.end(); ++it) { char tmp[1024]; if (headerString.length() > 0) { headerString += ","; } sprintf(tmp, "<%s>=<%s>", it->first.c_str(), it->second.c_str()); headerString += tmp; } sprintf(buf, "index<%d>, opcode<%s>, resultCode<%d>, header<%s>, payload_length<%d>, payload<%s>", index, opCodeString.c_str(), resultCode, headerString.c_str(), payloadLength, payload); return buf; }
true
e78e38430a18443e15ed45548ff487f9837e0df9
C++
abhishekchandra2522k/CPPrograms
/GFG/Kaprekar_Number.cpp
UTF-8
742
2.9375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: int isKaprekar(int N) { if (N == 1) { return 1; } long long sqr = N * N; long long div = 1; long long temp = sqr / 10; while (temp != 0) { div *= 10; if (div == N) { continue; } if (((sqr % div) + (sqr / div)) == N) { return 1; } temp /= 10; } return 0; } }; int main() { int T; cin >> T; while (T--) { int N; cin >> N; Solution ob; cout << ob.isKaprekar(N) << endl; } return 0; }
true
e52f9424b355264c8cd8c4ac071fec910175e3b7
C++
abdllhyalcn/Cryptology
/Kriptoloji/ZigZag.cpp
UTF-8
1,248
3.203125
3
[]
no_license
#include "ZigZag.h" void ZigZag::Encryption(string& mesaj, const int key) { string* satir = new string[key]; int liner = 0; int positioner = +1; for (int i = 0; i < mesaj.length(); i++) { if (liner == key-1) { positioner=-1; } else if (liner == 0) { positioner=+1; } (*(satir+liner)).push_back(mesaj.at(i)); liner += positioner; } string temp; for (int i = 0; i < key; i++) { temp.append(*(satir+i)); } mesaj = temp; } void ZigZag::Decryption(string& mesaj,const int key) { int msgLen = mesaj.length(), i, j, k = -1, row = 0, col = 0, m = 0; char** railMatrix = new char* [key]; for (int i = 0; i < key; i++) railMatrix[i] = new char[mesaj.length()]; for (i = 0; i < key; ++i) for (j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for (i = 0; i < msgLen; ++i) { railMatrix[row][col++] = '*'; if (row == 0 || row == key - 1) k = k * (-1); row = row + k; } for (i = 0; i < key; ++i) for (j = 0; j < msgLen; ++j) if (railMatrix[i][j] == '*') railMatrix[i][j] = mesaj[m++]; row = col = 0; k = -1; string temp; for (i = 0; i < msgLen; ++i) { temp.push_back(railMatrix[row][col++]); if (row == 0 || row == key - 1) k = k * (-1); row = row + k; } mesaj = temp; }
true
62c4981157782b98187fc1a09932161aa97c4109
C++
niranjan-85/Data-structures
/C++/Binary Search Trees/BSTusingPreorder.cpp
UTF-8
2,030
3.53125
4
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef struct node { int data; node* left, *right; }; node* newnode; void preorder(node* p) { if (p) { preorder(p->left); cout << p->data<<" "; preorder(p->right); } } node* make(node *ptr,int k) { newnode = new node; newnode->left = newnode->right = NULL; newnode->data = k; return newnode; } node * create(int key,node *temp) { if (temp == NULL) { newnode = new node; newnode->left = newnode->right = NULL; newnode->data = key; return newnode; } else if (key > temp->data) { temp->right = create(key, temp->right); } else { temp->left=create(key,temp->left); } return temp; } node * generate(int a[],int n,stack<node *> s) { node* root = new node; root->left = root->right = NULL; root->data = a[0]; node* p = root; for (int i = 1; i < n; i++) { if (a[i] < p->data) { newnode = make(p, a[i]); p->left = newnode; s.push(p); p = newnode; } else if (a[i] > p->data) { if (s.empty()) { newnode = make(p, a[i]); p->right = newnode; p = newnode; } else if (a[i] < s.top()->data) { newnode = make(p, a[i]); p->right = newnode; p = newnode; } else { p = s.top(); s.pop(); i--; } } } return root; } void main() { int a[100], n; cout << "Enter the elemets of a BST" << endl; cin >> n; cout << "Enter preorder traversal " << endl; for (int i = 0; i < n; i++) { cin >> a[i]; } stack <node*> s; preorder(generate(a,n,s)); //node* root = NULL; //root = create(a[0],root); /*for (int i = 1; i < n; i++) { create(a[i], root); }*/ //preorder(root); cout << endl; //search(root, 25) ? cout << "Found" << endl : cout<<"Not found"<<endl; //search(root, 30) ? cout << "Found" << endl : cout << "Not found" << endl; //delete_(root, 35); //cout << inorder_pred(root->left)->data << endl; //cout << inorder_succ(root -> right)->data << endl; }
true
8abce6c026ec1c4c40f9a7facdaa0eb6ef334c4c
C++
coding-freak456/algorithmsUse
/C++/Math/binary_exponentiation.cpp
UTF-8
444
3.5
4
[ "MIT" ]
permissive
/* * Author: karthikeyan rathore * Binary Exponentiation Algorithm recursive approach */ #include<bits/stdc++.h> using namespace std; long long bin(long long a , long long b){ if(b == 0) return 1; long long res = bin(a , b/2); if( b % 2) { return res * res * a; } else return res * res; } int main(){ long long a = 2 , b = 5; long long ans = bin(2 , 5); cout << ans; } /* * INPUT : a = 2 , b = 5 ....(2 ^ 5) * OUTPUT : 32 */
true
e1e2015abb59bd9ead30da237dd9fcf325f8131e
C++
AutumnKite/Codes
/Codeforces/1555F Good Graph/std.cpp
UTF-8
6,447
2.75
3
[]
no_license
#include <bits/stdc++.h> class DSU { std::vector<int> fa; public: DSU(int n) : fa(n) { for (int i = 0; i < n; ++i) { fa[i] = i; } } int find(int x) { return fa[x] == x ? x : (fa[x] = find(fa[x])); } bool merge(int x, int y) { x = find(x), y = find(y); if (x == y) { return false; } fa[y] = x; return true; } }; struct max { int operator()(int a, int b) const { return std::max(a, b); } }; #if __cplusplus > 201103L template<typename _Val, typename _Tag = _Val, typename _VV = std::plus<>, typename _VT = std::plus<>, typename _TT = std::plus<>> #else template<typename _Val, typename _Tag, typename _VV, typename _VT, typename _TT> #endif class segment_tree { public: typedef std::size_t size_type; private: static size_type enlarge(size_type n) { size_type res = 1; while (res < n) { res <<= 1; } return res; } protected: const size_type n, en; _VV fun_vv; _VT fun_vt; _TT fun_tt; std::vector<_Val> val; std::vector<_Tag> tag; void up(size_type u) { val[u] = fun_vv(val[u << 1], val[u << 1 | 1]); } void apply(size_type u, _Tag v) { val[u] = fun_vt(val[u], v); tag[u] = fun_tt(tag[u], v); } void down(size_type u) { apply(u << 1, tag[u]); apply(u << 1 | 1, tag[u]); tag[u] = _Tag(); } void build(size_type u, size_type l, size_type r, const std::vector<_Val> &a) { if (l + 1 == r) { val[u] = a[l]; return; } size_type mid = (l + r + 1) >> 1; build(u << 1, l, mid); build(u << 1 | 1, mid, r); up(u); } void modify(size_type u, size_type l, size_type r, size_type L, size_type R, _Tag v) { if (L <= l && r <= R) { apply(u, v); return; } size_type mid = (l + r + 1) >> 1; down(u); if (L < mid) { modify(u << 1, l, mid, L, R, v); } if (mid < R) { modify(u << 1 | 1, mid, r, L, R, v); } up(u); } _Val query(size_type u, size_type l, size_type r, size_type L, size_type R) { if (L <= l && r <= R) { return val[u]; } size_type mid = (l + r + 1) >> 1; down(u); if (R <= mid) { return query(u << 1, l, mid, L, R); } else if (L >= mid) { return query(u << 1 | 1, mid, r, L, R); } else { return fun_vv(query(u << 1, l, mid, L, R), query(u << 1 | 1, mid, r, L, R)); } } public: segment_tree() : segment_tree(0) {} segment_tree(size_type _n) : n(_n), en(enlarge(n)), val(en << 1), tag(en << 1) {} segment_tree(const std::vector<_Val> &a) : n(a.size()), en(enlarge(n)), val(en << 1), tag(en << 1) { build(1, 0, n, a); } size_type size() const { return n; } void modify(size_type l, size_type r, _Tag v) { if (l < r) { modify(1, 0, n, l, r, v); } } _Val query(size_type l, size_type r) { if (l < r) { return query(1, 0, n, l, r); } else { return _Val(); } } }; class tree { int n; int idx; std::vector<std::vector<std::pair<int, int>>> E; std::vector<int> fa, sz, dep, dis, son, top, dfn; segment_tree<bool, bool, std::logical_or<>, std::logical_or<>, std::logical_or<>> T; void dfs(int u) { sz[u] = 1; son[u] = -1; for (auto [v, w] : E[u]) { if (v != fa[u]) { fa[v] = u; dep[v] = dep[u] + 1; dis[v] = dis[u] ^ w; dfs(v); sz[u] += sz[v]; if (son[u] == -1 || sz[v] > sz[son[u]]) { son[u] = v; } } } } void dfs(int u, int tp) { top[u] = tp; dfn[u] = idx++; if (son[u] != -1) { dfs(son[u], tp); } for (auto [v, w] : E[u]) { if (v != fa[u] && v != son[u]) { dfs(v, v); } } } int LCA(int u, int v) { while (top[u] != top[v]) { if (dep[top[u]] > dep[top[v]]) { u = fa[top[u]]; } else { v = fa[top[v]]; } } return dep[u] < dep[v] ? u : v; } bool check(int u, int v) { while (top[u] != top[v]) { if (T.query(dfn[top[u]], dfn[u] + 1)) { return false; } u = fa[top[u]]; } return !T.query(dfn[v] + 1, dfn[u] + 1); } void cover(int u, int v) { while (top[u] != top[v]) { T.modify(dfn[top[u]], dfn[u] + 1, true); u = fa[top[u]]; } T.modify(dfn[v] + 1, dfn[u] + 1, true); } public: tree(const std::vector<std::vector<std::pair<int, int>>> &_E) : n(_E.size()), idx(0), E(_E), fa(n, -1), sz(n), dep(n), dis(n), son(n), top(n), dfn(n), T(n) { for (int i = 0; i < n; ++i) { if (fa[i] == -1) { dfs(i); dfs(i, i); } } } bool add_edge(int u, int v, int w) { if ((dis[u] ^ dis[v]) == w) { return false; } int z = LCA(u, v); if (!check(u, z) || !check(v, z)) { return false; } cover(u, z); cover(v, z); return true; } }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); int n, m; std::cin >> n >> m; std::vector<int> X(m), Y(m), W(m); DSU D(n); std::vector<std::vector<std::pair<int, int>>> E(n); std::vector<bool> ans(m); for (int i = 0; i < m; ++i) { std::cin >> X[i] >> Y[i] >> W[i]; --X[i], --Y[i]; if (D.merge(X[i], Y[i])) { E[X[i]].emplace_back(Y[i], W[i]); E[Y[i]].emplace_back(X[i], W[i]); ans[i] = true; } } tree T(E); for (int i = 0; i < m; ++i) { if (!ans[i]) { ans[i] = T.add_edge(X[i], Y[i], W[i]); } } for (int i = 0; i < m; ++i) { if (ans[i]) { std::cout << "YES\n"; } else { std::cout << "NO\n"; } } }
true
be4fda16ac19434431a1f9e471387371f4948b92
C++
olesyastorchakprojects/Vocabulator
/Database/examplestable.cpp
UTF-8
3,285
2.59375
3
[]
no_license
#include "examplestable.h" #include <QSqlQuery> #include <QVariant> #include <QDateTime> #include "database.h" QList<Example> ExamplesTable::selectAll() { QList<Example> list; QSqlQuery q; if(q.exec(QString("SELECT id, example, created, type from examples"))) { while(q.next()) { Example example(q.value(0).toInt(), q.value(1).toString(), q.value(2).toString(), static_cast<Example::ExampleType>(q.value(3).toInt())); list.push_back(example); } } return list; } QList<Example> ExamplesTable::examples(const int anchorId, Example::ExampleType exampleType) { QList<Example> list; QSqlQuery q; if(q.exec(QString("SELECT id, example, created from examples where definitionId=%1 and type=%2").arg(QString::number(anchorId), QString::number(exampleType)))) { while(q.next()) { Example example(q.value(0).toInt(), q.value(1).toString(), q.value(2).toString(), exampleType); list.push_back(example); } } return list; } int ExamplesTable::insertExample(const QString& example, const int definitionId, const Example::ExampleType exampleType) { QSqlQuery q; if(q.exec(QString("insert into examples (example, definitionId, created, type) values (\"%1\", %2, \"%3\", %4)").arg( example, QString::number(definitionId), Database::currentTime(), QString::number(exampleType)))) { return q.lastInsertId().toInt(); } return -1; } Example ExamplesTable::getExample(int exampleId) { QSqlQuery q; if(q.exec(QString("select example, created, type from examples where id=%1").arg(QString::number(exampleId)))) { if(q.next()) { return Example(exampleId, q.value(0).toString(), q.value(1).toString(), static_cast<Example::ExampleType>(q.value(2).toInt())); } } return Example(); } Example ExamplesTable::getExample(const QString& exampleName) { QSqlQuery q; if(q.exec(QString("select id, created, type from examples where example=\"%1\"").arg(exampleName))) { if(q.next()) { return Example(q.value(0).toInt(), exampleName, q.value(1).toString(), static_cast<Example::ExampleType>(q.value(2).toInt())); } } return Example(); } bool ExamplesTable::removeExample(int exampleId) { QSqlQuery q; if(q.exec(QString("delete from examples where id = \"%1\"").arg(QString::number(exampleId)))) { return true; } return false; } bool ExamplesTable::removeExample(const QString& exampleName) { QSqlQuery q; if(q.exec(QString("delete from examples where example = \"%1\"").arg(exampleName))) { return true; } return false; } bool ExamplesTable::removeAll() { QSqlQuery q; if(q.exec(QString("delete from examples"))) { return true; } return false; } bool ExamplesTable::updateExample(const Example& example) { QSqlQuery q; if(q.exec(QString("update examples set example=\"%1\", created = \"%2\", type = %4 where id = %3") .arg(example.value(), example.createdAt(), QString::number(example.id()), QString::number(example.exampleType())))) { return true; } return false; }
true
c7fe855f610e2f72cbad1dbeea2b2a06ba831d9a
C++
Alexisflipi/Club-de-Algoritmia
/Online-judge/COJ/2202 - How Many Lattice Points.cpp
UTF-8
606
2.625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; typedef long long lld; struct Punto{ lld x, y, z; Punto(lld a, lld b, lld c) : x(a), y(b), z(c) {} }; lld ad(Punto &A, Punto &B) { lld x = (B.x - A.x); lld y = (B.y - A.y); lld z = (B.z - A.z); return abs(__gcd(x, abs(__gcd(y, z)))) - 1; } lld solve(Punto &A, Punto &B) { lld r = ad(A, B); return r + 2; } int main() { ios::sync_with_stdio(0); cin.tie(0); lld a, b, c; while (cin >> a >> b >> c) { Punto A = Punto(a, b, c); cin >> a >> b >> c; Punto B = Punto(a, b, c); cout << solve(A, B) << "\n"; } return 0; }
true
d7851fd227f39092492f967b1ba892e142650bfb
C++
mcvine/mantid
/Framework/CurveFitting/src/ParDomain.cpp
UTF-8
3,157
2.6875
3
[]
no_license
//---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- #include "MantidCurveFitting/ParDomain.h" #include "MantidKernel/MultiThreaded.h" namespace Mantid { namespace CurveFitting { /** * Create and return i-th domain and i-th values, (i-1)th domain is released. * @param i :: Index of domain to return. * @param domain :: Output pointer to the returned domain. * @param values :: Output pointer to the returned values. */ void ParDomain::getDomainAndValues(size_t i, API::FunctionDomain_sptr &domain, API::FunctionValues_sptr &values) const { if (i >= m_creators.size()) throw std::range_error("Function domain index is out of range."); if (!m_domain[i]) { m_creators[i]->createDomain(m_domain[i], m_values[i]); } domain = m_domain[i]; values = m_values[i]; } /** * Calculate the value of a least squares cost function * @param leastSquares :: The least squares cost func to calculate the value for */ void ParDomain::leastSquaresVal( const CostFunctions::CostFuncLeastSquares &leastSquares) { const int n = static_cast<int>(getNDomains()); PARALLEL_FOR_NO_WSP_CHECK() for (int i = 0; i < n; ++i) { API::FunctionDomain_sptr domain; API::FunctionValues_sptr values; getDomainAndValues(static_cast<size_t>(i), domain, values); if (!values) { throw std::runtime_error("LeastSquares: undefined FunctionValues."); } leastSquares.addVal(domain, values); // PARALLEL_CRITICAL(printout) //{ // std::cerr << "val= " << leastSquares.m_value << std::endl; //} } } /** * Calculate the value, first and second derivatives of a least squares cost * function * @param leastSquares :: The least squares cost func to calculate the value for * @param evalDeriv :: Flag to evaluate the first derivatives * @param evalHessian :: Flag to evaluate the Hessian (second derivatives) */ void ParDomain::leastSquaresValDerivHessian( const CostFunctions::CostFuncLeastSquares &leastSquares, bool evalDeriv, bool evalHessian) { const int n = static_cast<int>(getNDomains()); PARALLEL_SET_DYNAMIC(0); std::vector<API::IFunction_sptr> funs; // funs.push_back( leastSquares.getFittingFunction()->clone() ); PARALLEL_FOR_NO_WSP_CHECK() for (int i = 0; i < n; ++i) { API::FunctionDomain_sptr domain; API::FunctionValues_sptr values; getDomainAndValues(i, domain, values); auto simpleValues = boost::dynamic_pointer_cast<API::FunctionValues>(values); if (!simpleValues) { throw std::runtime_error("LeastSquares: undefined FunctionValues."); } std::vector<API::IFunction_sptr>::size_type k = PARALLEL_THREAD_NUMBER; PARALLEL_CRITICAL(resize) { if (k >= funs.size()) { funs.resize(k + 1); } if (!funs[k]) { funs[k] = leastSquares.getFittingFunction()->clone(); } } leastSquares.addValDerivHessian(funs[k], domain, simpleValues, evalDeriv, evalHessian); } } } // namespace CurveFitting } // namespace Mantid
true
f774f6d117a7e4c476724e54467b0cc145982ac6
C++
tjy1985001/Teaching
/C-2018/C语言循环/stu_score.cpp
UTF-8
575
3.046875
3
[]
no_license
#include <stdio.h> int main() { int score = 0; int max_score = 0; int min_score = 100; int sum = 0; for (int i = 0; i < 5; i++) { printf("请输入第%d个学生成绩\n", i + 1); scanf("%d", &score); if (score > max_score) { max_score = score; } if (score < min_score) { min_score = score; } sum += score; } printf("max score = %d, min score = %d, average = %.2f\n", max_score, min_score, sum / 5.0); return 0; }
true
21da7f5af9a254ec423c0f44edcaf828be03c702
C++
aptx1231/PAT_BasicLevel
/1087 有多少不同的值(20).cpp
WINDOWS-1252
333
2.640625
3
[]
no_license
#include<iostream> #include<algorithm> using namespace std; int a[11000]; //ֵ10000/2+10000/3+10000/5=10333 int main() { int n; cin >> n; int cnt = 0; for (int i=1;i<=n;i++) { int tmp = i/2+i/3+i/5; //cout << tmp << endl; if (a[tmp] == 0) { a[tmp] = 1; cnt++; } } cout << cnt << endl; return 0; }
true
5aa314f9b4b1db6b1ec49a16ea109dddbdc21d3c
C++
zhmu/ananas
/external/gcc-12.1.0/libstdc++-v3/testsuite/23_containers/deque/modifiers/swap/2.cc
UTF-8
3,906
2.78125
3
[ "LGPL-2.1-only", "GPL-3.0-only", "GCC-exception-3.1", "GPL-2.0-only", "LGPL-3.0-only", "LGPL-2.0-or-later", "Zlib", "LicenseRef-scancode-public-domain" ]
permissive
// 2005-12-20 Paolo Carlini <pcarlini@suse.de> // Copyright (C) 2005-2022 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 23.2.1.3 deque::swap #include <deque> #include <testsuite_hooks.h> #include <testsuite_allocator.h> // uneq_allocator as a non-empty allocator. void test01() { using namespace std; typedef __gnu_test::uneq_allocator<char> my_alloc; typedef deque<char, my_alloc> my_deque; const char title01[] = "Rivers of sand"; const char title02[] = "Concret PH"; const char title03[] = "Sonatas and Interludes for Prepared Piano"; const char title04[] = "never as tired as when i'm waking up"; const size_t N1 = sizeof(title01); const size_t N2 = sizeof(title02); const size_t N3 = sizeof(title03); const size_t N4 = sizeof(title04); my_deque::size_type size01, size02; my_alloc alloc01(1); my_deque deq01(alloc01); size01 = deq01.size(); my_deque deq02(alloc01); size02 = deq02.size(); deq01.swap(deq02); VERIFY( deq01.size() == size02 ); VERIFY( deq01.empty() ); VERIFY( deq02.size() == size01 ); VERIFY( deq02.empty() ); my_deque deq03(alloc01); size01 = deq03.size(); my_deque deq04(title02, title02 + N2, alloc01); size02 = deq04.size(); deq03.swap(deq04); VERIFY( deq03.size() == size02 ); VERIFY( equal(deq03.begin(), deq03.end(), title02) ); VERIFY( deq04.size() == size01 ); VERIFY( deq04.empty() ); my_deque deq05(title01, title01 + N1, alloc01); size01 = deq05.size(); my_deque deq06(title02, title02 + N2, alloc01); size02 = deq06.size(); deq05.swap(deq06); VERIFY( deq05.size() == size02 ); VERIFY( equal(deq05.begin(), deq05.end(), title02) ); VERIFY( deq06.size() == size01 ); VERIFY( equal(deq06.begin(), deq06.end(), title01) ); my_deque deq07(title01, title01 + N1, alloc01); size01 = deq07.size(); my_deque deq08(title03, title03 + N3, alloc01); size02 = deq08.size(); deq07.swap(deq08); VERIFY( deq07.size() == size02 ); VERIFY( equal(deq07.begin(), deq07.end(), title03) ); VERIFY( deq08.size() == size01 ); VERIFY( equal(deq08.begin(), deq08.end(), title01) ); my_deque deq09(title03, title03 + N3, alloc01); size01 = deq09.size(); my_deque deq10(title04, title04 + N4, alloc01); size02 = deq10.size(); deq09.swap(deq10); VERIFY( deq09.size() == size02 ); VERIFY( equal(deq09.begin(), deq09.end(), title04) ); VERIFY( deq10.size() == size01 ); VERIFY( equal(deq10.begin(), deq10.end(), title03) ); my_deque deq11(title04, title04 + N4, alloc01); size01 = deq11.size(); my_deque deq12(title01, title01 + N1, alloc01); size02 = deq12.size(); deq11.swap(deq12); VERIFY( deq11.size() == size02 ); VERIFY( equal(deq11.begin(), deq11.end(), title01) ); VERIFY( deq12.size() == size01 ); VERIFY( equal(deq12.begin(), deq12.end(), title04) ); my_deque deq13(title03, title03 + N3, alloc01); size01 = deq13.size(); my_deque deq14(title03, title03 + N3, alloc01); size02 = deq14.size(); deq13.swap(deq14); VERIFY( deq13.size() == size02 ); VERIFY( equal(deq13.begin(), deq13.end(), title03) ); VERIFY( deq14.size() == size01 ); VERIFY( equal(deq14.begin(), deq14.end(), title03) ); } int main() { test01(); return 0; }
true
3a9ffa73ce869decaca8f85e9eab28d44a1cca11
C++
OpMonTeam/Projet-Pokemon-Regimys
/src/jlppc/regimys/start/main.hpp
WINDOWS-1250
1,056
2.515625
3
[]
no_license
/* main.hpp Auteur : Jlppc Fichier sous licence GPL-3.0 http://regimys.tk Contient des fonctions necessaires au programme */ #ifndef MAIN_HPP #define MAIN_HPP #include <iostream> #include <fstream> #include "../../utils/File.hpp" #include "../playercore/Player.hpp" #include <sstream> #define UNS using namespace std; #define toStr(toStrP) #toStrP #define PRINT_TICKS "[T = " << SDL_GetTicks() << "] - " /**Le log principal*/ extern std::ofstream rlog; /**Le log d'erreur*/ extern std::ofstream rerrLog; /** Methode a appeler lorsqu'une erreur peut intervenir dans le programme fatal : si true, teint le programme */ void gererErreur(std::string errorName, bool fatal); /** Methode qui quitte le programme en fermant toutes les ressources retourne : ce que le programme retournera */ int quit(int retourne); /** Namespace contenant des variables utiles au fonctionnement du jeu */ namespace Main { void main(); //->Useless extern long startTime; } /** Methode permettant de demmarer le jeu */ int main(int argc, char *argv[]); #endif // MAIN_HPP
true
ea146e8f1e7999669c25b694370fd040544e899a
C++
Spuddles/OpenCL-Testing
/Converters/FullBlock.cpp
UTF-8
1,006
2.984375
3
[]
no_license
#include "FullBlock.h" #include <algorithm> #include <sstream> #include "Utils.h" #include "Structs.h" FullBlock::FullBlock() { } FullBlock::~FullBlock() { } bool FullBlock::initialise() { return Converter::initialise(); } unsigned char FullBlock::getMainColour(RGBA *image) { int r{ 0 }, g{ 0 }, b{ 0 }; for (int i = 0; i < 64; i++) { RGBA &rgb = *image; r += rgb.R; g += rgb.G; b += rgb.B; image++; } RGBA colour; colour.R = r / 64; colour.G = g / 64; colour.B = b / 64; return getConsoleColour(colour); } bool FullBlock::convert(RGBA *input, CHAR_INFO *output) { for (int i = 0; i < 80*50; i++) { RGBA image[8 * 8]; int x = i % 80; int y = i / 80; // First extract the char we want to process Utils::extractFromImage((char*)input, 640, 400, (char*)image, 8, 8, x, y); char colour = getMainColour(image); output->Char.AsciiChar = 219; output->Attributes = colour; output++; } return true; } std::string FullBlock::getName() { return "FullBlock"; }
true
ff9da37c1e9581b7021e59cc296b59feaa096474
C++
Mikolka09/TESTING
/TESTING_OOP/Admin.cpp
UTF-8
21,682
2.765625
3
[]
no_license
#include"Admin.h" void Admin::shapka_start() { string S(40, '#'); gotoxy(30, 1); SetColor(8, 0); cout << S << endl; gotoxy(37, 2); SetColor(12, 0); cout << "ТЕСТОВАЯ БАЗА ТЕСТИРОВАНИЙ" << endl; gotoxy(30, 3); SetColor(8, 0); cout << S << endl << endl; } Admin::Admin(const Admin& ob) { log_admin_.clear(); log_admin_ = ob.log_admin_; pass_admin_ = ob.pass_admin_; } Admin& Admin::operator=(const Admin& ob) { log_admin_.clear(); log_admin_ = ob.log_admin_; pass_admin_ = 0; pass_admin_ = ob.pass_admin_; return *this; } //регестрация администратора void Admin::registry_in_admin() { if (log_admin_.empty()) { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕГЕСТРАЦИЯ АДМИНИСТРАТОРА:\n" << endl; string log; SetColor(14, 0); cout << "Введите ЛОГИН: "; SetColor(15, 0); cin >> log; uppercase(log); string pas; bool ad = true; while (ad) { SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; ad = check_size(pas); } auto pass = hashing(pas); this->log_admin_ = log; this->pass_admin_ = pass; SetColor(12, 0); cout << "\nДанные АДМИНИСТРАТОРА сохранены!!!" << endl; SetColor(15, 0); Sleep(2500); save_login_pass(); } else { system("cls"); SetColor(12, 0); gotoxy(10, 10); cout << "ОШИБКА!!! АДМИНИСТРАТОР уже ЗАРЕГЕСТРИРОВАН!!!" << endl; SetColor(15, 0); Sleep(2500); } } //меню админитсратора void Admin::menu_admin() { while (true) { system("cls"); shapka_start(); SetColor(12, 0); cout << "МЕНЮ АДМИНИСТРАТОРА:\n" << endl; SetColor(14, 0); cout << "1. Управление ПОЛЬЗОАВАТЕЛЯМИ\n" << "2. Управление СТАТИСТИКОЙ\n" << "3. Управление ТЕСТАМИ\n" << "4. Управление данными АДМИНИСТРАТОРА\n" << "5. Выход\n" << endl; int var1; bool v = true; while (v) { SetColor(15, 0); cin >> var1; cin.ignore(); if (var1 < 1 || var1 > 5) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; SetColor(15, 0); } else v = false; } switch (var1) { case 1: control_user(); break; case 2: look_statics(); break; case 3: control_tests(); break; case 4: change_login(); break; case 5: exit(0); default:; } } } //управление тестами void Admin::control_tests() { while (true) { Tested tes; Maths mat; Physics phys; Chemistry chem; system("cls"); shapka_start(); SetColor(12, 0); cout << "УПРАВЛЕНИЕ ТЕСТАМИ:\n" << endl; SetColor(14, 0); cout << "1. Управление тестами по МАТЕМАТИКЕ\n" << "2. Управление тестами по ФИЗИКЕ\n" << "3. Управление тестами по ХИМИИ\n" << "4. Возврат в предыдущее меню\n" << endl; int var1; bool v = true; while (v) { SetColor(15, 0); cin >> var1; cin.ignore(); if (var1 < 1 || var1 > 4) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; SetColor(15, 0); } else v = false; } switch (var1) { case 1: mat.menu_maths_admin(); break; case 2: phys.menu_physics_admin(); break; case 3: chem.menu_chem_admin();; break; case 4: menu_admin(); break; default:; } } } //загрузка тестов из файла void Admin::load_tests() { } //изменение логина и пароля администратора void Admin::change_login() { bool l = true; string log; while (l) { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕДАКТИРОВАНИЕ ДАННЫХ АДМИНИСТРАТОРА:\n" << endl; SetColor(14, 0); cout << "Введите новый ЛОГИН: "; SetColor(15, 0); cin >> log; uppercase(log); if (get_log_admin() == log) { SetColor(12, 0); cout << "\nТакой ЛОГИН уже есть, введите другой ЛОГИН!!!" << endl; SetColor(14, 0); Sleep(2500); } else l = false; } set_log_admin(log); SetColor(12, 0); cout << "\nЛОГИН ИЗМЕНЕН!!" << endl; SetColor(15, 0); Sleep(2500); bool ad = true; string pas; //проверка пороля на размер while (ad) { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕДАКТИРОВАНИЕ ДАННЫХ АДМИНИСТРАТОРА:\n" << endl; SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; ad = check_size(pas); } auto pass = hashing(pas); bool p = true; //проверка пароля на повторение while (p) { if (get_pass_admin() == pass) { SetColor(12, 0); cout << "\nТакой ПАРОЛЬ уже есть, введите другой ПАРОЛЬ!!!" << endl; Sleep(2500); system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕДАКТИРОВАНИЕ ДАННЫХ АДМИНИСТРАТОРА:\n" << endl; SetColor(14, 0); cout << "Введите новый ПАРОЛЬ: "; SetColor(15, 0); cin >> pas; pass = hashing(pas); if (get_log_admin() != log) p = false; } else p = false; } set_pass_admin(pass); SetColor(12, 0); cout << "\nПАРОЛЬ ИЗМЕНЕН!!" << endl; SetColor(15, 0); Sleep(2500); save_login_pass(); } void Admin::registry_user() { string log; bool lp = true; User* user = new User; Tested tes; tes.load_base(); //проверяем логин на повторение while (lp) { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕГЕСТРАЦИЯ ПОЛЬЗОВАТЕЛЯ:\n" << endl; SetColor(14, 0); cout << "Введите ЛОГИН: "; SetColor(15, 0); cin >> log; uppercase(log); int count = 0; //поиск одинаковых логинов со счетчиком auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == log) { count++; } } if (count != 0) { SetColor(12, 0); cout << "\nТакой ЛОГИН уже есть, введите другой ЛОГИН!!!" << endl; SetColor(15, 0); Sleep(2500); } else lp = false; } user->set_login(log); string pas; bool ad = true; //проверка пороля на размер while (ad) { SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; ad = check_size(pas); } //шифрование пароля auto pass = hashing(pas); bool ps = true; while (ps) { auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_pass() == pass) { SetColor(12, 0); cout << "\nТакой ПАРОЛЬ уже есть, введите другой ПАРОЛЬ!!!" << endl; SetColor(15, 0); Sleep(2500); bool d = true; while (d) { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕГЕСТРАЦИЯ ПОЛЬЗОВАТЕЛЯ:\n" << endl; SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; d = check_size(pas); } pass = hashing(pas); if ((*it)->get_pass() != pass) ps = false; } else ps = false; } } user->set_pass(pass); char* n = new char; cin.ignore(); SetColor(14, 0); cout << "Введите ФИО: "; SetColor(15, 0); cin.getline(n, 100); string name = n; user->set_name(name); string email; SetColor(14, 0); cout << "Введите электронный адрес: "; SetColor(15, 0); cin >> email; user->set_email(email); string phone; SetColor(12, 0); cout << "Введите номер телефона: "; SetColor(15, 0); cin >> phone; user->set_phone(phone); tes.base_tested_.push_back(user); SetColor(12, 0); cout << "\nПОЛЬЗОВАТЕЛЬ ДОБАВЛЕН!!!" << endl; SetColor(15, 0); Sleep(2500); tes.save_base(); control_user(); } //изменение данных пользователя (тестируемого) void Admin::control_user() { while (true) { Tested tes; tes.load_base(); system("cls"); shapka_start(); SetColor(12, 0); cout << "УПРАВЛЕНИЕ ПОЛЬЗОВАТЕЛЯМИ:\n" << endl; SetColor(14, 0); cout << "1. Создание ПОЛЬЗОАВАТЕЛЯ\n" << "2. Удаление ПОЛЬЗОВАТЕЛЯ\n" << "3. Редактирование ПОЛЬЗОВАТЕЛЯ\n" << "4. Печать ПОЛЬЗОВАТЕЛЕЙ\n" << "5. Возврат в предыдущее меню\n" << endl; int var; bool v = true; while (v) { SetColor(15, 0); cin >> var; cin.ignore(); if (var < 1 || var > 5) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; Sleep(2000); SetColor(15, 0); } else v = false; } switch (var) { case 1: registry_user(); break; case 2: dell_user(); break; case 3: edit_user(); break; case 4: while (true) { system("cls"); shapka_start(); SetColor(12, 0); cout << "ПЕЧАТЬ ПОЛЬЗОВАТЕЛЕЙ:\n" << endl; SetColor(14, 0); cout << "1. Печать в файл ПОЛЬЗОВАТЕЛЕЙ\n" << "2. Печать на экран ПОЛЬЗОВАТЕЛЕЙ\n" << "3. Возврат в предыдущее меню\n" << endl; int var1; bool v = true; while (v) { SetColor(15, 0); cin >> var1; cin.ignore(); if (var1 < 1 || var1 > 3) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; Sleep(2000); SetColor(15, 0); } else v = false; } switch (var1) { case 1: tes.print_users_file(); break; case 2: tes.print_users(); system(("pause")); break; case 3: control_user(); break; default:; } } case 5: menu_admin(); break; default:; } } } //удаление пользователя void Admin::dell_user() { system("cls"); shapka_start(); SetColor(12, 0); cout << "УДАЛЕНИЕ ПОЛЬЗОВАТЕЛЯ:\n" << endl; Tested tes; tes.load_base(); SetColor(15, 0); tes.print_users(); cout << "\n"; string ld; SetColor(14, 0); cout << "Введите ЛОГИН ПОЛЬЗОВАТЕЛЯ для УДАЛЕНИЯ: "; SetColor(15, 0); cin >> ld; uppercase(ld); bool set = false; auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) { it = tes.base_tested_.erase(it); set = true; } } if (set) { system("cls"); SetColor(12, 0); gotoxy(10, 10); cout << "ПОЛЬЗОВАТЕЛЬ УДАЛЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); } else { system("cls"); SetColor(12, 0); gotoxy(10, 10); cout << "ТАКОГО ПОЛЬЗОВАТЕЛЯ НЕТ!!!" << endl; SetColor(15, 0); Sleep(2500); } } //редактирование пользователя void Admin::edit_user() { system("cls"); shapka_start(); SetColor(12, 0); cout << "РЕДАКТИРОВАННИЕ ДАННЫХ ПОЛЬЗОВАТЕЛЯ:\n" << endl; Tested tes; tes.load_base(); SetColor(15, 0); tes.print_users(); cout << "\n"; string ld; SetColor(14, 0); cout << "Введите ЛОГИН ПОЛЬЗОВАТЕЛЯ для РЕДАКТИРОВАНИЯ: "; SetColor(15, 0); cin >> ld; uppercase(ld); bool set = false; unsigned int pas_p = 0; auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) { set = true; pas_p = (*it)->get_pass(); } } if (set) { while (true) { //tes.load_base(); system("cls"); int var; shapka_start(); SetColor(12, 0); cout << "РЕДАКТИРОВАНИЕ ПРОФИЛЯ:\n" << endl; SetColor(14, 0); cout << "1. Редактировать ЛОГИН\n" << "2. Редактировать ПАРОЛЬ\n" << "3. Редактировать ФИО\n" << "4. Редактировать EMAIL\n" << "5. Редактировать номер ТЕЛЕФОНА\n" << "6. Возврат в предыдущее меню\n" << endl; bool v = true; while (v) { SetColor(15, 0); cin >> var; cin.ignore(); if (var < 1 || var > 6) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; Sleep(2000); SetColor(15, 0); } else v = false; } switch (var) { case 1: { system("cls"); string log; bool s = true; while (s) { system("cls"); shapka_start(); SetColor(12, 0); cout << "Редактирование ЛОГИНА:\n" << endl; SetColor(14, 0); cout << "Введите новый ЛОГИН:"; SetColor(15, 0); cin >> log; uppercase(log); int count = 0; //поиск одинаковых логинов со счетчиком auto iterator = tes.base_tested_.begin(); for (; iterator != tes.base_tested_.end(); ++iterator) { if ((*iterator)->get_login() == log) { count++; } } if (count != 0) { SetColor(12, 0); cout << "\nТакой ЛОГИН уже есть, введите другой ЛОГИН!!!" << endl; SetColor(15, 0); Sleep(2500); } else s = false; } auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) { (*it)->set_login(log); } } ld = log; SetColor(12, 0); cout << "\nЛОГИН ИЗМЕНЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); break; } case 2: { string pas; bool ad = true; while (ad) { system("cls"); shapka_start(); SetColor(12, 0); cout << "Редактирование ПАРОЛЯ:\n" << endl; SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; ad = check_size(pas); } auto pp = hashing(pas); bool ps = true; while (ps) { auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_pass() == pp) { SetColor(12, 0); cout << "\nТакой ПАРОЛЬ уже есть, введите другой ПАРОЛЬ!!!" << endl; SetColor(15, 0); Sleep(2500); bool d = true; while (d) { system("cls"); shapka_start(); SetColor(12, 0); cout << "Редактирование ПАРОЛЯ:\n" << endl; SetColor(14, 0); cout << "Введите ПАРОЛЬ (не менее 8-ми символов): "; SetColor(15, 0); cin >> pas; d = check_size(pas); } pp = hashing(pas); if ((*it)->get_pass() != pp) ps = false; } else ps = false; } } auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) (*it)->set_pass(pp); } SetColor(12, 0); cout << "\nПАРОЛЬ ИЗМЕНЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); break; } case 3: { system("cls"); shapka_start(); char* n = new char; SetColor(12, 0); cout << "Редактирование ФИО:\n" << endl; SetColor(14, 0); cout << "Введите новые ФИО: "; SetColor(15, 0); cin.getline(n, 100); string name = n; auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) (*it)->set_name(name); } SetColor(12, 0); cout << "\nФИО ИЗМЕНЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); break; } case 4: { system("cls"); shapka_start(); SetColor(12, 0); cout << "Редактирование EMAIL:\n" << endl; SetColor(14, 0); cout << "Введите новый EMAIL: "; SetColor(15, 0); string em; cin >> em; auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) (*it)->set_email(em); } SetColor(12, 0); cout << "\nEMAIL ИЗМЕНЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); break; } case 5: { system("cls"); shapka_start(); SetColor(12, 0); cout << "Редактирование номера ТЕЛЕФОНА:\n" << endl; SetColor(14, 0); cout << "Введите новый номер ТЕЛЕФОНА:"; SetColor(15, 0); string ph; cin >> ph; auto it = tes.base_tested_.begin(); for (; it != tes.base_tested_.end(); ++it) { if ((*it)->get_login() == ld) (*it)->set_phone(ph); } SetColor(12, 0); cout << "\nТЕЛЕФОН ИЗМЕНЕН!!!" << endl; SetColor(15, 0); tes.save_base(); Sleep(2500); break; } case 6: control_user(); break; default: break; } } } else { system("cls"); SetColor(12, 0); gotoxy(10, 10); cout << "ТАКОГО ПОЛЬЗОВАТЕЛЯ НЕТ!!!" << endl; SetColor(15, 0); Sleep(2500); } } //просмотр статистики void Admin::look_statics() { while (true) { Tested tes; tes.load_results(); tes.load_base(); system("cls"); shapka_start(); SetColor(12, 0); cout << "УПРАВЛЕНИЕ СТАТИСТИКОЙ:\n" << endl; SetColor(14, 0); cout << "1. Результаты в ОБЩЕМ\n" << "2. Результаты по конкретным ТЕСТАМ\n" << "3. Результаты по конкретным ПОЛЬЗОВАТЕЛЯМ\n" << "4. Печать результатов в ФАЙЛ\n" << "5. Возврат в предыдущее меню\n" << endl; int var; bool v = true; while (v) { SetColor(15, 0); cin >> var; cin.ignore(); if (var < 1 || var > 5) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; Sleep(2000); SetColor(15, 0); } else v = false; } switch (var) { case 1: tes.print_all_results(); system("pause"); break; case 2: { system("cls"); string cat; shapka_start(); SetColor(12, 0); cout << "РЕЗУЛЬТАТЫ ПО КОНКРЕТНЫМ ТЕСТАМ:\n" << endl; SetColor(14, 0); cout << "1. АЛГЕБРА\n" << "2. ГЕОМЕТРИЯ\n" << "3. КВАНТОВАЯ ФИЗИКА\n" << "4. МЕХАНИКА\n" << "5. ОРГАНИЧЕСКАЯ ХИМИЯ\n" << "6. НЕОРГАНИЧЕСКАЯ ХИМИЯ\n" << "7. Возврат в предыдущее меню\n" << endl; int var; bool v = true; while (v) { SetColor(15, 0); cin >> var; cin.ignore(); if (var < 1 || var > 7) // проверка ввода { SetColor(12, 0); cout << "НЕВЕРНО!!! ПОПРОБУЙТЕ ЕЩЕ РАЗ!!!" << endl; Sleep(2000); SetColor(15, 0); } else v = false; } switch (var) { case 1: cat = "АЛГЕБРА"; tes.print_result_tests(cat); system("pause"); break; case 2: cat = "ГЕОМЕТРИЯ"; tes.print_result_tests(cat); system("pause"); break; case 3: cat = "КВАНТОВАЯ"; tes.print_result_tests(cat); system("pause"); break; case 4: cat = "МЕХАНИКА"; tes.print_result_tests(cat); system("pause"); break; case 5: cat = "ОРГАНИЧЕСКАЯ"; tes.print_result_tests(cat); system("pause"); break; case 6: cat = "НЕОРГАНИЧЕСКАЯ"; tes.print_result_tests(cat); system("pause"); break; default:; } break; } case 3: tes.print_result_user(); system("pause"); break; case 4: tes.print_all_result_file(); break; case 5: menu_admin(); break; default:; } } } //сохранение статистики в файл void Admin::save_statics() { } void Admin::save_login_pass() { ofstream out("PassAdmin.bin", ios::binary | ios::out); int len_log = get_log_admin().size() + 1; out.write(reinterpret_cast<char*>(&len_log), sizeof(int)); out.write(const_cast<char*>(get_log_admin().c_str()), len_log); unsigned int pass = get_pass_admin(); out.write(reinterpret_cast<char*>(&pass), sizeof(unsigned int)); out.close(); } void Admin::load_login_pass() { ifstream fin("PassAdmin.bin", ios::binary | ios::in); if (fin.is_open()) { int len_log = 0; unsigned int pass = 0; fin.read(reinterpret_cast<char*>(&len_log), sizeof(int)); char* buff = new char(len_log + 1); fin.read(buff, len_log); set_log_admin(buff); fin.read(reinterpret_cast<char*>(&pass), sizeof(unsigned int)); set_pass_admin(pass); } fin.close(); }
true
977216aab4bb97e04134c3ab102f5825591df8c3
C++
liupucn/Radiosity
/辐射度算法渲染双球场景(改进版)/P3.cpp
GB18030
1,788
3.234375
3
[]
no_license
#include "stdafx.h" #include "Test.h" #include "P3.h" #include <math.h> #define ROUND(d) int(d + 0.5) CP3::CP3(void) { z = 0.0; num = 0; } CP3::~CP3(void) { } CP3::CP3(double x, double y, double z):CP2(x, y) { this->z = z; num = 0; } CP3 operator + (const CP3& p0, const CP3& p1)// { CP3 p; p.x = p0.x + p1.x; p.y = p0.y + p1.y; p.z = p0.z + p1.z; return p; } CP3 operator - (const CP3& p0, const CP3& p1)// { CP3 p; p.x = p0.x - p1.x; p.y = p0.y - p1.y; p.z = p0.z - p1.z; return p; } CP3 operator * (const CP3& p, double scalar)//ͳĻ { return CP3(p.x * scalar, p.y * scalar, p.z * scalar); } CP3 operator * (double scalar, const CP3& p)//ͳĻ { return CP3(p.x * scalar, p.y * scalar, p.z * scalar); } CP3 operator / (const CP3& p0, double scalar)// { if (fabs(scalar) < 1e-4) scalar = 1.0; CP3 p; p.x = p0.x / scalar; p.y = p0.y / scalar; p.z = p0.z / scalar; return p; } CP3 operator += (CP3& p0, CP3& p1) { p0.x = p0.x + p1.x; p0.y = p0.y + p1.y; p0.z = p0.z + p1.z; return p0; } CP3 operator -= (CP3& p0, CP3& p1) { p0.x = p0.x - p1.x; p0.y = p0.y - p1.y; p0.z = p0.z - p1.z; return p0; } double dot(CP3& p0, CP3& p1) { return p0.x* p1.x + p0.y * p1.y + p0.z * p1.z; } CP3 operator *= (CP3& p, double scalar) { p.x = p.x * scalar; p.y = p.y * scalar; p.z = p.z * scalar; return p; } CP3 operator /= (CP3& p, double scalar) { if (fabs(scalar) < 1e-4) scalar = 1.0; p.x = p.x / scalar; p.y = p.y / scalar; p.z = p.z / scalar; return p; } BOOL operator == (CP3& p0, CP3& p1) { if (ROUND(p0.x) == ROUND(p1.x) && ROUND(p0.y) == ROUND(p1.y) && ROUND(p0.z) == ROUND(p1.z)) return TRUE; else return FALSE; } double CP3::Magnitude(void)// { return sqrt(x * x + y * y + z * z); }
true
385bca1225286d324abdb14b20c665466aa57d5c
C++
Variapolis/OpenGL-CW1-CarGame
/3DExample1/src/PlayerCar.h
UTF-8
614
2.765625
3
[]
no_license
#pragma once #include "Rect.h" //Player car used to represent the player, check collisions with the border and obstacles and contain score. class PlayerCar : public Rect { int _score; bool _hasWon; public: GLfloat _speed; PlayerCar(GLfloat speed, int startScore, GLfloat x, GLfloat y, GLfloat width, GLfloat height); PlayerCar(GLfloat speed, int startScore); void CheckCollision(GameObject* obstacle, int score); void CheckBoundsCollision(GameObject* obstacle, GLfloat startX, GLfloat startY); void HandleCollision(GameObject* obstacle); void Rotate(); void AddScore(int score); int GetScore(); };
true
5e71cfebaac18ff4c719019222e3ac11834c574f
C++
thexujie/xui
/x/core/color.h
GB18030
17,651
2.953125
3
[]
no_license
#pragma once namespace core { struct colorf { union { struct { float32_t a; float32_t r; float32_t g; float32_t b; }; float32_t arr[4]; }; }; // ʽARGBɫ class color { public: color() = default; constexpr color(uint32_t _argb) : argb(_argb) {} constexpr color(uint8_t a, uint8_t r, uint8_t g, uint8_t b) : a(a), r(r), g(g), b(b) { } color operator * (float32_t rate) const { if (a == 0) return color(0, static_cast<uint8_t>(r * rate), static_cast<uint8_t>(g * rate), static_cast<uint8_t>(b * rate)); if (a == 0xff) return color(0xff, static_cast<uint8_t>(r * rate), static_cast<uint8_t>(g * rate), static_cast<uint8_t>(b * rate)); return color(static_cast<uint8_t>(a * rate), r, g, b); } operator colorf() const { colorf colorf = { (float32_t)a / 0xFF, (float32_t)r / 0xFF, (float32_t)g / 0xFF, (float32_t)b / 0xFF }; return colorf; } operator uint32_t() const { return argb; } bool visible() const { return a > 0; } union { uint32_t argb; struct { uint8_t b; uint8_t g; uint8_t r; uint8_t a; }; }; }; class colors { public: inline static constexpr color Auto = 0x00000000; //! Զɫ //! ͸ inline static constexpr color Transparent = 0x00FFFFFF; //! ɫ inline static constexpr color Red = 0xFFFF0000; //! 졢ɺ inline static constexpr color DarkRed = 0xFFDC143C; //! ˿ inline static constexpr color AliceBlue = 0xFFF0F8FF; //! Ŷ inline static constexpr color AntiqueWhite = 0xFFFAEBD7; //! ˮ inline static constexpr color Aqua = 0xFF00FFFF; //! inline static constexpr color Aquamarine = 0xFF7FFFD4; //! inline static constexpr color Azure = 0xFFF0FFFF; //! ׻ inline static constexpr color Beige = 0xFFF5F5DC; //! ٻ inline static constexpr color Bisque = 0xFFFFE4C4; //! inline static constexpr color Black = 0xFF000000; //! ʰ inline static constexpr color BlanchedAlmond = 0xFFFFEBCD; //! inline static constexpr color Blue = 0xFF0000FF; //! inline static constexpr color BlueViolet = 0xFF8A2BE2; //! ɫ inline static constexpr color Brown = 0xFFA52A2A; //! ʵľԭľӲľ inline static constexpr color BurlyWood = 0xFFDEB887; //! ɫ inline static constexpr color CadetBlue = 0xFF5F9EA0; //! inline static constexpr color Chartreuse = 0xFF7FFF00; //! ɿ inline static constexpr color Chocolate = 0xFFD2691E; //! ɺ inline static constexpr color Coral = 0xFFFF7F50; //! dzʸ inline static constexpr color CornflowerBlue = 0xFF6495ED; //! ׳ɫ inline static constexpr color Cornsilk = 0xFFFFF8DC; //! ɺɫ inline static constexpr color Crimson = 0xFFDC143C; //! ɫ inline static constexpr color Cyan = 0xFF00FFFF; //! ɫ inline static constexpr color DarkBlue = 0xFF00008B; //! ɫɫ inline static constexpr color DarkCyan = 0xFF008B8B; inline static constexpr color DarkGoldenrod = 0xFFB8860B; //! ɫջ inline static constexpr color DarkGray = 0xFFA9A9A9; //! ɫ inline static constexpr color DarkGreen = 0xFF006400; //! 䲼ɫƺɫ inline static constexpr color DarkKhaki = 0xFFBDB76B; //! inline static constexpr color DarkMagenta = 0xFF8B008B; inline static constexpr color DarkOliveGreen = 0xFF556B2F; inline static constexpr color DarkOrange = 0xFFFF8C00; inline static constexpr color DarkOrchid = 0xFF9932CC; inline static constexpr color DarkSalmon = 0xFFE9967A; inline static constexpr color DarkSeaGreen = 0xFF8FBC8B; inline static constexpr color DarkSlateBlue = 0xFF483D8B; inline static constexpr color DarkSlateGray = 0xFF2F4F4F; inline static constexpr color DarkTurquoise = 0xFF00CED1; inline static constexpr color DarkViolet = 0xFF9400D3; inline static constexpr color DeepPink = 0xFFFF1493; inline static constexpr color DeepSkyBlue = 0xFF00BFFF; inline static constexpr color DimGray = 0xFF696969; inline static constexpr color DodgerBlue = 0xFF1E90FF; inline static constexpr color Firebrick = 0xFFB22222; inline static constexpr color FloralWhite = 0xFFFFFAF0; inline static constexpr color ForestGreen = 0xFF228B22; inline static constexpr color Fuchsia = 0xFFFF00FF; inline static constexpr color Gainsboro = 0xFFDCDCDC; inline static constexpr color GhostWhite = 0xFFF8F8FF; inline static constexpr color Gold = 0xFFFFD700; inline static constexpr color Goldenrod = 0xFFDAA520; inline static constexpr color Gray = 0xFF808080; inline static constexpr color Green = 0xFF008000; inline static constexpr color GreenYellow = 0xFFADFF2F; inline static constexpr color Honeydew = 0xFFF0FFF0; inline static constexpr color HotPink = 0xFFFF69B4; inline static constexpr color IndianRed = 0xFFCD5C5C; inline static constexpr color Indigo = 0xFF4B0082; inline static constexpr color Ivory = 0xFFFFFFF0; inline static constexpr color Khaki = 0xFFF0E68C; inline static constexpr color Lavender = 0xFFE6E6FA; inline static constexpr color LavenderBlush = 0xFFFFF0F5; inline static constexpr color LawnGreen = 0xFF7CFC00; inline static constexpr color LemonChiffon = 0xFFFFFACD; inline static constexpr color LightBlue = 0xFFADD8E6; inline static constexpr color LightCoral = 0xFFF08080; inline static constexpr color LightCyan = 0xFFE0FFFF; inline static constexpr color LightGoldenrodYellow = 0xFFFAFAD2; inline static constexpr color LightGray = 0xFFD3D3D3; inline static constexpr color LightGreen = 0xFF90EE90; inline static constexpr color LightPink = 0xFFFFB6C1; inline static constexpr color LightSalmon = 0xFFFFA07A; inline static constexpr color LightSeaGreen = 0xFF20B2AA; inline static constexpr color LightSkyBlue = 0xFF87CEFA; inline static constexpr color LightSlateGray = 0xFF778899; inline static constexpr color LightSteelBlue = 0xFFB0C4DE; inline static constexpr color LightYellow = 0xFFFFFFE0; inline static constexpr color Lime = 0xFF00FF00; inline static constexpr color LimeGreen = 0xFF32CD32; inline static constexpr color Linen = 0xFFFAF0E6; //! 졢Ϻ졢Ʒ inline static constexpr color Magenta = 0xFFFF00FF; inline static constexpr color Maroon = 0xFF800000; inline static constexpr color MediumAquamarine = 0xFF66CDAA; inline static constexpr color MediumBlue = 0xFF0000CD; inline static constexpr color MediumOrchid = 0xFFBA55D3; inline static constexpr color MediumPurple = 0xFF9370DB; inline static constexpr color MediumSeaGreen = 0xFF3CB371; inline static constexpr color MediumSlateBlue = 0xFF7B68EE; inline static constexpr color MediumSpringGreen = 0xFF00FA9A; inline static constexpr color MediumTurquoise = 0xFF48D1CC; inline static constexpr color MediumVioletRed = 0xFFC71585; inline static constexpr color MidnightBlue = 0xFF191970; inline static constexpr color MintCream = 0xFFF5FFFA; inline static constexpr color MistyRose = 0xFFFFE4E1; inline static constexpr color Moccasin = 0xFFFFE4B5; inline static constexpr color NavajoWhite = 0xFFFFDEAD; inline static constexpr color Navy = 0xFF000080; inline static constexpr color OldLace = 0xFFFDF5E6; inline static constexpr color Olive = 0xFF808000; inline static constexpr color OliveDrab = 0xFF6B8E23; inline static constexpr color Orange = 0xFFFFA500; inline static constexpr color OrangeRed = 0xFFFF4500; inline static constexpr color Orchid = 0xFFDA70D6; inline static constexpr color PaleGoldenrod = 0xFFEEE8AA; inline static constexpr color PaleGreen = 0xFF98FB98; inline static constexpr color PaleTurquoise = 0xFFAFEEEE; inline static constexpr color PaleVioletRed = 0xFFDB7093; inline static constexpr color PapayaWhip = 0xFFFFEFD5; inline static constexpr color PeachPuff = 0xFFFFDAB9; inline static constexpr color Peru = 0xFFCD853F; inline static constexpr color Pink = 0xFFFFC0CB; inline static constexpr color Plum = 0xFFDDA0DD; inline static constexpr color PowderBlue = 0xFFB0E0E6; inline static constexpr color Purple = 0xFF800080; inline static constexpr color RosyBrown = 0xFFBC8F8F; inline static constexpr color RoyalBlue = 0xFF4169E1; inline static constexpr color SaddleBrown = 0xFF8B4513; inline static constexpr color Salmon = 0xFFFA8072; inline static constexpr color SandyBrown = 0xFFF4A460; inline static constexpr color SeaGreen = 0xFF2E8B57; inline static constexpr color SeaShell = 0xFFFFF5EE; inline static constexpr color Sienna = 0xFFA0522D; inline static constexpr color Silver = 0xFFC0C0C0; inline static constexpr color SkyBlue = 0xFF87CEEB; inline static constexpr color SlateBlue = 0xFF6A5ACD; inline static constexpr color SlateGray = 0xFF708090; //! ѩ inline static constexpr color Snow = 0xFFFFFAFA; //! ɫ inline static constexpr color SpringGreen = 0xFF00FF7F; inline static constexpr color SteelBlue = 0xFF4682B4; inline static constexpr color Tan = 0xFFD2B48C; inline static constexpr color Teal = 0xFF008080; //! ɫ inline static constexpr color Thistle = 0xFFD8BFD8; inline static constexpr color Tomato = 0xFFFF6347; inline static constexpr color Turquoise = 0xFF40E0D0; inline static constexpr color Violet = 0xFFEE82EE; inline static constexpr color Wheat = 0xFFF5DEB3; inline static constexpr color White = 0xFFFFFFFF; inline static constexpr color WhiteSmoke = 0xFFF5F5F5; inline static constexpr color Yellow = 0xFFFFFF00; inline static constexpr color YellowGreen = 0xFF9ACD32; }; struct color_name { color color; const char8_t * name = nullptr; }; const color_name color_names[] = { { colors::Auto, u8"Auto" }, { colors::Transparent, u8"Transparent" }, { colors::Red, u8"Red" }, { colors::DarkRed, u8"DarkRed" }, { colors::Aqua, u8"Aqua" }, { colors::Bisque, u8"Bisque" }, { colors::Black, u8"Black" }, { colors::BlanchedAlmond, u8"BlanchedAlmond" }, { colors::Blue, u8"Blue" }, { colors::BlueViolet, u8"BlueViolet" }, { colors::Brown, u8"Brown" }, { colors::BurlyWood, u8"BurlyWood" }, { colors::CadetBlue, u8"CadetBlue" }, { colors::Chartreuse, u8"Chartreuse" }, { colors::Chocolate, u8"Chocolate" }, { colors::Coral, u8"Coral" }, { colors::CornflowerBlue, u8"CornflowerBlue" }, { colors::Cornsilk, u8"Cornsilk" }, { colors::Crimson, u8"Crimson" }, { colors::Cyan, u8"Cyan" }, { colors::DarkBlue, u8"DarkBlue" }, { colors::DarkCyan, u8"DarkCyan" }, { colors::DarkGoldenrod, u8"DarkGoldenrod" }, { colors::DarkGray, u8"DarkGray" }, { colors::DarkGreen, u8"DarkGreen" }, { colors::DarkKhaki, u8"DarkKhaki" }, { colors::DarkMagenta, u8"DarkMagenta" }, { colors::DarkOliveGreen, u8"DarkOliveGreen" }, { colors::DarkOrange, u8"DarkOrange" }, { colors::DarkOrchid, u8"DarkOrchid" }, { colors::DarkSalmon, u8"DarkSalmon" }, { colors::DarkSeaGreen, u8"DarkSeaGreen" }, { colors::DarkSlateBlue, u8"DarkSlateBlue" }, { colors::DarkSlateGray, u8"DarkSlateGray" }, { colors::DarkTurquoise, u8"DarkTurquoise" }, { colors::DarkViolet, u8"DarkViolet" }, { colors::DeepPink, u8"DeepPink" }, { colors::DeepSkyBlue, u8"DeepSkyBlue" }, { colors::DimGray, u8"DimGray" }, { colors::DodgerBlue, u8"DodgerBlue" }, { colors::Firebrick, u8"Firebrick" }, { colors::FloralWhite, u8"FloralWhite" }, { colors::ForestGreen, u8"ForestGreen" }, { colors::Fuchsia, u8"Fuchsia" }, { colors::Gainsboro, u8"Gainsboro" }, { colors::GhostWhite, u8"GhostWhite" }, { colors::Gold, u8"Gold" }, { colors::Goldenrod, u8"Goldenrod" }, { colors::Gray, u8"Gray" }, { colors::Green, u8"Green" }, { colors::GreenYellow, u8"GreenYellow" }, { colors::Honeydew, u8"Honeydew" }, { colors::HotPink, u8"HotPink" }, { colors::IndianRed, u8"IndianRed" }, { colors::Indigo, u8"Indigo" }, { colors::Ivory, u8"Ivory" }, { colors::Khaki, u8"Khaki" }, { colors::Lavender, u8"Lavender" }, { colors::LavenderBlush, u8"LavenderBlush" }, { colors::LawnGreen, u8"LawnGreen" }, { colors::LemonChiffon, u8"LemonChiffon" }, { colors::LightBlue, u8"LightBlue" }, { colors::LightCoral, u8"LightCoral" }, { colors::LightCyan, u8"LightCyan" }, { colors::LightGoldenrodYellow, u8"LightGoldenrodYell" }, { colors::LightGray, u8"LightGray" }, { colors::LightGreen, u8"LightGreen" }, { colors::LightPink, u8"LightPink" }, { colors::LightSalmon, u8"LightSalmon" }, { colors::LightSeaGreen, u8"LightSeaGreen" }, { colors::LightSkyBlue, u8"LightSkyBlue" }, { colors::LightSlateGray, u8"LightSlateGray" }, { colors::LightSteelBlue, u8"LightSteelBlue" }, { colors::LightYellow, u8"LightYellow" }, { colors::Lime, u8"Lime" }, { colors::LimeGreen, u8"LimeGreen" }, { colors::Linen, u8"Linen" }, { colors::Magenta, u8"Magenta" }, { colors::Maroon, u8"Maroon" }, { colors::MediumAquamarine, u8"MediumAquamarine" }, { colors::MediumBlue, u8"MediumBlue" }, { colors::MediumOrchid, u8"MediumOrchid" }, { colors::MediumPurple, u8"MediumPurple" }, { colors::MediumSeaGreen, u8"MediumSeaGreen" }, { colors::MediumSlateBlue, u8"MediumSlateBlue" }, { colors::MediumSpringGreen, u8"MediumSpringGreen" }, { colors::MediumTurquoise, u8"MediumTurquoise" }, { colors::MediumVioletRed, u8"MediumVioletRed" }, { colors::MidnightBlue, u8"MidnightBlue" }, { colors::MintCream, u8"MintCream" }, { colors::MistyRose, u8"MistyRose" }, { colors::Moccasin, u8"Moccasin" }, { colors::NavajoWhite, u8"NavajoWhite" }, { colors::Navy, u8"Navy" }, { colors::OldLace, u8"OldLace" }, { colors::Olive, u8"Olive" }, { colors::OliveDrab, u8"OliveDrab" }, { colors::Orange, u8"Orange" }, { colors::OrangeRed, u8"OrangeRed" }, { colors::Orchid, u8"Orchid" }, { colors::PaleGoldenrod, u8"PaleGoldenrod" }, { colors::PaleGreen, u8"PaleGreen" }, { colors::PaleTurquoise, u8"PaleTurquoise" }, { colors::PaleVioletRed, u8"PaleVioletRed" }, { colors::PapayaWhip, u8"PapayaWhip" }, { colors::PeachPuff, u8"PeachPuff" }, { colors::Peru, u8"Peru" }, { colors::Pink, u8"Pink" }, { colors::Plum, u8"Plum" }, { colors::PowderBlue, u8"PowderBlue" }, { colors::Purple, u8"Purple" }, { colors::RosyBrown, u8"RosyBrown" }, { colors::RoyalBlue, u8"RoyalBlue" }, { colors::SaddleBrown, u8"SaddleBrown" }, { colors::Salmon, u8"Salmon" }, { colors::SandyBrown, u8"SandyBrown" }, { colors::SeaGreen, u8"SeaGreen" }, { colors::SeaShell, u8"SeaShell" }, { colors::Sienna, u8"Sienna" }, { colors::Silver, u8"Silver" }, { colors::SkyBlue, u8"SkyBlue" }, { colors::SlateBlue, u8"SlateBlue" }, { colors::SlateGray, u8"SlateGray" }, { colors::Snow, u8"Snow" }, { colors::SpringGreen, u8"SpringGreen" }, { colors::SteelBlue, u8"SteelBlue" }, { colors::Tan, u8"Tan" }, { colors::Teal, u8"Teal" }, { colors::Thistle, u8"Thistle" }, { colors::Tomato, u8"Tomato" }, { colors::Turquoise, u8"Turquoise" }, { colors::Violet, u8"Violet" }, { colors::Wheat, u8"Wheat" }, { colors::White, u8"White" }, { colors::WhiteSmoke, u8"WhiteSmoke" }, { colors::Yellow, u8"Yellow" }, { colors::YellowGreen, u8"YellowGreen" }, }; }
true
5beb1b7ab5599ff149cbce54130fef737294bcbe
C++
GuilhermeMatheus/AcessoUFABC
/src/KeyPadListener.h
ISO-8859-1
2,187
3.09375
3
[]
no_license
#ifndef KEYPADLISTENER_H #define KEYPADLISTENER_H #define ROW_1 3 #define ROW_2 2 #define ROW_3 1 #define ROW_4 0 #define THRESHOLD_TOLERANCE 30 #define MIN_THRESHOLD_ROW_1 128 #define MAX_THRESHOLD_ROW_1 384 - THRESHOLD_TOLERANCE #define MIN_THRESHOLD_ROW_2 384 + THRESHOLD_TOLERANCE #define MAX_THRESHOLD_ROW_2 640 - THRESHOLD_TOLERANCE #define MIN_THRESHOLD_ROW_3 640 + THRESHOLD_TOLERANCE #define MAX_THRESHOLD_ROW_3 896 - THRESHOLD_TOLERANCE #define MIN_THRESHOLD_ROW_4 896 + THRESHOLD_TOLERANCE #include <Arduino.h> #include "System.h" /** * Classe responsvel por verificar o estado de um teclado matricial numrico. */ class KeyPadListener { private: int8_t pinColumnOne, pinColumnTwo, pinColumnThree, actualFunctionIndex; uint32_t cycle; protected: char keyTable[3][4]; int GetRowFromColumn(int8_t column); public: /** * Cria uma instncia de KeyPadListener. * * @param pinColumnOne Nmero do pino analgico responsvel pela primeira coluna da matriz, com os dgitos [1], [4], [7] e [*] * @param pinColumnTwo Nmero do pino analgico responsvel pela segunda coluna da matriz, com os dgitos [2], [5], [8] e [0] * @param pinColumnThree Nmero do pino analgico responsvel pela terceira coluna da matriz, com os dgitos [3], [6], [9] e [#] */ KeyPadListener(int8_t pinColumnOne, int8_t pinColumnTwo, int8_t pinColumnThree); ~KeyPadListener(); /** * Verifica o estado do teclado. * * @return Retorna o dgito pressionado ou -1, caso nenhuma tecla esteja acionada */ int16_t GetState(); /** * Para a aplicao at que uma tecla seja pressionada. * * @return Retorna o dgito pressionado */ char WaitForInput(); /** * Para a aplicao at que uma tecla de dgito seja pressionada. * * @return Retorna o nmero do dgito pressionado */ uint8_t WaitForDigitInput(); /** * Verifica por quanto tempo uma tecla pressionada * * @param max Tempo em millisegundos mximo a ser contado. * @param c Tecla a ser assistida. * @return Retorna o tempo em que a tecla foi pressionada ou {@code max} quando o tempo limite for excedido */ long GetPressTime(char c, long max); }; #endif /* KEYPADLISTENER_H */
true
33175afe072a5b0e71cfc6b16c217f0d74d508ba
C++
ssliuyi/ACMCode
/LeetCode/Triangle.cpp
UTF-8
990
2.859375
3
[]
no_license
class Solution { public: int minimumTotal(vector<vector<int> > &triangle) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<int> min; vector<vector<int>>::iterator i; vector<int>::iterator j; int k=0; for(i=triangle.begin();i!=triangle.end();i++) { vector<int> temp; for(j=i->begin(),k=0;j!=i->end();j++,k++) { if(min.empty()) { min.push_back(*j); } else { if(temp.empty()) { temp.push_back(*j+*min.begin()); } else if(temp.size()==i->size()-1) { temp.push_back(*j+*(--min.end())); } else { temp.push_back(*j+min.at(k)<*j+min.at(k-1)?*j+min.at(k):*j+min.at(k-1)); } } } if(!temp.empty()) min=temp; } int result=min.at(0); for(int s=0;s<min.size();s++) { if(result>min.at(s)) result=min.at(s); } return result; } };
true
c56af1a4c75ea6a324221838f6d48609f14ae1cd
C++
txaaron/Segs
/Projects/CoX/Common/GameData/serialization_common.h
UTF-8
5,094
2.578125
3
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * SEGS - Super Entity Game Server * http://www.segs.io/ * Copyright (c) 2006 - 2018 SEGS Team (see Authors.txt) * This software is licensed! (See License.txt for details) */ #pragma once #include "Colors.h" #include "Logging.h" #include <glm/vec3.hpp> #include <glm/vec2.hpp> #include <cereal/archives/json.hpp> #include <cereal/archives/binary.hpp> #include <cereal/types/vector.hpp> #include <cereal/types/array.hpp> #include <cereal/types/string.hpp> #include <cereal/cereal.hpp> #include <QtCore/QString> #include <QtCore/QFile> template<class T> void commonSaveTo(const T & target, const char *classname, const QString & baseName, bool text_format) { QString target_fname; if(text_format) target_fname = baseName + ".crl.json"; else target_fname = baseName + ".crl.bin"; std::ostringstream tgt; QFile tgt_fle(target_fname); try { if(text_format) { cereal::JSONOutputArchive ar( tgt ); ar(cereal::make_nvp(classname,target)); if(!tgt_fle.open(QFile::WriteOnly|QFile::Text)) { qCritical() << "Failed to open"<<target_fname<<"in write mode"; return; } } else { cereal::BinaryOutputArchive ar( tgt ); ar(cereal::make_nvp(classname,target)); if(!tgt_fle.open(QFile::WriteOnly)) { qCritical() << "Failed to open"<<target_fname<<"in write mode"; return; } } tgt_fle.write(tgt.str().c_str(),tgt.str().size()); } catch(cereal::RapidJSONException &e) { qWarning() << e.what(); } catch(std::exception &e) { qCritical() << e.what(); } } template<class T> bool commonReadFrom(const QString &crl_path,const char *classname, T &target) { QFile ifl(crl_path); if(crl_path.endsWith("json") || crl_path.endsWith("crl_json")) { if(!ifl.open(QFile::ReadOnly|QFile::Text)) { qWarning() << "Failed to open" << crl_path; return false; } std::istringstream istr(ifl.readAll().toStdString()); try { cereal::JSONInputArchive arc(istr); arc(cereal::make_nvp(classname,target)); } catch(cereal::RapidJSONException &e) { qWarning() << e.what(); } catch (std::exception &e) { qCritical() << e.what(); } } else if(crl_path.endsWith(".crl.bin")) { if(!ifl.open(QFile::ReadOnly)) { qWarning() << "Failed to open" << crl_path; return false; } std::istringstream istr(ifl.readAll().toStdString()); try { cereal::BinaryInputArchive arc(istr); arc(cereal::make_nvp(classname,target)); } catch(cereal::RapidJSONException &e) { qWarning() << e.what(); } catch (std::exception &e) { qCritical() << e.what(); } } else { qWarning() << "Invalid serialized data extension in" <<crl_path; } return true; } template<class T> void serializeToQString(const T &data, QString &tgt) { std::ostringstream ostr; { cereal::JSONOutputArchive ar(ostr); ar(data); } tgt = QString::fromStdString(ostr.str()); } template<class T> void serializeFromQString(T &data,const QString &src) { if(src.isEmpty()) return; std::istringstream istr; istr.str(src.toStdString()); { cereal::JSONInputArchive ar(istr); ar(data); } } namespace cereal { inline void epilogue(BinaryOutputArchive &, QString const &) { } inline void epilogue(BinaryInputArchive &, QString const &) { } inline void epilogue(JSONOutputArchive &, QString const &) { } inline void epilogue(JSONInputArchive &, QString const &) { } inline void prologue(JSONOutputArchive &, QString const &) { } inline void prologue(JSONInputArchive &, QString const &) { } inline void prologue(BinaryOutputArchive &, QString const &) { } inline void prologue(BinaryInputArchive &, QString const &) { } template<class Archive> inline void CEREAL_SAVE_FUNCTION_NAME(Archive & ar, ::QString const & str) { ar( str.toStdString() ); } //! Serialization for basic_string types, if binary data is supported template<class Archive> inline void CEREAL_LOAD_FUNCTION_NAME(Archive & ar, ::QString & str) { std::string rd; ar( rd ); str = QString::fromStdString(rd); } template<class Archive> void serialize(Archive & archive, glm::vec3 & m) { size_type size=3; archive( make_size_tag( size ) ); // this is new for( int i=0; i<3; ++i ) archive( m[i] ); } template<class Archive> void serialize(Archive & archive, glm::vec2 & m) { size_type size=2; archive( make_size_tag( size ) ); // this is new for( int i=0; i<2; ++i ) archive( m[i] ); } template<class Archive> void serialize(Archive & archive, RGBA & m) { archive(cereal::make_nvp("rgba",m.val)); } } // namespace cereal
true
e8df2a6fb0f7fb0e44822c5655d9a63bc9ce695b
C++
GabrielPlante/SaeGE2D
/SuperDUPER/Text.cpp
UTF-8
1,214
2.953125
3
[]
no_license
#include "Text.h" #include <iostream> Text::Text(const std::string& text, const Position<>& position, SDL_Renderer* renderer, const Font& font, const Color& color) :color{ color } { //To compensate for strange ttf behaviour const int positionY = position.y - font.getHeight() / 5; rect = Rectangle{ position.x, positionY, font.getWidth(text), font.getHeight() }; //Create the surface SDL_Surface* surfaceText{ TTF_RenderText_Solid(font.getFont(), text.c_str(), color.toSDLColor()) }; if (!surfaceText) { std::cout << SDL_GetError() << std::endl; throw std::runtime_error("Could not create SDL_Surface !"); } //Transform the surface into a texture texture = SDL_CreateTextureFromSurface(renderer, surfaceText); if (!texture) { std::cout << SDL_GetError() << std::endl; throw std::runtime_error("Could not create SDL_Texture !"); } //Release the surface SDL_FreeSurface(surfaceText); } void Text::render(SDL_Renderer* renderer, SDL_Rect* srcRect, SDL_Rect* dstRect) const { //Due to strange ttf behaviour if (srcRect) srcRect->h = srcRect->h * 6 / 5; SDL_RenderCopy(renderer, texture, srcRect, dstRect ? dstRect : &rect.toSDL_Rect()); } Text::~Text() { SDL_DestroyTexture(texture); }
true
74444162e501c4919f08a2f7151bfdbff2113760
C++
bharatkumarnitc/Compative-Programming
/Dynamic Programming 1/Q10.cpp
UTF-8
689
2.734375
3
[]
no_license
#include<bits/stdc++.h> #include<vector> using namespace std; int solve(int n,vector<int>A){ int arr[1000];//={0}; int dp[1000];//={0}; memset(arr,0,1000); memset(dp,0,1000); vector<int>::iterator it; dp[0]=0; dp[1]=A[0]; for(it=A.begin(); it!=A.end();it++) { arr[(*it)]++; } for(int i=2;i<=1000;i++) { dp[i]=max((dp[i-2]+(i*arr[i])),dp[i-1]); } for(int i=0;i<n;i++) cout<<dp[i]<<" "; cout<<endl; return dp[n]; } int main() { vector<int>A; int n; cin>>n; for(int i=0;i<n;i++) { int x; cin>>x; A.push_back(x); } cout<<solve(n,A)<<endl; }
true
662180829b0abc982ecbf4368d20d686e57d7c98
C++
ivanovdimitur00/programs
/Programs/domashno 2 (29.12)/gotovi/zadacha_2.cpp
UTF-8
2,223
3.265625
3
[]
no_license
#include <iostream> #include <cstring> void replace_exact (char* word, char* sent_word) { for (int i = 0; i < strlen(word); i++) { sent_word[i] = word[i]; } } void replace_with_shorter (char* word, char* sent_word) { for (int i = 0; i < strlen(word); i++) { sent_word[i] = word[i]; } sent_word[strlen(word)] = '\0'; } void replace_with_longer (char* word, char* sent_word) { for (int i = 0; i < strlen(word); i++) { sent_word[i] = word[i]; } sent_word[strlen(word)] = '\0'; } void find_replacement(char* sent_word, char word[][101],int n) { for (int i = 0 ; i < 2*n; i = i+2) { if (strcmp(sent_word,word[i]) == 0) { if (strcmp(word[i+1],sent_word) == 0) { replace_exact (word[i+1],sent_word); break; } else if (strcmp(word[i+1],sent_word) < 0) { replace_with_shorter (word[i+1],sent_word); break; } else { replace_with_longer (word[i+1],sent_word); break; } } } } int main() { int n; std::cin>>n; char words[200][101]; for (int i = 0; i < 2*n; i++) { std::cin>>words[i]; } char sentence[4097]; std::cin.getline(sentence,4097); char sentence_word[101]; int index = 0; char symbol = sentence[strlen(sentence) - 1]; for (int i = 0; i < strlen(sentence); i++) { if (sentence[i] != ' ' && sentence[i] != '.' && sentence[i] != '?' && sentence[i] != '!' ) { sentence_word[index] = sentence[i]; index++; } else { index++; sentence_word[index] = '\0'; find_replacement(sentence_word,words,n); if (strlen(sentence) - i != 1) { std::cout<<sentence_word<<" "; } else { std::cout<<sentence_word; } index = 0; } } std::cout<<symbol<<std::endl; return 0; }
true
7ee54e5a9b6061c319e0a6699ecbbf1f5dc8a8ed
C++
Lrs121/winds
/arm9/include/_gadget/gadget.fileview.h
UTF-8
3,422
2.734375
3
[ "MIT" ]
permissive
// Check if already included #ifndef _WIN_G_FILEVIEW_ #define _WIN_G_FILEVIEW_ #include <_type/type.gadget.h> #include <_type/type.uniqueptr.h> #include <_type/type.sound.static.h> #include <_gadget/gadget.scrollArea.h> #include <_gadget/gadget.fileobject.h> class _fileView : public _scrollArea { private: _direntry directory; _fileViewType viewType; _uniquePtr<_fileExtensionList> filemask; _uniquePtr<_callback<_eventHandler>> eventHandler; bool singleClickToExecute; // ContextMenu static _uniquePtr<_menu> defaultMenu; static void defaultMenuHandler( _u16 listIndex , _u16 entryIndex ); void initializeMenu(); // Member function to forward all events to the 'eventHandler' static _callbackReturn eventForwarder( _event ); // Generates all _fileObjects void generateChildren(); //! Full Ctor _fileView( _optValue<_coord> x , _optValue<_coord> y , _optValue<_length> width , _optValue<_length> height , string path , _fileViewType viewType , _fileExtensionList allowedExtensions , _callback<_eventHandler>* eventHandler , bool singleClickToExecute , _style&& style ); public: //! Method to set the Path void setPath( const string& path , bool preventClick = false ); //! Method to get the Path string getPath(){ return this->directory.getFileName(); } //! Tell the _fileview to reduce void setFileMask( _paramAlloc<_fileExtensionList> allowedExtensions ){ filemask = allowedExtensions.get(); this->generateChildren(); } //! Allow all extensions void removeFileMask(){ filemask = nullptr; this->generateChildren(); } //! Set eventHandler to handle onMouseClick, onMouseDblClick void setEventHandler( _paramAlloc<_callback<_eventHandler>> eventHandler ){ this->eventHandler = eventHandler.get(); } //! Remove the currently assigned eventHandler void removeEventHandler(){ this->eventHandler = nullptr; } //! Simple Ctor _fileView( _optValue<_coord> x , _optValue<_coord> y , _optValue<_length> width , _optValue<_length> height , string path , _fileViewType viewType , _fileExtensionList allowedExtensions = {} , _style&& style = _style() ) : _fileView( move(x) , move(y) , move(width) , move(height) , move(path) , viewType , move(allowedExtensions) , nullptr , false , (_style&&)style ) {} //! Ctor with eventHandler _fileView( _optValue<_coord> x , _optValue<_coord> y , _optValue<_length> width , _optValue<_length> height , string path , _fileViewType viewType , _paramAlloc<_callback<_eventHandler>> eventHandler , _fileExtensionList allowedExtensions = {} , _style&& style = _style() ) : _fileView( move(x) , move(y) , move(width) , move(height) , move(path) , viewType , move(allowedExtensions) , eventHandler.get() , false , (_style&&)style ) {} //! Ctor with singleClickToExecute flag _fileView( _optValue<_coord> x , _optValue<_coord> y , _optValue<_length> width , _optValue<_length> height , string path , _fileViewType viewType , bool singleClickToExecute , _fileExtensionList allowedExtensions = {} , _style&& style = _style() ) : _fileView( move(x) , move(y) , move(width) , move(height) , move(path) , viewType , move(allowedExtensions) , nullptr , singleClickToExecute , (_style&&)style ) {} //! Dtor ~_fileView(); }; #endif
true