blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
a964a794248a13638607f70b695c6b441e9699f8
a87c89d0a40965156c659adbc679b64909875cfa
/u24h_serial.cpp
c059e2bfaf83244fbd15934a33df1a6ae21d6844
[]
no_license
Roberto-Hoo/SerialLeArq2
d159ad128a599bb122edbfa8360dfe69e7d6ef1b
9a6db202b10be595beb9e460f9baa1e7b3d48bfe
refs/heads/master
2023-04-24T16:38:34.185164
2021-05-03T16:39:11
2021-05-03T16:39:11
363,995,473
0
0
null
null
null
null
ISO-8859-1
C++
false
false
63,592
cpp
u24h_serial.cpp
#include <math.h> #include <iostream> #include <boost/math/special_functions/beta.hpp> #include <iomanip> #include <time.h> #include <sys/types.h> #include <sys/timeb.h> #include <fstream> #include <string> #pragma warning(disable : 4996) using namespace std; // variáveis globais ifstream ArqLeDadosIniciais, ArqLeData; ofstream ArqEscreve, ArqErro; // arquivo para escrita string line; char data[100], linhaEmBranco[300]; int QtSing; // Quantidade de singularidades const int DIM = 3; // Dimensão do espaço (x,y,z) double b; // Valor do plano inicial bool debug = false; double h; // distância entre os pontos h=0.1 int M1, M2, N1, N2; double R; // -R <= x <= R ; -R <= y <= R =10 int N; // N = R/h int NT; // NT = 2N+1, número total de pontos da matriz interna int tamMatriz; // total de pontos da matriz com as bordas tamMatriz = NT+2 double tF, tF_new, tF_check; // tempo final double refv1; double refv2; double refv3; int AnoI, MesI, DiaI, HoraI, MinI, SegI, MilSegI; int AnoF, MesF, DiaF, HoraF, MinF, SegF, MilSegF; double t0, t; // initial time int no_runs; int Count, new_count; int previous_length; int tipoErro; double time_next_dump; double x_min, x_max; double y_min, y_max; double X1, X2, X3; // x - coordinates of singularities double Y1, Y2, Y3; // y - coordinates of singularities int ii1, ii2, ii3; // i - indices of singularities int jj1, jj2, jj3; // j - indices of singularities double b1, b2, b3; // solution values at the singularities double mass1, mass2, mass3; // mass of initial cones relative to height b int i_ff1a, i_ff1b, i_ff2a, i_ff2b, i_ff3a, i_ff3b; // i - indices of far - field zones int j_ff1a, j_ff1b, j_ff2a, j_ff2b, j_ff3a, j_ff3b; // j - indices of far - field zones int length_i1, length_i2, length_i3; // i - length of far - field zones int length_j1, length_j2, length_j3; // j - length of far - field zones double ff1_value_u0, ff2_value_u0, ff3_value_u0; // average values of u0 in far - field zones double minimum_distance_to_travel_1; double minimum_distance_to_travel_2; double minimum_distance_to_travel_3; double maximum_distance_to_travel_1; double maximum_distance_to_travel_2; double maximum_distance_to_travel_3; double t1_min, t2_min, t3_min; double t1_max, t2_max, t3_max; double d1, d2, d3; double r12, r13, r23; // distância entre os cones double r0; // raios dos cones, r0 = raio dos cones double time_start_cycle, time_finish_cycle; double total_elapsed_time; int i, j, loop, loop1, loop2, loopExterno, loopInterno; const double pi = 3.141592653589793238; double expoente, common_factor; double C1, C2, C3, cc1, cc2, cc3; double Rx, Ry; double expected_b; double total_time_spent = 0; // tempo total programa, feito pelo processador double dt_dump; // time interval elapsed between solution checkings double cfl; // Courant-Friedrichs-Lewy number double dt; // time step length // const int n = 2; // space dimension is 2 (plane) int n; double p; // we are interested in the case: p > n double q; // q = (p-2)/2 double variation_mass_0, variation_sup_0; double min_u0, max_u0; // minimum and maximum values of initial solution over the grid double mass_u0; // mass of initial solution u0 relative to reference height b double variation_mass_; double variation_sup_; double min_u_; double max_u_; double mass_u_; double FP_count, FLOPs; double ** u = NULL; // double ** v = NULL; // double ** u_previous = NULL; // double ** DadosIniciais = NULL; // Localização das singularidades int ** DATE_start_LOG_previous = NULL; int ** DATE_finish_LOG_previous = NULL; double * tF_LOG_previous = NULL; double * ff1_value_LOG_previous = NULL; double * ff2_value_LOG_previous = NULL; double * ff3_value_LOG_previous = NULL; double * min_u_LOG_previous = NULL; double * max_u_LOG_previous = NULL; double * variation_mass_LOG_previous = NULL; double * variation_sup_LOG_previous = NULL; double * elapsed_time_LOG_previous = NULL; double * ff1_value_u_previous = NULL; double * ff2_value_u_previous = NULL; double * ff3_value_u_previous = NULL; double * min_u_previous = NULL; double * max_u_previous = NULL; double * variation_mass_previous = NULL; double * variation_sup_previous = NULL; double * time_per_cycle_previous = NULL; int * DATE_start = NULL; int * DATE_finish = NULL; int no_dumps, new_length; double * ff1_value_u; double * ff2_value_u; double * ff3_value_u; double * variation_mass; double * variation_sup; double * min_u; double * max_u; double * time_per_cycle; clock_t time_start, time_finish; /* struct tm { int tm_sec; // seconds after the minute - [0,59] int tm_min; // minutes after the hour - [0,59] int tm_hour; // hours since midnight - [0,23] int tm_mday; // day of the month - [1,31] int tm_mon; // months since January - [0,11] int tm_year; // years since 1900 int tm_wday; // days since Sunday - [0,6] int tm_yday; // days since January 1 - [0,365] int tm_isdst; // daylight savings time flag }; */ tm * tm_; time_t time_t_; // Funções e Procedimentos void testesIniciais(double **); int I(double); // Converte a coordenada x para o índice i int J(double); // Converte a coordenada y para o índice j double X(int); // Converte o índice i para a coordenada x double Y(int); // Converte o índice j para a coordenada y int LeU24Serial_Input(); void inicializaMatriz(double ** &, double ** &, double ** &, double **); void imprimeMatrizSing(double **); void mostraMatriz(double **); double calculaRaio(double **); //void processa(double ** &, double ** &, double ** &); void Atualiza_U(double ** &, double ** &); double F(double ** &, int, int); double G(double ** &, int, int); void TempoEstimado(double ** &); void farFieldValue(double ** &); double CalculaFarField(int, int, int, int); bool DistFarFieldEstahCorreta(); //void CalculosGerais(double ** &, double ** &); void Dados_Estatisticos(double ** &, double ** &); void SalvaDadosNoArq(int); void GravaErro(int); void Iguala(double ** &, double ** &); void DataEHora(int *&); void DeleteData(); void DeleteData(void) { delete[]u; delete[]v; // delete[]u_previous; // delete[]DadosIniciais; // Localização das singularidades delete[]DATE_start_LOG_previous; delete[]DATE_finish_LOG_previous; delete[]tF_LOG_previous; delete[]ff1_value_LOG_previous; delete[]ff2_value_LOG_previous; delete[]ff3_value_LOG_previous; delete[]min_u_LOG_previous; delete[]max_u_LOG_previous; delete[]variation_mass_LOG_previous; delete[]variation_sup_LOG_previous; delete[]elapsed_time_LOG_previous; delete[]ff1_value_u_previous; delete[]ff2_value_u_previous; delete[]ff3_value_u_previous; delete[]min_u_previous; delete[]max_u_previous; delete[]variation_mass_previous; delete[]variation_sup_previous; delete[]time_per_cycle_previous; delete[]DATE_start; delete[]DATE_finish; delete[]ff1_value_u; delete[]ff2_value_u; delete[]ff3_value_u; delete[]variation_mass; delete[]variation_sup; delete[]min_u; delete[]max_u; delete[]time_per_cycle; } void DataEHora(int * & DataHora) { // get current time in format of time_t time_t_ = time(NULL); // convert time_t to tm tm_ = localtime(&time_t_); DataHora[0] = 1900 + tm_->tm_year; DataHora[1] = 1 + tm_->tm_mon; DataHora[2] = tm_->tm_mday; DataHora[3] = tm_->tm_hour; DataHora[4] = tm_->tm_min; DataHora[5] = tm_->tm_sec; struct timeb tmb; ftime(&tmb); DataHora[6] = tmb.millitm; } // u_previous:= u void Iguala(double ** &u_previous, double ** &u) { for (int i = 0; i <= NT + 1; i++) for (int j = 0; j <= NT + 1; j++) u_previous[i][j] = u[i][j]; } // Programa principal int main() { /* // ATUALIZA 2000 VEZES */ for (int n = 1; n <= 2000; n++) { time_start = clock(); // Dispara o cronometro DATE_start = new int[7]; DataEHora(DATE_start); tipoErro = LeU24Serial_Input(); if (tipoErro == 1) { // Arq. u24h_serial_INPUT_cpp.txt não existe GravaErro(1); // Erro: Arq. u24h_serial_INPUT_cpp.txt não existe cout << "\n\n Tecle uma letra e apos Enter para finalizar...\n"; getchar(); return 1; // Encerra o programa } else if (tipoErro == 2) { // previous_length != Count GravaErro(2); // Erro: previous_length != Count cout << "\n\n Tecle uma letra e apos Enter para finalizar...\n"; getchar(); return 2; // Encerra o programa } SalvaDadosNoArq(1); // Cria o arq."u24h_serial_input_previous_cpp.txt" /* !------------------------------------------------------------- !------------------------------------------------------------- !---------------------------------------------------------- ! Setting new t0, tF: !---------------------------------------------------------- */ tF_new = tF + 1; if (tF < 1.1) tF_new = 2; if (tF < 0.6) tF_new = 1; if (tF < 0.3) tF_new = 0.5; if (tF < 0.15) tF_new = 0.2; //<----eliminate if (tF < 0.05) tF_new = 0.1; //<----eliminate t0 = tF; tF = tF_new; /* !---------------------------------------------------------- ! ALLOCATING the new solution-statistics arrays: !---------------------------------------------------------- */ no_dumps = round((tF - t0) / dt_dump) + 10; // !<--- 10 is added here for CAUTION!! // ! (correct value will be given to "no_dumps" // ! AFTER all dumps have been done and counted) new_length = previous_length + no_dumps; // <--- this estimate will NOT actually be used ff1_value_u = new double[no_dumps]; ff2_value_u = new double[no_dumps]; ff3_value_u = new double[no_dumps]; variation_mass = new double[no_dumps]; variation_sup = new double[no_dumps]; min_u = new double[no_dumps]; max_u = new double[no_dumps]; time_per_cycle = new double[no_dumps]; // !--------------------------------------------------- // !---------------------------------------------------------- // ! Extending solution values to extended grid: // !---------------------------------------------------------- // Atualiza as bordas. Se supõe que a borda tem o mesmo valor // que a fronteira do quadrado interno // Atualiza a borda inferior e superior for (int i = 1; i <= NT; i++) { u[i][0] = u[i][1]; u[i][NT + 1] = u[i][NT]; } // Atualiza a borda esquerda e direita for (int j = 1; j <= NT; j++) { u[0][j] = u[1][j]; u[NT + 1][j] = u[NT][j]; } // Atualiza os 4 cantos do quadrado externo u[0][0] = u[1][1]; u[0][NT + 1] = u[1][NT]; u[NT + 1][0] = u[NT][1]; u[NT + 1][NT + 1] = u[NT][NT]; cout << "\n"; cout << "\n *********************************************************"; cout << "\n Computing ..."; cout << "\n *********************************************************"; cout << "\n"; time_next_dump = t0 + dt_dump; t = t0; Iguala(u_previous, u); dt = cfl * h * h; new_count = 0; no_runs = no_runs + 1; /* !---------------------------------------------------------------------- !---------------------------------------------------------------------- ! MAIN COMPUTATION SECTION !---------------------------------------------------------------------- !---------------------------------------------------------------------- */ tF_check = tF - dt / 4; loopInterno = round(dt_dump / dt); loopExterno = round(((tF - t0) / dt) / loopInterno); if (debug) { cout << "\nloopExterno=" << loopExterno; cout << "\nloopInterno=" << loopInterno; } loop1 = 0; for (int i = 1; i <= loopExterno; i++) { time_start_cycle = clock(); // Dispara o cronometro if (debug) { loop1++; loop2 = 0; cout << "\ntF_check=" << tF_check; cout << "\ntime_next_dump=" << time_next_dump; } //********************************************************** // // ATUALIZAÇÃO DE U - PARTE PRINCIPAL DO PROGRAMA // //********************************************************** for (int j = 1; j <= loopInterno; j++) { t = t + dt; Atualiza_U(u, v); //Atualização de U <---- if (debug) { cout << "\nt=" << t; loop2++; } } if (debug) { cout << "\nloop2=" << loop2; } // !--- time to save solution statistics: time_finish_cycle = clock(); new_count = new_count + 1; time_per_cycle[new_count] = time_finish_cycle - time_start_cycle; // !--- solution far-field values: ff1_value_u[new_count] = CalculaFarField(i_ff1a, i_ff1b, j_ff1a, j_ff1b); ff2_value_u[new_count] = CalculaFarField(i_ff2a, i_ff2b, j_ff2a, j_ff2b); ff3_value_u[new_count] = CalculaFarField(i_ff3a, i_ff3b, j_ff3a, j_ff3b); Dados_Estatisticos(u_previous, u); // !-------------------------------------------------- // saving minimum and maximum solution values at current time: min_u[new_count] = min_u_; max_u[new_count] = max_u_; // computing supnorm of solution variation from previous u: variation_sup[new_count] = variation_sup_; // maxval(abs(u - u_previous)); // ! computing mass of solution variation from previous u: variation_mass[new_count] = variation_mass_; // sum(u - u_previous) * h * * 2; // ! current solution values become previous solution values // ! for the next iteration cycle: Iguala(u_previous, u); time_next_dump = time_next_dump + dt_dump; } /* !---------------------------------------------------------------------- !---------------------------------------------------------------------- ! END OF MAIN COMPUTATION SECTION !---------------------------------------------------------------------- !---------------------------------------------------------------------- */ if (debug) { cout << "\nloop1=" << loop1; } total_elapsed_time = (clock() - time_start) / (double)CLOCKS_PER_SEC; cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(3); cout << "\n Tempo de processamento de todo o programa: " << total_elapsed_time << " segundos"; cout << "\n ------------------------------------------------------------"; cout << "\n TOTAL elapsed time: "; cout << total_elapsed_time << " segundos\n"; cout << "\n ------------------------------------------------------------"; cout << "\n SUCCESSFUL EXECUTION "; cout << "\n ------------------------------------------------------------"; cout << "\n ------------------------------------------------------------"; // total_elapsed_time = sum( time_per_cycle ); Count = Count + new_count; // updating "count" (= size of new total statistics arrays) no_dumps = new_count; // this puts to "no_dumps" the final, CORRECT value of the // actual number of dumps (which was ESTIMATED from above // by the previous value of no_dumps) /* !-------------------------------------------------------------------------- !-------------------------------------------------------------------------- ! SAVING OUTPUT DATA TO DISK ! (this data will serve as new input data for the program ! "u24h_serial.f90" on its next execution) !-------------------------------------------------------------------------- !-------------------------------------------------------------------------- */ SalvaDadosNoArq(2); // Cria o arquivo "u24h_serial_INPUT_cpp.txt" /* !------------------------------------------------------- ! Generating LOG FILE for current run: !------------------------------------------------------- */ SalvaDadosNoArq(3); // Cria o arquivo "u24h_serial_LOG_cpp.txt" SalvaDadosNoArq(4); // Cria o arquivo "u24h_serial_MatLab_cpp.txt" DeleteData(); } cout << "\n\n Tecle uma letra e apos Enter para finalizar...\n"; getchar(); return 0; } // end main void GravaErro(int erro) { cout << "\n***********************************************"; cout << "\n ERROR: see file \"u24h_serial_ERROR_cpp.txt\" "; cout << "\n for explanation "; if (erro == 2) { cout << "\n"; cout << "\n Count = " << Count; cout << "\n previous_length = " << previous_length; cout << "\n"; } cout << "\n ***** EXECUTION HAS BEEN ABORTED *********** "; cout << "\n***********************************************"; ArqErro.open("u24h_serial_ERROR_cpp.txt", ios::out); // ios::out (write) if (ArqErro.is_open()) { // get current time in format of time_t time_t_ = time(NULL); // convert time_t to tm tm_ = localtime(&time_t_); AnoF = 1900 + tm_->tm_year; MesF = 1 + tm_->tm_mon; DiaF = tm_->tm_mday; HoraF = tm_->tm_hour; MinF = tm_->tm_min; SegF = tm_->tm_sec; struct timeb tmb; ftime(&tmb); MilSegF = tmb.millitm; ArqErro << "\n"; ArqErro << "\n *******************************************************"; ArqErro << "\n ERROR ***** ERROR ***** ERROR ***** ERROR ***** ERROR "; ArqErro << "\n *******************************************************"; ArqErro << "\n"; ArqErro << "\n DAY : " << DiaF << " / " << MesF << " / " << AnoF; ArqErro << "\n TIME: " << HoraF << " : " << MinF << " : " << SegF; ArqErro << "\n"; ArqErro << "\n *******************************************************"; ArqErro << "\n ERROR CONDITION:"; if (erro == 1) { ArqErro << "\n FILE u24h_serial_INPUT_cpp.txt NOT FOUND"; } else if (erro == 2) { ArqErro << "\n variable \"Count\" should be equal to "; ArqErro << "\n variable \"previous_length\""; ArqErro << "\n"; ArqErro << "\n Count = " << Count; ArqErro << "\n previous_length = " << previous_length; } ArqErro << "\n"; ArqErro << "\n EXECUTION WILL TERMINATE"; ArqErro << "\n"; ArqErro << "\n ********************************************************"; ArqErro << "\n"; ArqErro << "\n"; ArqErro.close(); } else cout << "Nao foi possivel abrir o arquivo \"u24h_serial_ERROR_cpp.txt\""; } void SalvaDadosNoArq(int arq) { DATE_finish = new int[7]; DataEHora(DATE_finish); if (arq == 1) { ArqEscreve.open("u24h_serial_input_previous_cpp.txt", ios::out); // ios::out (write) } else if (arq == 2) { ArqEscreve.open("u24h_serial_INPUT_cpp.txt", ios::out); // ios::out (write) } else if (arq == 3) { ArqEscreve.open("u24h_serial_LOG_cpp.txt", ios::out); // ios::out (write) } else if (arq == 4) { ArqEscreve.open("u24h_serial_MatLab_cpp.txt", ios::out); // ios::out (write) } if (ArqEscreve.is_open()) { if (arq == 3) { // "u24h_serial_LOG_cpp.txt" ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n ***************************************************************************"; ArqEscreve << "\n * LOG DATA for u24h_serial.f90 *"; ArqEscreve << "\n ***************************************************************************"; ArqEscreve << "\n"; ArqEscreve << "\n"; // <<fixed<<setprecision(1); ArqEscreve << "\n M1 = " << M1 << " M2 = " << M2; ArqEscreve << "\n N1 = " << N1 << " N2 = " << N2; ArqEscreve << "\n" << scientific; ArqEscreve << "\n x_min = " << x_min << " x_max = " << x_max; ArqEscreve << "\n y_min = " << y_min << " y_max = " << y_max; ArqEscreve << "\n"; ArqEscreve << "\n refv1 = " << refv1; ArqEscreve << "\n refv2 = " << refv2; ArqEscreve << "\n refv3 = " << refv3; ArqEscreve << "\n"; ArqEscreve << "\n dimension n = " << n; ArqEscreve << "\n"; ArqEscreve << "\n p = " << p; ArqEscreve << "\n"; // <<setprecision(4); ArqEscreve << "\n h = " << h; ArqEscreve << "\n dt = " << dt; ArqEscreve << "\n dt_dump = " << dt_dump; ArqEscreve << "\n cfl = " << cfl; ArqEscreve << "\n"; ArqEscreve << "\n Singularities:"; ArqEscreve << "\n x1 = " << X1 << " y1 = " << Y1; ArqEscreve << "\n x2 = " << X2 << " y2 = " << Y2; ArqEscreve << "\n x3 = " << X3 << " y3 = " << Y3; ArqEscreve << "\n b1 = " << b1; ArqEscreve << "\n b2 = " << b2; ArqEscreve << "\n b3 = " << b3; ArqEscreve << "\n"; ArqEscreve << "\n value of b used: " << b; ArqEscreve << "\n expected value of b: " << (b1 + b2 + b3) / 3; ArqEscreve << "\n"; ArqEscreve << "\n current value of tF: " << tF; ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n ***************************************************************************"; ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n"; /* !----------------------------------------------------------------------- ! TABLE 1: Run no., DATE/TIME (start & finish), tF, FP count, FLOP/s: !----------------------------------------------------------------------- */ ArqEscreve << "\n |-----------|---------------------|----------------|----------------|----------------|"; ArqEscreve << "\n | | | | | |"; ArqEscreve << "\n | Run no. | DATE / TIME | tF | FP count | FLOP/s |"; ArqEscreve << "\n | | | | | |"; ArqEscreve << "\n |-----------|---------------------|----------------|----------------|----------------|"; i = 0; FP_count = 20 * (M2 - M1 + 1) * (N2 - N1 + 1) * dt_dump / dt; FLOPs = FP_count / elapsed_time_LOG_previous[0]; if (debug) { cout << "\nFP_count= " << FP_count; cout << "\nFLOPs= " << FLOPs; cout << "\ntF_LOG_previous[0]= " << tF_LOG_previous[i]; } ArqEscreve << "\n | | " << setw(2) << setfill('0') << DATE_start_LOG_previous[i][2] << "/" << setw(2) << DATE_start_LOG_previous[i][1] << "/" << DATE_start_LOG_previous[i][0]; ArqEscreve << " " << setw(2) << DATE_start_LOG_previous[i][3] << ":" << setw(2) << DATE_start_LOG_previous[i][4] << ":" << setw(2) << DATE_start_LOG_previous[i][5]; ArqEscreve << " | | | |"; ArqEscreve << "\n | " << setw(3) << i << " | " << setw(2) << DATE_finish_LOG_previous[i][2] << "/" << setw(2) << DATE_finish_LOG_previous[i][1] << "/" << DATE_finish_LOG_previous[i][0]; ArqEscreve << " " << setw(2) << DATE_finish_LOG_previous[i][3] << ":" << setw(2) << DATE_finish_LOG_previous[i][4] << ":" << setw(2) << DATE_finish_LOG_previous[i][5]; ArqEscreve << " | " << scientific << setprecision(7) << tF_LOG_previous[i] << " | " << FP_count << " | " << FLOPs << " | "; ArqEscreve << "\n |-----------|---------------------|----------------|----------------|----------------|"; for (int i = 1; i <= no_runs - 1; i++) { FP_count = 20 * (M2 - M1 + 1) * (N2 - N1 + 1) * (tF_LOG_previous[i] - tF_LOG_previous[i - 1]) / dt; FLOPs = FP_count / elapsed_time_LOG_previous[i]; ArqEscreve << "\n | | " << setw(2) << setfill('0') << DATE_start_LOG_previous[i][2] << "/" << setw(2) << DATE_start_LOG_previous[i][1] << "/" << DATE_start_LOG_previous[i][0]; ArqEscreve << " " << setw(2) << DATE_start_LOG_previous[i][3] << ":" << setw(2) << DATE_start_LOG_previous[i][4] << ":" << setw(2) << DATE_start_LOG_previous[i][5]; ArqEscreve << " | | | |"; ArqEscreve << "\n | " << setw(3) << i << " | " << setw(2) << DATE_finish_LOG_previous[i][2] << "/" << setw(2) << DATE_finish_LOG_previous[i][1] << "/" << DATE_finish_LOG_previous[i][0]; ArqEscreve << " " << setw(2) << DATE_finish_LOG_previous[i][3] << ":" << setw(2) << DATE_finish_LOG_previous[i][4] << ":" << setw(2) << DATE_finish_LOG_previous[i][5]; ArqEscreve << " | " << scientific << setprecision(7) << tF_LOG_previous[i] << " | " << FP_count << " | " << FLOPs << " | "; ArqEscreve << "\n |-----------|---------------------|----------------|----------------|----------------|"; } // i = no_runs; FP_count = 20 * (M2 - M1 + 1) * (N2 - N1 + 1) * (tF - tF_LOG_previous[no_runs - 1]) / dt; FLOPs = FP_count / total_elapsed_time; ArqEscreve << "\n | | " << setw(2) << setfill('0') << DATE_start[2] << "/" << setw(2) << DATE_start[1] << "/" << DATE_start[0]; ArqEscreve << " " << setw(2) << DATE_start[3] << ":" << setw(2) << DATE_start[4] << ":" << setw(2) << DATE_start[5]; ArqEscreve << " | | | |"; ArqEscreve << "\n | " << setw(3) << no_runs << " | " << setw (2) << DATE_finish[2] << "/" << setw(2) << DATE_finish[1] << "/" << DATE_finish[0]; ArqEscreve << " " << setw(2) << DATE_finish[3] << ":" << setw(2) << DATE_finish[4] << ":" << setw(2) << DATE_finish[5]; ArqEscreve << " | " << scientific << setprecision(7) << tF << " | " << FP_count << " | " << FLOPs << " | "; ArqEscreve << "\n |-----------|---------------------|----------------|----------------|----------------|"; /* !----------------------------------------------------------------------- ! TABLE 2: Run no., ff1_value, ff2_value, ff3_value, elapsed time: !----------------------------------------------------------------------- */ ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; ArqEscreve << "\n | | | | | |"; ArqEscreve << "\n | Run no. | ffv1 | ffv2 | ffv3 | elapsed time |"; ArqEscreve << "\n | | | | | (seconds) |"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; for (int i = 0; i <= no_runs - 1; i++) { ArqEscreve << "\n | " << setw(3) << setfill(' ') << i << " | " << scientific << setprecision(7) << ff1_value_LOG_previous[i] << " | " << ff2_value_LOG_previous[i] << " | " << ff3_value_LOG_previous[i] << " | " << elapsed_time_LOG_previous[i] << " | "; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; } // i = no_runs; ArqEscreve << "\n | " << setw(3) << no_runs << " | " << ff1_value_u[new_count] << " | " << ff2_value_u[new_count] << " | " << ff3_value_u [new_count] << " | " << total_elapsed_time << " | "; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; /* !----------------------------------------------------------------------- ! TABLE 3: Run no., variation_mass, variation_sup, min_u, max_u: !----------------------------------------------------------------------- */ ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; ArqEscreve << "\n | | | | | |"; ArqEscreve << "\n | Run no. | variation_mass | variation_sup | min_u | max_u |"; ArqEscreve << "\n | | | | | |"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; for (int i = 0; i <= no_runs - 1; i++) { ArqEscreve << "\n | " << setw(3) << setfill(' ') << i << " |" << scientific << setprecision(6) << setw (15) << variation_mass_LOG_previous[i] << " |" << setw(15) << variation_sup_LOG_previous[i] << " |" << setw(15) << min_u_LOG_previous[i] << " |" << setw(15) << max_u_LOG_previous[i] << " |"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; } // i = no_runs; ArqEscreve << "\n | " << setw(3) << no_runs << " |" << setw (15) << variation_mass[new_count] << " |" << setw(15) << variation_sup[new_count] << " |" << setw(15) << min_u[new_count] << " |" << setw(15) << max_u[new_count] << " |"; ArqEscreve << "\n |-----------|----------------|----------------|----------------|----------------|"; } // end arq=3: "u24h_serial_LOG_cpp.txt" else if (arq == 4) {//arq=4: "u24h_serial_MatLab_cpp.txt" ArqEscreve << setw(25) << M1 << setw(25) << M2; ArqEscreve << "\n" << setw(25) << N1 << setw(25) << N2; ArqEscreve << "\n" << setw(25) << scientific << setprecision(16) << n; ArqEscreve << "\n" << setw(25) << p; ArqEscreve << "\n" << setw(25) << h; ArqEscreve << "\n\n" << setprecision(16); for (int i = 1; i <= NT; i++) { for (int j = 1; j <= NT; j++) { ArqEscreve << setw(25) << u[i][j]; // current initial state if (j % 20 == 0) ArqEscreve << "\n"; } ArqEscreve << "\n"; } } else { // arq=1 ou arq=2 ArqEscreve << setw(25) << M1 << setw(25) << M2; ArqEscreve << "\n" << setw(25) << N1 << setw(25) << N2; ArqEscreve << "\n" << setw(25) << scientific << setprecision(16) << n; ArqEscreve << "\n" << setw(25) << p; ArqEscreve << "\n" << setw(25) << h; ArqEscreve << "\n" << setw(25) << cfl; ArqEscreve << "\n" << setw(25) << x_min << setw(25) << x_max; ArqEscreve << "\n" << setw(25) << y_min << setw(25) << y_max; ArqEscreve << "\n" << setw(25) << t0 << setw(25) << tF << setw(25) << dt_dump; ArqEscreve << "\n" << setw(25) << X1 << setw(25) << X2 << setw(25) << X3; ArqEscreve << "\n" << setw(25) << Y1 << setw(25) << Y2 << setw(25) << Y3; ArqEscreve << "\n" << setw(25) << ii1 << setw(25) << ii2 << setw(25) << ii3; ArqEscreve << "\n" << setw(25) << jj1 << setw(25) << jj2 << setw(25) << jj3; ArqEscreve << "\n" << setw(25) << b1 << setw(25) << b2 << setw(25) << b3; ArqEscreve << "\n" << setw(25) << b; ArqEscreve << "\n" << setw(25) << refv1 << setw(25) << refv2 << setw(25) << refv3; ArqEscreve << "\n" << setw(25) << Count; ArqEscreve << "\n" << setw(25) << no_runs; ArqEscreve << "\n" << setw(5) << i_ff1a << setw(5) << i_ff1b << setw (5) << i_ff2a << setw(5) << i_ff2b << setw(5) << i_ff3a << setw (5) << i_ff3b; ArqEscreve << "\n" << setw(5) << j_ff1a << setw(5) << j_ff1b << setw (5) << j_ff2a << setw(5) << j_ff2b << setw(5) << j_ff3a << setw (5) << j_ff3b; ArqEscreve << "\n" << setw(5) << length_i1 << setw(5) << length_i2 << setw(5) << length_i3; ArqEscreve << "\n" << setw(5) << length_j1 << setw(5) << length_j2 << setw(5) << length_j3; ArqEscreve << "\n" << setw(25) << ff1_value_u0 << setw(25) << ff2_value_u0 << setw(25) << ff3_value_u0; ArqEscreve << "\n" << setw(25) << min_u0 << setw(25) << max_u0; ArqEscreve << "\n" << setw(25) << mass_u0; ArqEscreve << "\n" << setw(25) << t1_min << setw(25) << t2_min << setw(25) << t3_min; ArqEscreve << "\n" << setw(25) << t1_max << setw(25) << t2_max << setw(25) << t3_max; ArqEscreve << "\n"; if (arq == 2) { // arq == 2 <--- u24h_serial_INPUT_cpp.txt" no_runs--; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n"; for (int j = 0; j < 7; j++) ArqEscreve << setw(5) << DATE_start_LOG_previous[i][j]; } if (arq == 2) { ArqEscreve << "\n"; for (int j = 0; j < 7; j++) ArqEscreve << setw(5) << DATE_start[j]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n"; for (int j = 0; j < 7; j++) ArqEscreve << setw(5) << DATE_finish_LOG_previous[i][j]; } if (arq == 2) { ArqEscreve << "\n"; for (int j = 0; j < 7; j++) ArqEscreve << setw(5) << DATE_finish[j]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << tF_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << tF; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << ff1_value_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << ff1_value_u[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << ff2_value_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << ff2_value_u[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << ff3_value_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << ff3_value_u[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << variation_mass_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << variation_mass[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << variation_sup_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << variation_sup[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << min_u_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << min_u[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << max_u_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << max_u[new_count]; } for (int i = 0; i <= no_runs; i++) { ArqEscreve << "\n" << setw(25) << elapsed_time_LOG_previous[i]; } if (arq == 2) { ArqEscreve << "\n" << total_elapsed_time; } ArqEscreve << "\n\n" << setprecision(16); for (int i = 1; i <= NT; i++) { for (int j = 1; j <= NT; j++) { ArqEscreve << setw(25) << u[i][j]; // current initial state if (j % 20 == 0) ArqEscreve << "\n"; } ArqEscreve << "\n"; } // Saving SOLUTION STATISTICS variables : if (arq == 2) { new_length = previous_length + new_count; // ! <--- same as newly updated value of "count" ArqEscreve << "\n"; ArqEscreve << "\n" << setw(5) << new_length; // ! <--- new_length = previous_length + new_count ArqEscreve << "\n"; } else if (arq == 1) { ArqEscreve << "\n"; ArqEscreve << "\n" << setw(5) << previous_length; ArqEscreve << "\n"; } for (int i = 0; i <= previous_length; i++) { ArqEscreve << "\n" << setw(25) << ff1_value_u_previous[i] << setw(25) << ff2_value_u_previous[i] << setw(25) << ff3_value_u_previous[i]; } if (arq == 2) { for (int i = 1; i <= new_count; i++) { ArqEscreve << "\n" << setw(25) << ff1_value_u[i] << setw(25) << ff2_value_u[i] << setw(25) << ff3_value_u[i]; } } // linha 928 Fortran for (int i = 0; i <= previous_length; i++) { ArqEscreve << "\n" << setw(25) << variation_mass_previous[i] << setw(25) << variation_sup_previous[i]; } if (arq == 2) { for (int i = 1; i <= new_count; i++) { ArqEscreve << "\n" << setw(25) << variation_mass[i] << setw (25) << variation_sup[i]; } } for (int i = 0; i <= previous_length; i++) { ArqEscreve << "\n" << setw(25) << min_u_previous[i] << setw(25) << max_u_previous[i]; } if (arq == 2) { for (int i = 1; i <= new_count; i++) { ArqEscreve << "\n" << setw(25) << min_u[i] << setw(25) << max_u[i]; } } for (int i = 0; i <= previous_length; i++) { ArqEscreve << "\n" << setw(25) << time_per_cycle_previous[i]; } if (arq == 2) { for (int i = 1; i <= new_count; i++) { ArqEscreve << "\n" << setw(25) << time_per_cycle[i]; } } if (arq == 2) { no_runs++; // Conserta a linha 720 // if (arq == 2) { // no_runs--; } } // End arq=2 ou arq=1 ArqEscreve.close(); } // Arquivo is Open else { // Some problem with arquivo if (arq == 1) { cout << "Nao foi possivel abrir u24h_serial_input_previous_cpp.txt"; } else if (arq == 2) { cout << "Nao foi possivel abrir u24h_serial_INPUT_cpp.txt"; } else if (arq == 3) { cout << "Nao foi possivel abrir u24h_serial_LOG_cpp.txt"; } else if (arq == 4) { cout << "Nao foi possivel abrir u24h_serial_MatLab_cpp.txt"; } } } /* Calcula: min_u0 = minval( u_previous ); max_u0 = maxval( u_previous ); mass_u0 = sum( u_previous - b )*h**2; variation_mass_0 = sum( u(M1:M2,N1:N2) - u_previous )*h**2; variation_sup_0 = maxval( abs( u(M1:M2,N1:N2) - u_previous ) ); void CalculosGerais(double ** &u_previous, double ** &u) { min_u0 = u[1][1]; max_u0 = u[1][1]; mass_u0 = 0; variation_mass_0 = 0; variation_sup_0 = abs(u[1][1] - u_previous[1][1]); for (int i = 1; i <= NT; i++) { for (int j = 1; j <= NT; j++) { // Descobre o mínimo e o máximo if (u_previous[i][j] < min_u0) min_u0 = u_previous[i][j]; else if (u_previous[i][j] > max_u0) max_u0 = u_previous[i][j]; if (abs(u[i][j] - u_previous[i][j]) > variation_sup_0) variation_sup_0 = abs(u[i][j] - u_previous[i][j]); mass_u0 = mass_u0 + u_previous[i][j] - b; variation_mass_0 = variation_mass_0 + u[i][j] - u_previous[i][j]; } } mass_u0 = mass_u0 * h * h; variation_mass_0 = variation_mass_0 * h * h; cout << "\nvariation_mass_0 = " << variation_mass_0; cout << "\nvariation_sup_0 = " << variation_sup_0; } */ /* Calcula: min_u = minval( u_previous ); max_u = maxval( u_previous ); mass_u = sum( u_previous - b )*h**2; variation_mass = sum( u(M1:M2,N1:N2) - u_previous )*h**2; variation_sup = maxval( abs( u(M1:M2,N1:N2) - u_previous ) ); */ void Dados_Estatisticos(double ** &u_previous, double ** &u) { min_u_ = u[1][1]; max_u_ = u[1][1]; variation_mass_ = 0; variation_sup_ = abs(u[1][1] - u_previous[1][1]); for (int i = 1; i <= NT; i++) { for (int j = 1; j <= NT; j++) { // Descobre o mínimo e o máximo if (u[i][j] < min_u_) min_u_ = u[i][j]; else if (u[i][j] > max_u_) max_u_ = u[i][j]; if (abs(u[i][j] - u_previous[i][j]) > variation_sup_) variation_sup_ = abs(u[i][j] - u_previous[i][j]); variation_mass_ = variation_mass_ + u[i][j] - u_previous[i][j]; } } variation_mass_ = variation_mass_ * h * h; if (debug) { cout << "\nmin_u_ = " << min_u_; cout << "\nmax_u_ = " << max_u_; cout << "\nvariation_mass_ = " << variation_mass_; cout << "\nvariation_sup_ = " << variation_sup_; } } // Verifica se as três regiões(farField) estão no interior do // retângulo(quadrado). Caso não esteja, escreve um aviso na tela, // retorna falso e o programa principal(main) encerra o programa. bool DistFarFieldEstahCorreta() { // Define as distâncias dos farfield x_min = M1 * h; x_max = M2 * h; y_min = N1 * h; y_max = N2 * h; R = min(min(abs(x_min), abs(x_max)), min(abs(y_min), abs(y_max))); refv1 = 0.5 * R; refv2 = 0.7 * R; refv3 = 0.9 * R; if (max(refv1, max(refv2, refv3)) > R) { cout << "\n *******************************************************"; cout << "\n ****** ERROR ***** ERROR ***** ERROR ***** ERROR ******"; cout << "\n"; cout << "\n Far-field zones INCONSISTENT with computational region"; cout << "\n"; cout << "\n Please reset the reference values: refv1, refv2, refv3"; cout << "\n"; cout << "\n which define the far-field zones"; cout << "\n in code: \"initialize.cpp\""; cout << "\n"; cout << "\n *******************************************************"; cout << "\n"; cout << "\n Execution will be ABORTED because of this error"; cout << "\n"; cout << "\n *******************************************************"; return false; } else return true; } // Calcula o tempo estimado para as alterações provocadas // pelas singularidades chegarem a borda void TempoEstimado(double ** &DadosIniciais) { // -------------------------------------------------------------- // //Location of singularities and corresponding solution values : // -------------------------------------------------------------- X1 = DadosIniciais[0][0]; // - x - coordinate of 1st singularity // cout << "\nX1=" << X1; Y1 = DadosIniciais[0][1]; // - y - coordinate of 1st singularity X2 = DadosIniciais[1][0]; // - x - coordinate of 2nd singularity Y2 = DadosIniciais[1][1]; // - y - coordinate of 2nd singularity X3 = DadosIniciais[2][0]; // - x - coordinate of 3rd singularity Y3 = DadosIniciais[2][1]; // - y - coordinate of 3rd singularity b1 = DadosIniciais[0][2]; b2 = DadosIniciais[1][2]; b3 = DadosIniciais[2][2]; expected_b = (b1 + b2 + b3) / 3; // expected far - field solution value is : (b1 + b2 + b3) / 3 // -------------------------------------------------------------- ii1 = I(X1); // - i - index of 1nd singularity ii2 = I(X2); // - i - index of 2nd singularity ii3 = I(X3); // - i - index of 3rd singularity jj1 = J(Y1); // - j - index of 1st singularity jj2 = J(Y2); // - j - index of 2st singularity jj3 = J(Y3); // - j - index of 3st singularity // testesIniciais(u); // -------------------------------------------------- // // INITIAL APPROXIMATION // to // STEADY STATE SOLUTION // // -------------------------------------------------- // -------------------------------------------------- // Computing the mass of each initial cone // relatively to the base plane z = b: mass1 = (1.0 / 3.0) * pi * r0 * r0 * abs(b1 - b); mass2 = (1.0 / 3.0) * pi * r0 * r0 * abs(b2 - b); mass3 = (1.0 / 3.0) * pi * r0 * r0 * abs(b3 - b); cout << "\nmass1=" << mass1 << " mass2=" << mass2 << "\nb2=" << b2 << " b3=" << b3; cout << "\nr0=" << r0; cout << "\nmass3 =" << mass3; cout << "\npi =" << (1.0 / 3.0) * pi; // The radius of the support of each initial cone // for large t is asymptotically given by // Rj = ccj * t ^ (1 / (n*(p - 2) + p)) // where ccj is given below(using Barenblatt solution) : expoente = (p / (p + n * (p - 2))) * ((p - 2) / (p - 1)); cout << "\nexpoente=" << expoente; common_factor = pow(1 / (n * (p - 2) + p), n / p) * p / ((p - 1) * (2 * pi)) * pow((p - 2) / p, n * (p - 1) / p); common_factor = common_factor / boost::math::beta(n * (p - 1) / p, (2 * p - 3) / (p - 2)); common_factor = pow(common_factor, expoente); cout << "\ncommon_factor=" << common_factor; cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(15); cout << "\nbeta(0.45,0.042)=" << boost::math::beta(0.45, 0.042); C1 = common_factor * pow(mass1, expoente); if (C1 < pow(10.0, -3)) C1 = pow(10.0, -3); C2 = common_factor * pow(mass2, expoente); if (C2 < pow(10.0, -3)) C2 = pow(10.0, -3); C3 = common_factor * pow(mass3, expoente); if (C3 < pow(10.0, -3)) C3 = pow(10.0, -3); cout << "\nC2=" << C2 << " C3=" << C3; cc1 = pow(n * (p - 2) + p, -1 / p) * pow((p - 2) / p, (p - 1) / p) * pow(C1, (1 - p) / p); cc2 = pow(n * (p - 2) + p, -1 / p) * pow((p - 2) / p, (p - 1) / p) * pow(C2, (1 - p) / p); cc3 = pow(n * (p - 2) + p, -1 / p) * pow((p - 2) / p, (p - 1) / p) * pow(C3, (1 - p) / p); cout << "\ncc2=" << cc2 << " cc3=" << cc3; // cc4 = 1 / (n*(p - 2) + p)**(1 / p) * ((p - 2) / p)**((p - 1) / p) / C4**((p - 1) / p); // Estimating time need to reach the boundary of // computational region[x_min, x_max] x[y_min, y_max]: // cout << "\nX1="<<X1<<" x_max="<< x_max; // cout<<"\nx_max - X1="<< x_max - X1<<" "<<X1 - x_min<<" "<<y_max - Y1<<" "<< Y1 - y_min; minimum_distance_to_travel_1 = min(min(x_max - X1, X1 - x_min), min(y_max - Y1, Y1 - y_min)); // cout << "\nminimum_distance_to_travel_1="<< minimum_distance_to_travel_1; minimum_distance_to_travel_2 = min(min(x_max - X2, X2 - x_min), min(y_max - Y2, Y2 - y_min)); minimum_distance_to_travel_3 = min(min(x_max - X3, X3 - x_min), min(y_max - Y3, Y3 - y_min)); // minimum_distance_to_travel_4 = min(Rx - x4, Rx + x4, Ry - y4, Ry + y4); maximum_distance_to_travel_1 = max(max(x_max - X1, X1 - x_min), max(y_max - Y1, Y1 - y_min)); maximum_distance_to_travel_2 = max(max(x_max - X2, X2 - x_min), max(y_max - Y2, Y2 - y_min)); maximum_distance_to_travel_3 = max(max(x_max - X3, X3 - x_min), max(y_max - Y3, Y3 - y_min)); // maximum_distance_to_travel_4 = max(Rx - x4, Rx + x4, Ry - y4, Ry + y4); t1_min = pow(cc1 * minimum_distance_to_travel_1, n * (p - 2) + p); t2_min = pow(cc2 * minimum_distance_to_travel_2, n * (p - 2) + p); t3_min = pow(cc3 * minimum_distance_to_travel_3, n * (p - 2) + p); // t4_min = (cc4 * minimum_distance_to_travel_4)**(n*(p - 2) + p); t1_max = pow(cc1 * maximum_distance_to_travel_1, n * (p - 2) + p); t2_max = pow(cc2 * maximum_distance_to_travel_2, n * (p - 2) + p); t3_max = pow(cc3 * maximum_distance_to_travel_3, n * (p - 2) + p); // t4_max = (cc4 * maximum_distance_to_travel_4)**(n*(p - 2) + p); cout << "\n-----------------------------------------------------------"; cout << "\nEstimated minimum time to reach the computational boundary:"; cout << "\n" << t1_min << "\n" << t2_min << "\n" << t3_min; cout << "\n\nEstimated time to pass the computational boundary entirely:"; cout << "\n" << t1_max << "\n" << t2_max << "\n" << t3_max; cout << "\n----------------------------------------------------------"; } // F calcula os seis pontos do retângulo vertical(altura > base) // à esquerda do ponto(i,j). Em relação ao centro do retângulo, // (i,j) está no meio do lado direito do retângulo. double F(double ** &u, int i, int j) { double FF; FF = pow(u[i][j] - u[i - 1][j], 2) + pow(((u[i][j + 1] + u[i - 1][j + 1] - u[i][j - 1] - u[i - 1][j - 1]) / 4), 2); FF = pow(FF, q) / pow(h, p - 2); FF = FF * (u[i][j] - u[i - 1][j]); return FF; } // fim de F // G calcula os seis pontos do retângulo horizontal(altura < base) // abaixo do ponto(i,j). Em relação ao centro do retângulo, // (i,j) está no meio do lado superior do retângulo. double G(double ** &u, int i, int j) { double GG; GG = pow(u[i][j] - u[i][j - 1], 2) + pow(((u[i + 1][j] + u[i + 1][j - 1] - u[i - 1][j] - u[i - 1][j - 1]) / 4), 2); GG = pow(GG, q) / pow(h, p - 2); GG = GG * (u[i][j] - u[i][j - 1]); return GG; } // fim de G /* // Parte principal do programa, atualiza a matriz u void processa(double ** &u, double ** &v, double ** &DadosIniciais) { double t; // clock_t start_time; // double time_in_seconds; time_next_dump = t0 + dt_dump; dt = cfl * h * h; t = 0; loop = 0; while (t < time_next_dump) { t = t + dt; loop = loop + 1; // Começa a contar o tempo // start_time = clock(); // Calcula os novos valores no quadrado interno for (int i = 1; i <= NT; i++) for (int j = 1; j <= NT; j++) { v[i][j] = F(u, i + 1, j) - F(u, i, j) + G(u, i, j + 1) - G(u, i, j); v[i][j] = u[i][j] + cfl * v[i][j]; } // Atualiza u com os novos valores for (int i = 1; i <= NT; i++) for (int j = 1; j <= NT; j++) u[i][j] = v[i][j]; // Atualiza as bordas. Se supõe que a borda tem o mesmo valor // que a fronteira do quadrado interno // Atualiza a borda superior e inferior for (int i = 1; i <= NT; i++) { u[i][0] = u[i][1]; u[i][NT + 1] = u[i][NT]; } // Atualiza a borda esquerda e direita for (int j = 1; j <= NT; j++) { u[0][j] = u[1][j]; u[NT + 1][j] = u[NT][j]; } // Atualiza os 4 cantos do quadrado externo u[0][0] = u[1][1]; u[0][NT + 1] = u[1][NT]; u[NT + 1][0] = u[NT][1]; u[NT + 1][NT + 1] = u[NT][NT]; // correcting u values at the singular points : for (int n = 0; n < QtSing; n++) { u[I(DadosIniciais[n][0])][J(DadosIniciais[n][1])] = DadosIniciais[n][DIM - 1]; } // Fim da atualização u:=v } // end While cout << "\nloop=" << loop; } // fim de processa */ // Parte principal do programa, atualiza a matriz u void Atualiza_U(double ** &u, double ** &v) { // Calcula os novos valores no quadrado interno for (int i = 1; i <= NT; i++) for (int j = 1; j <= NT; j++) { v[i][j] = F(u, i + 1, j) - F(u, i, j) + G(u, i, j + 1) - G(u, i, j); v[i][j] = u[i][j] + cfl * v[i][j]; } // Atualiza u com os novos valores for (int i = 1; i <= NT; i++) for (int j = 1; j <= NT; j++) u[i][j] = v[i][j]; // Atualiza as bordas. Se supõe que a borda tem o mesmo valor // que a fronteira do quadrado interno // Atualiza a borda superior e inferior for (int i = 1; i <= NT; i++) { u[i][0] = u[i][1]; u[i][NT + 1] = u[i][NT]; } // Atualiza a borda esquerda e direita for (int j = 1; j <= NT; j++) { u[0][j] = u[1][j]; u[NT + 1][j] = u[NT][j]; } // Atualiza os 4 cantos do quadrado externo u[0][0] = u[1][1]; u[0][NT + 1] = u[1][NT]; u[NT + 1][0] = u[NT][1]; u[NT + 1][NT + 1] = u[NT][NT]; // correcting u values at the singular points : u[ii1][jj1] = b1; u[ii2][jj2] = b2; u[ii3][jj3] = b3; // Fim da atualização u:=v } // fim de Atualiza_U // Calcula a média dos valores de u em três aneis quadrado // afastado do centro. void farFieldValue(double **&u_previous) { // cout << I(-8) << " " << I(-6) << " "; // cout << I(6) << " " << I(8) << " "; i_ff1a = I(-refv1); i_ff2a = I(-refv2); i_ff3a = I(-refv3); i_ff1b = I(refv1); i_ff2b = I(refv2); i_ff3b = I(refv3); j_ff1a = J(-refv1); j_ff2a = J(-refv2); j_ff3a = J(-refv3); j_ff1b = J(refv1); j_ff2b = J(refv2); j_ff3b = J(refv3); length_i1 = i_ff1b - i_ff1a + 1; length_i2 = i_ff2b - i_ff2a + 1; length_i3 = i_ff3b - i_ff3a + 1; length_j1 = j_ff1b - j_ff1a + 1; length_j2 = j_ff2b - j_ff2a + 1; length_j3 = j_ff3b - j_ff3a + 1; // --------------------------------------------------- - // Computing initial values of u_previous on far - field zones : // --------------------------------------------------- - ff1_value_u0 = CalculaFarField(i_ff1a, i_ff1b, j_ff1a, j_ff1b); ff2_value_u0 = CalculaFarField(i_ff2a, i_ff2b, j_ff2a, j_ff2b); ff3_value_u0 = CalculaFarField(i_ff3a, i_ff3b, j_ff3a, j_ff3b); } // fim de farFieldValue // Funcão usada por farFieldValue para calcular o valor // medio de "u" em um anel quadrado centrado na origem double CalculaFarField(int ia, int ib, int ja, int jb) { double soma = 0; int qt = 0; for (int j = ja; j <= jb; j++) { for (int i = ia; i <= ia + 10; i++) { qt++; soma = soma + u_previous[i][j]; } for (int i = ib - 10; i <= ib; i++) { soma = soma + u_previous[i][j]; qt++; } } for (int i = ia; i <= ib; i++) { for (int j = ja; j <= ja + 10; j++) { soma = soma + u_previous[i][j]; qt++; } for (int j = jb - 10; j <= jb; j++) { soma = soma + u_previous[i][j]; qt++; } } return soma / qt; } // Checa se a matriz u foi inicializado corretamente void mostraMatriz(double ** u) { cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(5); cout << "\n\n" << setw(5); for (int i = 0; i < tamMatriz; i++) cout << i << setw(8); for (int i = 0; i < tamMatriz; i++) { cout << "\n" << setw(3) << i << " "; for (int j = 0; j < tamMatriz; j++) cout << u[i][j] << " "; } } // Converte a coordenada x para o índice i int I(double x) { return static_cast<int>(x / h) + (-M1 + 1); // I=(x / h) + (-M1 + 1) } // Converte a coordenada y para o índice j int J(double y) { return static_cast<int>(y / h) + (-N1 + 1); // J = (y / h) + (-N1 + 1) } // Converte o índice i para a coordenada x double X(int i) { return static_cast<double>((i + M1 - 1) * h); // X = (i + M1 - 1) * h } // Converte o índice j para a coordenada y double Y(int j) { return static_cast<double>((j + N1 - 1) * h); // Y = (j + N1 - 1) * h } // Define o valor de R e h e inicializa as matrizes // u, v e u_previous com zeros. void inicializaMatriz(double ** &u, double ** &v, double ** &u_previous, double ** DadosIniciais) { double *distXY_Cone = new double[QtSing]; // Distancia do ponto(x,y) aos cones N = static_cast<int>(R / h); NT = 2 * N + 1; tamMatriz = NT + 2; cout << "\nN = " << N << "\ntamMatriz = " << tamMatriz; double z, d; /* 1. Pointer to pointer First, we will allocate memory for an array which contains a set of pointers. Next, we will allocate memory for each array which is pointed by the pointers.The deallocation of memory is done in the reverse order of memory allocation. */ u = new double *[tamMatriz]; v = new double *[tamMatriz]; u_previous = new double *[tamMatriz]; for (int i = 0; i < tamMatriz; i++) { u[i] = new double[tamMatriz]; v[i] = new double[tamMatriz]; u_previous[i] = new double[tamMatriz]; } cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(15); cout << "\nb= " << b; for (int i = 0; i < tamMatriz; ++i) { for (int j = 0; j < tamMatriz; ++j) { u[i][j] = b; // caso geral u_previous[i][j] = b; for (int k = 0; k < QtSing; k++) // Verifica a distância até os cones { distXY_Cone[k] = sqrt(pow(X(i) - DadosIniciais[k][0], 2) + pow(Y(j) - DadosIniciais[k][1], 2)); if ((distXY_Cone[k]) < r0) { z = DadosIniciais[k][2]; d = distXY_Cone[k]; u[i][j] = z + (b - z) * d / r0; u_previous[i][j] = u[i][j]; break; // Vai para o próximo ponto(x,y) } } } } } int LeU24Serial_Input(void) { ArqLeData.open("u24h_serial_INPUT_cpp.txt"); if (ArqLeData.is_open()) { cout << "\n\n O arquivo: \"u24h_serial_INPUT_cpp.txt\" foi aberto com exito"; ArqLeData >> M1 >> M2; ArqLeData >> N1 >> N2; ArqLeData >> n; ArqLeData >> p; q = static_cast<double>(p - 2) / 2; ArqLeData >> h; ArqLeData >> cfl; ArqLeData >> x_min >> x_max; ArqLeData >> y_min >> y_max; ArqLeData >> t0 >> tF >> dt_dump; ArqLeData >> X1 >> X2 >> X3; ArqLeData >> Y1 >> Y2 >> Y3; ArqLeData >> ii1 >> ii2 >> ii3; ArqLeData >> jj1 >> jj2 >> jj3; ArqLeData >> b1 >> b2 >> b3; ArqLeData >> b; ArqLeData >> refv1 >> refv2 >> refv3; ArqLeData >> Count; ArqLeData >> no_runs; ArqLeData >> i_ff1a >> i_ff1b >> i_ff2a >> i_ff2b >> i_ff3a >> i_ff3b; ArqLeData >> j_ff1a >> j_ff1b >> j_ff2a >> j_ff2b >> j_ff3a >> j_ff3b; ArqLeData >> length_i1 >> length_i2 >> length_i3; ArqLeData >> length_j1 >> length_j2 >> length_j3; ArqLeData >> ff1_value_u0 >> ff2_value_u0 >> ff3_value_u0; ArqLeData >> min_u0 >> max_u0; ArqLeData >> mass_u0; ArqLeData >> t1_min >> t2_min >> t3_min; ArqLeData >> t1_max >> t2_max >> t3_max; DATE_start_LOG_previous = new int *[no_runs + 1]; DATE_finish_LOG_previous = new int *[no_runs + 1]; for (int i = 0; i < no_runs + 1; i++) { DATE_start_LOG_previous[i] = new int[7]; DATE_finish_LOG_previous[i] = new int[7]; } tF_LOG_previous = new double[no_runs + 1]; ff1_value_LOG_previous = new double[no_runs + 1]; ff2_value_LOG_previous = new double[no_runs + 1]; ff3_value_LOG_previous = new double[no_runs + 1]; variation_mass_LOG_previous = new double[no_runs + 1]; variation_sup_LOG_previous = new double[no_runs + 1]; min_u_LOG_previous = new double[no_runs + 1]; max_u_LOG_previous = new double[no_runs + 1]; elapsed_time_LOG_previous = new double[no_runs + 1]; // ArqLeData >> linhaEmBranco; for (int i = 0; i < no_runs + 1; i++) { for (int j = 0; j < 7; j++) ArqLeData >> DATE_start_LOG_previous[i][j]; } for (int i = 0; i < no_runs + 1; i++) { for (int j = 0; j < 7; j++) ArqLeData >> DATE_finish_LOG_previous[i][j]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> tF_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> ff1_value_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> ff2_value_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> ff3_value_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> variation_mass_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> variation_sup_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> min_u_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> max_u_LOG_previous[i]; } for (int i = 0; i < no_runs + 1; i++) { ArqLeData >> elapsed_time_LOG_previous[i]; } R = min(min(abs(x_min), abs(x_max)), min(abs(y_min), abs(y_max))); N = round(R / h); NT = 2 * N + 1; tamMatriz = NT + 2; u = new double *[tamMatriz]; v = new double *[tamMatriz]; u_previous = new double *[tamMatriz]; for (int i = 0; i < tamMatriz; i++) { u[i] = new double[tamMatriz]; v[i] = new double[tamMatriz]; u_previous[i] = new double[tamMatriz]; } for (int i = 1; i <= NT; i++) { for (int j = 1; j <= NT; j++) { ArqLeData >> u[i][j]; } } ArqLeData >> previous_length; if (previous_length != Count) { return 2; // Erro=2 } ff1_value_u_previous = new double[previous_length + 1]; ff2_value_u_previous = new double[previous_length + 1]; ff3_value_u_previous = new double[previous_length + 1]; min_u_previous = new double[previous_length + 1]; max_u_previous = new double[previous_length + 1]; variation_mass_previous = new double[previous_length + 1]; variation_sup_previous = new double[previous_length + 1]; time_per_cycle_previous = new double[previous_length + 1]; for (int i = 0; i <= previous_length; i++) { ArqLeData >> ff1_value_u_previous[i] >> ff2_value_u_previous[i] >> ff3_value_u_previous[i]; } for (int i = 0; i <= previous_length; i++) { ArqLeData >> variation_mass_previous[i] >> variation_sup_previous[i]; } for (int i = 0; i <= previous_length; i++) { ArqLeData >> min_u_previous[i] >> max_u_previous[i]; } for (int i = 0; i <= previous_length; i++) { ArqLeData >> time_per_cycle_previous[i]; } if (debug) { cout << "\nM1=" << M1 << " M2=" << M2; cout << "\nN1=" << N1 << " N2=" << N2; cout << "\nn=" << n; cout << "\np=" << p; cout << "\nq=" << q; cout << "\nh=" << h; cout << "\ncfl=" << cfl; cout << "\nx_min=" << x_min << " x_max=" << x_max; cout << "\ny_min=" << y_min << " y_max=" << y_max; cout << "\nt0=" << t0 << " tF=" << tF << " dt_dump=" << dt_dump; cout << "\nX1=" << X1 << " X2=" << X2 << " X3=" << X3; cout << "\nY1=" << Y1 << " Y2=" << Y2 << " Y3=" << Y3; cout << "\nii1=" << ii1 << " ii2=" << ii2 << " ii3=" << ii3; cout << "\njj1=" << jj1 << " jj2=" << jj2 << " jj3=" << jj3; cout << "\nb1=" << b1 << " b2=" << b2 << " b3=" << b3; cout << "\nb=" << b; cout << "\nrefv1=" << refv1 << " refv2=" << refv2 << " refv3=" << refv3; cout << "\nCount=" << Count; cout << "\nno_runs=" << no_runs; cout << "\ni_ff1a=" << i_ff1a << " i_ff1b=" << i_ff1b << " i_ff2a=" << i_ff2a << " i_ff2b=" << i_ff2b << " i_ff3a=" << i_ff3a << " i_ff3b=" << i_ff3b; cout << "\nj_ff1a=" << j_ff1a << " j_ff1b=" << j_ff1b << " j_ff2a=" << j_ff2a << " j_ff2b= " << j_ff2b << " j_ff3a=" << j_ff3a << " j_ff3b=" << j_ff3b; cout << "\nlength_i1=" << length_i1 << " length_i2=" << length_i2 << " length_i3=" << length_i3; cout << "\nlength_j1=" << length_j1 << " length_j2=" << length_j2 << " length_j3=" << length_j3; cout << "\nff1_value_u0=" << ff1_value_u0 << " ff2_value_u0=" << ff2_value_u0 << " ff3_value_u0=" << ff3_value_u0; cout << "\nmin_u0=" << min_u0 << " max_u0=" << max_u0; cout << "\nmass_u0=" << mass_u0; cout << "\nt1_min=" << t1_min << " t2_min=" << t2_min << " t3_min=" << t3_min; cout << "\nt1_max=" << t1_max << " t2_max=" << t2_max << " t3_max=" << t3_max; cout << "\nelapsed_time_LOG_previous=" << elapsed_time_LOG_previous [0] << "\n"; for (int j = 0; j < 7; j++) cout << DATE_start_LOG_previous[0][j] << " "; cout << "\ntamMatriz=" << tamMatriz; cout << "\nN=" << N; cout << "\nNT=" << NT << "\n"; cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(16); for (int i = 1; i <= 1; i++) { for (int j = 1; j <= NT; j++) { cout << setw(4) << j << "=" << u[i][j]; if (j % 10 == 0) cout << "\n"; } } cout << "\nprevious_length=" << previous_length; for (int i = 0; i <= previous_length; i++) { cout << "\nff1_value_u_previous=" << ff1_value_u_previous[i] << " " << ff2_value_u_previous[i] << " " << ff3_value_u_previous[i]; } for (int i = 0; i <= previous_length; i++) { cout << "\nvariation_mass_previous=" << variation_mass_previous [i] << " variation_sup_previous=" << variation_sup_previous[i]; } for (int i = 0; i <= previous_length; i++) { cout << "\nmin_u_previous=" << min_u_previous[i] << " " << max_u_previous[i]; } for (int i = 0; i <= previous_length; i++) { cout << "\ntime_per_cycle_previous=" << time_per_cycle_previous[i]; } } ArqLeData.close(); return 0; // Sem erro } else { cout << "\nNao foi possivel abrir o arquivo \"u24h_serial_INPUT_cpp.txt\""; cout << "\nVerifique se ele existe ?"; return 1; // Erro = 1 } } // LeDadosIniciais // Mostra na tela os dados iniciais, R, h, os pontos singulares, b,... void imprimeMatrizSing(double ** DadosIniciais) { double media = 0; for (int i = 0; i < QtSing; i++) { media = media + DadosIniciais[i][2]; } media = media / QtSing; cout << "DADOS INICIAIS DAS SINGULARIDADES,"; cout << "\nTAMANHO DA MALHA E TEMPO FINAL"; cout << "\n\nQuantidade de singularidades: " << QtSing; cout << "\nR: " << R; cout << "\nh: " << h; cout << "\nTempo Final: " << tF; cout << "\nValor do b (nivel inicial): " << b; cout << "\nMedia dos b (b1 + .. + bn)/n : " << media; cout << "\n\nSingularidade" << setw(7) << "x" << setw(7) << "y" << setw (7) << "z"; for (int i = 0; i < QtSing; i++) { cout << "\n" << setw(7) << setprecision(0) << i + 1; cout << " "; for (int j = 0; j < DIM; j++) { cout << setprecision(2); cout << setw(7) << DadosIniciais[i][j]; } } } // Calcula a menor distância entre os cones(as singularidades) // O r0 é esta menor distância dividido por dois double calculaRaio(double ** DadosIniciais) { double dist, distMenor, r0; // menor distância entre cones // d1_2 cout << "\nDadosIniciais[1][2]= " << DadosIniciais[1][2]; distMenor = pow(DadosIniciais[0][0] - DadosIniciais[1][0], 2); distMenor = distMenor + pow(DadosIniciais[0][1] - DadosIniciais[1][1], 2); for (int i = 0; i < QtSing - 1; i++) for (int j = i + 1; j < QtSing; j++) { dist = pow(DadosIniciais[i][0] - DadosIniciais[j][0], 2); dist = dist + pow(DadosIniciais[i][1] - DadosIniciais[j][1], 2); if (dist < distMenor) distMenor = dist; } r0 = sqrt(distMenor) / 2; cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(15); cout << "\n\nraio= " << r0; return r0; } // Verifica se os métodos e a matriz está correta, // checa os procedimentos iniciais. void testesIniciais(double ** matriz) { cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(4); cout << "\n r0 = " << r0; cout << "\n b = " << b; cout << "\nu[I(1)][J(0.5)] = 6? = " << matriz[I(1)][J(0.5)]; cout << "\nu[I(-1.5)][J(1)] = 5? = " << matriz[I(-1.5)][J(1)]; cout << "\nu[I(0.5)][J(-1.5)] = 1? = " << matriz[I(0.5)][J(-1.5)]; cout << "\nu[I(0.6)][J(-1.5)] = u[" << I(0.6) << "][" << J(-1.5) << "]=" << matriz[I(0.6)][J(-1.5)]; cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(1); cout << "\n\n"; // nova linha for (int k = 0; k < tamMatriz; k++) { cout << " X(" << setw(3) << k << ")=" << setw(5) << X(k) << " "; if ((k + 1) % 10 == 0) cout << "\n"; } cout << setiosflags(ios::fixed | ios::showpoint) << setprecision(1); cout << "\n\n"; // nova linha for (int k = 0; k < tamMatriz; k++) { cout << " Y(" << setw(3) << k << ")=" << setw(5) << Y(k) << " "; if ((k + 1) % 10 == 0) cout << "\n"; } cout << "\n\n"; // nova linha for (int k = 0; k < tamMatriz; k++) { cout << " I(" << setw(5) << X(k) << ")=" << setw(3) << I(X(k)) << " "; if ((k + 1) % 10 == 0) cout << "\n"; } cout << "\n\n"; // nova linha for (int k = 0; k < tamMatriz; k++) { cout << " J(" << setw(5) << Y(k) << ")=" << setw(3) << J(Y(k)) << " "; if ((k + 1) % 10 == 0) cout << "\n"; } cout << "\nii1=" << ii1 << " ii2=" << ii2 << " ii3=" << ii3; cout << "\njj1=" << jj1 << " jj2=" << jj2 << " jj3=" << jj3; }
219e9821c26acd478594ffd497dbd026a3dff17a
bae4e79d035c09e7e9be483140120ab2c821f15a
/Engine/ShaderManager.h
5ee9e64156fdeac185ea8e9b959b4695ddfd2655
[]
no_license
OPsteffOP/Steff-Engine
fcc6d8d2ad3550ba2b701eec6f79906e5bc9bfa7
ac805b437b522da9a3aca119bdf9e9225019fc76
refs/heads/main
2022-12-28T12:12:32.279990
2020-10-15T16:08:25
2020-10-15T16:08:25
304,379,624
0
0
null
null
null
null
UTF-8
C++
false
false
1,088
h
ShaderManager.h
#pragma once #include "Shader.h" #include "VertexShader.h" #include "PixelShader.h" #include "GeometryShader.h" #include <unordered_map> namespace SteffEngine { namespace Core { class ShaderManager { public: static ShaderManager* GetInstance(); static void Destroy(); const std::pair<ID3DBlob*, ID3D11VertexShader*>& GetVertexShader(const std::wstring& compiledShaderPath); const std::pair<ID3DBlob*, ID3D11GeometryShader*>& GetGeometryShader(const std::wstring& compiledShaderPath); const std::pair<ID3DBlob*, ID3D11PixelShader*>& GetPixelShader(const std::wstring& compiledShaderPath); private: ShaderManager() = default; ~ShaderManager(); ID3DBlob* LoadBlob(const std::wstring& compiledShaderPath) const; static ShaderManager* m_pInstance; std::unordered_map<std::wstring, std::pair<ID3DBlob*, ID3D11VertexShader*>> m_pVertexShaders; std::unordered_map<std::wstring, std::pair<ID3DBlob*, ID3D11GeometryShader*>> m_pGeometryShaders; std::unordered_map<std::wstring, std::pair<ID3DBlob*, ID3D11PixelShader*>> m_pPixelShaders; }; } }
94083d1d0ff7233a4b47f99eb8e35edc89f12bf7
e22b23ad88e114461374f2a3fcbd10fc7fea3697
/Server/src/ServerSettings/ServerSettings.cpp
354adcef2d687353be49aad2b20fcbae8e8be92a
[ "MIT" ]
permissive
dz1domin/Proxy_server
d5b649f6b8c0628900f92fb01c56ac26527cfd36
828453f9858c98db9169cded0b62dd3a3b170d5f
refs/heads/master
2020-06-01T20:19:31.473776
2019-06-07T22:46:26
2019-06-07T22:46:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,490
cpp
ServerSettings.cpp
#include "../../include/ServerSettings/ServerSettings.hpp" ServerSettings::ServerSettings() { setCurrentTreeToDefault(); } ServerSettings::~ServerSettings() { deleteCurrentTree(); } void ServerSettings::deleteCurrentTree() { if (currentTree != nullptr) { delete currentTree; currentTree = nullptr; } } void ServerSettings::createCurrentTree() { if (currentTree != nullptr) deleteCurrentTree(); currentTree = new ptree(); } void ServerSettings::setCurrentTreeToDefault() { createCurrentTree(); for (auto const& i: treeDefaultvalues) { currentTree->put(i.first, i.second); } } bool ServerSettings::validateJsonFields() { if (currentTree != nullptr) { std::string connectionData26Numbers = currentTree->get<std::string>("connectionData26Numbers"); std::string maxNumberOfConnections = currentTree->get<std::string>("maxNumberOfConnections"); std::string timeoutLimit = currentTree->get<std::string>("timeoutLimit"); std::string certificateFilePath = currentTree->get<std::string>("certificateFilePath"); std::string privateKeyFilePath = currentTree->get<std::string>("privateKeyFilePath"); connectionData26Numbers.erase(std::remove_if(connectionData26Numbers.begin(), connectionData26Numbers.end(), ::isspace), connectionData26Numbers.end()); try { if (connectionData26Numbers.length() < 26 || connectionData26Numbers.length() > 26){ throw WrongJsonDataException("Wrong number sequence format."); } for (unsigned i=0; i<connectionData26Numbers.length(); i++) { if (isdigit(connectionData26Numbers[i]) == false) { throw WrongJsonDataException("Wrong number sequence format."); } } for (unsigned i=0; i<maxNumberOfConnections.length(); i++) { if (isdigit(maxNumberOfConnections[i]) == false) { throw WrongJsonDataException("Incorrect max number of connections"); } } for (unsigned i=0; i<timeoutLimit.length(); i++) { if (isdigit(timeoutLimit[i]) == false) { throw WrongJsonDataException("Incorrect timeout limit"); } } std::fstream certificateFile; certificateFile.open(certificateFilePath); if (certificateFile.fail()) { throw WrongJsonDataException("Given certificate file does not exist"); } certificateFile.close(); std::fstream privateKeyFile; privateKeyFile.open(privateKeyFilePath); if (privateKeyFile.fail()) { throw WrongJsonDataException("Given private key file does not exist"); } privateKeyFile.close(); } catch (WrongJsonDataException& e) { std::cout << e.what() << std::endl; return false; } setConnectionData26Numbers(connectionData26Numbers); setMaxNumberOfConnections(maxNumberOfConnections); setTimeoutLimit(timeoutLimit); setCertificateFilePath(certificateFilePath); setPrivateKeyFilePath(privateKeyFilePath); } return true; } void ServerSettings::readJson(const std::string& jsonPath) { createCurrentTree(); read_json(jsonPath, *currentTree); validateJsonFields(); } void ServerSettings::writeJson(const std::string& jsonPath) { if (currentTree == nullptr) createCurrentTree(); write_json(jsonPath, *currentTree); } void ServerSettings::printCurrentTree() { write_json(std::cout, *currentTree); } std::string ServerSettings::getConnectionData26Numbers() const { if (currentTree != nullptr) { return currentTree->get<std::string>("connectionData26Numbers"); } else return nullptr; } std::string ServerSettings::getCertificateFilePath() const { if (currentTree != nullptr) { return currentTree->get<std::string>("certificateFilePath"); } else return nullptr; } std::string ServerSettings::getPrivateKeyFilePath() const { if (currentTree != nullptr) { return currentTree->get<std::string>("privateKeyFilePath"); } else return nullptr; } unsigned ServerSettings::getMaxNumberOfConnections() const { if (currentTree != nullptr) { std::string maxNumberOfConnections = currentTree->get<std::string>("maxNumberOfConnections"); std::istringstream iss(maxNumberOfConnections); unsigned result; iss >> result; return result; } else return 0; } unsigned ServerSettings::getTimeoutLimit() const { if (currentTree != nullptr) { std::string timeoutLimit = currentTree->get<std::string>("timeoutLimit"); std::istringstream iss(timeoutLimit); unsigned result; iss >> result; return result; } else return 0; } void ServerSettings::setConnectionData26Numbers(const std::string& connectionData26Numbers) { if (currentTree != nullptr) { currentTree->put("connectionData26Numbers", connectionData26Numbers); } } void ServerSettings::setCertificateFilePath(const std::string& certificateFilePath) { if (currentTree != nullptr) { currentTree->put("certificateFilePath", certificateFilePath); } } void ServerSettings::setPrivateKeyFilePath(const std::string& privateKeyFilePath) { if (currentTree != nullptr) { currentTree->put("privateKeyFilePath", privateKeyFilePath); } } void ServerSettings::setMaxNumberOfConnections(const std::string& maxNumberOfConnections) { if (currentTree != nullptr) { currentTree->put("maxNumberOfConnections", maxNumberOfConnections); } } void ServerSettings::setTimeoutLimit(const std::string& timeoutLimit) { if (currentTree != nullptr) { currentTree->put("timeoutLimit", timeoutLimit); } }
5b7780411572e5abeff84cd64f88436cda59f18a
75e3d9935d552bfcdc20d8c58f9d14b83acbcf5c
/sem1/test3/Test-3.1/Test-3.1/Main.cpp
7bc006ca0ff1569639c1abccbda5cac5deadc971
[]
no_license
NadiaSob/HomeworkYear1
f53c4104e14ca90613831d0fff59eb7f4e1c3896
9148bc88b1e974be40c447ddd77b608bc0b18234
refs/heads/master
2020-03-30T04:37:32.354704
2019-10-14T16:16:25
2019-10-14T16:16:25
150,753,591
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
Main.cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include "List.h" int main() { List *list = createList(); int number = 1; while (number != 0) { scanf("%d", &number); if (number != 0) { addNode(list, number); } } printList(list); deleteList(list); return 0; }
516a80ac00442ae427939f4c8d938e5d92cf87e9
d5889c8ffa5f0d9369c5226205dccff7f5382379
/algospot/LUNCHBOX.cpp
44e5d24c345b09c3e3da63f9858eeb999dba5abe
[ "MIT" ]
permissive
fpdjsns/Algorithm
334457a0e18a28b51a54514b91daff798ed833fe
1414d9368f4047b28808952efa2b0c68792c154c
refs/heads/master
2023-05-04T16:55:43.599727
2023-04-18T14:27:50
2023-04-18T14:27:50
126,031,686
14
8
MIT
2021-12-06T07:30:28
2018-03-20T14:36:02
C++
UTF-8
C++
false
false
978
cpp
LUNCHBOX.cpp
/* * 문제 : https://algospot.com/judge/problem/read/LUNCHBOX * 시간복잡도 : O(NlogN) * 알고리즘 : Greedy */ #include <iostream> #include <vector> #include <algorithm> using namespace std; int solve(vector<int> microwave, vector<int> eat){ int N = microwave.size(); vector<pair<int,int>> order(N); for(int i=0;i<N;i++){ order[i] = {-eat[i],microwave[i]}; } sort(order.begin(), order.end()); int answer = 0; int eatTime = 0; for(int i=0;i<N;i++){ int spendTime = order[i].second; answer += spendTime; eatTime -= spendTime; eatTime = max(eatTime, -order[i].first); } return answer + eatTime; } int main() { int C; cin>> C; while(C--){ int N; cin>> N; vector<int> microwave(N), eat(N); for(int i=0;i<N;i++) cin>>microwave[i]; for(int i=0;i<N;i++) cin>>eat[i]; cout<<solve(microwave, eat)<<endl; } return 0; }
5ec329114e3db8495325bc2864996ce5be6f35af
bd048232cd40bb6b16fd6e7706322527e503ab6c
/code/mn_input/src/windows/win_input_module.cpp
f61f48e31c8284ce3f4a0e494979e35afa7e8616
[]
no_license
zozoiiiiii/moon_old
ff2b226592ef87d917c315308e47ff87d4b9c09d
f2c39bccc60112b579c855d92cf47779c11eda2d
refs/heads/master
2022-01-23T22:07:21.575969
2019-08-16T05:46:19
2019-08-16T05:46:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,602
cpp
win_input_module.cpp
#include "win_input_module.h" #include "public/object/mn_object_mgr.h" #include "public/object/mn_varlist.h" #define _WIN32_WINNT 0x0400 #include <windows.h> void WinInputModule::OnCreate() { m_pEventMgr = GetObjectMgr()->getEventMgr(); } void WinInputModule::OnDestroy() { } bool WinInputModule::MsgProc(unsigned int msg, size_t param1, size_t param2, int& result) { switch(msg) { case WM_KEYDOWN: { }break; case WM_KEYUP: { }break; case WM_MOUSEMOVE: { int nx = LOWORD(param2); int ny = HIWORD(param2); m_pEventMgr->Invoke(NULL, "input", MN::VarList()<<IET_Mouse_Move<<nx<<ny); }break; /* case WM_MOUSEWHEEL: { }break; */ case WM_LBUTTONDOWN: { int nx = LOWORD(param2); int ny = HIWORD(param2); m_pEventMgr->Invoke(NULL, "input", MN::VarList()<<IET_Mouse_LDown<<nx<<ny); }break; case WM_LBUTTONUP: { int nx = LOWORD(param2); int ny = HIWORD(param2); m_pEventMgr->Invoke(NULL, "input", MN::VarList()<<IET_Mouse_LUp<<nx<<ny); }break; case WM_RBUTTONDOWN: { int nx = LOWORD(param2); int ny = HIWORD(param2); m_pEventMgr->Invoke(NULL, "input", MN::VarList()<<IET_Mouse_RDown<<nx<<ny); }break; case WM_RBUTTONUP: { int nx = LOWORD(param2); int ny = HIWORD(param2); m_pEventMgr->Invoke(NULL, "input", MN::VarList()<<IET_Mouse_RUp<<nx<<ny); }break; default: break; } return true; }
ae690a2449dbc5bf99eddd5af1a925423ef9eec3
069debdd6a552366658b6b334005eefaf7482fd9
/engine/players.cpp
a8bfb2b2eb16f0778b0603dd84c97c5015704f4b
[]
no_license
demonxjj/generals-ai
c35bcea07a11243bc65f8dce9adc8a7639860805
5a3a331099690499993ee6982228663208a9b71d
refs/heads/master
2021-05-11T19:13:22.924352
2017-03-13T19:48:17
2017-03-13T19:48:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
131
cpp
players.cpp
#include "./players.h" const map<string, player_pair> STR_TO_PLAYER = { {"random", {new RandomPlayer(), new RandomPlayer()}} };
f3edecfa4720a0921d0825d2b1730b69cd6795a6
75d9df601a85ed10b53fefd11b36fea8dce54416
/src/node-socket.h
e88849cf34c0d10ec9de43d5b7add1c7e12d7488
[ "MIT" ]
permissive
emuggie/teaming
fed74e254dc1aca34ac2bfd5ef0b01e27038f4e7
0ab9da830032776e461babfba77e380ef01fcc19
refs/heads/master
2022-12-16T17:46:40.912449
2019-11-20T02:15:53
2019-11-20T02:15:53
222,628,572
0
0
MIT
2022-12-11T14:04:24
2019-11-19T06:51:27
C++
UTF-8
C++
false
false
1,002
h
node-socket.h
#ifndef NODE_SOCKET_H_ #define NODE_SOCKET_H_ #include "napi.h" #include "socket.h" #define NODE_SOCKET_CLASS_NAME "TeamSocket" namespace NODE { class Socket: public Napi::ObjectWrap<Socket>{ public : static Napi::Object Init(Napi::Env env, Napi::Object exports); Socket(const Napi::CallbackInfo& info); ~Socket(); Napi::Value getSfd(const Napi::CallbackInfo& info){ return Napi::Number::New(info.Env(), socket->getSfd()); } Napi::Value getCsfd(const Napi::CallbackInfo& info){ return Napi::Number::New(info.Env(), socket->getCsfd()); } Napi::Value getSemId(const Napi::CallbackInfo& info){ return Napi::Number::New(info.Env(), socket->getSemId()); } Napi::Value read(const Napi::CallbackInfo& info); Napi::Value write(const Napi::CallbackInfo& info); private : static Napi::FunctionReference constructor; ASSC::Socket* socket; }; } #endif
d5ddb98168fbd7335235ea9199acddd5fb48349b
464aa9d7d6c4906b083e6c3da12341504b626404
/src/server/loginapp/loginapp_config.hpp
6276ff5ceef01cf90bfb911182340c2489f08d9a
[]
no_license
v2v3v4/BigWorld-Engine-2.0.1
3a6fdbb7e08a3e09bcf1fd82f06c1d3f29b84f7d
481e69a837a9f6d63f298a4f24d423b6329226c6
refs/heads/master
2023-01-13T03:49:54.244109
2022-12-25T14:21:30
2022-12-25T14:21:30
163,719,991
182
167
null
null
null
null
UTF-8
C++
false
false
1,626
hpp
loginapp_config.hpp
/****************************************************************************** BigWorld Technology Copyright BigWorld Pty, Ltd. All Rights Reserved. Commercial in confidence. WARNING: This computer program is protected by copyright law and international treaties. Unauthorized use, reproduction or distribution of this program, or any portion of this program, may result in the imposition of civil and criminal penalties as provided by law. ******************************************************************************/ #include "server/external_app_config.hpp" #include "server/server_app_config.hpp" class LoginAppConfig : public ServerAppConfig, public ExternalAppConfig { public: static ServerAppOption< bool > shouldShutDownIfPortUsed; static ServerAppOption< bool > verboseExternalInterface; static ServerAppOption< float > maxLoginDelay; static uint64 maxLoginDelayInStamps() { return secondsToStamps( maxLoginDelay() ); } static ServerAppOption< std::string > privateKey; static ServerAppOption< bool > shutDownSystemOnExit; static ServerAppOption< bool > allowLogin; static ServerAppOption< bool > allowProbe; static ServerAppOption< bool > logProbes; static ServerAppOption< bool > registerExternalInterface; static ServerAppOption< bool > allowUnencryptedLogins; static ServerAppOption< int > loginRateLimit; static ServerAppOption< int > rateLimitDuration; static uint64 rateLimitDurationInStamps() { return secondsToStamps( rateLimitDuration() ); } static bool rateLimitEnabled() { return (rateLimitDuration() > 0); } static bool postInit(); }; // loginapp_config.hpp
77732d16f46ffd0fb07ccc1aae77a201e13f6ae6
0b73b64ad7477c05de9fd3a075ba9c93bd6785d3
/header/abstractdecorator.hpp
9a1cf9cb6ac78bbce1a6c01a7f68e50d8b119257
[]
no_license
aosterthun/software-engineering-ws15
b45cf201b209e8ea8c4e129cc5e66a8355c0f6ea
1215c75f10d74e1b823e7bef3f86a467a8ca1960
refs/heads/master
2021-01-17T23:05:11.915996
2016-01-30T14:48:42
2016-01-30T14:48:42
44,807,939
0
1
null
2015-10-23T11:03:30
2015-10-23T11:03:30
null
UTF-8
C++
false
false
419
hpp
abstractdecorator.hpp
#ifndef BUW_ABSTRACTDECORATOR #define BUW_ABSTRACTDECORATOR #include "converter.hpp" class ConverterDecorator : public converter { public: ConverterDecorator(); ConverterDecorator(converter* conv); ~ConverterDecorator(); double convert(double inValue) override; std::string toString() const override; void print() const override; converter* clone() override; protected: converter* _base; }; #endif
b6c9c2e556610fc46a08a9fb87976740bfb2d13f
f2c0a1be1ea037af953419d3707bf582507076a0
/src/main/main.cpp
9cb58439ee3ec974a86b4df2724b2281bc0e7282
[ "MIT" ]
permissive
Team5553-RoboLyon/2019_Raspberry
4a1a32eaa0b7181f2e41cb628e2c0058950f0570
b54db8e3c6a25511a39e81e3d1e0a40d53a4108f
refs/heads/master
2020-07-08T07:47:27.422908
2019-08-30T13:04:27
2019-08-30T13:04:27
164,417,287
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
cpp
main.cpp
#include "PrecompilationDefine.h" #include <iostream> #include <opencv2/opencv.hpp> #include <networktables/NetworkTableInstance.h> #include "lib/MjpegStream.h" #include "Values.h" #include "Vision.h" using namespace cv; using namespace std; #ifndef RUNNING_FRC_TESTS int main() { #ifdef __DESKTOP__ std::cout << "Running on Desktop - imshow enabled" << std::endl; #else std::cout << "Running embedded - imshow disabled" << std::endl; #endif // Initialization Mat imageTopView(CAPTURED_IMAGE_HEIGHT, CAPTURED_IMAGE_WIDTH, CV_8UC3); // Image 3D calculée à partir des données capturées // initialisation de la classe vision Vision vision(CAPTURED_IMAGE_WIDTH, CAPTURED_IMAGE_HEIGHT); lyonlib::MjpegStream stream_server("Pince Avant", CAPTURED_IMAGE_WIDTH, CAPTURED_IMAGE_HEIGHT, 50); auto inst = nt::NetworkTableInstance::GetDefault(); inst.StartClientTeam(5553); if (!vision.loadCameraIntrinsic(0, "data/camera_blanche.txt")) // Camera Avant { return 0; } if (!vision.loadCameraIntrinsic(1, "data/camera_blanche.txt")) // Camera Arriere { return 0; } vision.setCurrentCamera(0); // cas échéant, initialisation de l'interface d'édition ( sur PC, pour tester ) #ifdef PRECOMPIL_EDITING Editor editor(&vision); #endif // Boucle de traitement while (true) { if (vision.imageCapture()) { std::cout << vision.m_brightness << std::endl; std::cout << vision.m_awb_red << std::endl; std::cout << vision.m_awb_blue << std::endl; #ifdef __DESKTOP__ vision.renderVisionContours(vision.m_imageSrc); vision.renderVisionTargetCandidates(vision.m_imageUndistorded); vision.renderVisionTargetPairs(vision.m_imageUndistorded); vision.renderHorizon(vision.m_imageUndistorded, 1); vision.render3DVisionTargets(vision.m_imageUndistorded, 1); vision.render3DTopView(imageTopView); imshow("Undistort", vision.m_imageUndistorded); imshow("Src", vision.m_imageSrc); imshow("TopView", imageTopView); if (waitKey(10) == ' ') vision.capturePauseToggle(); #endif cv::Mat streamOutput = vision.m_imageUndistorded; #ifndef __DESKTOP__ // Code spécifique Raspberry (flip l'image en fonction de la position du pivot) if (inst.GetEntry("/SmartDashboard/Angle Pivot").GetDouble(1) < 0.0) { cv::flip(streamOutput, streamOutput, -1); } #endif vision.imageProcess(); vision.findVisionTargetPairs(); vision.getCenteredTargetPair(); vision.renderHud(vision.m_imageUndistorded, 1); vision.renderMax(vision.m_imageUndistorded); stream_server.PutFrame(streamOutput); } } return 0; } #endif
46308ee9498e43106ea48be6c18396720b1dbd73
1fd72a0e736c9d8e9b3f10fc424222f4ce8126a7
/morris2014.cpp
bd25f692cce02eb09e1569394d9b722f5ddafdc1
[]
no_license
shobe98/cs382_cpp
08d0eddec9df557840b85256c9ff703d5da3fb4a
4d96d32dedbc887e946b29eb9c1abc0d15aeb900
refs/heads/master
2022-06-30T14:28:29.394158
2020-05-08T20:31:20
2020-05-08T20:31:20
239,810,887
0
0
null
null
null
null
UTF-8
C++
false
false
7,131
cpp
morris2014.cpp
/* -------------------------- * CMPU-382, Spring 2020 * Authors: Andrei Stanciu, Abigail Ren * File: morris2014.cpp * -------------------------- * Implements morris2014 algorithm and main function * Defines Structs: NodeAndPrio * Defines Functions: unsuitable, DCBackprop, morris2014, main */ #include "graph2014.h" #include <algorithm> #include <cassert> #include <fstream> #include <iostream> #include <queue> #include <unordered_map> #include <vector> using namespace std; const int kMaxLabels = 1000; const int kNaN = -1; // -1 for now const int kInf = 0x3f3f3f3f; struct NodeAndPrio { int node; /// we very likeley need labels int prio; NodeAndPrio(int node = 0, int prio = 0) { this->node = node; this->prio = prio; } bool operator<(const NodeAndPrio &other) const { return prio > other.prio; // we want a min heap, thus the sign here needs to // be 'greater'. (prio queue defaults to max heap) } }; // Returns true if edge is unsuitable inline bool unsuitable(const Edge &e, const int &starting_label) { // For now an edge is unsuitable iff it is a lower case edge and it has the // same label as the initial uc edge // I'll leave this as a function in case we need to add anithing else here return e.type != 'u' && starting_label == e.C; } // for comodity we don't edit nodes int the heap, but keep track of wether we're // done with a node or not, and thus w ecan have a node appear multiple times in // the queue, I've done this multiple times with dijkstra, and the time // difference is not significant enough to make it reasonable to implement a // heap from scratch. bool DCBackprop(int source, STNU *stnu, bool debug = false) { debug && (cerr << "Currently running DCBackprop from " << stnu->numsToLabel[source] << endl); if (stnu->in_rec_stack[source]) { return false; } if (stnu->done[source]) { debug &&cerr << "Node was processed before!" << endl; return true; } stnu->in_rec_stack[source] = true; // change with N vector<int> dist(stnu->N, kInf); vector<int> label(stnu->N, 0); vector<bool> done_dijkstra(stnu->N, false); int starting_label = -1; dist[source] = 0; priority_queue<NodeAndPrio> Q; for (auto &edge : stnu->InEdges[source]) { // Only initialize the preds of the negative node connected by negative // edges if (edge.value < 0) { dist[edge.A] = edge.value; Q.push(NodeAndPrio(edge.A, dist[edge.A])); if (edge.type == 'u') { assert(starting_label == -1); starting_label = edge.C; } } } done_dijkstra[source] = true; while (!Q.empty()) { // popping int u = Q.top().node; Q.pop(); if (done_dijkstra[u]) { continue; // in case u was in the queue multiple times and we already // processed it. } done_dijkstra[u] = true; // done popping debug &&cerr << endl << "Expanding node " << stnu->numsToLabel[u] << endl; if (dist[u] >= 0) { // add new edge u->source // some bad memory management here. TODO(astanciu): change to a mtarix // that keeps track of edges actually, it's probably not needed, it's just // a constant optimisation but it doesn't change the complexity. at most // N^2 new edges are added (N per negative node), so the final complexity // is still N^3 (or N^3log(N) with binary heap) // // As mentioned in the paper, we only add ordinary edges "by virtue of // label removal rule" (where applicable). stnu->addEdge(Edge(u, source, dist[u], 'o')); // stnu->InEdges[source].push_back(Edge(u, source, dist[u], 'o')); debug && (cerr << "Added ord edge " << stnu->numsToLabel[u] << ' ' << stnu->numsToLabel[source] << ' ' << dist[u] << endl); continue; } if (stnu->is_negative_node[u]) { if (debug) { cerr << "about to enter recursion in " << stnu->numsToLabel[u] << endl; for (int i = 0; i < stnu->N; ++i) { if (dist[i] != kInf) { cerr << stnu->numsToLabel[i] << ":" << dist[i] << ' '; } } cerr << endl; } if (DCBackprop(u, stnu) == false) { return false; } } // WARN: If an edge gets added inside this forloop, iterators can get // invalidated. Safe for now. for (auto &edge : stnu->InEdges[u]) { if (edge.value < 0) { // we can only get to this case if node u has been processed (first if // statement before the loop) so all the relevant edges have been added // to u's predecessor list continue; } if (unsuitable(edge, starting_label)) { continue; } if (debug) { cerr << "Processing edge "; stnu->printEdge(edge); cerr << endl; } int v = edge.A; int new_dist = dist[u] + edge.value; if (new_dist < dist[v]) { dist[v] = new_dist; Q.push(NodeAndPrio(v, new_dist)); } } if (debug) { for (int i = 0; i < stnu->N; ++i) { if (dist[i] != kInf) { cerr << stnu->numsToLabel[i] << ":" << dist[i] << ' '; } } cerr << endl; } debug &&cerr << endl; } if (debug) { debug &&cerr << stnu->numsToLabel[source] << "'s propagation done" << endl; for (int i = 0; i < stnu->N; ++i) { if (dist[i] != kInf) { debug &&cerr << stnu->numsToLabel[i] << ":" << dist[i] << ' '; } } debug &&cerr << endl; } stnu->done[source] = true; stnu->in_rec_stack[source] = false; // Andrei's addition to the algorithm. // It is mentioned in the paper but nor present in the pseudocode. if (dist[source] < 0) { return false; } return true; } bool morris2014(string filename, bool debug = false) { STNU Graph(filename, debug); debug &&cerr << "Done reading!" << endl; for (int i = 0; i < Graph.N; ++i) { for (auto &edge : Graph.InEdges[i]) { if (edge.value < 0) { Graph.is_negative_node[i] = true; break; } } } debug &&cerr << "Done finding negative nodes!" << endl; for (int i = 0; i < Graph.N; ++i) { if (Graph.is_negative_node[i]) { debug &&cerr << "Going to call DCBackprop from main!" << endl; if (!DCBackprop(i, &Graph)) { debug &&cout << "Not DC!" << endl; return false; } } } debug &&cout << "DC!" << endl; return true; } int main(int argc, char *argv[]) { bool debug = false; if (argc >= 3) { if (string(argv[1]) == "--verbose=true") { debug = true; } else if (string(argv[1]) != "--verbose=false") { cout << "Usage: ./morris2014 --verbose={true/false} testfile " "[testfiles..]" << endl; exit(1); } } else { cout << "Usage: ./morris2014 --verbose={true/false} testfile " "[testfiles..]" << endl; exit(1); } for (int i = 2; i < argc; ++i) { cout << argv[i] << " Morris 2014: " << morris2014(string(argv[i]), debug) << endl; } return 0; }
26c100ab5b1db0e81422bcecf46a48f2ac68297f
99335dae711910ac15fd5e859f00026306499a37
/src/Render.h
2b4f4c704debe44870f0cdf23532575623b8e5b4
[]
no_license
terminal29/PrairieDog-Engine
394a7e1ac444802d711aeb6fb43e9bfa4e523369
5227a31fc653c7476bf71b56fdb788622ad15341
refs/heads/master
2021-06-17T03:38:26.775894
2017-05-10T12:24:14
2017-05-10T12:24:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
329
h
Render.h
#pragma once #include "Glyph.h" #include "Entity.h" #include <vector> #include <algorithm> #include <iostream> struct less_than_key { inline bool operator() (Entity* e1, Entity* e2) { return (e1->getPos().z < e2->getPos().z); } }; static void Render(int c_w, int c_h, std::vector<Entity> e_list) { }
9317ac49d644df31ecc1eefc44a9558d909b6faf
920c93ad3a4b88bb6bfc3cc8a81479d92b1e7e65
/Linear Search.cpp
8b1f045896479855936557315f25382ffdf9ddfb
[]
no_license
udaykhemewar/C-All-Topics
42b00560149fe80bb95aa017fb3d4cae069688aa
0292692fcbf3cf26f7688344da8f285b91686c6e
refs/heads/master
2023-05-02T17:20:19.134176
2021-05-22T18:42:36
2021-05-22T18:42:36
369,882,166
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
Linear Search.cpp
#include <iostream> using namespace std; int search(int array[], int x) { for (int i = 0; i < 5; i++) if (array[i] == x) return i; return -1; } int main() { cout<<"\nEnter the Numbers: "<<endl;; int array[5]; for (int i=0; i<5; i++) { cin>>array[i]; } int x; cout<<"Enter the number that you want to search :"; cin>>x; int result = search(array, x); (result == -1) ? cout << "Element not found" : cout << "Element found at index: " << result; }
7a2f5fd06b006e050901efc685a857ac0a33ea4a
7554af2534ee5f67e91485dad80f4ecdf59ec6d4
/src/PPApiForDotNet/Utilities.h
9de83a5ca1b1a487aff15f2d7972c2a3aef0dbfe
[]
no_license
AArnott/PPApiForDotNet
46eef8f5a93a2777deb9e5f14d670fa6ca4bdb73
15c0503771f28c62fd99ef329a41545d0a041d0d
refs/heads/master
2021-01-13T00:41:22.491487
2015-10-31T05:33:26
2015-10-31T05:33:26
45,123,075
19
4
null
null
null
null
UTF-8
C++
false
false
93
h
Utilities.h
#pragma once #include <filesystem> std::experimental::filesystem::v1::path GetModuleDir();
e143dd278add2d09ff0908ab37ccccc51e173b73
04462e43a083ef37c1e126c40fdf1d38ca81f586
/FlexEngine/include/Audio/AudioManager.hpp
3ba82beebbe7bbdfc775a6c9433c77115249f7ca
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ajweeks/FlexEngine
adb5aa135b3541e6f8189b88cf432896505d1118
fe7d4b165de8260dd9d6be4d20be7c2f9ba1ffe5
refs/heads/master
2023-08-31T14:04:17.224754
2023-08-28T23:41:27
2023-08-29T17:37:55
82,951,590
969
56
MIT
2021-05-18T18:35:27
2017-02-23T17:14:25
C++
UTF-8
C++
false
false
8,747
hpp
AudioManager.hpp
#pragma once IGNORE_WARNINGS_PUSH #define AL_ALEXT_PROTOTYPES #include "AL/al.h" #include "AL/alc.h" #include "AL/alext.h" #include "AL/efx.h" #include "AL/efx-presets.h" IGNORE_WARNINGS_POP #include "Histogram.hpp" #include <list> namespace flex { class StringBuilder; struct SoundClip_Looping { SoundClip_Looping(); SoundClip_Looping(const char* name, AudioSourceID startID, AudioSourceID loopID, AudioSourceID endID); bool IsValid() const; bool IsPlaying() const; void Start(); void End(); void Update(); void KillCurrentlyPlaying(); void DrawImGui(); enum class State { STARTING, LOOPING, ENDING, OFF }; static constexpr const char* StateStrings[] = { "Starting", "Looping", "Ending", "Off" }; static_assert(ARRAY_LENGTH(StateStrings) == (u32)State::OFF + 1, "Length of StateStrings must match length of State enum"); // Optional AudioSourceID start = InvalidAudioSourceID; AudioSourceID loop = InvalidAudioSourceID; // Optional AudioSourceID end = InvalidAudioSourceID; State state = State::OFF; real timeInState = 0.0f; real stateLength = -1.0f; private: void ChangeToState(State newState); real m_FadeFastDuration = 0.1f; real m_FadeDuration = 0.3f; // Debug only const char* m_Name = nullptr; Histogram m_TimeInStateHisto; }; struct SoundClip_LoopingSimple { SoundClip_LoopingSimple(); SoundClip_LoopingSimple(const char* name, StringID loopSID, bool b2D); bool IsValid() const; bool IsPlaying() const; void FadeIn(); void FadeOut(); void Update(); void KillCurrentlyPlaying(); void SetPitch(real pitch); void SetGainMultiplier(real gainMultiplier); // Returns true when sound clip has changed bool DrawImGui(); // Serialized value StringID loopSID = InvalidStringID; // Runtime value AudioSourceID loop = InvalidAudioSourceID; real fadeInTimeRemaining = -1.0f; real fadeOutTimeRemaining = -1.0f; private: real m_FadeFastDuration = 0.1f; real m_FadeDuration = 0.3f; bool bPlaying = false; // Debug only const char* m_Name = "Uninitialized"; Histogram m_VolHisto; }; struct AudioEffect { enum class Type : i32 { REVERB, CHORUS, DISTORTION, ECHO, FLANGER, FREQUENCY_SHIFTER, VOCAL_MORPHER, PITCH_SHITER, RING_MODULATOR, AUTOWAH, COMPRESSOR, EQUALIZER, EAX_REVERB, // TODO: low/hi/band pass _NONE }; EFXEAXREVERBPROPERTIES reverbProperties; ALuint effectID; Type type; i32 presetIndex = -1; }; static const char* AudioEffectTypeStrings[] = { "Reverb", "Chorus", "Distortion", "Echo", "Flanger", "Frequency Shifter", "Vocal Morpher", "Pitch Shifter", "Ring Modulator", "Auto Wah", "Compressor", "Equalizer", "EAX Reverb", "None" }; static_assert(ARRAY_LENGTH(AudioEffectTypeStrings) == (u32)AudioEffect::Type::_NONE + 1, "AudioEffectTypeStrings length must match AudioEffect::Type enum"); AudioEffect::Type AudioEffectTypeFromALEffect(i32 alEffect); const char* AudioEffectTypeToString(AudioEffect::Type type); AudioEffect::Type AudioEffectTypeFromString(const char* typeStr); // TODO: Make global instance like every other manager? // TODO: Inherit from System base class? class AudioManager { public: struct Source { ALuint source = InvalidAudioSourceID; real gain = 1.0f; real gainMultiplier = 1.0f; real pitch = 1.0f; real length = -1.0f; // AL_INITIAL, AL_PLAYING, AL_PAUSED, or AL_STOPPED ALenum state = AL_INITIAL; // If non-zero, we're fading in when bFadingIn, and out otherwise real fadeDuration = 0.0f; real fadeDurationRemaining = 0.0f; bool bFadingIn; // "2D" sounds remain at a constant volume regardless of listener position bool b2D; std::string fileName; bool bLooping = false; }; static void Initialize(); static void Destroy(); static void Update(); static void StopAllSources(); static real NoteToFrequencyHz(i32 note); static AudioSourceID SynthesizeSound(sec length, real freq); static AudioSourceID SynthesizeMelody(real bpm = 340.0f); static void SetListenerPos(const glm::vec3& posWS); static void SetListenerVel(const glm::vec3& velocity); /* [0.0, 1.0] logarithmic */ static void SetMasterGain(real masterGain); static real GetMasterGain(); static bool PlaySource(AudioSourceID sourceID, bool bForceRestart = true); static bool PlaySourceWithGain(AudioSourceID sourceID, real gain, bool bForceRestart = true); // Start source partway through (t in [0, 1]) static bool PlaySourceAtOffset(AudioSourceID sourceID, real t); static bool PlaySourceAtPosWS(AudioSourceID sourceID, const glm::vec3& posWS, bool bForceRestart = true); static bool PauseSource(AudioSourceID sourceID); static bool StopSource(AudioSourceID sourceID); static bool PlayNote(real frequency, sec length, real gain); static void SetSourcePositionWS(AudioSourceID sourceID, const glm::vec3& posWS); static void MarkSourceTemporary(AudioSourceID sourceID); static void FadeSourceIn(AudioSourceID sourceID, real fadeDuration, real fadeMaxDuration); static void FadeSourceOut(AudioSourceID sourceID, real fadeDuration, real fadeMaxDuration); /* Volume of sound [0.0, 1.0] (logarithmic) */ static void SetSourceGain(AudioSourceID sourceID, real gain); static real GetSourceGain(AudioSourceID sourceID); static void SetSourceGainMultiplier(AudioSourceID sourceID, real gainMultiplier); static real GetSourceGainMultiplier(AudioSourceID sourceID); static bool IsSource2D(AudioSourceID sourceID); static void AddToSourcePitch(AudioSourceID sourceID, real deltaPitch); /* Pitch of sound [0.5, 2.0] */ static void SetSourcePitch(AudioSourceID sourceID, real pitch); static real GetSourcePitch(AudioSourceID sourceID); static void SetSourceLooping(AudioSourceID sourceID, bool bLooping); static bool GetSourceLooping(AudioSourceID sourceID); static bool IsSourcePlaying(AudioSourceID sourceID); static real GetSourceLength(AudioSourceID sourceID); static u8* GetSourceSamples(AudioSourceID sourceID, u32& outSampleCount, u32& outVersion); static Source* GetSource(AudioSourceID sourceID); static std::string GetSourceFileName(AudioSourceID sourceID); static real GetSourcePlaybackPos(AudioSourceID sourceID); static void ToggleMuted(); static void SetMuted(bool bMuted); static bool IsMuted(); static void DrawImGuiObjects(); static bool AudioFileNameSIDField(const char* label, StringID& sourceFileNameSID, bool* bTreeOpen); static AudioEffect LoadReverbEffect(const EFXEAXREVERBPROPERTIES* reverb); // Returns the created effect type (Either EAX Reverb or normal Reverb) static i32 SetupReverbEffect(const EFXEAXREVERBPROPERTIES* reverb, ALuint& effectID); static void UpdateReverbEffect(u32 slotID, i32 effectID); static i32 SLOT_DEFAULT_2D; static i32 SLOT_DEFAULT_3D; private: friend ResourceManager; static AudioSourceID AddAudioSource(const std::string& filePath, StringBuilder* outErrorStr = nullptr, bool b2D = false); static AudioSourceID ReplaceAudioSource(const std::string& filePath, AudioSourceID sourceID, StringBuilder* outErrorStr = nullptr); static AudioSourceID SynthesizeSoundCommon(AudioSourceID newID, i16* data, u32 bufferSize, u32 sampleRate, i32 format, bool b2D); static bool DestroyAudioSource(AudioSourceID sourceID); static void ClearAllAudioSources(); // If error is not AL_NO_ERROR then an appropriate error message is printed // Returns true when error != AL_NO_ERROR static bool DisplayALError(const char* errorMessage, ALenum error); static void PrintAudioDevices(const ALCchar* devices); static ALuint GetNextAvailableSourceAndBufferIndex(); static AudioSourceID AddAudioSourceInternal(AudioSourceID sourceID, const std::string& filePath, StringBuilder* outErrorStr, bool b2D); static void UpdateSourceGain(AudioSourceID sourceID); static void CreateAudioEffects(); static void ClearAudioEffects(); static real s_MasterGain; static bool s_Muted; static const i32 NUM_BUFFERS = 2048; static ALuint s_Buffers[NUM_BUFFERS]; // Editor-only < static u8* s_WaveData[NUM_BUFFERS]; static u32 s_WaveDataLengths[NUM_BUFFERS]; // Monotonically increasing value, incrementing each time a new version is loaded static u32 s_WaveDataVersions[NUM_BUFFERS]; // > End Editor-only static std::array<Source, NUM_BUFFERS> s_Sources; static std::list<AudioSourceID> s_TemporarySources; static std::vector<AudioEffect> s_Effects; static ALCdevice* s_Device; static ALCcontext* s_Context; static AudioSourceID s_BeepID; AudioManager() = delete; ~AudioManager() = delete; }; } // namespace flex
03f8f533e01c8a6d9384443538a81225186ab293
1f8e76e13de19e604e6845b87d68d6b1a989addb
/review_2_files/review_2_employee_class/Project/Employee.cpp
66f0739dd007088e723db1a31280be4ad6cf7554
[]
no_license
tngo0508/Cplusplus-OCC-
fa74b0a4e67cb389c7ad15ff5c5296be6107103b
9311878e0e246e267b2f5e2608ec18745b72ef78
refs/heads/master
2021-09-20T17:05:23.971332
2018-08-12T22:01:12
2018-08-12T22:01:12
104,405,783
0
0
null
null
null
null
UTF-8
C++
false
false
792
cpp
Employee.cpp
/* HourlyEmployee.cpp Implementation of class HourlyEmployee */ #include "Employee.h" Employee::Employee( ) { //NOTE: Not necessary to give a value to a string, because // it will be initialized by the default constructor // of the STL string class name = "No name yet"; id = 0; } Employee::Employee(const string& newName, int newID) { name = newName; id = newID; } string Employee::getName( ) const { return name; } int Employee::getID() const { return id; } void Employee::setName(const string& newName) { name = newName; } void Employee::setID(int newID) { id = newID; } void Employee::print( ) const { cout << "Employee: " << name << endl << "ID: " << id << endl; } Employee::~Employee( ) { }
b1ea6386da25af9cdcf0ccdb9c43f5aba0d854a0
e3e6112eb7bf20b6823c83e5769bfe6ccfa45e0d
/Functor/src/main.cpp
a05dba9b5cd10f5a8fe12419b7fec49da2683d1c
[]
no_license
AlexandreHiroyuki/Testes
0d8d255c3352dba8ac4385f6c27f85fe5cbc2ffd
4e52c5566c60d6b47196d5b3702ff8140d00cde9
refs/heads/master
2021-11-26T23:06:25.157855
2021-11-12T20:21:13
2021-11-12T20:21:13
150,783,827
0
0
null
null
null
null
UTF-8
C++
false
false
244
cpp
main.cpp
#include <iostream> using namespace std; class myFunc { private: int _count; public: myFunc(int a) : _count(a) {} int operator()(int x) { return x + _count; } }; int main() { myFunc obj(10); cout << obj(2) << endl; return 0; }
98c1f236a8bc7a97d22b4a148912633a50cbc3c5
c9c83f433358b06a554f2b681f96928bed31d70a
/inc/VM.hpp
2667764207f0befccd9fbd4a4f867293d917093f
[]
no_license
rkyslyy/AbstractVM
983cbbb6c7a269268d812a6b6a560831e139cb85
8f94f5b392945da154cdbb92f644d867f8496f63
refs/heads/master
2020-03-23T22:25:07.459709
2018-12-14T15:44:05
2018-12-14T15:44:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,856
hpp
VM.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* VM.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rkyslyy <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/23 15:04:22 by rkyslyy #+# #+# */ /* Updated: 2018/08/23 15:04:23 by rkyslyy ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef VM_HPP #define VM_HPP #include <list> #include "Exceptions.hpp" #include "Operand.hpp" #include "Lexer.hpp" #include "Parser.hpp" #include "Visualizer.hpp" class VM { private: std::list<const IOperand*> _stack; Factory _factory; Lexer _lexer; Parser _parser; Visualizer _visualizer; bool _visualization; void _push(eOperandType, std::string); void _assertV(eOperandType, std::string, int); void _dump(int); void _add(int); void _sub(int); void _mul(int); void _div(int); void _mod(int); void _pop(int); void _print(int); std::string _trim(std::string, eOperandType); void _checkAssertionOverflow(eOperandType, std::string, int , std::map<eOperandType, std::string> &); public: VM(); VM(VM const & src); VM &operator=(VM const & src); ~VM(); void readInput(int, char**); void run(); }; #endif
16e6a052652c0a22dcc796f367bda2f748595603
1f9e4136b21bbb1cfc49dbeb7f42f684ddc7d0e1
/MarkdownEditorViewPart/ActionsRegister.cpp
44216839fddf5fc3aa70e1fb5c8dcea1beed02c2
[]
no_license
sld666666/HtmlWriter
c64129caf13add9d6786ad9a618c33fa3d775446
c7c7c29025e185271288913da90a75807cfc996b
refs/heads/master
2020-06-06T16:26:10.963660
2013-05-15T04:36:49
2013-05-15T04:36:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
ActionsRegister.cpp
#include "ActionsRegister.h" #include "actions/MarkdownEditorToolBar.h" #include "ServiceManager.h" using service::ServiceManager; ActionsRegister::ActionsRegister(QObject *parent) : QObject(parent) { } ActionsRegister::~ActionsRegister() { } void ActionsRegister::registerActions() { ServiceManager::instance().appendService(new MarkdownEditorToolBar(NULL)); }
2ca9a364974f6808f7ae4dc21a5d703b6e034ac5
4f9087d39d862c405c827a9e2f693797508d246f
/Chat/h/Chat_server_message_sender.h
662498fd0b2eb42f6311db88ca1afa5709498e5a
[]
no_license
aureooms-ulb-2010-2015/2011-2012-infof209-project
e1204eabe9dce71a6e843fdcf279103e246fb05b
169ee99ce38ffbba6cc4fcc9e359314c934d648e
refs/heads/master
2021-01-16T01:01:29.819169
2014-12-08T14:50:06
2014-12-08T14:50:06
38,203,046
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
Chat_server_message_sender.h
#if !defined(_CHAT_SERVER_MESSAGE_SENDER_H) #define _CHAT_SERVER_MESSAGE_SENDER_H #include "../../Library/Socket/ServerSocket.h" #include "./Feed.h" #include "./Chat_notification.h" #include <string> class Chat_client_manager; class Chat_server_message_sender{ private: Chat_client_manager *manager; ServerSocket *socket; string pseudo; public: Chat_server_message_sender(Chat_client_manager *manager,ServerSocket &socket); ~Chat_server_message_sender(); virtual Chat_server_message_sender& send_feed(Feed *feed); }; #endif //_CHAT_SERVER_MESSAGE_SENDER_H
b247a5a88687a9f0fb85c8272ecda1bce3be47da
07f58b7bce3b6fdab22e82a83c6de1c2a95e1f45
/include/psscpp/type_traits.h
20442d3c8c5e1e84b635f6e905e38635751c807c
[]
no_license
psalvaggio/psscpp
5c8f3f42b0deca1f44c586bcfe39ade05d756191
c5561cf76d751e7296c57c1ea0fd628b51af4ff9
refs/heads/master
2020-07-21T12:13:26.398254
2019-09-09T18:12:36
2019-09-09T18:12:36
206,861,592
0
0
null
null
null
null
UTF-8
C++
false
false
2,966
h
type_traits.h
/** Extensions to the standard type_traits header * * \file include/psscpp/type_traits.h * \author Dr. Philip Salvaggio (salvaggio.philip@gmail.com) * \date 06 Sep 2019 */ #pragma once #include <type_traits> namespace pss { /// Tests if the decayed types of the two arguments are the same template <class T, class U> struct decay_equiv : std::is_same<typename std::decay<T>::type, typename std::decay<U>::type> { }; #if __cplusplus >= 201402L template <class T, class U> #if __cplusplus >= 201703L inline #endif constexpr bool decay_equiv_v = decay_equiv<T, U>::value; #endif // Bring some C++17 traits back to C++11 #if __cplusplus < 201703L template <bool B> using bool_constant = std::integral_constant<bool, B>; /// Conjunction is a logical AND of all of the template parameters template <class...> struct conjunction : std::true_type {}; template <class B1> struct conjunction<B1> : B1 {}; template <class B1, class... Bn> struct conjunction<B1, Bn...> : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {}; /// Disjunction is a logcial OR of all of the template parameters template <class...> struct disjunction : std::false_type {}; template <class B1> struct disjunction<B1> : B1 {}; template <class B1, class... Bn> struct disjunction<B1, Bn...> : std::conditional<bool(B1::value), B1, disjunction<Bn...>>::type {}; /// Logical not of all of the template parameters template <class B> struct negation : bool_constant<!bool(B::value)> {}; #if __cplusplus >= 201402L template <class... B> constexpr bool conjunction_v = conjunction<B...>::value; template <class... B> constexpr bool disjunction_v = disjunction<B...>::value; template <class B> constexpr bool negation_v = negation<B>::value; #endif #else template <bool B> using bool_constant = std::bool_constant<B>; template <class... B> using conjunction = std::conjunction<B...>; template <class... B> inline constexpr bool conjunction_v = std::conjunction_v<B...>; template <class... B> using disjunction = std::disjunction<B...>; template <class... B> inline constexpr bool disjunction_v = std::disjunction_v<B...>; template <class B> using negation = std::negation<B>; template <class B> inline constexpr bool negation_v = negation<B>::value; #endif #if __cplusplus < 201402L template <class T> struct is_null_pointer : std::is_same<std::nullptr_t, typename std::remove_cv<T>::type> {}; #else template <class T> using is_null_pointer = std::is_null_pointer<T>; template <class T> #if __cplusplus >= 201703L inline #endif constexpr bool is_null_pointer_v = is_null_pointer_v<T>; #endif /// Tests whether all of the types are decay-equivalent template <class T, class... Ts> struct all_decay_equiv : conjunction<decay_equiv<T, Ts>...> {}; #if __cplusplus >= 201402L template <class T, class... Ts> #if __cplusplus >= 201703L inline #endif constexpr bool all_decay_equiv_v = conjunction_v<decay_equiv<T, Ts>...>; #endif }
73edc675c8521a1df6bb712609a328ba477aaaa8
a13e24b39fab4f5d9bc57d0bd5eb536c38a5eef1
/source/Plugins/Generic/AtmosphereScattering/WeatherUbo.hpp
43054dca5a8dfa09c5f931e9a73d0e264d2aadbc
[ "MIT" ]
permissive
DragonJoker/Castor3D
2bbd0eeba403a37570bfc959d58a6c8a01429c60
32a2e4bc5c6ea0d0a27f3c58f8edb74fbc7e59ce
refs/heads/development
2023-09-04T15:46:36.438955
2023-08-30T05:37:14
2023-08-30T12:34:39
34,847,313
424
18
MIT
2023-09-14T11:10:10
2015-04-30T09:53:00
C++
UTF-8
C++
false
false
2,915
hpp
WeatherUbo.hpp
/* See LICENSE file in root folder */ #ifndef ___C3DAS_WeatherUbo_H___ #define ___C3DAS_WeatherUbo_H___ #include "WeatherConfig.hpp" #include <Castor3D/Castor3DModule.hpp> #include <Castor3D/Buffer/UniformBufferOffset.hpp> #include <CastorUtils/Math/RangedValue.hpp> #include <ShaderWriter/BaseTypes/Array.hpp> #include <ShaderWriter/BaseTypes/Int.hpp> #include <ShaderWriter/CompositeTypes/StructHelper.hpp> #include <ShaderWriter/CompositeTypes/StructInstance.hpp> #include <ShaderWriter/CompositeTypes/StructInstanceHelper.hpp> #include <ShaderWriter/MatTypes/Mat4.hpp> #include <ShaderWriter/VecTypes/Vec4.hpp> namespace atmosphere_scattering { struct WeatherData : public sdw::StructInstanceHelperT< "WeatherData" , sdw::type::MemoryLayout::eStd140 , sdw::FloatField< "perlinAmplitude" > , sdw::FloatField< "perlinFrequency" > , sdw::FloatField< "perlinScale" > , sdw::UIntField< "perlinOctaves" > > { WeatherData( sdw::ShaderWriter & writer , ast::expr::ExprPtr expr , bool enabled ) : StructInstanceHelperT{ writer, std::move( expr ), enabled } { } auto perlinAmplitude()const { return getMember< "perlinAmplitude" >(); } auto perlinFrequency()const { return getMember< "perlinFrequency" >(); } auto perlinScale()const { return getMember< "perlinScale" >(); } auto perlinOctaves()const { return getMember< "perlinOctaves" >(); } }; Writer_Parameter( WeatherData ); class WeatherUbo { private: using Configuration = WeatherConfig; public: WeatherUbo( castor3d::RenderDevice const & device , bool & dirty ); ~WeatherUbo(); void cpuUpdate( Configuration const & config ); void createPassBinding( crg::FramePass & pass , uint32_t binding )const { m_ubo.createPassBinding( pass, "WeatherCfg", binding ); } void createSizedBinding( ashes::DescriptorSet & descriptorSet , VkDescriptorSetLayoutBinding const & layoutBinding )const { return m_ubo.createSizedBinding( descriptorSet, layoutBinding ); } ashes::WriteDescriptorSet getDescriptorWrite( uint32_t dstBinding , uint32_t dstArrayElement = 0u )const { return m_ubo.getDescriptorWrite( dstBinding, dstArrayElement ); } castor3d::UniformBufferOffsetT< Configuration > const & getUbo()const { return m_ubo; } castor3d::UniformBufferOffsetT< Configuration > & getUbo() { return m_ubo; } public: static const castor::String Buffer; static const castor::String Data; private: castor3d::RenderDevice const & m_device; castor3d::UniformBufferOffsetT< Configuration > m_ubo; CheckedWeatherConfig m_config; }; } #define C3D_Weather( writer, binding, set )\ auto weatherBuffer = writer.declUniformBuffer<>( atmosphere_scattering::WeatherUbo::Buffer, binding, set );\ auto c3d_weatherData = weatherBuffer.declMember< atmosphere_scattering::WeatherData >( atmosphere_scattering::WeatherUbo::Data );\ weatherBuffer.end() #endif
de44313c43395768ea2d717b9b17c49277c77b39
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-s3-encryption/source/s3-encryption/modules/CryptoModuleFactory.cpp
caae26e2cbc21d09c2f33230f58a57b55d31b43c
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
4,046
cpp
CryptoModuleFactory.cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/s3-encryption/modules/CryptoModule.h> #include <aws/s3-encryption/modules/CryptoModuleFactory.h> #include <aws/core/utils/logging/LogMacros.h> namespace Aws { namespace S3Encryption { namespace Modules { static const char* const ALLOCATION_TAG = "CryptoModuleFactory"; CryptoModuleFactory::CryptoModuleFactory() { m_cryptoFactories.insert(std::pair < CryptoMode, std::shared_ptr<CryptoModuleAbstractFactory>>(CryptoModuleFactoryEO().HandlesMode(), Aws::MakeShared<CryptoModuleFactoryEO>(ALLOCATION_TAG, CryptoModuleFactoryEO()))); m_cryptoFactories.insert(std::pair < CryptoMode, std::shared_ptr<CryptoModuleAbstractFactory>>(CryptoModuleFactoryAE().HandlesMode(), Aws::MakeShared<CryptoModuleFactoryAE>(ALLOCATION_TAG, CryptoModuleFactoryAE()))); m_cryptoFactories.insert(std::pair < CryptoMode, std::shared_ptr<CryptoModuleAbstractFactory>>(CryptoModuleFactoryStrictAE().HandlesMode(), Aws::MakeShared<CryptoModuleFactoryStrictAE>(ALLOCATION_TAG, CryptoModuleFactoryStrictAE()))); } std::shared_ptr<CryptoModule> CryptoModuleFactory::FetchCryptoModule(const std::shared_ptr<Aws::Utils::Crypto::EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig) const { auto entry = m_cryptoFactories.find(cryptoConfig.GetCryptoMode()); std::shared_ptr<CryptoModuleAbstractFactory> factory = entry->second; return factory->CreateModule(encryptionMaterials, cryptoConfig); } CryptoModuleFactoryEO::CryptoModuleFactoryEO() { } std::shared_ptr<CryptoModule> CryptoModuleFactoryEO::CreateModule(const std::shared_ptr<Aws::Utils::Crypto::EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig) { return Aws::MakeShared<CryptoModuleEO>(ALLOCATION_TAG, encryptionMaterials, cryptoConfig); } CryptoMode CryptoModuleFactoryEO::HandlesMode() const { return CryptoMode::ENCRYPTION_ONLY; } CryptoModuleFactoryAE::CryptoModuleFactoryAE() { } std::shared_ptr<CryptoModule> CryptoModuleFactoryAE::CreateModule(const std::shared_ptr<Aws::Utils::Crypto::EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig) { return Aws::MakeShared<CryptoModuleAE>(ALLOCATION_TAG, encryptionMaterials, cryptoConfig); } CryptoMode CryptoModuleFactoryAE::HandlesMode() const { return CryptoMode::AUTHENTICATED_ENCRYPTION; } CryptoModuleFactoryStrictAE::CryptoModuleFactoryStrictAE() { } std::shared_ptr<CryptoModule> CryptoModuleFactoryStrictAE::CreateModule(const std::shared_ptr<Aws::Utils::Crypto::EncryptionMaterials>& encryptionMaterials, const CryptoConfiguration& cryptoConfig) { return Aws::MakeShared<CryptoModuleStrictAE>(ALLOCATION_TAG, encryptionMaterials, cryptoConfig); } CryptoMode CryptoModuleFactoryStrictAE::HandlesMode() const { return CryptoMode::STRICT_AUTHENTICATED_ENCRYPTION; } } //namespace Modules } //namespace S3Encryption } //namespace Aws
70fd3956c5f1d0755813269150df61e335a1f34b
bcb5f0ad80e0e08d93e01802b4cb351202f49183
/sourcefiles/shuffle.h
5d35e6438ea17a9166a22d3ee5208edf26763905
[]
no_license
kacpwoja/EADS-Sequence
0e5f26505add08775c28ca9721e7cc2949ec37d0
72e6bc8d0a136071abeb580e9e9086efe43638f9
refs/heads/master
2020-03-08T15:14:33.915896
2018-04-05T13:01:44
2018-04-05T13:01:44
128,206,392
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
h
shuffle.h
#ifndef SHUFFLE #define SHUFFLE #include "sequence.h" template <typename Key, typename Info> Sequence<Key, Info> shuffle( const Sequence<Key, Info> &S1, int start1, int len1, const Sequence<Key, Info> &S2, int start2, int len2, int repeat) { if( start1 < 0 || start2 < 0 || len1 < 0 || len2 < 0 || repeat < 1 ) return Sequence<Key, Info>(); //Creating an output sequence, integers to store the current index being copied Sequence<Key, Info> outseq; int index1 = start1, index2 = start2; int size1 = S1.length(), size2 = S2.length(); //Declaring temporary Key and Info to store the data being copied Key tkey = Key(); Info tinfo = Info(); //Copyting elements for( ; repeat > 0; repeat-- ) { for( int i = 0; index1 < size1 && i < len1; i++ ) { if( S1.getNode( index1, tkey, tinfo ) ) outseq.pushBack( tkey, tinfo ); index1++; } for( int i = 0; index2 < size2 && i < len2; i++ ) { if( S2.getNode( index2, tkey, tinfo ) ) outseq.pushBack( tkey, tinfo ); index2++; } } //Returning the created sequence return outseq; } #endif
15765c87403fae13e719b48b2ba6f094e01dc22c
6c5fea76ce7abfdc637daf8978287c905f237792
/hackerrank/stl/deque.cpp
bd5e4f38ced2b5689053ea308fb4fbafd625a3c9
[]
no_license
Gurpreet3131/competitiveProgramming
d4ce8341d76b4d5dbce2d59bc677c1fd0e090f48
112d7d1d94a787c3ad07e7c170d6573e2b26ca4a
refs/heads/master
2021-08-12T07:54:39.729856
2017-11-14T15:12:20
2017-11-14T15:12:20
109,845,283
0
0
null
null
null
null
UTF-8
C++
false
false
815
cpp
deque.cpp
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <set> #include <map> #include <string.h> #include <deque> using namespace std; int n,k,a[10001]; void findmax() { deque<int> dqueue; int i; for(i=0;i<k;i++) { while((!dqueue.empty()) && a[i]>=a[dqueue.back()]) dqueue.pop_back(); dqueue.push_back(i); } printf("%d ",a[dqueue.front()]); for(;i<n;i++) { while((!dqueue.empty()) && dqueue.front()<=i-k) dqueue.pop_front(); while((!dqueue.empty()) && a[i]>=a[dqueue.back()]) dqueue.pop_back(); dqueue.push_back(i); printf("%d ",a[dqueue.front()]); } printf("\n"); } int main() { int t; scanf("%d",&t); //map<string,int>::iterator itr; while(t-->0) { scanf("%d%d",&n,&k); for(int i=0;i<n;i++) scanf("%d",&a[i]); findmax(); } return 0; }
9184d6f422b6e82417b70c00a5be8e8aa29d1dad
0d3641838da786642f7f1ef6a596632636fdfe6a
/src/Math/EVector.cpp
1bdd7a3c9a04b43bc36dcd52646c5e64e370cd11
[]
no_license
ericrobolson/SimpleGameEngine
93cbdb8f084b6b486f74361b478120691c73434a
eaad752e496d85474a2276c10fc159c24b3f4af3
refs/heads/master
2021-07-02T16:11:23.173761
2019-05-16T03:46:10
2019-05-16T03:46:10
148,493,179
1
0
null
2019-05-16T03:46:11
2018-09-12T14:26:58
C++
UTF-8
C++
false
false
174
cpp
EVector.cpp
#include "EVector.h" using namespace SGE_Math; EVector::EVector() { //ctor } EVector::EVector(const EVector& e) { *this = e; } EVector::~EVector() { //dtor }
6541f4128562793ca9544a18a6ef32d9d23a1c6b
8ef0a616cdfb3c56a7bcf97a8b673edd225d694b
/ionTori/State.cpp
99d541310507be63bf12259f8fa34c66264a3eaa
[]
no_license
laofei177/radproc_linux
d10f49f0b05aa9b2680003a7eb59a0d28fec48e7
540f42fd9bfabb19ade34371532953bf2c25ed2d
refs/heads/master
2023-01-01T14:08:18.652895
2020-10-18T18:01:31
2020-10-18T18:01:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,868
cpp
State.cpp
#include "State.h" #include "globalVariables.h" #include "torusFunctions.h" #include "modelParameters.h" #include <fparameters/Dimension.h> #include <fmath/physics.h> #include <fparameters/SpaceIterator.h> #include <fparameters/parameters.h> #include <boost/property_tree/ptree.hpp> //#include <fmath/bisection.h> using namespace std; State::State(boost::property_tree::ptree& cfg) : electron{ "electron" }, photon{ "photon" }, proton("proton"), magf(photon.ps, false), tempElectrons(photon.ps, false), tempIons(photon.ps, false), denf_i(photon.ps, false), denf_e(photon.ps, false) { particles.push_back(&electron); particles.push_back(&photon); particles.push_back(&proton); for (auto p : particles) { initializeParticle(*p, cfg); } magf.initialize(); magf.fill([&](const SpaceIterator& i){ double r=i.val(DIM_R); double theta=i.val(DIM_THETA); return sqrt(magFieldPar*24.0*pi*totalPressure(r,theta)); }); denf_i.initialize(); denf_i.fill([&](const SpaceIterator& i) { double r=i.val(DIM_R); double theta=i.val(DIM_THETA); return massDensity(r,theta)/(atomicMassUnit*iMeanMolecularWeight); }); denf_e.initialize(); denf_e.fill([&](const SpaceIterator& i) { double r=i.val(DIM_R); double theta=i.val(DIM_THETA); return massDensity(r,theta)/(atomicMassUnit*eMeanMolecularWeight); }); tempElectrons.initialize(); tempElectrons.fill([&](const SpaceIterator& i) { double r=i.val(DIM_R); double theta=i.val(DIM_THETA); return electronTemp(r,theta); }); tempIons.initialize(); tempIons.fill([&](const SpaceIterator& i) { double r=i.val(DIM_R); double theta=i.val(DIM_THETA); return ionTemp(r,theta); }); } Dimension* State::createDimension(Particle& p, string dimid, function<void(Vector&,double,double)> initializer, boost::property_tree::ptree& cfg) { int samples=p.getpar<int>(cfg,"dim."+dimid+".samples"); double min=p.getpar<double>(cfg,"dim."+dimid+".min"); double max=p.getpar<double>(cfg,"dim."+dimid+".max"); return new Dimension(samples,bind(initializer,placeholders::_1,min,max)); } void State::initializeParticle(Particle& p,boost::property_tree::ptree& cfg) { using std::bind; p.configure(cfg.get_child("particle.default")); p.configure(cfg.get_child("particle."+p.id)); // add dimension for energies //p.ps.add(createDimension(p,"energy",initEnergyPoints,cfg)); p.ps.add(new Dimension(nE,bind(initEnergyPoints,placeholders::_1, logMinEnergy,logMaxEnergy))); // add dimension for r double dr = (edgeRadius-cuspRadius)/nR; p.ps.add(new Dimension(nR,bind(initGridLinearly,placeholders::_1, cuspRadius+dr/2,edgeRadius-dr/2))); // add dimension for theta p.ps.add(new Dimension(nTheta,bind(initGridLinearly,std::placeholders::_1, minPolarAngle,maxPolarAngle))); p.initialize(); }
33bcb1353b3dc55d1fa18cf2a2e50a58b1dbb52b
cf296426ba12126a2b221d7e1a492021b6ce42ba
/Debug/memory_manager/samples/main.cpp
327346397916f515c392baa6549309c95b15ddb0
[]
no_license
rexou/Cpp-Tools
b49e5dbbd4117d0f65b0b31a71aad7b6f1a0b461
2f925a0b998f7d1a6e067a0aa5b0090a2cc10ae0
refs/heads/master
2021-01-17T08:32:10.864349
2016-07-27T08:38:13
2016-07-27T08:38:13
4,595,731
0
0
null
null
null
null
UTF-8
C++
false
false
709
cpp
main.cpp
/* ** main.cpp for test utilities ** by le-cor_w aka rexou */ #include <iostream> #include <memory_manager.hpp> #define DEFAULT_LOGFILE_NAME "memory_leaks.report" struct A { A() { std::cout << "A::A()" << std::endl; } ~A() { std::cout << "A::~A" << std::endl; } A(const A &other) { (void)other; std::cout << "A::A(const A &)" << std::endl; } void foo() { std::cout << "void A::foo()" << std::endl; } }; int main() { if (!(Debug::MemoryManager::init(DEFAULT_LOGFILE_NAME))) return 1; A *basic_a = new A; A *basic_a2 = new A(); A *array_a = new A[2]; (void)basic_a; delete basic_a2; delete [] array_a; Debug::MemoryManager::report_leaks(); }
941d183e2c366a562f0a3a27d56438dc44a94e05
9ed3330a736f6ef445bd083db0c131143b53dbc9
/Lab9/q2.cpp
b0bb91075876e391e1d1d06224ab609b8a7b8393
[]
no_license
Shaunmak1214/C-plusplus-Tutorials
7513ff4e7775aadb47e778e643d080894b5661f8
f73f0b5b6db8ef376305c639be4e7faad730e4cd
refs/heads/master
2022-12-28T12:17:36.868143
2020-10-15T06:08:05
2020-10-15T06:08:05
296,255,164
0
0
null
null
null
null
UTF-8
C++
false
false
2,688
cpp
q2.cpp
#include<iostream> #include<iomanip> #include<string> #include<stdio.h> #include<stdlib.h> using namespace std; class ChoreographyMarks{ private: float points, total; public: ChoreographyMarks (){ total = 30; } void setCgPoints(){ cout << "Enter Choreography Marks [max:30] : "; cin >> points; } friend class Dancer; }; class InventiveMarks{ private: float points,total; public: InventiveMarks(){ total = 20; } void SetInvPoints(){ cout << "Enter Inventive Marks [max:20] : "; cin >> points; } friend class Dancer; }; class Dancer{ private: string name; int age; float finalpoints=0, cpoints=0, ipoints=0; public: void set_details(){ cout << "\n:::::Details for Dancer:::::" << endl; cout << "Enter name : "; cin.ignore(); getline(cin, name); cout << "Enter age : "; cin >> age; cin.ignore(); } void calcFinalPoints(ChoreographyMarks CM ,InventiveMarks IM){ cpoints = (CM.points/CM.total)*100; ipoints = (IM.points/IM.total)*100; finalpoints = (CM.points + IM.points)/(CM.total + IM.total)*100; } int getAge(){ return age; } string getName(){ return name; } void displayScoreDetails(){ cout << "\n:::::Score Board:::::" << endl; cout << "Choreography : " << cpoints << endl; cout << "Inventive : " << ipoints << endl; cout << "Final score : " << finalpoints << endl; cout << "==============================================" << endl; } }; int main(){ int num; cout << "Enter number of dancers" << endl; cin >> num; cout << endl; cin.ignore(); ChoreographyMarks cm; InventiveMarks im; Dancer *p; p = new Dancer[num]; for(int i=0; i<num; i++){ p[i].set_details(); cm.setCgPoints(); im.SetInvPoints(); p->calcFinalPoints(cm, im); cout << "-----------------------------------------" << endl; cout << "=========================================" << endl; cout << "Dancer #" << i+1 << endl; cout << "=========================================" << endl; cout << "Name\t= " << p[i].getName() << endl; cout << "Age\t= " << p[i].getAge(); p->displayScoreDetails(); cout << "=========================================" << endl; cout << "-----------------------------------------" << endl; cout << endl; } delete[] p; return 0; }
69aa12f6600af7f9502c29141765dd2d6acfec86
25e47659d6f1e3abc8c1e367ce4264431d19a568
/HeadFirstC++/Class初探3-第一编写.h文件/BOOK.h
1766fc83864d2104110468578a5935c53dc8c954
[]
no_license
yeze322/Linux-C
5a5fa08152b99bbe64a40bd0cac9766f8f6cd5f6
d78181ad65d6cbd21ce2e79e34e87f0ca40f1181
refs/heads/master
2021-01-20T06:11:55.414324
2018-07-20T02:53:59
2018-07-20T02:54:43
30,003,334
0
3
null
null
null
null
UTF-8
C++
false
false
117
h
BOOK.h
class book { public: void initbook(); void showbook(); private: char title[60]; char author[60]; float price; };
2f637804e6a4ccad6f84e3a6aae45039b94a4a49
b215d2599878e3f2d162837fc6e59ae06a8f4bcd
/card.h
a1eeea78fb026412cc6a3e84867e0cf38e2c0221
[]
no_license
hagaddour/Card-Game
f9a0ed579fd981313cf7719fdfffea0f9151ab2a
2f7fb77e8552ed1c8b9b5e6e80967fdb7de6e719
refs/heads/master
2020-12-09T11:14:57.738727
2020-01-11T19:58:41
2020-01-11T19:58:41
233,287,917
0
0
null
null
null
null
UTF-8
C++
false
false
783
h
card.h
#ifndef __CARD_H__ #define __CARD_H__ #include <string> #include <vector> class Card { std::string name; int cost; std::string type; std::string descrip; public: //getters std::string getName(); int getCost(); std::string getType(); std::string getDescrip(); //setters void setName(std::string oName); void setCost(int oCost); void setType(std::string oType); void setDescrip(std::string oDescrip); Card(std::string name, int cost, std::string type, std::string descrip); //pure virtual ascii since each card type will have its own ascii. makes card astract virtual std::vector<std::string> getAscTemp() = 0; //print function to display the card void print(std::vector<std::string> cardAsc); }; #endif
50c6f33e30eef00833a36a6e9605b7191c0d5c14
ab786d963e4e959cbf185b3673133c468f40e5f8
/CPP1/upFun3.cpp
3742c01aa5443bad71b2a2724f2bfff05da37c09
[ "MIT" ]
permissive
mrnettek/CPP
beb2a37c0238fb398b74ed771bb24d05bec9d0b7
25127ae2dea8c4841787ae94669c56a716ee2bea
refs/heads/master
2021-06-28T19:17:38.106119
2020-12-31T18:52:29
2020-12-31T18:52:29
210,626,641
0
0
null
null
null
null
UTF-8
C++
false
false
239
cpp
upFun3.cpp
#include <iostream> using namespace std; void toUp(string &x) { for (int i = 0; i < x.length(); i++) if (x[i] > 96) x[i] = (char) (x[i] - 32); } int main() { string x = "Hello"; toUp(x); cout << x << endl; return 0; }
ae34ef582acf4f57210c3cc493800de45b6210ed
092d638d7e00daeac2b08a448c78dabb3030c5a9
/gcj/gcj/188266/hsisahens/168107/0/extracted/a.cpp
638c37be8af794e265991ee4b0023b5f3c625fc5
[]
no_license
Yash-YC/Source-Code-Plagiarism-Detection
23d2034696cda13462d1f7596718a908ddb3d34e
97cfdd458e851899b6ec6802a10343db68824b8b
refs/heads/main
2023-08-03T01:43:59.185877
2021-10-04T15:00:25
2021-10-04T15:00:25
399,349,460
2
0
null
null
null
null
UTF-8
C++
false
false
3,166
cpp
a.cpp
#include <cstdlib> #include <iostream> #include <fstream> #include <vector> #include <map> #include <algorithm> #include <conio.h> #include <climits> #include <queue> using namespace std; #define dv(vectName) for(int ii=0;ii<vectName.size();ii++) cout<<vectName[ii]<<' '; cout<<endl; #define d1da(arrayName,size) for(int ii=0;ii<size;ii++) cout<<arrayName[ii]<<' '; cout<<endl; #define d2da(arryName,row,col) for(int ii=0;ii<row;ii++){ for(int jj=0;jj<col;jj++) cout<<arryName[ii][jj]<<' '; cout<<endl; } cout<<endl; #define miii map<int,int>::iterator #define mici map<int,char>::iterator #define mcii map<char,int>::iterator #define vii vector<int>::iteartor #define pb(vectName,value) vectName.push_back(value); #define mi(mapName,keyType,valType,key,val) mapName.insert(pair<keyType,valType>(key,val)); fstream inp("a-small.in",ios::in); fstream out("a-small.out",ios::out); vector<int> convert(int num,int base){ vector<int> answer; while(num){ answer.push_back(num%base); num/=base; } return answer; } int sos(vector<int> num){ int answer=0; for(int i=0;i<num.size();i++){ answer+=(num[i]*num[i]); } return answer; } vector<int> parse(string s){ int num=0; vector<int> answer; for(int i=0;i<s.length();i++){ if(s[i]!=' '){ (num*=10)+=(s[i]-'0'); } else{ answer.push_back(num); num=0; } } answer.push_back(num); return answer; } bool ishappy(int n,const int base){ //cout<<"\nnumber is "<<n<<"and checking happiness in base"<<base; bool answer=true; int visited[100000]={0}; //memset(visited,0,1000000*sizeof(int)); int num=n; visited[num]=1; //cout<<"\nnumber is "<<n<<"and checking happiness in base"<<base; for(int j=1;j<=100;j++){ vector<int> c = convert(num,base); //cout<<"\n"<<num <<"in this base is "; //dv(c); num=sos(c); //cout<<"and sos is "<<num; //getch(); if(num==1) return true; if(visited[num]==1) return false; visited[num]=1; } } void solve(int testCaseNo){ string input; if(testCaseNo==1)getline(inp,input); getline(inp,input); vector<int> bases = parse(input); //dv(bases); bool done=false; int i=0; for(i=2;!done;i++){ done=true; //cout<<"\ni = "<<i<<"and bases.size = "<<bases.size(); for(int j=0;j<bases.size();j++){ if(! ishappy(i,bases[j]) ){ done=false; break; } } } out<<"Case #"<<testCaseNo<<": "<<i-1<<endl; } int main(void){ int T; inp>>T; for(int i=1;i<=T;i++) solve(i); getch(); return 0; }
7fdb4ca9e7d323849d1d75d1c6bd340ba8ccf21d
0ae50dc56dd8275fb14c522f08a0810ce094e4b1
/src/format.cpp
f7eee378ee21c7426e3ff8e12272400368014246
[ "MIT" ]
permissive
ayomide-adekunle/CplusND_System_Monitor
1de9a3808145136ff974b1bd31ffd060d1a1d08b
774e2fc32cab6199caa29952f4ba41627705cbc0
refs/heads/master
2023-06-18T21:43:59.280137
2021-07-17T15:29:36
2021-07-17T15:29:36
386,758,562
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
format.cpp
#include <string> #include "format.h" using std::string; // TODO: Complete this helper function // INPUT: Long int measuring seconds // OUTPUT: HH:MM:SS // REMOVE: [[maybe_unused]] once you define the function string Format::ElapsedTime(long sec) { int hrs, min; hrs = sec / 3600; sec = sec % 3600; min = sec / 60; sec = sec % 60; std::string hr_str, min_str, sec_str = ""; if (hrs < 10){ hr_str = "0"; } if (min < 10){ min_str = "0"; } if (sec < 10){ sec_str = "0"; } // if (sec < 10){ // return std::to_string(hrs) + ":" + std::to_string(min) + ":" +"0"+ // std::to_string(sec); // } return hr_str+std::to_string(hrs) + ":" + min_str+std::to_string(min) + ":" + sec_str+std::to_string(sec); }
fb336742acc333006bb7fcf2f379d796cce89420
270d448184cbe958e6e6bb17a98b35c381e22d99
/discrete/cs237SampleCode/pq_elegance.cpp
f12c570292e0784850249b413ed5ea99b8f4b863
[]
no_license
jcjolley/school
016ffde715bb07f9ddc09f0c7c0cf4d59a2bd0b3
bab28da74b1baba32844ec19278feb11ab65c375
refs/heads/master
2021-05-01T11:58:47.576569
2016-07-20T15:03:10
2016-07-20T15:03:10
59,164,873
1
0
null
null
null
null
UTF-8
C++
false
false
1,717
cpp
pq_elegance.cpp
// For your consideration: THE ULTIMATE IN ELEGANCE!! // // Using two helper functions (forAll and forSome --- // whose declarations you would need to add to the Predicate // class) simplifies each of the nested quantifier functions. // Each function (including the helpers) is four lines of code // (not counting curly braces all alone on a line) with no local // variables needed for flags or counts, and with a single, // uncluttered "for" loop. bool Predicate::forAll(int x, int setY[], int sizeY) { for (int i = 0; i < sizeY; i++) { if (isFalse(x, setY[i])) { return false; } } return true; } bool Predicate::forSome(int x, int setY[], int sizeY) { for (int i = 0; i < sizeY; i++) { if (isTrue(x, setY[i])) { return true; } } return false; } bool Predicate::forAllForAll(int setX[], int sizeX, int setY[], int sizeY) { for (int i = 0; i < sizeX; i++) { if (! forAll(setX[i], setY, sizeY)) { return false; } } return true; } bool Predicate::forAllForSome(int setX[], int sizeX, int setY[], int sizeY) { for (int i = 0; i < sizeX; i++) { if (! forSome(setX[i], setY, sizeY)) { return false; } } return true; } bool Predicate::forSomeForAll(int setX[], int sizeX, int setY[], int sizeY) { for (int i = 0; i < sizeX; i++) { if (forAll(setX[i], setY, sizeY)) { return true; } } return false; } bool Predicate::forSomeForSome(int setX[], int sizeX, int setY[], int sizeY) { for (int i = 0; i < sizeX; i++) { if (forSome(setX[i], setY, sizeY)) { return true; } } return false; }
68f16f8aac73301a690527f7d6098aa061a92b7f
78b0caa5032343ddb44c40da04cf77488b336c23
/expressions/unary/Not.cpp
4bdd80acde1cb8bc52af0d439c74b80c9f00ef4b
[]
no_license
noagol/interpreter
ede96f070f3a3d070ac56345120748938fb035d6
75661b9e5843d26360fa1beb2584ca18e059de73
refs/heads/master
2020-11-25T19:31:43.320158
2018-12-26T21:37:56
2018-12-26T21:37:56
228,813,136
0
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
Not.cpp
#include "Not.h" /** * Not operator * @param exp */ Not::Not(Expression *exp) : UnaryExpression(exp) {} /** * calculate logical not * @return ! expr */ double Not::calculate() { return !getExpression()->calculate(); }
db35b3ad2659a7473e988c509ae41c5202912769
cbce1565c63336b851b726cfb84bea99035c86e2
/devanshdalal/codeforces/328-B/328-B-4086911.cpp
8ac98d1c7e28b2e27df0ed1fcc53f8330b4eaeb2
[]
no_license
devanshdalal/CompetitiveProgrammingAlgos
3ad301c19e1b133e72e3b96a10a976a7955c4e25
ab19db4c4fed6f880537a9c45e5ccc50ceed9d97
refs/heads/master
2021-01-17T12:24:58.822428
2016-06-17T04:00:00
2016-06-17T04:00:00
51,207,702
2
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
328-B-4086911.cpp
#include<cstdio> #include<iostream> #include<algorithm> #include<vector> #include<cstdlib> #include<cmath> #include<cstring> #define sf scanf #define pf printf using namespace std; typedef long long ll; int n,k; ll modPow(int X, int Y) { ll Temp,Ans;ll M=(ll)pow(10,k); if(!Y) return 1; Temp = modPow(X,Y/2); Ans = (Temp*Temp)%M; if(!(Y&1)) return Ans; else return (X*Ans)%M; } char a[201]; int arr[10],b[10]; int main(){ int t,i,j=0,te;// j(1),1(2),14(3),144(4) scanf("%d",&t); memset(arr,0,sizeof(arr)); memset(b,0,sizeof(arr)); scanf("%s",&a); n=strlen(a); for(i=0;i<n;i++){ if(a[i]=='5')arr[2]++; else if(a[i]=='9')arr[6]++; else arr[a[i]-'0']++; } for(;t!=0;t=t/10){ j=t%10; if(j==5)b[2]++; else if(j==9)b[6]++; else b[j]++; } int ma= 200; for(i=0;i<10;i++){ if(b[i]){ ma=min(ma,arr[i]/b[i]); } } cout<<ma; return 0; }
5d11ef1416ef0a7777a1a5b7d975bb7b1c4ac4b2
8f60eb5560c657c699a13189a9f05ff38d06bad1
/C++ - Estrutura Case/exercicio12.cpp.cpp
e4ee45db76349728388685ffb3bc1cb011ca54f1
[]
no_license
l-jhon/C-Plus-Plus
deb2e551e24d495d41859d21cc8bfc6f47d9661a
8cb368e886c9beed4572109511d2f34ae1ba4283
refs/heads/master
2021-05-09T15:49:08.336602
2018-06-19T14:49:18
2018-06-19T14:49:18
119,097,547
0
0
null
null
null
null
UTF-8
C++
false
false
705
cpp
exercicio12.cpp.cpp
// Jhon Lucas Santos Silva /*Calculando o valor a ser pago por um produto , escolhendo diferentes formas de pagamento*/ #include <iostream> #include <cmath> using namespace std; int main () { float vp/*valor a ser pago*/,p/*preco de etiqueta*/,aux; int op/*opcao*/; cout<<"Digite o Valor de Etiqueta:\n"; cin>>p; cout<<"Digite a Opcaoo desejada:\n1-A vista em Dinheiro ou Cheque:\n2-A vista com Cartao de Credito:\n3-Em 2x :\n4-Em 3x;\n"; cin>>op; switch (op) { case 1: aux=p*0.10; vp=p-aux; break; case 2: aux=p*0.05; vp=p-aux; break; case 3: vp=p/2; break; case 4: aux=p*0.10; vp=p+aux/3; break; } cout<<"Valor a Ser Pago de : "<<vp<<endl; system("pause"); }
96cd1c9a3478ba3c60262ca651fb61b506502a06
b85eaaa722ab4199dd7d7ed9d74800aadb19d81e
/1053汉诺塔.cpp
866b75400c658bb46ee917933d42743bd2e49903
[]
no_license
WithLei/ACM
05bceed0bb535dba82d63d8c8ba2f99d16363255
c57307c2e83db032a47bba72f391f0b8624fa2cf
refs/heads/master
2021-01-20T01:04:20.005506
2017-10-05T11:12:44
2017-10-05T11:12:44
89,219,495
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
1053汉诺塔.cpp
#include<stdio.h> #include<math.h> int range; int ccl(int N){ range=0; for(int i=0;i<N;i++){ range=(range*2+1)%20142014; } return range; } int main(){ int M,N; scanf("%d",&M); for(int i=0;i<M;i++){ scanf("%d",&N); printf("%d\n",ccl(N)); } } //1-1 //2--3 //3--7 //4--15 //5--31 //6--63
6d454731f6d8c5f06f3d548eac99cab18b63eea5
ae1656c0199eb1cfd3affa51d855abf19e900acb
/Lab1-RPG/Archer.h
4130154c1fca0894fa475dfc589cedf339ab7034
[]
no_license
michaelbeneamatobruno/BYU_CS235
c73f93d1e0e5912b62a3b82811651190c590c033
e42cf46bc21961ad2b71daae50a133f37329294f
refs/heads/master
2021-01-19T23:02:35.041525
2017-04-20T21:55:53
2017-04-20T21:55:53
88,913,233
0
1
null
null
null
null
UTF-8
C++
false
false
336
h
Archer.h
#pragma once #include "Fighter.h" using namespace std; class Archer:public Fighter { public: Archer(string name, int maxHP, int strength, int originalSpeed, int magic):Fighter(name, maxHP, strength, originalSpeed, magic){}; ~Archer(){}; int getDamage(); void reset(); bool useAbility(); };
7ac308becbe737448fd621918f5a111e740acbae
c6f5524dd21cf8050aa06c9758ff54ec1811a469
/ET580/Week_6_Points_Dynamic_Arrays/1_pointer_variables/EX_1b_pointers.cpp
d67a631aea1dd9d3bc2682c864631c88b21b4e5a
[]
no_license
AChen24562/C-Plus-plus
482dbb33bd6b6b9b1cf49e3b5c0360285816d049
27364b7f02e5172aec89f2132bc963313b99d16b
refs/heads/master
2022-06-21T12:37:40.370312
2022-06-17T14:44:46
2022-06-17T14:44:46
236,824,208
0
1
null
null
null
null
UTF-8
C++
false
false
693
cpp
EX_1b_pointers.cpp
// S. Trowbridge 2020 #include <iostream> using namespace std; int main() { cout << endl; // int variable int i = 5; // initialize an integer pointer to the integer variable i // a pointer stores the memory address of another variable int *p = &i; // output the value of i and the memory address of i cout << i << " " << &i << "\n\n"; // output the values of i and p // the value of p is the memory address of i cout << i << " " << p << "\n\n"; // output the memory addresses of i and p // i and p are different variables, so they have different memory addresses cout << &i << " " << &p << "\n"; cout << endl; return 0; }
11341cd5b1cddecf318e312d44e756d0eab82ccf
1049415125c2c64f9ce714ecb4c15b3f3c130bee
/include/MemDC.h
4adb0410c7ec5e922be4238f04f2aa4401fe8d62
[ "MIT" ]
permissive
gearsns/TxtMiru2
3d53588d839b4304fb822630b5d1b78b6e66d21f
f829803721354e0639e791ba63962bd702aebfd1
refs/heads/master
2022-11-01T17:33:23.977198
2019-11-30T02:35:58
2019-11-30T02:35:58
208,549,945
5
0
null
null
null
null
UTF-8
C++
false
false
339
h
MemDC.h
#ifndef __MEMDC_H__ #define __MEMDC_H__ #include "Bitmap.h" #include <windows.h> class CGrMemDC { public: CGrMemDC(HDC hdc, RECT &rect); virtual ~CGrMemDC(); operator HDC(){ return m_hMemDC; } private: CGrBitmap m_bitmap; HBITMAP m_oldBitmap = NULL; HDC m_hMemDC = NULL; HDC m_hDC = NULL; RECT m_rect; }; #endif // __MEMDC_H__
54dc9513271ba73d050839906c51f6522f9d33f8
37867f639363ab2f188028dc158b483b6e6b81f3
/Src/Logic/Entity/Components/AnimationInventaryComponent.h
ab1241b8f18e9dcfad4b3c332990aac06ea462b9
[]
no_license
ailuoxz/BadPrincess-Game
704143bcafe1205a2ccdd7dbd68ed284c6fa1d76
47caae1a03fdfe8058260e44add25fd8e89f99c3
refs/heads/master
2021-12-14T15:13:50.974644
2017-05-04T16:31:22
2017-05-04T16:31:22
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
3,630
h
AnimationInventaryComponent.h
/** @file AnimationInventaryComponent.h Implement the component that manage all items that we have to attach to the skeleton for each animations @see Logic::IComponent @author Guidi Giacomo @date Mayo, 2015 */ #ifndef __Logic_AnimationInventaryComponent_H #define __Logic_AnimationInventaryComponent_H #include "Logic/Entity/Component.h" namespace Graphics{ class CMeshEntity; class CScene; } namespace Logic { class CAnimatedGraphics; class CAnimationInventaryComponent : public IComponent { DEC_FACTORY(CAnimationInventaryComponent); public: /** This constructor initialize the component with its component name and the rest attributes with their default value. */ CAnimationInventaryComponent(std::string componentName) : IComponent(componentName),_animationInventary(nullptr),_currentInventary(nullptr),_graphics(nullptr),_scene(nullptr),_luaAnimationTable("") {} /** Destructor (virtual); Liberamos los Manual Object recién creados */ virtual ~CAnimationInventaryComponent(); virtual void awake(); /** Inicialización del componente, utilizando la información extraída de la entidad leída del mapa (Maps::CEntity). Toma del mapa el tamaño de la cápsula que representa la entidad física y usa su radio para asignárselo al círculo de selección. Después crea un ManualObject para dibujar el círculo y lo asigna a un SceneNode de Ogre también recién creado. @param entity Entidad a la que pertenece el componente. @param map Mapa Lógico en el que se registrará el objeto. @param entityInfo Información de construcción del objeto leído del fichero de disco. @return Cierto si la inicialización ha sido satisfactoria. */ virtual bool spawn(CEntity* entity, CMap *map, const Map::CEntity *entityInfo); virtual bool activate(); virtual void deactivate(); /** Método virtual que elige que mensajes son aceptados. Son válidos EnemySelected. @param message Mensaje a chequear. @return true si el mensaje es aceptado. */ virtual bool acceptN(const std::shared_ptr<NMessage> &message); /** Método virtual que procesa un mensaje. @param message Mensaje a procesar. */ virtual void processN(const std::shared_ptr<NMessage> &message); protected: /* Function that reed from lua all mesh object that we have to attach to all animation */ void initAnimationInventary(); /* Function that free the memory */ void deleteAnimationInventary(); typedef std::pair<std::string,Graphics::CMeshEntity*> AttachableObject; typedef std::list<AttachableObject*> AttachableObjectList; /* Map of all animation that require to attach one or more object */ std::map<std::string,AttachableObjectList*> *_animationInventary; /* current list of attached objects */ const AttachableObjectList *_currentInventary; /* function that attach all the object to respective bone @param listToActivate list of objects that we have to attach to a bone */ void attachInventary(const AttachableObjectList *listToActivate); /* function that detach all the current objects from respective bone */ void detachCurrentInventary(); /* function that find for all animation that we are setting all objects that we have to attach to the skeleton @param name name of animation */ void changeAnimation(std::string name); /* Name of lua table that contains all animation with each objects to attach */ std::string _luaAnimationTable; Logic::CAnimatedGraphics* _graphics; Graphics::CScene*_scene; }; REG_FACTORY(CAnimationInventaryComponent); } #endif
dc456990e7c75ffc6d867dd2fff6349a9b5046e3
74d322a09045ff67f2c5f6897719543ed66bea67
/src/libgens/Vdp/Vdp_p.hpp
b706435b9fd1edb4a2c4349e9ec7a7d7267b645d
[]
no_license
LasDesu/gens-gs-ii
6eb73e7dfe6b2f21d74658eef4e1c1a33e3629e7
af19f8eadf64b6f2fe07347869d1fb9f9e9de2ef
refs/heads/master
2021-05-07T00:13:35.880499
2017-11-27T08:01:35
2017-11-27T08:01:35
110,127,163
1
1
null
2017-11-09T14:43:53
2017-11-09T14:43:53
null
UTF-8
C++
false
false
20,221
hpp
Vdp_p.hpp
/*************************************************************************** * libgens: Gens Emulation Library. * * Vdp_p.hpp: VDP emulation class. (Private class) * * * * Copyright (c) 1999-2002 by Stéphane Dallongeville. * * Copyright (c) 2003-2004 by Stéphane Akhoun. * * Copyright (c) 2008-2015 by David Korth. * * * * This program is free software; you can redistribute it and/or modify it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation; either version 2 of the License, or (at your * * option) any later version. * * * * This program is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef __LIBGENS_MD_VDP_P_HPP__ #define __LIBGENS_MD_VDP_P_HPP__ #include <stdint.h> #include "libcompat/byteorder.h" // Needed for FORCE_INLINE. #include "../macros/common.h" // VDP types. #include "VdpTypes.hpp" #include "VdpReg.hpp" #include "VdpPalette.hpp" #include "VdpStatus.hpp" #include "VdpStructs.hpp" #include "VdpRend_Err_p.hpp" namespace LibGens { class Vdp; class VdpPrivate { public: VdpPrivate(Vdp *q); ~VdpPrivate(); protected: friend class Vdp; Vdp *const q; private: // Q_DISABLE_COPY() equivalent. // TODO: Add LibGens-specific version of Q_DISABLE_COPY(). VdpPrivate(const VdpPrivate &); VdpPrivate &operator=(const VdpPrivate &); public: // Default VDP emulation options. static const VdpTypes::VdpEmuOptions_t def_vdpEmuOptions; // Screen mode. [H32, H40] // NOTE: Signed, not unsigned, due to // the way some things are calculated. unsigned int H_Cell; // [16, 20] int H_Pix; // [256, 320] int H_Pix_Begin; // [32, 0] (may not be necessary?) /** * Determine if the display mode is H40. (320px wide) * @return True if H40; false otherwise. */ inline bool isH40(void) const { // H40 mode is activated by setting VDP_Reg.m5.Set4, bit 0 (0x01, RS1). // Bit 7 (0x80, RS0) is also needed, but RS1 is what tells the VDP // to increase the pixel counters to 320px per line. // Source: http://wiki.megadrive.org/index.php?title=VDPRegs_Addendum (Jorge) return (VDP_Reg.m5.Set4 & 0x01); } /** * Check if 128 KB VRAM mode is enabled. * This checks both the register value and * whether or not 128 KB is enabled in the emulator. * @return True if 128 KB VRAM mode is enabled. */ inline bool is128KB(void) const { // TODO: Implement 128 KB mode. return false; } // Window row shift. (H40 == 6, H32 == 5) uint8_t H_Win_Shift; // Scroll mode masks. (Reg.11) uint8_t V_Scroll_MMask; uint8_t H_Scroll_Mask; // Scroll size masks. (Reg.16) uint8_t H_Scroll_CMul; uint8_t H_Scroll_CMask; uint8_t V_Scroll_CMask; // VDP window. (convenience values) unsigned int Win_X_Pos; unsigned int Win_Y_Pos; // Is Interlaced Mode 2 set? // Cached flag that can be overridden // by VDP options. bool im2_flag; /** * Is Interlaced Mode 1 set? * @return True if IM1 is set; false if not. */ inline bool isIM1(void) const { return ((VDP_Reg.m5.Set4 & 0x06) == 0x02); } /** * Is Interlaced Mode 2 set? * @return True if IM2 is set; false if not. */ inline bool isIM2(void) const { return ((VDP_Reg.m5.Set4 & 0x06) == 0x06); } /** * Is any Interlaced mode set? * @return True if either IM1 or IM2 is set; false if not. */ inline bool isIM1orIM2(void) const { return ((VDP_Reg.m5.Set4 & 0x02) == 0x02); } // VDP mode. VdpTypes::VDP_Mode_t VDP_Mode; void updateVdpMode(void); // VDP model. // TODO: Allow user to change this. VdpTypes::VDP_Model_t VDP_Model; // VRam, VSRam. // NOTE: VdpSpriteMaskingTest requires access to VRam. // ZOMG functions can be used as a workaround. VdpTypes::VRam_t VRam; VdpTypes::VSRam_t VSRam; int HInt_Counter; // Horizontal Interrupt Counter. int VDP_Int; // VDP interrupt state. VdpStatus Reg_Status; // VDP status register. uint16_t testReg; // Test register. // VDP registers. VdpTypes::VdpReg_t VDP_Reg; /** VDP tables. **/ // TODO: Precalculate H_Counter_Table? uint8_t H_Counter_Table[512][2]; /** * Set a VDP register. * @param reg_num Register number. (0-10 for M4; 0-23 for M5) * @param val New value for the register. */ void setReg(int reg_num, uint8_t val); /** * Reset the VDP registers. * @param bootRomFix If true, set the registers as the boot ROM would. */ void resetRegisters(bool bootRomFix); /** * Internal VDP data write function. * Used by writeDataMD() and DMA. * @param data Data word. */ void vdpDataWrite_int(uint16_t data); /** * VDP address pointers. * These are relative to VRam[] and are based on register values. */ uint32_t ScrA_Tbl_Addr; // Scroll A Name Table base address. uint32_t ScrB_Tbl_Addr; // Scroll B Name Table base address. uint32_t Win_Tbl_Addr; // Window Name Table bas address. uint32_t Spr_Tbl_Addr; // Sprite Table base address. uint32_t H_Scroll_Tbl_Addr; // Horizontal Scroll Table base address. // Pattern base addresses. uint32_t ScrA_Gen_Addr; // Scroll A Pattern Generator base address. uint32_t ScrB_Gen_Addr; // Scroll B Pattern Generator base address. uint32_t Spr_Gen_Addr; // Sprite Pattern Generator base address. /** * VDP address masks. * H40 mode typically has one bit masked compared to H32 * for certain registers. This mask also handles the extra * address bit for 128 KB mode. */ uint32_t VRam_Mask; // Based on 128 KB. uint32_t ScrA_Tbl_Mask; // Based on 128 KB. uint32_t ScrB_Tbl_Mask; // Based on 128 KB. uint32_t Win_Tbl_Mask; // Based on 128 KB and H32/H40. uint32_t Spr_Tbl_Mask; // Based on 128 KB and H32/H40. uint32_t H_Scroll_Tbl_Mask; // Based on 128 KB. /** VDP address functions: Get Pointers. **/ // FIXME: "& VRam_Mask" is probably not needed, // since the table addresses are already masked. // Name Tables inline uint16_t *ScrA_Tbl_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((ScrA_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t *ScrB_Tbl_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((ScrB_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t *Win_Tbl_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((Win_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline VdpStructs::SprEntry_m5 *Spr_Tbl_Addr_PtrM5(uint32_t link) { return (VdpStructs::SprEntry_m5*)&VRam.u16[((Spr_Tbl_Addr + (link*8)) & VRam_Mask) >> 1]; } inline uint16_t *H_Scroll_Tbl_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((H_Scroll_Tbl_Addr + offset) & VRam_Mask) >> 1]; } // Pattern Generators inline uint16_t *ScrA_Gen_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((ScrA_Gen_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t *ScrB_Gen_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((ScrB_Gen_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t *Win_Gen_Addr_Ptr16(uint32_t offset) // Same as Scroll A. { return ScrA_Gen_Addr_Ptr16(offset); } inline uint16_t *Spr_Gen_Addr_Ptr16(uint32_t offset) { return &VRam.u16[((Spr_Gen_Addr + offset) & VRam_Mask) >> 1]; } /** VDP address functions: Get Values. **/ // Name Tables inline uint16_t ScrA_Tbl_Addr_u16(uint32_t offset) const { return VRam.u16[((ScrA_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t ScrB_Tbl_Addr_u16(uint32_t offset) const { return VRam.u16[((ScrB_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t Win_Tbl_Addr_u16(uint32_t offset) const { return VRam.u16[((Win_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t Spr_Tbl_Addr_u16(uint32_t offset) const { return VRam.u16[((Spr_Tbl_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t H_Scroll_Tbl_Addr_u16(uint32_t offset) const { return VRam.u16[((H_Scroll_Tbl_Addr + offset) & VRam_Mask) >> 1]; } // Pattern Generators inline uint16_t ScrA_Gen_Addr_u16(uint32_t offset) const { return VRam.u16[((ScrA_Gen_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t ScrB_Gen_Addr_u16(uint32_t offset) const { return VRam.u16[((ScrB_Gen_Addr + offset) & VRam_Mask) >> 1]; } inline uint16_t Win_Gen_Addr_u16(uint32_t offset) const // Same as Scroll A. { return ScrA_Gen_Addr_u16(offset); } inline uint32_t Spr_Gen_Addr_u32(uint32_t offset) const { return VRam.u32[((Spr_Gen_Addr + offset) & VRam_Mask) >> 2]; } /** * Update the VDP address cache. (Mode 5) * @param updateMask 1 == 64KB/128KB; 2 == H32/H40; 3 == both */ void updateVdpAddrCache_m5(unsigned int updateMask); /** * Set the scroll plane size. (Mode 5 only!) * @param val Register value. * Format: [ 0 0 VSZ1 VSZ0 0 0 HSZ1 HSZ0] */ void setScrollSize_m5(uint8_t val); // VDP control struct. struct { /** * ctrl_latch: Control word latch. * 0: Next control word is FIRST word. * 1: Next control word is SECOND word, which triggers an action. */ uint8_t ctrl_latch; // Control word latch. // DMA values. uint8_t DMA_Mode; // (DMA ADDRESS HIGH & 0xC0) [reg 23] //int DMAT_Length; // TODO: Move it here. uint16_t reserved; // VDP internal registers. // addr_hi_latch is stored with the bits in the // shifted A16-A14 positions for performance reasons. // Reference: http://gendev.spritesmind.net/forum/viewtopic.php?t=1277&p=17430#17430 uint32_t address; // Address counter. uint32_t addr_hi_latch; // Latch for A16-A14. uint8_t code; // Access code. (CD5-CD0) // TODO: Address LSB latch for MD Mode 4? /** * Data latch. * - Mega Drive in SMS mode: Control word latch. * First byte of the control word is latched, * compared to SMS where it's applied immediately. * - Game Gear: CRAM latch. * Writes to even CRAM addresses go here. * Writes to odd CRAM addresses act as a word write, * with the written data as the even byte and * this latch as the odd byte. * NOTE: Game Gear CRAM is LE16. */ uint8_t data_latch; void reset(void) { ctrl_latch = 0; DMA_Mode = 0; reserved = 0; address = 0; addr_hi_latch = 0; code = 0; data_latch = 0; } } VDP_Ctrl; /** DMA helper functions. **/ /** * Get the DMA length from the VDP Mode 5 registers. * @return DMA length. */ inline uint16_t DMA_Length(void) const { return (VDP_Reg.m5.DMA_Length_H << 8) | (VDP_Reg.m5.DMA_Length_L); } /** * Set the DMA length in the VDP Mode 5 registers. * @param length DMA length. */ inline void set_DMA_Length(uint16_t length) { VDP_Reg.m5.DMA_Length_H = (length >> 8); VDP_Reg.m5.DMA_Length_L = (length & 0xFF); } /** * Get the DMA source address from the VDP Mode 5 registers. * @return DMA source address, divided by 2. */ inline uint32_t DMA_Src_Adr(void) const { return ((VDP_Reg.m5.DMA_Src_Adr_H & 0x7F) << 16) | (VDP_Reg.m5.DMA_Src_Adr_M << 8) | (VDP_Reg.m5.DMA_Src_Adr_L); } /** * Increment the DMA source address from the VDP Mode 5 registers. * Implements 128 KB wrapping, so only use this from DMA functions! * @param length Number of words to increment the source address by. */ inline void inc_DMA_Src_Adr(uint16_t length) { uint16_t src_adr = (VDP_Reg.m5.DMA_Src_Adr_M << 8) | (VDP_Reg.m5.DMA_Src_Adr_L); // Increment the address with 16-bit overflow. src_adr += length; // Save the new address. VDP_Reg.m5.DMA_Src_Adr_M = (src_adr >> 8); VDP_Reg.m5.DMA_Src_Adr_L = (src_adr & 0xFF); } /** * DMA transfer type: * - 0: External ROM/RAM to VRAM * - 1: External ROM/RAM to CRAM/VSRAM * - 2: DMA FILL * - 3: DMA COPY */ enum DMAT_Type_t { DMAT_MEM_TO_VRAM = 0, DMAT_MEM_TO_CRAM_VSRAM, DMAT_FILL, DMAT_COPY, }; DMAT_Type_t DMAT_Type; void DMA_Fill(uint16_t data); enum DMA_Dest_t { DMA_DEST_VRAM = 1, DMA_DEST_CRAM = 2, DMA_DEST_VSRAM = 3, }; enum DMA_Src_t { DMA_SRC_ROM = 0, DMA_SRC_M68K_RAM = 1, DMA_SRC_PRG_RAM = 2, DMA_SRC_WORD_RAM_2M = 3, DMA_SRC_WORD_RAM_1M_0 = 5, DMA_SRC_WORD_RAM_1M_1 = 6, DMA_SRC_WORD_RAM_CELL_1M_0 = 7, DMA_SRC_WORD_RAM_CELL_1M_1 = 8, }; // NOTE: This needs to be a macro, since it's used in case statements. #define DMA_TYPE(src, dest) (((int)src << 2) | ((int)dest)) template<DMA_Src_t src_component, DMA_Dest_t dest_component> inline void T_DMA_Loop(void); void processDmaCtrlWrite(void); /*!************************************************************** * VdpRend: Rendering functions and variables. * ****************************************************************/ public: /** * NOTE: rend_init(), rend_end(), and rend_reset() should ONLY be called from * Vdp::Vdp(), Vdp::~Vdp(), and Vdp::Reset()! */ void rend_init(void); void rend_end(void); void rend_reset(void); // Palette manager. VdpPalette palette; // VDP layer control. unsigned int VDP_Layers; // Line buffer for current line. union LineBuf_t { struct LineBuf_px_t { #if SYS_BYTEORDER == SYS_LIL_ENDIAN uint8_t pixel; uint8_t layer; #else /* SYS_BYTEORDER == SYS_BIG_ENDIAN */ uint8_t layer; uint8_t pixel; #endif }; LineBuf_px_t px[336]; uint8_t u8[336<<1]; uint16_t u16[336]; uint32_t u32[336>>1]; }; LineBuf_t LineBuf; template<bool hs, typename pixel> inline void T_Update_Palette(pixel *MD_palette, const pixel *palette); /*!************************************************************** * VdpRend_m5: Mode 5 rendering functions and variables. * ****************************************************************/ public: /** Line rendering functions. **/ void renderLine_m5(void); private: // Sprite Attribute Table cache. (Mode 5) // NOTE: Only 80 entries are present on the actual VDP, // but we have 128 here to prevent overflows. static const int SprAttrTbl_sz = (80 * sizeof(VdpStructs::SprEntry_m5)); union { // Direct byte/word access for SAT caching. uint8_t b[128*8]; uint16_t w[128*4]; // Sprite entries. VdpStructs::SprEntry_m5 spr[128]; } SprAttrTbl_m5; // Sprite line cache. // Caches the current line and the next line. // TODO: Reduce to a power-of-two size? struct SprLineCache_t { int16_t Pos_X; int16_t Pos_Y; uint8_t Size_X; uint8_t Size_Y; int16_t Pos_Y_Max; union { uint16_t Num_Tile; // M5: Includes palette, priority, and flip bits. struct { // M4/TMS sprite information. #if SYS_BYTEORDER == SYS_LIL_ENDIAN uint8_t sprite; // TMS/M4: Sprite pattern number. uint8_t color; // TMS: Color number. #else /* SYS_BYTEORDER == SYS_BIG_ENDIAN */ uint8_t color; // TMS: Color number. uint8_t sprite; // TMS/M4: Sprite pattern number. #endif }; }; }; /** * Sprite line cache array. * - TMS9918A: 4 sprites per line. * - SMS/GG: 8 sprites per line. * - MD: 16 or 20 sprites per line. * - Full 80 is used if sprite limits are disabled. * * NOTE: This was previously a union of variously-sized * arrays, e.g. tms[2][4], sms[2][8], etc, but it has * been changed to prevent issues on mode switch, since * the previous approach would result in wrong addresses: * &sms[1][0] == &md[0][8] */ SprLineCache_t sprLineCache[2][80]; // Sprite count cache. // Includes both the current line and the next line. uint8_t sprCountCache[2]; /*!***************************************** * VdpRend_m5: Mode 5 rendering functions. * *******************************************/ public: // Sprite dot overflow flag. // If set, the previous line had a sprite dot overflow. // This is needed to properly implement Sprite Masking in S1. bool sprDotOverflow; template<bool interlaced> FORCE_INLINE int T_GetLineNumber(void) const; template<bool plane, bool h_s, int pat_pixnum, uint32_t mask, int shift> FORCE_INLINE void T_PutPixel_P0(int disp_pixnum, uint32_t pattern, unsigned int palette); template<bool plane, bool h_s, int pat_pixnum, uint32_t mask, int shift> FORCE_INLINE void T_PutPixel_P1(int disp_pixnum, uint32_t pattern, unsigned int palette); template<bool priority, bool h_s, int pat_pixnum, uint32_t mask, int shift> FORCE_INLINE uint8_t T_PutPixel_Sprite(int disp_pixnum, uint32_t pattern, unsigned int palette); template<bool plane, bool h_s, bool flip> FORCE_INLINE void T_PutLine_P0(int disp_pixnum, uint32_t pattern, int palette); template<bool plane, bool h_s, bool flip> FORCE_INLINE void T_PutLine_P1(int disp_pixnum, uint32_t pattern, int palette); template<bool priority, bool h_s, bool flip> FORCE_INLINE void T_PutLine_Sprite(int disp_pixnum, uint32_t pattern, int palette); template<bool plane> FORCE_INLINE uint16_t T_Get_X_Offset(void); template<bool plane, bool interlaced> FORCE_INLINE unsigned int T_Get_Y_Offset(int cell_cur); template<bool interlaced, bool vscroll_mask> FORCE_INLINE unsigned int T_Get_Y_Cell_Offset(unsigned int y_offset); template<bool interlaced> FORCE_INLINE unsigned int T_Get_Y_Fine_Offset(unsigned int y_offset); template<bool plane> FORCE_INLINE uint16_t T_Get_Nametable_Word(unsigned int x, unsigned int y); template<bool interlaced> FORCE_INLINE uint32_t T_Get_Pattern_Data(uint16_t pattern, unsigned int y_fine_offset); template<bool plane, bool interlaced, bool vscroll, bool h_s> FORCE_INLINE void T_Render_Line_Scroll(int cell_start, int cell_length); template<bool interlaced, bool vscroll, bool h_s> FORCE_INLINE void T_Render_Line_ScrollA_Window(void); FORCE_INLINE void Update_Sprite_Line_Cache_m5(int line); // FIXME: FORCE_INLINE cannot be used here because this function // is used in Vdp.cpp. gcc-5.1 fails in release builds due to // the function definition not being available there. template<bool interlaced> unsigned int T_Update_Sprite_Line_Cache_m5(int line); template<bool interlaced, bool h_s> FORCE_INLINE void T_Render_Line_Sprite(void); template<bool interlaced, bool h_s> FORCE_INLINE void T_Render_Line_m5(void); template<typename pixel> FORCE_INLINE void T_Render_LineBuf(pixel *dest, pixel *md_palette); template<typename pixel> FORCE_INLINE void T_Apply_SMS_LCB(pixel *dest, pixel border_color); /*!***************************************** * VdpRend_m4: Mode 4 rendering functions. * *******************************************/ public: FORCE_INLINE unsigned int Update_Sprite_Line_Cache_m4(int line); /*!****************************************************** * VdpRend_tms: TMS9918A Modes 0-3 rendering functions. * ********************************************************/ public: FORCE_INLINE unsigned int Update_Sprite_Line_Cache_tms(int line); /*!*************************************************************** * VdpRend_Err: Error message rendering functions and variables. * *****************************************************************/ public: friend class VdpRend_Err_Private; VdpRend_Err_Private *const d_err; void renderLine_Err(void); void updateErr(void); }; } #endif /* __LIBGENS_MD_VDP_P_HPP__ */
33236a1c143d3face0dc005dfa5505f304ee9e77
c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64
/Engine/Plugins/2D/Paper2D/Source/PaperSpriteSheetImporter/Private/PaperJsonSpriteSheetImporter.cpp
ef40faacde22440ef4741cf527fa09ef9c2aa5a3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
windystrife/UnrealEngine_NVIDIAGameWorks
c3c7863083653caf1bc67d3ef104fb4b9f302e2a
b50e6338a7c5b26374d66306ebc7807541ff815e
refs/heads/4.18-GameWorks
2023-03-11T02:50:08.471040
2022-01-13T20:50:29
2022-01-13T20:50:29
124,100,479
262
179
MIT
2022-12-16T05:36:38
2018-03-06T15:44:09
C++
UTF-8
C++
false
false
22,344
cpp
PaperJsonSpriteSheetImporter.cpp
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "PaperJsonSpriteSheetImporter.h" #include "PaperSpriteSheetImporterLog.h" #include "Misc/Paths.h" #include "Misc/FeedbackContext.h" #include "Modules/ModuleManager.h" #include "Serialization/JsonTypes.h" #include "Serialization/JsonReader.h" #include "Serialization/JsonSerializer.h" #include "EditorReimportHandler.h" #include "Engine/Texture2D.h" #include "SpriteEditorOnlyTypes.h" #include "PaperSprite.h" #include "PaperJSONHelpers.h" #include "IAssetTools.h" #include "AssetToolsModule.h" #include "AssetRegistryModule.h" #include "PackageTools.h" #include "ObjectTools.h" #include "PaperSpriteSheet.h" #include "PaperImporterSettings.h" TSharedPtr<FJsonObject> ParseJSON(const FString& FileContents, const FString& NameForErrors, bool bSilent) { // Load the file up (JSON format) if (!FileContents.IsEmpty()) { const TSharedRef< TJsonReader<> >& Reader = TJsonReaderFactory<>::Create(FileContents); TSharedPtr<FJsonObject> SpriteDescriptorObject; if (FJsonSerializer::Deserialize(Reader, SpriteDescriptorObject) && SpriteDescriptorObject.IsValid()) { // File was loaded and deserialized OK! return SpriteDescriptorObject; } else { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Error: '%s'"), *NameForErrors, *Reader->GetErrorMessage()); } return nullptr; } } else { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Sprite descriptor file '%s' was empty. This sprite cannot be imported."), *NameForErrors); } return nullptr; } } TSharedPtr<FJsonObject> ParseJSON(FArchive* const Stream, const FString& NameForErrors, bool bSilent) { const TSharedRef< TJsonReader<> >& Reader = TJsonReaderFactory<>::Create(Stream); TSharedPtr<FJsonObject> SpriteDescriptorObject; if (FJsonSerializer::Deserialize(Reader, SpriteDescriptorObject) && SpriteDescriptorObject.IsValid()) { // File was loaded and deserialized OK! return SpriteDescriptorObject; } else { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Error: '%s'"), *NameForErrors, *Reader->GetErrorMessage()); } return nullptr; } } bool ParseMetaBlock(const FString& NameForErrors, TSharedPtr<FJsonObject>& SpriteDescriptorObject, FString& OutImage, bool bSilent) { bool bLoadedSuccessfully = true; TSharedPtr<FJsonObject> MetaBlock = FPaperJSONHelpers::ReadObject(SpriteDescriptorObject, TEXT("meta")); if (MetaBlock.IsValid()) { // Example contents: // "app": "Adobe Flash CS6", // "version": "12.0.0.481", (ignored) // "image": "MySprite.png", // "format": "RGBA8888", (ignored) // "size": {"w":2048,"h":2048}, (ignored) // "scale": "1" (ignored) const FString AppName = FPaperJSONHelpers::ReadString(MetaBlock, TEXT("app"), TEXT("")); OutImage = FPaperJSONHelpers::ReadString(MetaBlock, TEXT("image"), TEXT("")); const FString FlashPrefix(TEXT("Adobe Flash")); const FString TexturePackerPrefix(TEXT("http://www.codeandweb.com/texturepacker")); if (AppName.StartsWith(FlashPrefix) || AppName.StartsWith(TexturePackerPrefix)) { // Cool, we (mostly) know how to handle these sorts of files! if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Log, TEXT("Parsing sprite sheet exported from '%s'"), *AppName); } } else if (!AppName.IsEmpty()) { // It's got an app tag inside a meta block, so we'll take a crack at it if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Unexpected 'app' named '%s' while parsing sprite descriptor file '%s'. Parsing will continue but the format may not be fully supported"), *AppName, *NameForErrors); } } else { // Probably not a sprite sheet if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Expected 'app' key indicating the exporter (might not be a sprite sheet)"), *NameForErrors); } bLoadedSuccessfully = false; } if (OutImage.IsEmpty()) { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Expected valid 'image' tag"), *NameForErrors); } bLoadedSuccessfully = false; } } else { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Missing meta block"), *NameForErrors); } bLoadedSuccessfully = false; } return bLoadedSuccessfully; } static bool ParseFrame(TSharedPtr<FJsonObject>& FrameData, FSpriteFrame& OutFrame) { bool bReadFrameSuccessfully = true; // An example frame: // "frame": {"x":210,"y":10,"w":190,"h":223}, // "rotated": false, // "trimmed": true, // "spriteSourceSize": {"x":0,"y":11,"w":216,"h":240}, // "sourceSize": {"w":216,"h":240}, // "pivot": {"x":0.5,"y":0.5} [optional] OutFrame.bRotated = FPaperJSONHelpers::ReadBoolean(FrameData, TEXT("rotated"), false); OutFrame.bTrimmed = FPaperJSONHelpers::ReadBoolean(FrameData, TEXT("trimmed"), false); bReadFrameSuccessfully = bReadFrameSuccessfully && FPaperJSONHelpers::ReadRectangle(FrameData, "frame", /*out*/ OutFrame.SpritePosInSheet, /*out*/ OutFrame.SpriteSizeInSheet); if (OutFrame.bTrimmed) { bReadFrameSuccessfully = bReadFrameSuccessfully && FPaperJSONHelpers::ReadSize(FrameData, "sourceSize", /*out*/ OutFrame.ImageSourceSize); bReadFrameSuccessfully = bReadFrameSuccessfully && FPaperJSONHelpers::ReadRectangle(FrameData, "spriteSourceSize", /*out*/ OutFrame.SpriteSourcePos, /*out*/ OutFrame.SpriteSourceSize); } else { OutFrame.SpriteSourcePos = FIntPoint::ZeroValue; OutFrame.SpriteSourceSize = OutFrame.SpriteSizeInSheet; OutFrame.ImageSourceSize = OutFrame.SpriteSizeInSheet; } if (!FPaperJSONHelpers::ReadXY(FrameData, "pivot", /*out*/ OutFrame.Pivot)) { OutFrame.Pivot.X = 0.5f; OutFrame.Pivot.Y = 0.5f; } // A few more prerequisites to sort out before rotation can be enabled if (OutFrame.bRotated) { // Sprite Source Pos is from top left, our pivot when rotated is bottom left OutFrame.SpriteSourcePos.Y = OutFrame.ImageSourceSize.Y - OutFrame.SpriteSourcePos.Y - OutFrame.SpriteSizeInSheet.Y; // We rotate final sprite geometry 90 deg CCW to fixup // These need to be swapped to be valid in texture space. Swap(OutFrame.SpriteSizeInSheet.X, OutFrame.SpriteSizeInSheet.Y); Swap(OutFrame.ImageSourceSize.X, OutFrame.ImageSourceSize.Y); Swap(OutFrame.SpriteSourcePos.X, OutFrame.SpriteSourcePos.Y); Swap(OutFrame.SpriteSourceSize.X, OutFrame.SpriteSourceSize.Y); } return bReadFrameSuccessfully; } static bool ParseFramesFromSpriteHash(TSharedPtr<FJsonObject> ObjectBlock, TArray<FSpriteFrame>& OutSpriteFrames, TSet<FName>& FrameNames) { GWarn->BeginSlowTask(NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frame"), true, true); bool bLoadedSuccessfully = true; // Parse all of the frames int32 FrameCount = 0; for (auto FrameIt = ObjectBlock->Values.CreateIterator(); FrameIt; ++FrameIt) { GWarn->StatusUpdate(FrameCount, ObjectBlock->Values.Num(), NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frames")); bool bReadFrameSuccessfully = true; FSpriteFrame Frame; Frame.FrameName = *FrameIt.Key(); if (FrameNames.Contains(Frame.FrameName)) { bReadFrameSuccessfully = false; } else { FrameNames.Add(Frame.FrameName); } TSharedPtr<FJsonValue> FrameDataAsValue = FrameIt.Value(); TSharedPtr<FJsonObject> FrameData; if (FrameDataAsValue->Type == EJson::Object) { FrameData = FrameDataAsValue->AsObject(); bReadFrameSuccessfully = bReadFrameSuccessfully && ParseFrame(FrameData, /*out*/Frame); } else { bReadFrameSuccessfully = false; } if (bReadFrameSuccessfully) { OutSpriteFrames.Add(Frame); } else { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Frame %s is in an unexpected format"), *Frame.FrameName.ToString()); bLoadedSuccessfully = false; } FrameCount++; } GWarn->EndSlowTask(); return bLoadedSuccessfully; } static bool ParseFramesFromSpriteArray(const TArray<TSharedPtr<FJsonValue>>& ArrayBlock, TArray<FSpriteFrame>& OutSpriteFrames, TSet<FName>& FrameNames) { GWarn->BeginSlowTask(NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frame"), true, true); bool bLoadedSuccessfully = true; // Parse all of the frames for (int32 FrameCount = 0; FrameCount < ArrayBlock.Num(); ++FrameCount) { GWarn->StatusUpdate(FrameCount, ArrayBlock.Num(), NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ParsingSprites", "Parsing Sprite Frames")); bool bReadFrameSuccessfully = true; FSpriteFrame Frame; const TSharedPtr<FJsonValue>& FrameDataAsValue = ArrayBlock[FrameCount]; if (FrameDataAsValue->Type == EJson::Object) { TSharedPtr<FJsonObject> FrameData; FrameData = FrameDataAsValue->AsObject(); FString FrameFilename = FPaperJSONHelpers::ReadString(FrameData, TEXT("filename"), TEXT("")); if (!FrameFilename.IsEmpty()) { Frame.FrameName = FName(*FrameFilename); // case insensitive if (FrameNames.Contains(Frame.FrameName)) { bReadFrameSuccessfully = false; } else { FrameNames.Add(Frame.FrameName); } bReadFrameSuccessfully = bReadFrameSuccessfully && ParseFrame(FrameData, /*out*/Frame); } else { bReadFrameSuccessfully = false; } } else { bReadFrameSuccessfully = false; } if (bReadFrameSuccessfully) { OutSpriteFrames.Add(Frame); } else { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Frame %s is in an unexpected format"), *Frame.FrameName.ToString()); bLoadedSuccessfully = false; } } GWarn->EndSlowTask(); return bLoadedSuccessfully; } static ESpritePivotMode::Type GetBestPivotType(FVector2D JsonPivot) { // Not assuming layout of ESpritePivotMode if (JsonPivot.X == 0 && JsonPivot.Y == 0) { return ESpritePivotMode::Top_Left; } else if (JsonPivot.X == 0.5f && JsonPivot.Y == 0) { return ESpritePivotMode::Top_Center; } else if (JsonPivot.X == 1.0f && JsonPivot.Y == 0) { return ESpritePivotMode::Top_Right; } else if (JsonPivot.X == 0 && JsonPivot.Y == 0.5f) { return ESpritePivotMode::Center_Left; } else if (JsonPivot.X == 0.5f && JsonPivot.Y == 0.5f) { return ESpritePivotMode::Center_Center; } else if (JsonPivot.X == 1.0f && JsonPivot.Y == 0.5f) { return ESpritePivotMode::Center_Right; } else if (JsonPivot.X == 0 && JsonPivot.Y == 1.0f) { return ESpritePivotMode::Bottom_Left; } else if (JsonPivot.X == 0.5f && JsonPivot.Y == 1.0f) { return ESpritePivotMode::Bottom_Center; } else if (JsonPivot.X == 1.0f && JsonPivot.Y == 1.0f) { return ESpritePivotMode::Bottom_Right; } else { return ESpritePivotMode::Custom; } } //////////////////////////////////////////// // FPaperJsonSpriteSheetImporter FPaperJsonSpriteSheetImporter::FPaperJsonSpriteSheetImporter() : ImageTexture(nullptr) , NormalMapTexture(nullptr) , bIsReimporting(false) , ExistingBaseTexture(nullptr) , ExistingNormalMapTexture(nullptr) { } void FPaperJsonSpriteSheetImporter::SetReimportData(const TArray<FString>& ExistingSpriteNames, const TArray< TSoftObjectPtr<class UPaperSprite> >& ExistingSpriteSoftPtrs) { check(ExistingSpriteNames.Num() == ExistingSpriteSoftPtrs.Num()); if (ExistingSpriteNames.Num() == ExistingSpriteSoftPtrs.Num()) { for (int i = 0; i < ExistingSpriteSoftPtrs.Num(); ++i) { const TSoftObjectPtr<class UPaperSprite> SpriteSoftPtr = ExistingSpriteSoftPtrs[i]; UPaperSprite* LoadedSprite = SpriteSoftPtr.LoadSynchronous(); if (LoadedSprite != nullptr) { ExistingSprites.Add(ExistingSpriteNames[i], LoadedSprite); } } } bIsReimporting = true; } bool FPaperJsonSpriteSheetImporter::Import(TSharedPtr<FJsonObject> SpriteDescriptorObject, const FString& NameForErrors, bool bSilent) { bool bLoadedSuccessfully = ParseMetaBlock(NameForErrors, SpriteDescriptorObject, /*out*/ ImageName, bSilent); if (bLoadedSuccessfully) { TSharedPtr<FJsonObject> ObjectFrameBlock = FPaperJSONHelpers::ReadObject(SpriteDescriptorObject, TEXT("frames")); TSet<FName> FrameNames; if (ObjectFrameBlock.IsValid()) { bLoadedSuccessfully = ParseFramesFromSpriteHash(ObjectFrameBlock, /*out*/Frames, /*inout*/FrameNames); } else { // Try loading as an array TArray<TSharedPtr<FJsonValue>> ArrayBlock = FPaperJSONHelpers::ReadArray(SpriteDescriptorObject, TEXT("frames")); if (ArrayBlock.Num() > 0) { bLoadedSuccessfully = ParseFramesFromSpriteArray(ArrayBlock, /*out*/Frames, /*inout*/FrameNames); } else { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. Missing frames block"), *NameForErrors); } bLoadedSuccessfully = false; } } if (bLoadedSuccessfully && (Frames.Num() == 0)) { if (!bSilent) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to parse sprite descriptor file '%s'. No frames loaded"), *NameForErrors); } bLoadedSuccessfully = false; } } return bLoadedSuccessfully; } bool FPaperJsonSpriteSheetImporter::CanImportJSON(const FString& FileContents) { TSharedPtr<FJsonObject> SpriteDescriptorObject = ParseJSON(FileContents, FString(), /*bSilent=*/ true); if (SpriteDescriptorObject.IsValid()) { FString Unused; return ParseMetaBlock(FString(), SpriteDescriptorObject, /*out*/ Unused, /*bSilent=*/ true); } return false; } bool FPaperJsonSpriteSheetImporter::ImportFromString(const FString& FileContents, const FString& NameForErrors, bool bSilent) { TSharedPtr<FJsonObject> SpriteDescriptorObject = ParseJSON(FileContents, NameForErrors, bSilent); return SpriteDescriptorObject.IsValid() && Import(SpriteDescriptorObject, NameForErrors, bSilent); } bool FPaperJsonSpriteSheetImporter::ImportFromArchive(FArchive* Archive, const FString& NameForErrors, bool bSilent) { TSharedPtr<FJsonObject> SpriteDescriptorObject = ParseJSON(Archive, NameForErrors, bSilent); return SpriteDescriptorObject.IsValid() && Import(SpriteDescriptorObject, NameForErrors, bSilent); } bool FPaperJsonSpriteSheetImporter::ImportTextures(const FString& LongPackagePath, const FString& SourcePath) { bool bLoadedSuccessfully = true; const FString TargetSubPath = LongPackagePath / TEXT("Textures"); // Load the base texture const FString SourceSheetImageFilename = FPaths::Combine(*SourcePath, *ImageName); ImageTexture = ImportOrReimportTexture((bIsReimporting && (ExistingBaseTextureName == ImageName)) ? ExistingBaseTexture : nullptr, SourceSheetImageFilename, TargetSubPath); if (ImageTexture == nullptr) { UE_LOG(LogPaperSpriteSheetImporter, Warning, TEXT("Failed to import sprite sheet image '%s'."), *SourceSheetImageFilename); bLoadedSuccessfully = false; } // Try reimporting the normal map // Note: We are checking to see if the *base* texture has been renamed, since the .JSON doesn't actually store a name for the normal map. // If the base name has changed, we start from scratch for the normal map too, rather than reimport it even if the old computed one still exists if (bIsReimporting && (ExistingBaseTextureName == ImageName) && (ExistingNormalMapTexture != nullptr)) { if (FReimportManager::Instance()->Reimport(ExistingNormalMapTexture, /*bAskForNewFileIfMissing=*/ true)) { NormalMapTexture = ExistingNormalMapTexture; ComputedNormalMapName = ExistingNormalMapTextureName; } } // If we weren't reimporting (or failed the reimport), try scanning for a normal map (which may not exist, and that is not an error) if (NormalMapTexture == nullptr) { const UPaperImporterSettings* ImporterSettings = GetDefault<UPaperImporterSettings>(); // Create a list of names to test of the form [ImageName-[BaseMapSuffix]][NormalMapSuffix] or [ImageName][NormalMapSuffix], preferring the former const FString ImageNameNoExtension = FPaths::GetBaseFilename(ImageName); const FString ImageTypeExtension = FPaths::GetExtension(ImageName, /*bIncludeDot=*/ true); const FString NormalMapNameNoSuffix = ImporterSettings->RemoveSuffixFromBaseMapName(ImageNameNoExtension); TArray<FString> NamesToTest; ImporterSettings->GenerateNormalMapNamesToTest(NormalMapNameNoSuffix, /*inout*/ NamesToTest); ImporterSettings->GenerateNormalMapNamesToTest(ImageNameNoExtension, /*inout*/ NamesToTest); // Test each name for a file we can try to import for (const FString& NameToTestNoExtension : NamesToTest) { const FString NameToTest = NameToTestNoExtension + ImageTypeExtension; const FString NormalMapSourceImageFilename = FPaths::Combine(*SourcePath, *NameToTest); if (FPaths::FileExists(NormalMapSourceImageFilename)) { NormalMapTexture = ImportTexture(NormalMapSourceImageFilename, TargetSubPath); if (NormalMapTexture != nullptr) { ComputedNormalMapName = NameToTest; } break; } } } return bLoadedSuccessfully; } UTexture2D* FPaperJsonSpriteSheetImporter::ImportOrReimportTexture(UTexture2D* ExistingTexture, const FString& TextureSourcePath, const FString& DestinationAssetFolder) { UTexture2D* ResultTexture = nullptr; // Try reimporting if we have an existing texture if (ExistingTexture != nullptr) { if (FReimportManager::Instance()->Reimport(ExistingTexture, /*bAskForNewFileIfMissing=*/ true)) { ResultTexture = ExistingTexture; } } // If that fails, import the original textures if (ResultTexture == nullptr) { ResultTexture = ImportTexture(TextureSourcePath, DestinationAssetFolder); } return ResultTexture; } UTexture2D* FPaperJsonSpriteSheetImporter::ImportTexture(const FString& TextureSourcePath, const FString& DestinationAssetFolder) { FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools"); TArray<FString> TextureFileNames; TextureFileNames.Add(TextureSourcePath); TArray<UObject*> ImportedSheets = AssetToolsModule.Get().ImportAssets(TextureFileNames, DestinationAssetFolder); UTexture2D* ImportedTexture = (ImportedSheets.Num() > 0) ? Cast<UTexture2D>(ImportedSheets[0]) : nullptr; if (ImportedTexture != nullptr) { // Change the compression settings GetDefault<UPaperImporterSettings>()->ApplyTextureSettings(ImportedTexture); } return ImportedTexture; } UPaperSprite* FPaperJsonSpriteSheetImporter::FindExistingSprite(const FString& Name) { return ExistingSprites.FindRef(Name); } bool FPaperJsonSpriteSheetImporter::PerformImport(const FString& LongPackagePath, EObjectFlags Flags, UPaperSpriteSheet* SpriteSheet) { FAssetToolsModule& AssetToolsModule = FModuleManager::GetModuleChecked<FAssetToolsModule>("AssetTools"); GWarn->BeginSlowTask(NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ImportingSprites", "Importing Sprite Frame"), true, true); for (int32 FrameIndex = 0; FrameIndex < Frames.Num(); ++FrameIndex) { GWarn->StatusUpdate(FrameIndex, Frames.Num(), NSLOCTEXT("Paper2D", "PaperJsonImporterFactory_ImportingSprites", "Importing Sprite Frames")); // Check for user canceling the import if (GWarn->ReceivedUserCancel()) { break; } const FSpriteFrame& Frame = Frames[FrameIndex]; // Create a package for the frame const FString TargetSubPath = LongPackagePath + TEXT("/Frames"); UObject* OuterForFrame = nullptr; // @TODO: Use this if we don't want them to be individual assets - Flipbook; // Create a frame in the package UPaperSprite* TargetSprite = nullptr; if (bIsReimporting) { TargetSprite = FindExistingSprite(Frame.FrameName.ToString()); } if (TargetSprite == nullptr) { const FString SanitizedFrameName = ObjectTools::SanitizeObjectName(Frame.FrameName.ToString()); const FString TentativePackagePath = PackageTools::SanitizePackageName(TargetSubPath + TEXT("/") + SanitizedFrameName); FString DefaultSuffix; FString AssetName; FString PackageName; AssetToolsModule.Get().CreateUniqueAssetName(TentativePackagePath, DefaultSuffix, /*out*/ PackageName, /*out*/ AssetName); // Create a unique package name and asset name for the frame OuterForFrame = CreatePackage(nullptr, *PackageName); // Create the asset TargetSprite = NewObject<UPaperSprite>(OuterForFrame, *AssetName, Flags); FAssetRegistryModule::AssetCreated(TargetSprite); } TargetSprite->Modify(); FSpriteAssetInitParameters SpriteInitParams; SpriteInitParams.Texture = ImageTexture; if (NormalMapTexture != nullptr) { // Put the normal map into the additional textures array and ask for a lit material instead of unlit SpriteInitParams.AdditionalTextures.Add(NormalMapTexture); } SpriteInitParams.Offset = Frame.SpritePosInSheet; SpriteInitParams.Dimension = Frame.SpriteSizeInSheet; GetDefault<UPaperImporterSettings>()->ApplySettingsForSpriteInit(/*inout*/ SpriteInitParams, (NormalMapTexture != nullptr) ? ESpriteInitMaterialLightingMode::ForceLit : ESpriteInitMaterialLightingMode::Automatic); TargetSprite->InitializeSprite(SpriteInitParams, false); TargetSprite->SetRotated(Frame.bRotated, false); TargetSprite->SetTrim(Frame.bTrimmed, Frame.SpriteSourcePos, Frame.ImageSourceSize, false); // Set up pivot on object based on Texture Packer json ESpritePivotMode::Type PivotType = GetBestPivotType(Frame.Pivot); FVector2D TextureSpacePivotPoint = FVector2D::ZeroVector; if (PivotType == ESpritePivotMode::Custom) { TextureSpacePivotPoint.X = Frame.SpritePosInSheet.X - Frame.SpriteSourcePos.X + Frame.ImageSourceSize.X * Frame.Pivot.X; TextureSpacePivotPoint.Y = Frame.SpritePosInSheet.Y - Frame.SpriteSourcePos.Y + Frame.ImageSourceSize.Y * Frame.Pivot.Y; } TargetSprite->SetPivotMode(PivotType, TextureSpacePivotPoint, false); TargetSprite->RebuildData(); // Create the entry in the animation SpriteSheet->SpriteNames.Add(Frame.FrameName.ToString()); SpriteSheet->Sprites.Add(TargetSprite); TargetSprite->PostEditChange(); } SpriteSheet->TextureName = ImageName; SpriteSheet->Texture = ImageTexture; SpriteSheet->NormalMapTextureName = ComputedNormalMapName; SpriteSheet->NormalMapTexture = NormalMapTexture; GWarn->EndSlowTask(); return true; }
0b0fa5687aff91a2a333b70e2feda9dfe64f73c8
01be38e569d1519684d2da2253f097c9b4c0bd12
/connect_core.cpp
45ae9a462adc2cbc998d463cbeeff69abae11395
[]
no_license
dingyuanhong/epollTest
f830dd4163a94a9a189a3433d73de38dbed2ce4a
292549e1eca191421f341c47cdeb56ffad697f50
refs/heads/master
2021-10-22T08:02:03.264944
2019-03-09T04:05:56
2019-03-09T04:05:56
109,232,664
0
2
null
null
null
null
UTF-8
C++
false
false
7,790
cpp
connect_core.cpp
#include <errno.h> #include <stdlib.h> #include "util/staticUtil.h" #ifdef _WIN32 #include <WinSock2.h> //#include <Ws2def.h> #include <Ws2ipdef.h> #include <mstcpip.h> #define sa_family_t ADDRESS_FAMILY #define ssize_t int #define MSG_DONTWAIT 0 #define close closesocket #else #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #include <unistd.h> #include <fcntl.h> #include <netinet/tcp.h> #ifndef __MAC__ #include <error.h> #endif #endif #include "util/log.h" #include "connect_core.h" void nonBlocking(SOCKET socket) { #ifdef _WIN32 unsigned long flags = 1; ioctlsocket(socket, FIONBIO, &flags); #else int flags = fcntl(socket, F_GETFL, 0); fcntl(socket, F_SETFL, flags | O_NONBLOCK); #endif } void Reuse(SOCKET socket,int reuse) { #ifdef _WIN32 unsigned long flags = reuse; ioctlsocket(socket, SO_REUSEADDR, &flags); #else setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, (const void *)&reuse, sizeof(reuse)); #endif } void tcpNodelay(SOCKET fd) { int enable = 1; #ifdef _WIN32 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const char*)&enable, sizeof(enable)); #else setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&enable, sizeof(enable)); #endif } void cloexec(SOCKET socket) { #ifndef _WIN32 int flags = fcntl(socket, F_GETFD); flags |= FD_CLOEXEC; fcntl(socket, F_SETFD, flags); #endif } void keepalive(SOCKET socket,int keep) { #ifdef _WIN32 BOOL bSet= (keep != 0); int ret = setsockopt(socket,SOL_SOCKET,SO_KEEPALIVE,(const char*)&bSet,sizeof(BOOL)); if(ret == 0){ tcp_keepalive live,liveout; live.keepaliveinterval=5000; //每次检测的间隔 (单位毫秒) live.keepalivetime=10000; //第一次开始发送的时间(单位毫秒) live.onoff=TRUE; DWORD dw = 0; //此处显示了在ACE下获取套接字的方法,即句柄的(SOCKET)化就是句柄 if(WSAIoctl(socket,SIO_KEEPALIVE_VALS,&live,sizeof(live),&liveout,sizeof(liveout),&dw,NULL,NULL) == SOCKET_ERROR) { VLOGE("WSAIoctl error."); } } #else int keepAlive = keep;//设定KeepAlive int keepIdle = 3;//开始首次KeepAlive探测前的TCP空闭时间 int keepInterval = 3;//两次KeepAlive探测间的时间间隔 int keepCount = 3;//判定断开前的KeepAlive探测次数 if (setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, (void*)&keepAlive, sizeof(keepAlive)) == -1) { VLOGE("setsockopt SO_KEEPALIVE error.(%d)", errno); } #ifdef __MAC__ #else if (setsockopt(socket, SOL_TCP, TCP_KEEPIDLE, (void *)&keepIdle, sizeof(keepIdle)) == -1) { VLOGE("setsockopt TCP_KEEPIDLE error.(%d)", errno); } if (setsockopt(socket, SOL_TCP, TCP_KEEPINTVL, (void *)&keepInterval, sizeof(keepInterval)) == -1) { VLOGE("setsockopt TCP_KEEPINTVL error.(%d)", errno); } if (setsockopt(socket, SOL_TCP, TCP_KEEPCNT, (void *)&keepCount, sizeof(keepCount)) == -1) { VLOGE("setsockopt TCP_KEEPCNT error.(%d)", errno); } #endif #endif } struct sockaddr *createSocketAddr(const char * ip,int port) { struct sockaddr_in * addr = (struct sockaddr_in*)malloc(sizeof(struct sockaddr_in)); addr->sin_family = AF_INET; addr->sin_port = htons(port); addr->sin_addr.s_addr = inet_addr(ip); return (struct sockaddr *)addr; } int GetSockaddrSize(const struct sockaddr *sockaddr) { if(sockaddr == NULL) return 0; sa_family_t family = sockaddr->sa_family; if(family == AF_INET){ return sizeof(struct sockaddr_in); } else if (family == AF_INET6) { return sizeof(struct sockaddr_in6); } #ifndef WIN32 else if(family == AF_UNIX) { return sizeof(struct sockaddr_un); } #endif else { return 0; } } SOCKET createServerConnect(const sockaddr* socket_ptr,int max_listen) { SOCKET server = socket(AF_INET,SOCK_STREAM,0); if(server == -1) { VLOGE("socket create error(%d)\n",errno); return -1; } nonBlocking(server); Reuse(server,1); int ret = bind(server, socket_ptr,GetSockaddrSize(socket_ptr)); if(ret == -1) { VLOGE("socket bind error(%d)\n",errno); close(server); return -1; } ret = listen(server,max_listen); if(ret == -1) { VLOGE("socket listen error(%d)\n",errno); close(server); return -1; } return server; } struct interface_core * interfaceCreate() { struct interface_core *core = (struct interface_core*)malloc(sizeof(struct interface_core)); if(core == NULL) return NULL; core->type = 0; core->fd = -1; core->events = 0; core->lock = 0; return core; } void interfaceFree(struct interface_core ** connect_ptr) { if(connect_ptr == NULL) return; struct interface_core *core = *connect_ptr; if(core == NULL) return; if(core->fd != -1) { close(core->fd); } free(core); *connect_ptr = NULL; } struct connect_core * connectCreate() { struct connect_core *core = (struct connect_core*)malloc(sizeof(struct connect_core)); if(core == NULL) return NULL; connectInit(core); return core; } void connectInit(struct connect_core * connect) { if(connect == NULL) return; connect->type = 0; connect->fd = -1; connect->status = 0; connect->error = 0; connect->ret = 0; connect->lock = 0; } void connectClear(struct connect_core * connect) { if(connect == NULL) return; if(connect->fd != -1) { close(connect->fd); } connect->type = 0; connect->fd = -1; connect->status = 0; connect->error = 0; connect->ret = 0; connect->ptr = NULL; } void connectFree(struct connect_core ** connect_ptr) { if(connect_ptr == NULL) return; struct connect_core * core = *connect_ptr; if(core != NULL) { free(core); } *connect_ptr = NULL; } int connectRead(struct connect_core * connect) { if(connect == NULL) return CONNECT_STATUS_CLOSE; if(connect->status & CONNECT_STATUS_CLOSE) { return CONNECT_STATUS_CLOSE; } SOCKET fd = connect->fd; char buffer[65535]; ssize_t ret = recv(fd,buffer,65535,MSG_DONTWAIT); if(ret == 0) { VLOGI("recv close."); connect->status |= CONNECT_STATUS_CLOSE; return CONNECT_STATUS_CLOSE; }else if(ret == -1){ if(errno == EAGAIN) { return 0; } else if(ECONNRESET == errno) { VLOGE("recv ECONNRESET socket."); } else if(ENOTSOCK == errno) { VLOGE("recv ENOTSOCK socket."); } else{ VLOGE("recv(%d) error.(%d)",fd,errno); } connect->error = errno; connect->status |= CONNECT_STATUS_CLOSE; return CONNECT_STATUS_CLOSE; }else if(ret != 65535) { // VLOGI("recv data 接受完成.(%d)",ret); return CONNECT_STATUS_CONTINUE | CONNECT_STATUS_RECV; } return CONNECT_STATUS_CONTINUE | CONNECT_STATUS_RECV; } int connectWrite(struct connect_core * connect) { if(connect == NULL) return CONNECT_STATUS_CLOSE; if(connect->status & CONNECT_STATUS_CLOSE) { return CONNECT_STATUS_CLOSE; } SOCKET fd = connect->fd; char buffer[65535]; ssize_t ret = send(fd,buffer,65535,MSG_DONTWAIT); if(ret <= 0){ if(EAGAIN == errno) { return CONNECT_STATUS_SEND; } else if(ECONNRESET == errno) { VLOGE("send ECONNRESET socket."); } else { VLOGE("send error.(%d)",errno); } connect->error = errno; connect->status |= CONNECT_STATUS_CLOSE; return CONNECT_STATUS_CLOSE; }else if(ret != 65535) { VLOGD("send data 未完全发送.(%d)",ret); return CONNECT_STATUS_CONTINUE | CONNECT_STATUS_SEND; } return 0; } int connectGetErrno(struct connect_core * connect) { if(connect == NULL) return 0; return connect->error; } int connectShutdown(struct connect_core *connect,int howto) { VASSERT(connect != NULL); SOCKET fd = connect->fd; int ret = shutdown(fd,howto); if(ret != 0) { if(errno == ENOTCONN) { return 0; }else{ VLOGE("shutdown error:%d",errno); } return -1; }else{ VLOGD("(%d)shutdown success",fd); } return 0; } void connectDump(struct connect_core *connect) { VASSERT(connect != NULL); SOCKET fd = connect->fd; VLOGD("events:%x fd:%d ptr:%p status:%d",connect->events,fd,connect,connect->status); }
f63c1ca084392d9262e127de79b991fd27f67330
aeae8b58ba02405572dbc8e5633a6b6523902545
/NXPatcherLite++/PatchFile.cpp
0cd4a236c1a56287be035c9078eca71e465cc18b
[]
no_license
mechpaul/NXPatcherLite-
98988f6438740c53b0c6a903484340c9629bd28c
5581f991f0784a3d28462bfb2f9b5cd2025ca026
refs/heads/master
2020-06-26T04:31:00.813660
2016-11-23T07:14:37
2016-11-23T07:14:37
74,550,134
4
4
null
null
null
null
UTF-8
C++
false
false
401
cpp
PatchFile.cpp
#include <fstream> #include <iostream> #include <string> int CheckHeader(char* fileName) { std::ifstream f; std::string mystring("WzPatch\x1A\x02"); std::string checkString; int result = 0; checkString.resize(mystring.length()); f.open(fileName, std::ios::binary | std::ios::in); f.read(&checkString[0], mystring.length()); result = mystring == checkString; f.close(); return result; }
1aaa31575ac094569ae35933acebfee115a8cea2
8af5843b9d0c467cce1fc75a103dd33854d661eb
/Ares/Features/Bunnyhop.cpp
5bef4a4611243070385fcc0b403fe1ef7026c7b7
[]
no_license
Slyvred/Ares
b754942b1fcc92ff2bbd70da2b620ae7bb763c96
5327f5e17480532fa89efa408908214bc5e41508
refs/heads/master
2023-04-23T16:21:44.790809
2021-05-16T16:52:53
2021-05-16T16:52:53
367,937,835
0
0
null
null
null
null
UTF-8
C++
false
false
339
cpp
Bunnyhop.cpp
#include "../Hacks.h" #include "../Memory.h" #define FL_ONGROUND (1 << 0) void Hacks::Bunnyhop(bool enable) { if (enable) { BYTE flags = *(BYTE*)(localPlayer + netvars::m_fFlags); if (GetAsyncKeyState(VK_SPACE) & 0x8000 && flags & FL_ONGROUND) if (localPlayer->IsMoving()) *(int*)(client + signatures::dwForceJump) = 6; } }
d50c6d88a80bd57690e4d263bfd21cbc7872ab82
36de6ca7b2d2320fba58cbe6952761ddd7ee5a0e
/Files.h
7317d2222df16129d3a9f8ac2cce0535b6597ccc
[]
no_license
stupelc/Flight_Simulator-part2-
d118502cf1f0d83da624eba17df6c8e76a42cb0c
f7994aae59aaa7b3884e09e3b4f33b2cb65fc55b
refs/heads/master
2020-05-09T14:55:13.435572
2019-04-13T18:39:47
2019-04-13T18:39:47
181,214,056
1
0
null
null
null
null
UTF-8
C++
false
false
428
h
Files.h
// // Created by almogg on 1/7/19. // #ifndef PROJECT2_FILES_H #define PROJECT2_FILES_H #include <string> using namespace std; //for all things with files - all methods need to do things with the file class File { //have file name string fileName; public: File(string name); //read information from file to map void readFromFile(); //write to the file the information }; #endif //PROJECT2_FILES_H
7d33029ee21616fd8f9b06de04ff69b81539edf3
580031d5b09e0238e7d1f71fe4045cb46e7db123
/src/static_shader_program.h
fcd1ff21e6ee7a5bf318e1932073e17ed7021a1b
[]
no_license
Frommi/storwars
f3dc020d965f4e38f57fce78b0b20be90d9aa404
ab6c1306cccc30b4e055a9051d123ce7a5751d21
refs/heads/master
2021-01-25T10:08:00.584478
2017-05-17T21:32:31
2017-05-17T21:32:31
90,673,620
0
0
null
null
null
null
UTF-8
C++
false
false
1,875
h
static_shader_program.h
#pragma once #include <GL/glew.h> #include <GLFW/glfw3.h> #define GLM_SWIZZLE_XYZW #include <glm/glm.hpp> #include "shader_program.h" class StaticShaderProgram : public ShaderProgram { public: StaticShaderProgram() {} bool initShaderProgram(); inline void set_W_matrix_uniform(const glm::mat4& W) const { glUniformMatrix4fv(W_matrix_uniform_, 1, GL_TRUE, (const GLfloat*) &(W[0][0])); } inline void set_VP_matrix_uniform(const glm::mat4& VP) const { glUniformMatrix4fv(VP_matrix_uniform_, 1, GL_TRUE, (const GLfloat*) &(VP[0][0])); } inline void set_obs_pos_uniform(const glm::vec3& obs_pos) const { glUniform3fv(obs_pos_uniform_, 1, (const GLfloat*) &(obs_pos[0])); } inline void set_obs_impulse_uniform(const glm::vec3& obs_impulse) const { glUniform3fv(obs_impulse_uniform_, 1, (const GLfloat*) &(obs_impulse[0])); } inline void set_inverse_g_uniform(float inverse_g) const { glUniform1f(inverse_g_uniform_, inverse_g); } inline void set_obs_ifr_time_uniform(float obs_ifr_time) const { glUniform1f(obs_ifr_time_uniform_, obs_ifr_time); } inline void set_map_size_uniform(float map_size) const { glUniform1f(map_size_uniform_, map_size); } inline void set_diffuse_texture_uniform(int index) const { glUniform1i(diffuse_texture_uniform_, index); } inline void set_obj_velocity_uniform(const glm::vec3& obj_velocity) { glUniform3fv(obj_velocity_uniform_, 1, (const GLfloat*) &(obj_velocity[0])); } private: GLuint W_matrix_uniform_; GLuint VP_matrix_uniform_; GLuint obs_pos_uniform_; GLuint obs_impulse_uniform_; GLuint inverse_g_uniform_; GLuint obs_ifr_time_uniform_; GLuint map_size_uniform_; GLuint diffuse_texture_uniform_; GLuint obj_velocity_uniform_; };
3513704e959af035b03fb61e7bda06d0dff794f1
1b6b5f630696eb5ca848399a7cf8910ebc5d3fc2
/skinnyleetcode/canPermutePalindrome.cpp
d591f1a235e8e10315caa5f750db9a72d78353e4
[]
no_license
hmofrad/CodingPractice
bde55f7616d44f20aaaf544cf3c88b37f05651a0
7f642e4b9a2e3db0fe54ba66e8d3bf98b8407dce
refs/heads/master
2022-12-10T03:49:06.226039
2020-09-02T02:48:29
2020-09-02T02:48:29
63,923,207
0
0
null
null
null
null
UTF-8
C++
false
false
4,040
cpp
canPermutePalindrome.cpp
/* * https://leetcode.com/problems/palindrome-permutation/ * (c) Mohammad Hasanzadeh Mofrad, 2020 * (e) m.hasanzadeh.mofrad@gmail.com */ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> #include <string> class Solution { public: bool isPalindrome(std::string s) { bool tf = true; int size = s.size(); for(int i = 0; i < size/2; i++) { if(s[i] != s[size-1-i]) { tf = false; break; } } return(tf); } std::string insert_at(std::string t, int index, char c) { std::string first = t.substr(0, index); std::string last = t.substr(index, t.size()-index); printf("%s %d %c: <%s> <%s>\n", t.c_str(), index, c, first.c_str(), last.c_str()); return(first + c + last); } std::vector<std::string> permutations(std::string s) { //printf("%s\n", s.c_str()); std::vector<std::string> perms; if(s.empty()) { perms.push_back(""); return perms; } char first = s[0]; s.erase(s.begin()); std::vector<std::string> words = permutations(s); for(std::string word: words) { // printf(">%s\n", word.c_str()); int size = word.length(); for(int i = 0; i <= size; i++) { // printf("%d %c\n", i, first); std::string t = insert_at(word, i, first); perms.push_back(t); } } return(perms); } bool canPermutePalindrome(string s) { bool tf = false; std::vector<std::string> ps = permutations(s); for(std::string p: ps) { if(isPalindrome(p)) {tf = true; break;} } return(tf); } bool canPermutePalindrome3(string s) { int size = s.length(); //std::vector<std::string> p = permutations(s); std::vector<int> map(128); for(char c: s) { map[c]++; } bool tf = true; if(size%2) { int count = 0; for(int i = 0; i < 128; i++) { if(map[i]%2) { count++; } } if(count > 1) tf = false; } else { for(int i = 0; i < 128; i++) { if(map[i]%2) { tf = false; break; } } } return(tf); } bool permutation(std::string s, std::string t, std::vector<int> indices) { int size = s.length(); if(indices.empty()) return(isPalindrome(t)); std::vector<int> indices1 = indices; int index1 = indices1.front(); indices1.erase(indices1.begin()); std::vector<int> indices2 = indices; int index2 = 0; if(indices.size() > 1) { index2 = indices2[1]; indices2.erase(indices2.begin()+1); } else { index2 = index1; indices2 = indices1; } return(permutation(s, t+s[index1], indices1) or permutation(s, t+s[index2], indices2)); } bool canPermutePalindrome1(string s) { int size = s.length(); std::vector<int> indices(size); for(int i = 0; i < size; i++) indices[i] = i; return permutation(s, "", indices); } bool canPermutePalindrome2(string s) { bool tf = false; int size = s.length(); for(int i = 0; i < size; i++) { char temp = s[0]; for(int i = 1; i < size; i++) s[i-1] = s[i]; s[size-1] = temp; //printf("%s %d\n", s.c_str(), isPalindrome(s)); if(isPalindrome(s)) {tf = true; break;} } return(tf); } };
2c21235157809caaa8332dc0870ac20000e5ff91
0425662335cdf8a73330412ac2d7c67b4a766300
/AST/type.h
1b0f276f96045b7ffadd0b5c2567e30c6b0bbaf8
[]
no_license
sopilnyak/mipt-compilers
185a492ab0fc519ed15dc10ca5bef872e0c0c9c1
51fc376b30acdba4691b19bf65e8f8c49c327aad
refs/heads/master
2021-08-23T14:08:06.912964
2017-12-05T05:50:36
2017-12-05T05:50:36
104,077,978
1
1
null
null
null
null
UTF-8
C++
false
false
1,385
h
type.h
#ifndef MINIJAVA_TYPE_H #define MINIJAVA_TYPE_H #include "id.h" #include "visitable.h" #include <string> namespace AST { enum TypeValue { T_INT_ARRAY, T_BOOLEAN, T_INT, T_CLASS }; class IType : public Visitable { public: std::string type_name_; TypeValue type_value_; void accept(Visitor* visitor) override { visitor->visit(this); } }; class PrimitiveType: public IType { public: PrimitiveType(TypeValue type, Coordinates coordinates): IType(), type_value_(type), coordinates_(coordinates) { if (type_value_ == T_INT_ARRAY) { type_name_ = "int[]"; } if (type_value_ == T_BOOLEAN) { type_name_ = "boolean"; } if (type_value_ == T_INT) { type_name_ = "int"; } } TypeValue type_value_; Coordinates coordinates_; }; class ClassType: public IType { public: ClassType(Id* id_, Coordinates coordinates): id(id_), coordinates_(coordinates), IType() { type_name_ = id->getName(); type_value_ = T_CLASS; } std::unique_ptr<Id> id; Coordinates coordinates_; }; } #endif // MINIJAVA_TYPE_H
683e2abea0afea5586161045ad34b03938f5fff6
21f01f0ea7092df49d5f711ab627dc5628e09d49
/Direct3D_00/Direct3D_00/cScene_00.h
1bf1779fac4835e9e50131109adcd6db90b3b8f0
[]
no_license
JangMiKyung/DX2_pf_ver_2
9a44384b8334e7a15dc2daa4b757b728ea44a7f2
f3a919ae2c55a4fbfc1c5805d1070b575d164150
refs/heads/master
2020-06-14T03:32:52.045025
2016-12-04T02:18:30
2016-12-04T02:18:30
75,512,650
1
0
null
null
null
null
UHC
C++
false
false
1,506
h
cScene_00.h
#pragma once #include "cScene.h" //FVF?? //FVF는 flexible Vertex Format 의 약자로 //D3D 에서 정해져 있는 정점 포맷 중에서 사용자가 //임의로 선별해 새로운 정점 포맷을 정하는 방법이다. //1. 포지션 정점의 좌표 x,y,z (float) : D3DFVF_XYZ //2. RHW(float) : D3DFVF_XYZRHW //3. Blending Weight Data 결합 가중치 (float) : D3DFVF_XYZB1 ~ D3DFVF_XYZB5 //4. Vertex normal 정점의 법선 벡터(x,y,z)(float) : D3DFVF_NORMAL //5. Vertex Point Size 정점의 점 크기 (float) : D3DFVF_PSIZE //6. Diffuse Color (DWORD) : D3DFVF_DIFFUSE //7. Specular Color (DWORD) : D3DFVF_SPECULAR //8. Texture Coordinate Set 1 (float) : D3DFVF_TEX0 - D3DFVF_TEX8 class cScene_00 : public cScene { private: //정점하나에 대한 정보를 정의하는 구조체 typedef struct tagMYVERTEX { D3DXVECTOR3 pos; //정점의 위치 DWORD color; //정점의 컬러 //현제 정점의 정보를 나타내는 플래그 상수값 enum { FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE }; //D3DFVF_XYZ 정점의 위치정보 | D3DFVF_DIFFUSE 정점의 컬러정보 // FVF 의 선언 순서에 따라 구조체 자료형도 순서대로 해주어야 한다. }MYVERTEX, *LPMYVERTEX; MYVERTEX vertices[3]; //정점 구조체 3개 public: cScene_00(); ~cScene_00(); virtual void Init(); virtual void Release(); virtual void Update( float timeDelta ); virtual void Render(); };
ba08e1b6865e3534696d73bbd31fa52c775116e7
f6fd5f8bcda62e2b9c3c2b0267c8245100316a10
/codechef/MarchLong/PSHTRG.cpp
7b8769c50c315a942c3e52b8f6fd6ef0aa0937db
[]
no_license
hymsly/CompetitiveProgramming
9f292673dd6b1809deb354b9d9b0e85c820201f1
daf91095fab74e5a4f6441e34263ea3db1290d4a
refs/heads/master
2021-07-24T09:42:33.589976
2020-05-19T14:26:58
2020-05-19T14:26:58
172,566,245
0
0
null
null
null
null
UTF-8
C++
false
false
1,564
cpp
PSHTRG.cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; vector<ll> T[262144]; ll N=1; vector<ll> merge(vector<ll> a,vector<ll> b){ vector<ll> ans; int i=0,j=0; while(i<a.size() || j<b.size()){ if(i==a.size()) ans.push_back(b[j++]); else if(j==b.size()) ans.push_back(a[i++]); else{ if(a[i] < b[j]) ans.push_back(a[i++]); else ans.push_back(b[j++]); } } return ans; } void build(){ for(int i=N-1;i>0;i--) T[i] = merge(T[i<<1],T[i<<1|1]); } void update(int p,ll x){ p+=N; T[p].pop_back(); T[p].push_back(x); while(p>1){ T[p>>1] = merge(T[p],T[p^1]); p>>=1; } } ll binary(int nodo,ll val){ int lo=0,hi=T[nodo].size(); while((hi-lo)>1){ int mi = (hi+lo)/2; if(T[nodo][mi] > val) hi=mi; else lo=mi; } return T[nodo][lo]; } ll triangle(ll c,vector<int> &nodos){ } ll query(ll l,ll r){ if(r-l<3) return 0; vector<int> ans; l+=N; r+=N; while(l<r){ if(l&1){ ans.push_back(l++); } if(r&1){ ans.push_back(--r); } l>>=1; r>>=1; } ll lo=0,hi=(1e9+1); while((hi-lo)>1){ ll mi = (hi+lo)/2; ll x = 0; for(int i=0;i<ans.size();i++){ x = max(x,binary(ans[i],mi)); } if(triangle(x,ans)) lo=mi; else hi=mi; } } int main(){ ios::sync_with_stdio(0); cin.tie(NULL); ll n,q;cin>>n>>q; while(N<n) N<<=1; ll num; for(int i=N;i<N+n;i++){ cin>>num; T[i].push_back(num); } build(); int t; while(q--){ cin>>t; if(t==1){ int p;ll val; cin>>p>>val; p--; update(p,val); }else{ int l,r; cin>>l>>r; l--; cout<<query(l,r)<<'\n'; } } return 0; }
9576852bf78ca492089f3fe067847cccfe454b40
c208689db533cb1f30b9ffd767be24583c59f80f
/viewer/plugins/drawboundingbox/drawboundingbox.cpp
f3d82ffae4aa200c9447b1654e0804dd7ef27962
[]
no_license
elCrespo16/g
92b4553bd05d2989f9becaf37457071ad0b8d594
cfa0467cb58ba673852cf6f41a81f1168dd6183a
refs/heads/master
2023-02-04T18:08:31.507231
2020-12-14T17:46:53
2020-12-14T17:46:53
299,537,183
3
0
null
null
null
null
UTF-8
C++
false
false
2,063
cpp
drawboundingbox.cpp
#include "drawboundingbox.h" #include "glwidget.h" void Drawboundingbox::SetUpShaders() { vs = new QOpenGLShader(QOpenGLShader::Vertex,this); vs -> compileSourceFile("./ejercicio1.vert"); fs = new QOpenGLShader(QOpenGLShader::Fragment,this); fs -> compileSourceFile("./ejercicio1.frag"); program = new QOpenGLShaderProgram(this); program -> addShader(vs); program -> addShader(fs); program -> link(); } void Drawboundingbox::CreateBox(){ GLWidget& g = *glwidget(); g.makeCurrent(); g.glGenVertexArrays(1, &VAO); g.glBindVertexArray(VAO); float vertices[] = {0,0,0, 0,1,0, 0,1,1, 0,0,1, 1,0,1, 1,0,0, 1,1,0, 1,1,1 }; //float vertices[] = {1,0,1,1,1,1}; GLuint coordBufferID; g.glGenBuffers(1, &coordBufferID); g.glBindBuffer(GL_ARRAY_BUFFER, coordBufferID); g.glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); g.glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); g.glEnableVertexAttribArray(0); GLuint indices[] = { 0,1, 1,2, 2,3, 3,0, 3,4, 4,5, 5,0, 5,6, 6,1, 6,7, 7,2, 7,4 }; GLuint indicesID; g.glGenBuffers(1, &indicesID); g.glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesID); g.glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); g.glBindVertexArray(0); } void Drawboundingbox::onPluginLoad() { SetUpShaders(); CreateBox(); } void Drawboundingbox::preFrame(){ } void Drawboundingbox::postFrame() { program -> bind(); QMatrix4x4 MVP = camera()->projectionMatrix() * camera()->viewMatrix(); program->setUniformValue("modelViewProjectionMatrix", MVP); Scene* sc = scene(); const vector<Object> obj = (*sc).objects(); GLWidget &g = *glwidget(); g.makeCurrent(); for(int i = 0;i < obj.size();++i){ program->setUniformValue("boundingBoxMin",obj[i].boundingBox().min()); program->setUniformValue("boundingBoxMax",obj[i].boundingBox().max()); g.glBindVertexArray(VAO); //g.glDrawArrays(GL_LINES,0,2); g.glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0); g.glBindVertexArray(0); } program -> release(); }
c04806978789e0d498ec516cff12e5ee266cb579
fafdf1e62cf622035ee82666ba6ae7108127d140
/kynapse7/include/kypathdata/math/cardinaldir.h
c6bf6e169beecc17c650d214f2e6de3792beb32a
[]
no_license
saerich/RaiderZ-Evolved-SDK
7f18942ddc6c566d47c3a6222c03fad7543738a4
b576e6757b6a781a656be7ba31eb0cf5e8a23391
refs/heads/master
2023-02-12T03:21:26.442348
2020-08-30T15:39:54
2020-08-30T15:39:54
281,213,173
1
2
null
null
null
null
UTF-8
C++
false
false
1,766
h
cardinaldir.h
/* * Copyright 2010 Autodesk, Inc. All rights reserved. * Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, * or which otherwise accompanies this software in either electronic or hard copy form. */ /*! \file \ingroup kypathdata_math */ // ---------- Primary contact: JUBA - secondary contact: NOBODY #ifndef KyPathData_CardinalDir_H #define KyPathData_CardinalDir_H #include <kypathdata/generic/types.h> namespace Kaim { /*! Defines a type that refers to one of the cardinal points on the compass: #CardinalDir_EAST, #CardinalDir_NORTH, #CardinalDir_WEST, or #CardinalDir_SOUTH. \ingroup kypathdata_math */ typedef KyUInt32 CardinalDir; static const CardinalDir CardinalDir_EAST = 0; /*!< Identifies East, defined as the positive direction of the X axis. \ingroup kypathdata_math */ static const CardinalDir CardinalDir_NORTH = 1; /*!< Identifies North, defined as the positive direction of the Y axis. \ingroup kypathdata_math */ static const CardinalDir CardinalDir_WEST = 2; /*!< Identifies West, defined as the negative direction of the X axis. \ingroup kypathdata_math */ static const CardinalDir CardinalDir_SOUTH = 3; /*!< Identifies South, defined as the negative direction of the Y axis. \ingroup kypathdata_math */ static const CardinalDir CardinalDir_INVALID = KyUInt32MAXVAL; /*!< Identifies an invalid cardinal direction. \ingroup kypathdata_math */ /*! Returns the CardinalDir that lies in the opposite direction from the specified CardinalDir. For example, specifying #CardinalDir_EAST returns #CardinalDir_WEST. \ingroup kypathdata_math */ KY_FORCE_INLINE CardinalDir GetOppositeCardinalDir(const CardinalDir dir) { return (dir + 2) % 4; } } #endif
fd7961133acdef7ac3912fdb57f0a14ad10be579
9cbb3af861bbfb738f7adcdbb34339634d29e0f0
/filip.cpp
e4b19ef130593d57f77f150d4ae4582d66db1278
[]
no_license
ZebraFarm/OpenKattis
d3fcffd34e0fe87fb5e53ecd75236baea7a3fed5
b9748fde5547d4c5d596da61867a92eb3d4defc3
refs/heads/master
2021-06-21T11:32:18.454409
2021-06-16T06:10:35
2021-06-16T06:10:35
192,035,775
0
0
null
null
null
null
UTF-8
C++
false
false
389
cpp
filip.cpp
#include <iostream> #include <string> using namespace std; int main(){ string A,B; string Ans; cin >> A >> B; if(A[2] > B[2]){ Ans = A; } else if(A[2] == B[2]){ if(A[1] > B[1]){ Ans = A; } else if(A[1] == B[1]){ if(A[0] > B[0]){ Ans = A; } else{ Ans = B; } }else{ Ans = B; } }else{ Ans = B; } cout << Ans[2] << Ans[1] << Ans[0]; }
ac48f9417f74c6f7091eb3f15c63bbfedc5f1a9a
2ee540793f0a390d3f418986aa7e124083760535
/Online Judges/AtCoder/Alsing Programming Contest 2020/a.cpp
90cd963466678fb00485a811c7864fa6e4e952d0
[]
no_license
dickynovanto1103/CP
6323d27c3aed4ffa638939f26f257530993401b7
f1e5606904f22bb556b1d4dda4e574b409abc17c
refs/heads/master
2023-08-18T10:06:45.241453
2023-08-06T23:58:54
2023-08-06T23:58:54
97,298,343
0
0
null
null
null
null
UTF-8
C++
false
false
586
cpp
a.cpp
#include <bits/stdc++.h> using namespace std; #define inf 1000000000 #define unvisited -1 #define visited 1 #define eps 1e-9 #define mp make_pair #define pb push_back #define pi acos(-1.0) #define uint64 unsigned long long #define FastSlowInput ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define debug if(true) typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; int main(){ int l,r,d; scanf("%d %d %d",&l,&r,&d); int cnt = 0; for(int i=l;i<=r;i++){ if(i % d == 0){cnt++;} } printf("%d\n",cnt); return 0; };
6ebfa586aa255e00b83d3c76cb0a09e06f20aa81
5d24f800ad35397699dac7bf48f1aff9e256e552
/Kamek/src/firelaser.cpp
fa240d06018a567ebef323e84cfd979b7e95e53f
[ "MIT" ]
permissive
Danster64/NSMBWer
861c26e7440ce56af6227051224588d0141d94f7
05dae4ddf04745d389923670311de437d2df825c
refs/heads/master
2022-02-12T09:10:34.846693
2021-10-11T05:56:06
2021-10-11T05:56:06
236,567,638
5
5
MIT
2022-01-30T01:47:00
2020-01-27T18:54:51
C++
UTF-8
C++
false
false
2,336
cpp
firelaser.cpp
#include <common.h> #include <game.h> #include <g3dhax.h> class daFireLaser_c : public dEn_c { int onCreate(); int onDelete(); int onExecute(); int onDraw(); static daFireLaser_c *build(); int timer; float spitspeed; char direction; u64 eventFlag; USING_STATES(daFireLaser_c); DECLARE_STATE(pewpewpew); }; daFireLaser_c *daFireLaser_c::build() { void *buffer = AllocFromGameHeap1(sizeof(daFireLaser_c)); return new(buffer) daFireLaser_c; } CREATE_STATE(daFireLaser_c, pewpewpew); int daFireLaser_c::onCreate() { this->timer = 0; this->direction = this->settings & 0xF; this->spitspeed = 8.0; char eventNum = (this->settings >> 16) & 0xFF; this->eventFlag = (u64)1 << (eventNum - 1); doStateChange(&StateID_pewpewpew); this->onExecute(); return true; } int daFireLaser_c::onDelete() { return true; } int daFireLaser_c::onExecute() { acState.execute(); return true; } int daFireLaser_c::onDraw() { return true; } // Pew Pew State void daFireLaser_c::beginState_pewpewpew() { this->timer = 0; } void daFireLaser_c::executeState_pewpewpew() { if (dFlagMgr_c::instance->flags & this->eventFlag) { this->timer = this->timer + 1; if (this->timer < 20) { float xlaunch; float ylaunch; if (this->direction == 0) { xlaunch = this->spitspeed; ylaunch = 0.0; } else if (this->direction == 1) { // SE xlaunch = this->spitspeed; ylaunch = this->spitspeed; } else if (this->direction == 2) { // S xlaunch = 0.0; ylaunch = this->spitspeed; } else if (this->direction == 3) { // SW xlaunch = -this->spitspeed; ylaunch = this->spitspeed; } else if (this->direction == 4) { // W xlaunch = -this->spitspeed; ylaunch = 0.0; } else if (this->direction == 5) { // NW xlaunch = -this->spitspeed; ylaunch = -this->spitspeed; } else if (this->direction == 6) { // N xlaunch = 0.0; ylaunch = -this->spitspeed; } else if (this->direction == 7) { // NE xlaunch = this->spitspeed; ylaunch = -this->spitspeed; } dStageActor_c *spawner = CreateActor(106, 0, this->pos, 0, 0); spawner->speed.x = xlaunch; spawner->speed.y = ylaunch; } if (this->timer > 60) { this->timer = 0; } } else { this->timer = 0; } } void daFireLaser_c::endState_pewpewpew() { }
0b6f171ff469f18c5897070df8ec0d6168541248
ffb9b6b789f77bfdf95dcc3a479ed5dc13a28249
/IpcDelegate/AtomicInt.h
8b2603414a0ebe50d01b96dfdc48c07820d1467c
[ "MIT" ]
permissive
antonplakhotnyk/ipcdelegates
1ba23adeb875d2ebed2762d77dc3fe5b4e1f744e
0fc30118747596035fd13bf1dd55fa8c61fd1ad5
refs/heads/master
2021-01-11T06:22:56.169815
2016-10-05T16:12:26
2016-10-05T16:12:26
69,951,114
1
0
null
null
null
null
UTF-8
C++
false
false
824
h
AtomicInt.h
#pragma once //#include <atomic> // //class AtomicInt //{ //public: // // AtomicInt(int val):m_val(val){}; // // inline void ref() // { // m_val.fetch_add(1); // } // // inline bool deref() // { // return (m_val.fetch_sub(1)!=1); // } // // inline int load() // { // return m_val.load(); // } // // inline int exchange(int val) // { // return m_val.exchange(val); // } // //private: // // std::atomic<int> m_val; //}; class AtomicInt { public: AtomicInt(int val):m_val(val){}; inline void ref() { m_val++; } inline bool deref() { return --m_val; } inline int load() { return m_val; } inline int exchange(int val) { int tmp = m_val; m_val=val; return tmp; } private: int m_val; };
eb7ac451f0236581983fbda5508d61d07a9cdb7d
f83f4b7fd0ddc90e8b32b6471df56b5c8cc5757a
/MeshTools/FESmoothSurfaceMesh.cpp
946a165669fd5445cb168fd267e429e232737119
[ "MIT" ]
permissive
febiosoftware/FEBioStudio
e2e9c018247fd09dd779ea6cab811f45b5a031bd
d11e97ab3af4981196c7187d18915e3656c47e2d
refs/heads/develop
2023-09-01T03:39:19.777596
2023-09-01T01:15:28
2023-09-01T01:15:28
271,643,351
49
23
MIT
2023-06-15T18:47:52
2020-06-11T20:44:57
C++
UTF-8
C++
false
false
5,335
cpp
FESmoothSurfaceMesh.cpp
/*This file is part of the FEBio Studio source code and is licensed under the MIT license listed below. See Copyright-FEBio-Studio.txt for details. Copyright (c) 2021 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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 "stdafx.h" #include "FESmoothSurfaceMesh.h" #include <MeshLib/FEMesh.h> #include <MeshLib/FENodeNodeList.h> #include <MeshLib/FESurfaceMesh.h> #include <MeshLib/MeshTools.h> FESmoothSurfaceMesh::FESmoothSurfaceMesh() : FESurfaceModifier("Smooth") { AddIntParam(1, "iterations"); AddDoubleParam(0.0, "lambda"); AddBoolParam(false, "preserve shape"); AddBoolParam(false, "preserve edges"); } FSSurfaceMesh* FESmoothSurfaceMesh::Apply(FSSurfaceMesh* pm) { // create a copy of the mesh FSSurfaceMesh* newMesh = new FSSurfaceMesh(*pm); // apply smoothing bool bshape = GetBoolValue(2); bool bedge = GetBoolValue(3); ShapeSmoothMesh(*newMesh, *pm, bshape, bedge); // all done return newMesh; } void FESmoothSurfaceMesh::ShapeSmoothMesh(FSSurfaceMesh& mesh, const FSSurfaceMesh& backMesh, bool preserveShape, bool preserveEdges) { int niter = GetIntValue(0); double w = GetFloatValue(1); int N = mesh.Nodes(); std::vector<int> faceIDs(N, -1); // smooth node positions for (int n = 0; n<niter; ++n) { // clear tags // first = count of how often a node was visited // second = ID (edge or face) that the nodes should be back-projected to std::vector< std::pair<int, int> > tag(N, pair<int, int>(0, -1)); // storage for new node positions std::vector<vec3d> newPos(N, vec3d(0, 0, 0)); // tag all immovable nodes if (preserveShape || preserveEdges) { for (int i = 0; i<N; ++i) if (mesh.Node(i).m_gid >= 0) { newPos[i] = mesh.Node(i).r; tag[i].first = -1; tag[i].second = mesh.Node(i).m_gid; } } if (preserveEdges) { // lock all edges nodes for (int i = 0; i<mesh.Edges(); ++i) { FSEdge& edge = mesh.Edge(i); if (edge.m_gid >= 0) { int ne = edge.Nodes(); for (int j=0; j<ne; ++j) { tag[edge.n[j]].first = -1; } } } for (int i=0; i<N; ++i) { if (tag[i].first == -1) { newPos[i] = mesh.Node(i).r; } } } // process edge nodes if ((preserveEdges == false) && (preserveShape == true)) { for (int i = 0; i<mesh.Edges(); ++i) { FSEdge& edge = mesh.Edge(i); if (edge.m_gid >= 0) { int ne = edge.Nodes(); for (int j = 0; j<ne; ++j) { vec3d& rj = mesh.Node(edge.n[j]).r; for (int k = 0; k<ne; ++k) { int nk = edge.n[k]; if (tag[nk].first != -1) { newPos[nk] += rj; tag[nk].first++; assert((tag[nk].second == -1) || (tag[nk].second == edge.m_gid)); tag[nk].second = edge.m_gid; } } } } } for (int i = 0; i<N; ++i) { if (tag[i].first > 0) { newPos[i] /= (double)tag[i].first; // project the node back to the edge newPos[i] = projectToEdge(backMesh, newPos[i], tag[i].second); tag[i].first = -1; } } } // process face nodes for (int i = 0; i<mesh.Faces(); ++i) { FSFace& face = mesh.Face(i); int nf = face.Nodes(); for (int j = 0; j<nf; ++j) { vec3d& rj = mesh.Node(face.n[j]).r; for (int k = 0; k<nf; ++k) { int nk = face.n[k]; if (tag[nk].first != -1) { newPos[nk] += rj; tag[nk].first++; #ifdef _DEBUG if (preserveShape) { assert((tag[nk].second == -1) || (tag[nk].second == face.m_gid)); } #endif tag[nk].second = face.m_gid; } } } } for (int i = 0; i<N; ++i) { if (tag[i].first > 0) { newPos[i] /= (double)tag[i].first; if (preserveShape) { // project the node back to the surface assert(tag[i].second >= 0); if (faceIDs[i] != -1) { newPos[i] = projectToPatch(backMesh, newPos[i], tag[i].second, faceIDs[i], 2); } else newPos[i] = projectToSurface(backMesh, newPos[i], tag[i].second, &faceIDs[i]); } tag[i].first = -1; } } // assign new node positions for (int i = 0; i<N; ++i) { FSNode& ni = mesh.Node(i); if (tag[i].first == -1) { vec3d& vi = newPos[i]; ni.r = ni.r*w + vi*(1.0 - w); } } } }
b739fce109f963e7e7da039b3f9d9c6ba2ddad95
98b1e51f55fe389379b0db00365402359309186a
/homework_6/problem_2/10x10/0.115/T
59a9159b28deb618bf4a9b685697df08be9ad840
[]
no_license
taddyb/597-009
f14c0e75a03ae2fd741905c4c0bc92440d10adda
5f67e7d3910e3ec115fb3f3dc89a21dcc9a1b927
refs/heads/main
2023-01-23T08:14:47.028429
2020-12-03T13:24:27
2020-12-03T13:24:27
311,713,551
1
0
null
null
null
null
UTF-8
C++
false
false
2,074
T
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 8 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.115"; object T; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 1 0 0 0]; internalField nonuniform List<scalar> 100 ( 49.4258 10.3786 0.991337 -0.201313 -0.122094 -0.034678 -0.00729944 -0.00126626 -0.000189962 -2.27775e-05 92.2281 46.2955 16.4443 4.52139 1.0152 0.192894 0.0318119 0.00464083 0.00060842 6.58689e-05 106.099 65.3708 26.6403 8.09075 1.9626 0.397361 0.0692062 0.0105974 0.00145237 0.00016332 109.662 71.9438 30.5808 9.57384 2.37759 0.490732 0.0868832 0.0134982 0.0018744 0.000213131 110.419 73.6624 31.6926 10.0137 2.50538 0.520375 0.0926427 0.0144652 0.00201799 0.000230372 110.555 74.0282 31.9431 10.1166 2.53619 0.527701 0.094097 0.0147141 0.00205559 0.000234955 110.577 74.0943 31.9905 10.1367 2.54237 0.529203 0.0944011 0.014767 0.00206374 0.000235962 110.58 74.1047 31.998 10.1399 2.54333 0.529433 0.0944466 0.0147748 0.00206489 0.0002361 110.58 74.1064 32.0002 10.1413 2.54391 0.529613 0.0944912 0.014784 0.00206654 0.000236332 110.58 74.1056 31.9965 10.1383 2.5425 0.529147 0.0943713 0.0147586 0.00206193 0.000235665 ) ; boundaryField { left { type fixedValue; value uniform 100; } right { type zeroGradient; } up { type zeroGradient; } down { type fixedValue; value uniform 0; } frontAndBack { type empty; } } // ************************************************************************* //
af80169d5944dd02eac1c7f5a88afee64b036dd7
a8b08575d93904e2bf48b591f8c9ef43b014769f
/SimulacionBingo/jugador.h
0b732e4a721186d1d8f3efd5896d1a76dfd5d5fa
[]
no_license
Jarc97/SimulacionBingo
5466bde4598350f62a86ab2ffbb02951a72be9d3
b69876fc18f22cac49af4c0182e546484ff897a2
refs/heads/master
2021-07-13T15:48:43.851593
2017-10-18T02:12:50
2017-10-18T02:12:50
105,354,032
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
jugador.h
#pragma once #include <iostream> #include <sstream> #include "Matriz.h" #include "TableroBingo.h" using namespace std; class jugador{ private: int numeroJugador; int cantCartones; Matriz **cartones; public: bool existeGanador(); void setNumero(int n); Matriz** getCartones(); int getCantCartones(); void setTipoJ(int ); Matriz* obtenerCarton(int op); int getNumero(); void buscar(int num); string toString(); jugador(int n,int can); jugador(); ~jugador(); };
334572d4ffa895f3bcec6fb6775b8cd2c3a0a700
7f0688381353ba6e2cb7bd875b65cf82746ef947
/LeetCode/Minimum Window Substring/main.cpp
81e8ccaf624d578ae564adfc940430f108008490
[]
no_license
croaxx/ProjectEuler
cf7ad45d5e14dbf474049899ab73f183e1bebaf4
61afb52c909d3024b1e345490bbc1eec0ae7fe9b
refs/heads/master
2022-02-26T06:36:25.130321
2022-02-12T14:55:00
2022-02-12T14:55:00
70,401,901
0
0
null
null
null
null
UTF-8
C++
false
false
1,754
cpp
main.cpp
// Problem description: https://leetcode.com/problems/minimum-window-substring/submissions/ // Time complexity: O(S+T) - one pass over the string S with expand and shrink windowing // Space complexity: O(1) - dictionary of ASCII symbols + ints #include <unordered_map> using namespace std; const int INF = INT32_MAX; class Solution { private: using dict = unordered_map<char, int>; dict ds, dt; int mismatches, min_w, idx; void build_dict(const string& str) { for (const auto& ch : str) ++dt[ch]; } int expandWindow(int L, int R, const string& s, const string& t) { while (mismatches > 0 && R != s.size()) { char ch = s[++R]; ++ds[ch]; if (dt.find(ch) != end(dt) && dt[ch] >= ds[ch]) --mismatches; } return R; } int shrinkWindow(int L, int R, const string& s, const string& t) { if (mismatches != 0) return R; int len = R - L + 1; while (mismatches == 0 && L <= R) { if (mismatches == 0 && min_w > len) { min_w = len; idx = L; } char ch = s[L++]; --ds[ch]; if (dt.find(ch) != end(dt) && dt[ch] > ds[ch]) ++mismatches; --len; } return L; } public: string minWindow(const string& s, const string& t) { build_dict(t); ds.clear(); idx = 0; min_w = INF; mismatches = (int)t.size(); int L = 0, R = -1; while (L < s.size()) { R = expandWindow(L, R, s, t); L = shrinkWindow(L, R, s, t); } if (min_w != INF) return s.substr(idx, min_w); else return ""; } };
cb97cd2ac6f70acfced929380a43372eeb758286
33124afc125420a6acb08a90a912f3a1a1769632
/gflags_mutex.h
82717fae8a3c1a066abd06df1f6a37e713273282
[ "BSD-3-Clause" ]
permissive
qianlizhixing12/gflags-learn
5473c7ab4ca011345b1524e00443905a27c8dbea
b8cc781dc759aed76d7a74c376cfaebbcdc12716
refs/heads/main
2023-06-20T11:34:01.674721
2021-07-24T07:52:46
2021-07-24T07:52:46
389,035,151
0
0
null
null
null
null
UTF-8
C++
false
false
3,955
h
gflags_mutex.h
#ifndef GFLAGS_MUTEX_H_ #define GFLAGS_MUTEX_H_ #include <stdlib.h> #include <pthread.h> namespace gflags { typedef pthread_rwlock_t MutexType; #define SAFE_PTHREAD(fncall) \ do { /* run fncall if is_safe_ is true */ \ if (is_safe_ && fncall(&mutex_) != 0) \ abort(); \ } while (0) class Mutex { public: // This is used for the single-arg constructor enum LinkerInitialized { LINKER_INITIALIZED }; // Create a Mutex that is not held by anybody. This constructor is // typically used for Mutexes allocated on the heap or the stack. inline Mutex() : destroy_(true) { SetIsSafe(); if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); } // This constructor should be used for global, static Mutex objects. // It inhibits work being done by the destructor, which makes it // safer for code that tries to acqiure this mutex in their global // destructor. explicit inline Mutex(LinkerInitialized) : destroy_(false) { SetIsSafe(); if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); } // Destructor inline ~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); } // Block if needed until free then acquire exclusively inline void Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } // Release a lock acquired via Lock() inline void Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } // Block until free or shared then acquire a share inline void ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } // Release a read share of this Mutex inline void ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } // Acquire an exclusive lock inline void WriterLock() { Lock(); } // Release a lock from WriterLock() inline void WriterUnlock() { Unlock(); } private: pthread_rwlock_t mutex_; // We want to make sure that the compiler sets is_safe_ to true only // when we tell it to, and never makes assumptions is_safe_ is // always true. volatile is the most reliable way to do that. volatile bool is_safe_; // This indicates which constructor was called. bool destroy_; inline void SetIsSafe() { is_safe_ = true; } // Catch the error of writing Mutex when intending MutexLock. explicit Mutex(Mutex * /*ignored*/) {} // Disallow "evil" constructors Mutex(const Mutex &); void operator=(const Mutex &); }; #undef SAFE_PTHREAD // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class MutexLock { public: explicit MutexLock(Mutex *mu) : mu_(mu) { // mu_->Lock(); } ~MutexLock() { mu_->Unlock(); } private: Mutex *const mu_; // Disallow "evil" constructors MutexLock(const MutexLock &); void operator=(const MutexLock &); }; // ReaderMutexLock and WriterMutexLock do the same, for rwlocks class ReaderMutexLock { public: explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } ~ReaderMutexLock() { mu_->ReaderUnlock(); } private: Mutex *const mu_; // Disallow "evil" constructors ReaderMutexLock(const ReaderMutexLock &); void operator=(const ReaderMutexLock &); }; class WriterMutexLock { public: explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } ~WriterMutexLock() { mu_->WriterUnlock(); } private: Mutex *const mu_; // Disallow "evil" constructors WriterMutexLock(const WriterMutexLock &); void operator=(const WriterMutexLock &); }; #define COMPILE_ASSERT(msg) !##msg // Catch bug where variable name is omitted, e.g. MutexLock (&mu); #define MutexLock(x) COMPILE_ASSERT(mutex_lock_decl_missing_var_name) #define ReaderMutexLock(x) COMPILE_ASSERT(rmutex_lock_decl_missing_var_name) #define WriterMutexLock(x) COMPILE_ASSERT(wmutex_lock_decl_missing_var_name) } // namespace gflags #endif
7157c6f23f9f01d8305856a6dfa09020fe9747ba
5b27603a8de4f955948cb69ed46f38741d8d0d7b
/CRU/PropertiesFormClass.h
c34edca7e95f05029292a4ac4078c50a365827e6
[]
no_license
jasonhargrove/Custom-Resolution-Utility-ToastyX
e867a92f63a7ffbb2abd705155b133e683b6f845
77f7fa2dd6b04876fa08eb82125576d9e0073a38
refs/heads/master
2021-09-11T19:23:36.813207
2018-04-11T12:25:30
2018-04-11T12:25:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,016
h
PropertiesFormClass.h
//--------------------------------------------------------------------------- #ifndef PropertiesFormClassH #define PropertiesFormClassH //--------------------------------------------------------------------------- #include "CommonFormClass.h" #include "PropertiesClass.h" #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <Buttons.hpp> #include <ExtCtrls.hpp> //--------------------------------------------------------------------------- class TPropertiesForm : public TCommonForm { __published: // IDE-managed Components TLabel *ProductIDLabel; TLabel *SerialIDLabel; TLabel *VRateLabel; TShape *VRateDash; TLabel *HzLabel; TLabel *HRateLabel; TShape *HRateDash; TLabel *kHzLabel; TLabel *MaxPClockLabel; TLabel *MHzLabel; TGroupBox *ProductIDGroupBox; TEdit *ProductID; TButton *ProductIDResetButton; TEdit *SerialID; TGroupBox *NameGroupBox; TEdit *Name; TCheckBox *IncludeName; TGroupBox *SerialNumberGroupBox; TEdit *SerialNumber; TCheckBox *IncludeSerialNumber; TGroupBox *RangeLimitsGroupBox; TEdit *MinVRate; TEdit *MaxVRate; TEdit *MinHRate; TEdit *MaxHRate; TEdit *MaxPClock; TCheckBox *IncludeRangeLimits; TButton *FormOKButton; TButton *FormCancelButton; void __fastcall FormCreate(TObject *Sender); void __fastcall FormShow(TObject *Sender); void __fastcall ProductIDChange(TObject *Sender); void __fastcall ProductIDExit(TObject *Sender); void __fastcall ProductIDResetButtonClick(TObject *Sender); void __fastcall SerialIDChange(TObject *Sender); void __fastcall SerialIDExit(TObject *Sender); void __fastcall NameChange(TObject *Sender); void __fastcall NameExit(TObject *Sender); void __fastcall IncludeNameClick(TObject *Sender); void __fastcall SerialNumberChange(TObject *Sender); void __fastcall SerialNumberExit(TObject *Sender); void __fastcall IncludeSerialNumberClick(TObject *Sender); void __fastcall MinVRateChange(TObject *Sender); void __fastcall MinVRateExit(TObject *Sender); void __fastcall MaxVRateChange(TObject *Sender); void __fastcall MaxVRateExit(TObject *Sender); void __fastcall MinHRateChange(TObject *Sender); void __fastcall MinHRateExit(TObject *Sender); void __fastcall MaxHRateChange(TObject *Sender); void __fastcall MaxHRateExit(TObject *Sender); void __fastcall MaxPClockChange(TObject *Sender); void __fastcall MaxPClockExit(TObject *Sender); void __fastcall IncludeRangeLimitsClick(TObject *Sender); private: // User declarations PropertiesClass *Properties; bool Refreshing; public: // User declarations __fastcall TPropertiesForm(TComponent *Owner); bool Connect(PropertiesClass &); TColor GetTextColor(bool); bool Refresh(void *); bool ScaleControls(); }; //--------------------------------------------------------------------------- extern PACKAGE TPropertiesForm *PropertiesForm; //--------------------------------------------------------------------------- #endif
1198c048f3a3f85fd83d791249d1c72c2e1b301f
bb02e04bb1a2f9044ab4e2551d5e1e3b41a9b5e4
/BinaryTreeZigzagLevelOrderTraversal.cpp
6753a6c350f44b5a84a878d4930480551dcea591
[]
no_license
be-for-rain/LeetCode
6df1445d7d4ff529b01bc23703400b49375e9983
d54b1098e9bbce1320976ced9f0f9419e42cb25d
refs/heads/master
2021-01-22T07:18:03.803620
2015-05-07T12:15:24
2015-05-07T12:15:24
35,216,679
0
0
null
null
null
null
UTF-8
C++
false
false
1,752
cpp
BinaryTreeZigzagLevelOrderTraversal.cpp
/* * Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). * * For example: * Given binary tree {3,9,20,#,#,15,7}, * 3 * / \ * 9 20 * / \ * 15 7 * return its zigzag level order traversal as: * [ * [3], * [20,9], * [15,7] * ] * * * Sol : * [step 0] do level order travesal * [step 1] reverse the vector of odd level -- reverse(ans[i].begin(), ans[i].end()); */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int> > zigzagLevelOrder(TreeNode *root) { vector<vector<int> > ans; if (root == NULL) { return ans; } queue<pair<TreeNode*, int> > q; q.push(make_pair(root, 0)); while (!q.empty()) { pair<TreeNode*, int> cur = q.front(); q.pop(); TreeNode *node = cur.first; int depth = cur.second; ans.resize(depth+1); ans[depth].push_back(node->val); if (node->left) { q.push(make_pair(node->left, depth+1)); } if (node->right) { q.push(make_pair(node->right, depth+1)); } } //do zig-zag for (vector<vector<int> >::size_type i = 1; i < ans.size(); i += 2) { reverse(ans[i].begin(), ans[i].end()); } } };
1a3e165e3ac407818460d7e1411c000acc993c49
309c47cad0e7c2f795efe301277869b2bf192cfa
/_resampling/_functions_TH/cast_binary.cpp
9d0887ca83cfcee533a95328a39fb640e9ba136d
[ "CC-BY-4.0" ]
permissive
sPlotOpen/sPlotOpen_Code
9d19e0242f2082c1ce47b10fdc4743840861c769
cf5d2c396c4beeb94064f877a42fa6bef985f983
refs/heads/master
2023-02-01T09:59:08.621448
2020-12-18T13:01:20
2020-12-18T13:01:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
cast_binary.cpp
// To enable the functionality provided by Armadillo's various macros, // simply include them before you include the RcppArmadillo headers. #define ARMA_NO_DEBUG // [[Rcpp::depends(RcppArmadillo, BH, bigmemory)]] // [[Rcpp::plugins(cpp11)]] #include <RcppArmadillo.h> #include <RcppArmadilloExtensions/sample.h> #include <bigmemory/BigMatrix.h> #include <Rcpp.h> using namespace Rcpp; using namespace arma; IntegerVector whichEq( IntegerVector x, int value) { int nx = x.size(); std::vector<int> y; y.reserve(nx); for(int i = 0; i < nx; i++) { if (x[i] == value) y.push_back(i); } return wrap(y); } // [[Rcpp::export]] IntegerMatrix castC(IntegerVector iD, IntegerVector sp , NumericVector cov){ int sizeI = iD.size(); IntegerVector plotNb = unique(iD); IntegerVector spNb = unique(sp); int rowSize = plotNb.size(); int colSize= spNb.size() ; IntegerMatrix comMat(rowSize, colSize +1); comMat(_ , 0) = plotNb; for (int i = 0; i < sizeI ; i++) { IntegerVector rowI = whichEq (plotNb,iD[i]); int plotID = rowI[0]; int species = sp[i]; comMat(plotID, species) = 1; } return comMat; }
bf622f0dfa708ee3492d32d88591dccc8f639f44
10a9042a56f6777891d01b5ffb9d0b3d91b4955b
/prjHotel/prjHotel/FacturableFraisFixe.h
1d81ec9817cf6e865964f4cf3c13118b8324d15f
[]
no_license
oualidGit/HotelRepo
303e8f28c93b05157e037311ebabeb90e778a965
0f144f115dd1cbf17dfd8f49aebb05a90912c3ed
refs/heads/master
2022-06-18T03:24:48.690594
2020-05-04T05:25:35
2020-05-04T05:25:35
261,085,211
0
0
null
null
null
null
UTF-8
C++
false
false
346
h
FacturableFraisFixe.h
#pragma once #ifndef __FACTURABLEFRAISFIXE_H__ #define __FACTURABLEFRAISFIXE_H__ #include "elementfacturable.h" class FacturableFraisFixe : public ElementFacturable{ private: const int TAXEADD = 7; public : FacturableFraisFixe(string le_nom, float le_prix_base, int ordre_imp); float calculerMontant(); string afficherElmt(); }; #endif
f9354c36864e251c53af228a276e70f86fcad31b
458033b6b2a4d35e8fac5128a112d75f1346eacd
/Sort_frequency.cpp
fad210a0ec564fcce375d6c010f421b10cfae1ab
[]
no_license
RajeswarSharma/ProgrammingPuzzles
469af9cb12b59f0871f86026044399d04902fab9
8c094432dce8df26d5b2e64581def53613f7bfa5
refs/heads/master
2020-12-11T17:28:29.273701
2020-08-15T15:16:13
2020-08-15T15:16:13
233,912,142
0
0
null
null
null
null
UTF-8
C++
false
false
1,768
cpp
Sort_frequency.cpp
#include <iostream> using namespace std; /* insertion sort */ void Sort(int *arr,int n) { int temp; int j; for(int i =1 ;i<n;i++) { j=i-1; temp=arr[i]; while(temp<arr[j]&&j>=0) { arr[j+1]=arr[j]; j--; } arr[j+1]=temp; } } /* void Sort2D() sort the 2D array on the bases of frequency low to high using insertion sort. */ void Sort2D(int arr[][2],int n) { int temp,element; int j; for(int i =1;i<n;i++) { j=i-1; temp=arr[i][1]; element=arr[i][0]; while(j>=0&&temp<arr[j][1]) { arr[j+1][0]=arr[j][0]; arr[j+1][1]=arr[j][1]; j--; } arr[j+1][1]=temp; arr[j+1][0]=element; } } int main() { int A[100],Size; int tempArray[100][2],tcounter=0; int temp; int counter=0; cout<<"Size :"; cin>>Size; for(int i =0;i<Size;i++) { cin>>A[i]; } Sort(A,Size); int j; //creating 2D array to hold element and its frequency. for(int i=0;i<Size;i++) { temp=A[i]; counter=1; j=i+1; while(j<Size) { if(temp==A[j]) { counter++; j++; i++; } else break; } tempArray[tcounter][0]=temp; // saving the element tempArray[tcounter++][1]=counter; //saving the frequency } temp=0;//reseting temp value to reuse it as counter for A[] Sort2D(tempArray,tcounter); //sorting for(int i =0;i<tcounter;i++) // Converting 2D Array back to simple array. { for(int j=0;j<tempArray[i][1];j++) { A[temp++]=tempArray[i][0]; } } for(int i=0;i<Size;i++) //printing { cout<<A[i]<<" "; } return 0; }
ba7170c52429abe0ad9003a1678723db216eadd5
b85d28cdd5ae653e6122b913e06fe0ed41d73b6e
/51nod/1596.cpp
09360c988823cf6a50896a6ef347f10d81e4e4b4
[]
no_license
a62625536/ACM
46b19d8b43dad857629d5420cafb1d82bd8c3fa8
9dcc28a9d96e27f6aa50aeeb4e03324b240ec142
refs/heads/master
2021-09-18T15:55:02.765547
2018-07-17T01:46:30
2018-07-17T01:46:30
120,172,970
0
0
null
null
null
null
UTF-8
C++
false
false
420
cpp
1596.cpp
#include<bits/stdc++.h> using namespace std; int n,a[1100005] = {0}; int main() { ios::sync_with_stdio(0); cin >> n; for(int i = 1;i <= n;i++) { int x; cin >> x; a[x]++; } for(int i = 0;i <= 1100000;i++) { a[i+1] += a[i]/2; a[i] %= 2; } int ans = 0; for(int i = 0;i <= 1100000;i++) ans += a[i]; cout << ans << endl; return 0; }
abd4b486099c987962d836166f7660846d5966fd
5fb6b0c27e231379f4aa05f7a9268a28dd9cc496
/warmup/compare-the-triplets/compare-the-triplets.cpp
e70844c37893aec70c3500b5f42fc75798aa0e53
[ "MIT" ]
permissive
Rholais/hacker-rank
c3a47595454f62eeb4bce5c5baead05bb4d4f758
3d2a352a92998454d13da7db8695c0768f818443
refs/heads/master
2021-01-01T17:51:34.976909
2017-07-28T07:07:11
2017-07-28T07:07:11
98,179,612
0
0
null
null
null
null
UTF-8
C++
false
false
574
cpp
compare-the-triplets.cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ vector<unsigned> a = { 0, 0, 0 }; vector<unsigned> b = { 0, 0, 0 }; cin >> a[0] >> a[1] >> a[2] >> b[0] >> b[1] >> b[2]; unsigned c = 0; unsigned d = 0; for (size_t i = 0; i != 3; ++i) { if (a[i] > b[i]) { ++c; } else if (a[i] < b[i]) { ++d; } } cout << c << '\t' << d; return 0; }
13c9fb434ce4f2107f770d6e5b5391118a73b597
4578812c8d55c8fdd305fb2ac7ee35fed53cd033
/exprtmpl/sarray1.cpp
245975324e5925be2c62c2a93e214c2b85d532da
[ "LicenseRef-scancode-other-permissive" ]
permissive
ywen-cmd/C-Templates
bda53a9c967631742672439bf04be837ee266d80
3960bd4e852ed0d3b4db5203f4d125b4a725dd48
refs/heads/master
2023-06-12T00:15:03.342044
2021-07-04T06:41:19
2021-07-04T06:41:19
382,781,477
0
0
null
null
null
null
UTF-8
C++
false
false
864
cpp
sarray1.cpp
/* The following code example is taken from the book * "C++ Templates - The Complete Guide" * by David Vandevoorde and Nicolai M. Josuttis, Addison-Wesley, 2002 * * (C) Copyright David Vandevoorde and Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include "sarray1.hpp" #include "sarrayops1.hpp" #include <iostream> int main() { // SArray<double> x(1000), y(1000); SArray<double> x(4), y(4); x[0]=1; x[1]=2; x[2]=3; x[3]=4; y[0]=0; y[1]=1; y[2]=2; y[3]=3; //... x = 1.2*x + x*y; for(int i=0;i<4;i++){ std::cout<<x[i]<<std::endl; } }
cbc4c2c8fb1b282b047b3678155dbb01c74276db
286a1f86f6045ea910746234037048c90bbd7b6e
/Parcial2/RadioButtons/ai.cpp
3bc4ce44723b2860f11b021a4cbfa192cdd27e0a
[ "Apache-2.0" ]
permissive
feguedi/dispositivos_moviles
ad12123fa1cced42024692f2f97b72aded4a84aa
8fcd1dc73b5987226c0ee386bb8a6db6a839eeb3
refs/heads/master
2021-08-20T09:10:46.993221
2017-11-28T18:28:58
2017-11-28T18:28:58
100,408,034
2
0
null
null
null
null
UTF-8
C++
false
false
2,195
cpp
ai.cpp
#include "ai.h" #include <QDebug> Ai::Ai(QObject *parent) : QObject(parent), msg("No has seleccionado algún animal") { } QString Ai::setMessage(QString ac, QString vol, QString ter) { if() { } return msg; } QString Ai::setPers(QString ac, QString vol, QString ter) { if(ac == 0 && vol == 0 && ter == 0) { return ""; } else { switch (ac) { case 0: switch (vol) { case 0: switch (ter) { case 1: return "Fuerte"; break; case 2: return "Fluido"; break; case 3: return "Noble"; break; default: break; } break; case 1: switch (ter) { case 1: return "Fuerte"; break; case 2: return "Fuerte y fluido"; break; case 3: return "Fuerte y noble"; break; default: break; } break; case 2: switch (ter) { case 1: return "Fuerte y fluido"; break; case 2: return "Fluido"; break; case 3: return "Fluido y noble"; break; default: break; } break; case 3: break; default: break; } break; case 1: switch (vol) { case 1: break; case 2: break; case 3: break; default: break; } break; case 2: break; case 3: break; default: break; } } }
ff13d585f35f744db769406e70801af23f71320f
d69c48c9bbf90eb6ff0ee3b9852f310db1ca3e1b
/toolsrc/include/StatusParagraph.h
1386bbdf4495d540bb7991a9acdf6175ca54badf
[ "MIT" ]
permissive
martin-traverse/vcpkg
69adae741d5426e9f4fb9a5853381984aa4bd9a7
da09a8136d32890ab5f3804d9abcc5f9685a30e0
refs/heads/master
2022-11-09T10:09:06.286239
2017-03-09T22:17:00
2017-03-09T22:17:00
84,499,040
0
0
NOASSERTION
2022-11-04T10:27:45
2017-03-09T23:41:26
CMake
UTF-8
C++
false
false
756
h
StatusParagraph.h
#pragma once #include <unordered_map> #include "BinaryParagraph.h" namespace vcpkg { enum class install_state_t { error, not_installed, half_installed, installed, }; enum class want_t { error, unknown, install, hold, deinstall, purge }; struct StatusParagraph { StatusParagraph(); explicit StatusParagraph(const std::unordered_map<std::string, std::string>& fields); BinaryParagraph package; want_t want; install_state_t state; }; std::ostream& operator<<(std::ostream& os, const StatusParagraph& pgh); std::string to_string(install_state_t f); std::string to_string(want_t f); }
0d4d5d16546dfbb58770e69d2f046ba1292251ac
1e730ca5fab13013ad44a2c81dda517451568b26
/Robot/Robot.ino
eb4316e44a761b170ab15cd5e994a5e7274d14f9
[]
no_license
lostangles/Robot
1675d5f6b5158cae1b552b69a3718d4d0e34b712
ae798f4456fc3fe657dfacf76cc3042cd424a3df
refs/heads/master
2021-01-11T00:32:21.147245
2016-11-16T22:11:27
2016-11-16T22:11:27
70,516,621
0
0
null
null
null
null
UTF-8
C++
false
false
29,087
ino
Robot.ino
#include <Wire.h> #include <LiquidCrystal.h> #include "Arduino.h" #include <math.h> #include "SharpIR.h" #include "QTRSensors.h" //Line sensor defines #define Kp_line .13 // experiment to determine this, start by something small that just makes your bot follow the line at a slow speed #define Kd_line 1 #define Ki_line 0// experiment to determine this, slowly increase the speeds and adjust this value. ( Note: Kp < Kd) #define rightMaxSpeed 200 // max speed of the robot #define leftMaxSpeed 200 // max speed of the robot #define rightBaseSpeed 150 // this is the speed at which the motors should spin when the robot is perfectly on the line #define leftBaseSpeed 150 // this is the speed at which the motors should spin when the robot is perfectly on the line #define NUM_SENSORS 5 // number of sensors used #define TIMEOUT 2500 // waits for 2500 us for sensor outputs to go low #define EMITTER_PIN 3 // emitter is controlled by digital pin 2 #define rightMotor1 3 #define rightMotor2 4 #define rightMotorPWM 5 #define leftMotor1 12 #define leftMotor2 13 #define leftMotorPWM 4 #define motorPower 8 //Encoder pins #define encRtA T4 //on PH7 #define encLtA T5 //on PL2 #define PWM_lt 4 #define PWM_rt 5 #define EN_lt 7 #define EN_rt 6 //LCD pins #define LCD_RS 24 #define LCD_EN 25 #define LCD_D0 18 #define LCD_D1 19 #define LCD_D2 22 #define LCD_D3 23 //GLOBAL VARIABLES #define DEBUG false #define LOOPTIME 100 #define WHEEL_SIZE 1.18 #define WHEEL_DISTANCE 6.69 #define SONAR_NUM 3 // Number of sensors. #define MAX_DISTANCE 200 // Maximum distance (in cm) to ping. #define PING_INTERVAL 50 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo). #define IR_LeftLeft A15 #define IR_Front A14 #define IR_RightRight A7 #define IR_Left A9 #define IR_Right A6 SharpIR sharp_l(IR_Left, 25, 93, 1080); SharpIR sharp_r(IR_Right, 25, 93, 1080); int Sensor[4]; int last_proximity = 0; int base_speed_lt = 150; int base_speed_rt = 150; const int set_point = 30; double P_adjust = 0; double I_adjust = 0; double D_adjust = 0; int PIorD = 0; ////////////PROJECT VARIABLES/////////////// float x, y, Beta, theta, Vr, Vl, w, R; int DirL = 0; int DirR = 1; char cmd[15]; int target_x, target_y, target_theta; bool NewCommand = false; bool Waypoint = false; int errSum = 0; int DistanceToGoal = 0; int InitialDistanceToGoal = 0; float Goal[3]; float PreGoal[3]; int errSum_lt = 0; int errSum_rt = 0; //Sensor 0 = front //Sensor 1 = Right //Sensor 2 = left boolean Maze = false; //Line following stuff unsigned char QTIPins[] = { A1, A2, A3, A4, A5 }; QTRSensorsRC qtrrc(QTIPins, 3, TIMEOUT, EMITTER_PIN); // sensor connected through analog pins A0 - A5 i.e. digital pins 14-19 int lastError = 0; double I = 0; int position = -1; boolean LineFollow = false; //LCD Setup LiquidCrystal LCD(LCD_RS, LCD_EN, LCD_D0, LCD_D1, LCD_D2, LCD_D3); //Button input // Right = 1 // Up = 2 // Down = 3 // Left = 4 // Select = 5 volatile int button = 0; enum Function { DRIVE, LINE, TURN, STOP, CALIBRATE, COURSE, MAZE, LEADER, FOLLOWER, COMMAND, NAVIGATE } FUNCTION; /* enum Direction { LEFT, RIGHT, FWD, REV, BRAKE, HARD_LEFT }direction_t; */ Function STATE; int StateIncrementer = 0; enum Direction { LEFT, RIGHT } DIRECTION; int CourseCounter = 0; volatile boolean RobotStopped = true; volatile boolean RaceStarted = false; //Motor/Encoder variables volatile int target_rt = 150; volatile int target_lt = 150; volatile int RPM_rt = 0; volatile int RPM_lt = 0; static int last_error_rt = 0; static int last_error_lt = 0; unsigned long currentMilli = 0; unsigned long lastMilli = 0; volatile unsigned long speed_count_rt = 0; volatile unsigned long speed_count_lt = 0; volatile unsigned long distance_count_rt = 0; volatile unsigned long distance_count_lt = 0; volatile unsigned long desired_distance = 0; volatile unsigned long count = 0; volatile long lastCount_rt = 0; volatile long lastCount_lt = 0; volatile long count_correction = 1000; // take into account that the wheels don't stop when PWM's go to 0 int PWM_val_rt = 0; int PWM_val_lt = 0; float Kp = 1.5;//.45; //setting Kp float Ki = 1;// .5;// 1.8; // .55 //.98 float Kd = .5;// .5;// 5.5;// 1.8; // 1.5; //.58 //.98 //setting Kd //End motor variables void pinInit() { pinMode(PWM_rt, OUTPUT); pinMode(PWM_lt, OUTPUT); pinMode(EN_lt, OUTPUT); pinMode(EN_rt, OUTPUT); analogWrite(PWM_rt, 0); analogWrite(PWM_lt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); pinMode(A11, OUTPUT); pinMode(A10, INPUT); } void LCDInit() { LCD.begin(16, 2); LCD.setCursor(0, 0); LCD.print("Mode: "); LCD.print(FUNCTION); } void TCInit() { TIMSK4 &= ~(1 << TOIE4); //disable Timer4 interrupt TIMSK5 &= ~(1 << TOIE5); //disable Timer5 interrupt TCCR4A = 0; // set entire TCCR4A register to 0 TCCR4B = 0; TCCR5A = 0; // set entire TCCR5A register to 0 TCCR5B = 0; //Set timer4 mode 0 TCCR4A &= ~(1 << WGM40); TCCR4A &= ~(1 << WGM41); TCCR4B &= ~(1 << WGM43); TCCR4B &= ~(1 << WGM42); //Set timer4 external clock, triggered on rising edge (T1 pin = Arduino pin 5) TCCR4B |= (1 << CS42); TCCR4B |= (1 << CS41); TCCR4B &= ~(1 << CS40); //Set timer5 mode 0 TCCR5A &= ~(1 << WGM50); TCCR5A &= ~(1 << WGM51); TCCR5B &= ~(1 << WGM53); TCCR5B &= ~(1 << WGM52); //Set timer5 external clock, triggered on rising edge (T1 pin = Arduino pin 5) TCCR5B |= (1 << CS52); TCCR5B |= (1 << CS51); TCCR5B |= (1 << CS50); //TIMSK4 |= (1 << TOIE4); //enable Timer4 interrupt //TIMSK5 |= (1 << TOIE5); //enable Timer5 interrupt } void ReadButtons() { int x; x = analogRead(0); LCD.setCursor(7, 0); if (x < 60) { button = 1; LCD.print("Right "); if (STATE == MAZE && PIorD != 0) { if (STATE == MAZE && PIorD == 1) P_adjust = P_adjust + .1; if (STATE == MAZE && PIorD == 2) I_adjust = I_adjust + .1; if (STATE == MAZE && PIorD == 3) D_adjust = D_adjust + .1; } else StateIncrementer++; } else if (x < 200) { button = 2; if (STATE == MAZE) { PIorD++; if (PIorD > 3) PIorD = 0; } // STATE = DRIVE; } else if (x < 400) { button = 3; if (STATE == MAZE) { PIorD--; if (PIorD < 0) PIorD = 3; } // LCD.print("Line"); // STATE = LINE; } else if (x < 600) { button = 4; // LCD.print("Left "); if (STATE == MAZE && PIorD != 0) { if (STATE == MAZE && PIorD == 1) P_adjust = P_adjust - .1; if (STATE == MAZE && PIorD == 2) I_adjust = I_adjust - .1; if (STATE == MAZE && PIorD == 3) D_adjust = D_adjust - .1; } else { if (StateIncrementer != 0) StateIncrementer--; else StateIncrementer = 8; } } else if (x < 800) { if (FUNCTION == STOP) { button = 5; FUNCTION = STATE; distance_count_lt = 0; distance_count_rt = 0; //LCD.print("Select"); } else { FUNCTION = STOP; PWM_val_lt = 0; PWM_val_rt = 0; } } delay(200); } void ChangeAngle(int angle) { int steps = CountsPerDistance( angle * (28.26 / 360) ); desired_distance = steps; OCR4A = steps; OCR5A = steps; TIMSK4 |= (1 << TOIE4); TIMSK5 |= (1 << TOIE5); FUNCTION = TURN; } void setup() { Serial.begin(115200); FUNCTION = STOP; DIRECTION = LEFT; pinInit(); LCDInit(); TCInit(); TCNT5 = 0; TCNT4 = 0; x = 0; y = 0; theta = PI / 2; Vr = 0; Vl = 0; DirL = 0; DirR = 1; while (Serial.available() > 0) char flushBuffer = Serial.read(); } void Brake() { //This is applying "brakes" digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 0); analogWrite(PWM_rt, 20); analogWrite(PWM_lt, 30); RobotStopped = true; } void LinePID() { unsigned int sensors[NUM_SENSORS]; if (!RaceStarted) UpdateSensors(); position = qtrrc.readLine(sensors); // get calibrated readings along with the line position, refer to the QTR Sensors Arduino Library for more details on line position. int error = position - 1500; if (Sensor[2] < 20 && !RaceStarted ) { analogWrite(rightMotorPWM, 0); analogWrite(leftMotorPWM, 0); } else { RaceStarted = true; int P = error * Kp_line; I = (I + error) * Ki_line; int D = (error - lastError) * Kd_line; int motorSpeed = P + I + D; lastError = error; int rightMotorSpeed = rightBaseSpeed + motorSpeed; int leftMotorSpeed = leftBaseSpeed - motorSpeed; if (rightMotorSpeed > rightMaxSpeed) rightMotorSpeed = rightMaxSpeed; // prevent the motor from going beyond max speed if (leftMotorSpeed > leftMaxSpeed) leftMotorSpeed = leftMaxSpeed; // prevent the motor from going beyond max speed if (rightMotorSpeed < 70) rightMotorSpeed = 0; // keep the motor speed positive if (leftMotorSpeed < 80) leftMotorSpeed = 0; // keep the motor speed positive analogWrite(rightMotorPWM, rightMotorSpeed); analogWrite(leftMotorPWM, leftMotorSpeed); } } void BackUp() { digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 0); analogWrite(PWM_lt, 110); analogWrite(PWM_rt, 100); delay(300); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); delay(50); } void UpdateSensors() { int raw = analogRead(IR_Right); float voltFromRaw = map(raw, 0, 1023, 0, 5000); Sensor[1] = 27.728*pow(voltFromRaw / 1000, -1.2045); raw = analogRead(IR_LeftLeft); voltFromRaw = map(raw, 0, 1023, 0, 5000); Sensor[4] = 27.728*pow(voltFromRaw / 1000, -1.2045); raw = analogRead(IR_Front); voltFromRaw = map(raw, 0, 1023, 0, 5000); Sensor[0] = 27.728*pow(voltFromRaw / 1000, -1.2045); raw = analogRead(IR_RightRight); voltFromRaw = map(raw, 0, 1023, 0, 5000); Sensor[2] = 27.728*pow(voltFromRaw / 1000, -1.2045); Sensor[3] = sharp_l.distance(); if (Sensor[0] == 50 || Sensor[0] == 51) Sensor[0] = 0; if (Sensor[4] == 50 || Sensor[4] == 51) Sensor[4] = 0; /* for (int i = 0; i < 5; i++) { Serial.print("Sensor["); Serial.print(i); Serial.print("]: "); Serial.print(Sensor[i]); Serial.print(" "); } Serial.print(" Target_rt: "); Serial.print(target_rt); Serial.print(" Target_lt: "); Serial.print(target_lt); Serial.print(" RPM_rt: "); Serial.print(RPM_rt); Serial.print(" RPM_lt: "); Serial.print(RPM_lt); Serial.print(" PWM_val_lt: "); Serial.print(PWM_val_lt); Serial.print(" PWM_val_rt: "); Serial.print(PWM_val_rt); Serial.println();*/ } void MazePID() { UpdateSensors(); int front_proximity = Sensor[2]; int proximity = Sensor[1]; if (front_proximity < 30 && front_proximity != 0) { BackUp(); delay(500); TurnLeft90(); delay(500); } double error = proximity - set_point ; double P = error * ( P_adjust); I = (I + error) * (I_adjust); double D = (error - lastError) * ( D_adjust ); double motorSpeed = (P + I + D); lastError = error; int rightMotorSpeed = rightBaseSpeed + motorSpeed; int leftMotorSpeed = leftBaseSpeed - motorSpeed; if (rightMotorSpeed > rightMaxSpeed) rightMotorSpeed = rightMaxSpeed; // prevent the motor from going beyond max speed if (leftMotorSpeed > leftMaxSpeed) leftMotorSpeed = leftMaxSpeed; // prevent the motor from going beyond max speed if (rightMotorSpeed < 70) rightMotorSpeed = 80; // keep the motor speed positive if (leftMotorSpeed < 80) leftMotorSpeed = 80; // keep the motor speed positive analogWrite(rightMotorPWM, rightMotorSpeed); analogWrite(leftMotorPWM, leftMotorSpeed); /* int P = proximity - set_point; int D = proximity - last_proximity; int Pd = P * .8 + D * 10; int left_motor = base_speed_lt - Pd; int right_motor = base_speed_rt + Pd; if (left_motor < 80) left_motor = 80; if (right_motor < 80) right_motor = 80; analogWrite(PWM_lt, left_motor); analogWrite(PWM_rt, right_motor); */ last_proximity = proximity; Serial.print("Left PWM: "); Serial.print(leftMotorSpeed); Serial.print(" Right PWM: "); Serial.print(rightMotorSpeed); Serial.print(" Left sensor: "); Serial.print(proximity); Serial.print(" Front sensor: "); Serial.println(front_proximity); } void Leader() { // unsigned int sensors[NUM_SENSORS]; UpdateSensors(); // int cliff = qtrrc.readLine(sensors); // Serial.println("Cliff: "); Serial.print(cliff); // position = cliff; while ( (Sensor[0] > 7 || Sensor[2] < 20) && Sensor[0] != 0 && Sensor[2] != 0) { if (Sensor[0] > 15) FUNCTION = STOP; delay(1000); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); UpdateSensors(); // FUNCTION = STOP; } if (Sensor[1] > 15) { //PWM_val_lt += 15; //PWM_val_rt -= 10; digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 0); analogWrite(PWM_lt, 120); analogWrite(PWM_rt, 100); delay(15); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); } else if (Sensor[3] > 15) { //PWM_val_lt -= 10; //PWM_val_rt += 15; digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 1); analogWrite(PWM_lt, 110); analogWrite(PWM_rt, 100); delay(15); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); } else { digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); analogWrite(PWM_lt, 120); analogWrite(PWM_rt, 100); delay(30); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); } //SetSpeed_L(); //SetSpeed_R(); /* if (PWM_val_lt > 200) PWM_val_lt = 200; if (PWM_val_rt > 200) PWM_val_rt = 200; if (PWM_val_lt < 70) PWM_val_lt = 70; if (PWM_val_rt < 75) PWM_val_rt = 75; */ //delay(100); } void Follower() { // unsigned int sensors[NUM_SENSORS]; UpdateSensors(); float error = Sensor[2] - 30; float Kp = .5; int PWM_value = round( constrain((error)* Kp + 120, 90, 255)); if ((error) > 0) { if (Sensor[1] > 15) { //PWM_val_lt += 15; //PWM_val_rt -= 10; digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 0); analogWrite(PWM_lt, 120); analogWrite(PWM_rt, 100); delay(10); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); } else if (Sensor[3] > 15) { //PWM_val_lt -= 10; //PWM_val_rt += 15; digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 1); analogWrite(PWM_lt, 110); analogWrite(PWM_rt, 100); delay(10); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); } else { digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); analogWrite(PWM_lt, PWM_value + 5); analogWrite(PWM_rt, PWM_value); delay(30); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); } //SetSpeed_L(); //SetSpeed_R(); /* if (PWM_val_lt > 200) PWM_val_lt = 200; if (PWM_val_rt > 200) PWM_val_rt = 200; if (PWM_val_lt < 70) PWM_val_lt = 70; if (PWM_val_rt < 75) PWM_val_rt = 75; */ //delay(25); } //analogWrite(PWM_lt, 0); //analogWrite(PWM_rt, 0); } void ModeLoop() { switch (FUNCTION) { case DRIVE: RobotStopped = false; if ( (distance_count_lt >= desired_distance) || (distance_count_rt >= desired_distance)) { /* //Moved to STOP function if (!RobotStopped) { digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 0); analogWrite(PWM_rt, 30); analogWrite(PWM_lt, 50); //delay(1); }*/ FUNCTION = STOP; distance_count_lt = 0; distance_count_rt = 0; PWM_val_lt = 0; PWM_val_rt = 0; } else { printCount(); SetSpeed_L(); SetSpeed_R(); analogWrite(PWM_lt, PWM_val_lt); analogWrite(PWM_rt, PWM_val_rt); } break; case LEADER: RobotStopped = false; //Leader(); break; case FOLLOWER: RobotStopped = false; break; case COURSE: CourseCounter = 1; FUNCTION = DRIVE; break; case MAZE: Maze = true; MazePID(); break; case TURN: RobotStopped = false; if (DIRECTION == LEFT) { digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 1); FUNCTION = DRIVE; } else if (DIRECTION == RIGHT) { digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 0); FUNCTION = DRIVE; } break; case LINE: LineFollow = true; break; case COMMAND: //printCount(); if (NewCommand) executeCmd(); break; case NAVIGATE: getCmd(); break; case CALIBRATE: for (int i = 0; i < 100; i++) // calibrate for sometime by sliding the sensors across the line qtrrc.calibrate(); FUNCTION = STOP; break; case STOP: if (!RobotStopped) { //This is applying "brakes" digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 0); analogWrite(PWM_rt, 40); analogWrite(PWM_lt, 50); } else { analogWrite(PWM_rt, 0); analogWrite(PWM_lt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); // count_correction = distance_count_rt; } RobotStopped = true; //target_lt = 100; //target_rt = 100; break; } } ISR(TIMER5_COMPA_vect) { //TIMSK4 &= ~(1 << TOIE4); //disable Timer4 interrupt //TIMSK5 &= ~(1 << TOIE5); //disable Timer5 interrupt } ISR(TIMER4_COMPA_vect) { //TIMSK4 &= ~(1 << TOIE4); //disable Timer4 interrupt //TIMSK5 &= ~(1 << TOIE5); //disable Timer5 interrupt } void LCDLoop() { if (FUNCTION == STOP) ReadButtons(); LCD.setCursor(0, 0); switch (StateIncrementer) { case 0: LCD.setCursor(0, 0); LCD.print("Mode: Stopped "); STATE = STOP; break; case 1: LCD.setCursor(0, 0); LCD.print("Mode: Drive "); STATE = DRIVE; desired_distance = CountsPerDistance(60); break; case 2: LCD.setCursor(0, 0); LCD.print("Mode: Line "); STATE = LINE; break; case 3: LCD.setCursor(0, 0); LCD.print("Mode: Calibrate "); STATE = CALIBRATE; unsigned int sensors[3]; position = qtrrc.readLine(sensors); UpdateSensors(); Serial.println(position); break; case 4: LCD.setCursor(0, 0); LCD.print("Mode: Course "); STATE = COURSE; break; case 5: LCD.setCursor(0, 0); LCD.print("Mode: Maze "); STATE = MAZE; break; case 6: LCD.setCursor(0, 0); LCD.print("Mode: Leader "); STATE = LEADER; break; case 7: LCD.setCursor(0, 0); LCD.print("Mode: Follower "); STATE = FOLLOWER; break; case 8: LCD.setCursor(0, 0); LCD.print("Mode: Navigate "); STATE = NAVIGATE; break; default: StateIncrementer = 0; break; } LCD.setCursor(0, 1); if (STATE == LINE || STATE == CALIBRATE) { LCD.setCursor(0, 1); LCD.print(Sensor[2]); if (position > 1400 && position < 1600) { LCD.print(" X0X "); Serial.print(position); } else if (position < 1400) { LCD.print(" XX0 "); LCD.print(position); LCD.print(" "); } else if (position > 1600) { LCD.print(" 0XX "); LCD.print(position); LCD.print(" "); } else { LCD.print(" XXX "); LCD.print(" "); LCD.print(" "); } } else if (STATE == MAZE) { LCD.print(""); LCD.print(P_adjust); LCD.print(" "); LCD.print(I_adjust); LCD.print(" "); LCD.print(D_adjust); } else if (STATE == LEADER || STATE == FOLLOWER) { LCD.print(" L: "); LCD.print(Sensor[1]); LCD.print(" R: "); LCD.print(Sensor[3]); LCD.print(" "); LCD.print(Sensor[0]); LCD.print(" "); } else if (STATE == NAVIGATE) { LCD.print("X: "); LCD.print(x); LCD.print(" Y: "); LCD.print(y); LCD.print(" "); } else { LCD.print(" L: "); LCD.print(RPM_lt); LCD.print(" R: "); LCD.print(RPM_rt); LCD.print(" "); } } void TurnRight90() { int temp = TCNT4; int temp2 = TCNT5; //RobotStopped = false; digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 0); analogWrite(PWM_lt, 115); analogWrite(PWM_rt, 105); delay(190); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); delay(50); TCNT4 = temp; TCNT5 = temp2; } void TurnLeft90() { int temp = TCNT4; int temp2 = TCNT5; //RobotStopped = false; digitalWrite(EN_lt, 1); digitalWrite(EN_rt, 1); analogWrite(PWM_lt, 115); analogWrite(PWM_rt, 105); delay(205); analogWrite(PWM_lt, 0); analogWrite(PWM_rt, 0); digitalWrite(EN_lt, 0); digitalWrite(EN_rt, 1); delay(50); TCNT4 = temp; TCNT5 = temp2; } void CourseControl() { if (CourseCounter == 1 && RobotStopped) { delay(250); CourseCounter++; FUNCTION = DRIVE; desired_distance = CountsPerDistance(20); distance_count_lt = 0; distance_count_rt = 0; } else if (CourseCounter == 2 && RobotStopped ){ delay(250); CourseCounter++; TurnRight90(); delay(250); desired_distance = CountsPerDistance(5.5); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; } else if (CourseCounter == 3 && RobotStopped) { delay(250); CourseCounter++; TurnRight90(); delay(250); desired_distance = CountsPerDistance(20); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; } else if (CourseCounter == 4 && RobotStopped) { delay(250); CourseCounter++; TurnRight90(); delay(250); desired_distance = CountsPerDistance(2); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; CourseCounter = 0; } else if (CourseCounter == 5 && RobotStopped) { delay(500); TurnRight90(); delay(200); TurnRight90(); delay(200); CourseCounter++; } else if (CourseCounter == 6 && RobotStopped) { delay(500); CourseCounter++; desired_distance = CountsPerDistance(60); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; } else if (CourseCounter == 7 && RobotStopped) { delay(500); CourseCounter++; TurnLeft90(); delay(200); desired_distance = CountsPerDistance(36); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; } else if (CourseCounter == 8 && RobotStopped) { delay(500); CourseCounter++; TurnLeft90(); delay(200); desired_distance = CountsPerDistance(96); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; } else if (CourseCounter == 9 && RobotStopped) { delay(500); CourseCounter++; TurnLeft90(); delay(200); desired_distance = CountsPerDistance(24); distance_count_lt = 0; distance_count_rt = 0; FUNCTION = DRIVE; CourseCounter = 0; } } void loop() { if (!LineFollow && !(FUNCTION == LEADER) && !(FUNCTION == FOLLOWER)) { if ((millis() - lastMilli) >= LOOPTIME) { currentMilli = lastMilli; lastMilli = millis(); getCount(); if (DEBUG) printCount(); if (CourseCounter != 0) CourseControl(); LCDLoop(); ModeLoop(); //printCount(); if (STATE == NAVIGATE) getCmd(); } } else if (LineFollow) LinePID(); else if (FUNCTION == LEADER) { Leader(); LCDLoop(); } else if (FUNCTION == FOLLOWER) { Follower(); LCDLoop(); } // UpdateSensors(); } //Given a distance, returns the amount of counts on the output shaft to get there int CountsPerDistance(double distance) { // int temp = count_correction; // if (FUNCTION == TURN) temp = 0; return (round((distance / (WHEEL_SIZE * PI * 2 * 2)) * (2249/3.0))); // -temp; //1100 is roughly how many extra encoder ticks happen after shutting the motors off } void SetSpeed_R() { PWM_val_rt = updatePid_rt(PWM_val_rt, target_rt, RPM_rt); } void SetSpeed_L() { PWM_val_lt = updatePid_lt(PWM_val_lt, target_lt, RPM_lt); } int updatePid_rt(int command, int targetValue, int currentValue) { // compute PWM value float pidTerm = 0; // PID correction int error = 0; int dErr = 0; error = abs(targetValue) - abs(currentValue); dErr = round(((error - last_error_rt) / (LOOPTIME / 1000))); errSum_rt += error * (LOOPTIME / 1000); pidTerm = ((Kp - 0) * error) + ( (Kd + 0) * (dErr)) + ( (Ki ) * errSum); last_error_rt = error; return constrain(command + int(pidTerm), 76, 255); } int updatePid_lt(int command, int targetValue, int currentValue) { // compute PWM value float pidTerm = 0; // PID correction int error = 0; int dErr = 0; error = abs(targetValue) - abs(currentValue); dErr = (error - last_error_lt) / (LOOPTIME/1000); errSum_lt += error * (LOOPTIME / 1000); //.33 pidTerm = ((Kp + 0 ) * error) + ( (Kd + 0) * (dErr)) + ((Ki + 0 ) * errSum ); last_error_lt = error; return constrain(command + int(pidTerm), 93, 255); } void getCount() { cli(); speed_count_rt = TCNT5; speed_count_lt = TCNT4; distance_count_lt += speed_count_lt; distance_count_rt += speed_count_rt; TCNT5 = 0; TCNT4 = 0; sei(); lastCount_rt = speed_count_rt; lastCount_lt = speed_count_lt; RPM_lt = ((float)speed_count_lt) * 60 * ((1000.0 / (float)LOOPTIME)) / (2249.0/3.0); RPM_rt = ((float)speed_count_rt) * 60 * ((1000.0 / (float)LOOPTIME)) / (2249.0/3.0); Vl = RPM_lt * (WHEEL_SIZE ) / 60; Vr = RPM_rt * (WHEEL_SIZE ) / 60; x += Vr * cos(theta); y += Vl * sin(theta); theta += (Vr - Vl) / WHEEL_DISTANCE; if (Vr - Vl != 0) R = (WHEEL_DISTANCE / 2) * (Vr + Vl) / (Vr - Vl); else R = 0; w = (Vr - Vl) / WHEEL_DISTANCE; if (theta > 2 * PI ) theta -= 2 * PI; else if (theta < -2 * PI ) theta += 2 * PI; Serial.print(x); Serial.print(","); Serial.print(y); Serial.print(","); Serial.print(theta); Serial.print(","); Serial.print(Vl); Serial.print(","); Serial.print(Vr); Serial.print(","); Serial.print(w); Serial.print(","); Serial.println(R); } void printCount() { String message = ""; message += "PWM_val_rt: "; message += PWM_val_rt; message += " RPM_rt: "; message += RPM_rt; message += "\nPWM_val_lt: "; message += PWM_val_lt; message += " RPM_lt: "; message += RPM_lt; message += " Vr: "; message += Vr; message += " Vl: "; message += Vl; message += " x: "; message += x; message += " y: "; message += y; message += " theta: "; message += theta * RAD_TO_DEG; message += " target x: "; message += target_x; message += " target_y: "; message += target_y; message += " target_theta: "; message += target_theta; message += " Time: "; Serial.print(message); Serial.println(lastMilli - currentMilli); // Serial.println(distance_count_lt); /* Serial.print("Count_rt: "); Serial.print(speed_count_rt); Serial.print(" Last Count_rt: "); Serial.print(lastCount_rt); Serial.print(" PWM_val_rt: "); Serial.print(PWM_val_rt); Serial.print(" RPM_rt: "); Serial.print(RPM_rt); Serial.print(" Distance count right: "); Serial.print(distance_count_rt); Serial.print(" Desired distance: "); Serial.print(desired_distance); Serial.print(" Target_RPM_rt: "); Serial.println(target_rt); Serial.print("Count_lt: "); Serial.print(speed_count_lt); Serial.print(" Last Count_lt: "); Serial.print(lastCount_lt); Serial.print(" PWM_val_lt: "); Serial.print(PWM_val_lt); Serial.print(" RPM_lt: "); Serial.println(RPM_lt); //Serial.print(" Target_RPM_lt: "); Serial.println(target_lt); */ } void getCmd() { int i = 0; if (Serial.available() > 0) { while (Serial.available() > 0) { char command = Serial.read(); cmd[i] = command; i++; } if (cmd[0] != NULL) parseCommand(); } } void parseCommand() { int j = 0; int commaCnt = 0; char temp[15]; //Serial.println(cmd); for (int i = 0; i < 10; i++) { if (cmd[i] == ',') { temp[j + 1] = NULL; if (commaCnt == 0) { target_x = atoi(temp); Goal[0] = target_x; j = 0; } else if (commaCnt == 1) { target_y = atoi(temp); Goal[1] = target_y; j = 0; } else if (commaCnt == 2) { target_theta = atoi(temp) * DEG_TO_RAD; j = 0; Goal[2] = target_theta; InitialDistanceToGoal = sqrt(pow(target_x - x, 2) + pow(target_y - y, 2)); PreGoal[0] = target_x + (InitialDistanceToGoal/2 * cos( target_theta + 180*DEG_TO_RAD )); PreGoal[1] = target_y + (InitialDistanceToGoal/2 * sin( target_theta + 180*DEG_TO_RAD )); PreGoal[2] = (target_theta + 180*DEG_TO_RAD); } commaCnt++; temp[1] = temp[2] = temp[3] = temp[4] = NULL; } else { temp[j] = cmd[i]; j++; } NewCommand = true; FUNCTION = COMMAND; } } void executeCmd() { SpeedTrack(); HeadingTrack(); if (FUNCTION == COMMAND && DistanceToGoal < 5 ) { Brake(); FUNCTION = STOP; NewCommand = false; Waypoint = false; } } void SpeedTrack() { //Serial.println( (Beta - theta) * RAD_TO_DEG); DistanceToGoal = sqrt(pow(target_x - x, 2) + pow(target_y - y, 2)); int error = 0; int dErr = 0; error = (DistanceToGoal); dErr = ((error - last_error_lt) / (LOOPTIME / 1000)); errSum += (error) * (LOOPTIME / 1000); last_error_lt = error; int PID = (8)*error + (3)*dErr + (4)*errSum; base_speed_rt = constrain(PID, 100, 200); base_speed_lt = constrain(PID, 100, 200); //Serial.println(error); //Serial.println(base_speed_lt); } void HeadingTrack() { //Serial.println( (Beta - theta) * RAD_TO_DEG); Beta = (atan2(target_y - y, target_x - x)) - (1.75 * DEG_TO_RAD);// -(45 * DEG_TO_RAD); //Serial.println((Beta)* RAD_TO_DEG); int error = 0; int dErr = 0; error = (Beta - theta) * RAD_TO_DEG; //Serial.println(error); dErr = ((error - last_error_rt) / (LOOPTIME / 1000)); errSum += (error) * (LOOPTIME / 1000); last_error_rt = error; int motorSpeed = (8)*error + (3)*dErr + (4)*errSum; int rightMotorSpeed = base_speed_rt + motorSpeed; int leftMotorSpeed = base_speed_lt - motorSpeed; PWM_val_lt = constrain(leftMotorSpeed, 80, 255); PWM_val_rt = constrain(rightMotorSpeed, 80, 255); analogWrite(rightMotorPWM, PWM_val_rt); analogWrite(leftMotorPWM, PWM_val_lt); }
a07e5ac2084cec1d4f07f6b2c3ad141da110325a
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir11710/file11748.cpp
de5f72ae337867031186a9d7e0e45dfde1ff1056
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
file11748.cpp
#ifndef file11748 #error "macro file11748 must be defined" #endif static const char* file11748String = "file11748";
4341dfcd3d67a9d7891771d7cd1517eeea991735
68e79139e39ad2330b5157b60edbae1e02c778d9
/src/core/transformations/map_height.h
11a4a93ef90bbdb02a9a43a45c82eab9826715b5
[]
no_license
pandaive/pto_takifajnyprojekt
2bf59e42ede85acac1f32dae32e87fc664a3720f
750aa8255e965d688c6c5b63df76ba8291b91433
refs/heads/master
2021-01-23T04:40:03.333695
2016-01-28T02:59:41
2016-01-28T02:59:41
43,886,572
0
0
null
null
null
null
UTF-8
C++
false
false
243
h
map_height.h
#ifndef MAP_HEIGHT_H #define MAP_HEIGHT_H #include "transformation.h" class MapHeight : public Transformation { public: MapHeight(PNM*); MapHeight(PNM*, ImageViewer*); PNM* transform(); }; #endif // MAP_HEIGHT_H
57a6f15eee2469eb0b18d1b93c5d3b3c6d6e3752
9cdd1751bc27310f486427aaaae901ca06b79003
/be/src/runtime/debug-options.h
4b723b3096c6ab3c7c56eb5fb70c71ee50dc4b2c
[ "Apache-2.0", "OpenSSL", "bzip2-1.0.6", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows", "LicenseRef-scancode-google-patent-license-webrtc", "PSF-2.0", "BSD-3-Clause", "dtoa", "MIT", "LicenseRef-scancode-mit-modification-obligations", "Minpack", "BSL-1.0", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apache/impala
bb9970c64a43824950ec5b69f2ef4b50158a1e8a
b718d63860356a04814e07d91711c3c748b3e769
refs/heads/master
2023-09-03T04:29:12.639452
2023-06-07T23:51:15
2023-08-30T04:56:51
56,128,733
985
475
Apache-2.0
2023-08-31T14:15:44
2016-04-13T07:00:08
C++
UTF-8
C++
false
false
2,513
h
debug-options.h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 IMPALA_RUNTIME_DEBUG_OPTIONS_H #define IMPALA_RUNTIME_DEBUG_OPTIONS_H #include <vector> #include <string> #include "gen-cpp/Frontend_types.h" #include "gen-cpp/Types_types.h" #include "gen-cpp/ImpalaInternalService_types.h" namespace impala { // Container for debug options in TPlanFragmentInstanceCtx (debug_node, debug_action, // debug_phase). // TODO: move to subdirectory /coordinator class DebugOptions { public: DebugOptions(const TQueryOptions& query_options); TDebugOptions ToThrift() const; /// query-wide fragment instance index; -1 if not set int instance_idx() const { return instance_idx_; } /// The node the debug option should be applied to. -1 if it should be applied to all /// nodes. int node_id() const { return node_id_; } /// True if a debug action is enabled. bool enabled() const { return phase_ != TExecNodePhase::INVALID; } TDebugAction::type action() const { return action_; } TExecNodePhase::type phase() const { return phase_; } std::string action_param() const { return action_param_; } private: int instance_idx_; int node_id_; TDebugAction::type action_; TExecNodePhase::type phase_; // INVALID: debug options invalid // A string parameter that goes along with 'action_'. The semantics depend on the // specific action. std::string action_param_; static TExecNodePhase::type GetExecNodePhase(const std::string& key); // Parse a debug action from a string. Either of format "ACTION_TYPE" or // "ACTION_TYPE@<param value>". Returns true when 'action' is a valid debug action // string. static bool GetDebugAction( const std::string& action, TDebugAction::type* type, std::string* action_param); }; } #endif
202972bb41b0afb1866b526ac5b3c2b06777baef
a4c86e1aa7573ec15a87aaf954c8b4f64d512d56
/Chapter8/H8.7.cc
f7f5e8b5b83192b38d6afe138bf01b555c4ad9d6
[]
no_license
ghostxiu/CplusplusPrimerPlus6thEditions
b0916b5ac0f5adfd8b6f4daa40d3a4c996eb1592
c7bd797cf2028eb31b20acc2a7511260e04f5b67
refs/heads/master
2020-07-05T17:02:47.512468
2018-01-19T03:32:52
2018-01-19T03:32:52
73,989,525
1
0
null
null
null
null
UTF-8
C++
false
false
1,070
cc
H8.7.cc
//修改8.14,显示数组总和 #include<iostream> using namespace std ; template<class T> T sum_arr(T arr[] , int n ); template<class T> T sum_arr(T *arr[] , int n ) ; struct debts { char name[50]; double amount ; }; int main() { using namespace std ; int things[6] = {12,31,103,301,310,130}; debts E[3] = { {"Ima Wolfe",2400.0}, {"Ura Foxe",1300.0}, {"Iby Stout",1800.0} }; double *p[3] ; for(int i = 0 ; i < 3 ; ++i ) { p[i] = &E[i].amount; } int sum_a = sum_arr(things,6); cout << "Mr.E's all of things:" ; cout << sum_a << endl ; double sum_b = sum_arr(p,3); cout << "Mr.E's all costs:" ; cout << sum_b << endl ; cin.get(); cin.get(); return 0 ; } template<class T> T sum_arr(T arr[] , int n ) { int sum = 0 ; for(int i = 0 ; i < n ; ++i) { sum += arr[i]; } return sum ; } //调用时 T = double template<class T> T sum_arr(T *arr[] , int n ) { double sum = 0.0 ; for(int i = 0 ; i < n ; ++i) { sum += *arr[i]; } return sum ; }
ff598717188dfaf5171141032541eb0369bb029f
48c9e33a480e531bf5edfa278a64f47aac7a26c3
/AP_spring2016_CPP_Python/HW2/3/3-2/main.cpp
496f8be54a2769eb8ac5ab055ab8e50dce198ece
[]
no_license
mahi97/AUT-HomeWorks
d640c50e64b4233bc3edd0b2aa5e0844c8d61538
2e7c9c8cea8419831d0b9e990620a9278ad185ce
refs/heads/master
2020-12-20T04:37:13.144511
2018-09-27T10:14:54
2018-09-27T10:14:54
73,499,580
5
0
null
2018-09-27T10:14:55
2016-11-11T17:57:58
C++
UTF-8
C++
false
false
1,954
cpp
main.cpp
#include "base.h" int row1{}, col1{}, row2{}, col2{}; template<typename T1, typename T2> auto dynamicMultiply(T1 **_first, T2 **_second)-> decltype(_first[0][0] * _second[0][0]); int main() { std::ifstream file {"matrix.txt"}; std::string mat{}; int **elemnts; double **elemnts2; if(file.is_open()) { file >> mat; file >> row1 >> col1; elemnts = new int* [row1]; for2(i, 0, row1) elemnts[i] = new int[col1]; for2(i, 0, row1) { for2(j, 0, col1) { file >> elemnts[i][j]; std::cout << i <<" "<< j << " "<< elemnts[i][j] << std::endl; } } file >> mat; file >> row2 >> col2; elemnts2 = new double* [row1]; for2(i, 0, row2) elemnts2[i] = new double[col2]; for2(i, 0, row2) for2(j, 0, col2) { file >> elemnts2[i][j]; std::cout << i <<" "<< j << " "<< elemnts2[i][j] << std::endl; } file.close(); } else { std::cout << "file not Found!" << std::endl; return 0; } std::cout << "row1 : " << row1 <<std::endl; std::cout << "col1 : " << col1 <<std::endl; std::cout << "row2 : " << row2 <<std::endl; std::cout << "col2 : " << col2 <<std::endl; std::cout << "Result : " << dynamicMultiply(elemnts, elemnts2) << std::endl; for2(i, 0, row2) delete [] elemnts2[i]; delete [] elemnts2; for2(i, 0, row1) delete [] elemnts[i]; delete [] elemnts; return 0; } template<typename T1, typename T2> auto dynamicMultiply(T1 **_first, T2 **_second) -> decltype(_first[0][0] * _second[0][0]) { decltype(_first[0][0] * _second[0][0]) temp = {}; for2(i, 0, row1) { for2(j, 0, col1) { temp += _first[i][j] * _second[i][j]; } } temp /= 100; return temp; }
ade787ba7566c0aa9959b9b7ae6a8fae055dda4e
7d830df06ab35cabba058602c072573c042a371a
/186-Reverse Words in a String II.cpp
5182bea6b1bb4402cfef78ba96e46fdf010e3c98
[]
no_license
vinsonleelws/LeetCode
26b04f5a9e05f2093e1207ab8760986220564355
92275a92ef68d6726b84218c01dab9da9d05d6d6
refs/heads/master
2020-03-12T21:13:00.890172
2018-10-22T03:24:39
2018-10-22T03:24:39
130,823,369
0
0
null
null
null
null
UTF-8
C++
false
false
1,327
cpp
186-Reverse Words in a String II.cpp
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters. The input string does not contain leading or trailing spaces and the words are always separated by a single space. For example, Given s = "the sky is blue", return "blue is sky the". Could you do it in-place without allocating extra space? class Solution { public: void reverseWords(string &s) { } }; // --------------------------------------------------- // 这道题相比"151-Reverse Words in a String"降低了难度,因为不考虑首尾空格了和单词之间的多空格了,方法还是很简单,先把每个单词翻转一遍,再把整个字符串翻转一遍, // 或者也可以调换个顺序,先翻转整个字符串,再翻转每个单词 class Solution { public: void reverseWords(string &s) { int left = 0; for (int i = 0; i <= s.size(); ++i) { if (i == s.size() || s[i] == ' ') { reverse(s, left, i - 1); left = i + 1; } } reverse(s, 0, s.size() - 1); } void reverse(string &s, int left, int right) { while (left < right) { char t = s[left]; s[left] = s[right]; s[right] = t; ++left; --right; } } };
568eab1b825eaf8c174c8f331fd55a6ddf1961cb
eefc878d0790c14d74b4b8e8ce977653bcf6ae69
/tests/mainTest.cpp
54d3c62cb31626fd676ceceb065fb936e909ff5b
[ "MIT" ]
permissive
Dandigit/wombling
6680606bd127530e43017e90dd35641a2aa6c712
26c3c3252edeb37264f1c5f8564a19620bc2ba29
refs/heads/master
2020-03-24T19:30:34.668310
2018-08-14T10:51:17
2018-08-14T10:51:17
142,930,616
0
0
null
null
null
null
UTF-8
C++
false
false
532
cpp
mainTest.cpp
#include <iostream> #include "../wom/womcolor.h" #include "../wom/womtime.h" #include "../wom/womio.h" int main() { wom::timer t; wom::setColor("red"); std::cout << "Alert! Alert!\n"; wom::setColor("green"); std::cout << "Oh - it's OK now.\n"; wom::resetColor(); std::cout << "Back to normal.\nExecuted in " << t.elapsed() << " milliseconds.\n"; std::cout << "The current time is " << wom::time{} << "\n"; t.restart(); wom::sleep(5327); std::cout << "Waited for " << t.elapsed() << " milliseconds.\n"; wom::pause(); }
e0fa50e4f23569dd614c7109d52e0bcc8c2a0f8f
b806c8c338688effb0b31b73967c1d14b81c2c70
/stdlib/public/stubs/MathStubs.cpp
f6bc8f271320076545a283a403b5d2a350488327
[ "Apache-2.0", "Swift-exception" ]
permissive
TianWenguang/swift
38989321a7f5baef28f2b9ff644419c9dce06795
3124f6ad5082ec0811c2367a59d099884ee033fa
refs/heads/master
2020-03-10T19:11:33.271063
2018-04-14T02:30:05
2018-04-14T02:30:05
129,542,740
1
0
Apache-2.0
2018-04-14T18:15:09
2018-04-14T18:15:09
null
UTF-8
C++
false
false
4,063
cpp
MathStubs.cpp
//===--- MathStubs.cpp - Swift Language Runtime Stubs ---------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Math stubs for functions which should be defined in the core standard // library, but are difficult or impossible to write in Swift at the // moment. // //===----------------------------------------------------------------------===// #include "../SwiftShims/Visibility.h" #include <climits> #include <cstdlib> #if __has_attribute(__mode__) #define SWIFT_MODE_DI __attribute__((__mode__(DI))) #define SWIFT_MODE_TI __attribute__((__mode__(TI))) #else #define SWIFT_MODE_DI #define SWIFT_MODE_TI #endif typedef int di_int SWIFT_MODE_DI; typedef int ti_int SWIFT_MODE_TI; extern "C" { // Although this builtin is provided by clang rt builtins, // it isn't provided by libgcc, which is the default // runtime library on Linux, even when compiling with clang. // This implementation is copied here to avoid a new dependency // on compiler-rt on Linux. // FIXME: rdar://14883575 Libcompiler_rt omits muloti4 #if (defined(__linux__) && defined(__x86_64__)) || \ (defined(__linux__) && defined(__aarch64__)) || \ (defined(__linux__) && defined(__powerpc64__)) || \ (defined(__linux__) && defined(__s390x__)) || \ (defined(__ANDROID__) && defined(__arm64__)) SWIFT_RUNTIME_STDLIB_INTERFACE ti_int __muloti4(ti_int a, ti_int b, int* overflow) { const int N = (int)(sizeof(ti_int) * CHAR_BIT); const ti_int MIN = (ti_int)1 << (N-1); const ti_int MAX = ~MIN; *overflow = 0; ti_int result = a * b; if (a == MIN) { if (b != 0 && b != 1) *overflow = 1; return result; } if (b == MIN) { if (a != 0 && a != 1) *overflow = 1; return result; } ti_int sa = a >> (N - 1); ti_int abs_a = (a ^ sa) - sa; ti_int sb = b >> (N - 1); ti_int abs_b = (b ^ sb) - sb; if (abs_a < 2 || abs_b < 2) return result; if (sa == sb) { if (abs_a > MAX / abs_b) *overflow = 1; } else { if (abs_a > MIN / -abs_b) *overflow = 1; } return result; } #endif // FIXME: ideally we would have a slow path here for Windows which would be // lowered to instructions as though MSVC had generated. There does not seem to // be a MSVC provided multiply with overflow detection that I can see, but this // avoids an unnecessary dependency on compiler-rt for a single function. #if (defined(__linux__) && defined(__arm__)) || defined(_WIN32) // Similar to above, but with mulodi4. Perhaps this is // something that shouldn't be done, and is a bandaid over // some other lower-level architecture issue that I'm // missing. Perhaps relevant bug report: // FIXME: https://llvm.org/bugs/show_bug.cgi?id=14469 SWIFT_RUNTIME_STDLIB_INTERFACE di_int __mulodi4(di_int a, di_int b, int* overflow) { const int N = (int)(sizeof(di_int) * CHAR_BIT); const di_int MIN = (di_int)1 << (N-1); const di_int MAX = ~MIN; *overflow = 0; di_int result = a * b; if (a == MIN) { if (b != 0 && b != 1) *overflow = 1; return result; } if (b == MIN) { if (a != 0 && a != 1) *overflow = 1; return result; } di_int sa = a >> (N - 1); di_int abs_a = (a ^ sa) - sa; di_int sb = b >> (N - 1); di_int abs_b = (b ^ sb) - sb; if (abs_a < 2 || abs_b < 2) return result; if (sa == sb) { if (abs_a > MAX / abs_b) *overflow = 1; } else { if (abs_a > MIN / -abs_b) *overflow = 1; } return result; } #endif }
69d17aa58baa226208b02dec95335547c55f9d9b
619d7a86226f34cd06535720d1421f42d80a31dd
/Functions.cpp
028d8f12196396781c4614ae216785556afb8067
[]
no_license
PhamHaiThang/INT2202-21-DINO-RUN
d85f4bdc8060896751835a6cd18f7b4b53cb9d5c
c9bb79831d335b895ac1497a9aa4dfa9fa93681a
refs/heads/master
2020-05-24T02:03:39.607184
2019-05-16T14:44:55
2019-05-16T14:44:55
187,046,410
0
0
null
null
null
null
UTF-8
C++
false
false
4,912
cpp
Functions.cpp
#include "Functions.h" #include "Score.h" #include <iostream> #define standing 0; #define jump 0; #define running1 1; #define running2 2; #define crouch_jumping 3; #define crouch_running1 4; #define crouch_running2 5; using namespace std; GameObject::GameObject(GameWindow &window,const vector<vector<vector<int>>> &rects_info, int x, int y) : GameWindow(window), _rects_info(rects_info), _x(x), _y(y) {} GameObject::GameObject(GameWindow &window, int w, int h, int x, int y, const string &img_path) : GameWindow(window), _w(w), _h(h), _x(x), _y(y) { SDL_Surface *surface = IMG_Load(img_path.c_str()); if (!surface) { cerr << "Failed to create surface. " << SDL_GetError() << endl; } _texture = SDL_CreateTextureFromSurface(GameWindow::_renderer, surface); if (!_texture) { cerr << "Failed to create texture. " << SDL_GetError() << endl; } SDL_FreeSurface(surface); } GameObject::~GameObject() { SDL_DestroyTexture(_texture); } void GameObject::draw() { if (_texture) { SDL_Rect rect = { _x, _y, _w, _h }; SDL_RenderCopy(GameWindow::_renderer, _texture, 0, &rect); _RECTS.clear(); _RECTS.push_back(rect); } else { for (vector<int> i : _rects_info[shape]) { SDL_Rect rect = { i[2] + _x + addition_x, i[3] + _y + addition_y, i[0], i[1] }; SDL_SetRenderDrawColor(GameWindow::_renderer, 100, 100, 100, 255); SDL_RenderFillRect(GameWindow::_renderer, &rect); if(_RECTS.size() < _rects_info[shape].size()) { _RECTS.push_back(rect); } else { _RECTS.clear(); _RECTS.push_back(rect); } } } } void GameObject::ground_update() { addition_x -= speed + ScoreBoard::current_score / 500; if(_rects_info[shape][0][2] + _x + addition_x + _rects_info[shape][0][0] <= 0) { // outside of the screen addition_x = _width - _rects_info[shape][0][2] - _x; } } void GameObject::obstacle_update() { vector<int> appear_rate; if(ScoreBoard::current_score <= 1000) { appear_rate = { 0,1,1,1,1,2,2,2,2,3,3,3,4}; } else if(ScoreBoard::current_score <= 2000) { appear_rate = { 0,1,1,2,2,2,2,3,3,3,4,4,4,5,6 }; } else if(ScoreBoard::current_score <= 4000) { appear_rate = { 1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,7,7 }; } else { appear_rate = { 1,2,3,3,3,3,4,4,4,4,5,5,6,6,7,7 }; } addition_x -= speed + ScoreBoard::current_score / 500; if(_rects_info[shape][0][2] + _x + addition_x + _rects_info[shape][0][0] <= -300) { // outside of the screen addition_x = _width - _rects_info[shape][0][2] - _x; shape = appear_rate[rand() % appear_rate.size()]; } } int gravity = 30; double addition_gravity = 0; double t = 0.1; int max_velocity = 100; int velocity = 100; void GameObject::t_rex_pos_update() { if(jumping) { if(fast_falling) { addition_gravity += 4; } addition_y = -(velocity * t) + ((gravity + addition_gravity) * t * t / 2); t += 0.15; if(addition_y >= 0) { addition_y = 0; addition_gravity = 0; t = 0.1; jumping = false; fast_falling = false; } } } int step = 0; void GameObject::t_rex_shape_update() { if(GameWindow::playing) { step++; } if(GameWindow::playing == false) { shape = 0; } else if(jumping) { if(crouching) { shape = 3; } else { shape = 0; } } else if(crouching) { if(shape != 4 && shape != 5) { shape = 4; } if(step % 7 == 0) { if(shape != 4) { step = 0; shape = 4; } else if(shape != 5) { step = 0; shape = 5; } } } else { if(shape != 1 && shape != 2) { shape = 1; } if(step % 7 == 0) { if(shape != 1) { step = 0; shape = 1; } else if(shape != 2) { step = 0; shape = 2; } } } } void GameObject::pollEvent(SDL_Event event) { switch(event.type) { case SDL_MOUSEBUTTONDOWN: if(!jumping) { jumping = true; } crouching = false; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_UP || event.key.keysym.sym == SDLK_SPACE) { if (!jumping) { jumping = true; } crouching = false; break; } else if(event.key.keysym.sym == SDLK_DOWN) { if (jumping && !fast_falling) { fast_falling = true; crouching = true; } else if(!jumping && !crouching) { crouching = true; } } break; case SDL_KEYUP: if (event.key.keysym.sym == SDLK_DOWN) { crouching = false; } break; default: break; } } void GameObject::restart() { shape = 0; addition_x = 0; addition_y = 0; jumping = false; fast_falling = false; crouching = false; }
2c16e64c0ffbcc83a3535e5c64ce8123f45a283b
546b701d6b9c42e008ed29f9bb1851d142753074
/code_corpus/manual/sort_4.cpp
4ef0f0ba8c0889f5fb910c2ad044b27830068bde
[]
no_license
rushimg/SVM_code_completion
f5a3308796c4fde5c00d4e38bb5fd2d2b7b71165
37787a10dd56db8cd8e52b81d285f90e1a5c68be
refs/heads/master
2016-08-05T16:01:40.944530
2014-08-27T19:19:38
2014-08-27T19:19:38
14,997,376
3
0
null
null
null
null
UTF-8
C++
false
false
681
cpp
sort_4.cpp
void SortAlgo::quickSort(int* data, int const len) { int const lenD = len; int pivot = 0; int ind = lenD/2; int i,j = 0,k = 0; if(lenD>1){ int* L = new int[lenD]; int* R = new int[lenD]; pivot = data[ind]; for(i=0;i<lenD;i++){ if(i!=ind){ if(data[i]<pivot){ L[j] = data[i]; j++; } else{ R[k] = data[i]; k++; } } } quickSort(L,j); quickSort(R,k); for(int cnt=0;cnt<lenD;cnt++){ if(cnt<j){ data[cnt] = L[cnt];; } else if(cnt==j){ data[cnt] = pivot; } else{ data[cnt] = R[cnt-(j+1)]; } } } }
2574b58e5cfec44542e7af19f1983d5c309043d2
b5fb48e554741c994805e868d842bc5a78bfa571
/CS223 - Advanced Datat Structures/homework/LMel02/DTList.h
1910df72468fbc4b8d7430ddc725196e8b07de5e
[]
no_license
PoloMelendez/CSUB
0d71c81180b67a3240cd93bbc4cfb4cc14447e35
12b82fe995891ed81aab43d0f982f65ee8d9aa5c
refs/heads/master
2020-02-26T13:28:24.142703
2017-07-06T19:45:47
2017-07-06T19:45:47
62,668,195
1
0
null
null
null
null
UTF-8
C++
false
false
658
h
DTList.h
#ifndef DTLIST_H #define DTLIST_H #include<iostream> #include<iomanip> #include<cassert> #include<cstring> using namespace std; template <class T> class DTList { protected: T * element; int count, cap; private: void shiftRight( int end ); void expand(); T rand(T lb, T ub); public: DTList( int cap = 10 ); ~DTList(); DTList( const DTList<T> & lst); bool empty() const; DTList<T> & insert( const T & itm, int pos); T erase( int pos ); void display() const; T & operator [] ( int k ); template<class C> friend ostream& operator << (ostream& out, const DTList<C>& lst ); int size()const; int capacity()const; }; #endif
59d8d008006ac1dc3066510e8db00095278be77b
06e26b3c3968febaa90d039d357a0768ed7caa3d
/Day06_20190828/Day06_20190828/Monster.cpp
17f601dc393a09b507133739d6f4891bc9e1bb90
[]
no_license
choiwsx/STLProgramingPratice
c8071eabf351ee2358c32387d46d1f6e589a0b80
ad65ec86d59f30bd5a6a10ee1ae40d5564505dff
refs/heads/master
2020-07-06T17:46:35.496022
2019-08-28T07:04:44
2019-08-28T07:04:44
203,094,809
0
1
null
null
null
null
UTF-8
C++
false
false
316
cpp
Monster.cpp
#include "Monster.h" #include <iostream> using namespace std; Monster::Monster() { } Monster::~Monster() { } void Monster::BeginPlay() { cout << " Monster::BeginPlay()" << endl; } void Monster::Tick() { cout << " Monster::Tick()" << endl; } void Monster::Render() { cout << " Monster::Render()" << endl; }
c8cfb870df355210aa40cc0f48a262f97f74a2f8
696ec5c9f43b96304cc85c38f94e3d33e886fa71
/Chapter7/7_3a/7_3a.cpp
cf9b27d2d886797ca6ced033a750843d1959c649
[]
no_license
leeyunhome/tbcpp_review2
2eddce8cccd4818cbea334cd0baffb4f89f63acb
6e9783a5ffa19301b22ca94a7ea3e35977c9e7c7
refs/heads/master
2020-12-12T20:40:42.239865
2020-02-29T13:02:24
2020-02-29T13:02:24
234,224,290
0
0
null
null
null
null
UTF-8
C++
false
false
460
cpp
7_3a.cpp
// 7_3a.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include <vector> using namespace std; //void foo(int (&arr)[5]) void printElements(int arr[]) { cout << arr << endl; } void printElements(const std::vector<int>& myArr) { } int main() { std::vector<int> myArr{ 1,2,3,4,5,6,7 }; int arr[]{ 1,2, 3,4,5 }; cout << arr << endl; printElements(arr); printElements(myArr); return 0; }
bfae07f549d4f37b9074a1eaf1b79b0952c7f465
17711096359106c13da5875153eccc308b765003
/cython_tassl_wrap/cpp_linux/test_native.cpp
7076573179bd6ad27b78a394987903d977314df7
[ "MIT", "Python-2.0" ]
permissive
FISCO-BCOS/python-sdk
625ae9e6d601237c5a4684e0fe94629dfa6fd9c1
5fa6cc416b604de4bbd0d2407f36ed286d67a792
refs/heads/master
2023-07-25T22:35:37.472322
2023-07-13T10:04:56
2023-07-13T10:04:56
194,997,013
68
71
MIT
2023-03-08T07:53:04
2019-07-03T06:55:05
Python
UTF-8
C++
false
false
3,342
cpp
test_native.cpp
/* This lib is a tls client for FISCO BCOS2.0 (https://github.com/FISCO-BCOS/) This lib is free software: you can redistribute it and/or modify it under the terms of the MIT License as published by the Free Software Foundation. This project is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. @author: kentzhang @date: 2021-03 */ #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include "client_tools.h" #include "string.h" #include "unistd.h" #include "native_tassl_sock_wrap_api_def.h" int main(int argc, char **argv) { void *module; char libname[]="libnative_tassl_sock_wrap.so"; module = dlopen (libname, RTLD_LAZY); if (!module) { fprintf (stderr, "%s ", dlerror()); exit(1); } FN_ssock_create pfn_create=(FN_ssock_create)dlsym(module, "ssock_create"); FN_ssock_release pfn_release = (FN_ssock_release)dlsym(module, "ssock_release"); FN_ssock_init pfn_init = (FN_ssock_init)dlsym(module, "ssock_init"); FN_ssock_finish pfn_finish = (FN_ssock_finish)dlsym(module, "ssock_finish"); FN_ssock_try_connect pfn_try_connect= (FN_ssock_try_connect)dlsym(module, "ssock_try_connect"); FN_ssock_set_echo_mode pfn_set_echo_mode = (FN_ssock_set_echo_mode)dlsym(module, "ssock_set_echo_mode"); FN_ssock_recv pfn_recv = (FN_ssock_recv)dlsym(module, "ssock_recv"); FN_ssock_send pfn_send = (FN_ssock_send)dlsym(module, "ssock_send"); bool b_fn_ok = true; if(pfn_create==NULL){printf("pf_create is NULL\n");b_fn_ok=false;} if(pfn_release==NULL){printf("pfn_release is NULL\n");b_fn_ok=false;} if(pfn_init==NULL){printf("FN_ssock_init is NULL\n");b_fn_ok=false;} if(pfn_finish==NULL){printf("pfn_finish is NULL\n");b_fn_ok=false;} if(pfn_try_connect==NULL){printf("pfn_try_connect is NULL\n");b_fn_ok=false;} if(pfn_set_echo_mode==NULL){printf("pfn_set_echo_mode is NULL\n");b_fn_ok=false;} if(pfn_recv==NULL){printf("pfn_recv is NULL\n");b_fn_ok=false;} if(pfn_send==NULL){printf("pfn_send is NULL\n");b_fn_ok=false;} if(!b_fn_ok){ printf("load function error\n"); dlclose (module); exit(-1); } void * p_ssock=pfn_create(); printf("dll create return %d\n",p_ssock); int retval = 0; pfn_set_echo_mode(p_ssock, ECHO_PRINTF); pfn_init(p_ssock,"sdk/gmca.crt","sdk/gmsdk.crt","sdk/gmsdk.key","sdk/gmensdk.crt","sdk/gmensdk.key"); printf("ssock init ret %d\n",retval); char ip[1024]="127.0.0.1"; int port = 20200; load_host_port(ip,&port); printf("after load : %s: %d\n",ip,port); retval = pfn_try_connect(p_ssock,ip,port); printf("connect %s,%d,ret %d\n",ip,port,retval); char reqtext[1024] = "{\"jsonrpc\":\"2.0\",\"method\":\"getClientVersion\",\"params\":[],\"id\":1}"; char channelpack[10000]="\0"; int packlen = make_channel_pack(reqtext,strlen(reqtext),channelpack); retval = pfn_send(p_ssock,channelpack,packlen); printf("write socket %d\n",retval); char buff[1024*100]="\0"; for (int i=0;i<10;i++) { retval = pfn_recv(p_ssock,buff,sizeof(buff)); printf("!after recv ret len: %d\n",retval); if (retval >42) { char data[4096]="\0"; strncpy(data,buff+42,retval-42); printf("server return :%s\n",data); break; } sleep(1); } pfn_finish(p_ssock); dlclose (module); }
af45bb44f03a0c615e65958865862f0375e965ce
e7c48ae8678de798e8b10765c76f6c6b9282dd8b
/src/SideMoveList.h
11cd07312e90d8769dbddb09821d6cefc84c1519
[ "Apache-2.0" ]
permissive
dss-bridge/newdss
7a4e9464ca3540721cbbaa4732edb136ba182cee
5698e1bd7314bf910472f8e25fc2dac710543236
refs/heads/master
2020-12-12T23:16:59.873110
2016-07-07T21:04:42
2016-07-07T21:04:42
48,687,247
0
0
null
null
null
null
UTF-8
C++
false
false
2,159
h
SideMoveList.h
/* SDS, a bridge single-suit double-dummy quick-trick solver. Copyright (C) 2015-16 by Soren Hein. See LICENSE and README. */ #ifndef SDS_SIDEMOVELIST_H #define SDS_SIDEMOVELIST_H #include <string> #include <vector> #include "Header.h" #include "Holding.h" #include "DefList.h" #include "Hash.h" #include "summary.h" #include "const.h" #define SIDEMOVE_CHUNK_SIZE 1000 class SideMoveList { private: struct ListEntry { unsigned no; ListEntry * next; }; struct MoveData { DefList def; Header header; unsigned suitLengthExample; unsigned counterExample; }; std::vector<MoveData> list; std::vector<unsigned> moveCount; unsigned listLength; ListEntry * index[ML_MAXKEY]; unsigned indexCount[ML_MAXKEY]; Hash hash; unsigned numEntries; unsigned histD[SDS_MAX_DEF]; unsigned histAsum[SDS_MAX_DEF * SDS_MAX_ALT]; void Extend(); void PrintMoveStats( std::ostream& out, SideSummaryType& ssumm) const; void PrintHashStats( std::ostream& out, SideSummaryType& ssumm) const; void PrintList( std::ostream& out, const unsigned hist[], const unsigned l, const char text[]) const; public: SideMoveList(); ~SideMoveList(); unsigned AddMove( DefList& def, const Holding& holding, bool& newFlag, unsigned& hashKey); unsigned GetMaxRank( const unsigned no); unsigned GetSymmTricks( const unsigned no) const; void GetAD( const unsigned no, unsigned& dno, unsigned& ano); DefList& GetMove( const unsigned no); void Print( const unsigned no) const; void PrintMove( std::ostream& out, const unsigned no); void PrintMovesByOrder( std::ostream& out = std::cout); void PrintMoveListByKeys( std::ostream& out = std::cout); void PrintMoveListByCount( std::ostream& out = std::cout); void PrintLists( std::ostream& out, SideSummaryType& ssumm) const; void PrintStats( std::ostream& out) const; }; #endif
f87bd87a53224f1284fbef6a4172fc64d9aa79bd
7f4b30fe162e0c57a15529c122c6d1d7c1f06ffe
/initial/arduino/controller_logicBoardv4/controller_logicBoardv4.ino
71405a41abdb3f39611cc849ae9163bb41957bab
[]
no_license
seeimadeit/z80
28527f1b7de70a8e2bc22276e6daef887ee405e8
dac95e80031555b74bf8e913c6aed3330becf38a
refs/heads/main
2023-02-16T07:57:18.210773
2021-01-08T20:40:45
2021-01-08T20:40:45
312,393,569
0
0
null
null
null
null
UTF-8
C++
false
false
6,476
ino
controller_logicBoardv4.ino
#define SERIAL_TX_BUFFER_SIZE 2 #define SERIALPORT 1 #define VERSION "\nSerialPort Ready v0.0.0,Device id 0x01" // IO device port 0x01 uint8_t character = 0; // character to send int characterpause = 0; #define keypressdelay 100 int xcontrol = 1; // xon=char(19), xoff=char(17). xcontrol=1 = enabled #define DELAY 10 // CLK,WAIT arduino pins used #define RESETZ80 8 #define WAIT 13 #define RFSH 12 #define HASPOWER 11 #define IOREQ 42 // not used I hope #define M1 4 #define IOREAD 2 #define INT 5 #define D0 22 #define D1 23 #define D2 24 #define D3 25 #define D4 26 #define D5 27 #define D6 28 #define D7 29 #define ACTIVE 40 // comes from GAL ATF16V8 (ACTIVE LOW) #define DEBUG #ifdef DEBUG #define DWRITE(c) Serial.println(c) #else #define DWRITE(c) #endif void setup() { // put your setup code here, to run once: setMode(INPUT); #ifdef DEBUG Serial.begin(115200); while (!Serial) ; DWRITE(VERSION); #endif pinMode(HASPOWER, INPUT); pinMode(INT, OUTPUT); digitalWrite(INT, HIGH); pinMode(IOREQ, INPUT); pinMode(M1, INPUT); pinMode(IOREAD, INPUT); pinMode(ACTIVE, INPUT); pinMode(RFSH, INPUT); digitalWrite(WAIT, HIGH); DoRead(INPUT); DWRITE("Time setup complete"); // reset the z80 pinMode(RESETZ80, OUTPUT); digitalWrite(RESETZ80, LOW); for (int i = 0; i < 20; i++) delay(2); digitalWrite(RESETZ80, HIGH); pinMode(RESETZ80, INPUT); DWRITE("Reset complete"); } void setMode(uint8_t mode) { //pinMode(CLK, mode); pinMode(WAIT, mode); } /* change the direction of IO pins for reading or writing */ void DoRead(uint8_t mode) { pinMode(D0, mode); pinMode(D1, mode); pinMode(D2, mode); pinMode(D3, mode); pinMode(D4, mode); pinMode(D5, mode); pinMode(D6, mode); pinMode(D7, mode); } /* write to the databus */ void write(uint8_t c) { DoRead(OUTPUT); //DWRITE("busWrite"); DWRITE(c); for (int i = 0; i < 8; i++) { digitalWrite(D7 - i, (c >> 7)); //DWRITE((c >> 7)); c = c << 1; } } void readchannel( uint8_t *_c) { // problem with compiler not setting variables. so needed to create // local variables here. argggg uint8_t c = 0; uint8_t d = 0; DoRead(INPUT); c = (c << 1) | digitalRead(D7); c = (c << 1) | digitalRead(D6); c = (c << 1) | digitalRead(D5); c = (c << 1) | digitalRead(D4); c = (c << 1) | digitalRead(D3); c = (c << 1) | digitalRead(D2); c = (c << 1) | digitalRead(D1); c = (c << 1) | digitalRead(D0); *_c = c; } uint8_t c = 0; void handleioacknowledge() { /* Serial.print("ioreq="); Serial.print(ioreq); Serial.print(",Active="); Serial.print(digitalRead(ACTIVE)); Serial.print(",M1="); Serial.println(m1); */ digitalWrite(INT, HIGH); if (character != 0 ) { // this is for interrupt mode 1 or mode 2 write(2); // vector for mode 2, note this code will also work with mode 1 // test ioreq pin if (digitalRead(IOREQ) == HIGH) { Serial.print("ooops"); } int ccc = 0; /* digitalWrite(WAIT, LOW); // may need a pause // while (digitalRead(ACTIVE) == LOW); // wait for the low state to change while (digitalRead(IOREQ) == LOW) ccc++; // wait for the low state to change digitalWrite(WAIT, HIGH); */ // this is working for the interrupts, the refresh happens after the z80 has accepted the data byte digitalWrite(WAIT, LOW); // may need a pause digitalWrite(WAIT, HIGH); while (digitalRead(RFSH) == LOW) ; // wait for the low state to change DoRead(INPUT); //Serial.println(ccc); } else { Serial.print("hey whats going on"); write(2); // vector for mode 2, note this code will also work with mode 1 digitalWrite(WAIT, LOW); // may need a pause while (digitalRead(IOREQ) == LOW); // wait for the low state to change DoRead(INPUT); digitalWrite(WAIT, HIGH); // while (digitalRead(RFSH)==LOW); // extra 1 for testing } //digitalWrite(WAIT, HIGH); } void handleiorequest() { // only process when active = low bool IsRead = digitalRead(IOREAD); if (!IsRead) { readchannel(&c); if (c == 19) xcontrol = 0; // xoff - disable sending keystrokes - allow processor time to process if (c == 17) xcontrol = 1; // xon - enable sending keystrokes again - keyboard if (c == 0) { Serial.println("zero"); } else { Serial.print((char)c); } // may need a pause while (digitalRead(ACTIVE) == LOW) { digitalWrite(WAIT, LOW); // wait for the low state to change // Serial.print('P'); } digitalWrite(WAIT, HIGH); } else {// !isread if (character == 0) character = '+'; write(character); character = 0; //Serial.print("X"); /* digitalWrite(WAIT, LOW); // may need a pause //while (digitalRead(ACTIVE) == LOW) ; // wait for the low state to change while (digitalRead(IOREQ) == LOW) ; // wait for the low state to change digitalWrite(WAIT, HIGH); */ //delay(1000); while (digitalRead(ACTIVE) == LOW) { digitalWrite(WAIT, LOW) ; // wait for the low state to change // Serial.print('*'); } DoRead(INPUT); digitalWrite(WAIT, HIGH); } } void loop() { //digitalWrite(WAIT, LOW); int ioreq = digitalRead(IOREQ); int m1 = digitalRead(M1); if (ioreq == LOW && m1 == LOW) { handleioacknowledge(); } else { int active = digitalRead(ACTIVE); if (active == LOW) { handleiorequest(); } else { // if active low } // xon/xoff flow control } // intack //if (xcontrol == 1) { if (character == 0 && Serial.available()) { // discovered the z80 will just allow interrupts after interrupts therefore not allowing // the processor time to deal with the data. so we will not send keys without a pause between // each character. characterpause++; if (characterpause > keypressdelay) { characterpause = 0; character = Serial.read(); // Serial.print("N"); digitalWrite(INT, LOW); // hold it low until we get a response. } } //} // change the current mode; setMode(digitalRead(HASPOWER)); } // void loop
f1523e20ce10b188158f3d4889e7184a7f395cb0
15e79f904954c6456eebfad1eb109a3c29d61c5a
/src/test/libDynamicClassLoader/src/AudioProcessor.cpp
706b6e7cbc78a253b8e505cd7fa20f31139e63db
[]
no_license
Darksider7/terkos
e8ded3f2f45e7132c2f74a1936b6879bce92f668
593ad04a31fd09c10776337c847e9a171212e80d
refs/heads/master
2016-09-06T11:51:53.588709
2013-01-21T06:58:31
2013-01-21T06:58:31
37,706,130
0
0
null
null
null
null
UTF-8
C++
false
false
2,341
cpp
AudioProcessor.cpp
// // This file is part of Terk and TerkOS. // // All Terk and TerkOS source code is provided under the terms of the // GNU General Public License v2 (http://www.gnu.org/licenses/gpl-2.0.html). // Those wishing to use Terk and TerkOS source code, software and/or // technologies under different licensing terms should contact us at // telepresencerobotkit@cs.cmu.edu. Such licensing terms are available for // all portions of the Terk and TerkOS codebase presented here. // #include <iostream> #include <DynamicLibrary.h> #include <DynamicLoader.h> #include "Filter.h" using namespace std; int main(int argc, char** argv) { string filter1ClassName = "HighPassFilter"; string filter2ClassName = "LowPassFilter"; string filter1LibraryName = "lib" + filter1ClassName + ".so"; string filter2LibraryName = "lib" + filter2ClassName + ".so"; // Load the dynamic library with the high-pass filter class DynamicLibrary* dynLibrary1 = DynamicLoader::loadObjectFile(filter1LibraryName.c_str(), RTLD_NOW); if (dynLibrary1 == NULL) { cerr << "Couldn't load dynamic library 1." << endl; return -1; } // Load a HighPassFilter object Filter* filter1 = dynamic_cast<Filter*> (dynLibrary1->newObject(filter1ClassName.c_str(), 0, NULL)); if (filter1 == NULL) { cerr << "Couldn't create filter object 1." << endl; return -1; } // Load the dynamic library with the low-pass filter class DynamicLibrary* dynLibrary2 = DynamicLoader::loadObjectFile(filter2LibraryName.c_str(), RTLD_NOW); if (dynLibrary2 == NULL) { cerr << "Couldn't load dynamic library 2." << endl; return -1; } // Load a LowPassFilter object Filter* filter2 = dynamic_cast<Filter*> (dynLibrary2->newObject(filter2ClassName.c_str(), 0, NULL)); if (filter2 == NULL) { cerr << "Couldn't create filter object 2." << endl; return -1; } // A buffer for storing audio int bufLen; unsigned char* buffer; filter1->processAudio(bufLen, buffer); filter2->processAudio(bufLen, buffer); // Get rid of the filter objects filter1->deleteSelf(); filter1 = NULL; filter2->deleteSelf(); filter2 = NULL; // Close the dynamic libraries delete dynLibrary1; delete dynLibrary2; // Exit the program return 0; }
4dbbf8eb3403c4c5ade0bf5c73743502c610e72c
be4952850ad6a8b0abe50de671c495c6add9fae7
/codeforce/CF_1004A.cpp
a13d9afe27230f685b524547940ba351e9908be5
[]
no_license
ss5ssmi/OJ
296cb936ecf7ef292e91f24178c9c08bd2d241b5
267184cef5f1bc1f222950a71fe705bbc5f0bb3e
refs/heads/master
2022-10-29T18:15:14.290028
2022-10-12T04:42:47
2022-10-12T04:42:47
103,818,651
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
CF_1004A.cpp
#include<bits/stdc++.h> using namespace std; int main(){ int n,d,s[100],t=2; cin>>n>>d; for(int i=0;i<n;i++){ cin>>s[i]; } for(int i=0;i<n-1;i++){ if((s[i+1]-s[i]) > 2*d){ t+=2; }else if((s[i+1]-s[i]) == 2*d){ t++; } } printf("%d\n",t); return 0; }
a92ce7fa8a54436cbe6a2993a9ca2137949aab20
9fe4996abce476cfe5501a10c52d9793bb7f8682
/Template/李进/我的代码/数学/基础乘幂_因数分解/快速幂.cpp
0d5be69505d7e047996dbb2addc74e54e875d642
[]
no_license
dhs347/Dream
e63c6322fef124676e0389830e4ce5ab4d4bdf21
7825e0f082f6538989202490abb9cd1dd95163e5
refs/heads/master
2020-08-01T21:25:44.942688
2019-09-26T13:59:11
2019-09-26T13:59:11
211,120,816
12
1
null
null
null
null
UTF-8
C++
false
false
161
cpp
快速幂.cpp
inline ll QM(ll a, ll n, const ll & p) { ll ans = 1; for (ll tmp = a; n; n >>= 1) { if (n & 1) ans = ans * tmp % p; tmp = tmp * tmp % p; } return ans; }
32683dddfc5df8dd24a75092300528c9254f58fb
b1df1b955a0554da1d21ceeea57fb0f2fbb36a2e
/Spelprojekt/Spelprojekt/RenderTarget.cpp
2215539def141fb8f67b7ab4cc81a5709ef2cac7
[]
no_license
maze516/Game-Of-Cones
75a163fa2ec28192e2aafd85b6db075b52f8304b
bdfe84499ee2476b212a895ed17af416dc9ea582
refs/heads/main
2023-06-09T09:11:54.466092
2021-06-27T22:32:58
2021-06-27T22:32:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,456
cpp
RenderTarget.cpp
#include "RenderTarget.h" #include <iostream> RenderTarget::RenderTarget(ID3D11RenderTargetView* rtv, ID3D11ShaderResourceView* srv, ID3D11DepthStencilView* dsv, D3D11_VIEWPORT viewport) : bufferCount(1), viewport(viewport), dss(nullptr) { this->rtv = new ID3D11RenderTargetView * [1]{ rtv }; this->srv = new ID3D11ShaderResourceView * [1]{ srv }; this->dsv = dsv; this->bufferCount = 1; } RenderTarget::RenderTarget(size_t bufferCount, size_t width, size_t height, bool createDepthBuffer) : bufferCount(bufferCount), width(width), height(height), createDepthBuffer(createDepthBuffer), dss(nullptr) { } RenderTarget::~RenderTarget() { Cleanup(); } void RenderTarget::Initalize(ID3D11Device* device) { rtv = new ID3D11RenderTargetView * [bufferCount]; srv = new ID3D11ShaderResourceView * [bufferCount]; HRESULT hr; /* VIEWPORT */ ZeroMemory(&viewport, sizeof(D3D11_VIEWPORT)); viewport.TopLeftX = 0.0f; viewport.TopLeftY = 0.0f; viewport.Width = static_cast<float>(width); viewport.Height = static_cast<float>(height); viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; if (this->createDepthBuffer) { D3D11_DEPTH_STENCIL_DESC depthStencilStateDsc; ZeroMemory(&depthStencilStateDsc, sizeof(D3D11_DEPTH_STENCIL_DESC)); depthStencilStateDsc.DepthEnable = true; depthStencilStateDsc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilStateDsc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; depthStencilStateDsc.StencilEnable = false; depthStencilStateDsc.StencilReadMask = 0xFF; depthStencilStateDsc.StencilWriteMask = 0xFF; // Stencil operations if pixel is front-facing.s depthStencilStateDsc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDsc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDsc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR; depthStencilStateDsc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. depthStencilStateDsc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDsc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilStateDsc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; depthStencilStateDsc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; HRESULT createDepthStencilResult = device->CreateDepthStencilState(&depthStencilStateDsc, &dss); assert(SUCCEEDED(createDepthStencilResult)); ID3D11Texture2D* depthTextureDX11; ZeroMemory(&depthTextureDX11, sizeof(ID3D11Texture2D)); // DEPTH TEXTURE D3D11_TEXTURE2D_DESC depthTextureDescription; ZeroMemory(&depthTextureDescription, sizeof(D3D11_TEXTURE2D_DESC)); depthTextureDescription.Width = width; depthTextureDescription.Height = height; depthTextureDescription.MipLevels = 1; depthTextureDescription.ArraySize = 1; depthTextureDescription.SampleDesc.Count = 1; depthTextureDescription.SampleDesc.Quality = 0; depthTextureDescription.Format = DXGI_FORMAT_R24G8_TYPELESS; //DXGI_FORMAT_R32_TYPELESS;//DXGI_FORMAT_D24_UNORM_S8_UINT; // DXGI_FORMAT_R32G32B32A32_UINT; // DXGI_FORMAT_R24G8_TYPELESS; //DXGI_FORMAT_R32G32B32A32_FLOAT; // DXGI_FORMAT_D32_FLOAT; // DXGI_FORMAT_R24_UNORM_X8_TYPELESS; depthTextureDescription.Usage = D3D11_USAGE_DEFAULT; depthTextureDescription.BindFlags = D3D11_BIND_DEPTH_STENCIL | D3D11_BIND_SHADER_RESOURCE; depthTextureDescription.CPUAccessFlags = 0; depthTextureDescription.MiscFlags = 0; HRESULT textureResult = device->CreateTexture2D(&depthTextureDescription, 0, &depthTextureDX11); assert(SUCCEEDED(textureResult)); // DEPTH STENCIL VIEW D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilDescription; ZeroMemory(&depthStencilDescription, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC)); depthStencilDescription.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; //DXGI_FORMAT_D32_FLOAT;//DXGI_FORMAT_D24_UNORM_S8_UINT; // DXGI_FORMAT_D32_FLOAT;//DXGI_FORMAT_D24_UNORM_S8_UINT; // DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDescription.Flags = 0; depthStencilDescription.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; depthStencilDescription.Texture2D.MipSlice = 0; // SHADER RESOURCE D3D11_SHADER_RESOURCE_VIEW_DESC shaderResourceDescription; ZeroMemory(&shaderResourceDescription, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC)); shaderResourceDescription.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; ///DXGI_FORMAT_R24_UNORM_X8_TYPELESS; // DXGI_FORMAT_R32_UINT;//depthTexDesc.Format;//DXGI_FORMAT_R32G32B32A32_FLOAT;// DXGI_FORMAT_R24_UNORM_X8_TYPELESS; shaderResourceDescription.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; //shaderResourceDescription.Texture2D.MostDetailedMip = 0; shaderResourceDescription.Texture2D.MipLevels = 1; HRESULT depthStencilResult = device->CreateDepthStencilView(depthTextureDX11, &depthStencilDescription, &dsv); assert(SUCCEEDED(depthStencilResult)); HRESULT shaderResourceView = device->CreateShaderResourceView(depthTextureDX11, &shaderResourceDescription, &depth_srv); } /* RENDER TEXTURES */ ID3D11Texture2D** targetTextures = new ID3D11Texture2D * [bufferCount]; D3D11_TEXTURE2D_DESC textureDesc; ZeroMemory(&textureDesc, sizeof(textureDesc)); textureDesc.Width = width; textureDesc.Height = height; textureDesc.MipLevels = 1; textureDesc.ArraySize = 1; textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = 0; for (size_t i = 0; i < bufferCount; i++) { hr = device->CreateTexture2D(&textureDesc, nullptr, &targetTextures[i]); assert(SUCCEEDED(hr)); } /* RENDER TARGET VIEWS */ D3D11_RENDER_TARGET_VIEW_DESC rtvDesc; ZeroMemory(&rtvDesc, sizeof(rtvDesc)); rtvDesc.Format = textureDesc.Format; rtvDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtvDesc.Texture2D.MipSlice = 0; // Create the render target views. for (size_t i = 0; i < bufferCount; i++) { rtvDesc.Texture2DArray.FirstArraySlice = i; hr = device->CreateRenderTargetView(targetTextures[i], &rtvDesc, &rtv[i]); assert(SUCCEEDED(hr)); } /* SHADER RESOURCE VIEWS */ D3D11_SHADER_RESOURCE_VIEW_DESC shrDesc; ZeroMemory(&shrDesc, sizeof(shrDesc)); shrDesc.Format = textureDesc.Format; shrDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; shrDesc.Texture2D.MostDetailedMip = 0; shrDesc.Texture2D.MipLevels = 1; // Create the shader resource views. for (size_t i = 0; i < bufferCount; i++) { hr = device->CreateShaderResourceView(targetTextures[i], &shrDesc, &srv[i]); assert(SUCCEEDED(hr)); } for (size_t i = 0; i < bufferCount; i++) { if (targetTextures[i]) { targetTextures[i]->Release(); targetTextures[i] = 0; } } delete[] targetTextures; } void RenderTarget::Bind(ID3D11DeviceContext* context) { for (size_t i = 0; i < bufferCount; i++) context->PSSetShaderResources(i, 1, &srv[i]); } void RenderTarget::Unbind(ID3D11DeviceContext* context) { for (size_t i = 0; i < bufferCount; i++) { ID3D11ShaderResourceView* nullSRV[1] = { nullptr }; context->PSSetShaderResources(i, 1, nullSRV); } } void RenderTarget::Cleanup() { for (size_t i = 0; i < bufferCount; i++) { if (srv[i]) { srv[i]->Release(); srv[i] = 0; } if (rtv[i]) { rtv[i]->Release(); rtv[i] = 0; } } delete dsv; delete dss; delete[] srv; delete[] rtv; }
756d3b549e1a0be0be653c0245892ca153bb798b
58496be10ead81e2531e995f7d66017ffdfc6897
/Sources/Common/IVarMapImpl.cpp
46cf9ed0a6cc1747c1f273e665ea5d92462bcdf7
[]
no_license
Diego160289/cross-fw
ba36fc6c3e3402b2fff940342315596e0365d9dd
532286667b0fd05c9b7f990945f42279bac74543
refs/heads/master
2021-01-10T19:23:43.622578
2011-01-09T14:54:12
2011-01-09T14:54:12
38,457,864
0
0
null
null
null
null
UTF-8
C++
false
false
3,476
cpp
IVarMapImpl.cpp
//============================================================================ // Date : 22.12.2010 // Author : Tkachenko Dmitry // Copyright : (c) Tkachenko Dmitry (TkachenkoDmitryV@gmail.com) //============================================================================ #include "IVarMapImpl.h" namespace IFacesImpl { IVarMapImpl::IVarMapImpl() { } IVarMapImpl::~IVarMapImpl() { } RetCode IVarMapImpl::AddVariable(IFaces::INamedVariable *namedVar) { Common::ISyncObject Locker(GetSynObj()); try { std::string Name = INamedVariableHelper(INamedVariablePtr(namedVar)).GetName(); for (VarPool::const_iterator i = Vars.begin() ; i != Vars.end() ; ++i) { if (INamedVariableHelper(*i).GetName() == Name) return retFail; } Vars.push_back(INamedVariablePtr(namedVar)); } catch (std::exception &) { return retFail; } return retOk; } RetCode IVarMapImpl::RemoveVariable(const char *varName) { Common::ISyncObject Locker(GetSynObj()); try { for (VarPool::iterator i = Vars.begin() ; i != Vars.end() ; ++i) { if (INamedVariableHelper(*i).GetName() == varName) { Vars.erase(i); return retOk; } } } catch (std::exception &) { return retFail; } return retFail; } RetCode IVarMapImpl::GetVariable(const char *varName, IFaces::IVariant **var) const { Common::ISyncObject Locker(GetSynObj()); try { for (VarPool::const_iterator i = Vars.begin() ; i != Vars.end() ; ++i) { if (INamedVariableHelper(*i).GetName() == varName) return (*i)->Get(var); } } catch (std::exception &) { return retFail; } return retFail; } RetCode IVarMapImpl::EnumVariables(IFaces::IEnum **vars) const { Common::ISyncObject Locker(GetSynObj()); try { Common::RefObjPtr<IEnumImpl> NewEnum = CreateEnum<System::Mutex>(); for (VarPool::const_iterator i = Vars.begin() ; i != Vars.end() ; ++i) NewEnum->AddItem(*i); return NewEnum.QueryInterface(vars); } catch (std::exception &) { return retFail; } return retOk; } IVarMapHelper::IVarMapHelper(IVarMapPtr varMap) : VarMap(varMap) { if (!VarMap.Get()) throw IVarMapHelperException("Empty varmap ptr"); } void IVarMapHelper::AddVariable(Common::RefObjPtr<IFaces::INamedVariable> namedVar) { if (VarMap->AddVariable(namedVar.Get()) != retOk) throw IVarMapHelperException("Can't add variable"); } void IVarMapHelper::RemoveVariable(const std::string &varName) { if (VarMap->RemoveVariable(varName.c_str()) != retOk) throw IVarMapHelperException("Can't remove variable"); } const IVariantHelper IVarMapHelper::GetVariable(const std::string &varName) const { Common::RefObjPtr<IFaces::IVariant> Var; if (VarMap->GetVariable(varName.c_str(), Var.GetPPtr()) != retOk) throw IVarMapHelperException("Can't get variable"); return Var; } const IEnumHelper IVarMapHelper::EnumVariables() const { Common::RefObjPtr<IFaces::IEnum> Enum; if (VarMap->EnumVariables(Enum.GetPPtr()) != retOk) throw IVarMapHelperException("Can't get variable"); return Enum; } }
0e7629cabccde6beff7e7d73420c5f780014f67d
dd1b4089f638d801698e34b830b2767149b665f6
/R3BRoot_Source/tcal/R3BTCalEngine.h
183533a322da650154d436430ebb59110dcb1443
[]
no_license
ChristiaanAlwin/NeuLAND_Veto
d1c1b41cfb1f4ade2de664188da615b2541d3e7b
ed06682b03b1bd6b2c7ecc2f3be7c62036ef45ee
refs/heads/master
2021-01-05T19:02:08.598882
2020-02-17T13:55:17
2020-02-17T13:55:17
241,109,623
2
0
null
null
null
null
UTF-8
C++
false
false
4,298
h
R3BTCalEngine.h
#ifndef _R3BTCAL_ENGINE_ #define _R3BTCAL_ENGINE_ #define MAX_TACQUILA_SAM 7 // 0 .. 7 #define MAX_TACQUILA_GTB 1 // 0 and 1 #define MAX_TACQUILA_MODULE 20 // 0 .. 20 #define TACQUILA_NUM_GEOM ((MAX_TACQUILA_SAM + 1) * (MAX_TACQUILA_GTB + 1) * (MAX_TACQUILA_MODULE + 1)) #define TACQUILA_CLOCK_MHZ 40.002903 #define VFTX_CLOCK_MHZ 200 #include "R3BTCalPar.h" #include "TObject.h" class TH1F; /** * Class with implementation of TCAL time calibration. * Currently supported electronics: Tacquila and VFTX. * Clock frequency is set as a constant in MHz and the * clock cycle in ns is calculated from it. * Recommended value of minimum statistics per module is * 10000 entries. * @author D. Kresan * @since September 4, 2015 */ class R3BTCalEngine : public TObject { public: /** * Standard constructor. * Creates instance of TCAL engine. To be used in * analysis task for specific detector. * @param param a pointer to parameter container. * @param nModules a number of detector modules. * @param minStats a minimum number of entries per module. */ R3BTCalEngine(R3BTCalPar* param, Int_t minStats = 10000); /** * Destructor. * Releases memory used by the object. */ virtual ~R3BTCalEngine(); /** * A method to fill TDC distribution for a specific module. * To be called from event loop of an analysis task. * @param iModule an index of a module. * @param tdc a raw TDC value. */ void Fill(Int_t plane, Int_t paddle, Int_t side, Int_t tdc); /** * A method to calculate calibration parameters for Tacquila * electronics. Parameters will be automatically stored. * To be called from FinishTask() method of an analysis task. */ void CalculateParamTacquila(); /** * A method to calculate calibration parameters for VFTX * electronics. Parameters will be automatically stored. * To be called from FinishTask() method of an analysis task. */ void CalculateParamVFTX(); protected: /** * A method to determine the range of a TDC distribution. * @param h1 a pointer to the histogram with data. * @param ic output: center of distribution. * @param iMin output: lower bound. * @param iMax output: upper bound. */ void FindRange(TH1F* h1, Int_t& ic, Int_t& iMin, Int_t& iMax); /** * A method to interpolate a section of the raw TDC distribution * starting from the middle towards the lower bound. * @param h1 a pointer to the histogram with data. * @param iMin a lower bound. * @param iMax an upper bound. * @param il an initial value and output of a lower bound of the section. * @param ih an initial value and output of an upper bound of the section. * @param slope output: a slope of linear interpolation. * @param offset output: an offset of linear interpolation (value at il). */ void LinearUp(TH1F* h1, Int_t iMin, Int_t iMax, Int_t& il, Int_t& ih, Double_t& slope, Double_t& offset); /** * A method to interpolate a section of the raw TDC distribution * starting from the middle towards the upper bound. * @param h1 a pointer to the histogram with data. * @param iMin a lower bound. * @param iMax an upper bound. * @param il an initial value and output of a lower bound of the section. * @param ih an initial value and output of an upper bound of the section. * @param slope output: a slope of linear interpolation. * @param offset output: an offset of linear interpolation (value at il). */ void LinearDown(TH1F* h1, Int_t iMin, Int_t iMax, Int_t& il, Int_t& ih, Double_t& slope, Double_t& offset); private: Int_t fMinStats; /**< Minimum number of entries in raw TDC distribution per module */ TH1F* fhData[N_PLANE_MAX][N_PADDLE_MAX][N_SIDE_MAX]; /**< An array of histograms to store raw TDC distributions. */ TH1F* fhTime[N_PLANE_MAX][N_PADDLE_MAX] [N_SIDE_MAX]; /**< An array of histograms to store unparametrized bin-by-bin calibration. */ R3BTCalPar* fCal_Par; /**< A pointer to the parameter container. */ Double_t fClockFreq; /**< A clock cycle in [ns]. */ public: ClassDef(R3BTCalEngine, 1) }; #endif
9a247ceb6c5de8b09ba87ae50d4aa5169f6510e0
012f0800c635f23d069f0c400768bc58cc1a0574
/hhvm/hhvm-3.17/hphp/runtime/ext/xdebug/php5_xdebug/xdebug_str.cpp
04681e20a4822bbf855ec7923409e5583e5b9320
[ "Zend-2.0", "BSD-3-Clause", "PHP-3.01" ]
permissive
chrispcx/es-hhvm
c127840387ee17789840ea788e308b711d3986a1
220fd9627b1b168271112d33747a233a91e8a268
refs/heads/master
2021-01-11T18:13:42.713724
2017-02-07T02:02:10
2017-02-07T02:02:10
79,519,670
5
0
null
null
null
null
UTF-8
C++
false
false
2,160
cpp
xdebug_str.cpp
/* +----------------------------------------------------------------------+ | Xdebug | +----------------------------------------------------------------------+ | Copyright (c) 2002-2013 Derick Rethans | +----------------------------------------------------------------------+ | This source file is subject to version 1.0 of the Xdebug license, | | that is bundled with this package in the file LICENSE, and is | | available at through the world-wide-web at | | http://xdebug.derickrethans.nl/license.php | | If you did not receive a copy of the Xdebug license and are unable | | to obtain it through the world-wide-web, please send a note to | | xdebug@derickrethans.nl so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Derick Rethans <derick@xdebug.org> | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/xdebug/php5_xdebug/xdebug_str.h" #include "hphp/runtime/base/memory-manager.h" #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <locale.h> char* xdebug_sprintf(const char* fmt, ...) { int size = 1; va_list args; auto const orig_locale = setlocale(LC_ALL, nullptr); setlocale(LC_ALL, "C"); SCOPE_EXIT { setlocale(LC_ALL, orig_locale); }; auto new_str = (char*)HPHP::req::malloc_noptrs(size); for (;;) { va_start(args, fmt); auto const n = vsnprintf(new_str, size, fmt, args); va_end(args); if (n > -1 && n < size) { break; } if (n < 0) { size *= 2; } else { size = n + 1; } new_str = (char*)HPHP::req::realloc_noptrs(new_str, size); } return new_str; } char* xdstrdup(const char* str) { if (str == nullptr) { return nullptr; } auto const size = strlen(str) + 1; auto const dup = (char*)HPHP::req::malloc_noptrs(size); memcpy(dup, str, size); return dup; }