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
41f40ac3afe13697be3c8ef15eab5cb7d0770f2a
C++
teru01/algorithms
/dp/lcs.cpp
UTF-8
1,027
2.6875
3
[]
no_license
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <iostream> #include <string> #include <vector> #include <map> #include <set> #include <stack> #include <list> #include <queue> #include <deque> #include <algorithm> #include <numeric> #include <utility> #include <complex> #include <functional> #include <climits> using namespace std; int lcs(string x, string y) { int c[1001][1001]; int n = x.length(); int m = y.length(); for(int i = 0; i < n; i++) { c[i][0] = 0; } for(int j = 0; j < m; j++) { c[0][j] = 0; } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(x[i-1] == y[j-1]) { c[i][j] = c[i-1][j-1] + 1; } else { c[i][j] = max(c[i][j-1], c[i-1][j]); } } } return c[n][m]; } int main() { int n; cin >> n; for(int i=0; i<n; i++) { string s1, s2; cin >> s1 >> s2; cout << lcs(s1, s2) << endl; } }
true
54538e8125ff4b8f08d09ea0574e9fce2c41af0e
C++
accepted2019/Accepted.no.1.c-.CN
/c++获取键盘事件.cpp
GB18030
418
2.546875
3
[]
no_license
#include <conio.h> #include<bits/stdc++.h> using namespace std; int main() { int ch; while (1){ if (_kbhit()){//а£_kbhit() ch=_getch();//ʹ_getch()ȡµļֵ cout<<ch; if (ch == 27){ break; }//ESCʱѭESCļֵʱ27. } } system("pause"); return 0; }
true
0959eacb671c21d6ba203dca98ed512198ac5f24
C++
pgngp/practice-code
/addBinary.cpp
UTF-8
1,619
3.859375
4
[]
no_license
/* Add binary (158): Given two binary strings, return their sum (also a binary string). For example, a = "11", b = "1", the return is "100". http://www.programcreek.com/2014/05/leetcode-add-binary-java/ */ #include <iostream> #include <string> using namespace std; string add(const string &s1, const string &s2) { int i = s1.length() - 1, j = s2.length() - 1, k, carry = 0, maxLen; maxLen = (s1.length() >= s2.length()) ? s1.length() : s2.length(); string s3(maxLen + 1, ' '); k = s3.length() - 1; while (i >= 0 && j >= 0) { if (s1[i] == '1' && s2[j] == '1') { if (carry) { s3[k] = '1'; } else { s3[k] = '0'; carry = 1; } } else if (s1[i] == '1' || s2[j] == '1') { if (carry) { s3[k] = '0'; } else { s3[k] = '1'; } } else { if (carry) { s3[k] = '1'; carry = 0; } else { s3[k] = '0'; } } --i; --j; --k; } while (i >= 0) { if (s1[i] == '1') { if (carry) { s3[k] = '0'; } else { s3[k] = '1'; } } else { if (carry) { s3[k] = '1'; carry = 0; } else { s3[k] = '0'; } } --i; --k; } while (j >= 0) { if (s2[j] == '1') { if (carry) { s3[k] = '0'; } else { s3[k] = '1'; } } else { if (carry) { s3[k] = '1'; carry = 0; } else { s3[k] = '0'; } } --j; --k; } if (carry) { s3[k] = '1'; } return s3; } int main(int argc, char **argv) { if (argc < 3) { cout << "Usage: a.out <num1> <num2>" << endl; return 1; } string s1(argv[1]); string s2(argv[2]); string s3 = add(s1, s2); cout << "s3: " << s3 << endl; return 0; }
true
682c35357e8839f2e564eba5e97fa05c9b7dcef5
C++
BazzalSeed/Programming-Systems-and-Languages
/labs/lab1_seeDISAWESOME/lab1_00v_1.1/lab1_00/TerminalsAST.h
UTF-8
403
2.640625
3
[]
no_license
/* This is the derived class of abstract ASTNode for terminal node(directly contains token) */ #pragma once #include "ASTnode.h" class Terminals : public ASTNode { public: Terminals(std::string s, shared_ptr<Token> & t, shared_ptr<ASTNode> & parent); ~Terminals(); void visit(set<string>& valid_label, set<unsigned int>& valid_number); private : shared_ptr<Token> token; };
true
02f4ae13afc5a2a422ad6b30934fc05ae813ce94
C++
Rafsan15048/Calender-Application-Digital-Clock
/Calender Application Project Final/Calender Project Main.cpp
UTF-8
21,469
2.875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> ///For music play #include<Windows.h> #include<MMSystem.h> ///For time and date #include <time.h> #define LEN 150 ///For Year Print #define TRUE 1 #define FALSE 0 int days_in_month[]= {0,31,28,31,30,31,30,31,31,30,31,30,31}; ///A #include <graphics.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <conio.h> #include<math.h> #include<dos.h> #include<string.h> #include<iostream> #include<ctime> #define M_PI acos(-1) #define S_N_L (radius-10) // Second Needle Length #define S_N_C RED // Second needle Color #define M_N_L (radius-20) // Minute Needle Length #define M_N_C LIGHTRED // Minute Needle Color #define H_N_L (radius-(radius/2)) // Hour Needle Length #define H_N_C CYAN // Hour Needle Color float cx,cy; float radius=100; void draw_face(float radius); void get_time(int &h,int &m,int &s); void second_needle(int s); void minute_needle(int m,int s); void hour_needle(int h,int m,int s); ///For Day Print And Month struct Date { int dd; int mm; int yy; }; struct Date date; void menu(); int check_leapYear(int year) { if(year % 400 == 0 || (year % 100!=0 && year % 4 ==0)) return 1; return 0; } int getNumberOfDays(int month,int year) { switch(month) { case 1 : return(31); case 2 : if(check_leapYear(year)==1) return(29); else return(28); case 3 : return(31); case 4 : return(30); case 5 : return(31); case 6 : return(30); case 7 : return(31); case 8 : return(31); case 9 : return(30); case 10: return(31); case 11: return(30); case 12: return(31); default: return(-1); } } char *getName(int day) { switch(day) { case 0 : return("Sunday"); case 1 : return("Monday"); case 2 : return("Tuesday"); case 3 : return("Wednesday"); case 4 : return("Thursday"); case 5 : return("Friday"); case 6 : return("Saturday"); default: return("Error in getName() module.Invalid argument passed"); } printf("press any key to get back to main menu..."); getchar(); menu(); } void print_date(int mm, int yy) { printf("\n****************************************************\n"); printf("******************"); switch(mm) { case 1: printf("January"); break; case 2: printf("February"); break; case 3: printf("March"); break; case 4: printf("April"); break; case 5: printf("May"); break; case 6: printf("June"); break; case 7: printf("July"); break; case 8: printf("August"); break; case 9: printf("September"); break; case 10: printf("October"); break; case 11: printf("November"); break; case 12: printf("December"); break; } printf(" , %d*******************", yy); printf("\n****************************************************\n"); } int getDayNumber(int day,int mon,int year) { int res = 0, t1, t2, y = year; year = year - 1600; while(year >= 100) { res = res + 5; year = year - 100; } res = (res % 7); t1 = ((year - 1) / 4); t2 = (year-1)-t1; t1 = (t1*2)+t2; t1 = (t1%7); res = res + t1; res = res%7; t2 = 0; for(t1 = 1; t1 < mon; t1++) { t2 += getNumberOfDays(t1,y); } t2 = t2 + day; t2 = t2 % 7; res = res + t2; res = res % 7; if(y > 2000) res = res + 1; res = res % 7; return res; } char *getDay(int dd,int mm,int yy) { int day; if(!(mm>=1 && mm<=12)) { return("Invalid month value"); printf("press any key to get back to main menu..."); getchar(); menu(); } if(!(dd>=1 && dd<=getNumberOfDays(mm,yy))) { return("Invalid date"); printf("press any key to get back to main menu..."); getchar(); menu(); } if(yy>=1600) { day = getDayNumber(dd,mm,yy); day = day%7; return(getName(day)); } else { return("Please give year more than 1600"); printf("press any key to get back to main menu..."); getchar(); menu(); } } ///print all day of the month void printMonth(int mon,int year,int x,int y) { char Var; if(mon >12) { mon = 1; year = year+1; } else if(mon<1) { mon = 12; year-=1; } int nod, day, cnt, d = 1, x1 = x, y1 = y; int z; if(!(mon>=1 && mon<=12)) { printf("INVALID MONTH"); getchar(); return; } if(!(year>=1600)) { printf("INVALID YEAR"); getchar(); return; } print_date(mon,year); printf("*Sun\tMon\tTue\tWed\tThu\tFri\tSat*\n"); printf("****************************************************\n\n"); nod = getNumberOfDays(mon,year); day = getDayNumber(d,mon,year); z = day; while(z) { printf("\t"); z--; } cnt = day; for(z=1; z<=nod; z++) { cnt++; printf("%02d\t",z); if(cnt%7==0) { printf("\n"); } } printf("\n\n\nPress Enter to continue...... :"); printf("\n\n\nPress N or P to Next or Prev...... :"); getchar(); scanf("%c",&Var); if( Var == 'N' || Var == 'n') printMonth(mon+1,date.yy,20,5); else if(Var == 'P' || Var == 'p') printMonth(mon-1,date.yy,20,5); } ///All Month of the year char *months[]= { " ", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int determinedaycode(int year) { int daycode; int d1, d2, d3; d1 = (year - 1.0)/ 4.0; d2 = (year - 1.0)/ 100.0; d3 = (year - 1.0)/ 400.0; daycode = (year + d1 - d2 + d3) %7; return daycode; } int determineleapyear(int year) { if(year% 4 == FALSE && year%100 != FALSE || year%400 == FALSE) { days_in_month[2] = 29; return TRUE; } else { days_in_month[2] = 28; return FALSE; } } void calendar(int year, int daycode) { int month, day; char Var; for ( month = 1; month <= 12; month++ ) { printf("\n______________________________________________________________________________________________\n\n"); printf("******** %s *********", months[month]); printf("\n\n***********************************"); printf("\n*Sun Mon Tue Wed Thu Fri Sat*" ); printf("\n***********************************\n"); for ( day = 1; day <= 1 + daycode * 5; day++ ) { printf(" "); } for ( day = 1; day <= days_in_month[month]; day++ ) { printf("%2d", day ); if ( ( day + daycode ) % 7 > 0 ) printf(" " ); else printf("\n " ); } daycode = ( daycode + days_in_month[month] ) % 7; } printf("\n\nEnter N for Next ans P for Prev ...................."); printf("\nPress enter for main Menu ............................\n\n\n\n"); getchar(); scanf("%c",&Var); if(Var == 'P' || Var == 'p') { printf("\t\t\t\tYEAR %d\n\n",year-1); daycode = determinedaycode(year-1); determineleapyear(year-1); calendar(year-1, daycode); } else if(Var == 'n' || Var == 'N') { printf("\t\t\t\tYEAR %d\n\n",year+1); daycode = determinedaycode(year+1); determineleapyear(year+1); calendar(year+1, daycode); } } ///See time void see_time() { ///Current time char buf[LEN]; time_t curtime; struct tm *loc_time; ///Getting current time of system curtime = time (NULL); /// Converting current time to local time loc_time = localtime (&curtime); ///Displaying date and time in standard format printf(" %s", asctime (loc_time)); strftime (buf, LEN, "\n Date: %A, %b %d.\n\n", loc_time); printf("************************************************************************************************************************"); fputs (buf, stdout); strftime (buf, LEN, "\n Time : %I:%M %p.\n\n", loc_time); ///strftime(),returns the time into string printf("************************************************************************************************************************"); fputs (buf, stdout); ///Universal time time_t orig_format; time(&orig_format); printf("************************************************************************************************************************"); printf ("\n Universal Time or Greenwich Mean Time (GMT) : %s\n",asctime(gmtime(&orig_format))); printf("************************************************************************************************************************"); printf("\nPress any key to continue : "); getchar(); } ///set time void set_time() { system("start set_time.exe"); } ///Alarm //time_t now; //struct tm *right_now; ///Set alarm /*int alarm() { int hour , minutes; system("color AC"); printf("Enter Hour : "); scanf("%d",&hour); printf("\nEnter Minutes : "); scanf("%d",&minutes); system("cls"); printf("\n\n\n\nAlarm Time Is %d:%d",hour,minutes); //system("color 3F"); while(1) { time(&now); right_now=localtime(&now); if(hour == right_now->tm_hour & minutes == right_now->tm_min) { //system("color D0"); printf("\n\n\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); printf("\n\n*******************************************************Wake Up********************************************************"); //printf("\nWake Up"); PlaySound(TEXT("Linkin Park - Final Masquerade1.wav"),NULL,SND_SYNC); break; } else { free(right_now); } } } */ ///For Analog Clock int analog(void) { /* request auto detection */ int gdriver = DETECT, gmode, errorcode; initgraph(&gdriver,&gmode,"d:\\tc\\bgi"); /***********************************/ cx=getmaxx()/2.0; // cx is center x value. cy=getmaxy()/2.0; // cy is center y value. /** Now the point (cx,cy) is the center of your screen. **/ float x,y; int hour,minute,second; draw_face(radius); while(!kbhit()) { get_time(hour,minute,second); second_needle(second); minute_needle(minute,second); hour_needle(hour,minute,second); circle(cx,cy,2); delay(100); } getch(); closegraph(); menu(); getchar(); //return 0; } //*************** FUNCTIONS DEFINITIONS *****************// void draw_face(float radius) { int theta=0; // theta is the angle variable. float x,y; /** Draw Clock Border. **/ circle(cx,cy,radius+24); circle(cx,cy,radius+23); /** Draw GREEN material border. **/ setcolor(BLUE); // I like a wooden frame! /** Paint the border. **/ for(int i=0; i<9; i++) circle(cx,cy,radius+13+i); /** Set the color white. **/ setcolor(RED); /** Draw outer-inner border. **/ circle(cx,cy,radius+12); circle(cx,cy,radius+10); /** Draw center dot. **/ circle(cx,cy,2); int i=0; /** DRAW NUMERIC POINTS **/ do { /** Getting (x,y) for numeric points **/ x=cx+radius*cos(theta*M_PI/180); y=cy+radius*sin(theta*M_PI/180); /** Draw Numeric Points **/ circle(x,y,2); /* Draw Dots around each numeric points **/ circle(x+5,y,0); circle(x-5,y,0); circle(x,y+5,0); circle(x,y-5,0); /** Increase angle by 30 degrees, which is the circular distance between each numeric points. **/ theta+=30; /** Increase i by 1. **/ i++; } while(i!=12); //LIMIT NUMERIC POINTS UPTO =12= Numbers. i=0; /** DRAW DOTS BETWEEN NUMERIC POINTS. **/ do { putpixel(cx+radius*cos(i*M_PI/180),cy+radius*sin(i*M_PI/180),DARKGRAY); i+=6; } while(i!=360); /** FACE COMPLETELY DRAWN. **/ } //================ /** Function to get the current time. **/ void get_time(int &h,int &m,int &s) { /*time_t rawtime; struct tm *t; time(&rawtime); t = gmtime(&rawtime); h=t->tm_hour; m=t->tm_min; s=t->tm_sec;*/ time_t curtime; struct tm *t; curtime = time (NULL); t = localtime (&curtime); h=t->tm_hour; m=t->tm_min; s=t->tm_sec; } //================= /** Function to draw Second needle. **/ void second_needle(int s) { float angle=-90; float sx,sy; setcolor(0); sx=cx+S_N_L*cos((angle+s*6-6)*M_PI/180); sy=cy+S_N_L*sin((angle+s*6-6)*M_PI/180); line(cx,cy,sx,sy); setcolor(S_N_C); sx=cx+S_N_L*cos((angle+s*6)*M_PI/180); sy=cy+S_N_L*sin((angle+s*6)*M_PI/180); line(cx,cy,sx,sy); } /** Function to draw Minute needle. **/ void minute_needle(int m,int s) { float angle=-90; float sx,sy; setcolor(0); sx=cx+M_N_L*cos((angle+m*6-6)*M_PI/180); sy=cy+M_N_L*sin((angle+m*6-6)*M_PI/180); line(cx,cy,sx,sy); setcolor(M_N_C); sx=cx+M_N_L*cos((angle+m*6/*+(s*6/60)*/)*M_PI/180); sy=cy+M_N_L*sin((angle+m*6/*+(s*6/60)*/)*M_PI/180); line(cx,cy,sx,sy); } /** Function to draw Hour needle. **/ void hour_needle(int h,int m,int s) { float angle=-90; float sx,sy; setcolor(0); sx=cx+H_N_L*cos((angle+h*30-(m*30/60))*M_PI/180); sy=cy+H_N_L*sin((angle+h*30-(m*30/60))*M_PI/180); line(cx,cy,sx,sy); setcolor(H_N_C); sx=cx+H_N_L*cos((angle+h*30+(m*30/60))*M_PI/180); sy=cy+H_N_L*sin((angle+h*30+(m*30/60))*M_PI/180); line(cx,cy,sx,sy); } ///Digital Clock int digital() { int gd=DETECT; int gm; initwindow(1000,600,"C:\\TC\\BGI"); time_t rawTime; struct tm *currentTime; char a[100]; while(!kbhit()) { rawTime=time(NULL); currentTime=localtime(&rawTime); strftime(a,100,"%I:%M:%S",currentTime); setcolor(4);//3478 10 11 settextstyle(BOLD_FONT, HORIZ_DIR,10); outtextxy(210, 170, a); strftime(a, 100, "%p", currentTime); setcolor(LIGHTGREEN); settextstyle(8, HORIZ_DIR, 6); outtextxy(800, 120, a); strftime(a, 100, "%a, %d %b, %Y", currentTime); setcolor(YELLOW); settextstyle(8, HORIZ_DIR, 5); outtextxy(280, 380, a); //delay(1000); } getch(); closegraph(); } ///For Everything void menu() { char Var; int choice; int d; char ch = 'a'; int year, daycode, leapyear; while(1) { system("color 9F"); system("cls"); printf(" Name : Rafsan Jani \n"); printf(" ID : CE-15048 \n\n"); printf("************************************************************************************************************************"); printf(" Calender Application: \n"); printf("________________________________________________________________________________________________________________________\n"); printf("________________________________________________________________________________________________________________________\n\n"); printf("1. Find Out the Day\n"); printf("2. Print all the day of month\n"); printf("3. Print All the Month of the year\n"); printf("4. See Todays time and date\n"); printf("5. Set Time Or Stop Watch\n"); printf("6. Alarm Clock\n"); printf("7. See Analog Clock\n"); printf("8. See Digital Clock\n"); printf("9. Exit\n"); printf("\n________________________________________________________________________________________________________________________\n\n\n"); printf(" ENTER YOUR CHOICE : "); scanf("%d",&choice); getchar(); system("cls"); switch(choice) { case 1: //system("cls"); system("color D0"); printf("\n\n\n Enter date (DD MM YYYY) : "); scanf("%d %d %d",&date.dd,&date.mm,&date.yy); system("color 70"); printf("\n________________________________________________________________________________________________________________________\n"); printf("\n Day is : %s",getDay(date.dd,date.mm,date.yy)); printf("\n________________________________________________________________________________________________________________________\n"); printf("\n\n\nPress Enter to continue...... : "); getchar(); getchar(); break; case 2 : system("color E0"); printf("\n\n\n Enter month and year (MM YYYY) : "); scanf("%d %d",&date.mm,&date.yy); system("cls"); system("color 1F"); printMonth(date.mm,date.yy,20,5); break; case 3: system("color 47"); printf("\n\n\n Please enter a year : "); scanf("%d", &year); daycode = determinedaycode(year); determineleapyear(year); calendar(year, daycode); system("color 50"); break; case 4: system("color E0"); see_time(); break; case 5: //system("start sound_1.exe"); set_time(); getchar(); break; case 6: //printf("Enter 24 hour formate!\n"); //alarm(); system("Start Alarm.exe"); //getchar(); break; case 7: //system("color C9"); //system("Analog clock 1.cpp"); //printf("Under Construction"); analog(); printf("\nPress Enter to continue......"); getchar(); //getchar(); break; case 8: digital(); printf("\nPress Enter to COntinue: "); getchar(); ///menu(); break; case 9 : exit(0); } } } int main() { menu(); return 0; }
true
5f601a1da578cd247d9a8fea39081523b79e3fa0
C++
microsoft/CCF
/src/crypto/certs.h
UTF-8
3,819
2.546875
3
[ "Apache-2.0" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. #pragma once #include "ccf/crypto/key_pair.h" #include "ccf/crypto/pem.h" #include "ds/x509_time_fmt.h" #include <chrono> #include <string> namespace crypto { static std::string compute_cert_valid_to_string( const std::string& valid_from, size_t validity_period_days) { using namespace std::chrono_literals; // Note: As per RFC 5280, the validity period runs until "notAfter" // _inclusive_ so substract one second from the validity period. auto valid_to = ds::time_point_from_string(valid_from) + std::chrono::days(validity_period_days) - 1s; return ds::to_x509_time_string(valid_to); } static Pem create_self_signed_cert( const KeyPairPtr& key_pair, const std::string& subject_name, const std::vector<SubjectAltName>& subject_alt_names, const std::string& valid_from, const std::string& valid_to) { return key_pair->self_sign( subject_name, valid_from, valid_to, subject_alt_names, true /* CA */); } static Pem create_self_signed_cert( const KeyPairPtr& key_pair, const std::string& subject_name, const std::vector<SubjectAltName>& subject_alt_names, const std::string& valid_from, size_t validity_period_days) { return create_self_signed_cert( key_pair, subject_name, subject_alt_names, valid_from, compute_cert_valid_to_string(valid_from, validity_period_days)); } static Pem create_endorsed_cert( const Pem& csr, const std::string& valid_from, const std::string& valid_to, const Pem& issuer_private_key, const Pem& issuer_cert) { return make_key_pair(issuer_private_key) ->sign_csr(issuer_cert, csr, valid_from, valid_to, false /* Not CA */); } static Pem create_endorsed_cert( const Pem& csr, const std::string& valid_from, size_t validity_period_days, const Pem& issuer_private_key, const Pem& issuer_cert) { return create_endorsed_cert( csr, valid_from, compute_cert_valid_to_string(valid_from, validity_period_days), issuer_private_key, issuer_cert); } static Pem create_endorsed_cert( const KeyPairPtr& subject_key_pair, const std::string& subject_name, const std::vector<SubjectAltName>& subject_alt_names, const std::string& valid_from, size_t validity_period_days, const Pem& issuer_private_key, const Pem& issuer_cert) { return create_endorsed_cert( subject_key_pair->create_csr(subject_name, subject_alt_names), valid_from, validity_period_days, issuer_private_key, issuer_cert); } static Pem create_endorsed_cert( const Pem& public_key, const std::string& subject_name, const std::vector<SubjectAltName>& subject_alt_names, const std::string& valid_from, const std::string& valid_to, const Pem& issuer_private_key, const Pem& issuer_cert, bool ca = false) { auto issuer_key_pair = make_key_pair(issuer_private_key); auto csr = issuer_key_pair->create_csr(subject_name, subject_alt_names, public_key); return issuer_key_pair->sign_csr( issuer_cert, csr, valid_from, valid_to, ca, KeyPair::Signer::ISSUER); } static Pem create_endorsed_cert( const Pem& public_key, const std::string& subject_name, const std::vector<SubjectAltName>& subject_alt_names, const std::pair<std::string, std::string>& validity_period, const Pem& issuer_private_key, const Pem& issuer_cert, bool ca = false) { return create_endorsed_cert( public_key, subject_name, subject_alt_names, validity_period.first, validity_period.second, issuer_private_key, issuer_cert, ca); } }
true
b2e3ff28a4e455e37c845759506138d51f44721b
C++
celidon/Schoolwork
/c++/Semester2/figure/triangle.h
UTF-8
482
2.75
3
[]
no_license
//This is the header file triangle.h. //This is the interface for the class Triangle. //This is primarily intended to be used as a base class to derive //classes for different kinds of triangles. #ifndef TRIANGLE_H #define TRIANGLE_H #include "figure.h" using namespace std; namespace shapes { class Triangle:public Figure { public: Triangle(); void draw(); void erase(); void center(); }; }//shapes #endif //TRIANGLE_H
true
64c8b720ec09ca6e0597837d54eeac235e9860fd
C++
wuli2496/OJ
/UVa/1377 Ruler/Ruler(dfs).cpp
UTF-8
5,759
3.078125
3
[ "Apache-2.0" ]
permissive
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <memory> #include <set> #include <cmath> #include <map> using namespace std; template<typename Result> class AlgoPolicy { public: virtual ~AlgoPolicy() {} virtual Result execute() = 0; }; template<typename Result> class InputPolicy { public: virtual ~InputPolicy() {} virtual bool hasNext() = 0; virtual Result next() = 0; }; class OutputPolicy { public: virtual ~OutputPolicy() {} virtual void write() = 0; }; struct Data { vector<int> d; }; void print(int num) { cout << num << " "; } class DfsAlgo : public AlgoPolicy<set<int>> { public: DfsAlgo(const Data& data) { this->data = data; } set<int> execute() override { vector<int> availableSet; initAvailalbleSet(availableSet); set<int> dset(data.d.begin(), data.d.end()); map<int, int> property; set<int> ans; vector<int> curAns; curAns.push_back(0); dfs(0, availableSet, 0, curAns, 0, ans, property, dset); return ans; } private: void initAvailalbleSet(vector<int>& s) { set<int> ans; for (size_t i = 0; i < data.d.size(); ++i) { ans.insert(data.d[i]); } for (size_t i = 0; i < data.d.size(); ++i) { for (size_t j = i + 1; j < data.d.size(); ++j) { ans.insert(data.d[j] - data.d[i]); } } for(auto& n : ans) { s.push_back(n); } } void dfs(int curDepth, const vector<int>& v, int cur, vector<int>& curAns, int size, set<int>& ans, map<int, int>& property, const set<int>& dset) { if (curDepth >= MAXSIZE) { return; } if (size == static_cast<int>(data.d.size())) { if (ans.size() == 0 || curAns.size() < ans.size()) { ans.clear(); for (size_t i = 0; i < curAns.size(); ++i) { ans.insert(curAns[i]); } } return; } for (size_t i = cur; i < v.size(); ++i) { int cnt = add(v[i], curAns, property, dset); if (!cnt) { del(v[i], curAns, property, dset); continue; } curAns.push_back(v[i]); dfs(curDepth + 1, v, i + 1, curAns, size + cnt, ans, property, dset); curAns.pop_back(); del(v[i], curAns, property, dset); } } int add(int d, const vector<int>& curAns, map<int, int>& property, const set<int>& dset) { int cnt = 0; for (size_t i = 0; i < curAns.size(); ++i) { int diff = abs(curAns[i] - d); if (dset.count(diff)) { ++property[diff]; if (property[diff] == 1) { ++cnt; } } } return cnt; } void del(int d, const vector<int>& curAns, map<int, int>& property, const set<int>& dset) { for (size_t i = 0; i < curAns.size(); ++i) { int diff = abs(curAns[i] - d); if (dset.count(diff)) { --property[diff]; } } } private: Data data; const int MAXSIZE = 7; }; template <typename Result> class Solution { public: Solution(AlgoPolicy<Result>* algo) { pimpl.reset(algo); } Result run() { return pimpl->execute(); } private: shared_ptr<AlgoPolicy<Result>> pimpl; }; class LimitInput : public InputPolicy<Data> { public: LimitInput(istream& in) : instream(in) { } bool hasNext() override { instream >> n; return n != 0; } Data next() override { Data data; for (int i = 0; i < n; ++i) { int d; instream >> d; data.d.push_back(d); } sort(data.d.begin(), data.d.end()); data.d.erase(unique(data.d.begin(), data.d.end()), data.d.end()); return data; } private: istream& instream; int n; }; class Output : public OutputPolicy { public: Output(ostream& o, set<int>& s): out(o), ans(s) { } void write() override { out << "Case " << caseNo++ << ":" << endl; out << ans.size() << endl; bool first = true; for (auto& n : ans) { if (first) { out << n; first = false; } else { out << " " << n; } } out << endl; } private: ostream& out; set<int>& ans; static int caseNo; }; int Output::caseNo = 1; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); #ifndef ONLINE_JUDGE ifstream fin("F:\\OJ\\uva_in.txt"); streambuf* cinback = cin.rdbuf(fin.rdbuf()); #endif shared_ptr<InputPolicy<Data>> in(new LimitInput(cin)); while (in.get() != nullptr && in->hasNext()) { Data data = in->next(); AlgoPolicy<set<int>>* algo = new DfsAlgo(data); Solution<set<int>> solution(algo); set<int> s = solution.run(); shared_ptr<OutputPolicy> output(new Output(cout, s)); output->write(); } #ifndef ONLINE_JUDGE cin.rdbuf(cinback); #endif return 0; }
true
069cf0049f705969e58527a790e7168df7fefbc1
C++
datross/dungeonMaster
/src/camera.cpp
UTF-8
729
2.71875
3
[]
no_license
#include "camera.h" Camera::Camera() { } void Camera::init(float fov, float aspectRatio){ projection = glm::perspective<float>(glm::radians(fov), aspectRatio, 0.01, 100.); } glm::mat4 Camera::getVMatrix() { direction.x = glm::cos(glm::radians(rotation.y)) * glm::cos(glm::radians(rotation.x)); direction.z = glm::cos(glm::radians(rotation.y)) * glm::sin(glm::radians(rotation.x)); direction.y = glm::sin(glm::radians(rotation.y)); glm::vec3 local_left = glm::vec3(glm::sin(glm::radians(rotation.x)), 0, -glm::cos(glm::radians(rotation.x))); return glm::lookAt(position, position + direction, glm::cross(direction, local_left)); } glm::mat4 Camera::getPMatrix() { return projection; }
true
9c7f61347e3c9cf258a407d3063b52828958f338
C++
kudroma/SimpleApplication
/SimpleApplication/Ellipse.cpp
UTF-8
1,374
3.328125
3
[]
no_license
#include "Ellipse.h" #define _USE_MATH_DEFINES #include <math.h> #include <random> using namespace SimpleApplication; Ellipse::Ellipse() { m_center = Point2d(20, 21); m_a = 10; m_b = 5; m_name = "Ellipse"; int indexI = 0; const auto angle = M_PI / 20; while (angle * indexI < M_PI * 2) { auto point = pointInArc(m_angle, indexI); m_points.push_back(point); indexI++; } } Ellipse::Ellipse(const Point2d & center, float a, float b) : AbstractFigure(), m_center(center), m_a(a), m_b(b) // angle in degrees { m_name = "Ellipse"; int indexI = 0; //const auto angle = M_PI / 20; while (m_angle * indexI < M_PI * 2) { auto point = pointInArc(m_angle, indexI); m_points.push_back(point); indexI++; } } Ellipse::~Ellipse() { } float Ellipse::perimeter() const { return 4 * (static_cast<float>(M_PI) * m_a * m_b + m_a - m_b) / (m_a + m_b); } float Ellipse::area() const { return m_a * m_b * static_cast<float>(M_PI); } BoundingRect Ellipse::boundingBox() const { BoundingRect bRect; bRect.setCenter(m_center); bRect.setWidth(m_a); bRect.setHeight(m_b); return bRect; } Point2d Ellipse::pointInArc(float t, int indexPoint) const // t - angle in radians { Point2d pointVar; pointVar.setX(m_center.x() + m_a * cos(M_PI / 2 - indexPoint * t)); pointVar.setY(m_center.y() + m_b * sin(M_PI / 2 - indexPoint * t)); return pointVar; }
true
b0b98990355ac7db98b6c779af9768dcf879f7b6
C++
Rockmen0113/ConsoleSnakePractice
/SnakeGame/Map.cpp
MacCentralEurope
1,395
2.96875
3
[]
no_license
#include "pch.h" #include <iostream> #include "Map.h" #include "ConsoleSetting.h" Position Map::getPosition() const { return mapPosition; } int Map::getHeight() const { return Height; } int Map::getWidth() const { return Width; } Map::Map(Position position,int height, int width):mapPosition(position), Height(height), Width(width) { } void Map::Drow() { char drowSymb = ' '; int X = mapPosition.X; int Y = mapPosition.Y; int d_width = Width + mapPosition.X; int d_height = Height + mapPosition.Y; ConsoleSetting::GotoXY(X, Y); while (Y != d_height + 1) { if (X < d_width && (Y == mapPosition.Y || Y == d_height)) { drowSymb = UpDownLine; } else if (Y < d_height && (X == mapPosition.X || X == d_width)) { drowSymb = LeftRightLine; } if (Y == mapPosition.Y) { if (X == mapPosition.X) { drowSymb = TopLeftorner; } else if (X == d_width) { drowSymb = TopRightCorner; } } else if (Y == d_height) { if (X == mapPosition.X) { drowSymb = BotLeftCorner; } else if (X == d_width) { drowSymb = BotRightCorner; } } if (X > mapPosition.X && (Y > mapPosition.Y && Y != d_height)) { ConsoleSetting::GotoXY(d_width, Y); X = d_width; } //Drowing std::cout << drowSymb; ++X; if (X == d_width + 1) { X = mapPosition.X; ++Y; ConsoleSetting::GotoXY(X, Y); } } }
true
48be6f8ff78c1253c746850407b0833f6850f75b
C++
o2gy84/misc
/benchmark/euclid/emb.cpp
UTF-8
3,969
3.171875
3
[]
no_license
#include <iostream> #include <chrono> #include <vector> #include <xmmintrin.h> #include <math.h> namespace { float l2sqr_dist_sse2(const float *pVect1, const float *pVect2, std::size_t qty) // sqrt of Euclid distance { static_assert(sizeof(float) == 4, "Cannot use SIMD instructions with non-32-bit floats."); std::size_t qty4 = qty/4; std::size_t qty16 = qty/16; const float* pEnd1 = pVect1 + 16 * qty16; const float* pEnd2 = pVect1 + 4 * qty4; const float* pEnd3 = pVect1 + qty; __m128 diff, v1, v2; __m128 sum = _mm_set1_ps(0); while (pVect1 < pEnd1) { v1 = _mm_loadu_ps(pVect1); pVect1 += 4; v2 = _mm_loadu_ps(pVect2); pVect2 += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); v1 = _mm_loadu_ps(pVect1); pVect1 += 4; v2 = _mm_loadu_ps(pVect2); pVect2 += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); v1 = _mm_loadu_ps(pVect1); pVect1 += 4; v2 = _mm_loadu_ps(pVect2); pVect2 += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); v1 = _mm_loadu_ps(pVect1); pVect1 += 4; v2 = _mm_loadu_ps(pVect2); pVect2 += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); } while (pVect1 < pEnd2) { v1 = _mm_loadu_ps(pVect1); pVect1 += 4; v2 = _mm_loadu_ps(pVect2); pVect2 += 4; diff = _mm_sub_ps(v1, v2); sum = _mm_add_ps(sum, _mm_mul_ps(diff, diff)); } float __attribute__((aligned(16))) TmpRes[4]; _mm_store_ps(TmpRes, sum); float res = TmpRes[0] + TmpRes[1] + TmpRes[2] + TmpRes[3]; while (pVect1 < pEnd3) { float diff2 = *pVect1++ - *pVect2++; res += diff2 * diff2; } return res; } float euclidean_distance_impl(const std::vector<float> &v1, const std::vector<float> &v2) // Pseudocode: // float dist = 0; // for (size_t i = 0; i < v1.size(); ++i) // { // float v = (v1[i] - v2[i]); // v = v * v; // dist += v; // } // return sqrt(dist); { if (v1.size() != v2.size()) { throw std::runtime_error("bad vectors"); } float s = l2sqr_dist_sse2(v1.data(), v2.data(), v1.size()); return sqrt(s); } } // namespace float euclidean_distance(const std::vector<float> &v1, const std::vector<float> &v2) { return euclidean_distance_impl(v1, v2); } float dot_product(const std::vector<float> &v1, const std::vector<float> &v2) { if (v1.size() != v2.size()) { throw std::runtime_error("bad vectors"); } float res = 0; for (int i = 0; i < v1.size(); ++i) { res += v1[i]*v2[i]; } return res; } float global_sum = 0; // need common sum to prevent compiler optimizations std::vector<float> v1(128, 0.0); std::vector<float> v2(128, 0.0); void test_impl(int n) { for (float &f : v1) { f += n; } for (float &f : v2) { f -= n; } global_sum += euclidean_distance(v1, v2); global_sum += dot_product(v1, v2); } int test(size_t num) { std::cerr << "iterations: " << num << "\n"; auto start = std::chrono::steady_clock::now(); for (size_t i = 0; i < num; ++i) { test_impl(i); } auto end = std::chrono::steady_clock::now(); int ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); std::cerr << "total: " << ms << " ms\n"; return 0; } int main(int argc, char *argv[]) { if (argc < 2) { std::cerr << "usage: ./" << argv[0] << " num\n"; exit(-1); } try { test(std::stoul(argv[1])); } catch (const std::exception &e) { std::cerr << "exception: " << e.what() << "\n"; exit(-1); } std::cerr << "sum: " << global_sum << "\n"; return 0; }
true
c53502c9096bd782ec85cbc466aa4b5c9dce3b70
C++
OTTFFYZY/StandardCodeLibrary
/BasicDataStructure/FenwickTree_rarq2.cpp
UTF-8
636
2.6875
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; const int M=1e5+5; int bit0[M],bit1[M]; inline int lowbit(int x) { return x&(-x); } void init() { memset(bit0,0,sizeof(bit0)); memset(bit1,0,sizeof(bit1)); } void add(int p,int x) { for(int i=p;i<M;i++) bit0[i]+=x,bit1[i]+=x*p; } void add(int l,int r,int x) { add(l-1,-x); add(r,x); } int getsum(int p,int bit[]) { int ans=0; for(int i=p;i;i-=lowbit(i)) ans+=bit[i]; return ans; } int getsum(int l,int r) { return getsum(r,bit1)+(getsum(M-1,bit0)-getsum(r,bit0))*r -getsum(l-1,bit1)-(getsum(M-1,bit0)-getsum(l-1,bit0))*(l-1); } int main() { return 0; }
true
f00980c78c0e9e8389cbc94280008b7e04fad604
C++
jakubsadura/Swiezy
/src/Apps/Gimias/Core/DataHandling/src/coreLightData.h
UTF-8
2,298
2.640625
3
[]
no_license
/* * Copyright (c) 2009, * Computational Image and Simulation Technologies in Biomedicine (CISTIB), * Universitat Pompeu Fabra (UPF), Barcelona, Spain. All rights reserved. * See license.txt file for details. */ #ifndef coreLightData_H #define coreLightData_H #include "gmDataHandlingWin32Header.h" #include "coreObject.h" #include <boost/serialization/vector.hpp> #include <boost/serialization/string.hpp> #include <boost/serialization/nvp.hpp> #include "boost/filesystem.hpp" namespace Core{ /** \brief A LightData is a light representation of DataEntity. It is used in Session class to store essential information about data entity which later can be stored in xml session file \author Jakub Lyko \date 10 Dec 2009 \ingroup gmDataHandling */ class GMDATAHANDLING_EXPORT LightData { public: //! LightData(); //! virtual ~LightData(); //! std::string GetName() const { return m_name; } //! void SetName(std::string val) { m_name = val; } //! std::string GetFilepath() const { return m_filepath; } //! std::string GetRelativePath() const { return m_relativePath; } //! unsigned int GetNumOfTimeSteps() const { return std::atoi(m_numOfTimeSteps.c_str());} //! void SetFilepath(std::string val) { m_filepath = val; } //! void SetNumberOfTimeSteps(std::string val) { m_numOfTimeSteps = val; } //! std::vector<LightData*> GetChildren() {return m_childrenList;} //! void AddChild(LightData* child); //! give access to private members for serialization friend class boost::serialization::access; private: template<class Archive> void serialize(Archive &ar, const unsigned int version); private: //! std::string m_name; //! std::string m_filepath; //! std::string m_relativePath; //! std::string m_numOfTimeSteps; //! std::vector<LightData*> m_childrenList; }; template<class Archive> void LightData::serialize(Archive &ar, const unsigned int version) { boost::filesystem::path pathFile(m_filepath); m_relativePath = boost::filesystem::basename(pathFile) + boost::filesystem::extension(pathFile); using boost::serialization::make_nvp; ar & make_nvp("Name", m_name); ar & make_nvp("TimeSteps", m_numOfTimeSteps ); ar & make_nvp("Filepath", m_relativePath); ar & make_nvp("Children", m_childrenList); } } // end namespace Core #endif
true
d45fab7a593d08fa0bd68cfb94b366f79192f244
C++
ayanamizuta/cpro
/atcoder/arc/arc110/d.cpp
UTF-8
1,454
2.609375
3
[]
no_license
#include "bits/stdc++.h" #include <atcoder/all> using namespace std; #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) #define ALL(a) (a).begin(),(a).end() #define LL long long using mint = atcoder::modint1000000007; #define MOD 1000000007 #define FACT_MAX 1000000 LL fact[FACT_MAX]; class Combinatrics{ private: long long mod = MOD; int fact_max = FACT_MAX; public: Combinatrics(){ fact[0]=1; for(int i=1;i<fact_max;i++) fact[i] = (fact[i-1]*i)%mod; } long long power(long long n, long long e){ long long ret = 1; long long b = n; while(e){ if(e%2!=0) ret*=b; ret%=mod; b*=b; b%=mod; e/=2; } return ret; } long long inv(long long n){ return power(n,mod-2); } long long div(long long n1,long long n2){ return n1*power(n2,mod-2)%mod; } long long nck(int n,int k){ if(k>n || k<0) return 0LL; if(k==n || k==0) return 1LL; return (fact[n]*inv(fact[n-k])%mod)*inv(fact[k])%mod; } }; int n,m; int a[2001]; // (su 0) + (su+1 1) + (su+2 2) + ... + (su+mk mk) mint solve(LL su, LL mk){ Combinatrics comb; //cerr<<su+1+mk<<" "<<mk<<endl; mint ret = 1; FOR(i,1,2+su)ret*=mint(su+2+mk-i)/mint(i); return ret; } int main(){ cin>>n>>m; REP(i,n)cin>>a[i]; LL mk = m,su=0; REP(i,n)su += a[i]; mk -= su; su += n-1; mint ret = solve(su,mk); cout<<ret.val()<<endl; }
true
2c7b8cdfd566698075ac816e0261e0dafd313366
C++
s-shirayama/ProgramingContestChallengeBook
/2-2-2.cpp
UTF-8
569
2.546875
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> using namespace std; const int MAXN = 2000; int main() { int N; string S; cin >> N >> S; string T(S); reverse(T.begin(), T.end()); int len = S.length(), idxS = 0, idxT = 0; for (int i = N; i > 0; i--) { bool chk = false; for (int j = 0; j < N - idxS - idxT; j++) { if (S[idxS+j] > T[idxT+j]) { cout << T[idxT++]; chk = true; break; } else if (S[idxS+j] < T[idxT+j]) { cout << S[idxS++]; chk = true; break; } } if (!chk) cout << S[idxS++]; } cout << endl; return 0; } /* 6 ACDBCB =>ABCBCD */
true
e9ee462ba21b00d2b42cc43e07bc4a63ef31811f
C++
mlkood/OpenFFBoard
/Firmware/FFBoard/Src/CAN.cpp
UTF-8
4,514
2.53125
3
[ "MIT" ]
permissive
/* * CAN.cpp * * Created on: 21.06.2021 * Author: Yannick */ #include "target_constants.h" #ifdef CANBUS #include "CAN.h" CANPort::CANPort(CAN_HandleTypeDef &hcan) : hcan(&hcan) { //HAL_CAN_Start(this->hcan); } CANPort::~CANPort() { // removes all filters for (uint8_t i = 0; i < canFilters.size(); i++){ canFilters[i].FilterActivation = false; HAL_CAN_ConfigFilter(this->hcan, &canFilters[i]); } canFilters.clear(); HAL_CAN_Stop(this->hcan); } uint32_t CANPort::getSpeed(){ return presetToSpeed(speedPreset); } uint8_t CANPort::getSpeedPreset(){ return (speedPreset); } /** * Converts a numeric speed in bits/s to the matching preset ID */ uint8_t CANPort::speedToPreset(uint32_t speed){ uint8_t preset = 255; switch(speed){ case 50000: preset = CANSPEEDPRESET_50; break; case 100000: preset = CANSPEEDPRESET_100; break; case 125000: preset = CANSPEEDPRESET_125; break; case 250000: preset = CANSPEEDPRESET_250; break; case 500000: preset = CANSPEEDPRESET_500; break; case 1000000: preset = CANSPEEDPRESET_1000; break; default: break; } return preset; } /** * Converts a preset to bits/s */ uint32_t CANPort::presetToSpeed(uint8_t preset){ uint32_t speed = 0; switch(preset){ case CANSPEEDPRESET_50: speed = 50000; break; case CANSPEEDPRESET_100: speed = 100000; break; case CANSPEEDPRESET_125: speed = 125000; break; case CANSPEEDPRESET_250: speed = 250000; break; case CANSPEEDPRESET_500: speed = 500000; break; case CANSPEEDPRESET_1000: speed = 1000000; break; default: break; } return speed; } /** * Changes the speed of the CAN port to a preset */ void CANPort::setSpeedPreset(uint8_t preset){ if(preset > 5 || preset == this->speedPreset) return; speedPreset = preset; takeSemaphore(); HAL_CAN_Stop(this->hcan); HAL_CAN_AbortTxRequest(hcan, txMailbox); this->hcan->Instance->BTR = canSpeedBTR_preset[preset]; HAL_CAN_ResetError(hcan); HAL_CAN_Start(this->hcan); giveSemaphore(); } /** * Changes the speed of the CAN port in bits/s * Must match a preset speed */ void CANPort::setSpeed(uint32_t speed){ uint8_t preset = speedToPreset(speed); setSpeedPreset(preset); } void CANPort::takeSemaphore(){ bool isIsr = inIsr(); BaseType_t taskWoken = 0; if(isIsr) this->semaphore.TakeFromISR(&taskWoken); else this->semaphore.Take(); isTakenFlag = true; portYIELD_FROM_ISR(taskWoken); } void CANPort::giveSemaphore(){ bool isIsr = inIsr(); BaseType_t taskWoken = 0; if(isIsr) this->semaphore.GiveFromISR(&taskWoken); else this->semaphore.Give(); isTakenFlag = false; portYIELD_FROM_ISR(taskWoken); } bool CANPort::sendMessage(CAN_tx_msg msg){ return this->sendMessage(&msg.header,msg.data,&this->txMailbox); } bool CANPort::sendMessage(CAN_TxHeaderTypeDef *pHeader, uint8_t aData[],uint32_t *pTxMailbox){ if(pTxMailbox == nullptr){ pTxMailbox = &this->txMailbox; } takeSemaphore(); this->isTakenFlag = true; if (HAL_CAN_AddTxMessage(this->hcan, pHeader, aData, pTxMailbox) != HAL_OK) { /* Transmission request Error */ giveSemaphore(); return false; } giveSemaphore(); return true; } /** * Adds a filter to the can handle * Returns a free bank id if successfull and -1 if all banks are full * Use the returned id to disable the filter again */ int32_t CANPort::addCanFilter(CAN_FilterTypeDef sFilterConfig){ takeSemaphore(); int32_t lowestId = sFilterConfig.FilterFIFOAssignment == CAN_RX_FIFO0 ? 0 : slaveFilterStart; int32_t highestId = sFilterConfig.FilterFIFOAssignment == CAN_RX_FIFO0 ? slaveFilterStart : 29; int32_t foundId = -1; for(uint8_t id = lowestId; id < highestId ; id++ ){ for(CAN_FilterTypeDef filter : canFilters){ if(filter.FilterFIFOAssignment == sFilterConfig.FilterFIFOAssignment && id == filter.FilterBank){ break; } } foundId = id; break; } if(foundId < highestId){ if (HAL_CAN_ConfigFilter(this->hcan, &sFilterConfig) == HAL_OK){ canFilters.push_back(sFilterConfig); } } giveSemaphore(); return foundId; } /** * Disables a can filter * Use the id returned by the addCanFilter function */ void CANPort::removeCanFilter(uint8_t filterId){ semaphore.Take(); for (uint8_t i = 0; i < canFilters.size(); i++){ if(canFilters[i].FilterBank == filterId){ canFilters[i].FilterActivation = false; HAL_CAN_ConfigFilter(this->hcan, &canFilters[i]); canFilters.erase(canFilters.begin()+i); break; } } semaphore.Give(); } #endif
true
2263d72abe7ad16f16ee7c0be1909fc201e595ad
C++
flotzilla/light_table
/src/NeoLight.h
UTF-8
1,974
2.671875
3
[ "MIT" ]
permissive
#ifndef NEOLIGHT_H #define NEOLIGHT_H #include <Adafruit_NeoPixel.h> class NeoLight : public Adafruit_NeoPixel { #define MODE_LIGHT 0 #define MODE_ANIMATION 1 #define LIGHNT_MODE_0 0 // WHITE #define LIGHNT_MODE_1 1 // GREEN #define LIGHNT_MODE_2 2 // BLUE #define LIGHNT_MODE_3 3 // RED #define LIGHNT_MODE_4 4 // YELLOW #define LIGHNT_MODE_5 5 // LIGHT_BLUE #define LIGHNT_MODE_6 6 // PURPLE #define LIGHNT_MODE_7 7 // LIGHT_BLUE #define LIGHNT_MODE_8 8 // LIGHT_BLUE #define LIGHNT_MODE_9 9 // LIGHT_BLUE #define LIGHNT_MODE_10 10 // LIGHT_BLUE #define LIGHNT_MODE_11_CUSTOM 11 // LIGHT_BLUE #define MAX_LIGHT_MODE LIGHNT_MODE_11_CUSTOM #define MIN_LIGHT_MODE LIGHNT_MODE_0 #define ANIMATION_MODE_0 0 // RAINBOW #define ANIMATION_MODE_1 1 // CHASE #define ANIMATION_MODE_2 2 // LAVA #define ANIMATION_MODE_3 3 // SCANNER #define MAX_ANIMATION_MODE ANIMATION_MODE_3 #define MIN_ANIMATION_MODE ANIMATION_MODE_0 const uint8_t ANIMATION_CHASE_DELAY = 70, ANIMATION_SCANNER_DELAY = 10, ANIMATION_LAVA_DELAY = 50; bool shouldAnimationStop = false, shouldBeTurnedOff = false; uint8_t current_mode = MODE_LIGHT, currentLightMode = LIGHNT_MODE_0, currentAnimationMode = ANIMATION_MODE_0, light_intensity; public: NeoLight(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)()); uint32_t Wheel(byte WheelPos); uint32_t customColor; void (*OnComplete)(); void setIntensity(uint8_t val); void Update(); void Increment(); void Reverse(); void ColorSet(uint32_t color); void calculateColor(); void turnOn(); void turnOff(); void changeMode(); void changeAnimationMode(); // animations void animationRainbow(); void animationChase(); void animationLava(); void animationScanner(); void setCustomColor(uint8_t r, uint8_t g, uint8_t b); int getCurrentLightMode(); }; #endif
true
f97e5c8af4ca5dc08e1f837af93ecc9335e37f72
C++
wandec/cmake
/cmake3/main.cpp
UTF-8
671
2.90625
3
[]
no_license
#include <iostream> #include "version.hpp" #include <algorithm> #include "vector" #include "iostream" #if defined(BOOST) #include <boost/range/algorithm.hpp> #endif void sortValues(std::vector<int> &values) { #if defined(BOOST) std::cout << "boost sort \n"; boost::range::sort(values); #else std::cout<<"std sort \n"; std::sort(values.begin(), values.end()); #endif } int main() { std::cout << "projectname "<<_DPROJECT_NAME<<" version " << VERSION_MAJOR << "." << VERSION_MINOR << "\n"; std::vector<int> values = {13, 24, 5, 56, 78}; sortValues(values); for (auto &i : values) { std::cout << i << " "; } return 0; }
true
0da2c2339facff9916369581358a1dc3a2d41668
C++
watson-intu/self
/src/gestures/VolumeGesture.h
UTF-8
1,550
2.515625
3
[]
no_license
/** * Copyright 2017 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef VOLUME_GESTURE_H #define VOLUME_GESTURE_H #include "IGesture.h" #include "SelfLib.h" //! This is the base class for any gesture that changes the volume. class SELF_API VolumeGesture : public IGesture { public: RTTI_DECL(); //! Construction VolumeGesture() : m_fChange( 0.0f ), m_fTargetVolume( 0.0f ) {} VolumeGesture( const std::string & a_GestureId ) : IGesture( a_GestureId ), m_fChange( 0.0f ), m_fTargetVolume( 0.0f ) {} //! ISerializable interface virtual void Serialize(Json::Value & json); virtual void Deserialize(const Json::Value & json); //! IGesture interface virtual bool Execute( GestureDelegate a_Callback, const ParamsMap & a_Params ); //! Mutators void SetChange(float a_fChange) { m_fChange = a_fChange; } void SetTargetVolume(float a_fTargetVolume) { m_fTargetVolume = a_fTargetVolume; } protected: //! Data float m_fChange; float m_fTargetVolume; }; #endif //VOLUME_GESTURE_H
true
4582c711a9160d0fbf0afed164e22523ce7d63f0
C++
industriousonesoft/leet-code
/62.Unique Paths/main.cpp
UTF-8
1,775
3.453125
3
[ "MIT" ]
permissive
/* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? Example 1: Input: m = 3, n = 7 Output: 28 Example 2: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Down -> Down 2. Down -> Down -> Right 3. Down -> Right -> Down Example 3: Input: m = 7, n = 3 Output: 28 Example 4: Input: m = 3, n = 3 Output: 6   Constraints: 1 <= m, n <= 100 It's guaranteed that the answer will be less than or equal to 2 * 109. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-paths 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ #include <iostream> using namespace std; int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) { return 0; } int dp[m][n]; memset(dp, 0, sizeof(dp)); for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { // 到与起点在同一维度的点,只有一条路径可选 // 起点到自身的路径也是1 if (i == 0 || j == 0) { dp[i][j] = 1; }else { // 与起点不再同一维度的点,存在向右和向下选择 dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } } return dp[m-1][n-1]; } int main(int argc, const char* argv[]) { int m = 3, n = 0; cout << "m: " << m << " n: " << n << " res: " << uniquePaths(m, n) << endl; return 0; }
true
f2f6a04e59516fc2a26d552b43aba2228d6425df
C++
sensidev/savnet-cpp-course
/apps/exp-tinder/match_making_service.h
UTF-8
596
2.515625
3
[]
no_license
#ifndef SAVNET_CPP_MATCH_MAKING_SERVICE_H #define SAVNET_CPP_MATCH_MAKING_SERVICE_H #include "profile.h" #include "profile_database.h" class MatchMakingService { private: ProfileDatabase *database_pointer; /* Here will be the instance stored. */ static MatchMakingService *instance; /* Private constructor to prevent instancing. */ MatchMakingService(ProfileDatabase *database_pointer); public: /* Static access method. */ static MatchMakingService *get_instance(ProfileDatabase *database_pointer); vector<Profile> match(const Profile& profile); }; #endif
true
bde950569e719223aa1f13a93b49f23278ae4869
C++
MakinoRuki/TopCoder
/TCO18R4Easy.cpp
UTF-8
745
2.578125
3
[]
no_license
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <algorithm> #define N 1002 using namespace std; const int mod = 1000000007; class SumPyramid { public: int dp[N]; int comb[N][N]; int countPyramids(int lev, int top) { memset(comb, 0, sizeof(comb)); for (int i = 0; i <= lev; ++i) { comb[i][0] = 1; for (int j = 1; j <= i; ++j) { comb[i][j] = min(comb[i - 1][j] + comb[i - 1][j - 1], N); } } memset(dp, 0, sizeof(dp)); dp[0] = 1; for (int i = 1; i <= lev; ++i) { int number = comb[lev - 1][i - 1]; if (number >= N) continue; for (int j = 0; j + number <= top; ++j) { dp[j + number] = (dp[j + number] + dp[j]) % mod; } } return dp[top]; } };
true
7bd54f964474a1f6a59689920497adff5ec31e2f
C++
vidalmatheus/codes
/LintCode/Medium/maximumSizeSubarraySumEqualsk.cpp
UTF-8
1,524
3.453125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: /** * @param nums: an array * @param k: a target value * @return: the maximum length of a subarray that sums to k */ int maxSubArrayLen(vector<int> &nums, int k) { // Write your code here if (nums.size() == 0) return 0; unordered_map<int,int> index; int prefix_sum_i = 0; index[0] = -1; int max_size = nums[0] == k ? 1 : 0; for (int i=0;i<nums.size();i++){ prefix_sum_i += nums[i]; // j i -> i-(j+1)+1 // [0,1,2,3,4] // prefix_sum_i - prefix_sum_j = k int prefix_sum_j = prefix_sum_i - k; if (index.find(prefix_sum_j) != index.end()){ int j = index[prefix_sum_j]; max_size = max(max_size, i-j); } if (index.find(prefix_sum_i) != index.end()) index[prefix_sum_i] = min(index[prefix_sum_i],i); else index[prefix_sum_i] = i; } return max_size; } }; // Time: O(n) // Space: O(n) int main(){ Solution sol; vector<int> nums{1, -1, 5, -2, 3}; int k = 3; assert(sol.maxSubArrayLen(nums,k) == 4); nums = {-2, -1, 2, 1}; k = 1; assert(sol.maxSubArrayLen(nums,k) == 2); nums = {-1}; k = -1; assert(sol.maxSubArrayLen(nums,k) == 1); cout << "Passed!" << endl; return 0; }
true
8a03f7ee0a05c99f694477fcb8849b592a8386e6
C++
AG-Systems/Markov
/Markov/Markov.h
UTF-8
3,399
3.65625
4
[]
no_license
#pragma once #include <string> #include <map> #include <random> #include <vector> #include <regex> class Markov { public: void SetOrder(int ord) { order = ord; } void ParseText(std::string input) { // Define what constitutes a word. Punctuation, in this case, counts. std::regex word("([\\w-']+|[,\\.!\\?][\"']|['\"]|[\\.,:;!\\?\\n])"); std::smatch results; // Find all matches auto entries_begin = std::sregex_iterator(input.begin(), input.end(), word); auto entries_end = std::sregex_iterator(); // Track the preceeding words in a vector std::vector<std::string> prev_words; prev_words.resize(order, "\n"); std::string next_word; std::string first; // For every match for (auto it = entries_begin; it != entries_end; ++it) { // Push back on the vector of preceeding words (old words fall off the end) // Store the state of the vector as a concat-ed string first = prev_words[0]; for (int i = 1; i < order; ++i) { first.append(prev_words[i]); prev_words[i - 1] = prev_words[i]; } // Store the match to a string next_word = (*it)[1]; // Convert to lowercase std::transform(next_word.begin(), next_word.end(), next_word.begin(), ::tolower); // Store the new word in the preceeding words vector for use next time round prev_words[order - 1] = next_word; // Store the relationship RegisterChain(first, next_word); } } std::string GetMarkovString(int words_approx) { std::string output; std::string next; std::string last; std::vector<std::string> last_strings; last_strings.resize(order, "\n"); // While we still want more words (or are not at a convenient stopping point) while (words_approx > 0 || next != "\n") { // Get the preceeding word concat-ed string and push back on the vector of words last = last_strings[0]; for (int i = 1; i < order; ++i) { last.append(last_strings[i]); last_strings[i - 1] = last_strings[i]; } // Use the preceeding words to find the next word next = GetNextWord(last); // Push that new word to the vector of preceeding words for next time around last_strings[order - 1] = next; // Do a little housekeeping to keep things tidier, add spaces when words are real words if (next != "," && next != "." && next != ",\"" && next != ".\"" && next != ",'" && next != ".'") { output.append(" "); words_approx--; } // Store the word to the output string output.append(next); } return output; } std::string GetNextWord(std::string first) { // First fetch the map of next-word options from the primary map auto options = markov_map.at(first); std::uniform_int_distribution<int> dist(0, markov_count[first]); // Generate a random number (up to max of total number of times this string occurred) int val = dist(generator); auto it = options.begin(); // Iterate over options and subtract from generated number. Simple probability method. do { val -= it->second; if (val > 0) ++it; } while (val > 0); // Return the value return it->first; } void SeedGenerator(int seed) { generator.seed(seed); } void RegisterChain(std::string first, std::string last) { markov_map[first][last]++; markov_count[first]++; } private: std::map<std::string, std::map<std::string, int>> markov_map; std::map<std::string, int> markov_count; std::default_random_engine generator; int order; };
true
54d130847daaae2364555cbe50024380446b54df
C++
Kapelka-Yaroslav/Kapelka-Yaroslav
/Лабораторные/Лабораторная работа №4/Лабораторная работа № 4/CMetod.h
UTF-8
720
2.65625
3
[]
no_license
#include "CCountry.h" class CMetod { private: CCountry* countries; CCountry* copy; int next_i = 0; int new_i = 1; public: void add_el(const CCountry& CCountry); void remove_el(const int& index); void del_all(); void get_to_Screen(const int& index) const; CCountry find_to_index(const int& index) const; void print_all() const; void find_to_population_density() const; void find_to_str_by_file(const std::string str); std::string get_str_by_file(const int& index) const; void write_to_file(const std::string name); void read_from_file(const std::string name); bool check_str(const std::string& str) const; void print_all_with_2_or_more_words() const; };
true
04ea2569672a3b3ad3a2c87846c607267417d5d6
C++
Althieris/Algoritmo_II
/Exercicio27.cpp
UTF-8
814
3.171875
3
[]
no_license
#include "pch.h" #include <iostream> int lerdados() { int a; printf(": "); scanf_s("%i", &a); return a; } void calculonotas(int valorcompra, int valordinheiro) { int troco = valordinheiro - valorcompra; int nota100 = 0; int nota10 = 0; int nota1 = 0; if (troco > 0) { nota100 = (troco - (troco % 100)) / 100; nota10 = (troco % 100) / 10; nota1 = (troco % 10); printf("Notas de 100 : %i \n Notas de 10 : %i \n Notas de 1: %i \n", nota100, nota10, nota1); } else { printf("Faltando valor em dinheiro \n"); } } int main() { printf("Digite o valor da compra "); int valorcompra = lerdados(); printf("Digite o em dinheiro "); int valoremdinheiro = lerdados(); calculonotas(valorcompra, valoremdinheiro); system("pause"); return 0; }
true
02e0fc24db3ce5919fe263c68d60a624938b3fec
C++
linpengchao/DataStructures
/Graph/code/adjacencylish/adjacency_lish.cpp
UTF-8
11,615
3.296875
3
[]
no_license
#include "adjacency_lish.h" #include <cstdio> #include <iostream> #include <queue> #include <stack> #include <algorithm> // 若图G中存在顶点v,则返回v在图中的位置信息,否则返回其他信息 int LocateVex(ALGraph G, VertexType v) { for (int i = 0; i != G.vexnum; ++i) if (G.vertices[i].data == v) return i; return -1; } void Clear() { while (std::getchar() != '\n'); } /*----------------------------------------------以邻接表储方式创建相关图或网------------------------------------------------*/ // 采用邻接表表示法创建无向图 void CreateUDG(ALGraph &G) { std::cout << "接表表示法创建无向图。\n依次输入总顶点数和总边数:"; std::cin >> G.vexnum >> G.arcnum; Clear(); // 创建表头节点表 std::cout << "请输入顶点值的序列:"; for (int i = 0; i != G.vexnum; ++i) { std::cin >> G.vertices[i].data; G.vertices[i].firstarc = nullptr; } Clear(); // 创建边表 VertexType v1, v2; // 两个顶点确定一条边 for (int k = 0; k != G.arcnum; ++k) { std::cout << "请输入第" << k + 1 << "条边依附的两个顶点:"; std::cin >> v1 >> v2; Clear(); // 确定v1和v2在G中位置,即顶点在G.vertices中的序号 int i = LocateVex(G, v1); int j = LocateVex(G, v2); // 头插法创建边链表 ArcNode *p1 = new ArcNode; // 生成一个新的边结点*p1 p1->adjvex = j; // 邻接点序号为j p1->nextarc = G.vertices[i].firstarc; G.vertices[i].firstarc = p1; ArcNode *p2 = new ArcNode; p2->adjvex = i; p2->nextarc = G.vertices[j].firstarc; G.vertices[j].firstarc = p2; } } // 创建有向图 void CreateDG(ALGraph &G) { // 获取有向图的总顶点数和总边数 std::cout << "输入有向图的总顶点数和总边数:"; std::cin >> G.vexnum >> G.arcnum; // 获取顶点序列 std::cout << "输入顶点序列:"; for (int i = 0; i != G.vexnum; ++i) { std::cin >> G.vertices[i].data; G.vertices[i].firstarc = nullptr; } // 输入各条边的信息 VertexType v1, v2; for (int k = 0; k != G.arcnum; ++k) { std::cout << "输入第" << k+1 << "条有向边依附的两个顶点:"; std::cin >> v1 >> v2; int i = LocateVex(G, v1); int j = LocateVex(G, v2); ArcNode *p = new ArcNode; p->adjvex = j; p->nextarc = G.vertices[i].firstarc; G.vertices[i].firstarc = p; } } // 创建有向网 void CreateDN(ALGraph &G) { // 输入有向网的总顶点数和总边数 std::cout << "输入有向网的总顶点数和总边数:"; std::cin >> G.vexnum >> G.arcnum; // 输入有向网的顶点序列 std::cout << "输入有向网的顶点序列:"; for (int i = 0; i != G.vexnum; ++i) { std::cin >> G.vertices[i].data; G.vertices[i].firstarc = nullptr; } // 输入各条边的信息 v1 v2 weight VertexType v1, v2; int weight = 0; for (int k = 0; k != G.arcnum; ++k) { std::cout << "输入第" << k+1 << "条弧依附的顶点和权值:"; std::cin >> v1 >> v2 >> weight; int i = LocateVex(G, v1); int j = LocateVex(G, v2); ArcNode *p = new ArcNode; p->weight = weight; p->adjvex = j; p->nextarc = G.vertices[i].firstarc; G.vertices[i].firstarc = p; } } void DestroyGraph(ALGraph &G) { for (int i = 0; i != G.vexnum; ++i) { for (ArcNode *p = G.vertices[i].firstarc; p != nullptr; p = G.vertices[i].firstarc) { G.vertices[i].firstarc = p->nextarc; delete p; p = nullptr; } } } void PrintAdjList(ALGraph G) { for (int i = 0; i != G.vexnum; ++i) { std::cout << i << " | " << G.vertices[i].data << " |"; for (auto p = G.vertices[i].firstarc; p != nullptr; p = p->nextarc) std::cout << "-->| " << p->adjvex << " |"; std::cout << std::endl; } } int FirstAdjVex(ALGraph G, VertexType v) { if (LocateVex(G, v) == -1) return -1; return G.vertices[LocateVex(G, v)].firstarc->adjvex; } int NextAdjVex(ALGraph G, VertexType v, VertexType w) { if (LocateVex(G, v) == -1) return -1; for (ArcNode *p = G.vertices[LocateVex(G, v)].firstarc; p != nullptr; p = p->nextarc) { if (p->adjvex == LocateVex(G, w)) { if (p->nextarc == nullptr) return -1; else return p->nextarc->adjvex; } } return -1; } bool visited[MVNum]; void BFS(ALGraph G, VertexType v) { // 从顶点v出发,访问v并置true std::cout << v << " "; visited[LocateVex(G, v)] = true; // 初始化队列,顶点v进队 std::queue<VertexType> Queue; Queue.push(v); // 只要队列不空 while (!Queue.empty()) { VertexType u = Queue.front(); // 取得队头元素 Queue.pop(); // 队头元素出队 for (int w = FirstAdjVex(G, u); w >= 0; w = NextAdjVex(G, u, G.vertices[w].data)) { if (!visited[w]) { std::cout << G.vertices[w].data << " "; visited[w] = true; Queue.push(G.vertices[w].data); } } } } void BFSTravese(ALGraph G) { for (int i = 0; i != G.vexnum; ++i) visited[i] = false; for (int i = 0; i != G.vexnum; ++i) if (!visited[i]) BFS(G, G.vertices[i].data); } void DFS(ALGraph G, VertexType v) { // 初始化栈,顶点v进栈 std::stack<VertexType> stk; stk.push(v); // 当栈不为空 while (!stk.empty()) { VertexType u = stk.top(); int i = LocateVex(G, u); if (!visited[i]) // 没有被访问 { std::cout << G.vertices[i].data << " "; visited[i] = true; } for (ArcNode *p = G.vertices[i].firstarc; p != nullptr; p = p->nextarc) { if (!visited[p->adjvex]) { stk.push(G.vertices[p->adjvex].data); break; } if (p->nextarc == nullptr) stk.pop(); } } std::cout << std::endl; } void DFSTraverse(ALGraph G) { for (int i = 0; i != G.vexnum; ++i) visited[i] = false; for (int i = 0; i != G.vexnum; ++i) { if (!visited[i]) DFS(G, G.vertices[i].data); } } /*-----------------------------------------------------最短路径问题----------------------------------------------------*/ // 求顶点u到其他顶点的最短路径 void BFS_Min_Distance(ALGraph G, VertexType u) { // 辅助队列 std::queue<VertexType> q; // 辅助数组,对应顶点是否已经访问,初始化为false bool visited[G.vexnum]; std::fill(visited, visited + G.vexnum, false); // 顶点u到各个顶点的路径长度数组,初始化为INT_MAX int distance[G.vexnum]; std::fill(distance, distance + G.vexnum, INT_MAX); // 顶点u到自身的距离为0 distance[LocateVex(G, u)] = 0; // 顶点u入队,并标为已访问 q.push(u); visited[LocateVex(G, u)] = true; // BFS算法主过程 while (!q.empty()) { // 得队头元素,并出队 VertexType v = q.front(); q.pop(); for (int w = FirstAdjVex(G, v); w >= 0; w = NextAdjVex(G, v, G.vertices[w].data)) if (!visited[w]) { distance[w] = distance[LocateVex(G, v)] + 1; visited[w] = true; q.push(G.vertices[w].data); } // if } // while // 打印日志 for (int i = 0; i != G.vexnum; ++i) { std::cout << "顶点" << u << "到顶点" << G.vertices[i].data << "的路径长度为:" << distance[i] << std::endl; } } /*--------------------------------------------------------拓扑排序----------------------------------------------------------*/ // 算法实现要引入以下辅助的数据结构 int indegree[MVNum] = {0}; // 存放各顶点的入度 std::stack<VertexType> s; // 暂存所有入度为0的顶点 VertexType topo[MVNum]; // 记录拓扑序列的顶点 // 求出各顶点的入度存入数组indegree中 void FindIndegree(const ALGraph &G, int indegree[]) { for (int i = 0; i != G.vexnum; ++i) { for (ArcNode *p = G.vertices[i].firstarc; p != nullptr; p = p->nextarc) indegree[p->adjvex] = indegree[p->adjvex] + 1; } } bool TopologicalSort(const ALGraph &G) { // 有向图G采用邻接表存储结构 // 若G无回路,则生成G的一个拓扑序列并返回true,否则false FindIndegree(G, indegree); // 遍历indegree组,入度为零的顶点进栈 for (int i = 0; i != G.vexnum; ++i) if (indegree[i] == 0) s.push(G.vertices[i].data); // 输出顶点的计数器初始为0 int count = 0; // 栈不为空时 while (!s.empty()) { // 取得栈顶元素并出栈 VertexType v = s.top(); s.pop(); // 将v保存在拓扑序列数组中 topo[count++] = v; ArcNode *p = G.vertices[LocateVex(G, v)].firstarc; while (p != nullptr) { if (--indegree[p->adjvex] == 0) s.push(G.vertices[p->adjvex].data); p = p->nextarc; } // while } // while if (count != G.vexnum) return false; else return true; } /*-------------------------------------------------------关键路径-----------------------------------------------------------*/ // 算法的实现要引入辅助的数据结构 // 一维数组ve[i]:事件vi的最早发生时间 int ve[MVNum]; // 一维数组vl[i]:事件vi的最迟发生时间 int vl[MVNum]; bool CriticalPath(const ALGraph &G) { // G为邻接表存储的有向网,输出G的各项关键活动 // 调用拓扑排序算法,使拓扑序列保存在topo中,若调用失败,则存在有向环,返回false if (!TopologicalSort(G)) return false; // 给每个事件的最早发生时间置初值0 for (int i = 0; i != G.vexnum; ++i) ve[i] = 0; /*-----------------------按拓扑次序求每个时间的最早发生时间-----------------------------*/ for (int i = 0; i != G.vexnum; ++i) { // 取得拓扑序列中的顶点序号k int k = LocateVex(G, topo[i]); // p 指向k的第一个邻接顶点 ArcNode *p = G.vertices[k].firstarc; while (p != nullptr) { // 依次更新k的所有邻接顶点的最早发生时间 // j为邻接顶点的序号 int j = p->adjvex; if (ve[j] < ve[k]+p->weight) ve[j]=ve[k]+p->weight; p = p->nextarc; // p指向k的下一个邻接顶点 } // while } // for // 给每个事件的最迟发生时间置初值ve[G.vexnum-1] for (int i = 0; i != G.vexnum; ++i) vl[i] = ve[G.vexnum-1]; /*-------------按逆拓扑次序求每个事件的最迟发生时间--------------------------------------------*/ for (int i = G.vexnum-1; i >= 0; --i) { // 取得拓扑序列中的顶点序号k int k = LocateVex(G, topo[i]); ArcNode *p = G.vertices[k].firstarc; while (p != nullptr) { // 根据k的邻接点,更新k的最迟发生时间 // j为邻接顶点的序号 int j = p->adjvex; // 更新顶点k的最迟发生时间vl[k] if (vl[k] > vl[j] - p->weight) vl[k] = vl[j] - p->weight; // p指向k的下一个邻接顶点 p = p->nextarc; } // while } // for /*--------------判断每一活动是否为关键活动---------------------------------------*/ // 每次循环针对vi为活动开始点的所有活动 for (int i = 0; i != G.vexnum; ++i) { // p指向i的第一个邻接顶点 ArcNode *p = G.vertices[i].firstarc; while (p != nullptr) { // j 为i的邻接顶点的序号 int j = p->adjvex; // 计算活动<vi,vj>的最早开始时间 int e = ve[i]; // 计算活动<vi,vj>的最迟开始时间 int l = vl[j] - p->weight; // 若为关键活动,则输出<vi,vj> if (e == l) std::cout << G.vertices[i].data << "->" << G.vertices[j].data << " 为关键活动" << std::endl; p = p->nextarc; } // while } // for return true; }
true
f5a6148d249a5a3a1ff53989837c4e953b5247bf
C++
SuperWhite18/LeetCode-Solution-of-Problems
/LeetCode_April_clock_in/4_23.368.最大整除子集..cpp
UTF-8
1,078
3.25
3
[]
no_license
//题目链接: https://leetcode-cn.com/problems/largest-divisible-subset/ //代码实现: class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { int n = nums.size(); //定义最大的整除子集 vector<int> f(n); sort(nums.begin(),nums.end()); //表示取到最大值的尾节点 int k = 0; //从小到大枚举每一个数 for(int i = 0; i < n; i ++) { f[i] = 1; for(int j = 0; j < i; j ++) { if(nums[i] % nums[j] == 0) f[i] = max(f[i],f[j] + 1); } if(f[k] < f[i]) k = i; } vector<int> res; while(true) { res.push_back(nums[k]); if(f[k] == 1) break; for(int i = 0; i < k; i ++) { if(nums[k] % nums[i] == 0 && f[k] == f[i] + 1) { k = i; break; } } } return res; } };
true
0fd6c856af8391dd36bc7fab47f8fcde70437349
C++
lfahmi-ghb/CPP
/C++ projects/OOP244/OOP244 LAB09/NumbersBox.h
UTF-8
1,838
3.59375
4
[]
no_license
#pragma once #ifndef SDDS_NUMBERSBOX_H #define SDDS_NUMBERSBOX_H #include <iostream> #include<cstring> #include<iomanip> using namespace std; namespace sdds { template<class T> class NumbersBox { //MEMBER FUNCTIONS char name[15]; int size; T* items; public: NumbersBox(int n_size, const char* n_name) { if (n_size > 0 && n_name != nullptr) { strcpy(name, n_name); size = n_size; items = new T[n_size]; } else { *this = NumbersBox(); } } NumbersBox() { name[0] = '\0'; size = 0; items = nullptr; }; ~NumbersBox() { if (items != nullptr) delete[] items; } // OPERATOR # 1 T& operator[](int i) { return items[i]; }; // OPERATOR # 2 NumbersBox<T>& operator*=(const NumbersBox<T>& other) { if (size == other.size) { for (int i = 0; i < size; i++) { items[i] *= other.items[i]; } } return *this; } // OPERATOR # 3 NumbersBox<T>& operator+=(T num) { T* temp = new T[size + 1]; //new temp var temp[size] = num; //assign it if (size > 1 && name != nullptr) { //validate for (int i = 0; i < this->size; i++) { //loop temp[i] = items[i]; } delete[] items; //deallocate items = temp; } size++; //add return *this; } //other member functions //template <class T> ostream& display(ostream& os) const { if ((name == nullptr || name[0] == '\0') || size < 1) { os << "Empty Box\n"; } else { os << "Box name: " << name << '\n'; //os << items[0]; for (int i = 0; i < size; i++) { os << items[i]; if(i + 1 < size) os << ", "; } os << '\n'; } return os; } }; //OUTSIDE FRIEND OPERATOR template <class T> ostream& operator <<(ostream& os, NumbersBox<T>& box) { box.display(os); return os; } } #endif
true
2f45d3d40bb758e109685af22f5caf5c76f9a6f7
C++
mainmmx/cpp.fundamentals
/chapter02/exercise06.cpp
UTF-8
608
3.453125
3
[]
no_license
#include <iostream> using namespace std; const int amountAstronomicalUnitsInOneLightYear = 63240; double LightYears2AstronomicalUnits(double lightYears); int main() { double lightYears = 0.0; double astronomicalUnits = 0.0; cout << "Enter the number of light years: "; cin >> lightYears; astronomicalUnits = LightYears2AstronomicalUnits(lightYears); cout << lightYears << " light years = " << astronomicalUnits << " astronomical units."; cin.get(); cin.get(); return 0; } double LightYears2AstronomicalUnits(double lightYears) { return lightYears * amountAstronomicalUnitsInOneLightYear; }
true
1d020a4da53c77da3187b256bfb7c393ec7f8552
C++
concepcionrey/CppLearning
/LearnCpp/Chapter 6 Arrays, Strings, Pointers, and References/7.cpp
UTF-8
2,234
4.15625
4
[]
no_license
#include <iostream> // Chp 7 // Pointers // a variable is a name for a place in memory that can hold a value // when a program reads that variable, it locates the memory adress and checks // what value is stored in that address int main() { // the "&" address-of operator int x{5}; std::cout << "This is the value: " << x << "\n"; std::cout << "This is the mem_adress: " << &x << '\n'; // the "*" dereference operator std::cout << "This is a sample of using the dereference operator: " << *&x << "\n"; // Pointers: variabls that strictly hold other memory addresses as its value int *ptr{nullptr}; // a null int ptr, ptrs are like other variables and hold garbage when created double *dptr{nullptr}; // a null double ptr int *ptr_0, ptr_1; // watch out, ptr_1 is actually just an int! ptr = &x; // assigning a value to a ptr std::cout << "This line outputs the value of the pointer: " << ptr << '\n'; std::cout << "This line outputs the value of the address that is pointed by the pointer: " << *ptr << '\n'; *ptr = 25; // it is possible to change the value of the original variable through a pointer std::cout << "This is the value of x after using a pointer to change its value: " << x << '\n'; // NOTE: never dereference invalid pointers return 0; } /* ======= Why use Pointers? ========= 1) Arrays are implemented using pointers. Pointers can be used to iterate through an array (as an alternative to array indices) (covered in lesson 6.8). 2) They are the only way you can dynamically allocate memory in C++ (covered in lesson 6.9). This is by far the most common use case for pointers. 3) They can be used to pass a large amount of data to a function in a way that doesn’t involve copying the data, which is inefficient (covered in lesson 7.4) 4) They can be used to pass a function as a parameter to another function (covered in lesson 7.8). 5) They can be used to achieve polymorphism when dealing with inheritance (covered in lesson 12.1). 6) They can be used to have one struct/class point at another struct/class, to form a chain. This is useful in some more advanced data structures, such as linked lists and trees. */ // Quiz // 2) error on line 3, assigning a mem_address to an int variable
true
737d920d8c2d325465192c21af8aa4bfd5cfb467
C++
sturdyplum/lightcppbignum
/bigNum.cpp
UTF-8
8,802
3.4375
3
[]
no_license
#include <iostream> #include <cstring> #include <cstdio> #include <random> #include <time.h> using namespace std; #define maxBigIntLength 300//size of numbers struct bigInt{ int number[maxBigIntLength];//number is stored here backwards bool pos;//pos = true if number is positive //default constructor bigInt() {this->pos = true, memset(this->number, 0, sizeof this->number);} //integer constructor bigInt(int i) { if(i < 0) this->pos = false; else this->pos = true; i = i<0?i*-1:i; memset(this->number, 0, sizeof this->number); int index = 0; while(i != 0) { this->number[index++] = i%10; i/=10; } } //string constructor bigInt(string s) { this->pos= true; int n = s.length(), i = 0; if(s[0] == '-') this->pos = false, i++; memset(this->number, 0, sizeof this->number); for(; i < n; i++) { this->number[i] = s[n-i-1]-'0'; } } //returns true if |this| > |other| bool absGreater(bigInt &other) { int i = maxBigIntLength-1; while(this->number[i] == other.number[i] and i >= 0)i--; if(i < 0) return false; return (this->number[i] > other.number[i]); } //adds a and b assums that they are either both positive or bot negative static bigInt addBig(bigInt &a, bigInt &b) { bigInt c; for(int i = 0; i < maxBigIntLength; i++) { if(i+1 != maxBigIntLength) c.number[i+1] += (a.number[i]+b.number[i]+c.number[i])/10; c.number[i] = (a.number[i]+b.number[i]+c.number[i]) % 10; } return c; } //subtracts b from a assumes that both are positive and that a is greater than b static bigInt subBig(bigInt &a, bigInt &b) { bigInt c; memset(c.number, 0, sizeof c.number); for(int i = 0; i < maxBigIntLength-1; i++) { c.number[i] = a.number[i]-b.number[i]+c.number[i]; if(c.number[i] < 0) c.number[i]+= 10, c.number[i+1]--; } return c; } //handles addition operator bigInt operator+(bigInt& other) { //if both are positive or both are negative then just add and make the sign equal to either if((this->pos && other.pos)||(!this->pos && !other.pos)) { bigInt c = addBig(*this,other); c.pos = other.pos; return c; }//if one is positive and one is negative, subtract the one with the smallest absolute value from the one with the greatest and then make the sign equal to whatever the greatest is else if(this->absGreater(other)) { bigInt c = subBig(*this,other); c.pos = this->pos; return c; } else { bigInt c = subBig(other,*this); c.pos = other.pos; return c; } } bigInt operator-(bigInt& other) { //switch the sign of other then add then switch it back other.pos = !other.pos; bigInt c = *this + other; other.pos = !other.pos; return c; } bigInt operator*(bigInt& other) {//warning do not multiply 2 numbers whos n is > maxBigIntLength/2 or you will get a wrong answer bigInt c; c.pos = (other.pos and this->pos) or (!other.pos and !this->pos); for(int i = 0; i < maxBigIntLength/2; i++) { int carry = 0, digit, j = i; for(; j < maxBigIntLength/2 + i; j++) { digit = c.number[j]+(this->number[i]*other.number[j-i])+carry; carry = digit/10; c.number[j] = digit % 10; } if(carry) { digit = c.number[j] + carry; carry = digit/10; c.number[j] = digit%10; } } return c; } void operator>>(int a) {//left shift a (divide by 10^a) int i; for(i = 0; i < maxBigIntLength - a; i++) { this->number[i] = this->number[i+a]; // cout << number[i]; } for(;i < maxBigIntLength; i++) { this->number[i] = 0; } } bigInt operator/(bigInt &other) {//while i have been able to improve this it now runs in (9n)^2 I might be able to improve this further and make it just n^2 bigInt c; c.pos = (other.pos and this->pos) or (!other.pos and !this->pos); if(other.absGreater(*this)) return c; if(other == *this) { c.number[0] = 1; return c; } bigInt temp = other, temp2 = *this; bigInt zero(0); bigInt ans(0); int t2 = maxBigIntLength-1, t1 = t2; while(this->number[t2] == 0) t2--; while(other.number[t1] == 0) t1--; string x(max(t2-t1,1),'0'); x[0] = '1'; bigInt mul(x); while(mul > zero) { temp = other*mul; while(temp2.absGreater(temp) or temp2 == temp) { temp2 = temp2 - temp; ans = ans + mul; } mul>>1; } return ans; } bool probablePrime(int k) { bigInt one(1),two(2),three(3); bigInt n = *this; if(n == one) return false; if(n == two or n == three) return true; if(n.number[0]%2 == 0) return false; bigInt d=n-one, hold = d; while(d.number[0]%2 == 0) { d = d/two; } for(int i = 0; i < k; i++) { bigInt a = genRand(two,hold); bigInt x = power(a,d,n); if(x == one or x == hold) continue; bool cont = false; while(!(d == hold)) { x = (x*x)%n; d = d * two; if(x == one) return false; if(x == hold) { cont = true; break; } } if(!cont) return false; } return true; } static bigInt genRand(bigInt &low, bigInt &high) { bigInt range = high-low; bigInt temp, val; int index = 0; while((temp < range or temp == range) and index < maxBigIntLength) { int x = rand()%10; temp.number[index] = x; if(temp < range or temp == range) { val.number[index] = temp.number[index]; index++; } } return val + low; } static bigInt power(bigInt &n, bigInt pow, bigInt &mod) { bigInt zero, one(1), two(2); if(pow == zero) return one; if(pow == one) return n; if(pow.number[0] % 2 == 0) { pow = pow/two; bigInt temp = power(n,pow,mod); temp = temp * temp; return temp %mod; } else { bigInt temp = power(n,(pow/two),mod); temp = (temp * temp)%mod; bigInt c = (n * temp)%mod; return c; } } bool operator==(bigInt &other) {//if signs are not equal then return false otherwise step through number array making sure all indicies are equal if(this->pos != other.pos) return false; for(int i = 0; i < maxBigIntLength; i++) { if(this->number[i] != other.number[i]) return false; } return true; } bool operator>(bigInt &other) {//check signs then check right most non equal number in the number array if(this->pos and !other.pos) return true; if(other.pos and !this->pos) return false; if(this->pos and other.pos) return this->absGreater(other); return other.absGreater(*this); } bool operator<(bigInt &other) {//flip and check that also not equal too (could probably speed this up if implemented on its own since you wouldn't have to run equals) if(!(*this == other) and !(*this > other)) return true; return false; } bigInt operator%(bigInt & other) { bigInt divisor = *this/other, temp = divisor*other, ans = *this - temp; return ans; } void print() {//prints out the big int without leading zeros int i = maxBigIntLength-1; if(!this->pos) printf("-"); while(this->number[i] == 0 and i>=0) i--; if(i == -1){ printf("0"); return; } for(;i>=0;i--)printf("%d",this->number[i]); } }; int main() { srand(time(NULL)); for(int i = 1; i < 1000;i++) { bigInt a(i);if(a.probablePrime(10)) cout << i << endl; } return 0; }
true
3f28697e6fc6892416b91f04df023340bdebe17d
C++
checkoutb/LeetCodeCCpp
/ge500/LT0542_01_Matrix.cpp
UTF-8
3,292
3.328125
3
[]
no_license
#include "../header/myheader.h" class LT0542 { public: // int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // queue.add(new int[] {r, c}); // 用Queue保存 点0,循环Queue直到empty,设置4个方向的距离,如果其他点被影响到了,就加入Queue, //Runtime: 172 ms, faster than 98.67% of C++ online submissions for 01 Matrix. //Memory Usage: 20.7 MB, less than 100.00% of C++ online submissions for 01 Matrix. vector<vector<int>> lt0542b(vector<vector<int>>& matrix) { for (auto& p : matrix) { for (int& a : p) { if (a != 0) { a = matrix.size() + matrix[0].size(); } } } for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[0].size(); j++) { if (i + 1 < matrix.size() && matrix[i + 1][j] != 0) { matrix[i + 1][j] = min(matrix[i + 1][j], matrix[i][j] + 1); // [0][0] + 1 <= INT_MAX, 所以不能用INT_MAX 初始化。 } if (j + 1 < matrix[0].size() && matrix[i][j + 1] != 0) { matrix[i][j + 1] = min(matrix[i][j + 1], matrix[i][j] + 1); } } } for (int i = matrix.size() - 1; i >= 0; i--) { for (int j = matrix[0].size() - 1; j >= 0; j--) { if (i > 0 && matrix[i -1][j] != 0) { matrix[i - 1][j] = min(matrix[i - 1][j], matrix[i][j] + 1); } if (j > 0 && matrix[i][j - 1] != 0) { matrix[i][j - 1] = min(matrix[i][j - 1], matrix[i][j] + 1); } } } return matrix; } // 19 / 48 . tle vector<vector<int>> lt0542a(vector<vector<int>>& matrix) { for (auto& p : matrix) // &, & { for (int& a : p) { if (a != 0) { a = INT_MAX; } } } for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[0].size(); j++) { if (matrix[i][j] == 0) { dfsa1(matrix, i + 1, j, 1); dfsa1(matrix, i, j + 1, 1); dfsa1(matrix, i - 1, j, 1); dfsa1(matrix, i, j - 1, 1); } } } return matrix; } void dfsa1(vector<vector<int>>& m, int i, int j, int v) { if (i < 0 || i >= m.size() || j < 0 || j >= m[0].size()) return; if (v > m[i][j]) return; if (m[i][j] == 0) return; m[i][j] = v; dfsa1(m, i + 1, j, v + 1); dfsa1(m, i, j + 1, v + 1); dfsa1(m, i - 1, j, v + 1); dfsa1(m, i, j - 1, v + 1); } }; int main() { vector<vector<int>> vv = {{0,0,0},{0,1,0},{1,1,1}}; LT0542 lt; lt.lt0542b(vv); for (auto p : vv) { for (int i : p) { cout<<i<<", "; } cout<<endl; } return 0; }
true
8a9dfbef2cc0483a2e946e77eb55e7b1ea368bec
C++
hoon4233/Algo-study
/2020_spring/2020_04_02/1051_JJ.cpp
UTF-8
735
2.71875
3
[]
no_license
#include <cstdio> #include <iostream> using namespace std; int table[51][51]; int n,m; int ans = 1; bool is_in(int x, int y) { return (0<x && x<=n)&&(0<y && y<=m); } int main() { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) scanf("%1d",&table[i][j]); } //size for(int i=1;i<=min(n,m);i++) { for(int j=1;j<=n;j++) { for(int k=1;k<=m;k++) { if(is_in(j+i,k+i)) { if( (table[j][k]==table[j+i][k])&&(table[j][k+i]==table[j+i][k+i])&& (table[j][k+i]==table[j+i][k])) ans=max(ans,(i+1)*(i+1)); } } } } printf("%d\n",ans); return 0; }
true
3e9d93a903fcf830da544c6a1ae46290ac09a719
C++
MaxStubbe/Linal2020
/LinearAlga_opdr1/Vector3D.h
UTF-8
1,349
3.28125
3
[]
no_license
#ifndef __Vector3D_h__ #define __Vector3D_h__ #include <cmath> #include <SDL.h> #include <SDL_main.h> #include "Matrix.h" class Vector3D { public: float x; float y; float z; const int WINDOWWIDTH = 640; const int WINDOWHEIGHT = 480; Vector3D() { this->x = 0; this->y = 0; this->z = 0; }; Vector3D(float x1, float y1, float z1 = 1) { this->x = x1; this->y = y1; this->z = z1; }; Vector3D operator+(const Vector3D& other) { Vector3D vec; vec.x = x + other.x; vec.y = y + other.y; vec.z = z + other.z; return vec; }; Vector3D operator-(const Vector3D& other) { Vector3D vec; vec.x = x - other.x; vec.y = y - other.y; vec.z = z - other.z; return vec; }; Vector3D operator*(const float scalair) { Vector3D vec; vec.x = x * scalair; vec.y = y * scalair; vec.z = z * scalair; return vec; }; Vector3D operator*(const Matrix& other) { float newX; float newY; float newZ; if (other.collumns >= 2) { newX = ((other.x[0] * x) + (other.x[1] * y)); newY = ((other.y[0] * x) + (other.y[1] * y)); newZ = ((other.z[0] * x) + (other.z[1] * y)); if (other.collumns > 3) { newX += (x * other.x[2]); newY += (y * other.y[2]); newZ += (z * other.z[2]); } return Vector3D(newX, newY, newZ); } else { throw "Matrix and Vector can't multiply"; } }; }; #endif
true
534f34bab38dd5413b4290b527b8d99c4b5a8379
C++
MartienLagerweij/paper_sources
/pubsub/src/pub.cpp
UTF-8
2,588
2.765625
3
[]
no_license
// for ROS nodes basic needs #include <ros/ros.h> // for reading the vmem size from /proc/self/status #include <fstream> #include <string> #include <sstream> // the custom-made latency test message #include "pubsub/latency_test_message.h" int main(int argc, char **argv) { float publish_rate = 1; float shutdown_after_sending = 10; float message_payload_size = 0; long int sent_count = 0; char* message_string; ros::init(argc, argv, "talker"); ros::NodeHandle nh; pubsub::latency_test_message msg; ros::Publisher chatter_pub = nh.advertise<pubsub::latency_test_message>("chatter", 1000); ros::param::get("~/publish_rate", publish_rate); ros::param::get("~/shutdown_after_sending", shutdown_after_sending); ros::param::get("~/message_payload_size", message_payload_size); if (message_payload_size > 0) { message_string = (char *)malloc((size_t)message_payload_size); for (long int i=0; i < message_payload_size; i++) { message_string[i] = i%10 + '0'; } msg.payload.append(message_string); free(message_string); } ros::Rate loop_rate((double)publish_rate); ROS_INFO("Publisher ('talker') loop starts now with publish rate %ld", (long int)publish_rate); ROS_INFO("Publisher ('talker') will shutdown after publishing %ld messages", (long int)shutdown_after_sending); ROS_INFO("Publisher ('talker') will publish messages with a size of %ld bytes", (long int)message_payload_size); while (ros::ok() && sent_count < (long int)shutdown_after_sending) { msg.header.seq = sent_count; // begin vmem size code // source copied from MIRA benchmark and adapted for re-use here std::ifstream statStream("/proc/self/status", std::ios_base::in); std::string line; bool vmem_found = false; while(!std::getline(statStream, line).eof() && !vmem_found) { // format of line we are looking for: // VmSize: 28812 kB if (line.find("VmSize") != std::string::npos) { vmem_found = true; sscanf(line.c_str(),"VmSize:%ld kB", &(msg.virtual_memory_size)); // important note: a throttled console message uses quite some extra cpu power, so // be aware of that when you turn debug on using e.g. rqt_logger_level ROS_DEBUG_THROTTLE(1.0,">>>> sscanf of line %s gives pub virtual_memory_size %ld", line.c_str(), msg.virtual_memory_size); } } // end vmem size code ros::WallTime wallTime = ros::WallTime::now(); msg.header.stamp.sec = wallTime.sec; msg.header.stamp.nsec = wallTime.nsec; chatter_pub.publish(msg); sent_count++; loop_rate.sleep(); } ros::shutdown(); return 0; } //main
true
495259471f3843cb32561416a11e17a8102d27e6
C++
Lukkario/pp2_zadania
/zad4.cpp
UTF-8
1,251
3.359375
3
[]
no_license
#include <iostream> #include <algorithm> #include <ctime> #include <cstdlib> using namespace std; void wypelnij(int *tab, int a, int b, int wielkosc) { for(int i = 0; i < wielkosc; i++) *(tab+i) = rand() % b + a; } void wypisz(int *tab, int wielkosc) { for(int i = 0; i < wielkosc; i++) cout << *(tab+i) << " "; } int main() { srand(time(NULL)); int wielkosc; int srodek, koniec; int a , b; cout << "Podaj wielkosc tablicy: "; cin >> wielkosc; while(cin.fail() == 1) { cin.clear(); cin.ignore(1024, '\n'); cout << "Podaj wielkosc tablicy: "; cin >> wielkosc; } if(wielkosc % 2 == 0) { cout << "Nie mozna wyznaczyc srodka"; return 1; } cout << "Podaj poczatek przedzialu: "; cin >> a; cout << "Podaj koniec przedzialu: "; cin >> b; int * tab = new int[wielkosc]; wypelnij(tab, a, b, wielkosc); //cout << *(tab+0) << " " << *(tab+1) << " " << *(tab+2) << " " << *(tab+wielkosc-1) << endl; wypisz(tab, wielkosc); srodek = wielkosc/2; koniec = wielkosc-1; int pomoc; for(int i = 0; i < srodek; i++, koniec--) { //pomoc = *(tab+i); //*(tab+i) = *(tab+wielkosc-i); //*(tab+wielkosc-i) = pomoc; swap(*(tab+i), *(tab+koniec)); } cout << endl; wypisz(tab, wielkosc); delete [] tab; return 0; }
true
7a7f13639ac0f0b318b0e543cb798aab0b9a6031
C++
HekpoMaH/Olimpiads
/Shumen AiB/more2013/Untitled Folder/ru-olymp-roi-2010-tests/1-gift/gift_sk_2.cpp
UTF-8
864
2.6875
3
[]
no_license
#include <cmath> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; typedef long long ll; int main() { freopen("gift.in", "r", stdin); freopen("gift.out", "w", stdout); ll n; cin >> n, n /= 2; ll a = (ll)(sqrt(n / 3) + 1e-6), b = a; ll res = a * a * a; ll ra = a, rb = a, rc = a; while (a > 0) { // 2ab + b^2 == n // ab^2 --> max (let b^2 == n) while (2 * a * b + b * b < n) b++; if (a * b * b <= res) break; for (ll b = a; a * b <= n; b++) { ll c = (n - a * b) / (a + b); if (c < b) // a <= b <= c break; ll tmp = (ll)a * b * c; if (tmp > res) res = tmp, ra = a, rb = b, rc = c; } a--; } cout << res << endl; cout << ra << " " << rb << " " << rc << endl; return 0; }
true
87a1f755bb3cddadf5536ec01d06d411ff2b41a7
C++
jfrascon/MANFRED_ROS_STACK
/openmrl/firmware/skybot_IRSensors/skybot_IRSensors.ino
UTF-8
2,216
2.609375
3
[]
no_license
char incomingByte; int a = 2; // LSB multiplexer int b = 3; // int c = 4; // MSB multiplexer int readPin; // Select the output channel float sensorValue = 0; // variable to store the value coming from the sensor void sendIRdata(int number, boolean A, boolean B, boolean C, int AN, float alpha, float beta, float x, float y, float theta, int minimum, int maximum, int fov){ digitalWrite(a, A); digitalWrite(b, B); digitalWrite(c, C); sensorValue = analogRead(AN); sensorValue = sensorValue*5000/1024; sensorValue = alpha*pow(sensorValue,-beta); Serial.print("IR_L"); Serial.print(number); Serial.print("\t"); Serial.print(sensorValue); Serial.print("\t"); Serial.print(x); Serial.print("\t"); Serial.print(y); Serial.print("\t"); Serial.print(theta); Serial.print("\t"); Serial.print(minimum); Serial.print("\t"); Serial.print(maximum); Serial.print("\t"); Serial.println(fov); } void setup() { Serial.begin(57600); // opens serial port, sets data rate to 9600 bps //Serial.println("Hi there! I'm Arduino"); pinMode(a, OUTPUT); pinMode(b, OUTPUT); pinMode(c, OUTPUT); Serial.println("Hello"); } void loop() { if (Serial.available() > 0) { // read the incoming byte: incomingByte = Serial.read(); switch (incomingByte){ case 'i': // Send robot information to the computer { Serial.println("MiniSkybot"); break; } // void sendIRdata(int number, boolean A, boolean B, boolean C, int AN, float alpha, float beta, float x, float y, float theta, int minimum, int maximum, int fov){ // IR_L0 0.18 75.00 0.00 0.00 100 800 8 case 'm': // Send measure of the selected sensor to the computer { sendIRdata(0, 0, 1, 1, A0, 350.8, 1.036,75, 0, 0, 100, 800, 8); sendIRdata(1, 0, 1, 1, A1, 350.8, 1.036,75, 0, 0, 100, 800, 8); sendIRdata(2, 0, 1, 1, A1, 350.8, 1.036,75, 0, 0, 100, 800, 8); sendIRdata(3, 0, 1, 1, A1, 350.8, 1.036,75, 0, 0, 100, 800, 8); sendIRdata(4, 0, 1, 1, A1, 350.8, 1.036,75, 0, 0, 100, 800, 8); sendIRdata(5, 1, 0, 1, A0, 350.8, 1.036,75, 0, 0, 100, 800, 8); Serial.println(); } } } }
true
abcbb93cdc538061b839c251395077f9b11d8cb6
C++
rupeshsjce/C-
/Student.cpp
UTF-8
490
3.28125
3
[]
no_license
#include "Student.h" #include <iostream> using namespace std; //Student CLASS DEFINITION Student::Student(string nm, string yr, float g) //constructor :name(nm), year(yr), gpa(g) //initialization list { } void Student::boost_grade() { gpa+=1.0; if(gpa > 4.0) gpa=4.0; } void Student::display() { cout << "Studentt Record" << endl; cout << "--------------" << endl; cout << "Name: " << name << endl; cout << "Academic Level: " << year << endl; cout << "GPA : " << gpa << endl; }
true
5f4800a3f3f9b4a90c8ee894021167c2b447e61f
C++
bdliyq/algorithm
/misc/google/combine-intervals.cc
UTF-8
649
3.46875
3
[]
no_license
// Question: Combine intervals. struct Interval { int start; int end; Interval(int s, int e) : start(s), end(e) {} }; struct cmp { bool operator() (Interval& i1, Interval& i2) { return (i1.start < i2.start); } }; vector<Interval> solve(vector<Interval> intervals) { vector<Interval> ans; if (intervals.empty()) { return ans; } sort(intervals.begin(), intervals.end()); for (auto i : intervals) { if (ans.empty() || ans.back().end < i.start) { ans.push_back(i); } else { ans.back().end = max(ans.back().end, i.end); } } return ans; }
true
2133948f507b3740117287c777313dedc60f752e
C++
portaloffreedom/tol-controllers
/shared/include/CppnGenome.h
UTF-8
4,046
3.109375
3
[]
no_license
#ifndef OM_CPPNGENOME_H_ #define OM_CPPNGENOME_H_ #include "Defines.h" #include "ParametersReader.h" #include "NEAT.h" #include <iostream> #include <random> class CppnGenome { double size; //The size of the grid that should be used when translating this genome boost::shared_ptr<NEAT::GeneticIndividual> cppn; //Pointer to a Cppn public: /** * Constructs a random, minimal genome with a grid size of size. * The minimal genome will contain one output node, two input nodes * and a bias node. The network will be fully connected and all * nodes, except the bias node, will have a random activation function. * * @param size The grid size of this genome. */ CppnGenome(int size); /** * Constructs a copy of genome1. * The genome will not be mutated. * * @param genome1 The genome to be copied. */ CppnGenome(const CppnGenome& genome1); /** * Constructs the genome described by stream. * This constructor is able to process streams based on the output of the toString() function, * creating the exact same genome that returned the string. * * @param stream Stream containing the description of a CppnGenome. */ CppnGenome(std::istream& stream); /** * Destroys the CppnGenome. * Does not actually perform any additional clean-up. */ virtual ~CppnGenome(); /** * Returns a string of this genome that contains enough information to create * an exact copy of this genome. * Used in combination with the stream based constructor to write the genome to file, * and then reconstruct for detailed analysis. * Useful for debugging, logging or saving genomes for later use. * * @return Returns a string containing all information to reconstruct the genome. */ string toString() const; /** * Mutates this genome. * Mutation of the cppn depends on the NEAT global settings. * Mutation of size happens with a chance of SIZE_MUTATION_RATE * by adding a random number drawn from a normal distribution with a mean of zero * and a standard deviation of SIZE_MUTATION_STRENGTH */ void mutate(); /** * Combines this genome with the input genome and then mutates this genome. * Crossover and mutation of the cppn depends on the NEAT global settings. * Crossover of size happens by taking the average of both parents, * rounding up or down 50% of the time. * Mutation of size happens with a chance of SIZE_MUTATION_RATE * by adding a random number drawn from a normal distribution with a mean of zero * and a standard deviation of SIZE_MUTATION_STRENGTH * * @param genome The genome to use in the crossover. */ void crossoverAndMutate(const CppnGenome& genome); /** * Returns a pointer to the cppn used by the Activation Value Matrix. * * @return Returns a shared pointer to the cppn that is used to get the values of the Activation Value Matrix */ boost::shared_ptr<NEAT::GeneticIndividual> getCppn() const; /** * Returns the size of the Activation Value Matrix, * where the size is the width and height of the, always square, matrix. * * @return Returns the size of the Activation Value Matrix. */ double getSize() const; private: double SIZE_MUTATION_RATE = ParametersReader::get<double>("SIZE_MUTATION_RATE"); double SIZE_MUTATION_STRENGTH = ParametersReader::get<double>("SIZE_MUTATION_STRENGTH"); int CPPN_GRID_MINIMUM_SIZE = ParametersReader::get<int>("CPPN_GRID_MINIMUM_SIZE"); /** * Mutates the size gene of this genome. * Mutation of size happens with a chance of SIZE_MUTATION_RATE * by adding a random number drawn from a normal distribution with a mean of zero * and a standard deviation of SIZE_MUTATION_STRENGTH */ void mutateSize(); }; #endif /* OM_CPPNGENOME_H_ */
true
b9e769e7b8c39c7f997f7214b93fcc604666a805
C++
alo456/Arduino
/ej9-dado/ej9-dado.ino
UTF-8
1,302
2.84375
3
[]
no_license
int ledPins[7] = {2, 3, 4, 5, 6, 7, 8}; int dicePatterns[7][7] = { {0, 0, 0, 0, 0, 1, 1}, // 1 {0, 0, 1, 1, 0, 1, 0}, // 2 {0, 0, 1, 1, 0, 1, 1}, // 3 {1, 0, 1, 1, 0, 0, 0}, // 4 {1, 0, 1, 1, 0, 0, 1}, // 5 {1, 1, 1, 1, 1, 0, 0}, // 6 {0, 0, 0, 0, 0, 1, 0} // BLANK }; //logica al revés en el pin 7 porque el led está raro int switchPin = 9; int blank = 6; void setup(){ for (int i = 0; i < 7; i++){ pinMode(ledPins[i], OUTPUT); digitalWrite(ledPins[i], LOW); } randomSeed(analogRead(0)); } void loop(){ /*for(int i=0;i<7;i++){ show(i); delay(5000); apagaTodo(); }*/ if (digitalRead(switchPin)){ rollTheDice(); delay(100); } } void rollTheDice(){ int result = 0; int lengthOfRoll = random(15, 25); for (int i = 0; i < lengthOfRoll; i++){ result = random(0, 6); // result will be 0 to 5 not 1 to 6 show(result); delay(50 + i * 10); } for (int j = 0; j < 3; j++){ show(blank); delay(500); show(result); delay(500); } } void show(int result){ for (int i = 0; i < 7; i++){ if(dicePatterns[result][i] == 1) digitalWrite(ledPins[i],HIGH); else digitalWrite(ledPins[i],LOW); //digitalWrite(ledPins[i], dicePatterns[result][i]); } } void apagaTodo(){ for(int i=0;i<7;i++){ digitalWrite(ledPins[i],LOW); } delay(1000); }
true
61b884372910e6c5205c00e77cf23c27340ee614
C++
Hotckiss/cpp_labs
/lab7/src/my_vector.cpp
UTF-8
2,198
3.171875
3
[]
no_license
#include "../include/my_vector.h" #include <cassert> #include <cstdlib> #include <string.h> #include <algorithm> #include <iostream> #include <cstdio> MyVector::MyVector() { _data = (MySuperPuperVectorType *)malloc(sizeof(MySuperPuperVectorType) * 2); _sz = 0; _cp = 2; } MyVector::MyVector(std::size_t init_capacity) { _cp = init_capacity; _sz = 0; _data = (MySuperPuperVectorType *)malloc(sizeof(MySuperPuperVectorType) * init_capacity); } MyVector::~MyVector() { free(_data); } void MyVector::set(std::size_t index, MySuperPuperVectorType value) { assert(0 <= index && index < _sz); _data[index] = value; } MySuperPuperVectorType MyVector::get(std::size_t index) { assert(0 <= index && index < _sz); return _data[index]; } std::size_t MyVector::size() { return _sz; } std::size_t MyVector::capacity() { return _cp; } void MyVector::reserve(std::size_t new_capacity) { if (_cp < new_capacity) { _data = (MySuperPuperVectorType *)realloc(_data, new_capacity * sizeof(MySuperPuperVectorType)); _cp = new_capacity; } } void MyVector::resize(std::size_t new_size) { if (_cp < new_size) { while (_cp < new_size) _cp *= 2; _data = (MySuperPuperVectorType *)realloc(_data, _cp * sizeof(MySuperPuperVectorType)); } for (size_t i = _sz; i < new_size; i++) _data[i] = 0; _sz = new_size; } void MyVector::push_back(MySuperPuperVectorType value) { if (_sz == _cp) { _data = (MySuperPuperVectorType *)realloc(_data, 2 * _cp * sizeof(MySuperPuperVectorType)); _cp *= 2; } _data[_sz] = value; _sz++; } void MyVector::insert(std::size_t index, MySuperPuperVectorType value) { assert(0 <= index && index <= _sz); if (_sz == _cp) { _data = (MySuperPuperVectorType *)realloc(_data, 2 * _cp * sizeof(MySuperPuperVectorType)); _cp *= 2; } _sz++; for (size_t i = _sz - 1; i > index; i--) _data[i] = _data[i - 1]; _data[index] = value; } void MyVector::erase(std::size_t index) { assert(0 <= index && index < _sz); for (size_t i = index; i < _sz - 1; i++) _data[i] = _data[i + 1]; _sz--; }
true
36817cfef42a5510f27a335d985b79ad954a8c0e
C++
hafnerfe/Choice-Dictionaries
/src/Profiling/Utilities/Rf_formatter.cpp
UTF-8
1,239
3.046875
3
[]
no_license
/* * * * Created by Felix Hafner, 24.06.18 */ #include "Rf_formatter.h" #include <fstream> #include <cmath> #include <numeric> #include <cassert> double compute_mean(const std::vector<double>& v) { double sum = std::accumulate(v.begin(), v.end(), 0.0); return sum / v.size(); } double compute_stdev(const std::vector<double>& v) { double mean = compute_mean(v); double sq_sum = std::inner_product( v.begin(), v.end(), v.begin(), 0.0); return std::sqrt(sq_sum / v.size() - mean * mean); } double compute_min(const std::vector<double>& v) { return *min_element(v.begin(), v.end()); } double compute_max(const std::vector<double>& v) { return *max_element(v.begin(), v.end()); } void write_statistics( const std::vector<std::string>& names, const std::vector<std::vector<double> >& results, std::ostream& os) { assert(names.size() == results.size()); for (unsigned int i = 0; i < names.size(); ++i) { auto name = names[i]; auto result = results[i]; os << "Name: " << names[i] << '\n'; os << "mean: " << compute_mean(result) << '\n'; os << "stdev: " << compute_stdev(result) << '\n'; os << "min: " << compute_min(result) << '\n'; os << "max: " << compute_max(result) << '\n'; os << "---" << "\n\n"; } }
true
358fb63edd194d2faff1ef51c73d5c1df0802abb
C++
BastienPateyron/Cpp_ISIMA2
/gangster/tests.cpp
UTF-8
4,895
3.109375
3
[]
no_license
#include "catch.hpp" #include "gangster.hpp" #include <stdexcept> #include <sstream> #include <cstring> /* TEST_CASE("Personne1") { const char * nom = "corleone"; Personne zz(nom); REQUIRE(nom == zz.getNom()); zz.setNom("vito"); REQUIRE("vito" == zz.getNom()); } */ /* TEST_CASE("Personne2") { const char * nom = "frank"; const Personne zz(nom); REQUIRE(nom == zz.getNom()); } */ /* TEST_CASE("Personne3") { REQUIRE("INCONNU" == INCONNU.getNom()); }*/ /* TEST_CASE("Gangster") { const Gangster parrain; Gangster accolyte1; const Gangster accolyte2; CHECK (1 == parrain.getId()); CHECK (1 == parrain.getInfluence()); CHECK (parrain.getId() +1 == accolyte1.getId()); CHECK (1 == accolyte1.getInfluence()); CHECK (accolyte1.getId()+1 == accolyte2.getId()); CHECK (1 == accolyte2.getInfluence()); } */ /* TEST_CASE("Chef") { Gangster soldat1; Chef lieutenant; Gangster soldat2; CHECK( 1 == lieutenant.getInfluence()); CHECK( soldat1.getId()+1 == lieutenant.getId()); CHECK(lieutenant.getId()+1 == soldat2.getId()); lieutenant.commande(&soldat1); CHECK( 11 == lieutenant.getInfluence()); lieutenant.commande(&soldat2); CHECK( 12 == lieutenant.getInfluence()); Chef boss; CHECK( 1 == boss.getInfluence()); CHECK(soldat2.getId()+1 == boss.getId()); boss.commande(&lieutenant); CHECK( 22 == boss.getInfluence()); } */ /* TEST_CASE("Inconnu") { InconnuException inconnu; CHECK( strcmp(inconnu.what(), "personnalite inconnue")==0); }*/ /* TEST_CASE("Exception") { Gangster inconnu; REQUIRE_THROWS_AS(inconnu.getPersonne(), InconnuException); } */ /* TEST_CASE("Revelation") { Gangster parrain; const Personne vito("Vito Corleone"); CHECK(! vito.equals(Personne("loic"))); parrain.setPersonne(vito); CHECK(parrain.getPersonne().equals(Personne("Vito Corleone"))); } */ /* TEST_CASE("Comparaison") { Gangster g1; Gangster g2; Chef c; // gangster de meme influence => "age" qui compte CHECK( g2 < g1 ); CHECK( c < g1 ); c.commande(&g2); // gangster de plus d'influence CHECK( g1 < c ); CHECK( g2 < c ); } */ /* void creerFamille(Famille & famille, Gangster*hommes[]) { for (int i = 0; i < 10; ++i) { hommes[i] = new Gangster(); famille.ajouter(hommes[i]); } for (int i = 10; i < 13; ++i) { hommes[i] = new Chef(); famille.ajouter(hommes[i]); } for (int i = 0; i < 5; ++i) { ((Chef*)hommes[10])->commande(hommes[2*i]); ((Chef*)hommes[11])->commande(hommes[2*i+1]); } ((Chef*)hommes[12])->commande(hommes[10]); ((Chef*)hommes[12])->commande(hommes[11]); } */ /* TEST_CASE("Famille1A") { Famille famille; std::stringstream ss; Gangster * hommes[13]; creerFamille(famille, hommes); const char * tableau[13] = {"Tony", "Clemenza", "Peter", "Kay", "Lucas", "Salvatore", "Virgil", "Carlo", "Jack", "Moe", "Tom Hagen", "Santino Corleone", "Vito" }; for(int i =0; i<13; ++i) if (i%4) { hommes[i]->setPersonne(Personne(tableau[i])); // std::cout << hommes[i]->getPersonne().getNom() << std::endl; } //famille.listePersonnes(std::cout); famille.listePersonnes(ss); std::stringstream attendu; attendu << "Carlo, Clemenza, Kay, Moe, Peter, Salvatore, Santino Corleone, Tom Hagen, Virgil"; CHECK(attendu.str() == ss.str()); } */ /* TEST_CASE("Famille1B") { Famille famille; std::stringstream ss; Gangster * hommes[13]; creerFamille(famille, hommes); const char * tableau[13] = {"Tony", "Clemenza", "Peter", "Kay", "Lucas", "Salvatore", "Virgil", "Carlo", "Jack", "Moe", "Tom Hagen", "Santino Corleone", "Vito" }; for(int i =0; i<13; ++i) if (i%4) { hommes[i]->setPersonne(Personne(tableau[i])); } ss << famille; std::stringstream attendu; attendu << "Carlo, Clemenza, Kay, Moe, Peter, Salvatore, Santino Corleone, Tom Hagen, Virgil"; CHECK(attendu.str() == ss.str()); } */ /* TEST_CASE("Foncteur") { Gangster g1; Gangster g2; Chef c; c.commande(&g1); FoncteurInf foncteur; CHECK(foncteur(&g2, &g1)); CHECK(foncteur(&g1, &c )); } */ /* TEST_CASE("Famille2") { Famille famille; std::stringstream ss; Gangster * hommes[13]; creerFamille(famille, hommes); // std::cout << std::endl; // for(Gangster * homme : hommes) // std::cout << homme->getId() << "/" << homme->getInfluence() << " "; // std::cout << std::endl; // famille.listeMembres(std::cout); famille.listeMembres(ss); std::stringstream attendu; attendu << hommes[12]->getId() << " "; attendu << hommes[10]->getId() << " "; attendu << hommes[11]->getId(); for(int i =0; i<10; ++i) attendu << " " << hommes[i]->getId(); CHECK(attendu.str() == ss.str()); } */ // ET VALGRIND ????
true
303ca6c3b5787369afe1580cff05a48f900e4688
C++
Zhenghao-Liu/LeetCode_problem-and-solution
/0076(重要).最小覆盖子串/solution_sliding_window.cpp
UTF-8
1,323
2.96875
3
[]
no_license
class Solution { public: string minWindow(string s, string t) { int s_size=s.size(),t_size=t.size(); if (s_size==0 || t_size==0 || t_size>s_size) return ""; unordered_map<char,int> t_number_of_letters; for (char i:t) ++t_number_of_letters[i]; int left=0,right=-1; unordered_map<char,int> window_number_of_letters; int judge_stop_increasing_left=0,judge_stop_increasing_right=0; int minimum=INT_MAX,low; while (right<s_size) { while(right<s_size) { judge_stop_increasing_right=1; for (auto i:t_number_of_letters) if (i.second>window_number_of_letters[i.first]) { ++right; judge_stop_increasing_right=0; break; } if(judge_stop_increasing_right==1) break; else if (right<s_size) ++window_number_of_letters[s.at(right)]; } while(left<s_size) { --window_number_of_letters[s.at(left)]; ++left; for (auto i:t_number_of_letters) if (i.second>window_number_of_letters[i.first]) { judge_stop_increasing_left=1; break; } if (judge_stop_increasing_left==1) { judge_stop_increasing_left=0; break; } } if (right-left+2<minimum && right<s_size) { low=left-1; minimum=right-left+2; } } return (minimum==INT_MAX) ? "" : s.substr(low,minimum); } };
true
cad8228f3575bd9007af55d2981532229baa61be
C++
Valeryn4/StaticECS
/example/Example.cpp
UTF-8
4,217
2.84375
3
[]
no_license
#include "include/ECS/ECS.hpp" #include <string> #include <iostream> #include <chrono> #include <thread> //Данные для компонента-слушателя struct ListenerTargetData { std::string name = "Target_0"; int i = 0; void Set(int v) { i = v; printf("Listener %s i set to %i\n", name.c_str(), i); } }; //данные для компонента слушателя бродкастов struct ListenerBrodcastData { std::string name = "Brodcast"; int i = 0; void Set(int v) { i = v; printf("ListenerBrodcast %s i set to %i\n", name.c_str(), i); } }; //Компонент слушателя одиночки using ListenerTargetComp = StaticECS::Component<ListenerTargetData>; //компонент слушателя бродкастов using ListenerBrodcastComp = StaticECS::Component< ListenerBrodcastData>; //компонент event using EventComponent = StaticECS::EventComponent; //сущность генерирующая события и слушатель одиночка using Entity = StaticECS::EntityComp< EventComponent, ListenerTargetComp>; //сущность слушатель бродкастов и слушатель одиночка (ВНИМАНИЕ! МЫ СПЕЦИАЛЬНО ДОБАВИЛИ СЮДА СЛУШАТЕЛЯ-ОДИНОЧКУ! ДЛЯ ДЕМОНСТРАЦИИ) using Entity2 = StaticECS::EntityComp<ListenerBrodcastComp, ListenerTargetComp>; int main() { //создаем сущность, которая будет генерировать события Entity entity; //создаем систему StaticECS::SystemEvent system_; //получаем указатели на компоненты бродкастера auto listener = entity.GetComponentPtr<ListenerTargetComp>(); auto event = entity.GetComponentPtr<EventComponent>(); //компонент event, в который мы будем посылать кобытия //создаем 10 сущностей, которые будут ловить бродкасты, посылаемые в ListenerBrodcastComp for (int i = 0; i < 10; ++i) { auto e = new Entity2(); e->GetComponent<ListenerBrodcastComp>().name = "Brodcast_" + std::to_string(i); } //Пусть это будет у наж GameLoop std::thread thread([listener, event, &system_]() { for (int i = 0; i < 10; ++i) { auto parent = event->GetParent(); //отправляем три события в целевой компонент самому себе. Ключ является parent! for (int z = 0; z < 3; ++z) { event->PushEvent([parent]() { //так мы получаем компонент-слушатель, который принадлежит той же сущности, что и создает ивент //если такого компонента нет - получим nullptr auto comp = ListenerTargetComp::Pool::Instance().GetComponent(parent); if (comp) { comp->Set(comp->i + 1); } }); } //отправляем событие-бродкаст, которео отправиться всем компонентам ListenerBrodcastComp event->PushEvent([]() { auto& pool = ListenerBrodcastComp::Pool::Instance().GetPool(); //обратиет внимание! Что порядок перебора зависит от реализации std::unorder_map for (auto &&v : pool) { v.second->Set(v.second->i + 1); } }); printf("\nUpdate all events!\n"); system_.Update(1); using namespace std::chrono_literals; std::this_thread::sleep_for(1s); } }); thread.join(); system("pause"); }
true
8fbdb80f55390bd7554dc3753b9fc332530f0674
C++
softwareschneiderei/viewer
/camera_module/epics/Channel.h
UTF-8
677
2.5625
3
[]
no_license
#pragma once #include <cadef.h> #include <string> class Channel { public: Channel(std::string const& name, capri priority=0); Channel(Channel const&) = delete; ~Channel(); Channel& operator=(Channel const&) = delete; channel_state state() const; void array_get(chtype type, unsigned long count, void* pValue); void put(chtype type, void* value); void get(chtype type, void* value); template <class T> T get() { T value; get(value); return value; } void get(int& value); void put(int value); bool is_connected() const; static void wait(double time); private: chid mHandle; };
true
9a26e8518bbd673d215563497e1b53777a04d213
C++
Maheshmahi7/Hangman
/Test/Test.cpp
UTF-8
12,834
2.609375
3
[]
no_license
#include <iostream> #include <string> #include "Coder.h" #include "Category.h" #include "Words.h" #include "Difficulty.h" #include "DatabaseXmlParser.h" #include "DatabaseInterface.h" #include "DatabaseImplementation.h" using namespace std; void test_coder(); void test_category(); void test_difficulty(); void test_words(); void test_xml_parser_get_category_from_xml(); void test_xml_parser_get_diffiulty_from_xml(); void test_xml_parser_get_word_from_xml(); void test_get_category(); void test_get_difficulty(); void test_get_word(); void test_update_game_details(); void test_get_maximum_game_id(); void test_insert_into_game_details(); void test_load_data(); void main() { test_load_data(); test_coder(); test_category(); test_difficulty(); test_words(); test_xml_parser_get_category_from_xml(); test_xml_parser_get_diffiulty_from_xml(); test_xml_parser_get_word_from_xml(); test_get_word(); test_insert_into_game_details(); test_update_game_details(); test_get_maximum_game_id(); cin.get(); cin.ignore(1000, '\n'); } void test_coder(){ string Word = "mahesh123", Encode, Decode; string encodedWord = "ocjguj345"; Coder code; Encode = code.encoder(Word); if (encodedWord.compare(Encode) == 0) { Decode = code.decoder(Encode); if (Word.compare(Decode) == 0) { cout << "Coder Test Passed" << endl; } else { cout << "Coder Test Failed" << endl; } } else { cout << "Coder Test Failed" << endl; } } void test_category(){ int Id = 1, IsActive = 1; string Name = "asdfg"; Category CategoryObject; CategoryObject.set_id(Id); CategoryObject.set_name(Name); CategoryObject.set_is_active(IsActive); if (Id == CategoryObject.get_id()) { if (Name.compare(CategoryObject.get_name()) == 0) { if (IsActive == CategoryObject.get_is_active()) { cout << "Category Test Passed" << endl; } else { cout << "Category Test Failed" << endl; } } else { cout << "Category Test Failed" << endl; } } else { cout << "Category Test Failed" << endl; } } void test_difficulty(){ int Id = 1, IsActive = 1; string Name = "asdfg"; Difficulty DifficultyObject; DifficultyObject.set_id(Id); DifficultyObject.set_name(Name); DifficultyObject.set_is_active(IsActive); if (Id == DifficultyObject.get_id()) { if (Name.compare(DifficultyObject.get_name()) == 0) { if (IsActive == DifficultyObject.get_is_active()) { cout << "Difficulty Test Passed" << endl; } else { cout << "Difficulty Test Failed" << endl; } } else { cout << "Difficulty Test Failed" << endl; } } else { cout << "Difficulty Test Failed" << endl; } } void test_words() { int Id = 1, IsActive = 1, CategoryId = 1, DifficultyId = 1; string Word = "asdf"; Words WordsObject; Category CategoryObject; Difficulty DifficultyObject; WordsObject.set_id(Id); CategoryObject.set_id(CategoryId); WordsObject.set_category_id(CategoryObject); DifficultyObject.set_id(DifficultyId); WordsObject.set_difficulty_id(DifficultyObject); WordsObject.set_word(Word); WordsObject.set_is_active(IsActive); if (Id == WordsObject.get_id()) { if (CategoryId == WordsObject.get_category_id().get_id()) { if (DifficultyId == WordsObject.get_difficulty_id().get_id()) { if (Word.compare(WordsObject.get_word())==0) { if (IsActive == WordsObject.get_is_active()) { cout << "Words Test Passed" << endl; } else { cout << "Words Test Failed" << endl; } } else { cout << "Words Test Failed" << endl; } } else { cout << "Words Test Failed" << endl; } } else { cout << "Words Test Failed" << endl; } } else { cout << "Words Test Failed" << endl; } } void test_xml_parser_get_category_from_xml() { xml_document<> Document; int count = 0; string category[4] = { "Animals","Countries","Movies","Plants" }; xml_node<> *Node; string Buffer="<Hangman><Categories><Category><Name>Animals</Name><IsActive>1</IsActive></Category><Category><Name>Countries</Name><IsActive>1</IsActive></Category><Category><Name>Movies</Name><IsActive>1</IsActive></Category><Category><Name>Plants</Name><IsActive>1</IsActive></Category></Categories></Hangman>"; Document.parse<0>(&Buffer[0]); Node = Document.first_node(); DatabaseXmlParser Xml; vector<Category> CategoryVector; CategoryVector = Xml.get_category_from_xml(Node); if (CategoryVector.size() == 4) { for (unsigned int i = 0; i < CategoryVector.size(); i++) { if (CategoryVector[i].get_name().compare(category[i])==0) { count++; } } if (count == CategoryVector.size()) { cout << "Xml Category Test Passed" << endl; } else { cout << "Xml Category Test Failed" << endl; } } else { cout << "Xml Category Test Failed" << endl; } } void test_xml_parser_get_diffiulty_from_xml() { xml_document<> Document; xml_node<> *Node; int count = 0; string difficulty[4] = { "Easy", "Medium", "Hard"}; string Buffer = "<Hangman> <Difficulties><Difficulty><Name>Easy</Name><IsActive>1</IsActive></Difficulty><Difficulty><Name>Medium</Name><IsActive>1</IsActive></Difficulty><Difficulty><Name>Hard</Name><IsActive>1</IsActive></Difficulty></Difficulties></Hangman>"; Document.parse<0>(&Buffer[0]); Node = Document.first_node(); DatabaseXmlParser Xml; vector<Difficulty> DifficultyVector; DifficultyVector = Xml.get_difficulty_from_xml(Node); if (DifficultyVector.size() == 3) { for (unsigned int i = 0; i < DifficultyVector.size(); i++) { if (DifficultyVector[i].get_name().compare(difficulty[i]) == 0) { count++; } } if (count == DifficultyVector.size()) { cout << "Xml Difficulty Test Passed" << endl; } else { cout << "Xml Difficulty Test Failed" << endl; } } else { cout << "Xml Difficulty Test Failed" << endl; } } void test_xml_parser_get_word_from_xml() { xml_document<> Document; xml_node<> *Node; int count = 0; string word[6] = { "Lion", "Tiger", "Snake", "Zebra", "Yak", "Wolf" }; string Buffer = "<Hangman><Words><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Lion</Name><IsActive>1</IsActive></Word><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Tiger</Name><IsActive>1</IsActive></Word><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Snake</Name><IsActive>1</IsActive></Word><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Zebra</Name><IsActive>1</IsActive></Word><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Yak</Name><IsActive>1</IsActive></Word><Word><CategoryId>1</CategoryId><DifficultyId>1</DifficultyId><Name>Wolf</Name><IsActive>1</IsActive></Word></Words></Hangman>"; Document.parse<0>(&Buffer[0]); Node = Document.first_node(); DatabaseXmlParser Xml; vector<Words> WordsVector; WordsVector = Xml.get_words_from_xml(Node); if (WordsVector.size() == 6) { for (unsigned int i = 0; i < WordsVector.size(); i++) { if (WordsVector[i].get_word().compare(word[i]) == 0) { count++; } } if (count == WordsVector.size()) { cout << "Xml Words Test Passed" << endl; } else { cout << "Xml Words Test Failed" << endl; } } else { cout << "Xml Words Test Failed" << endl; } } void test_load_data() { DatabaseInterface* DBInterface = new DatabaseImplementation(); DBInterface->load_data(); test_get_category(); test_get_difficulty(); } void test_get_category() { DatabaseInterface* DBInterface = new DatabaseImplementation(); int count = 0; string category[4] = { "Animals", "Countries", "Movies", "Plants" }; vector<Category> CategoryVector; CategoryVector = DBInterface->get_category(); if (CategoryVector.size() == 4) { for (unsigned int i = 0; i < CategoryVector.size(); i++) { if (CategoryVector[i].get_name().compare(category[i]) == 0) { count++; } } if (count == CategoryVector.size()) { cout << "Category from DB Test Passed" << endl; } else { cout << "Category from DB Test Failed" << endl; } } else { cout << "Category from DB Test Failed" << endl; } } void test_get_difficulty() { DatabaseInterface* DBInterface = new DatabaseImplementation(); vector<Difficulty> DifficultyVector; int count = 0; string difficulty[4] = { "Easy", "Medium", "Hard" }; DifficultyVector = DBInterface->get_difficulty(); if (DifficultyVector.size() == 3) { for (unsigned int i = 0; i < DifficultyVector.size(); i++) { if (DifficultyVector[i].get_name().compare(difficulty[i]) == 0) { count++; } } if (count == DifficultyVector.size()) { cout << "Difficulty from DB Test Passed" << endl; } else { cout << "Difficulty from DB Test Failed" << endl; } } else { cout << "Difficulty from DB Test Failed" << endl; } } void test_update_game_details() { int GameId = 6; string Result = "WIN"; vector<GameDetails> GameDetailsVector; DatabaseInterface* DBInterface = new DatabaseImplementation(); string Status = DBInterface->update_game_result(GameId, (char*)Result.c_str()); GameDetailsVector = DBInterface->get_updated_result(GameId); if (GameDetailsVector.size() > 0) { if (GameDetailsVector[0].get_result().compare(Result) == 0) { cout << "Test Update Game Details By GameId Passed" << endl; } else { cout << "Test Update Game Details By GameId Failed" << endl; } } else { cout << "Test Update Game Details By GameId Failed" << endl; } GameId = 6; Result = "WIN"; int SocketAddress = 4125; Status = DBInterface->update_game_result(GameId, SocketAddress,(char*)Result.c_str()); GameDetailsVector = DBInterface->get_updated_result(GameId,SocketAddress); if (GameDetailsVector.size() > 0) { if (GameDetailsVector[0].get_result().compare(Result) == 0) { cout << "Test Update Game Details By Socket Address Passed" << endl; } else { cout << "Test Update Game Details By Socket Address Failed" << endl; } } else { cout << "Test Update Game Details By Socket Address Failed" << endl; } } void test_get_maximum_game_id() { int GameId; DatabaseInterface* DBInterface = new DatabaseImplementation(); GameId = DBInterface->get_maximum_game_id(); if (GameId >= 5) { cout << "Test Get Maximum Game Id Passed" << endl; } else { cout << "Test Get Maximum Game Id Failed" << endl; } } void test_insert_into_game_details() { int GameId = 6, SocketAddress = 4125, count = 0; string UserName = "mani",Word="Elephant"; DatabaseInterface* DBInterface = new DatabaseImplementation(); string Status = DBInterface->insert_into_game_details(GameId, (char*)UserName.c_str(), SocketAddress, (char*)Word.c_str()); vector<GameDetails> gamedetails = DBInterface->get_playing_game_detail(GameId); for (unsigned int i = 0; i < gamedetails.size(); i++) { if (gamedetails[i].get_game_id() == GameId) { if (gamedetails[i].get_username().compare(UserName) == 0) { if (gamedetails[i].get_socket_address() == SocketAddress) { if (gamedetails[i].get_word_id().get_word().compare(Word) == 0) { count++; } } } } } gamedetails = DBInterface->get_playing_game_detail(); for (unsigned int i = 0; i < gamedetails.size(); i++) { if (gamedetails[i].get_game_id() == GameId) { if (gamedetails[i].get_username().compare(UserName) == 0) { if (gamedetails[i].get_socket_address() == SocketAddress) { if (gamedetails[i].get_word_id().get_word().compare(Word) == 0) { count++; } } } } } if (count == 2) { cout << "Test Insert Game Details Passed" << endl; } else { cout << "Test Insert Game Details Failed" << endl; } } void test_get_word() { DatabaseInterface* DBInterface = new DatabaseImplementation(); int count = 0; char* CategoryName = "Animals"; char* DifficultyName = "Easy"; string words[10] = { "Lion", "Tiger", "Snake", "Zebra", "Yak", "Wolf", "Cat", "Bear", "Owl", "monkey" }; string Word; Word = DBInterface->get_word(CategoryName,DifficultyName); if (!Word.empty()) { for (unsigned int i = 0; i < 10 ; i++) { if (Word.compare(words[i]) == 0) { count++; } } if (count == 1) { cout << "Word from DB Test Passed" << endl; } else { cout << "Word from DB Test Failed" << endl; } } else { cout << "Word from DB Test Failed" << endl; } }
true
a861319fc6226a783cf105b359146dfb8c4b8003
C++
Louis-tiany/tiny_rpc
/src/TcpClient.cc
UTF-8
1,387
2.59375
3
[]
no_license
/* * File : TcpClient.cc * Author : * * Mail : * * Creation : Tue 29 Dec 2020 04:48:23 PM CST */ #include <functional> #include <iostream> #include "../include/TcpClient.h" TcpClient::TcpClient(EventLoop *loop, InetAddress addr): loop_(loop), ip_(addr.ip()), port_(addr.port()), connector_(new Connector(loop, ip_, port_)), connect_(false) { connector_->set_new_conn_callback(std::bind(&TcpClient::new_connection, this, std::placeholders::_1)); } TcpClient::~TcpClient(){ } void TcpClient::connect(){ connect_ = true; connector_->start(); } void TcpClient::disconnect(){ connect_ = false; //should shutdown tcpconnection } void TcpClient::stop(){ connect_ = false; connector_->stop(); } void TcpClient::new_connection(int sockfd){ TcpConnectionPrt conn(new TcpConnection(loop_, sockfd)); conn->set_conn_callback(connection_callback_); conn->set_message_callback(message_callback_); conn->set_write_callback(write_callback_); conn->set_close_callback(std::bind(&TcpClient::remove_connection, this, std::placeholders::_1)); printf("new conn\n %s", __FUNCTION__); connection_ = conn; conn->conn_established(); } void TcpClient::remove_connection(const TcpConnectionPrt &conn){ connection_.reset(); loop_->run_in_loop(std::bind(&TcpConnection::connection_destroy, conn)); }
true
3d3cf08a37c334d7b2a3cc759a529bfda0dee993
C++
pederson/simbox
/unit_tests/hdf5/HDFFileSystemWriter_test.cpp
UTF-8
879
2.5625
3
[]
no_license
#include "../../include/HDFFileSystemWriter.hpp" #include "../../include/DataBufferWriter.hpp" #include <iostream> #include <vector> int main(int argc, char * argv[]){ typedef simbox::DataBufferWriter<std::vector<int>, simbox::HDFFileSystemWriter> Writer; std::size_t nvals = 20; std::vector<int> v1(nvals); for (auto i=0; i<nvals; i++) v1[i] = i; Writer bio("output.h5"); bio.resize(nvals); for (auto i=0; i<nvals; i++) bio[i] = v1[i]; // test the filesystem write bio.write_buffer("booger", "eater", "field1"); for (auto i=0; i<nvals; i++) bio[i] = v1[i]+1; bio.write_buffer("booger", "picker", "test2"); for (auto i=0; i<nvals; i++) bio[i] = v1[i]-1; bio.write_buffer("doodee", "licker", "test3"); // // test the filesystem read bio.read_buffer("booger", "eater", "field1"); for (auto i=0; i<nvals; i++) std::cout << bio[i] << std::endl; return 0; }
true
6e37dc5b9e3149fba77eed8ce05a9fea7b716ed2
C++
Falcondorf/ZurvivalArena
/Zurvival-Arena/snak/Menu.h
ISO-8859-1
1,617
3.34375
3
[]
no_license
#pragma once #include <SFML\Graphics.hpp> /*! * \brief Classe reprsentant le menu de demarage du jeu. *\file menu.h *\author Aynaou Dupont Fakir Bauwens Temsamani */ class Menu { public: /*! * \brief Constructeur du Menu du jeu. * \param width la longeur du menu. * \param height la largeur du menu. */ Menu(float width, float height); /*! * \brief Dessine dans la fentre du jeu. *\param window La fentre principal. */ void draws(sf::RenderWindow &window); /*! * \brief Permet de parcourir le menu vers le haut. */ void MoveUp(); /*! * \brief Permet de parcourir le menu vers le bas. */ void MoveDown(); /*! * \brief Permet de parcourir le menu vers le haut. * \return le numero d'index selectionn. */ int getPressedItem() { return selectedItemIndex; } /*! * \brief Permet de changer le nom d'element parcourir dans le menu. * \param nbmenu le nombre d'element dans le menu. */ inline void changernbMenu(int nbmenu); sf::RenderWindow window; /*! * \brief Geteur d'un element du menu. * \param id le nombre d'element dans le menu. */ inline sf::Text getMenu(int id) const; private: int selectedItemIndex;/*!< L'index selectionner dans le menu */ sf::Font font;/*!< la police utilise pour les ecritures du menu */ sf::Text menu[5];/*!< le tableau de titre du menu */ sf::Texture texture;/*!< La texture sur lequel on va appliquer l'image du fond d'ecran. */ sf::Sprite background;/*!<l'image du fond d'ecran. */ int nbMenu;/*!< le nombre d'element dans le menu */ }; sf::Text Menu::getMenu(int id) const { return menu[id]; } inline void Menu::changernbMenu(int nbmenu) { nbMenu = nbmenu; }
true
1816ea8a6010c7db7dcb81ebf75ff7a67333a8d8
C++
PaThAkavi/Trees
/BSTOperations.hxx
UTF-8
2,396
3.6875
4
[]
no_license
#include<iostream> using namespace std; typedef long long ll; typedef struct node { ll data; struct node* left; struct node* right; }node; node* insert(node* root, ll value){ if(!root){ node* newnode = (node*)malloc(sizeof(node)); newnode->data = value; newnode->left = NULL; newnode->right = NULL; root = newnode; } else{ if(value >= root->data){ root->right = insert(root->right, value); } else{ root->left = insert(root->left, value); } } } void inorder(node* root){ if(root){ inorder(root->left); printf("%lld ", root->data); inorder(root->right); } } node * minValueNode(struct node* root) { node* current = root; while (current && current->left != NULL) current = current->left; return current; } node* deleteNode(node* root, ll key) { if (root == NULL) return root; if (key < root->data) root->left = deleteNode(root->left, key); else if (key > root->data) root->right = deleteNode(root->right, key); else { if (root->left == NULL) { node *temp = root->right; free(root); return temp; } else if (root->right == NULL) { struct node *temp = root->left; free(root); return temp; } struct node* temp = minValueNode(root->right); root->data = temp->data; root->right = deleteNode(root->right, temp->data); } return root; } int main(){ ll n, i, val, parent; char op; cout << "Enter number of operations to be performed:\n"; cin >> n; node* root = NULL; for(i = 0; i < n; i++){ cout << "Please specify operation(i or d) and the node value:\n"; cin >> op >> val; if(op == 'i'){ root = insert(root, val); } else if(op == 'd'){ root = deleteNode(root, val); } else{ cout << "No such operation present" << endl; } if(i == 0){ printf("%lld\n", i+1); parent = i+1; } else if(val >= root->data){ printf("%lld\n", 2*parent+1); } else{ printf("%lld\n", 2*parent); } } inorder(root); return 0; }
true
32af3ec174903a0fa53603090bded5e36d4be56f
C++
lsst-ts/ts_sal_runtime
/tcs/tcs/tpk/TrackingTarget.cpp
UTF-8
1,616
2.8125
3
[]
no_license
/// \file TrackingTarget.cpp /// \brief Implementation of the tracking target class. // D L Terrett // Copyright CCLRC. All rights reserved. #include "TrackingTarget.h" #include "slalib.h" namespace tpk { /// Get target position in the tracking frame. /** This method is called by the kernel "fast" routines an must therefore be efficient. The base class implementation assumes that the position and rates in the tracking frame have been stored in the data members Position T0 and Velocity by the object constructor and are kept up-to-date by the update method (if required). \returns the target position in the tracking frame at the specified time. */ vector TrackingTarget::position( const double& t ///< TAI (MJD) ) const { mMutex.lock(); vector p = mPosition; deltav v = mVelocity; double t0 = mT0; mMutex.unlock(); return p + v * (t - t0); } /// Update position in the tracking frame /** Recomputes the tracking frame position and rates by computing the positions 10 seconds apart. */ void TrackingTarget::update( const double& t1 ///< TAI (MJD) ) { // Position in tracking frame "now". vector p1 = position(t1, *mTrackFrame); // Position in tracking frame in 10 sec time. double dt = 10.0/86400.0; vector p2 = position(t1 + dt, *mTrackFrame); // Rates deltav v = (p2 - p1) / dt; // Store. mMutex.lock(); mPosition = p1; mT0 = t1; mVelocity = v; mMutex.unlock(); } }
true
1be4ccd1d0d544f2a522c4faeb1cdaa778ae057d
C++
mricha41/Data-Structures-and-Algorithms-CPP
/CircularLinkedList/main.cpp
UTF-8
1,709
3.1875
3
[]
no_license
#include <iostream> #include <string> #include "CircularList.hpp" #include "Algorithms.hpp" typedef float mine; int main() { CircularList<mine> first(15.7f); first.pushBack(25.001f); first.pushBack(66.575f); first.pushBack(99.654f); first.pushBack(100.0f); first.pushBack(101.677f); std::cout << "first length: " << first.length() << "\n"; std::cout << "first..." << "\n"; DisplayList(first); std::cout << "first recursive..." << "\n"; DisplayListRecursive(first.begin()); CircularList<mine> second(15.7f); second.pushFront(25.001f); second.pushFront(66.575f); second.pushFront(99.654f); second.pushFront(100.0f); second.pushFront(101.677f); std::cout << "second length: " << second.length() << "\n"; std::cout << "second..." << "\n"; DisplayList(second); std::cout << "second recursive..." << "\n"; DisplayListRecursive(second.begin()); CircularList<mine> third(15.7f); third.insert(1, 25.001f); third.insert(0, 66.575f); third.insert(3, 99.654f); third.insert(0, 100.0f); third.insert(5, 101.677f); std::cout << "third length: " << third.length() << "\n"; std::cout << "third..." << "\n"; DisplayList(third); std::cout << "third recursive..." << "\n"; DisplayListRecursive(third.begin()); CircularList<mine> test(15.7f); test.pushBack(33.f); test.pushBack(43.f); test.pushBack(73.f); test.pushBack(303.f); test.pushBack(133.f); std::cout << "length test: " << test.length() << "\n"; DisplayList(test); test.clear(); std::cout << "empty?" << "\n"; DisplayList(test); test.pushBack(12.f); test.pushBack(70.f); test.pushBack(304.f); test.pushBack(1.f); DisplayList(test); test.erase(3); test.erase(0); DisplayList(test); return 0; }
true
02c1ab378907b107cdea5a1111d264bbde7050bd
C++
renjiedai/SETerminal
/Classes/Character/Monster.h
GB18030
1,123
2.671875
3
[]
no_license
#pragma once /** * @file Monster.h */ #ifndef MONSTER_H #define MONSTER_H #include "cocos2d.h" #include "Const/Const.h" #include "Character.h" /** *@brief */ class Monster : public Character { public: /** * @brief һMonsterʵ * @param MonsterʵӦزļ * @return ָMonsterʵָ * @author ʽ */ static Monster* create(const std::string& filename); static Monster* create(enemyType_ type); /** * @brief MonsterƶԼӵδԽ﷢ӵ * @return * @author ʽ */ void Monster::move(); void shoot(); virtual void die(); /** * @brief ΪMonster * @return Ƿɹ * @author ʽ */ virtual bool bindPhysicsBody(); virtual void receiveDamage(int damage); virtual void updateFacingStatus(); virtual void updateWalkingStatus(); void update(float dt); static bool isPlayerSuperDamage_; protected: int ShootFreq; enemyType_ typeOfThisMonster; bool autoShoot = false; float shootGap = 2.f; }; #endif // !MONSTER_H
true
b098ed35470c3a0bff051f1fee9c755e40b40bce
C++
ddl1997/PTA-Test
/PTA/PTA/A1011.cpp
UTF-8
521
2.84375
3
[]
no_license
#include<iostream> #include<iomanip> using namespace std; int main() { double m[3] = {0, 0, 0}; char its[3]; char select[3] = {'W', 'T', 'L'}; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { double temp; cin >> temp; if (m[i] < temp) { m[i] = temp; its[i] = select[j]; } } } double profit = (m[0] * m[1] * m[2] * 0.65 - 1) * 2; cout << its[0] << " " << its[1] << " " << its[2] << " " << setiosflags(ios::fixed) << setprecision(2) << profit; //cin >> m[0]; return 0; }
true
4fb9c85fd8aa61391997ad54f75ba51aebd09b22
C++
fengsharp/study
/08libcurl/code/CookieCache.cpp
UTF-8
7,490
2.84375
3
[]
no_license
#include "CookieCache.h" #include <stdio.h> #include <string.h> #include <time.h> #include <vector> #include <regex> #include "StringUtil.h" CookieCache* CookieCache::s_pInstance = nullptr; CookieCache* CookieCache::instance() { if (s_pInstance == nullptr) { s_pInstance = new CookieCache(); } return s_pInstance; } CookieCache::CookieCache() { } void CookieCache::init(const std::string &localFilePath) { m_strFile = localFilePath; loadData(); } void CookieCache::loadData() { FILE* file = fopen(m_strFile.c_str(), "r"); if (file == NULL) // if file not exist, return { return; } // domain \t key \t value \t expires \n long long now = time(NULL); char buf[BUFSIZ]; while(fgets(buf, BUFSIZ, file) != NULL) { size_t len = strlen(buf); if (buf[len-1] == '\n') { len -= 1; } std::string strLine(buf, len); std::vector<std::string> splits; stringSplit(strLine, "\t", splits); if (splits.size() != 4) { continue; } long long expires = str2longlong(splits[3]); if (now < expires) { addCookie(splits[0], splits[1], splits[2], expires); } } fclose(file); // try clear expires trySaveData(); } bool CookieCache::saveData() { FILE* file = fopen(m_strFile.c_str(), "w"); if (file == NULL) { return false; } long long now = time(NULL); for (auto& domainItem : m_mapLocalCookie) { const std::string& strDomain = domainItem.first; for(auto& cookieItem : domainItem.second) { long long expires = cookieItem.second.expires; if (expires <= now) { continue; } // domain key value expires fprintf(file, "%s\t%s\t%s\t%lld\n", strDomain.c_str(), cookieItem.first.c_str(), cookieItem.second.value.c_str(), expires); } } fclose(file); return true; } void CookieCache::trySaveData() { if (m_bSave) { saveData(); m_bSave = false; } } void CookieCache::addCookie(const std::string& domain, const std::string& cookieKey, const std::string& cookieValue, long long expires/*=0*/) { if (domain.empty() || cookieKey.empty()) { return; } long long now = time(NULL); if (expires > 0 && expires <= now) { return; } bool dataChanged = false; std::map<std::string, std::map<std::string, CookieProperty>>::iterator findDomain = m_mapLocalCookie.find(domain); if (cookieValue.empty()) // delete { if (findDomain != m_mapLocalCookie.end()) { std::map<std::string, CookieProperty>::iterator cookieItem = findDomain->second.find(cookieKey); if (cookieItem != findDomain->second.end()) { findDomain->second.erase(cookieItem); dataChanged = true; // data delete } } } else // set { if (findDomain == m_mapLocalCookie.end()) { m_mapLocalCookie[domain].insert(std::pair<std::string, CookieProperty>(cookieKey, CookieProperty(cookieValue, expires))); dataChanged = true; // data add } else { std::map<std::string, CookieProperty>::iterator cookieItem = findDomain->second.find(cookieKey); if (cookieItem == findDomain->second.end()) { findDomain->second[cookieKey] = CookieProperty(cookieValue, expires); dataChanged = true; } else { if (cookieItem->second.value != cookieValue) { findDomain->second[cookieKey] = CookieProperty(cookieValue, expires); dataChanged = true; } // else value not change, expires change, ignore } } } if (!m_bSave && (expires > 0 && dataChanged)) { m_bSave = true; } } void CookieCache::parseAndAddCookie(const std::string& reqDomain, const std::string& strCookie) { // Set-Cookie: k=v;Domain=...;Expires=... static const std::string COOKIE_SET_MARK = "Set-Cookie:"; if (strCookie.find(COOKIE_SET_MARK) != 0) { return; } // cookieFormat = [ k=v;Domain=...;Expires=...] std::string cookieFormat = strCookie.substr(COOKIE_SET_MARK.length()); std::vector<std::string> splits; stringSplit(cookieFormat, ";", splits); if (splits.empty()) { return; } // name-value std::vector<std::string> nameValues; stringSplit(splits[0], "=", nameValues); if (nameValues.size() != 2) { return; } std::string cookieKey = trim(nameValues[0]); std::string cookieValue = trim(nameValues[1]); std::string domain = reqDomain; long long expires = 0; // Domain Expires for (size_t i=1; i<splits.size(); ++i) { std::vector<std::string> tmpKeyValue; stringSplit(splits[i], "=", tmpKeyValue); if (tmpKeyValue.size() != 2) { continue; } std::string key = trim(tmpKeyValue[0]); std::string value = trim(tmpKeyValue[1]); if (key == "Domain") { domain = value; } else if (key == "Expires") { expires = str2longlong(value); } } addCookie(domain, cookieKey, cookieValue, expires); } void CookieCache::setCurlRequestCookie(const std::string& reqDomain, CURL* curlHandle) { std::map<std::string, std::map<std::string, CookieProperty>>::iterator findItem = m_mapLocalCookie.find(reqDomain); if (findItem == m_mapLocalCookie.end()) { return; } long long now = time(NULL); std::map<std::string, CookieProperty>& mapCookies = findItem->second; for (auto& cookieItem : mapCookies) { if (cookieItem.second.value.empty() || cookieItem.second.expires <= now) { continue; } else { std::string strCookie("Set-Cookie: "); strCookie.append(cookieItem.first); strCookie.append("="); strCookie.append(cookieItem.second.value); printf("### set cookie string:%s\n", strCookie.data()); curl_easy_setopt(curlHandle, CURLOPT_COOKIELIST, strCookie.c_str()); } } } // http://192.168.154.128:8888/game // http://www.baidu.com // http://www.baidu.com/game // http://www.baidu.com:8888/game char* CookieCache::parseDomain(const char* url) { char* ret = nullptr; if (!url) { return ret; } static const char* URL_PRIFIX = "http://"; static const size_t URL_PRIFIX_LEN = strlen(URL_PRIFIX); const char* start = url; while (*start == ' ' && *start != '\0') { ++start; } if (strlen(start) < URL_PRIFIX_LEN) { return ret; } if (memcmp(URL_PRIFIX, start, URL_PRIFIX_LEN) == 0) { start += URL_PRIFIX_LEN; } const char* stop = start; while (*stop != '\0' && *stop != '/' && *stop != ':') { ++stop; } if (stop > start) { ret = strndup(start, (stop - start)); } return ret; }
true
665ec8ce3e53f9753669cf64082a631d61a93190
C++
VipulKhandelwal1999/Coding_Blocks
/61.Interactive_Problems/02.Interactive_Problems_2_Examples.cpp
UTF-8
2,915
3.671875
4
[]
no_license
/* This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You may also refer to the guide on interactive problems: https://codeforces.com/blog/entry/45307. The jury guessed some array a consisting of 6 integers. There are 6 special numbers — 4, 8, 15, 16, 23, 42 — and each of these numbers occurs in a exactly once (so, a is some permutation of these numbers). You don't know anything about their order, but you are allowed to ask up to 4 queries. In each query, you may choose two indices i and j (1≤i,j≤6, i and j are not necessarily distinct), and you will get the value of ai⋅aj in return. Can you guess the array a? The array a is fixed beforehand in each test, the interaction program doesn't try to adapt to your queries. Interaction Before submitting the answer, you may ask up to 4 queries. To ask a query, print one line in the following format: ? i j, where i and j should be two integers such that 1≤i,j≤6. The line should be ended with a line break character. After submitting a query, flush the output and read the answer to your query — one line containing one integer ai⋅aj. If you submit an incorrect query (or ask more than 4 queries), the answer to it will be one string 0. After receiving such an answer, your program should terminate immediately — otherwise you may receive verdict "Runtime error", "Time limit exceeded" or some other verdict instead of "Wrong answer". To give the answer, your program should print one line ! a1 a2 a3 a4 a5 a6 with a line break in the end. After that, it should flush the output and terminate gracefully. Example inputCopy 16 64 345 672 outputCopy ? 1 1 ? 2 2 ? 3 5 ? 4 6 ! 4 8 15 16 23 42 Note If you want to submit a hack for this problem, your test should contain exactly six space-separated integers a1, a2, ..., a6. Each of 6 special numbers should occur exactly once in the test. The test should be ended with a line break character. */ #include<bits/stdc++.h> using namespace std; int query(int i, int j) { cout << "? "<< i << " " << j << endl; int ans; cin >> ans; return ans; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); vector<int> v = {4, 8, 15, 16, 23, 42}; vector<int> a(4); for(int i=0; i<4; i++){ a[i] = query(i+1, i+2); } do{ bool can = 1; for(int i=0; i<4; i++){ if(a[i] != v[i]*v[i+1]){ can = 0; } } if(can == 1){ cout << "! "; for(auto x: v){ cout << x << " "; } return 0; } } while(next_permutation(v.begin(), v.end())); }
true
4124c1b3566a5124802fc4247b28a034f09aea29
C++
HavocTheGnome/HWNUM13
/Driver.hpp
UTF-8
770
3.65625
4
[]
no_license
#include <iostream> using namespace std; void printArray(int* ar, int begin, int end) { for(int i = begin; i < end; i++) { cout << ar[i] << " "; } cout << "\n"; } void mergeSort(int* ar, int begin, int end) { cout << "Merge Sorting: "; printArray(ar, begin, end); if(begin != end) { int begin1 = begin; int end1 = (end + begin) / 2; int begin2 = end1 + 1; int end2 = end; mergeSort(ar, begin1, end1); mergeSort(ar, begin2, end2); cout << "Now we have to merge!!!!\n Start to cry Clancy!!!\n"; } else { cout << "One List! Do nothing\n"; } } int main() { int ar[5] = {7, 2, 1, 4, 3}; mergeSort(ar, 0, 4); printArray(ar, 0, 4); }
true
ef6d7c8ecff6a5e2b27188c2802c82b6b881b67f
C++
ghostxiu/CplusplusPrimerPlus6thEditions
/Chapter12/cow.h
UTF-8
432
2.65625
3
[]
no_license
//Changed by Ghostxiu 2017/9/12 #ifndef COW_H_ #define COW_H_ class Cow{ private: char name[20]; char * hobby ; double weight; public: Cow(); Cow(const char * nm , const char * ho , double wt); ~Cow(); Cow(const Cow & c); Cow & operator = (const Cow & c); void ShowCow() const ; }; #endif // COW_H_ //文件地址:https://github.com/ghostxiu/CplusplusPrimerPlus6thEditions/tree/master/Chapter12/
true
a0876e6191bec9d0f0e3644258468fe7733fb088
C++
blitz-research/blitz3d_msvc2017
/blitz3d/meshmodel.h
UTF-8
1,357
2.53125
3
[ "Zlib" ]
permissive
#ifndef MESHMODEL_H #define MESHMODEL_H #include "model.h" #include "surface.h" class MeshCollider; class MeshModel : public Model{ public: typedef vector<Surface*> SurfaceList; MeshModel(); MeshModel( const MeshModel &t ); ~MeshModel(); //Entity interface virtual MeshModel *getMeshModel(){ return this; } virtual Entity *clone(){ return d_new MeshModel( *this ); } //Object interface virtual bool collide( const Line &line,float radius,Collision *curr_coll,const Transform &t ); //Model interface virtual void setRenderBrush( const Brush &b ); virtual bool render( const RenderContext &rc ); virtual void renderQueue( int type ); //boned mesh! void createBones(); //MeshModel interface Surface *createSurface( const Brush &b ); void setCullBox( const Box &box ); void updateNormals(); void flipTriangles(); void transform( const Transform &t ); void paint( const Brush &b ); void add( const MeshModel &t ); void optimize(); //accessors const SurfaceList &getSurfaces()const; Surface *findSurface( const Brush &b )const; bool intersects( const MeshModel &m )const; MeshCollider *getCollider()const; const Box &getBox()const; private: struct Rep; Rep *rep; int brush_changes; Brush render_brush; vector<Brush> brushes; vector<Surface::Bone> surf_bones; MeshModel &operator=(const MeshModel &); }; #endif
true
fb93a42853e90366de3292e188bb45cba29c8e23
C++
goeldivyansh/Data-Structures-and-Algorithms
/Searching/SearchInSortedRotatedArray.cpp
UTF-8
726
3.28125
3
[]
no_license
#include<iostream> #include <bits/stdc++.h> using namespace std; //Time: O(logn) Space: O(1) int Search(int a[], int n, int x) { //6,7,8,9,10,1,2 int m,l=0,r=n-1; while(l<=r) { m = (l+r)/2; if(x == a[m]) return m; else if(a[m] > a[l]) // Left Array Sorted { if(x >= a[l] && x < a[m]) r = m-1; else l = m+1; } else // Right Array Sorted { if(x > a[m] && x <= a[r]) l = m+1; else r = m-1; } } return -1; } int main() { int a[] = {6,7,8,9,10,1,2}; cout << Search(a,7,2) << endl; return 0; }
true
891055a53f9db748f679af5665c82c8aa6b479de
C++
artisdom/idUTF8lib
/tests/tests.cpp
UTF-8
943
3.234375
3
[ "BSD-3-Clause" ]
permissive
#define CATCH_CONFIG_MAIN #include "catch/catch.hpp" #include "../lib/idutf8lib.hpp" TEST_CASE("Initialization is correct") { Utf8String empty_utf8str; REQUIRE(empty_utf8str.to_string().empty() == true); Utf8String string_to_utf8str("Hello World"); REQUIRE(string_to_utf8str.to_string() == "Hello World"); } TEST_CASE("Public Interface", "[interface]") { SECTION("Operators") { Utf8String test_str; test_str = "ĥéĺĺõ ẃòŕĺd"; REQUIRE(test_str.to_string() == "ĥéĺĺõ ẃòŕĺd"); } SECTION("to string") { Utf8String test_str("hello"); REQUIRE(test_str.to_string() == "hello"); } SECTION("clear") { Utf8String test_str("Important API key"); test_str.clear(); REQUIRE(test_str.to_string().empty()); } SECTION("size in {chars, bytes}") { Utf8String test_str("Heĺĺç"); REQUIRE(test_str.size_in_chars() == 5); test_str = "Not utf8 please"; REQUIRE(test_str.size_in_bytes() == 15); } }
true
a838cda0a62d9c413298482ac6648db13d660b96
C++
HekpoMaH/Olimpiads
/grupa A/esenen turnir/RMI/2011/day2/sorting/sorting20.cpp
UTF-8
864
2.71875
3
[]
no_license
#include <stdio.h> #include <string.h> #define MOD 999017 int N, perm[4096], uz[4096], cycle[4096], cnt; inline int sort1(const int *perm, int N) { int time = 0; for (int i = 0; i < N; ++i) for (int j = i+1; j < N; ++j) time += perm[i] > perm[j]; return time; } inline int sort2(const int *perm, int N) { int nrc = 0; memset(cycle, 0, sizeof(cycle)); for (int i = 0; i < N; ++i) if (!cycle[i]) { ++nrc; int j = i; while (!cycle[j]) { cycle[j] = 1; j = perm[j]-1; } } return N-nrc; } void back(int level) { if (level == N) { cnt += sort2(perm, N) < sort1(perm, N); if (cnt >= MOD) cnt -= MOD; return ; } for (int i = 1; i <= N; ++i) if (!uz[i]) { uz[i] = 1; perm[level] = i; back(level+1); uz[i] = 0; } } int main() { scanf("%d", &N); back(0); printf("%d\n", cnt); return 0; }
true
02415a7f10d0d5bb0ac435936e56846f209b908e
C++
duc-la192773/baitapc-c-
/Week78.Ex2.cpp
UTF-8
1,307
3.3125
3
[]
no_license
#include<iostream> #include<fstream> using namespace std; typedef struct { int a, b; }PS; ostream& operator<< (ostream& os, PS p){ os<<p.a<<"/"<<p.b; return os; }; istream& operator>> (istream& is, PS& p){ cout<<" Nhap tu so:";is>>p.a; cout<<" Nhap mau so: ";is>>p.b; if(p.b==0) { cout<<" Xin nhap lai mau so :"; cin>>p.b; } return is; }; int ucln(int x,int y){ if(y==0) { return x;} return ucln(y,x%y); } PS rutgon(PS p){ int t=ucln(p.a,p.b); p.a=p.a/t; p.b=p.b/t; return p; } PS operator +(PS p1, PS p2){ PS p; p.a=p1.a*p2.b+p1.b*p2.a; p.b=p2.b*p1.b; return rutgon(p); }; PS operator-(PS p1, PS p2){ PS p; p.a=p1.a*p2.b-p1.b*p2.a; p.b=p1.b*p2.b; return rutgon(p); }; PS operator*(PS p1, PS p2){ PS p; p.a=p1.a*p2.a; p.b=p1.b*p2.b; return rutgon(p); }; int main() { PS p1,p2; cout<<" Nhap p1 :"<<endl; cin>>p1; cout<<" p1="<<p1<<endl; cout<<" Nhap p2 :"<<endl; cin>>p2; cout<<" p2="<<p2<<endl; cout<<endl; cout<<" p1+p2="<<p1+p2<<endl; cout<<" p1-p2="<<p1-p2<<endl; cout<<" p1*p2="<<p1*p2<<endl; system("pause"); return 0; }
true
570a3385c6fa5199ec46d222e7e0e771306eedad
C++
mahtab04/Cpp-Programs
/Array/removes_duplicates_sorted_array.cpp
UTF-8
899
3.375
3
[]
no_license
#include <bits/stdc++.h> using namespace std; int removeDuplicates(vector<int> &nums) { if (nums.size() == 0) return 0; int j = 0; for (int i = 0; i < nums.size() - 1; i++) { if (nums[i] != nums[i + 1]) { nums[j++] = nums[i]; } } nums[j++] = nums[nums.size() - 1]; return j; } int removeDuplicates(int arr[], int size) { if (size == 0 || size == 1) return size; int j = 0; for (int i = 0; i < size - 1; i++) { if (arr[i] != arr[i + 1]) { arr[j] = arr[i]; j++; } } arr[j++] = arr[size - 1]; return j; } int main() { int arr[] = {1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9}; int size = sizeof(arr) / sizeof(int); size = removeDuplicates(arr, size); for (auto x = 0; x < size; x++) { cout << arr[x] << " "; } }
true
75e873652b12a7a91fd9cd3f1f9d92fe5f25a850
C++
pragmadox/data_structures
/homework13/stack5driver.cpp
UTF-8
1,022
3.84375
4
[]
no_license
//File: stack5driver.cpp #include <iostream> #include <iomanip> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "stack5.h" using namespace std; int main() { stack stack1; const char *traverse; //pointer used to traverse the user string. const char *user_string; //string entered by the user; cout << setw(23) << "Enter a string: "; string str; getline(cin, str); user_string = str.c_str(); stack1.initialize_stack(strlen(user_string)); /*Traverse the string and put each character on the stack. */ for(traverse=user_string; *traverse!='\0'; traverse++) stack1.push(*traverse); /* Demonstrate the top function. */ cout << "The top of the stack is: "; cout << stack1.top() << endl; cout << "The top of the stack is: "; cout << stack1.top() << endl; cout << "Popped characters are: "; while(!stack1.is_empty()) cout << setw(2) << stack1.pop(); stack1.destroy_stack(); cout << endl; return 0; }
true
8d33d52a420cd3b6d1c2f71d9c1b49819519fd61
C++
SeekingMini/Algorithm-Repositary
/链表/1-6.cpp
UTF-8
986
3.984375
4
[]
no_license
/* * 题目:移除重复结点 * 链表:https://leetcode-cn.com/problems/remove-duplicate-node-lcci/ */ #include <iostream> #include <unordered_set> using namespace std; struct ListNode { int val; ListNode *next; explicit ListNode(int x) { val = x; next = nullptr; } }; ListNode *removeDuplicateNodes(ListNode *head) { if (!head) return nullptr; ListNode *p = head; unordered_set<int> set; while (p && p->next) { set.insert(p->val); if (set.count(p->next->val) != 0) p->next = p->next->next; else p = p->next; } return head; } int main() { // 手动创建链表 auto head = new ListNode(1); auto n1 = new ListNode(2); auto n2 = new ListNode(3); auto n3 = new ListNode(3); auto n4 = new ListNode(1); head->next = n1; n1->next = n2; n2->next = n3; n3->next = n4; // 去除重复结点 ListNode *newhead = removeDuplicateNodes(head); auto p = newhead; while (p) { cout << p->val << " "; p = p->next; } cout << endl; return 0; }
true
31297dae65749af86c3f67fdf2903ce4ab85be8c
C++
ThomasDHZ/VulkanRayTrace
/VulkanRayTraceTest/Buffer.cpp
UTF-8
7,417
3.171875
3
[]
no_license
#include "Buffer.h" #include <cassert> #include <cstring> #include <stdexcept> /** * Map a memory range of this buffer. If successful, mapped points to the specified buffer range. * * @param size (Optional) Size of the memory range to map. Pass VK_WHOLE_SIZE to map the complete buffer range. * @param offset (Optional) Byte offset from beginning * * @return VkResult of the buffer mapping call */ VkResult Buffer::map(VkDeviceSize size, VkDeviceSize offset) { return vkMapMemory(device, memory, offset, size, 0, &mapped); } /** * Unmap a mapped memory range * * @note Does not return a result as vkUnmapMemory can't fail */ void Buffer::unmap() { if (mapped) { vkUnmapMemory(device, memory); mapped = nullptr; } } /** * Attach the allocated memory block to the buffer * * @param offset (Optional) Byte offset (from the beginning) for the memory region to bind * * @return VkResult of the bindBufferMemory call */ VkResult Buffer::bind(VkDeviceSize offset) { return vkBindBufferMemory(device, buffer, memory, offset); } /** * Setup the default descriptor for this buffer * * @param size (Optional) Size of the memory range of the descriptor * @param offset (Optional) Byte offset from beginning * */ void Buffer::setupDescriptor(VkDeviceSize size, VkDeviceSize offset) { descriptor.offset = offset; descriptor.buffer = buffer; descriptor.range = size; } /** * Copies the specified data to the mapped buffer * * @param data Pointer to the data to copy * @param size Size of the data to copy in machine units * */ void Buffer::copyTo(void* data, VkDeviceSize size) { assert(mapped); memcpy(mapped, data, size); } /** * Flush a memory range of the buffer to make it visible to the device * * @note Only required for non-coherent memory * * @param size (Optional) Size of the memory range to flush. Pass VK_WHOLE_SIZE to flush the complete buffer range. * @param offset (Optional) Byte offset from beginning * * @return VkResult of the flush call */ VkResult Buffer::flush(VkDeviceSize size, VkDeviceSize offset) { VkMappedMemoryRange mappedRange = {}; mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mappedRange.memory = memory; mappedRange.offset = offset; mappedRange.size = size; return vkFlushMappedMemoryRanges(device, 1, &mappedRange); } /** * Invalidate a memory range of the buffer to make it visible to the host * * @note Only required for non-coherent memory * * @param size (Optional) Size of the memory range to invalidate. Pass VK_WHOLE_SIZE to invalidate the complete buffer range. * @param offset (Optional) Byte offset from beginning * * @return VkResult of the invalidate call */ VkResult Buffer::invalidate(VkDeviceSize size, VkDeviceSize offset) { VkMappedMemoryRange mappedRange = {}; mappedRange.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; mappedRange.memory = memory; mappedRange.offset = offset; mappedRange.size = size; return vkInvalidateMappedMemoryRanges(device, 1, &mappedRange); } void Buffer::createBuffer(VkDevice& device, VkPhysicalDevice& physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = getMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t Buffer::getMemoryType(VkPhysicalDevice& physicalDevice, uint32_t typeBits, VkMemoryPropertyFlags properties) { VkBool32* memTypeFound = nullptr; VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeBits & 1) == 1) { if ((memProperties.memoryTypes[i].propertyFlags & properties) == properties) { if (memTypeFound) { *memTypeFound = true; } return i; } } typeBits >>= 1; } if (memTypeFound) { *memTypeFound = false; return 0; } else { throw std::runtime_error("Could not find a matching memory type"); } } VkResult Buffer::createBuffer(VkDevice& device, VkPhysicalDevice& physicalDevice, VkBufferUsageFlags usageFlags, VkMemoryPropertyFlags memoryPropertyFlags, Buffer* buffer, VkDeviceSize size, void* data) { buffer->device = device; // Create the buffer handle VkBufferCreateInfo bufCreateInfo{}; bufCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufCreateInfo.usage = usageFlags; bufCreateInfo.size = size; vkCreateBuffer(device, &bufCreateInfo, nullptr, &buffer->buffer); // Create the memory backing up the buffer handle VkMemoryRequirements memReqs; VkMemoryAllocateInfo memAllocInfo{}; memAllocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; vkGetBufferMemoryRequirements(device, buffer->buffer, &memReqs); memAllocInfo.allocationSize = memReqs.size; // Find a memory type index that fits the properties of the buffer memAllocInfo.memoryTypeIndex = getMemoryType(physicalDevice, memReqs.memoryTypeBits, memoryPropertyFlags); // If the buffer has VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT set we also need to enable the appropriate flag during allocation VkMemoryAllocateFlagsInfoKHR allocFlagsInfo{}; if (usageFlags & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) { allocFlagsInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHR; allocFlagsInfo.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT_KHR; memAllocInfo.pNext = &allocFlagsInfo; } vkAllocateMemory(device, &memAllocInfo, nullptr, &buffer->memory); buffer->alignment = memReqs.alignment; buffer->size = size; buffer->usageFlags = usageFlags; buffer->memoryPropertyFlags = memoryPropertyFlags; // If a pointer to the buffer data has been passed, map the buffer and copy over the data if (data != nullptr) { buffer->map(); memcpy(buffer->mapped, data, size); if ((memoryPropertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) == 0) buffer->flush(); buffer->unmap(); } // Initialize a default descriptor that covers the whole buffer size buffer->setupDescriptor(); // Attach the memory to the buffer object return buffer->bind(); } /** * Release all Vulkan resources held by this buffer */ void Buffer::destroy() { if (buffer) { vkDestroyBuffer(device, buffer, nullptr); } if (memory) { vkFreeMemory(device, memory, nullptr); } }
true
fe62e4d3a33ea9b154f4fe80a4966b0844f2e116
C++
noamraveh/wet2DS
/SongAll.cpp
UTF-8
1,012
3.21875
3
[]
no_license
#include "SongAll.h" SongAll::SongAll(int artist_id, int song_id, int num_streams) : artist_id(artist_id),song_id(song_id),num_streams(num_streams){} bool SongAll::operator<(const SongAll &song) { if (num_streams>song.num_streams){ return true; } else if(num_streams<song.num_streams){ return false; } else{ // num streams is equal, checking according to artist id and then song id if (artist_id<song.artist_id){ return true; } else if(artist_id>song.artist_id){ return false; } else{ // artist id is equal, checking according to song id return song_id < song.song_id; } } } bool SongAll::operator==(const SongAll &song) { return num_streams==song.num_streams && artist_id==song.artist_id && song_id == song.song_id; } int SongAll::getArtistID() { return artist_id; } int SongAll::getSongID() { return song_id; } int SongAll::getNumStreams() { return num_streams; }
true
37bc873fcd3a56fc6d9666bb2c706d94136b2b0d
C++
alexandrovsky/freestyle
/engine/animation.h
UTF-8
4,441
2.625
3
[]
no_license
/* * Copyright (C) 2008-2013 by Mathias Paulin, David Vanderhaeghe * Mathias.Paulin@irit.fr * vdh@irit.fr */ #ifndef ANIMATION_H #define ANIMATION_H #include <string> #include <vector> #include <map> #include "opengl.h" #include "assimp/anim.h" #include <glm/gtx/quaternion.hpp> #include "skeleton.h" namespace vortex { class Animation { public: struct VectorKey { double mTime; glm::vec3 mValue; // Default constructor VectorKey() { } // Construction from a given time and key value VectorKey(double time, const glm::vec3 &value) : mTime(time), mValue(value) { } }; struct QuatKey { double mTime; glm::quat mValue; // Default constructor QuatKey() { } // Construction from a given time and key value QuatKey(double time, const glm::quat &value) : mTime(time), mValue(value) { } }; /** * Struct of an animation attached to a bone */ struct BoneAnim { std::string mBoneName; unsigned int mNumPositionKeys; std::vector<VectorKey *> mPositionKeys; unsigned int mNumRotationKeys; std::vector<QuatKey *> mRotationKeys; unsigned int mNumScalingKeys; std::vector<VectorKey *> mScalingKeys; // Default constructors BoneAnim() : mNumPositionKeys(0), mNumRotationKeys(0), mNumScalingKeys(0) { } ~BoneAnim() { } }; // Default constructors Animation(); Animation(std::string name, double duration, double ticksPerSecond, unsigned int numChannels, std::vector<BoneAnim *> channels, unsigned int numMeshNames, std::vector<std::string> names); /** * Constructor from aiAnimation structure * @param animation An aiAnimation */ Animation(aiAnimation *animation); ~Animation(); /** * @return The name of the animation */ const std::string &name() { return mName; } /** * @return The duration of animation in ticks */ double duration() const { return mDuration; } /** * @return The number of ticks per second */ double ticksPerSecond() const { return mTicksPerSecond; } /** * @return The number of channels */ unsigned int nChannels() const { return mNumChannels; } /** * Get a specific channel * @param index Index of channel in array * @return The channel selected */ BoneAnim *getChannel(unsigned int index) { return mChannels[index]; } /** * Set the skeleton of the animation * @param skeleton The skeleton */ void setSkeleton(SkeletonGraph *skeleton) { mSkeleton = skeleton; } /** * @return The skeleton root */ SkeletonGraph::Node* getSkeletonRoot() { return mSkeleton->getRoot(); } /** * @return The skeleton */ SkeletonGraph* getSkeleton() { return mSkeleton; } /** * Return an animation attached to a bone * @param boneName Bone wich attache to the animation * @return Animation attached to the bone */ BoneAnim* getAnimByBoneName(std::string boneName) { std::map<std::string, BoneAnim *>::iterator it = mAnimByBoneName.find(boneName); if(it != mAnimByBoneName.end()) { return it->second; } else { return NULL; } } /** * Update the animation * @param time The current time in second */ void update(double time); private: void updateSkeletonTransform(SkeletonGraph::Node *node); void setAtBindPose(SkeletonGraph::Node *node); glm::mat4x4 computeLocalTransform(BoneAnim *channel); // Name of animation (may be empty) std::string mName; // Duration of animation in ticks double mDuration; // Ticks per seconde (may be 0) double mTicksPerSecond; // Current time double mCurrentTime; // Array of bone animation channels unsigned int mNumChannels; std::vector<BoneAnim *> mChannels; // Skeleton of animation SkeletonGraph *mSkeleton; // Map of anim by bone name std::map<std::string, BoneAnim *> mAnimByBoneName; // list of name mesh unsigned int mNumMeshNames; std::vector<std::string> mMeshNames; }; } // namespace vortex #endif // ANIMATION_H
true
42d5ed89090165b1cb232052c2dabf57cda4cfeb
C++
mihneasaracin/Distributed-CSP
/include/hps-1.0.0/src/buffer/string_output_buffer.h
UTF-8
1,252
3.109375
3
[ "MIT", "Apache-2.0" ]
permissive
#pragma once #include <string> #include "../serializer.h" namespace hps { constexpr size_t STRING_OUTPUT_BUFFER_SIZE = 1 << 10; class StringOutputBuffer { public: StringOutputBuffer(std::string& str) : str(&str) { pos = 0; } void write(const char* content, size_t length) { if (pos + length > STRING_OUTPUT_BUFFER_SIZE) { const size_t n_avail = STRING_OUTPUT_BUFFER_SIZE - pos; write_core(content, n_avail); length -= n_avail; content += n_avail; flush(); if (length > STRING_OUTPUT_BUFFER_SIZE) { str->append(content, length); return; } } write_core(content, length); } void write_char(const char ch) { if (pos == STRING_OUTPUT_BUFFER_SIZE) { flush(); } buffer[pos] = ch; pos++; } void flush() { str->append(buffer, pos); pos = 0; } template <class T> StringOutputBuffer& operator<<(const T& t) { Serializer<T, StringOutputBuffer>::serialize(t, *this); return *this; } private: std::string* const str; char buffer[STRING_OUTPUT_BUFFER_SIZE]; int pos; void write_core(const char* content, const size_t length) { memcpy(buffer + pos, content, length); pos += length; } }; } // namespace hps
true
fe8422270f0260334ece0fe6d03fdbe45d646269
C++
taketakeyyy/atcoder
/abc/231/e.cpp
UTF-8
1,579
2.5625
3
[]
no_license
#define _USE_MATH_DEFINES // M_PI等のフラグ #include <bits/stdc++.h> #define MOD 1000000007 #define COUNTOF(array) (sizeof(array)/sizeof(array[0])) #define rep(i,n) for (int i = 0; i < (n); ++i) #define intceil(a,b) ((a+(b-1))/b) using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<long,long>; // const long long INF = LONG_LONG_MAX - 1001001001001001; const long long INF = 1e18; void chmax(ll& x, ll y) { x = max(x,y); } void chmin(ll& x, ll y) { x = min(x,y); } void solve() { ll N, X; cin >> N >> X; vector<ll> A(N); for(ll i=0; i<N; i++) cin >> A[i]; // 筆算の桁DP // dp[c] := (i桁目まで決めて、)繰り下がりがcのときの最小枚数 vector<ll> dp(2, INF); dp[0] = 0; for(ll i=0; i<N-1; i++) { ll d = A[i+1]/A[i]; // 倍率 ll x = X%d; // Xのi桁目の値 vector<ll> p(2, INF); swap(dp, p); // pからdpへの遷移を書く for(ll c=0; c<2; c++) { // i桁目の繰り下がり for(ll nc=0; nc<2; nc++) { // i+1桁目の繰り下がり ll nx = x + c - nc*d; // A[i]-B[i]の値。 今A[i]+B[i]の値が最小枚数にしたい。nxが正だったらA[i]に、負だったらB[i]にすればOK dp[nc] = min(dp[nc], p[c]+abs(nx)); } } X /= d; } ll ans = INF; for(ll c=0; c<2; c++) { ans = min(ans, dp[c]+X+c); } cout << ans << endl; } int main() { solve(); return 0; }
true
6cd1dcc42476347306e6f62a2ad08025d1e8e215
C++
sabahtalateh/Stepic_CPP
/mod4/les_5_oop/main.cpp
UTF-8
3,773
3.875
4
[]
no_license
#include <iostream> #include <iostream> #include <string> using namespace std; struct Number; struct BinaryOperation; struct Visitor { virtual void visitNumber(Number const *number) = 0; virtual void visitBinaryOperation(BinaryOperation const *binary) = 0; virtual ~Visitor() {} }; struct Expression { virtual double evaluate() const = 0; virtual void visit(Visitor *v) const = 0; virtual ~Expression() {}; }; struct Number : Expression { Number(double value) : value(value) {} ~Number() { delete &value; } double evaluate() const { return value; } double get_value() const { return value; }; void visit(Visitor *v) const { v->visitNumber(this); }; private: double value; }; struct BinaryOperation : Expression { /* Здесь op это один из 4 символов: '+', '-', '*' или '/', соответствующих операциям, которые вам нужно реализовать. */ BinaryOperation(Expression const *left, char op, Expression const *right) : left(left), op(op), right(right) {} ~BinaryOperation() { delete &left; delete &right; delete &op; } double evaluate() const { double result = 0; switch (op) { case '+': result = left->evaluate() + right->evaluate(); break; case '-': result = left->evaluate() - right->evaluate(); break; case '*': result = left->evaluate() * right->evaluate(); break; default: result = left->evaluate() / right->evaluate(); break; } return result; } void visit(Visitor *v) const { v->visitBinaryOperation(this); }; Expression const *get_left() const { return left; } Expression const *get_right() const { return right; } char get_op() const { return op; } private: Expression const *left; Expression const *right; char op; }; struct PrintBinaryOperationVisitor : Visitor { virtual void visitNumber(Number const *number) {}; virtual void visitBinaryOperation(BinaryOperation const *binary) { binary->get_left()->visit(this); cout << binary->get_op() << endl; binary->get_right()->visit(this); }; }; struct PrintVisitor : Visitor { void visitNumber(Number const *number) { cout << number->get_value(); } void visitBinaryOperation(BinaryOperation const *bop) { cout << "("; bop->get_left()->visit(this); cout << bop->get_op(); bop->get_right()->visit(this); cout << ")"; } }; struct Person { public: int get_age() const { return age; } virtual void add_bober() { bober++; } private: int bober; int age; }; struct Student : private Person { public: // virtual void add_bober(){} private: void add_bober(){} }; int main() { Student * s = new Student(); // s->add_bober(); // (1 + 4) * (2 + 3) Expression *onePlusFour = new BinaryOperation(new Number(1), '+', new Number(4)); Expression *twoPlusThree = new BinaryOperation(new Number(2), '+', new Number(3)); Expression *firstMulSecond = new BinaryOperation(onePlusFour, '*', twoPlusThree); Expression *sube = new BinaryOperation(new Number(12), '+', new Number(5)); Expression *sube1 = new BinaryOperation(sube, '*', new Number(5)); // cout << sube->evaluate() << endl; PrintBinaryOperationVisitor bov; sube1->visit(&bov); PrintVisitor pov; firstMulSecond->visit(&pov); return 0; }
true
2daf8ccf81721eafde8edbf21f5b840cc5948e80
C++
tarraschk/Chi-Fu-Mi
/Chi-Fu-Mi/Chi-Fu-Mi/IA.cpp
UTF-8
878
2.78125
3
[]
no_license
// // IA.cpp // Chi-Fu-Mi // // Created by Maxime Alay-eddine on 05/11/12. // Copyright 2012 Ecole Centrale de Nantes. All rights reserved. // #include "IA.h" #include "Coup.h" #include "Pierre.h" #include "Papier.h" #include "Ciseaux.h" #include <sstream> #include <string> #include <iostream> #include <cstdlib> IA::IA() { }; IA::IA(int i) : Joueur(i){ }; Coup& IA::obtenir_coup() const { std::string chaineCoup = ""; int entierJoue = (rand() % 3) + 1; Coup * coupJoue; switch (entierJoue) { case 1: coupJoue = new Pierre(*this); break; case 2: coupJoue = new Papier(*this); break; case 3: coupJoue = new Ciseaux(*this); break; default: std::cout << "Erreur avec l'IA ! Recommencez...\n"; break; } return *coupJoue; };
true
8ceb46f5383132c85de4c10d3265ce32a7ff02c4
C++
kksweet8845/Uva
/Uva-167/Uva-167.cpp
UTF-8
1,133
2.84375
3
[]
no_license
#include<cstdio> #include<cstdlib> #include<cstring> using namespace std; bool visit[8][8]; bool dx[8],dy[8],ds1[15],ds2[15]; int board[8][8]; int ans,max; void backtrack(int x, int y,int c); int main(void) { int k,i,j,l; scanf("%d",&k); for(i=0;i<k;i++) { memset(visit,0,sizeof(visit)); memset(board,0,sizeof(board)); memset(dx,0,sizeof(dx)); memset(dy,0,sizeof(dy)); memset(ds1,0,sizeof(ds1)); memset(ds2,0,sizeof(ds2)); max = ans =0; for(j=0;j<8;j++) { for(l=0;l<8;l++) scanf("%d",&board[j][l]); } backtrack(0,0,0); printf("%5d\n",max); } } void backtrack(int x, int y, int c) { if(y == 8) x++,y=0; if(x == 8 && c==8) { int i,j,ans=0; for(i=0;i<8;i++) for(j=0;j<8;j++) if( visit[i][j] == 1) ans+=board[i][j]; if(max < ans) max = ans; return; } else if(x ==8 && c!=8) return; int d1 = x+y, d2 = x+7-y; if(!dx[x] && !dy[y] && !ds1[d1] && !ds2[d2]) { dx[x] = dy[y] = ds1[d1] = ds2[d2] = true; visit[x][y] = true; backtrack(x,y+1,c+1); dx[x] = dy[y] = ds1[d1] = ds2[d2] = false;; } visit[x][y] = false; backtrack(x,y+1,c); }
true
5460087710f4dd417c753ed1851d1dd6893d6d92
C++
mboroff/V10_TFT_28_Weather_with_Chimes
/getNtp.ino
UTF-8
2,264
2.546875
3
[]
no_license
void getNtp() { // update the system clock // Serial.println(); // Serial.println(F("UpdateNTPTime")); internetCtr++; mysntp.UpdateNTPTime(); // Serial.println(F("Current local time is:")); mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now2, true), &timeExtract); // Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min); Serial.print(F(":"));Serial.print(timeExtract.sec); Serial.print(F("."));Serial.println(timeExtract.millis); // Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year); // Serial.print(F("Day of year: ")); Serial.println(timeExtract.yday + 1); int localHour; int myMonth = timeExtract.mon, myMonthDay = timeExtract.mday, myYear = timeExtract.year; // used for setDate int myHour = timeExtract.hour, myMinute = timeExtract.min, mySecond = timeExtract.sec; // used for setTime int beginDSTDay = (14 - (1 + myYear * 5 / 4) % 7); int beginDSTMonth=3; int endDSTDay = (7 - (1 + myYear * 5 / 4) % 7); int endDSTMonth=11; int workMonth, workDay, workYear, workHour; localHour = myHour; if (((workMonth > beginDSTMonth) && (workMonth < endDSTMonth)) || ((workMonth == beginDSTMonth) && (workDay > beginDSTDay)) || ((workMonth == beginDSTMonth) && (workDay == beginDSTDay) && (myHour >= 2)) || ((workMonth == endDSTMonth) && (workDay < endDSTDay)) || ((workMonth == endDSTMonth) && (workDay == endDSTDay) && (myHour < 1))) { localHour++; } doy = timeExtract.yday + 1; mYhour = localHour; mYminute = timeExtract.min; mYsecond = timeExtract.sec; mYweekDay = timeExtract.wday; mYmonth = timeExtract.mon; mYmonthDay = timeExtract.mday; mYyear = timeExtract.year; setTime(mYhour, mYminute, mYsecond, mYmonthDay, mYmonth, mYyear); #ifdef DEBUG Serial.print("Time has been set to "); Serial.print(hour()); Serial.print(":"); Serial.print(minute()); Serial.print(":"); Serial.print(second()); Serial.print(" "); Serial.print(month()+1); Serial.print("/"); Serial.print(day()); Serial.print("/"); Serial.println(year()); #endif }
true
c2a1015b3691c1139342cfdd3b12033a0f587586
C++
Natureal/bytecamp-shm_backup
/1148/test_AF_UNIX.cpp
UTF-8
2,803
3
3
[]
no_license
#include <sys/time.h> #include <iostream> #include <pthread.h> #include "AF_UNIX_client.h" #include "AF_UNIX_server.h" int size = 32; //每次读 写的大小 char *p = (char*) "socket.address"; int pt_num = 100; //连接server的client数量 AF_UNIX_server ser(p); bool is_end = false; //线程是否能结束 bool time_start = false; //开始计时 long total_traffic = 0L; //传输的总数据大小 long count = 0L; //读写总计次 struct timeval start; struct timeval end; long used_time = 0L; //所用时间 void *new_connect(void *args) { printf("新线程建立\n"); AF_UNIX_client cli(p); cli.client_init(); cli.client_connect(); ser.server_connect(); printf("建立连接\n"); char p_read[size]; char p_write[size]; while(!is_end) { ser.server_write(p_write, size); cli.client_read(p_read, size); if(time_start) { total_traffic += size; count++; } if(count >= 100*1000*1000) { is_end = true; gettimeofday(&end, NULL); used_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000 / 1000; } } printf("读写结束\n"); } int main() { ser.server_init(); pthread_t tids[pt_num]; for(int i=0; i < pt_num; i++) { int ret = pthread_create(&tids[i],NULL, new_connect, NULL); if(ret != 0) { printf("线程创建失败\n"); } } gettimeofday(&start, NULL); time_start = true; while(used_time == 0L); printf("所用时间(s): %ld\n", used_time); printf("数据量(kB): %ld\n", total_traffic / 1024); printf("正常结束\n"); } /* int main() { char p_server_w[size]; char p_server_r[size]; char p_client_w[size]; char p_client_r[size]; long used_time = 0L; //所用时间 long total_traffic = 0L; //传输的总数据大小 struct timeval start; struct timeval end; //建立连接 ser.server_init(); cli.client_init(); cli.client_connect(); ser.server_connect(); //开始计时 gettimeofday(&start, NULL); for(int i=0; i<10000000; i++) { ser.server_write(p_server_w, size); total_traffic += cli.client_read(p_client_r, size); // cli.client_write(p_client_w, size); // total_traffic += ser.server_read(p_server_r, size); } //结束计时 gettimeofday(&end, NULL); used_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - end.tv_usec) / 1000000; printf("每次读写长度:%d \n", size); printf("总用时(s):%ld\n", used_time); printf("总流量(MB):%ld\n", total_traffic / 1024 / 1024); printf("传输速率(MB/s):%ld\n", total_traffic / used_time / 1024 / 1024); } */
true
e1c6c8419f207da7f89edd952c53480bbd9b6a26
C++
green-fox-academy/Boritse
/week-03/day-03/fibonacci/main.cpp
UTF-8
248
3.53125
4
[]
no_license
#include <iostream> int fibonacci(int n){ if(n==0){ return 0; }else if(n==1){ return 1; }else{ n=fibonacci(n-1)+fibonacci(n-2); } return n; } int main() { std::cout << fibonacci(17); return 0; }
true
4a0375cdead602d320bb339b52138e7582d458d4
C++
HekpoMaH/Olimpiads
/Shumen AiB/more2013/Untitled Folder/ru-olymp-roi-2010-tests/6-farmer/src/gen_frombmp/bmp.h
UTF-8
2,359
3.078125
3
[]
no_license
#ifndef _BMP #define _BMP #include <vector> using namespace std; typedef struct { char id1; char id2; char tmp1, tmp2; unsigned int file_size; unsigned int reserved; unsigned int bmp_data_offset; unsigned int bmp_header_size; unsigned int width; unsigned int height; unsigned short int planes; unsigned short int bits_per_pixel; unsigned int compression; unsigned int bmp_data_size; unsigned int h_resolution; unsigned int v_resolution; unsigned int colors; unsigned int important_colors; } bmp_header; /* * Opens a 24 bit true color bmp file and strips its header and its data. * The data starts at location "data", its grouped into 3 layers of "size" * floats of size and they represent the colors blue, green and red. */ void bmpRead(char *str, bmp_header *header, vector<vector<int> > &data) { FILE *bmp_file; unsigned long int size, i, j, rd; unsigned char *ptr; /* Open bmp file and read header */ bmp_file=fopen(str,"rb"); if (bmp_file == NULL) { printf("File \"%s\" couldn't be opened.\n\n", str); exit(EXIT_FAILURE); } i = fread(header,56,1,bmp_file); /* Make header fit into struct */ for (i = 0; i < 51; i++) { ptr = (unsigned char*)(header) + (55 - i); *ptr= *(ptr - 2); } /* Check color depth */ if ((*header).bits_per_pixel != 24) { printf("Sorry, but can handle only 24-bit true color mode pictures.\n\n"); exit(EXIT_FAILURE); } size = (*header).width*(*header).height; fseek(bmp_file, 54, SEEK_SET); /* Read pixel data into color layers */ rd = 0; //cerr << "Width = " << header->width << " Height = " << header->height << "\n"; data.resize(header->height); for (i = 0; i < header->height; i++) { data[header->height - 1 - i].resize(header->width); for (j = 0; j < header->width; j++) { int a1 = (unsigned char)fgetc (bmp_file); int a2 = (unsigned char)fgetc (bmp_file); int a3 = (unsigned char)fgetc (bmp_file); data[header->height - 1 - i][j] = a1 + (a2 << 8) + (a3 << 16); rd += 3; } while ((rd & 3) != 0) { fgetc(bmp_file); rd++; } } fclose(bmp_file); } #endif
true
88640f9ff8267c85374ca4e0edf97ad8e56bb7f0
C++
gondurovad/mp2-lab3-postfix
/Гондурова/base_test/test_tstack.cpp
UTF-8
960
3.859375
4
[]
no_license
#include "stack.h" #include <gtest.h> TEST(TStack, can_create_stack_with_positive_length) { ASSERT_NO_THROW(TStack<int> st(5)); } TEST(TStack, cant_create_stack_with_negative_length) { ASSERT_ANY_THROW(TStack<int> st(-5)); } TEST(TStack, cant_create_too_large_stack) { ASSERT_ANY_THROW(TStack<int> st(MaxStackSize + 1)); } TEST(TStack, can_create_copied_stack) { TStack<int> st(5); ASSERT_NO_THROW(TStack<int> st1(st)); } TEST(TStack, copied_stack_has_its_own_memory) { TStack<int> st1(5); TStack<int> st2(5); st1.Push(1); st2.Push(1); EXPECT_FALSE(&st1 == &st2); } TEST(TStack, created_stack_is_empty) { TStack<int> st(5); EXPECT_EQ(true, st.IsEmpty()); } TEST(TStack, can_push_element) { TStack<int> st(5); st.Push(5); EXPECT_EQ(false, st.IsEmpty()); } TEST(TStack, can_pop_element) { TStack<int> st(5); st.Push(5); EXPECT_EQ(5, st.Pop()); } TEST(TStack, throws_when_pop_empty) { TStack<int> st(5); ASSERT_ANY_THROW(st.Pop()); }
true
df9468113c5c7aa8911552918f4ff4f77719ea6c
C++
gregormey/TestVer
/TestVer/class_BCNS.h
UTF-8
3,070
2.640625
3
[]
no_license
/* * class_BCNS.h * * Created on: 30 nov. 2015 * Author: Susanne Riess, following Vanessa Erbenich * * Implementation of the key exchange protocol described in BCNS14, originally designed by Peikert as a KEM */ #ifndef CLASS_BCNS_H_ #define CLASS_BCNS_H_ #include <stdio.h> #include <NTL/ZZ_p.h> #include <NTL/ZZ_pX.h> #include <NTL/ZZX.h> #include "class_gauss_selected.h" class class_BCNS { private: long n; // The degree of all polynomials in this scheme (especially of f) uint64_t p; // The integer modulus for R_p=Z_p[X]/f NTL::ZZ_pX f,a; // Public parameters of the scheme NTL::ZZ_pX e_ALICE_old, e_ALICE, s_ALICE_old, s_ALICE, p_ALICE_mult, p_ALICE; // Variables to create the secret (s_ALICE) and public key (p_ALICE) of Alice NTL::ZZ_pX e_BOB_old, e_BOB, s_BOB_old, s_BOB, p_BOB_mult, p_BOB; // Variables to create the secret (s_BOB) and public key (p_BOB) of Bob NTL::ZZ_pX e_BOB_2_old, e_BOB_2, v_mult, v; // Variables to create the polynomials e_BOB_2 and v for Bob NTL::ZZX ran, dbl_mult, dbl, f_mod; // Degree n-1 polynomial with entries in -1, 0, 0, 1 uniformely (called ran) and dbl=2*v+ran double p_half, p_quarter, seven_p_quarter; // Stores p/2, p/4 and 7p/4 int rounded_p_half, rounded_3p_half; // Stores rounded (p/2) and (3p/2) NTL::ZZ_pX c, k; // c=cross round(dbl(v)), k=round(dbl(v)) NTL::ZZ_pX two_p_BOB, rec; // rec=2*p_BOB*s_ALICE=two_p_BOB*s_ALICE NTL::ZZX key, rec_mod; // final key=output of rec(rec) class_gauss_selected *gauss; // Stated which Gaussian sampling method is used (the decision is made in class_gauss_selected) public: class_BCNS(long n, uint64_t p, double sigma, long factor, long precision); // Preparation functions void generating_f(); void generating_uniform_polynomial_a(); // Key generation of Alice void generating_Gaussian_error_e_ALICE(); void generating_Gaussian_secret_key_s_ALICE(); void computing_mult_part_of_public_key_p_ALICE(); void computing_add_part_of_public_key_p_ALICE(); // Key generation of Bob void generating_Gaussian_error_e_BOB(); void generating_Gaussian_secret_key_s_BOB(); void computing_mult_part_of_public_key_p_BOB(); void computing_add_part_of_public_key_p_BOB(); // Protocol for Bob void generating_Gaussian_error_e_BOB_2(); void computing_mult_part_of_polynomial_v(); void computing_add_part_of_polynomial_v(); void generating_random_ternary_polynomial_ran(); void computing_mult_part_of_double_v(); void computing_add_part_of_double_v(); //some constants void computing_p_half(); void computing_p_quarter(); void computing_7p_quarter(); void computing_rounded_p_half(); void computing_rounded_3p_half(); //rounding functions void crossrounding_dbl_v(); void rounding_dbl_v(); // Protocol for Alice void computing_two_p_BOB(); void computing_two_p_BOB_s_ALICE(); void computing_key_with_rec(); }; #endif /* CLASS_BCNS_H_ */
true
4bcb6af6e438287766b611ca3e0a3868670df31a
C++
simakovvv/NIIT-work-with-C
/lesson7/main.cpp
UTF-8
985
3.1875
3
[]
no_license
#include "list.h" #include "operations.h" #include <math.h> #include <stdlib.h> #include <stdio.h> #include <time.h> int main() { Node *phead = 0; Node *phead1 = 0; srand(time(0)); for (int i = 0; i < 10; ++i) { add2list(&phead, rand() % 100); add2listSort(&phead1, rand() % 100); } printf("Elements of the list1 (not sort): \n"); print(phead); printf("Sum of elements: %d \n", summ(phead)); printf("Maximum element: %d \n", maxElem(phead)); printf("The sum of the maximum and minimum elements: %d \n", summMinMax(phead)); printf("Mass Sort Indicator: %s \n", (hasSort(phead)) ? "Not sort":"Sort"); printf("Elements of the list2 (sort): \n"); print(phead1); printf("Sum of elements: %d \n", summ(phead1)); printf("Maximum element: %d \n", maxElem(phead1)); printf("The sum of the maximum and minimum elements: %d \n", summMinMax(phead1)); printf("Mass Sort Indicator: %s \n", (hasSort(phead1)) ? "Not sort" : "Sort"); deleteList(phead); deleteList(phead1); }
true
695d713d7ec9284398421fe4271842ad59f91e36
C++
Flowsaiba/HashLib
/CLRTest/Murmur3Test.h
UTF-8
2,870
2.640625
3
[]
no_license
#pragma once namespace CLRTest { ref class Murmur3CSharpTest : TestBaseNonCryptoNonBlock { private: HashLib::IHash^ m_hash = HashLib::HashFactory::Hash32::CreateMurmur3(); protected: virtual int GetHashSize() override { return m_hash->HashSize; } virtual String^ GetTestVectorsDir() override { return "Murmur3_32"; } virtual String^ GetTestName() override { return "Murmur3-CSharp"; } virtual int GetMaxBufferSize() override { return 4; } public: virtual void TransformBytes(array<byte>^ a_data, int a_index, int a_length) override { return m_hash->TransformBytes(a_data, a_index, a_length); } virtual array<byte>^ ComputeBytes(array<byte>^ a_data) override { return m_hash->ComputeBytes(a_data)->GetBytes(); } virtual array<byte>^ TransformFinal() override { return m_hash->TransformFinal()->GetBytes(); } virtual void InitializeHash() override { m_hash->Initialize(); } static void DoTest() { Murmur3CSharpTest^ test = gcnew Murmur3CSharpTest(); test->Test(); } }; ref class Murmur3_128_CSharpTest : TestBaseNonCryptoNonBlock { private: HashLib::IHash^ m_hash = HashLib::HashFactory::Hash128::CreateMurmur3_128(); protected: virtual int GetHashSize() override { return m_hash->HashSize; } virtual String^ GetTestVectorsDir() override { return "Murmur3_128"; } virtual String^ GetTestName() override { return "Murmur3_128-CSharp"; } virtual int GetMaxBufferSize() override { return 16; } public: virtual void TransformBytes(array<byte>^ a_data, int a_index, int a_length) override { return m_hash->TransformBytes(a_data, a_index, a_length); } virtual array<byte>^ ComputeBytes(array<byte>^ a_data) override { return m_hash->ComputeBytes(a_data)->GetBytes(); } virtual array<byte>^ TransformFinal() override { return m_hash->TransformFinal()->GetBytes(); } virtual void InitializeHash() override { m_hash->Initialize(); } static void DoTest() { Murmur3_128_CSharpTest^ test = gcnew Murmur3_128_CSharpTest(); test->Test(); } }; }
true
a56b7b18c9d7086ec04ceb8433c35881e5f3a2a0
C++
Cibi-R/NeuralNetwork
/lib/neural_network/src/neural_net.cpp
UTF-8
792
2.921875
3
[]
no_license
#include <iostream> #include <vector> #include <MyMath.h> #include <NeuralNetwork.h> NN::NeuralNet::NeuralNet(const std::vector<uint32_t> &layer) : Layer(layer) { Z.resize(Layer.size()-1); A.resize(Layer.size()); W.resize(Layer.size()-1); for (int i = 0; i < W.size(); i++) { W[i] = MyMath::Matrix(layer[i], layer[i+1]); /*< Need to set random values to the Weight array. */ W[i].ResetTo(i+1); } } uint8_t NN::NeuralNet::FeedForward(std::vector<std::vector<double>> input) { /*< Input value is stored in A[0] instead of storing in Z[0] */ A[0] = input; for (uint16_t i = 0; i < A.size() - 1; i++) { Z[i] = (A[i] * W[i]); Z[i].Sigmoid(A[i + 1]); } std::cout << A[A.size()-1] << std::endl; return 1; } uint8_t NN::NeuralNet::BackPropagate(void) { return 1; }
true
8c9f19a768451ba93315e68dc9f7c99f378f31cb
C++
FriedrichFrankenstein/A.19-Green
/Programming/Vyacheslav_Diedov/Game/Untitled1.cpp
UTF-8
1,366
3.109375
3
[]
no_license
#include <iostream> #include <string> using namespace std; string binary(unsigned char x){ unsigned char mask=64; string s; for(int i=0; i<7; i++) { s.push_back((x&mask)>0 ? '1':'0'); mask=mask>>1; } return s; } int main() { string l; string a; unsigned char x; while(cin >> x){ l+=binary(x); } for(int i=0;i<l.size();i++) { if(l.at(i)=='0') { if(i==0||l.at(i-1)=='1') { if(i!=0) { a+=" "; a.push_back('0'); a.push_back('0'); a+=" "; } else { a.push_back('0'); a.push_back('0'); a+=" "; } } a.push_back(l.at(i)); } else if(l.at(i)=='1') { if(i==0||l.at(i-1)=='0') { if(i!=0) { a+=" "; a.push_back('0'); a+=" "; } else{ a.push_back('0'); a+=" "; } } a.push_back(l.at(i)); } } for(int i=0;i<a.size();i++) { if(a.at(i)=='1') { a.at(i)='0'; } } cout<<a; return 0; }
true
c197f3589f7b9a88ac3d92a753c70df26f7f42e5
C++
nikopo1/playground
/langs/c-cpp-test-zone/function-p-cpp/function_pointers.cpp
UTF-8
347
3.515625
4
[]
no_license
#include <cstdio> #include <iostream> class MyClass { public: int my_mul(int a, int b) { return a + b; } }; int add(int a, int b) { return a + b; } int (*f) (int, int); int (MyClass::*g) (int, int); int main(void) { MyClass c; f = add; g = &MyClass::my_mul; std::cout<<f(1,1)<<std::endl; std::cout<<(c.*g)(1,1)<<std::endl; return 0; }
true
6eb2c07f7c9653eae8205d890bd94975aff78933
C++
mayankwasekar/Study
/C++/Programs/Classes/dtortest.cpp
UTF-8
1,838
4.15625
4
[]
no_license
#include <iostream> using namespace std; class Interval { public: //Constructor - initializes the object Interval(long s=0, long m=0) { seconds = 60 * m + s; ++count; } void SetTime(long value) { seconds = value; } long GetTime() { return seconds; } //It refers to non-static members so it requires 'this' argument //which points to the object on which the method is invoked //using member selection operator void Print() { if((seconds % 60) < 10) cout << (seconds / 60) << ":0" << (seconds % 60) << endl; else cout << (seconds / 60) << ":" << (seconds % 60) << endl; } //It only refers to static members so it does not require 'this' argument //and it can be invoked on the class using scope resolution operator static int CountInstances() { return count; } //Destructor - finalizes the object ~Interval() { count--; } private: long seconds; //each instance will receive a separate value for this field. static int count; //all instances will share a single value for this field. }; int Interval::count = 0; //allocating memory space for static field. void Run(void) { cout << "Activating Interval instance for john" << endl; Interval john = 200; cout << "John's Interval = "; john.Print(); cout << "Deactivating Interval instance for john" << endl; } int main(void) { cout << "Activating Interval instance for jack" << endl; Interval jack; jack.SetTime(125); cout << "Jack's Interval = "; jack.Print(); Run(); cout << "Activating Interval instance for jeff" << endl; Interval jeff(70, 3); cout << "Jeff's Interval = "; jeff.Print(); cout << "Number of active Interval instances = " << Interval::CountInstances() << endl; cout << "Deactivating Interval instance for jeff" << endl; cout << "Deactivating Interval instance for jack" << endl; }
true
cac91a475fa6717470b9d93b1346a26e2dbbd412
C++
salif45/EscapeGameIrrlicht
/create_window.cpp
UTF-8
5,931
2.578125
3
[]
no_license
// create_window.cpp #include <irrlicht.h> #include <irrMap.h> #include <irrList.h> #include "create_window.h" using namespace irr; namespace ic = irr::core; namespace is = irr::scene; namespace iv = irr::video; namespace ig = irr::gui; /*===========================================================================*\ * create_window * \*===========================================================================*/ ig::IGUIWindow * create_window(ig::IGUIEnvironment *gui,const wchar_t *Question, const wchar_t *Answers_1, const wchar_t *Answers_2, const wchar_t *Answers_3,const wchar_t *Answers_4) //ajouter parametres pour texte et reponses { // La fenêtre ig::IGUIWindow *window = gui->addWindow(ic::rect<s32>(80,50, 560,360), true,L"Questions"); //(420,25, 620,460) // Question gui->addStaticText(Question, ic::rect<s32>(70,30, 430,120), false, false, window);//(22,48, 65,66) // Réponses gui->addButton(ic::rect<s32>(60,130, 200,180), window, WINDOW_BUTTON_1, Answers_1); //(40,74, 140,92) gui->addButton(ic::rect<s32>(290,130, 430,180), window, WINDOW_BUTTON_2, Answers_2); gui->addButton(ic::rect<s32>(60,230, 200,280), window, WINDOW_BUTTON_3, Answers_3); gui->addButton(ic::rect<s32>(290,230, 430,280), window, WINDOW_BUTTON_4, Answers_4); window->setVisible(false); return window; } /*===========================================================================*\ * create_menu * \*===========================================================================*/ void create_menu(ig::IGUIEnvironment *gui) { ig::IGUIContextMenu *submenu; // Les trois entrées principales : ig::IGUIContextMenu *menu = gui->addMenu(); menu->addItem(L"File", -1, true, true); menu->addItem(L"Help", -1, true, true); // Le contenu du menu File : submenu = menu->getSubMenu(0); submenu->addItem(L"New game...", MENU_NEW_GAME); submenu->addSeparator(); submenu->addItem(L"Quit", MENU_QUIT); // Le contenu du menu Help : submenu = menu->getSubMenu(1); submenu->addItem(L"Règles du jeu", MENU_ABOUT); } /*===========================================================================*\ * create_window * \*===========================================================================*/ // static indique que le fonction n'est visible que par ce .cpp ig::IGUIWindow * create_window_not_leaving(ig::IGUIEnvironment *gui) //ajouter parametres pour texte et reponses { // La fenêtre ig::IGUIWindow *window = gui->addWindow(ic::rect<s32>(80,50, 560,360), true, L"MESSAGE"); //(420,25, 620,460) // Texte gui->addStaticText(L"Please enter the code first", ic::rect<s32>(200,48, 560,460), false, false, window);//(22,48, 65,66) window->setVisible(false); return window; } ig::IGUIWindow * create_window_Cadenas(ig::IGUIEnvironment *gui) { // La fenêtre ig::IGUIWindow *window = gui->addWindow(ic::rect<s32>(80,50, 560,360), true, L"Déverouille le cadenas"); //(420,25, 620,460) // Question // Texte gui->addStaticText(L"Quel est le code?", ic::rect<s32>(190,48, 560,460), false, false, window);//(22,48, 65,66) // Réponses // boites combo (listes déroulantes) ig::IGUIComboBox *cbox_1000 = gui->addComboBox(ic::rect<s32>(100,126, 150,142), window, WINDOW_COMBO_BOX_1); cbox_1000->addItem(L"0", WINDOW_COMBO_CHOICE_0); cbox_1000->addItem(L"1", WINDOW_COMBO_CHOICE_1); cbox_1000->addItem(L"2", WINDOW_COMBO_CHOICE_2); cbox_1000->addItem(L"3", WINDOW_COMBO_CHOICE_3); cbox_1000->addItem(L"4", WINDOW_COMBO_CHOICE_4); cbox_1000->addItem(L"5", WINDOW_COMBO_CHOICE_5); cbox_1000->addItem(L"6", WINDOW_COMBO_CHOICE_6); cbox_1000->addItem(L"7", WINDOW_COMBO_CHOICE_7); cbox_1000->addItem(L"8", WINDOW_COMBO_CHOICE_8); cbox_1000->addItem(L"9", WINDOW_COMBO_CHOICE_9); ig::IGUIComboBox *cbox_100 = gui->addComboBox(ic::rect<s32>(180,126, 230,142), window, WINDOW_COMBO_BOX_2); cbox_100->addItem(L"0", WINDOW_COMBO_CHOICE_0); cbox_100->addItem(L"1", WINDOW_COMBO_CHOICE_1); cbox_100->addItem(L"2", WINDOW_COMBO_CHOICE_2); cbox_100->addItem(L"3", WINDOW_COMBO_CHOICE_3); cbox_100->addItem(L"4", WINDOW_COMBO_CHOICE_4); cbox_100->addItem(L"5", WINDOW_COMBO_CHOICE_5); cbox_100->addItem(L"6", WINDOW_COMBO_CHOICE_6); cbox_100->addItem(L"7", WINDOW_COMBO_CHOICE_7); cbox_100->addItem(L"8", WINDOW_COMBO_CHOICE_8); cbox_100->addItem(L"9", WINDOW_COMBO_CHOICE_9); ig::IGUIComboBox *cbox_10 = gui->addComboBox(ic::rect<s32>(260,126, 310,142), window, WINDOW_COMBO_BOX_3); cbox_10->addItem(L"0", WINDOW_COMBO_CHOICE_0); cbox_10->addItem(L"1", WINDOW_COMBO_CHOICE_1); cbox_10->addItem(L"2", WINDOW_COMBO_CHOICE_2); cbox_10->addItem(L"3", WINDOW_COMBO_CHOICE_3); cbox_10->addItem(L"4", WINDOW_COMBO_CHOICE_4); cbox_10->addItem(L"5", WINDOW_COMBO_CHOICE_5); cbox_10->addItem(L"6", WINDOW_COMBO_CHOICE_6); cbox_10->addItem(L"7", WINDOW_COMBO_CHOICE_7); cbox_10->addItem(L"8", WINDOW_COMBO_CHOICE_8); cbox_10->addItem(L"9", WINDOW_COMBO_CHOICE_9); ig::IGUIComboBox *cbox_1 = gui->addComboBox(ic::rect<s32>(340,126, 390,142), window, WINDOW_COMBO_BOX_4); cbox_1->addItem(L"0", WINDOW_COMBO_CHOICE_0); cbox_1->addItem(L"1", WINDOW_COMBO_CHOICE_1); cbox_1->addItem(L"2", WINDOW_COMBO_CHOICE_2); cbox_1->addItem(L"3", WINDOW_COMBO_CHOICE_3); cbox_1->addItem(L"4", WINDOW_COMBO_CHOICE_4); cbox_1->addItem(L"5", WINDOW_COMBO_CHOICE_5); cbox_1->addItem(L"6", WINDOW_COMBO_CHOICE_6); cbox_1->addItem(L"7", WINDOW_COMBO_CHOICE_7); cbox_1->addItem(L"8", WINDOW_COMBO_CHOICE_8); cbox_1->addItem(L"9", WINDOW_COMBO_CHOICE_9); gui->addButton(ic::rect<s32>(200,200, 280,230), window, WINDOW_BUTTON_OK, L"OK"); window->setVisible(false); return window; }
true
26885e02286bdf0c01cad71388e9d87dd53cf407
C++
jakubrospek/C_PlusPlus-Szkola-programowania
/rozdział 8/roz8cw6.cpp
WINDOWS-1250
2,370
4
4
[]
no_license
#include<iostream> #include<cstring> using namespace std; template<typename T> void maxn(T tab[], int rozmiar); template<>void maxn<string>(string tab[], int rozmiar); // <string> to nowy typ zwracany przez funkcj, w tym przypadku mona go pomin bo pierwowzr funkcjii nic nie zwraca - void int main() { int tab1[5] = {1,2,3,4,5}; double tab2[4] = {1.1,1.2,1.3,1.4}; string tab3[3] = {"Ala","ma","kota"}; maxn(tab1, 5); cout << endl; maxn(tab2, 4); cout << endl; maxn(tab3, 3); system("pause"); return 0; } template<typename T> void maxn(T tab[], int rozmiar) { T max = tab[0]; T min = tab[0]; for( int i = 1; i < rozmiar; i++ ) { if( tab[ i ] > max ) max = tab[ i ]; //jeli sprawdzany element tablicy jest wikszy od tego (dotychczas) najwikszego, to on staje si tym najwikszym if( tab[ i ] < min ) min = tab[ i ]; //jeli sprawdzany element tablicy jest mniejszy od tego (dotychczas) najmniejszego, to on staje si tym najmniejszym } cout << "Najwieksza wartosc w tablicy: " << max << endl; cout << "Najmniejsza wartosc w tablicy: " << min << endl; } template<>void maxn<string>(string tab[], int rozmiar) // <string> to nowy typ zwracany przez funkcj, w tym przypadku mona go pomin bo pierwowzr funkcjii nic nie zwraca - void { int max = tab[0].length(); int min = tab[0].length(); string MAX, MIN; for( int i = 1; i < rozmiar; i++ ) { if(tab[i].length() > max) { max = tab[i].length(); //jeli sprawdzany element tablicy jest wikszy od tego (dotychczas) najwikszego, to on staje si tym najwikszym MAX = tab[i]; } if(tab[i].length() < min ) { min = tab[i].length(); //jeli sprawdzany element tablicy jest mniejszy od tego (dotychczas) najmniejszego, to on staje si tym najmniejszym MIN = tab[i]; } } cout << "Najdluzszy lancuch w tablicy: " << MAX << " : " << max << " znaki," << " adres: " << &MAX << endl; cout << "Najkrotszy lancuch w tablicy: " << MIN << " : " << min << " znaki," << " adres: " << &MIN << endl; }
true
18e3b5ff33d119573c5511af792a612c744beaec
C++
Tigerxin/DataStructure
/About-C/基数排序.cpp
GB18030
493
2.921875
3
[]
no_license
#include <stdio.h> // ųʼ typedef struct LinkNode{ char *data; struct LinkNode *next; }LinkNode, *LinkList; // ŷ typedef struct{ // ʽ LinkNode *head,*rear; // еĶͷͶβָ }LinkQueue; /** ҪrУռ临Ӷ=Or һ˷O(n),һռO(r),ܹd˷䣬ռܵʱ临Ӷ=O(d(n+r)) ȶԣȶ */ int main(){ return 0; }
true
983409404f7fe131c81b7383810f85b7b1b8bd7c
C++
Ayeshasaif13/Object-Oriented-Programming-Project
/Library.hpp
UTF-8
3,411
2.640625
3
[]
no_license
#include <fstream> #include<conio.h> #include<stdio.h> #include<process.h> #include<string.h> #include <iomanip> #include <iostream> #include<windows.h> #include"USER.h" #include"student.hpp" #include"book.hpp" #include"filing.hpp" using namespace std; //*************************************************************** // FUCTION TO CALL LIBRARY //**************************************************************** void library() { char ch; system("cls"); cout <<" ******" << endl; cout <<" *********" << endl; cout <<" ***********" << endl; cout <<" **** ****" << endl; cout <<" ***" << endl; cout <<" ***" << endl; cout <<" *** ******************" << endl; cout <<" *** ******************" << endl; cout <<" *** ** ******" << endl; cout <<" **** *** ******" << endl; cout <<" *********** ******" << endl; cout <<" ****** *******" << endl; cout <<" ***************" << endl; cout <<" ***************" << endl; cout << endl; cout << " WELCOME TO GEEKZILLA LIBRARY MANAGEMENT SYSTEM!" << endl; intro(); do { system("cls"); cout<<"\n\n\n\tMAIN MENU"; cout<<"\n\n\t01. BOOK ISSUE"; cout<<"\n\n\t02. BOOK DEPOSIT"; cout<<"\n\n\t03. ADMINISTRATOR MENU"; cout<<"\n\n\t04. LIST ALL BOOKS"; cout<<"\n\n\t05. EXIT"; cout<<"\n\n\tPlease Select Your Option (1-5) "; ch=getche(); switch(ch) { case '1':system("cls"); book_issue(); break; case '2':book_deposit(); break; case '3': system("cls"); cout<<"Enter your admin password(Max length 10):"; char ch; int characterposition; characterposition=0; char Password[10]; while(1){ ch= getch(); if(ch==32||ch==9){ continue; }else if(ch==13){ break; }else if(ch==8){ if(characterposition>0){ characterposition--; Password[characterposition]='\0'; cout<<"\b \b";} }else if(characterposition<10){ Password[characterposition]=ch; characterposition++; cout<<"*"; }else { cout<<"\n Your password length exceeds max password length so only first 10 characters will be stored"; break; } } Password[characterposition]='\0'; if(Password==pass){ admin_menu(); }else{ cout<<endl<<"Wrong Password......."; system("pause"); } break; case '4':display_allb(); break; case '5':return; default :cout<<"\a"; } }while(ch!='5'); return ; } //*************************************************************** // END //***************************************************************
true
807b5206572ee3ff9c6a600221fd635bab7d5367
C++
ngthvan1612/OJCore
/TestModule/HK1/Users/20110299/BAI4.CPP
UTF-8
694
2.9375
3
[]
no_license
#include<stdio.h> void nhap(long a[200][200],long &n,long&m); int NT(long x); void tinh(long a[200][200],long n,long m); void main() { long a[200][200]; long n,m; nhap(a,n,m); tinh(a,n,m); } void nhap(long a[200][200],long &n,long&m) { scanf("%d%d",&n,&m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) scanf("%d",&a[i][j]); } int NT(long x) { int dem=0; for(int i=1;i<=x;i++) if(x%i==0) dem++; if(dem==2) return 1; else return 2; } void tinh(long a[200][200],long n,long m) { int min=100000000; for(int i=0;i<n;i++) { long tong =0; for(int j=0;j<m;j++) { if(NT(a[i][j])==1) tong = tong +a[i][j]; } if(tong < min) min=tong; } printf("%d",min); }
true
d76749e0a8e91808097c415fd22aea57661c121e
C++
coreygamache/senior_design
/sd_sensors/src/ball_sensor.cpp
UTF-8
698
3.078125
3
[]
no_license
//includes #include <ball_sensor.hpp> //#include <ros/ros.h> //default constructor BallSensor::BallSensor(int output) { //run wiringPi setup function wiringPiSetup(); //set output pin setOutputPin(output); } //basic functions //return output pin int BallSensor::getOutputPin() { return this->_outputPin; } //set output pin to given value void BallSensor::setOutputPin(int output) { this->_outputPin = output; } //advanced functions //returns true if a ball is detected, and false otherwise bool BallSensor::ballDetected() { //if sensor output is high then ball is detected, else return false if (digitalRead(this->_outputPin)) return false; else return true; }
true
f6a5d0d7fae1f1d5ce3d0da2ef4c487ec57bdcd6
C++
bananaXu/algorithm
/算法题解/小珂的数学题(组合数学).cpp
GB18030
1,651
3.421875
3
[]
no_license
#include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <cstdlib> #include <stack> #include <cmath> #include <ctype.h> using namespace std; int c(int m, int n) { int i, j; int sum = 1; for (i = 1; i <= n; i ++) { sum = sum*(m-n+i)/i; } return sum; } int main() { char s[30]; int i, j, l, sum; bool f; while (~scanf("%s", &s)) { sum = 1; l = strlen(s)-1; f = true; if (l) { for (i = 1; i <= l; i ++) { if (s[i] <= s[i-1]) { f = false; break; } } } if (!f) { printf("0\n"); } else { for (i = 1; i <= l; i ++) sum += c(26, i); for (i = 0; i <= l; i ++) { for (j = 1; j <= s[i]-'a'-i; j ++) sum += c(25-i-j, l-i); } printf("%d\n", sum); } } return 0; } /* Сѧ ʱƣ1000 ms | ڴƣ65535 KB Ѷȣ3 СϿһֵʾʽдһѸתһ¡ĿϢ£ ֪һֶӦϵ,aʼֵӣַΪ5ͬĻߺַǰĴַͲ a->1 b->2 z->26 ab->27 ac->28 vwxyz->83681 200еݣÿһһֲַϹַַǵģ0Ӧare Ϲ򣬶Ӧ0 ÿн a z cat vwxyz 1 26 0 83681 */
true
8043b5afa90437605c8098cc34ee0fd01ee3193c
C++
thisroot/Cpp-snippets
/arrays/count_of_days_onto_birth.cpp
UTF-8
1,247
3.421875
3
[ "MIT" ]
permissive
//ДНИ РОЖДЕНИЯ. Вводятся номера дней недели, на которые приходятся //дни рождения N из Ваших знакомых в этом году (0-воскр.,1-понедельник,...6-субб.). //Определить : //а) количество дней рождений, приходящихся на каждый из дней недели; //б) номер дня недели, на который приходится максимальное число дней рождения #include <iostream> int main() { int N = 14; int arr[] = {0,2,5,0,2,6,2,2,2,2,4,3,3,7}; int days_of_week[7] = {0,1,2,3,4,5,6}; int counts_of_birth[7] = {0,0,0,0,0,0,0}; int maxd = -1; int ds; for(int i = 0; i != 7; i++) { for(int j=0; j != N; j++) { if(i == arr[j]) { counts_of_birth[i] += 1; } } if(maxd < counts_of_birth[i] ) { maxd = counts_of_birth[i]; } } std::cout << "count birth on to days: "; for(int i = 0; i != 7; i++) { std::cout << i << "-" <<counts_of_birth[i] << " "; if(maxd == counts_of_birth[i]) { ds = i; } } std::cout << std::endl; std::cout << "max count birth on to day: "; std::cout << ds << std::endl; }
true
293704938d924a5c69a7b87b70f05c642b0c6004
C++
acsl-technion/nuevomatch
/src/cpu_core_tools.cpp
UTF-8
3,483
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
/* * MIT License * Copyright (c) 2019 Alon Rashelbach * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/sysinfo.h> #include <stdexcept> #include <cpu_core_tools.h> #include <logging.h> /** * @brief Returns the number of processors currently available in the system */ int cpu_core_tools_get_core_count() { return get_nprocs(); } /** * @brief Return the CPU index in which the current thread is running * @note On error returns -1; */ int cpu_core_tools_get_index_of_current_thread() { pthread_t my_thread = pthread_self(); int cpu_count = cpu_core_tools_get_core_count(); int result; cpu_set_t cpu_set; // Get the current thread cpu_set result = pthread_getaffinity_np(my_thread, sizeof(cpu_set_t), &cpu_set); if (result) { warning("CPU set (thread " << pthread_self() << "): cannot acquire cpu_set affinity: " << strerror(result)); return -1; } // Find the CPU id in which the current thread is running for (int i=0; i<cpu_count; ++i) { if(CPU_ISSET(i, &cpu_set)) { return i; } } // No CPU was found in set (should never get here) return -1; } /** * @brief Sets the thread affinity to run on a single CPU * @param thread The thread * @param cpu_index The desired CPU index * @throws In case of memory allocation error, or thread migration error */ void cpu_core_tools_set_thread_affinity(pthread_t thread, int cpu_index) { int cpu_count = cpu_core_tools_get_core_count(); int dst_cpu_index = cpu_index % cpu_count; info("trying to migrate the thread (" << thread << ") to CPU " << dst_cpu_index << "..."); // Allocate memory for cpu_set object cpu_set_t cpu_set; // Clear the set CPU_ZERO_S(sizeof(cpu_set), &cpu_set); // Set the CPU index CPU_SET_S(dst_cpu_index, sizeof(cpu_set), &cpu_set); // Set the thread affinity int result = pthread_setaffinity_np(thread, sizeof(cpu_set), &cpu_set); if (result) { throw error("cannot set affinity of thread (%" << thread << ") " << strerror(result)); } info("thread (" << thread << ") was migrated to CPU " << dst_cpu_index << " out of " << cpu_count); } /** * @brief Returns the next available physical core index * @param core_idx The current core index */ int cpu_core_tools_get_next_physical_core(int core_idx) { // Important: make sure the hyperthreading is disabled! return (core_idx+1) % cpu_core_tools_get_core_count(); }
true