language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#define _POSIX_C_SOURCE 200809L #define _XOPEN_SOURCE 700 #include<stdio.h> #include<unistd.h> #include<time.h> #include<signal.h> #include<stdarg.h> #include<string.h> #include<setjmp.h> #include<sched.h> #define SEC_TO_NANO 1000000000 #define MILLI_TO_NANO 1000000 #define MICRO_TO_NANO 1000 #define MILLI 1000 #define MICRO 1000000 #define NANO 1000000000 int waiting_for_signal; jmp_buf env; /*Function responsible for performing the operation of the sensors*/ void sensor(){ int num; struct timespec ts; ts.tv_sec = 1; ts.tv_nsec = 5000000 ; srand(time(NULL)); num = rand(); if(num % 2 == 0){ nanosleep(&ts, NULL); } } /*Function responsible for executing the control strategy */ void controller(){} /*Function responsible for implementing the control decision*/ void actuate(){} void sense(){int i; for(i =0 ;i <1000000000; i++){printf("%d\n", i);}} void compute(){} void handle_deadline(){printf("deadline overshot");} /* Computes the difference between two timespec values, returns (time1-time2)*/ struct timespec diff_timespec(struct timespec time1, struct timespec time2){ struct timespec result; if((time1.tv_sec < time2.tv_sec) || ((time1.tv_sec == time2.tv_sec) && (time1.tv_nsec <= time2.tv_nsec))){ result.tv_sec = result.tv_nsec = 0; } else{ result.tv_sec = time1.tv_sec - time2.tv_sec; if(time1.tv_nsec < time2.tv_nsec){ result.tv_nsec = time1.tv_nsec + 1000000000 - time2.tv_nsec; result.tv_sec--; } else{ result.tv_nsec = time1.tv_nsec - time2.tv_nsec; } } return(result); } /* Function to add two timespec values*/ struct timespec add_timespec(struct timespec* tt, struct timespec time1, struct timespec time2){ struct timespec result; result.tv_sec = time1.tv_sec + time2.tv_sec; result.tv_nsec = time1.tv_nsec + time2.tv_nsec; if(result.tv_nsec >= NANO){ result.tv_sec++; result.tv_nsec = result.tv_nsec-NANO; } *tt = result; return(result); } /** Compares two timespec value Return Value : time1 < time2 -1 time1 > time2 1 time1 = time2 0 **/ int cmp_timespec(struct timespec time1, struct timespec time2){ if(time1.tv_sec < time2.tv_sec){ return(-1); } else if(time1.tv_sec > time2.tv_sec){ return(1); } else if(time1.tv_nsec < time2.tv_nsec){ return(-1); } else if(time1.tv_nsec > time2.tv_nsec){ return(1); } else return 0; } /* Converts timespec value to user readable long (millisecond) value*/ long convert_timespec_to_ms(struct timespec val){ return(val.tv_sec*1000 + val.tv_nsec/1000000); } /*Converts time from seconds/microseconds/nanoseconds to milliseconds*/ long convert_to_ms(long interval, char* unit){ if(!strcmp(unit, "sec")){ return(interval * 1000); } if(!strcmp(unit, "ms")){ return(interval); } if(!strcmp(unit, "micro")){ return(interval/1000); } if(!strcmp(unit, "ns")){ return(interval/1000000); } } /*Converts user specified interval from long (seconds/milliseonds/microseconds/nanoseconds value to timespec value for computation in C*/ struct timespec convert_to_timespec(struct timespec*tt, long interval, char* unit){ struct timespec temp; if(!strcmp(unit, "sec")){ temp.tv_sec = interval; temp.tv_nsec = 0; } if(!strcmp(unit, "ms")){ temp.tv_sec = interval/MILLI; temp.tv_nsec = (interval % MILLI)*(MILLI_TO_NANO); } if(!strcmp(unit, "micro")){ temp.tv_sec = interval/MICRO; temp.tv_nsec = (interval % MICRO)*(MICRO_TO_NANO); } if(!strcmp(unit, "ns")){ temp.tv_sec = interval/NANO; temp.tv_nsec = (interval % NANO); } *tt = temp; return temp; } int waiting_for_signal; jmp_buf env; void timer_signal_handler(int sig, siginfo_t *extra, void *cruft){ static int count = 0; count++; if(waiting_for_signal == 1){ siglongjmp(env, count); } waiting_for_signal = 0; } void main(){ struct timespec start_time, interval_timespec; long interval; char* unit; int ret_jmp; struct itimerspec i; struct sigaction sa; struct sigevent timer_event; timer_t mytimer; convert_to_timespec(&interval_timespec, 30, "ms"); sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = timer_signal_handler; if(sigaction(SIGRTMIN, &sa, NULL) < 0){ perror("sigaction"); exit(0); } timer_event.sigev_notify = SIGEV_SIGNAL; timer_event.sigev_signo = SIGRTMIN; timer_event.sigev_value.sival_ptr = (void*) &mytimer; if(timer_create(CLOCK_REALTIME, &timer_event, &mytimer) < 0){ perror("timer_create"); exit(0); } (void) clock_gettime(CLOCK_REALTIME, &start_time); add_timespec(&(i.it_value ), start_time, interval_timespec); i.it_interval.tv_sec = 0; i.it_interval.tv_nsec = 0; if(timer_settime(mytimer, TIMER_ABSTIME, &i, NULL) < 0 ){ perror("timer_setitimer"); exit(0); } while(1){ ret_jmp = sigsetjmp(env, 1); waiting_for_signal = 1; if(ret_jmp != 0){ handle_deadline(); goto JMP; } sense(); JMP: clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &i.it_value, NULL); waiting_for_signal = 0; add_timespec(&(i.it_value ), i.it_value, interval_timespec); i.it_interval.tv_sec = 0; i.it_interval.tv_nsec = 0; timer_settime(mytimer, TIMER_ABSTIME, &i, NULL); }}
C
#include <stdio.h> int main(void) { int a = 0x12345678; char *p = (char *)(&a); if (*p == 0x78) { printf("Little-Endian!\n"); } else if (*p == 0x12) { printf("Big-Endian!\n"); } else { printf("other!\n"); } return 0; }
C
/************************************************************************* > File Name: bruteforce.c > Author: gpx > Mail: 1457495424@qq.com > Created Time: 2019年01月01日 星期二 09时46分56秒 ************************************************************************/ #include <stdio.h> #include <stdlib.h> int BruteForce(char *str, char *pattern) { for (int i = 0; str[i]; i++) { int flag = 1; for (int j = 0; pattern[j]; j++) { if (str[i + j] == pattern[j]) continue; flag = 0; break; } if (flag) return i; } return -1; } int main() { char str[100], pattern[30]; while (scanf("%s%s", str, pattern) != EOF) { printf("search %s in %s = %d\n", pattern, str, BruteForce(str, pattern)); } return 0; }
C
#include "uthread.h" #include "types.h" #include "user.h" #define T_A_DEBUG 0 static int k_stat = 0; void thread_do() { int s_i, s_tid; s_tid = uthread_self().tid; for (s_i=0; s_i<k_stat; s_i++) { DEBUG_PRINT(3, "inside thread %d", s_tid); printf(2, "thread %d iteration %d\n", uthread_self().tid, s_i); // printf(2, "priority %d\n", uthread_self().priority); uthread_yield(); } DEBUG_PRINT(3, "thread tid=%d exiting. s_i=%d", uthread_self().tid, s_i); uthread_exit(); } void show_esp() { int esp; STORE_ESP(esp); DEBUG_PRINT(4, "ESP=%x", esp); } int main(int argc, char** argv) { int n; int c; int ret, esp; n = atoi(argv[1]); k_stat = atoi(argv[2]); DEBUG_PRINT(4, "n=%d k=%d", n, k_stat); for (c=0; c < n; c++) { ret = uthread_create(thread_do, (c % 2)); DEBUG_PRINT(4, "creating thread %d. ret=%d", c, ret); } STORE_ESP(esp); DEBUG_PRINT(4, "Before 'uthread_start_all' ESP=%x", esp); show_esp(); DEBUG_PRINT(4, "calling uthread_start_all", 999); uthread_start_all(); STORE_ESP(esp); DEBUG_PRINT(4, "After 'uthread_start_all' ESP=%x", esp); printf(2, "this will not be printed\n"); return 0; }
C
#include <pthread.h> #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { pid_t p1_pid,p2_pid,p3_pid,p4_pid,p5_pid; int pip13[2]; pipe(pip13); char buffer[100]; if ((p1_pid = fork())== 0) { dup2(pip13[1],1); close(pip13[0]); printf("I am P1 and I am proud of it.\n"); } else { close(pip13[1]); if ((p2_pid = fork()) == 0) { printf("I am P2 and want children!\n"); if ((p3_pid = fork()) == 0) { dup2(pip13[0],0); read(pip13[0],buffer,sizeof(buffer)); printf("P3 has received : %s",buffer); // printf("I am P3. I like it.\n"); } else { close(pip13[0]); wait(p1_pid); if ((p4_pid = fork()) == 0) { printf("I am P4. Get used to it.\n"); } else { printf("I am P2 and have two children!\n"); } } } else { close(pip13[0]); close(pip13[1]); printf("I am the parent process, obey or die!\n"); } } }
C
#include <stdio.h> #include <stdbool.h> #include <math.h> #include "geometry.h" bool is_intersect(line_t *l1, line_t *l2) { double cp1 = (l1->p2.x - l1->p1.x) * ((l2->p1.y) - (l1->p1.y)) - ((l1->p2.y - l1->p1.y) * ((l2->p1.x) - (l1->p1.x))); double cp2 = ((l1->p2.x - l1->p1.x) * (l2->p2.y - l1->p1.y)) - ((l1->p2.y - l1->p1.y) * (l2->p2.x - l1->p1.x)); double cp3 = (l2->p2.x - l2->p1.x) * ((l1->p1.y) - (l2->p1.y)) - ((l2->p2.y - l2->p1.y) * ((l1->p1.x) - (l2->p1.x))); double cp4 = ((l2->p2.x - l2->p1.x) * (l1->p2.y - l2->p1.y)) - ((l2->p2.y - l2->p1.y) * (l1->p2.x - l2->p1.x)); //printf("cp1:%f, cp2:%f\n", cp1, cp2); if (cp1 * cp2 < 0 && cp3 * cp4 < 0) { return 1; } if (cp1 * cp2 > 0) { return 0; } if (cp1 * cp2 == 0) { if (is_pt_eq(&l1->p1, &l2->p1) || is_pt_eq(&l1->p1, &l2->p2) || is_pt_eq(&l1->p2, &l2->p1) || is_pt_eq(&l1->p2, &l2->p2)) { return 1; } return 0; } return 0; } void init_line(line_t *l, double x1, double y1, double x2, double y2) { l->p1.x = x1; l->p1.y = y1; l->p2.x = x2; l->p2.y = y2; } bool is_pt_eq(point_t *p1, point_t *p2) { if (p1->x == p2->x && p1->y == p2->y) { return 1; } return 0; } bool is_collide(polygon_t *pol1, polygon_t *pol2) { for (int i = 0; i < pol1->size; i++) { for (int j = 0; j < pol2->size; j++) { //printf("side %d x side %d:\n", i, j); if (is_intersect(&pol1->side[i], &pol2->side[j])) { return 1; } } } return 0; } void init_poly(polygon_t *pol, point_t *point) { for (int i = 0; i < (pol->size) - 1; i++) { init_line(&pol->side[i], point->x, point->y, (point + 1)->x, (point + 1)->y); point++; } init_line(&pol->side[pol->size - 1], point->x, point->y, (point - (pol->size - 1))->x, (point - (pol->size - 1))->y); } double cross(line_t *l, point_t *p) { return ((l->p2.x - l->p1.x) * (l->p1.y - p->y) - (l->p2.y - l->p1.y) * (l->p1.x - p->x)); } bool is_contain(polygon_t *pol1, polygon_t *pol2) { int size[2] = {pol1->size, pol2->size}; double cross_prev = cross(&pol1->side[0], &pol2->side[0].p1); //printf("cross_prev:%lf\n", cross_prev); for (int i = 0; i < size[0]; i++) { for (int j = 0; j < size[1]; j++) { double cros = cross(&pol1->side[i], &pol2->side[j].p1); //printf("side[%d]xside[%d]:%lf\n", i, j, cros); if (cros * cross_prev < 0) { return 0; } cross_prev = cros; } } return 1; } void rot(point_t *p, double theta) { double theta_rad = (theta * 3.14159) / 180.0; double x = p->x; double y = p->y; //printf("theta_rad:%f | p.x:%f | p.y:%f\n",theta_rad, p->x, p->y); p->x = (x * cos(theta_rad) - y * sin(theta_rad)); p->y = (x * sin(theta_rad) + y * cos(theta_rad)); //printf("x:%f|y:%f\n",p->x,p->y); } void trans(point_t *p, double trans_x, double trans_y) { p->x = p->x + trans_x; p->y = p->y + trans_y; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> /* 34. Ler os dados pessoais de um conjunto de candidatas de um concurso de beleza e escrever os nomes daquelas que tm altura maior que 1,70m. Os dados pessoais so: nmero da inscrio, nome completo, altura, peso, naturalidade e estado. O nmero de inscrio igual a -1 indica o fim do conjunto de candidatas. */ struct candidata{ char nome[50], naturalidade[50], estado[50]; int numero_inscricao, peso; float altura; }; int main() { setlocale(LC_ALL,""); struct candidata vet_candidatas[50]; int i=0, cont=0, validacao=0; while(validacao != -1){ printf("\nDigite o nome da candidata: \n"); fflush(stdin); fgets(vet_candidatas[i].nome, 50, stdin); printf("\nDigite a naturalidade da candidata: \n"); fflush(stdin); fgets(vet_candidatas[i].naturalidade, 50, stdin); printf("\nDigite o estado de origem da candidata: \n"); fflush(stdin); fgets(vet_candidatas[i].estado, 50, stdin); printf("\n Numero de Inscricao: \n"); scanf("%d", &vet_candidatas[i].numero_inscricao); printf("\n Peso(kg): \n"); scanf("%d", &vet_candidatas[i].peso); printf("\n Altura: \n"); scanf("%f", &vet_candidatas[i].altura); i++; cont++; printf("\n--------------------------------------------\n"); printf("\n Deseja cadastrar mais uma candidata ? (1 para sim | -1 para nao): \n"); scanf("%d", &validacao); } printf("\n Nomes das candidatas mais altas do que 1,70: \n"); for(i=0;i<cont;i++){ if(vet_candidatas[i].altura > 1.70){ printf("\n %s \n", vet_candidatas[i].nome); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* color_parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mgupta <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/16 05:51:57 by mgupta #+# #+# */ /* Updated: 2020/07/16 05:51:58 by mgupta ### ########.fr */ /* */ /* ************************************************************************** */ #include "../cub3d.h" int create_trgb(int t, int color[], t_game *g) { if (color[0] > 255 || color[1] > 255 || color[2] > 255 || color[0] < 0 || color[1] < 0 || color[2] < 0) printf_error("color range should be between 0 and 255\n", g); return (t << 24 | color[0] << 16 | color[1] << 8 | color[2]); } char *check_comma(char *line, t_game *g) { line = remove_space(line); if (*line != ',') printf_error("Color should be seperated by comma.\n", g); line++; return (line); } void cp_helpr(char *line, t_game *g, int isfloor) { int color[3]; color[0] = ft_atoi_cub(&line); line = check_comma(line, g); color[1] = ft_atoi_cub(&line); line = check_comma(line, g); color[2] = ft_atoi_cub(&line); if (isfloor) g->vars.floor_color = create_trgb(0, color, g); else g->vars.ceiling_color = create_trgb(0, color, g); while (*line != '\0' && *line != 0) { if (*line++ != ' ') printf_error("Extra input in colors\n", g); } } void check_color_line(char *line, t_game *g) { int i; int comma; i = 0; comma = 0; while (line[++i] != '\0') { if (line[i] < '0' || line[i] > '9') { if (line[i] == ',') comma++; else if (line[i] != ' ') printf_error("Invalid color format.\n", g); } } if (comma != 2) printf_error("Invlaid no of commas in color.\n", g); } void color_parser(t_game *g, char *line) { check_color_line(line, g); if (g->map.size > 0) printf_error("Input order incorrect:color_parser.\n", g); if (*line++ == 'F') { cp_helpr(line, g, 1); g->pars_check[6]++; } else { cp_helpr(line, g, 0); g->pars_check[7]++; } }
C
#ifndef _SEARCH_ALGOS_H_ #define _SEARCH_ALGOS_H_ #include <stddef.h> /** * struct listint_s - simple linked list nodes * @n: value in this node * @index: index in the list * @next: pointer to next node in the list */ typedef struct listint_s { int n; size_t index; struct listint_s *next; } listint_t; /** * struct skiplist_s - skip list nodes * @n: value in this node * @index: index of this node in list * @next: pointer to next node in list * @express: pointer to node further ahead in list */ typedef struct skiplist_s { int n; size_t index; struct skiplist_s *next; struct skiplist_s *express; } skiplist_t; int linear_search(int *array, size_t size, int value); int binary_search(int *array, size_t size, int value); int jump_search(int *array, size_t size, int value); int advanced_binary(int *array, size_t size, int value); int exponential_search(int *array, size_t size, int value); listint_t *jump_list(listint_t *list, size_t size, int value); skiplist_t *linear_skip(skiplist_t *list, int value); #endif
C
#include "Real.h" //****************************************************************************************** // Real - class used to manage real numbers. Includes methods to unpack half/single/double // precision numbers into a 'real' (64 bits worth of binary digits with sign and // decimal place). // // half-precision float stored in low order 16 bits... // // for half-precision: // sign bit is 16 // 5 bit exponent // low order bit of exponent is then bit 15 // low order 12 bits are mantissa // // single-precision float stored in low order 32 bits... // // for single-precision: // sign bit is 31 // 8 bit exponent // low order bit of exponent is then bit 23 // low order 23 bits are mantissa // // double-precision is 64 bits... // // for double-precision: // sign bit is 63 // 11 bit exponent // low order bit of exponent is then bit 52 // low order 52 bits are mantissa //****************************************************************************************** //****************************************************************************************** // _unpack - unpack floating point value into its constitute parts, characterize the // value, convert to real... //****************************************************************************************** double Real::infinity() { return HUGE_VAL; } void Real::unpack(int _input_type, unsigned long long _fpval) { input_type = _input_type; fpval = _fpval; breakout_parts(); // sign, exponent, fractional values split out here if (exp==0) { // exponent is zero... if ( (frac==0) || flush_to_zero() ) { // exponent and fraction are zero, ie, value is indeed zero... type = FPType_Zero; dval = 0.0; real = 0; } else { // exponent is zero, but fraction is not... type = FPType_NonZero; // normalize it, then make it real... dval = normalize(); double2real(dval); } } else if (exponent_is_all_ones()) { // exponent is all ones... if (frac==0) { // exponent is all ones and fraction is all zeros, ie, infinity... type = FPType_Infinity; dval = infinity(); real = 0; } else { // exponent is all ones with non-zero fraction, ie, NaN... type = is_signaling_nan() ? FPType_QNaN : FPType_SNaN; dval = 0.0; real = 0; } } else { // convert 'normal' number... type = FPType_NonZero; unpack_normal(); } } //****************************************************************************************** // _breakout_parts() - break out sign, exponent, and fractional part from floating point // (binary) value... //****************************************************************************************** void Real::breakout_parts() { switch(input_type) { case FP_HALF: sign = (fpval>>15) & 1; exp = (fpval>>10) & 0x1f; frac = fpval & 0x3ff; break; case FP_SINGLE: sign = (fpval>>31) & 1; exp = (fpval>>23) & 0xff; frac = fpval & 0x7fffff; break; case FP_DOUBLE: sign = (fpval>>63) & 1; exp = (fpval>>52) & 0x7ff; frac = fpval & 0xffffffffffffull; break; default: // should throw some sort of exception here... break; } } //****************************************************************************************** // _flush_to_zero() - return true if flush-to-zero mode enabled... //****************************************************************************************** bool Real::flush_to_zero() { bool do_flush = false; switch(input_type) { case FP_HALF: // no flush to zero for half-precision... break; case FP_SINGLE: case FP_DOUBLE: do_flush = (FTZ==1); break; default: // should throw some sort of exception here... break; } return do_flush; } //****************************************************************************************** // _normalize() - convert a 'denormal' floating point value into normal form... //****************************************************************************************** double Real::normalize() { double fv = 0.0; switch(input_type) { case FP_HALF: fv = powf(2.0,-14.0) * ldexpf(frac,-10.0); break; case FP_SINGLE: fv = powf(2.0,-126.0) * ldexpf(frac,-23.0); break; case FP_DOUBLE: fv = powf(2.0,-126.0) * ldexpl(frac,-23.0); break; default: // should throw some sort of exception here... break; } return fv; } //****************************************************************************************** // convert double precision floating point value to real ('string' of binary digits and // decimal point index)... //****************************************************************************************** void Real::double2real(double _fp) { double fp = fabs(_fp); // we already recorded the sign // Separate integer and fractional parts... double fp_int, fp_frac; fp_frac = modf(fp,&fp_int); // start with integer part... real = (unsigned long long) fp_int; // coerce to ull if (real != fp_int) // if real does not equal integer portion of original # overflow = true; // ASSUME overflow... // now fraction... decimal_point = 0; // add in bits from fraction, shifting real bits left each time // but only as long as there is 'room' in the result, ie, // as long as no significant bits are shifted out... while((fp_frac > 0) && ( (real>>63) != 1 ) ) { fp_frac *= 2; fp_frac = modf(fp_frac,&fp_int); real = (real<<1) | ( (lrint(fp_int) > 0) ? 1 : 0 ); decimal_point += 1; } // if resulting real is zero then ASSUME underflow has occurred... if (real == 0) underflow = true; } //****************************************************************************************** // _exponent_is_all_ones() - return true if exponent is all ones... //****************************************************************************************** bool Real::exponent_is_all_ones() { bool all_ones = false; switch(input_type) { case FP_HALF: // FPCR.AHP - if set, then alternate (non-IEEE) mode... all_ones = (exp==0x1f) && (AHP==0); break; case FP_SINGLE: all_ones = (exp==0xff); break; case FP_DOUBLE: all_ones = (exp==0x7ff); break; default: // should throw some sort of exception here... break; } return all_ones; } //****************************************************************************************** // _is_signaling_nan() - Not-a-Number detected, return true if a Signaling NaN... //****************************************************************************************** bool Real::is_signaling_nan() { bool is_snan = false; switch(input_type) { case FP_HALF: is_snan = ((frac>>9) & 1)==1; break; case FP_SINGLE: is_snan = ((frac>>22) & 1)==1; break; case FP_DOUBLE: is_snan = ((frac>>51) & 1)==1; break; default: // should throw some sort of exception here... break; } return is_snan; } //****************************************************************************************** // _unpack_normal() - convert 'normal' (not zero or infinity or NaN) floating point value // into real binary number with decimal place... //****************************************************************************************** void Real::unpack_normal() { switch(input_type) { case FP_HALF: { // convert half-precision value into double precision, then to real... dval = powf(2.0,exp-15) * (1.0 + ldexpf(frac,-10.0)); double2real(dval); } break; case FP_SINGLE: { // work from 'original' number... union { float fv; unsigned int uv; } tmp; tmp.uv = fpval; dval = tmp.fv; double2real(dval); } break; case FP_DOUBLE: { // work from 'original' number... union { double fv; unsigned long long uv; } tmp; tmp.uv = fpval; dval = tmp.fv; double2real(dval); } break; default: // should throw some sort of exception here... break; } } //****************************************************************************************** // Type() - return real number tgype as string... //****************************************************************************************** std::string Real::Type() { std::string _type; switch(type) { case FPType_Zero: _type = "ZERO"; break; case FPType_NonZero: _type = "NON-ZERO"; break; case FPType_Infinity: _type = "INFINITY"; break; case FPType_QNaN: _type = "QNAN"; break; case FPType_SNaN: _type = "SNAN"; break; default: _type = "UNKNOWN"; break; } return _type; } //****************************************************************************************** // RealToDouble(), RealToInt() - operate on real number to result either double or int... //****************************************************************************************** double Real::RealToDouble() { double result = 0.0; if (type == FPType_NonZero) { unsigned long long int_bits = real >> decimal_point; unsigned long long frac_bits = (real & (1<<decimal_point)) - 1; double fb = (double) frac_bits; for (int i = 0; i < decimal_point; i++) { fb = fb / 2; } result = (double) int_bits + fb; if (sign) result = -result; } return result; } long long Real::RealToInt(/*bool round_up*/) { long long result = (long long) (real >> decimal_point); // effectively rounding to zero or down /* if (round_up) { double diff = dval - (double) result; if (diff >= 0.5) result += 1; } */ if (sign) result = -result; return result; }
C
/* *********************************** */ /* */ /* Morphosis project */ /* */ /* Created by Artur Makhnach */ /* github.com/DippyArtu */ /* artum.me */ /* */ /* *********************************** */ #include "morphosis.h" void gl_retrieve_tris(t_data *data) { uint i; uint j; i = 0; j = 0; if (!(data->gl->tris = (float *)malloc(data->gl->num_pts * sizeof(float)))) error(MALLOC_FAIL_ERR, data); bzero(data->gl->tris, data->gl->num_pts); while (j < data->gl->num_pts) { for (int c = 0; c < 3; c++) { data->gl->tris[j++] = data->triangles[i][c].x; data->gl->tris[j++] = data->triangles[i][c].y; data->gl->tris[j++] = data->triangles[i][c].z; } i++; } } void gl_set_attrib_ptr(t_gl *gl, char *attrib_name, GLint num_vals, int stride, int offset) { GLuint attrib; attrib = glGetAttribLocation(gl->shaderProgram, attrib_name); glVertexAttribPointer(attrib, num_vals, GL_FLOAT, GL_FALSE, stride * sizeof(float), (void *)(offset * sizeof(float))); glEnableVertexAttribArray(attrib); }
C
#include <stdio.h> main(int argc,char **argv) { int i; for(i=1;i<atoi(argv[1]);i++) printf("%03d\n",i); }
C
/** @file orbit.h @brief Main header for the photodynamical routines. */ #include <stdio.h> #include <math.h> // Constants #define BIGG 0.00029591220363 /**< Gravitational constant (AU^3 / MSUN / day^2) */ #define PI 3.14159265358979323846 #define TWOPI 6.283185307179586476925287 /** Struct containing all the information pertaining to a body (star, planet, or moon) in the system. */ typedef struct { double m; /**< Body mass in solar masses */ double x; /**< The Cartesian x position on the sky (right positive) */ double y; /**< The Cartesian y position on the sky (up positive) */ double z; /**< The Cartesian z position on the sky (into sky negative) */ double vx; /**< The Cartesian x velocity on the sky (right positive) */ double vy; /**< The Cartesian y velocity on the sky (up positive) */ double vz; /**< The Cartesian z velocity on the sky (into sky positive) */ int nt; double *transit_times; } Body;
C
/* Author: gturr001, Giovany Turrubiartes * Partner(s) Name: * Lab Section: * Assignment: Lab #8 Exercise #1 * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. */ #include <avr/io.h> #ifdef _SIMULATE_ #include "simAVRHeader.h" #endif void set_PWM(double frequency) { static double current_frequency; if (frequency != current_frequency) { if (!frequency) { TCCR3B &= 0x08; } else { TCCR3B |= 0x03; } if (frequency < 0.954) { OCR3A = 0xFFFF; } else if (frequency > 31250) { OCR3A = 0x0000; } else { OCR3A = (short)(8000000 / (128 * frequency)) - 1; } TCNT3 = 0; current_frequency = frequency; } } void PWM_on () { TCCR3A = (1 << COM3A0); TCCR3B = (1 << WGM32); set_PWM(0); } void PWM_off () { TCCR3A = 0x00; TCCR3B = 0x00; } int main(void) { DDRA = 0x00; PORTA = 0xFF; unsigned char button1 = 0x00; unsigned char button2 = 0x00; unsigned char button3 = 0x00; DDRB = 0x40; PORTB = 0x00; PWM_on(); /* Insert DDR and PORT initializations */ /* Insert your solution below */ while (1) { // PWM_on(); button1 = ~PINA & 0x01; button2 = ~PINA & 0x02; button3 = ~PINA & 0x04; if ((button1 && button2) || (button2 && button3) || (button1 && button3)) { set_PWM(0); } else if (button1) { set_PWM(261.63); } else if (button2) { set_PWM(293.66); } else if (button3) { set_PWM(329.63); } else { set_PWM(0); } } }
C
#include "ngx_core.h" // compile with ``gcc main.c ngx_alloc.c ngx_palloc.c -o scaffold`` int main() { ngx_init_mem_params(); printf("memory allocation test: \n"); const char* s1 = "hello world"; const char* s2 = "hello world"; void* p = ngx_alloc(20); memcpy(p, s1, strlen(s1)); printf("p address: %p, p: %s\n", p, (char*)p); printf("s1 address: %p, s1: %s\n", s1, s1); printf("s2 address: %p, s2: %s\n", s2, s2); ngx_free(p); p = NULL; printf("memory pool test: \n"); ngx_pool_t* pool = ngx_create_pool(1024); for(int i=0; i<20; ++i) { void* p = ngx_palloc(pool, 1<<i); printf("\taddress: %p\n", p); } ngx_destroy_pool(pool); return 0; }
C
#pragma once #include <stdbool.h> #include "board.h" typedef void *T; #define check_pointer(p) \ if (!p) { \ printf("Out of memory."); \ exit(EXIT_FAILURE); \ } /** * An element of a linked list * */ typedef struct list_element { struct list_element *next; ///< Pointer to next element in the list T value; ///< Value at node } list_element; /** * A linked list * */ typedef struct linked_list { list_element *head; ///< Pointer to the head of the list int size; ///< Length of list } linked_list; /** * @brief Initialize an empty list * * @return Pointer to created list */ linked_list *list_create(); /** * @brief Destory a a given list * * @param l Pointer to list to be destroyed * * @warning For now, one should remove all the elements, then free the list's * pointer, as the implementation has a bug */ void list_destroy(linked_list *l); /** * @brief Add an element with value e to a list * * Add an item at the front of the list, taking constant time. * * @param e The item to add to the list @p l * @param l The list to which @p e is added */ void list_add(T e, linked_list *l); /** * @brief Add an element with value e to the list at a specified position * * Add an item at position @p index (list indexing starts at 0), taking linear * time with respect to the index. Will not add the item if the index is out of * bounds. * * @param index The position that the item will occupy in the list * @param e The item to add to the list * @param l The list to which @p e is added */ void list_add_at(int index, T e, linked_list *l); /** * @brief Remove an element from a list at a specified position * * Remove an item at position @p index (list indexing starts at 0), taking linear * time with respect to the index. * * @param index The position from which to remove an element * @param l The list from which the element is removed * * @note The item's value is destroyed as well. If additional allocation has * been for the element's value, then this must be manually managed. */ void list_remove(int index, linked_list *l); /** * @brief Retrieve a value from a list at a specified position * * Retrieve an value of a list_element at position @p index (list indexing * starts at 0), taking linear time with respect to the index. Will not remove * the item if the index is out of bounds. * * @param index The position from which to find the element * @param l The list from which the element is retrieved */ T list_get(int index, linked_list *l); /** * @brief Set a value from a list at a specified position * * Set an value of a list_element at position @p index (list indexing * starts at 0), taking linear time with respect to the index. Will not change * the item if the index is out of bounds. * * @param index The position from which to find the element * @param l The list from which the element is set * * @return The element at the given @p index */ void list_set(int index, T e, linked_list *l); /** * @brief Check if a list contains a certain value * * Check that a list contains an element whose value is e. * * @param e The value to find in the list * @param l The list to search * * @return @c TRUE if list contains a list_element with value @p e else @c FALSE list contains a list_element with value @p e* * @warning The implementation must change according to T's type. For the * moment, the equality of board types is declared. The behaviour will be undefined * on other types. */ bool list_contains(T e, linked_list *l); /** * @brief Check if a list is empty * * Check that a list is empty (has no list_elements) * * @param l The list to check * * @return @c TRUE if list is empty else @c FALSE */ bool list_is_empty(linked_list *l);
C
int main (){ int year1,month1,day1,year2,month2,day2; int total=0; scanf("%d %d %d",&year1,&month1,&day1); scanf("%d %d %d",&year2,&month2,&day2); while((year1!=year2)||(month1!=month2)||(day1!=day2)){ if(month1==1||month1==3||month1==5||month1==7||month1==8||month1==10){ if(day1<31){ day1++; total++; }else if(day1==31){ day1=0; month1++; } } if(month1==4||month1==6||month1==9||month1==11){ if(day1<30){ day1++; total++; }else if(day1==30){ day1=0; month1++; } } if(month1==2){ if((year1%4==0&&year1%100!=0)||(year1%400==0)){ if(day1<29){ day1++; total++; }else if(day1==29){ day1=0; month1++; } }else{ if(day1<28){ day1++; total++; }else if(day1==28){ day1=0; month1++; } } } if(month1==12){ if(day1<31){ day1++; total++; }else if(day1==31){ day1=0; month1=1; year1++; } } } printf("%d",total); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <sys/socket.h> #include <sys/epoll.h> #include <arpa/inet.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #define BUFFER_SIZE 4096 #define MAX_EPOLL_EVENTS 1024 #define SERVER_PORT 8888 typedef int (*NCALLBACK)(int sockfd, int events, void *arg); struct ntyevent { int sockfd; // socket int events; // EPOLLIN or EPOLLOUT int flag; // if the ntyevent has been added to ntyreactor then flag = 1, else flag = 0 long last_active; NCALLBACK cb; void *arg; int size; char buffer[BUFFER_SIZE]; }; struct ntyreactor { int epfd; struct ntyevent *events; }; int accept_cb(int sockfd, int events, void *arg); int recv_cb(int sockfd, int events, void *arg); int send_cb(int sockfd, int events, void *arg); void ntyevent_set(struct ntyevent* ev, int sockfd, int events, NCALLBACK cb, void *arg) { ev->sockfd = sockfd; ev->events = events; // EPOLLIN or EPOLLOUT ev->flag = 0; // init 0 ev->last_active = time(NULL); ev->arg = arg; ev->cb = cb; } int ntyreactor_init(struct ntyreactor *reactor) { if(reactor == NULL) { return -1; } memset(reactor, 0, sizeof(struct ntyreactor)); reactor->epfd = epoll_create(1); if(reactor->epfd < 0) { printf("create epfd in %s error: %s\n", __func__, strerror(errno)); return -2; } reactor->events = (struct ntyevent *)malloc(MAX_EPOLL_EVENTS * sizeof(struct ntyevent)); if(reactor->events == NULL) { printf("malloc in %s error: %s\n", __func__, strerror(errno)); close(reactor->epfd); return -3; } return 0; } int ntyreactor_add_event_to_epoll(struct ntyreactor *reactor, struct ntyevent *ev) { if(reactor == NULL || ev == NULL) { return -1; } if(ev->flag == 0) { struct epoll_event epollev; epollev.events = ev->events; epollev.data.ptr = (void *)ev; int res = epoll_ctl(reactor->epfd, EPOLL_CTL_ADD, ev->sockfd, &epollev); if(res < 0) { return -2; } ev->flag = 1; // set flag } return 0; } int ntyreactor_del_event_from_epoll(struct ntyreactor *reactor, struct ntyevent *ev) { if(reactor == NULL || ev == NULL) { return -1; } if(ev->flag == 1) { struct epoll_event epollev; epollev.events = ev->events; epollev.data.ptr = (void *)ev; int res = epoll_ctl(reactor->epfd, EPOLL_CTL_DEL, ev->sockfd, &epollev); if(res < 0) { return -2; } ev->flag = 0; } return 0; } int ntyreactor_add_listener(struct ntyreactor *reactor, int sockfd, NCALLBACK accept_cb) { if(reactor == NULL || reactor->events == NULL) { return -1; }; ntyevent_set(&reactor->events[sockfd], sockfd, EPOLLIN, accept_cb, (void *)reactor); ntyreactor_add_event_to_epoll(reactor, &reactor->events[sockfd]); return 0; } int ntyreactor_run(struct ntyreactor *reactor) { if(reactor == NULL || reactor->epfd < 0 || reactor->events == NULL) { return -1; } struct epoll_event events[MAX_EPOLL_EVENTS]; while(1) { int nfds = epoll_wait(reactor->epfd, events, MAX_EPOLL_EVENTS, 1000); if(nfds < 0) { continue; } for(int i = 0; i < nfds; ++i) { struct ntyevent *ev = (struct ntyevent *)events[i].data.ptr; if((events[i].events & EPOLLIN) && (ev->events & EPOLLIN)) { ev->cb(ev->sockfd, events[i].events, ev->arg); } if((events[i].events & EPOLLOUT) && (ev->events & EPOLLOUT)) { ev->cb(ev->sockfd, events[i].events, ev->arg); } } } return 0; } int ntyreactor_destory(struct ntyreactor *reactor) { if(reactor == NULL) { return -1; } close(reactor->epfd); free(reactor->events); return 0; } int init_socket(int port) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) { return -1; } int flags = fcntl(sockfd, F_GETFL, 0); fcntl(sockfd, F_SETFL, flags |= O_NONBLOCK); // 设置套接字为非阻塞 struct sockaddr_in serveraddr; memset(&serveraddr, 0, sizeof(struct sockaddr_in)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htonl(port); int res = bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(struct sockaddr)); if(res < 0) { printf("bind failed: %s\n", strerror(errno)); return -2; } res = listen(sockfd, 10); if(res < 0) { printf("listen failed: %s\n", strerror(errno)); return -3; } return sockfd; } int accept_cb(int sockfd, int events, void *arg) { struct ntyreactor *reactor = (struct ntyreactor *)arg; if(reactor == NULL) { return -1; } struct sockaddr_in clientaddr; memset(&clientaddr, 0, sizeof(struct sockaddr_in)); socklen_t len = sizeof(clientaddr); int clientfd = accept(sockfd, (struct sockaddr *)&clientaddr, &len); if(clientfd < 0) { printf("accept failed: %s\n", strerror(errno)); return -2; } int flags = fcntl(clientfd, F_GETFL, 0); fcntl(clientfd, F_SETFL, flags |= O_NONBLOCK); // 设置套接字为非阻塞 ntyevent_set(&reactor->events[clientfd], clientfd, EPOLLIN, recv_cb, (void *)reactor); ntyreactor_add_event_to_epoll(reactor, &reactor->events[clientfd]); return 0; } int recv_cb(int sockfd, int events, void *arg) { struct ntyreactor *reactor = (struct ntyreactor *)arg; struct ntyevent *ev = &reactor->events[sockfd]; int size = recv(sockfd, ev->buffer, BUFFER_SIZE, 0); ntyreactor_del_event_from_epoll(reactor, ev); if(size > 0) { ev->size = size; ev->buffer[size] = '\0'; printf("Client[%d]:%s\n", sockfd, ev->buffer); ntyevent_set(ev, sockfd, EPOLLOUT, send_cb, (void *)reactor); ntyreactor_add_event_to_epoll(reactor, ev); } else if(size == 0) { close(sockfd); printf("[sockfd=%d] pos[%ld], closed\n", sockfd, ev - reactor->events); } else { close(sockfd); printf("recv[sockfd=%d] error[%d]:%s\n", sockfd, errno, strerror(errno)); } return size; } int send_cb(int sockfd, int events, void *arg) { struct ntyreactor *reactor = (struct ntyreactor *)arg; struct ntyevent *ev = &reactor->events[sockfd]; int size = send(sockfd, ev->buffer, ev->size, 0); if(size > 0) { printf("send[sockfd=%d], [%d]%s\n", sockfd, size, ev->buffer); ntyreactor_del_event_from_epoll(reactor, ev); ntyevent_set(ev, sockfd, EPOLLIN, recv_cb, (void *)reactor); ntyreactor_add_event_to_epoll(reactor, ev); } else { close(sockfd); ntyreactor_del_event_from_epoll(reactor, ev); printf("send[sockfd=%d] error %s\n", sockfd, strerror(errno)); } return size; } int main(int argc, char *argv[]) { int sockfd = init_socket(SERVER_PORT); struct ntyreactor reactor; ntyreactor_init(&reactor); ntyreactor_add_listener(&reactor, sockfd, accept_cb); ntyreactor_run(&reactor); ntyreactor_destory(&reactor); close(sockfd); return 0; }
C
/* * Lcd.c * * Created: 9/13/2021 1:24:59 PM * Author: Eslam Emara */ #include "Lcd.h" ST_TIMER_config_t TimerConfig = {TIMER0,FREQ_1_MHZ,NORMAL_MODE}; /*Set the timer for delay configurations*/ /* *Description: Function to initalize the connected LCD according to Config file *Set your desired configuration in "Lcd_config.h" *Expected Output: Setting the control pins and direction pins as output * and sending config commands for connected lcd *Void input and return. * */ void Lcd_init(){ Timer_init(TimerConfig); #if LCD_MODE == FOUR_BIT_MODE /*SET HIGH PINS DIRECTIONS OUT AND SEND 4BIT COMMANDS*/ DIO_setPinDir(LCD_D4,OUT); DIO_setPinDir(LCD_D5,OUT); DIO_setPinDir(LCD_D6,OUT); DIO_setPinDir(LCD_D7,OUT); DIO_setPinDir(LCD_RS,OUT); /*CONTROL PINS*/ DIO_setPinDir(LCD_EN,OUT); DIO_setPinDir(LCD_RW,OUT); Lcd_SendCommand(LCD_4BIT_MODE); /*4BIT COMMANDS*/ Lcd_SendCommand(FOUR_BIT_TWO_LINES_5x7); #else /*SET PINS DIRECTIONS OUT AND SEND 8BIT COMMANDS*/ DIO_setPinDir(LCD_D0,OUT); DIO_setPinDir(LCD_D1,OUT); DIO_setPinDir(LCD_D2,OUT); DIO_setPinDir(LCD_D3,OUT); DIO_setPinDir(LCD_D4,OUT); DIO_setPinDir(LCD_D5,OUT); DIO_setPinDir(LCD_D6,OUT); DIO_setPinDir(LCD_D7,OUT); DIO_setPinDir(LCD_RS,OUT); /*CONTROL PINS*/ DIO_setPinDir(LCD_EN,OUT); DIO_setPinDir(LCD_RW,OUT); Lcd_SendCommand(LCD_8BIT_MODE); /*8BIT COMMANDS*/ Lcd_SendCommand(EIGHT_BIT_TWO_LINES_5x7); #endif Lcd_SendCommand(DISPLAY_ON_CURSOR_OFF); /* Display on cursor off*/ Lcd_SendCommand(CURSOR_RIGHT); /* shift cursor to right*/ Lcd_SendCommand(CLR_DISPLAY); /* Clear screen*/ } /* *Description: Function to send a command byte to the LCD (see commands in lcd.h) *Input: uint8_t command *Output: NONE *return void * */ void Lcd_SendCommand( uint8_t cmnd ) { #if LCD_MODE == FOUR_BIT_MODE WriteHighNibble(cmnd); DIO_clearPin(LCD_RS); /*Write to control register*/ ToggleEN(); WriteLowNibble(cmnd); ToggleEN(); #endif } /* *Description: Function to display a character on the lcd *Input: uint8_t ascii code of the character *Expected Output: the character is printed on the screen. *void return. */ void Lcd_SendChar( uint8_t data ) { #if LCD_MODE == FOUR_BIT_MODE WriteHighNibble(data); DIO_setPin(LCD_RS); /*Write to Data register*/ ToggleEN(); WriteLowNibble(data); ToggleEN(); #endif } /* *Description: Function to print a string on the screen *Inputs: pointer to a character points to the first character of the string *Void return. *EXAMPLE: Lcd_SendString("Hello World"); */ void Lcd_SendString (sint8_t *str) /* Send string to LCD function */ { uint8_t chars_iterator; for(chars_iterator=0;str[chars_iterator]!= '\0';chars_iterator++){ /* Send each char of string till the end of string */ Lcd_SendChar (str[chars_iterator]); } } /* *Description: Function to put the cursor on the screen in a certain position *inputs: row number , column number , string to be printed * row number must be 0 or 1 if using 16*2 LCD * column number must be less than maximum character numbers in one row *void return. */ void Lcd_GoToXY(uint8_t row , uint8_t col){ if (col < MAX_CHARS && row <MAX_ROWS){ if (row == 0){ /*First row , row number 0*/ Lcd_SendCommand((col & 0x0F)|CURSOR_BEGIN_FIRST_LINE); } else if(row == 1){ /*Second row , row number 1*/ Lcd_SendCommand((col & 0x0F)|CURSOR_BEGIN_SECOND_LINE); } } } /* *Description: Function to print a string on the screen in a certain position *inputs: row number , column number , string to be printed * row number must be 0 or 1 if using 16*2 LCD * column number must be less than maximum character numbers in one row *void return. */ void Lcd_SendStringXY (uint8_t row, uint8_t col, sint8_t *str) { Lcd_GoToXY(row,col); Lcd_SendString(str); } /* *Description: function to delay until processor is not busy *inputs: None. *Return: none. *Expected Output: Delay the code until the processor of lcd is done from the current instruction **/ void Lcd_CheckBusyFlag() { DIO_setPinDir(LCD_D7,IN); DIO_clearPin(LCD_RS); DIO_setPin(LCD_RW); while(DIO_getPin(LCD_D7) == HIGH); DIO_setPinDir(LCD_D7,OUT); DIO_clearPin(LCD_RW); } /* * Function to clean the LCD screen. * Inputs: NONE * void return. **/ void Lcd_ClrScreen(){ Lcd_SendCommand(CLR_DISPLAY); } /* Description: Function to write low nibble of number to the connected high pins for 4bit mode *Input : uint8_t the number to write *return: None */ void WriteLowNibble( uint8_t n ){ DIO_write(LCD_D4 , ((n) & (0x01)) ); DIO_write(LCD_D5 , ((n >> 1) & (0x01)) ); DIO_write(LCD_D6 , ((n >> 2) & (0x01)) ); DIO_write(LCD_D7 , ((n >> 3) & (0x01)) ); } /* Description: Function to write high nibble of number to the connected high pins for 4bit mode *Input : uint8_t the number to write *return: None */ void WriteHighNibble( uint8_t n ){ DIO_write(LCD_D4 , ((n>>4) & (0x01)) ); DIO_write(LCD_D5 , ((n >> 5) & (0x01)) ); DIO_write(LCD_D6 , ((n >> 6) & (0x01)) ); DIO_write(LCD_D7 , ((n >> 7) & (0x01)) ); } /* Description: Function to make a falling edge on the enable pin with delay 1us *Input : None. *return: None. */ void ToggleEN(void){ DIO_setPin(LCD_EN); Timer_Delay(0.000001,TimerConfig); DIO_clearPin(LCD_EN); }
C
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> static uint32_t x = 123456789; static uint32_t y = 362436069; static uint32_t z = 521288629; static uint32_t w = 88675123; static uint32_t v = 886756453; static uint32_t xorshift(void) { uint32_t t; t = x ^ (x >> 7); x = y; y = z; z = w; w = v; v = v ^ (v << 6) ^ t ^ (t << 13); return (y + y + 1) * v; } int main(int argc, char *argv[]) { char buf[32], *endptr; unsigned long l; uint32_t i, a, b, j, r; if(argc != 2 || *argv[1] == '\0') goto usage; l = strtoul(argv[1], &endptr, 10); if(*endptr != '\0' || l < 2 || 22 < l) goto usage; for(i = 0; i < (1UL << (l + 4)) * (l + 4); ++i) { a = 0; b = 0; for(j = 0; j < l; ++j) { a <<= 1; b <<= 1; r = xorshift() % 20; if(r < 11) a |= 1; if(r < 8 || r >= 18) b |= 1; } printf("Thu Jan 01 00:00:00 UTC 1970\t%lu@example.com\t%lu@example.com\n", (unsigned long)a, (unsigned long)b); } return 0; usage: printf(1, "usage: %s logpopulation", argv[0]); }
C
#include<stdio.h> #include<unistd.h> main() { pid_t pro_id; pro_id = fork(); if(pro_id == 0) { printf("Child ID: %d Parent ID: %d \n",getpid(),getppid()); } else if(pro_id > 0) { printf("Parent ID: %d Parent's Parent ID: %d \n",getpid(),getppid()); } else printf("Fork failure\n"); }
C
/* برنامه ای بنویسید که آرایه ای از رشته ایجاد کند. مثال : {"apple", "banana", "peach", "lemon"} سپس این رایه را بتوجه به طول رشته مرتب کند و در خروجی چاپ نماید. */ #include <stdio.h> #include <string.h> #define SIZE 4 #define STRING_MAX_SIZE 50 void initList(char listPtr[SIZE][STRING_MAX_SIZE]); void sortByLength(char listPtr[SIZE][STRING_MAX_SIZE]); void printArray(char listPtr[SIZE][STRING_MAX_SIZE]); int main() { char list[SIZE][STRING_MAX_SIZE]; initList(list); sortByLength(list); printArray(list); } void initList(char listPtr[SIZE][STRING_MAX_SIZE]) { for (int i = 0; i < SIZE; i++) { printf("\nPlease Enter Name : "); scanf("%s", listPtr[i]); } } void printArray(char listPtr[SIZE][STRING_MAX_SIZE]) { for (int i = 0; i < SIZE; i++) { printf("\n%s", listPtr[i]); } } void sortByLength(char listPtr[SIZE][STRING_MAX_SIZE]) { char temp[STRING_MAX_SIZE]; for (int i = 0; i < SIZE - 1; i++) { for (int j = i + 1; j < SIZE; j++) { if (strlen(listPtr[i]) > strlen(listPtr[j])) { strcpy( temp,listPtr[i]); strcpy( listPtr[i],listPtr[j]); strcpy(listPtr[j],temp); } } } }
C
#include <stdio.h> #include <stdlib.h> #include <windows.h> void merge(int arr[], int esq, int meio, int dir){ int i, j, k; int a1 = meio - esq + 1; int a2 = dir - meio; int E[a1], D[a2]; for(i=0; i<a1;i++){ E[i] = arr[esq + i]; } for(j=0; j < a2; j++){ D[j] = arr[meio + 1 + j]; } i = 0; j = 0; k = esq; while(i<a1 && j < a2){ if(E[i]<= D[j]){ arr[k] = E[i]; i++; } else{ arr[k] = D[j]; j++; } k++; } while(i<a1){ arr[k] = E[i]; i++; k++; } while(j<a2){ arr[k] = D[j]; j++; k++; } } void mergeSort(int arr[], int esq, int dir){ if(esq < dir){ int meio = esq+(dir-esq)/2; mergeSort(arr, esq, meio); mergeSort(arr, meio+1, dir); merge(arr, esq, meio, dir); } } void printArray(int arr[], int tamanho) { int i; for (i=0; i < tamanho; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int a[8] = {5,7,10,4,1,3,8,6}; int b[5] = {8,6,2,5,1}; int c[10] = {10,9,8,7,6,5,4,3,2,1}; int escolha; do{ system("cls"); printf("Digite 1 um para o array A.\n"); printf("Digite 2 um para o array B.\n"); printf("Digite 3 um para o array C.\n"); printf("Digite 4 para sair.\n"); scanf("%d", &escolha); switch(escolha){ case 1: system("cls"); printf("O array A tem o tamanho [8] e eh composto por: 5,7,10,4,1,3,8,6.\n"); mergeSort(a, 0, 7); printf("Sorted array: \n"); printArray(a, 8); Sleep(10000); break; case 2: system("cls"); printf("O array B tem o tamanho [5] e eh composto por: 8,6,2,5,1.\n"); mergeSort(b, 0, 4); printf("Sorted array: \n"); printArray(b, 5); Sleep(10000); break; case 3: system("cls"); printf("O array C tem o tamanho [10] e eh composto por: 10,9,8,7,6,5,4,3,2,1.\n"); mergeSort(c, 0, 9); printf("Sorted array: \n"); printArray(c, 10); Sleep(10000); break; } }while(escolha != 4); }
C
#include <stdalign.h> #include <stddef.h> #include <stdio.h> struct int_pair_s { int x, y; }; typedef struct int_pair_s int_pair; struct has_padding { int x; int:1; int y; }; typedef struct { int a, b; } anon; void entry (const unsigned sz, int buf[const]) { // anonymous and nested anonymous structs struct { struct { int x, y; } n; int z; } local = { .n.x = 1, .n.y = 2, .z = 3}; // initializers int i = 0; buf[i++] = local.n.x; buf[i++] = local.n.y; buf[i++] = local.z; struct int_pair_s pair1, pair2; pair1.x = 10; pair1.y = 20; pair2 = pair1; // struct assignment buf[i++] = pair2.x; buf[i++] = pair2.y; struct int_pair_s uninit = {0}; buf[i++] = uninit.x; buf[i++] = uninit.y; struct { struct { int x; }; struct { int y; }; } z = {0}; buf[i++] = z.x; buf[i++] = z.y; } typedef struct { int a; long long int b; } __attribute__((aligned(8))) Aligned8Struct; size_t alignment_of_aligned8_struct(void) { return alignof(Aligned8Struct); } #define DEFINE_TEST_STRUCT(x) struct x { char c; short s; long long ll; } DEFINE_TEST_STRUCT(S1); #pragma pack(push, 1) DEFINE_TEST_STRUCT(S2); #pragma pack(2) DEFINE_TEST_STRUCT(S3); #pragma pack(4) DEFINE_TEST_STRUCT(S4); #pragma pack(8) DEFINE_TEST_STRUCT(S5); #pragma pack(pop) DEFINE_TEST_STRUCT(S6) __attribute__((packed)); DEFINE_TEST_STRUCT(S7) __attribute__((aligned(1))); DEFINE_TEST_STRUCT(S8) __attribute__((aligned(2))); DEFINE_TEST_STRUCT(S9) __attribute__((aligned(4))); DEFINE_TEST_STRUCT(S10) __attribute__((aligned(8))); DEFINE_TEST_STRUCT(S11) __attribute__((aligned(16))); DEFINE_TEST_STRUCT(S12) __attribute__((packed, aligned(1))); DEFINE_TEST_STRUCT(S13) __attribute__((packed, aligned(2))); DEFINE_TEST_STRUCT(S14) __attribute__((packed, aligned(4))); DEFINE_TEST_STRUCT(S15) __attribute__((packed, aligned(8))); DEFINE_TEST_STRUCT(S16) __attribute__((packed, aligned(16))); #undef DEFINE_TEST_STRUCT #define DEFINE_TEST_STRUCT(x, y) struct x { char c; struct y s; } DEFINE_TEST_STRUCT(S17, S7); DEFINE_TEST_STRUCT(S18, S8); DEFINE_TEST_STRUCT(S19, S9); DEFINE_TEST_STRUCT(S20, S10); DEFINE_TEST_STRUCT(S21, S11); DEFINE_TEST_STRUCT(S22, S12); DEFINE_TEST_STRUCT(S23, S13); DEFINE_TEST_STRUCT(S24, S14); DEFINE_TEST_STRUCT(S25, S15); DEFINE_TEST_STRUCT(S26, S16); DEFINE_TEST_STRUCT(S27, S7) __attribute__((packed)); DEFINE_TEST_STRUCT(S28, S8) __attribute__((packed)); DEFINE_TEST_STRUCT(S29, S9) __attribute__((packed)); DEFINE_TEST_STRUCT(S30, S10) __attribute__((packed)); DEFINE_TEST_STRUCT(S31, S11) __attribute__((packed)); DEFINE_TEST_STRUCT(S32, S12) __attribute__((packed)); DEFINE_TEST_STRUCT(S33, S13) __attribute__((packed)); DEFINE_TEST_STRUCT(S34, S14) __attribute__((packed)); DEFINE_TEST_STRUCT(S35, S15) __attribute__((packed)); DEFINE_TEST_STRUCT(S36, S16) __attribute__((packed)); #undef DEFINE_TEST_STRUCT void alignment_entry(const unsigned sz, int buf[const]) { int i = 0; #define CHECK_TEST_STRUCT(S) \ do { \ struct S s = { .c = 42, .s = 1337, .ll = 65537 }; \ buf[i++] = sizeof(s); \ buf[i++] = alignof(s); \ buf[i++] = s.c; \ buf[i++] = s.s; \ buf[i++] = s.ll; \ buf[i++] = offsetof(struct S, c); \ buf[i++] = offsetof(struct S, s); \ buf[i++] = offsetof(struct S, ll); \ struct S sz = { }; \ buf[i++] = sz.c; \ buf[i++] = sz.s; \ buf[i++] = sz.ll; \ } while (0) CHECK_TEST_STRUCT(S1); CHECK_TEST_STRUCT(S2); CHECK_TEST_STRUCT(S3); CHECK_TEST_STRUCT(S4); CHECK_TEST_STRUCT(S5); CHECK_TEST_STRUCT(S6); CHECK_TEST_STRUCT(S7); CHECK_TEST_STRUCT(S8); CHECK_TEST_STRUCT(S9); CHECK_TEST_STRUCT(S10); CHECK_TEST_STRUCT(S11); CHECK_TEST_STRUCT(S12); CHECK_TEST_STRUCT(S13); CHECK_TEST_STRUCT(S14); CHECK_TEST_STRUCT(S15); CHECK_TEST_STRUCT(S16); #undef CHECK_TEST_STRUCT #define CHECK_TEST_STRUCT(S) \ do { \ struct S s = { }; \ buf[i++] = sizeof(s); \ buf[i++] = alignof(s); \ buf[i++] = offsetof(struct S, s.c); \ buf[i++] = offsetof(struct S, s.s); \ buf[i++] = offsetof(struct S, s.ll); \ } while (0) CHECK_TEST_STRUCT(S17); CHECK_TEST_STRUCT(S18); CHECK_TEST_STRUCT(S19); CHECK_TEST_STRUCT(S20); CHECK_TEST_STRUCT(S21); CHECK_TEST_STRUCT(S22); CHECK_TEST_STRUCT(S23); CHECK_TEST_STRUCT(S24); CHECK_TEST_STRUCT(S25); CHECK_TEST_STRUCT(S26); CHECK_TEST_STRUCT(S27); CHECK_TEST_STRUCT(S28); CHECK_TEST_STRUCT(S29); CHECK_TEST_STRUCT(S30); CHECK_TEST_STRUCT(S31); CHECK_TEST_STRUCT(S32); CHECK_TEST_STRUCT(S33); CHECK_TEST_STRUCT(S34); CHECK_TEST_STRUCT(S35); CHECK_TEST_STRUCT(S36); #undef CHECK_TEST_STRUCT }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #ifdef __cplusplus extern "C" { // will be compiled as C, not C++ (no overrides etc.) // but cannot be in C sources => #ifdef #endif double pi = 3.14159265358979323846; float retfl(float a); double retdbl(double a); double fl2dbl(float a); double obvod(double r, double pi); int fl2i(float a); // this is actually ROUND! float prumer(float* p, int N); float max(float* p, int N); float arrsum(float* p, int N); // - - - - - - - - - - - - - - - - - - double vsphere(double r, double pi); float pytha(float a, float b); void vecsum(double* a, double *b, int N); double vecsize(double *v, int N); #ifdef __cplusplus } #endif // - - - - - - - - - - - - - - - - - - int main() { printf("\n\n\nretfl: %f\n", retfl((float)pi)); printf("retdbl: %f\n", retdbl(pi)); printf("fl2dbl: %f\n", fl2dbl((float)pi)); printf("\nobvod: %f\n", obvod(5, M_PI)); printf("fl2i: %d, %d, %d\n", fl2i(3.14), fl2i(3.5), fl2i(3.51)); float floatnums[] = {1.1, 2.2, 3.9, -2, 1, 9, 10, 88, 9, 10, -6, 12}; printf("\navg: %f\n", prumer(floatnums, sizeof(floatnums)/sizeof(*floatnums))); printf("\nmax: %f\n", max(floatnums, sizeof(floatnums)/sizeof(*floatnums))); printf("\narrsum: %f\n", arrsum(floatnums, sizeof(floatnums)/sizeof(*floatnums))); printf("\n--------------------------------\n"); printf("\nvsphere: %f\n", vsphere(5, M_PI)); printf("pytha(3, 4): %f\n", pytha(3.0, 4.0)); double veca[] = {3.0, 1.0, 5.0}; double vecb[] = {2.0, -2.0, 1.0}; int veclen = 3; vecsum(veca, vecb, veclen); printf("vecsum: "); for(int i=0; i<veclen; i++) printf("%f ", veca[i]); printf("\nvecsize: %f\n", vecsize(veca, veclen)); }
C
/* Limbus - A cross-platform multimedia library. Written in 2014 by Jesper Oskarsson jesosk@gmail.com To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "vector.h" void vector_construct( Vector* vector, unsigned int element_size ) { assert( vector != NULL ); vector->size = 0; vector->element_size = element_size; vector->data_size = 3 * element_size; vector->data = malloc( vector->data_size ); assert( vector->data != NULL ); } void vector_destruct( Vector* vector ) { assert( vector != NULL ); assert( vector->data != NULL ); free( vector->data ); vector->data = NULL; } int vector_push_back( Vector* vector, void* element ) { unsigned int offset; assert( vector != NULL ); assert( vector->data != NULL ); assert( vector->data_size > 0 ); assert( vector->element_size > 0 ); assert( element ); offset = (vector->element_size * vector->size); if (offset >= vector->data_size) { vector->data_size *= 2; vector->data = realloc( vector->data, vector->data_size ); assert( vector->data != NULL ); } memcpy( (char*)vector->data + offset, element, vector->element_size ); vector->size++; return vector->size - 1; } void* vector_at( Vector* vector, unsigned int position ) { assert( vector != NULL ); assert( vector->data != NULL ); assert( vector->element_size > 0 ); if (position < vector->size) return (char*)vector->data + (vector->element_size * position); else return NULL; } #define ASSERT_ITERATOR_IS_IN_RANGE( iterator )\ assert( iterator >= vector->data &&\ iterator < (void*)((char*)vector->data + vector->data_size) );\ assert( 0 == (((char*)iterator - (char*)vector->data)\ % vector->element_size) ); void* vector_next( Vector* vector, void* current ) { void *next, *last; assert( vector != NULL ); assert( vector->data != NULL ); assert( vector->size >= 0 ); if (current == NULL) { if (vector->size == 0) return NULL; else return vector->data; } else { ASSERT_ITERATOR_IS_IN_RANGE( current ); next = (char*)current + vector->element_size; last = (char*)vector->data + (vector->element_size * vector->size); if (next >= last) return NULL; return next; } } int vector_size( Vector* vector ) { assert( vector ); assert( vector->data != NULL ); return vector->size; } void vector_erase( Vector* vector, void* iterator ) { void *next, *last; size_t tail_size; assert( vector != NULL ); assert( vector->data != NULL ); assert( iterator != NULL ); ASSERT_ITERATOR_IS_IN_RANGE( iterator ); next = (char*)iterator + vector->element_size; last = (char*)vector->data + (vector->element_size * vector->size); tail_size = ((char*)last - (char*)next) + vector->element_size; vector->size--; if (iterator != last) { memcpy( iterator, next, tail_size ); } } void vector_clear( Vector* vector ) { assert( vector != NULL ); assert( vector->data != NULL ); vector->size = 0; } void* vector_data( Vector* vector ) { assert( vector != NULL ); assert( vector->data != NULL ); return vector->data; } #include "unittest.h" void vector_unittest() { Vector vector; int integer, i; int* iterator; /* An empty vector. */ vector_construct( &vector, sizeof( int ) ); EXPECT_EQUAL( vector_next( &vector, NULL ), NULL ); EXPECT_EQUAL( vector_at( &vector, 0 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 1 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 2 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 3 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 14 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 2345 ), NULL ); vector_destruct( &vector ); /* Adding elements */ vector_construct( &vector, sizeof( int ) ); for (i = 0; i < 9; i++) { integer = 9 - i; EXPECT_EQUAL( vector_push_back( &vector, &integer ), i ); EXPECT_EQUAL( vector_size( &vector ), (i + 1) ); } EXPECT_NOT_EQUAL( vector_at( &vector, 0 ), NULL ); EXPECT_EQUAL( *((int*)vector_at( &vector, 0 )), 9 ); EXPECT_NOT_EQUAL( vector_at( &vector, 1 ), NULL ); EXPECT_EQUAL( *((int*)vector_at( &vector, 1 )), 8 ); EXPECT_NOT_EQUAL( vector_at( &vector, 2 ), NULL ); EXPECT_EQUAL( *((int*)vector_at( &vector, 2 )), 7 ); EXPECT_NOT_EQUAL( vector_at( &vector, 3 ), NULL ); EXPECT_EQUAL( *((int*)vector_at( &vector, 3 )), 6 ); EXPECT_EQUAL( vector_at( &vector, 14 ), NULL ); EXPECT_EQUAL( vector_at( &vector, 2345 ), NULL ); i = 9; iterator = NULL; while ((iterator = (int*)vector_next( &vector, iterator ))) { EXPECT_EQUAL( i, *iterator ); i--; } /* Erasing elements */ for (i = 9 - 1; i >= 4; i--) { vector_erase( &vector, vector_next( &vector, NULL ) ); EXPECT_EQUAL( vector_size( &vector ), i ); } i = 4; iterator = NULL; while ((iterator = (int*)vector_next( &vector, iterator ))) { EXPECT_EQUAL( i, *iterator ); i--; } vector_destruct( &vector ); /* Erase from the middle of a vector */ vector_construct( &vector, sizeof( int ) ); integer = 0x12345678; vector_push_back( &vector, &integer ); integer = 0x21436587; vector_push_back( &vector, &integer ); integer = 0x87654321; vector_push_back( &vector, &integer ); vector_erase( &vector, vector_at( &vector, 1 ) ); EXPECT_EQUAL( 0x12345678, *(int*)vector_at( &vector, 0 ) ); EXPECT_EQUAL( 0x87654321, *(int*)vector_at( &vector, 1 ) ); EXPECT_EQUAL( NULL, vector_at( &vector, 2 ) ); vector_destruct( &vector ); /* Clearing a vector */ vector_construct( &vector, sizeof( int ) ); EXPECT_EQUAL( NULL, vector_next( &vector, NULL ) ); vector_clear( &vector ); EXPECT_EQUAL( NULL, vector_next( &vector, NULL ) ); integer = 3; vector_push_back( &vector, &integer ); vector_clear( &vector ); EXPECT_EQUAL( NULL, vector_next( &vector, NULL ) ); vector_clear( &vector ); EXPECT_EQUAL( NULL, vector_next( &vector, NULL ) ); vector_destruct( &vector ); }
C
/* ** EPITECH PROJECT, 2017 ** nnlib ** File description: ** Test the transpose function */ /* File created the 11/04/2018 at 13:05:48 by julian.frabel@epitech.eu */ #include <criterion/criterion.h> #include "nn.h" Test(nn_matrix_transpose, valid_matrix, .timeout=1) { float array[2][3] = {{1.2, 2.3, 3.0}, {0.4, 5.2, 6.11}}; nn_matrix_t *mat = create_empty_nn_matrix(2, 3); nn_matrix_t *res = NULL; cr_assert(mat != NULL); for (int row = 0; row < mat->nb_rows; row++) for (int col = 0; col < mat->nb_columns; col++) mat->values[row][col] = array[row][col]; res = nn_matrix_transpose(mat); cr_assert(res != NULL); cr_assert_eq(res->nb_columns, 2); cr_assert_eq(res->nb_rows, 3); for (int row = 0; row < res->nb_rows; row++) for (int col = 0; col < res->nb_columns; col++) cr_assert_eq(res->values[row][col], array[col][row]); } Test(nn_matrix_transpose, invalid_matrix, .timeout=1) { cr_assert(nn_matrix_transpose(NULL) == NULL); }
C
#include <stdio.h> #include <stdlib.h> typedef struct node { int i; struct node *next; } listNode; int searchList(listNode *head, int value); int main() { int i, value; listNode *cur, *head = NULL;/*INITIALIZE HEAD TO A NULL POINTER*/ printf("Enter a list of numbers, terminated by the value -1:\n"); scanf("%d", &i);/*ASK FOR INPUT BEFORE WHILE LOOP*/ while (i != -1) { if (head == NULL) {/*CHECK IF HEAD IS NULL TO ALLOCATE SPACE TO THE FIRST NODE*/ head = malloc(sizeof(listNode)); cur = head; } else { cur -> next = malloc(sizeof(listNode)); cur = cur -> next; } cur -> i = i; scanf("%d", &i); } if (head == NULL){return 0;} /*THIS IS VERY IMPORTANT SINCE IF USERS ENTER -1 */ /*THEN THE PROGRAM WILL RUN IN ERROR WITHOUT THIS LINE*/ cur -> next = NULL; printf("Current list: "); cur = head; while (cur != NULL) { printf("%d ", cur -> i); cur = cur -> next; } printf("\n"); printf("Enter value to search for: "); scanf("%d", &value); printf("Value %d found at index %d", value, searchList(head, value)); listNode *p = head; while (p) { head = p; p = p -> next; free(head); } } int searchList(listNode *head, int value) { int index = 0; listNode *cur = head; while (cur) { if (cur -> i == value) {return index;} cur = cur -> next; index++; } return -1; }
C
#include <stdio.h> struct Score { char name[20]; double kor, eng, total; }; typedef struct Score Student; int main() { Student s1, s2; FILE* stream; puts("1. Է : "); fscanf(stdin, "%s", s1.name); // Է ޾Ƽ ü puts("2. , Է : "); fscanf(stdin, "%lf %lf", &s1.kor, &s1.eng); // Է ޾Ƽ ü s1.total = s1.kor + s1.eng; stream = fopen("student.txt", "wb"); fwrite(&s1, sizeof(s1), 1, stream); // ü stream fclose(stream); stream = fopen("student.txt", "rb"); fread(&s2, sizeof(s2), 1, stream); // ü б fprintf(stdout, "%s, %f, %f, %f\n", s2.name, s2.kor, s2.eng, s2.total); fclose(stream); } // 24° // ü stream û Ѵ. // 28° // ü stream б û Ѵ.
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* helpers.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ibaran <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/02 19:26:11 by ibaran #+# #+# */ /* Updated: 2019/03/06 17:42:00 by ibaran ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" size_t ft_error(t_fdf **fdf) { ft_putendl("an error occured\nnote: usage: ./fdf <valid file>"); free_all(fdf); return (1); } void free_array(char ***array) { int i; i = 0; while ((*array)[i]) { free((*array)[i]); i++; } free(*array); } int ft_array_len(char **array) { size_t out; out = 0; while (array[out]) out++; return (out); } size_t ft_check(int ac, char **av, t_fdf **fdf) { size_t i; int fd; char **array_str; char *line; if (ac != 2 || (fd = open(av[1], O_RDONLY)) <= 0) return (1); i = 0; while (get_next_line(fd, &line) == 1) { array_str = ft_strsplit(line, ' '); if (i == 0) (*fdf)->input_x = ft_array_len(array_str); else if ((*fdf)->input_x != ft_array_len(array_str)) { free_array(&array_str); free(line); return (1); } free_array(&array_str); free(line); i++; } (*fdf)->input_y = i; return (i == 0 ? 1 : 0); } size_t fill_default_fdf(t_fdf **fdf, char *file_name) { if (reader(file_name, fdf) == 1) return (1); if (ft_projection_alloc(fdf) == 1) return (1); if (ft_rotation_alloc(fdf) == 1) return (1); copy_input_in_matrix(fdf); (*fdf)->image_x_input = IMAGE_X / (float)(((*fdf)->input_x) * 2); (*fdf)->image_y_input = IMAGE_Y / (float)(((*fdf)->input_y) * 2); (*fdf)->altitude_coef = 0.8; (*fdf)->angle = 0.523599; (*fdf)->max_z = (*fdf)->max_z_input * (*fdf)->altitude_coef; (*fdf)->min_z = (*fdf)->min_z_input * (*fdf)->altitude_coef; (*fdf)->zoom = 0.95; (*fdf)->trans_x = IMAGE_X / 2; (*fdf)->trans_y = IMAGE_Y / 2; (*fdf)->x_degree = 0.0; (*fdf)->z_degree = 0.0; (*fdf)->y_degree = 0.0; (*fdf)->proj = 0; return (0); }
C
#include "headers.h" void ls(char * input_str, char * add_root) { long long int i,j,k,len,flag_l = 0,flag_a = 0,num_dirs=0,curr_dir=0,cnt=0,blocks=0; char * token = strtok(input_str, " "),dirs[100][1000],add_curr_dir[1000]; struct dirent * file; struct stat info; struct passwd * passwd; struct group * grp; time_t now = time (NULL); struct tm timefl , timenow; char time_str[10000]; DIR *DIR_dir; token = strtok(NULL, " "); while(token!=NULL) { if(token[0]=='-') { len = strlen(token); for(i=1;i<len;i++) { if(token[i]!='a' && token[i]!='l') { printf("Flag not found : %c\n",token[i]); return; } else { if(token[i] == 'a') { flag_a = 1; } else if(token[i] == 'l') { flag_l = 1; } } } } else { strcpy(dirs[num_dirs],token); num_dirs++; } token = strtok(NULL," "); } if(num_dirs==0) { strcpy(dirs[num_dirs++],"."); } for(curr_dir=0;curr_dir<num_dirs;curr_dir++) { if(dirs[curr_dir][0]=='~') { strcpy(add_curr_dir,add_root); j=strlen(add_root); len = strlen(dirs[curr_dir]); for(i=1;i<len;i++) { add_curr_dir[j++]=dirs[curr_dir][i]; } add_curr_dir[j]='\0'; } else { strcpy(add_curr_dir,dirs[curr_dir]); } // printf("%s\n",add_curr_dir); DIR_dir = opendir(add_curr_dir); if(num_dirs>1) { if(curr_dir >=1) { printf("\n\033[1;35m%s :\033[0m\n",dirs[curr_dir]); } else { printf("\033[1;35m%s :\033[0m\n",dirs[curr_dir]); } } if (DIR_dir==0) { printf("No such file or directory\n"); } else { if(flag_l==0) { cnt=0; while(file = readdir(DIR_dir)) { char *name = file->d_name; if(flag_a==0) { if(name[0]!='.') { printf("%15s ",name); cnt++; } } else { printf("%15s ",name); cnt++; } if(cnt%6==0 && cnt!=0) { printf("\n"); } } if(cnt%6!=0 && cnt!=0) { printf("\n"); } } else if(flag_l!=0) { blocks=0; while(file = readdir(DIR_dir)) { stat(file->d_name, &info); char *name = file->d_name; if(flag_a==0) { if(name[0] != '.') { blocks += info.st_blocks; } } else { blocks += info.st_blocks; } } printf("total %lld\n",blocks/2); closedir(DIR_dir); DIR_dir = opendir(add_curr_dir); while(file = readdir(DIR_dir)) { // stat(file->d_name, &info); // printf("\nNAME %s\n",file->d_name); char *name = file->d_name; char file_path_name[10000]; strcpy(file_path_name,add_curr_dir); strcat(file_path_name,"/"); strcat(file_path_name,name); // printf("\nNAME %s\n",file_path_name); stat(file_path_name, &info); localtime_r(&info.st_mtime, &timefl); localtime_r(&now, &timenow); if(timefl.tm_year != timenow.tm_year) { strftime(time_str, 10000 , "%b %e %Y",&timefl); } else { strftime(time_str, 10000 , "%b %e %H:%M", &timefl); } if(flag_a==0 && name[0]=='.') { continue; } passwd = getpwuid(info.st_uid); grp = getgrgid(info.st_gid); if(S_ISDIR(info.st_mode)==1) printf("d"); else printf("-"); if((info.st_mode & S_IRUSR)) printf("r"); else printf("-"); if((info.st_mode & S_IWUSR)) printf("w"); else printf("-"); if((info.st_mode & S_IXUSR)) printf("x"); else printf("-"); if((info.st_mode & S_IRGRP)) printf("r"); else printf("-"); if((info.st_mode & S_IWGRP)) printf("w"); else printf("-"); if((info.st_mode & S_IXGRP)) printf("x"); else printf("-"); if((info.st_mode & S_IROTH)) printf("r"); else printf("-"); if((info.st_mode & S_IWOTH)) printf("w"); else printf("-"); if((info.st_mode & S_IXOTH)) printf("x "); else printf("- "); printf("%ld ", info.st_nlink); printf("%s ",passwd->pw_name); printf("%s ",grp->gr_name); printf("%10ld ", info.st_size); printf("%s ",time_str); printf("%s",name); printf("\n"); } } closedir(DIR_dir); } } }
C
#include "utils.h" #include "peripherals/p_uart.h" #include "peripherals/gpio.h" void uart_send ( char c ) { while(get32(PL011_UART_FR) & (1<<5)) { } put32(PL011_UART_DR, c); } char uart_recv ( void ) { while(get32(PL011_UART_FR) & (1<<4)) { } return(get32(PL011_UART_DR)&0xFF); } void uart_send_string(char* str) { for (int i = 0; str[i] != '\0'; i ++) { uart_send((char)str[i]); } } void uart_init ( void ) { //Page 92 & 102, use gpio14&15 for UART0 unsigned int selector; selector = get32(GPFSEL1); selector &= ~(7<<12); // clean gpio14 selector |= 0b100<<12; // set alt0 for gpio14 selector &= ~(7<<15); // clean gpio15 selector |= 0b100<<15; // set alt0 for gpio15 put32(GPFSEL1,selector); //Page 101: GPIO Pull-up/down Clock Registers put32(GPPUD,0); delay(150); put32(GPPUDCLK0,(1<<14)|(1<<15)); delay(150); put32(GPPUDCLK0,0); put32(PL011_UART_CR, 0); //disable cr register put32(PL011_UART_IMSC, 0); // Disable all interrupts //set baud rate to 115200 //default option in config.txt : init_uart_clock = 48MHz //https://www.raspberrypi.org/documentation/configuration/config-txt/boot.md //BAUDDIV = (FUARTCLK/(16 Baud rate)) = 48*10^6 / (16*115200)=26.0417 //http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0183g/I54603.html //IBRD = 26 //BRDF = 0.0417, FBRD = integer ( (BRDF × 64) + 0.5 ) = 3 put32(PL011_UART_IBRD, 26); put32(PL011_UART_FBRD, 3); put32(PL011_UART_LCRH, (1<<4)|(3<<5));//word length = 8 bits, FIFOS ensable put32(PL011_UART_IMSC, 0); // mask interupts put32(PL011_UART_CR, (1<<0)|(1<<8)|(1<<9)); //enable cr register }
C
#include<stdio.h> # define N 5 int queue[N]; int front = -1; int rear = -1; void enqueue(); void dequeue(); void display(); int isEmpty(); int isFull(); void peek(); int main() { printf("IsEmpty -- %d\n",isEmpty()); printf("IsFull -- %d\n",isFull()); enqueue(10); enqueue(20); enqueue(30); display(); dequeue(); dequeue(); display(); peek(); printf("front == %d\nrear == %d\n",front,rear); dequeue(); printf("front == %d\nrear == %d\n",front,rear); return 0 ; } void enqueue(int x) { if(isFull()) printf("Queue is full\n"); else { if(rear == -1) { front = 0 ; queue[++rear] = x; } else { rear = (rear+1)%N; queue[rear] = x; } } } void dequeue() { if(isEmpty()) printf("Queue is Empty\n"); else { if(front == rear) { front =-1; rear = -1; } else front = (front+1)%N; } } void peek() { printf("Peek is %d\n",queue[front]); } void display() { int i; if(isEmpty()) printf("Queue is Empty\n"); else { for(i=front ; i!=rear ; i = (i+1)%N) printf("%d ",queue[i]); printf("%d\n",queue[rear]); } } int isEmpty() { return rear == -1; } int isFull() { return (rear+1)%N == front; }
C
#include <stdio.h> int main() { char array[2][9] = {"WBWBWBWB","BWBWBWBW"}; for (int r = 0; r < 2; r++) { for (int c = 0; c < 8; c++) { printf("%c",array[r][c]); } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include "../src/sorted_queue.h" int cmp(const void *a, const void *b){ int a_val = *((int *)a); int b_val = *((int *)b); if (a_val>b_val) return 1; else if (a_val<b_val) return -1; return 0; } int main(){ int a = 5; int b = 6; int c = 7; int d = 1; int e = 10; sorted_queue_t queue; queue = sorted_queue_new(cmp); printf("elements in queue: %li\n", sorted_queue_count(queue)); sorted_queue_append(queue, &b); sorted_queue_append(queue, &a); sorted_queue_append(queue, &e); sorted_queue_append(queue, &d); sorted_queue_append(queue, &c); printf("////\n"); while(sorted_queue_count(queue)) { printf("elements in queue: %li\n", sorted_queue_count(queue)); printf("poped value is %i\n", *((int*)(sorted_queue_pop(queue)))); } printf("elements in queue: %li\n", sorted_queue_count(queue)); sorted_queue_append(queue, &a); printf("peeked value is %i\n", *((int*)(sorted_queue_peek(queue)))); printf("elements in queue: %li\n", sorted_queue_count(queue)); sorted_queue_free(queue); return 0; }
C
/* * mm.c * * NOTE TO STUDENTS: Replace this header comment with your own header * comment that gives a high level description of your solution. * */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdbool.h> #include <stdint.h> #include "mm.h" #include "memlib.h" #ifdef DRIVER #define memset mem_memset #define memcpy mem_memcpy #endif /* DRIVER */ static size_t get_size(void * p) {return *(unsigned int *) p & ~0x7;} static size_t get_alloc(void * p) {return *(unsigned int *) p & 0x1;} static unsigned long pack(unsigned long x, unsigned long y) { return x | y; } static void put(char * p, size_t x){ memcpy(p, &x, 8); } inline size_t get(char * p){ size_t temp; memcpy(&temp, p, 8); return temp; } int main(void) { size_t b = 0x1; size_t a = 0x1234567012345678; size_t c; char * m ; c = pack(b, a); //m = &c; size_t addr = (unsigned long) m; char * temp = (char * ) addr; printf("%p\n", m); printf("%p\n", addr); printf("%p\n", temp); }
C
#include "DDBLinkedList.h" #include <stdio.h> int main(int argc, const char * argv[]) { List list; ListInit(&list); LInsert(&list, 4); LInsert(&list, 5); int data; if (LFirst(&list, &data)) printf("num: %d \n", data); if (LNext(&list, &data)) printf("num: %d \n", data); printf("remove num: %d \n", LRemove(&list)); printf("remove num: %d \n", LRemove(&list)); return 0; }
C
#include<stdio.h> int main() { int n,i,j,temp; printf("Enter the no of elements:"); scanf("%d",&n); int a[n]; printf("Enter the elements: "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=0;i<n-1;i++) { int min =i; //taking first element as min number;// for(j=i+1;j<n;j++) //Normal Linear Search for finding the min element // { if(a[j]<a[min]) // if new min element if found update that location // { min=j; } } if(min!=i) // if min value is changed then swap a[i] and a[min];// { temp=a[i]; a[i]=a[min]; a[min]=temp; } } for(i=0;i<n;i++) { //Output printf("%d ",a[i]); } return 0; }
C
#include <stdio.h> #include <sys/socket.h> #include <unistd.h> #include <sys/un.h> #include <stdlib.h> #include <netinet/in.h> #include <string.h> #include <ctype.h> #define BUF_SIZE 1000 #define BACKLOG 1 #define SOCKET_ERR -2 #define BIND_ERR -3 #define LISTEN_ERR -4 #define ACCEPT_ERR -5 void string_toupper(char* ptr, int len){ if(ptr != NULL && len > 0) { int i = 0; for(; i< len; i++) { ptr[i] = toupper(ptr[i]); } return; } return; } int main() { int socket_fd, client_fd, read_bytes; struct sockaddr_un address; /*in -internet, un - connection via OS objects*/ int addrlen = sizeof(address); char buffer[BUF_SIZE] = {0}; /*AF_UNIX - unix domain, SOCK_STREAM - TCP connection in four steps - create, bind, listen, accept*/ socket_fd = socket(AF_UNIX, SOCK_STREAM, 0); if(socket_fd < 0) { perror("Error while creating socket\n"); return SOCKET_ERR; } /*null struct*/ memset(&address, 0, sizeof(address)); /*address family*/ address.sun_family = AF_UNIX; char * path = "tmp_file"; strcpy(address.sun_path, path); /*temp file for communication*/ int if_binded = bind(socket_fd, (struct sockaddr*)&address, sizeof(address)); if(if_binded < 0) { perror("Error while binding\b"); unlink(path); return BIND_ERR; } int listen_code = listen(socket_fd, BACKLOG); if(listen_code < 0) { perror("Error while listening\n"); unlink(path); return LISTEN_ERR; } struct sockaddr_un client_address; socklen_t client_address_len = sizeof(client_address); client_fd = accept(socket_fd, (struct sockaddr*)&client_address, (socklen_t*)&client_address_len); if(client_fd < 0) { unlink(path); perror("Error while accepting\n"); return ACCEPT_ERR; } read_bytes = read(client_fd, buffer, BUF_SIZE); string_toupper(&buffer, read_bytes); printf("%s\n", buffer); unlink(path); return 0; }
C
// 2.Write a program which accept number from user and return the count of odd // digits. // Input : 2395 // Output : 3 // Input : 1018 // Output : 2 // Input : -1018 // Output : 2 // Input : 8462 // Output : 0 #include "header.h" int main() { int iNo=0; int iRet=0; printf("Enter number\n"); scanf("%d",&iNo); iRet=CountOdd(iNo); printf("%d",iRet); return 0; }
C
/* You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). You need to return whether the student could be rewarded according to his attendance record. Example 1: Input: "PPALLP" Output: True Example 2: Input: "PPALLL" Output: False */ #include "LC551.h" bool checkRecord(char* s) { int len = (int)strlen(s); int countA = 0; int countContinuousL = 0; for (int i = 0; i < len; i++) { switch (s[i]) { case 'A': { countContinuousL = 0; countA++; if (countA >= 2) { return false; } } break; case 'L': { countContinuousL++; if (countContinuousL >= 3) { return false; } } break; default: { countContinuousL = 0; } break; } } return true; }
C
/** * replaceString(source,s1,s2); * Function replace s1 in source with s2. */ #include <stdio.h> #include <stdbool.h> int findString(const char source[], const char search[]) { int i = 0, j = 0; while (search[0] != source[j] && source[j + 1] && source[0]) ++j; do { if (search[i] != source[j + i]) return -1; if ( search[i] ) ++i; } while(search[i] != '\0'); return j; } void removeString(char source[], int start, int nChars) { int i, j, nextCharNumber, index = 0; char result[81]; while ( source[index] ) ++index; index -= 1; // the index of the last non-null in source[]; nextCharNumber = start + nChars; // Copying all elements AFTER those have been deleted into the result array. if(nChars <= index - nChars + 1 && nChars != 0) { for (j = 0; source[nextCharNumber + j] ; j++) result[j] = source[nextCharNumber + j]; // Pasting upon those that are to be deleted. for (i = 0; i < j; i++) source[start + i] = result[i]; source[start + i] = '\0'; } else source[start] = '\0'; // Account for removeString(word3,4,100); } int stringLength(char string[]) { int i = 0; while (string[i]) ++i; return i; } void insertString(char source[], char str[], int position) { int i, strLength, sourceLength; int stringLength(char string[]); sourceLength = stringLength(source); strLength = stringLength(str); // First, move the "end" string to the end of the string. for (i = sourceLength; i >= position; i--) source[strLength + i] = source[i]; // Now we have the space for str, let's put it on source! for (i = 0; i < strLength; i++) source[position + i] = str[i]; } // We now write replaceString bool replaceString(char source[], char s1[], char s2[]) { void insertString(char source[], char str[], int position); void removeString(char source[], int start, int nChars); int findString(const char source[], const char search[]), start, nChars; start = findString(source,s1); nChars = stringLength(s1); if (start != -1) { removeString(source,start,nChars); insertString(source,s2,start); return true; } else return false; } int main(void) { bool replaceString(char source[], char s1[], char s2[]), stillFound; char text[] = "The chosen one the boy may be."; do { stillFound = replaceString(text,"o","0"); } while(stillFound == true); printf("%s\n", text); return 0; }
C
/* * client_actions.c * * Written By: * Naveed Ashfaq - #1003859559 * Yu Dong Feng - #1002587523 */ #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <unistd.h> #include <string.h> #include "client_actions.h" void print_intro() { printf("\n=== Welcome to the Multi-Party Text Conferencing App! ===\n\n"); printf("To get started, login to a server with your username and password.\n"); printf("\nAvailable commands:\n /login <username> <password> <server-ip> <server-port>\n"); printf("\nYou can use /quit to exit the program anytime\n\n"); } void print_commands() { printf("\nAvailable commands to communicate with the server:\n"); printf(" /logout\n"); printf(" /createsession <session_name>\n"); printf(" /joinsession <session_name>\n"); printf(" /leavesession [session_name]\n"); printf(" /list\n"); printf(" /all <message...>\n"); printf(" /msg <session_name> <message...>\n"); printf(" /invite <username> [session_name]\n"); printf(" /invitelist\n"); printf(" /inviteresponse <session_name> <yes/no>\n"); printf(" /help [command_name]\n"); printf("\nWhile in a session, simply type your message to send it to other users in your active session.\n"); printf("\nYou can use /quit to exit the program anytime\n\n"); } int parse_client_command(char *command) { if (command[0] != '/') return MESSAGE; if (!strcmp(command, "/login")) return LOGIN; else if (!strcmp(command, "/logout")) return EXIT; else if (!strcmp(command, "/joinsession")) return JOIN; else if (!strcmp(command, "/leavesession")) return LEAVE_SESS; else if (!strcmp(command, "/createsession")) return NEW_SESS; else if (!strcmp(command, "/list")) return QUERY; else if (!strcmp(command, "/help")) return HELP; else if (!strcmp(command, "/quit")) return -1; else if (!strcmp(command, "/msg")) return MESSAGE_SPEC; else if (!strcmp(command, "/all")) return MESSAGE_ALL; else if (!strcmp(command, "/invite")) return INVITE; else if (!strcmp(command, "/invitelist")) return INVITE_LIST; else if (!strcmp(command, "/inviteresponse")) return INVITE_RESP; else return MESSAGE; } void client_help(char *input) { char command[MAX_NAME]; int r = sscanf(input, "/help %s", command); if (r < 1) { print_commands(); } else { if (!strcmp(command, "/login")) { printf("\nUsage: /login <username> <password> <server-ip> <server-port>\n"); printf("<username>: your login username.\n"); printf("<password>: your login password.\n"); printf("<server-ip>: IP Address of the server to connect to, in dots and numbers notation.\n"); printf("<server-port>: Port number of server to connect to.\n"); printf("\nUse this command to login to the server.\n"); } else if (!strcmp(command, "/logout")) { printf("\nUsage: /logout\n"); printf("\nUse this command to logout from the server.\n"); printf("You will automatically leave any sessions you have joined.\n"); } else if (!strcmp(command, "/joinsession")) { printf("\nUsage: /joinsession <session_name>\n"); printf("<session_name>: name of session to join.\n"); printf("\nUse this command to join an existing session or to change your current active session.\n"); } else if (!strcmp(command, "/leavesession")) { printf("\nUsage: /leavesession [session_name]\n"); printf("[session_name]: (optional) name of session to leave.\n"); printf("\nUse this command to leave a session that you are a member of.\n"); printf("If [session_name] is omitted, you will leave your current active session.\n"); } else if (!strcmp(command, "/createsession")) { printf("\nUsage: /createsession <session_name>\n"); printf("<session_name>: name of session to create.\n"); printf("\nUse this command to create and join a new session.\n"); } else if (!strcmp(command, "/list")) { printf("\nUsage: /list\n"); printf("\nUse this command to view a list of currently online users, as well "); printf("as information about currently existing sessions and their members.\n"); } else if (!strcmp(command, "/help")) { printf("\nUsage: /help [command_name]\n"); printf("[command_name]: (optional) name of command for extended help.\n"); printf("\nUse this command to view in-depth usage info of a command.\n"); printf("If [command_name] is omitted, will list all the available commands and their usage.\n"); } else if (!strcmp(command, "/quit")) { printf("\nUsage: /quit\n"); printf("\nUse this command to quit the program.\n"); printf("You will automatically be logged out and leave any sessions you have joined.\n"); } else if (!strcmp(command, "/msg")) { printf("\nUsage: /msg <session_name> <message...>\n"); printf("<session_name>: name of session to send message to.\n"); printf("<message...>: the message to send.\n"); printf("\nUse this command to send a message to a session that you are a member of.\n"); printf("This allows you to send messages to sessions that you have joined without having to actively switch to them.\n"); } else if (!strcmp(command, "/all")) { printf("\nUsage: /all <message...>\n"); printf("<message...>: the message to send.\n"); printf("\nUse this command to send a message to all sessions that you are a member of.\n"); } else if (!strcmp(command, "/invite")) { printf("\nUsage: /invite <username> [session_name]\n"); printf("<username>: the user to invite.\n"); printf("[session_name]: (optional) the session to invite the user to.\n"); printf("\nUse this command to send an invite to a user to join a session that you are a member of.\n"); printf("If [session_name] is omitted, will send an invite for your currently active session.\n"); } else if (!strcmp(command, "/invitelist")) { printf("\nUsage: /invitelist\n"); printf("\nUse this command to view a list of all of your current invites.\n"); } else if (!strcmp(command, "/inviteresponse")) { printf("\nUsage: /inviteresponse <session_name> <yes/no>\n"); printf("<session_name>: the session invite you want to respond to.\n"); printf("<yes/no>: your response to the invite. 'yes' to accept, 'no' to decline.\n"); printf("\nUse this command to respond to an invite.\n"); } else { printf("'%s' is not a valid command.\nUse /help to view a list of available commands.\n", command); } printf("\n"); } } int client_login(char *input, Message *msg) { // Input format: /login <username> <password> <server-ip> <server-port> char username[MAX_NAME], password[MAX_NAME], server_ip[MAX_NAME]; int port_number; int r = sscanf(input, "/login %s %s %s %d", username, password, server_ip, &port_number); if (r < 4) { printf("Invalid usage of /login command.\nUsage: /login <username> <password> <server-ip> <server-port>\n"); return -1; } // Declare Variables int socketfd; struct sockaddr_in server_addr; socklen_t server_addr_len; server_addr_len = sizeof server_addr; port_number = htons(port_number); // Get port number in network format // Get socket socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd < 0) { printf("Error acquiring socket\n"); exit(1); } // Create the address struct for server memset(&server_addr, 0, server_addr_len); server_addr.sin_family = AF_INET; server_addr.sin_port = port_number; server_addr.sin_addr.s_addr = INADDR_ANY; inet_aton(server_ip, &server_addr.sin_addr); if (connect(socketfd, (struct sockaddr *) &server_addr, server_addr_len)) { printf("Error connecting to server"); return -1; } strcpy(msg->source, username); strcpy(msg->data, password); msg->size = strlen(password); return socketfd; } bool client_logout(char *input, Message *msg) { // Input format: /logout //if (close(socketfd)) { // printf("Error closing socket\n"); // exit(1); //} msg->size = 0; return true; } bool client_query(char *input, Message *msg) { // Input format: /list // Ignoring any text after the /list, this cannot have a usage error msg->size = 0; return true; } bool client_create_session(char *input, Message *msg) { // Input format: /createsession <sessionID> char session_name[MAX_NAME]; int r = sscanf(input, "/createsession %s", session_name); if (r < 1) { printf("Invalid usage of /createsession command.\nUsage: /createsession <sessionID>\n"); return false; } strcpy(msg->data, session_name); msg->size = strlen(session_name); return true; } bool client_join_session(char *input, Message *msg) { // Input format: /joinsession <sessionID> char session_name[MAX_NAME]; int r = sscanf(input, "/joinsession %s", session_name); if (r < 1) { printf("Invalid usage of /joinsession command.\nUsage: /joinsession <sessionID>\n"); return false; } strcpy(msg->data, session_name); msg->size = strlen(session_name); return true; } bool client_message(char *input, Message *msg) { // Input format: none int input_size = strlen(input); if (input_size > MAX_DATA) { printf("Message too large to send\n"); return false; } strcpy(msg->data, input); msg->size = input_size; return true; } bool client_message_specific(char *input, Message *msg) { // Input format: /msg <session_name> <message> char buf[MAX_NAME]; char message[MAX_DATA]; int r = sscanf(input, "/msg %s", buf); if (r < 1) { printf("Invalid usage of /msg command.\nUsage: /msg <session_name> <message>\n"); return false; } input += strlen("/msg "); extract_name_and_info(input, buf, message); int msg_size = strlen(message); if (msg_size == 0) { printf("Invalid usage of /msg command.\nUsage: /msg <session_name> <message>\n"); return false; } else if (msg_size + strlen(buf) + 1 > MAX_DATA) { printf("Message too large to send\n"); return false; } sprintf(msg->data, "%s %s", buf, message); msg->size = strlen(msg->data); return true; } bool client_message_all(char *input, Message *msg) { // Input format: /all <message> char buf[MAX_NAME]; char message[MAX_DATA]; extract_name_and_info(input, buf, message); int msg_size = strlen(message); if (msg_size == 0) { printf("Invalid usage of /all command.\nUsage: /all <message>\n"); return false; } else if (msg_size > MAX_DATA) { printf("Message too large to send\n"); return false; } strcpy(msg->data, message); msg->size = msg_size; return true; } bool client_invite(char *input, Message *msg) { // Input format: /invite <username> [session_name] char username[MAX_NAME], session_name[MAX_NAME]; int r = sscanf(input, "/invite %s %s", username, session_name); if (r < 1) { printf("Invalid usage of /invite command.\nUsage: /invite <username> [session_name]\n"); return false; } else if (r == 1) { // No inputted session name strcpy(msg->data, username); } else { sprintf(msg->data, "%s %s\0", username, session_name); } msg->size = strlen(msg->data); return true; } bool client_invite_list(char *input, Message *msg) { // Input format: /invitelist msg->size = 0; return true; } bool client_invite_response(char *input, Message *msg) { // Input format: /inviteresponse <session_name> <yes/no> char session_name[MAX_NAME], response[8]; int r = sscanf(input, "/inviteresponse %s %s", session_name, response); if (r < 2) { printf("Invalid usage of /inviteresponse command.\nUsage: /inviteresponse <session_name> <yes/no>\n"); return false; } if (strcmp(response, "yes") && strcmp(response, "no")) { printf("Please input your response as 'yes' to accept or 'no' to decline the invitation\n"); return false; } sprintf(msg->data, "%s %s\0", session_name, response); msg->size = strlen(msg->data); return true; } bool client_leave_session(char *input, Message *msg) { // Input format: /leavesession [session_name] char session_name[MAX_NAME]; int r = sscanf(input, "/leavesession %s", session_name); if (r < 1) { msg->size = 0; } else { strcpy(msg->data, session_name); msg->size = strlen(session_name); } return true; } void client_response(Message msg) { char name_buf[MAX_NAME], data_buf[MAX_DATA]; switch(msg.type) { case LO_ACK: printf("%s successfully logged in.\n", msg.source); print_commands(); break; case LO_NAK: printf("Could not log in %s.\nReason: %s\n", msg.source, msg.data); break; case QU_ACK: printf("\n%s", msg.data); break; case QU_NAK: printf("Could not successfully obtain query.\nReason: %s\n", msg.data); break; case NS_ACK: printf("Successfully created and joined session '%s'\n", msg.data); break; case NS_NAK: extract_name_and_info(msg.data, name_buf, data_buf); printf("Could not create session '%s'.\nReason: %s\n", name_buf, data_buf); break; case JN_ACK: { int is_new = 0; sscanf(msg.data, "%d %s", &is_new, name_buf); if (is_new) printf("Successfully joined and moved active session to '%s'\n", name_buf); else printf("Successfully moved active session to '%s'\n", name_buf); break; } case JN_NAK: extract_name_and_info(msg.data, name_buf, data_buf); printf("Could not join session '%s'.\nReason: %s\n", name_buf, data_buf); break; case NOTIFICATION: printf("\nSERVER NOTIFICATION => %s\n\n", msg.data); break; case MESSAGE: extract_name_and_info(msg.data, name_buf, data_buf); printf("[%s] %s: %s", name_buf, msg.source, data_buf); //printf("%s: %s", msg.source, msg.data); break; case MS_ACK: break; case MS_NAK: printf("Could not send message.\nReason: %s\n",msg.data); break; case INVITE: sscanf(msg.data, "%s %s", name_buf, data_buf); printf("\nYou have received an invite from %s to join the session %s\n", name_buf, data_buf); printf("Use the command /inviteresponse <session_name> <yes/no> to respond to the invite\n"); printf("Use the command /invitelist to view a list of all your invites.\n\n"); break; case INVITE_ACK: sscanf(msg.data, "%s %s", name_buf, data_buf); printf("Successfully sent an invite to %s to join the session %s\n", name_buf, data_buf); break; case INVITE_NAK: printf("Could not send invite.\nReason: %s\n", msg.data); break; case IL_ACK: printf("\n%s", msg.data); break; case IL_NAK: printf("Could not create invite list.\nReason: %s\n", msg.data); break; case IR_ACK: sscanf(msg.data, "%s %s", name_buf, data_buf); if (!strcmp(data_buf, "yes")) printf("You have accepted the invite and are now a member of %s\n", name_buf); else printf("You have declined the invite to join %s\n", name_buf); break; case IR_NAK: printf("Could not respond to invite.\nReason: %s\n", msg.data); break; case LV_ACK: { int r = sscanf(msg.data, "%s %s", name_buf, data_buf); printf("Successfully left session '%s'\n", name_buf); if (r > 1) printf("New active session is '%s'\n", data_buf); break; } case LV_NAK: printf("Could not leave session.\nReason: %s\n", msg.data); break; default: break; } } void extract_name_and_info(char *src, char *name, char *data) { char *s = src, *d = name; while (*s != ' ' && *s != '\0') *d++ = *s++; *d = '\0'; d = data; if (*s != '\0') s++; while (*s != '\0') *d++ = *s++; *d = '\0'; }
C
#include "unsigned_short_int_array.h" #include "unity.h" #include "unity_fixture.h" TEST_GROUP(UnsignedShortIntArrayTests); UnsignedShortIntArray unsignedShortIntArray; UnsignedShortIntArray otherUnsignedShortIntArray; TEST_SETUP(UnsignedShortIntArrayTests) { UnsignedShortIntArrayInitialize(&unsignedShortIntArray); UnsignedShortIntArrayInitialize(&otherUnsignedShortIntArray); } TEST_TEAR_DOWN(UnsignedShortIntArrayTests) { UnsignedShortIntArrayDeinitialize(&unsignedShortIntArray); UnsignedShortIntArrayDeinitialize(&otherUnsignedShortIntArray); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayInitialLength) { TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayInitialCapacity) { TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY, unsignedShortIntArray.capacity); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayInitializeFromEmptyPointer) { unsigned short int values[] = { }; int result = UnsignedShortIntArrayInitializeFromPointer(&unsignedShortIntArray, values, 0); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, UnsignedShortIntArrayCount(&unsignedShortIntArray)); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayInitializeFromPointer) { unsigned short int values[5] = { 1U, 2U, 3U, 4U, 5U }; int result = UnsignedShortIntArrayInitializeFromPointer(&unsignedShortIntArray, values, 5); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, UnsignedShortIntArrayCount(&unsignedShortIntArray)); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayPushOneElement) { int result = UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(1, unsignedShortIntArray.length); TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY, unsignedShortIntArray.capacity); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayPushCapacityPlusOneElements) { int result; for (size_t i = 0; i < GA_INITIAL_CAPACITY + 1; i++) { result = UnsignedShortIntArrayPush(&unsignedShortIntArray, (unsigned short int)i); TEST_ASSERT_EQUAL(GA_SUCCESS, result); } TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY + 1, unsignedShortIntArray.length); TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY * GA_CAPACITY_MULTIPLIER, unsignedShortIntArray.capacity); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayAtZeroLength) { unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayAtExistingElement) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(3U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayAtLessThanZeroIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, -2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayAtGreaterThanLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 5, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayAtLessThanNegativeLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, -6, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayClear) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayClear(&unsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayConcatEmptyArrays) { int result = UnsignedShortIntArrayConcat(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayConcatEmptyArrayToNonEmptyArray) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); int result = UnsignedShortIntArrayConcat(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayConcatNonEmptyArrayToEmptyArray) { UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 2U); int result = UnsignedShortIntArrayConcat(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayConcatNonEmptyArrayToNonEmptyArray) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 4U); int result = UnsignedShortIntArrayConcat(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(4U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayCountEmptyArray) { size_t result = UnsignedShortIntArrayCount(&unsignedShortIntArray); TEST_ASSERT_EQUAL(0, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayCountNonEmptyArray) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); size_t result = UnsignedShortIntArrayCount(&unsignedShortIntArray); TEST_ASSERT_EQUAL(2, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteFromEmptyArray) { int result = UnsignedShortIntArrayDelete(&unsignedShortIntArray, 1U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteNonExistingElement) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); int result = UnsignedShortIntArrayDelete(&unsignedShortIntArray, 3U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteExistingElement) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); int result = UnsignedShortIntArrayDelete(&unsignedShortIntArray, 2U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(1, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteAtZeroLength) { int result = UnsignedShortIntArrayDeleteAt(&unsignedShortIntArray, 0); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteAtExistingElement) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDeleteAt(&unsignedShortIntArray, 2); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteAtLessThanZeroIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDeleteAt(&unsignedShortIntArray, -2); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteAtGreaterThanLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDeleteAt(&unsignedShortIntArray, 5); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDeleteAtLessThanNegativeLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDeleteAt(&unsignedShortIntArray, -6); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDropOneEmptyArray) { int result = UnsignedShortIntArrayDrop(&unsignedShortIntArray, 1); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDropManyEmptyArray) { int result = UnsignedShortIntArrayDrop(&unsignedShortIntArray, 10); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDropLessThanArrayLength) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDrop(&unsignedShortIntArray, 3); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, unsignedShortIntArray.length); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayDropGreaterThanArrayLength) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayDrop(&unsignedShortIntArray, 6); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, unsignedShortIntArray.length); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayEmptyArrayIsEmpty) { int result = UnsignedShortIntArrayIsEmpty(&unsignedShortIntArray); TEST_ASSERT_EQUAL(1, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayNonEmptyArrayIsNotEmpty) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayIsEmpty(&unsignedShortIntArray); TEST_ASSERT_EQUAL(0, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayPush) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); TEST_ASSERT_EQUAL(5, unsignedShortIntArray.length); unsigned short int x; int result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(1U, x); result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2U, x); result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(3U, x); result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4U, x); result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayMultipleElementArrayToString) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); char* asString; int result = UnsignedShortIntArrayToString(&unsignedShortIntArray, &asString); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL_STRING("[1, 2, 3, 4, 5]", asString); free(asString); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySetZeroLength) { int result = UnsignedShortIntArraySet(&unsignedShortIntArray, 2, 5U); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySetExistingElement) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); int result = UnsignedShortIntArraySet(&unsignedShortIntArray, 2, 5U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); unsigned short int x; result = UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySetLessThanZeroIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); int result = UnsignedShortIntArraySet(&unsignedShortIntArray, -2, 5U); TEST_ASSERT_EQUAL(GA_SUCCESS, result); unsigned short int x; result = UnsignedShortIntArrayAt(&unsignedShortIntArray, -2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySetGreaterThanLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); int result = UnsignedShortIntArraySet(&unsignedShortIntArray, 4, 5U); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySetLessThanNegativeLengthIndex) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); int result = UnsignedShortIntArraySet(&unsignedShortIntArray, -5, 5U); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } int UnsignedShortIntAscendingCompare(const void *a, const void *b) { __GENERIC_ARRAY_TYPE__ f = *((__GENERIC_ARRAY_TYPE__*)a); __GENERIC_ARRAY_TYPE__ s = *((__GENERIC_ARRAY_TYPE__*)b); if (GENERIC_ARRAY_VALUES_GREATER_THAN(f, s)) { return 1; } if (GENERIC_ARRAY_VALUES_LESS_THAN(f, s)) { return -1; } return 0; } int UnsignedShortIntDescendingCompare(const void *a, const void *b) { __GENERIC_ARRAY_TYPE__ f = *((__GENERIC_ARRAY_TYPE__*)a); __GENERIC_ARRAY_TYPE__ s = *((__GENERIC_ARRAY_TYPE__*)b); if (GENERIC_ARRAY_VALUES_LESS_THAN(f, s)) { return 1; } if (GENERIC_ARRAY_VALUES_GREATER_THAN(f, s)) { return -1; } return 0; } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySortEmptyArray) { UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntAscendingCompare); TEST_ASSERT_EQUAL(0, UnsignedShortIntArrayCount(&unsignedShortIntArray)); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySortAscending) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntAscendingCompare); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArraySortDescending) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntDescendingCompare); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(5U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(1U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayOverlapEmptyArrays) { int result = UnsignedShortIntArrayOverlap(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, UnsignedShortIntArrayCount(&unsignedShortIntArray)); TEST_ASSERT_EQUAL(0, UnsignedShortIntArrayCount(&otherUnsignedShortIntArray)); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayOverlapNonEmptyArrayWithEmptyArray) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); int result = UnsignedShortIntArrayOverlap(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, UnsignedShortIntArrayCount(&unsignedShortIntArray)); TEST_ASSERT_EQUAL(0, UnsignedShortIntArrayCount(&otherUnsignedShortIntArray)); UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntAscendingCompare); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayOverlapEmptyArrayWithNonEmptyArray) { UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 5U); int result = UnsignedShortIntArrayOverlap(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, UnsignedShortIntArrayCount(&unsignedShortIntArray)); TEST_ASSERT_EQUAL(5, UnsignedShortIntArrayCount(&otherUnsignedShortIntArray)); UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntAscendingCompare); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(5U, x); } TEST(UnsignedShortIntArrayTests, UnsignedShortIntArrayOverlapNonEmptyArrays) { UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&unsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 1U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 2U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 3U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 4U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 5U); UnsignedShortIntArrayPush(&otherUnsignedShortIntArray, 5U); int result = UnsignedShortIntArrayOverlap(&unsignedShortIntArray, &otherUnsignedShortIntArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(10, UnsignedShortIntArrayCount(&unsignedShortIntArray)); TEST_ASSERT_EQUAL(8, UnsignedShortIntArrayCount(&otherUnsignedShortIntArray)); UnsignedShortIntArraySort(&unsignedShortIntArray, UnsignedShortIntAscendingCompare); unsigned short int x; UnsignedShortIntArrayAt(&unsignedShortIntArray, 0, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 1, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 2, &x); TEST_ASSERT_EQUAL(1U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 3, &x); TEST_ASSERT_EQUAL(2U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 4, &x); TEST_ASSERT_EQUAL(3U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 5, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 6, &x); TEST_ASSERT_EQUAL(4U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 7, &x); TEST_ASSERT_EQUAL(5U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 8, &x); TEST_ASSERT_EQUAL(5U, x); UnsignedShortIntArrayAt(&unsignedShortIntArray, 9, &x); TEST_ASSERT_EQUAL(5U, x); }
C
#include "param.h" #include "types.h" #include "stat.h" #include "user.h" #include "fs.h" #include "fcntl.h" #include "syscall.h" #include "traps.h" #include "memlayout.h" #include "tournament_tree.h" #include "kthread.h" #define STACK_SIZE 100 void trnmt_test(){ printf(1,"4 ttree starting\n"); trnmnt_tree* tree; int result; tree = trnmnt_tree_alloc(4); if(tree == 0){ printf(1,"4 ttree allocated unsuccessfully\n"); } result = trnmnt_tree_acquire(tree, 1); if(result < 0){ printf(1,"ttree locked unsuccessfully\n"); } result = trnmnt_tree_release(tree, 1); if(result < 0){ printf(1,"ttree unlocked unsuccessfully\n"); } result = trnmnt_tree_dealloc(tree); if(result == -1){ printf(1,"1 ttree deallocated unsuccessfully\n"); } printf(1,"ttree test and all good \n"); //kthread_exit(); } void func_for_thread1(void) { for (int i = 0; i <1000 ; ++i) { sleep(10); } kthread_exit(); } void func_for_thread2(void) { for (int i = 0; i <1000 ; ++i) { sleep(1); } kthread_exit(); } void thread_t1(){ void *stack_t1 = ((char *) malloc(STACK_SIZE * sizeof(char))) + STACK_SIZE; void (*start_t1)(void) = func_for_thread1; int t1_id = kthread_create(start_t1, stack_t1); if(t1_id == -1) { printf(1,"kthread_create func has failed\n"); return; } else { printf(1,"kthread_create func has succeeded \n"); } } void thread_t2(){ void *stack_t1 = ((char *) malloc(STACK_SIZE * sizeof(char))) + STACK_SIZE; void *stack_t2 = ((char *) malloc(STACK_SIZE * sizeof(char))) + STACK_SIZE; void (*start_t1)(void) = func_for_thread1; void (*start_t2)(void) = func_for_thread2; int t1_id = kthread_create(start_t1, stack_t1); kthread_join(t1_id); printf(1,"thread 1 finished, join is working \n"); int t2_id = kthread_create(start_t2, stack_t2); if(t1_id == -1||t2_id==-1) { printf(1,"kthread_create func has failed\n"); return; } else { printf(1,"kthread_create func has succeeded \n"); } } int main(){ printf(1,"sanity tests starting \n"); trnmt_test(); thread_t1(); thread_t2(); printf(1,"sanity tests ending \n"); exit(); }
C
#include <stdio.h> union test { struct { int part; char* moji: }; struct data_2 { int part; char* moji_moji; }; }; int main(void) { test_t test; test.data_1_t.part = 15; printf("%d\n",test.data_2_t.part); return 0; }
C
int factorial (int f) { int i; int res = 1; for (i = 0; i < f; i++) res *= i; return res }
C
/* ** EPITECH PROJECT, 2019 ** my_strncmp.c ** File description: ** strncmp */ int my_strncmp(char const *s1, char const *s2, int n) { int value = 0; for (int i = 0; s1[i] != s1[n] && s2[i] != s2[n]; i++) { if (s1[i] != s2[i]) { value = s1[i] - s2[i]; return (value); } } return (0); }
C
#include <stdio.h> #include <math.h> int ft_recursive_power(int nb, int power) { if (power < 0) return 0; if (power == 0) return 1; return (nb * ft_recursive_power(nb, power - 1)); } int main(void) { int num; int power; num = 5; power = 0; printf("Value 0 ^ 0 = %lf\n", pow(0.0, 0.0)); num = ft_recursive_power(num, power); printf("%d\n", num); return 0; }
C
#inlcude<stdio.h> #include<string.h> void main() { char s1[20],s2[20]; printf("Enter a string"); scanf("%s",&s1); s2=strrev(s1); printf("Rversed string is:%s",s2); }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> /* key_t, sem_t, pid_t */ #include <sys/shm.h> /* shmat(), IPC_RMID */ #include <errno.h> /* errno, ECHILD */ #include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */ #include <fcntl.h> /* O_CREAT, O_EXEC */ #include <unistd.h> #include <semaphore.h> #include <errno.h> #include <sys/types.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/fcntl.h> #include <sys/wait.h> //state 0: thinking ........ //state 1: hungry and waiting ........ //state 2: eating ....... sem_t *fork1red ,*fork2red ,*fork1gr ,*fork2gr ,*spoon1red ,*spoon2red ,*spoon1green, *spoon2green; int redfork=2 , greenfork=2 , redspoon=2,greenspoon=2; int value=1; void phillospher(int id ) { int state=0;//thinking...... while(1){ if(state==0){ printf("philosopher %d is thinking\n",id); state=1; sleep(2); printf("state is changed to 1.\n"); } else if(state==1){ printf("state 1 enters\n"); if(sem_trywait(fork1red)==0){ printf("inside redfork\n"); if(!sem_trywait(spoon1red)){ printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork1red); sem_post(spoon1red); state=0; // sleep(1); } else { sem_wait(spoon2red); printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork1red); sem_post(spoon2red); state=0; } } else if (sem_trywait(fork2red)==0) { printf("inside redfork2\n"); if(!sem_trywait(spoon1red)){ printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork2red); sem_post(spoon1red); state=0; } else { sem_wait(spoon2red); printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork2red); sem_post(spoon2red); state=0; } } else if(sem_trywait(fork1gr)==0) { printf("inside \n"); if(!sem_trywait(spoon2green)){ printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork1gr); sem_post(spoon2green); state=0; } else { sem_wait(spoon1green); printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork1gr); sem_post(spoon1green); state=0; } } else { sem_wait(fork2gr); printf("inside \n"); if(!sem_trywait(spoon2green)){ printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork2gr); sem_post(spoon2green); state=0; } else { sem_wait(spoon1green); printf("philosopher id=%d is eating\n", id); sleep(2); printf("philosopher id=%d has finished eating\n", id); sem_post(fork2gr); sem_post(spoon1green); state=0; } } } } } int main(){ sem_unlink ("pSemredfork1"); sem_close(fork1red); sem_unlink ("pSemredfork2"); sem_close(fork2red); sem_unlink ("pSemgreenfork1"); sem_close(fork1gr); sem_unlink ("pSemgreenfork2"); sem_close(fork2gr); sem_unlink ("pSemredspoon1"); sem_close(spoon1red); sem_unlink ("pSemredspoon2"); sem_close(spoon2red); sem_unlink ("pSemgreenspoon1"); sem_close(spoon1green); sem_unlink ("pSemgreenspoon2"); sem_close(spoon2green); int i; key_t shmkey; /* shared memory key */ int shmid; /* shared memory id */ /* synch semaphore *//*shared */ pid_t pid; /* fork pid */ int *p; /* shared variable *//*shared */ unsigned int n=5; /* fork count */ unsigned int value=1; /* semaphore value */ int status,ret; //printf ("shmkey for p = %d\n", shmkey); shmid = shmget (shmkey, sizeof (int), 0644 | IPC_CREAT); if (shmid < 0){ /* shared memory error check */ perror ("shmget\n"); exit (1); } p = (int *) shmat (shmid, NULL, 0); /* attach p to shared memory */ *p = 0; //printf ("p=%d is allocated in shared memory.\n\n", *p); fork1red = sem_open("pSemredfork1", O_CREAT , 0644, value); fork2red = sem_open("pSemredfork2", O_CREAT | O_EXCL, 0644, value); fork1gr = sem_open("pSemgreenfork1", O_CREAT | O_EXCL, 0644, value); fork2gr = sem_open("pSemgreenfork2", O_CREAT | O_EXCL, 0644, value); spoon1red = sem_open("pSemredspoon1", O_CREAT | O_EXCL, 0644, value); spoon2red = sem_open("pSemredspoon2", O_CREAT | O_EXCL, 0644, value); spoon1green = sem_open("pSemgreenspoon1", O_CREAT | O_EXCL, 0644, value); spoon2green = sem_open("pSemgreenspoon2", O_CREAT | O_EXCL, 0644, value); for (i=0;i<n;i++){ pid = fork (); if (pid < 0) { printf ("Fork error.\n"); } else if (pid == 0){ printf("child created...\n"); phillospher(i); break; } } while(waitpid(-1,NULL,0)!=-1);printf("all child destroyed\n"); /* if ((ret = waitpid (pid, &status, 0)) == -1) printf("parent:error\n"); */ return 0; }
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> typedef struct queue { struct queue* next; struct queue* prev; int value; } q; typedef struct HeadAndTail { struct queue* head; struct queue* tail; int size; } ht; ht* CreateQueue() { ht* creation = malloc(sizeof(ht)); creation->head = creation->tail = NULL; creation->size = 0; return creation; } void DestroyList(ht** list) { q* first = (*list)->head; q* buffer = NULL; while (first) { buffer = first->next; free(first); first = buffer; }; free(*list); (*list) = NULL; } void Write(ht* queue, int newvalue) { q* element = malloc(sizeof(q)); if (queue->size == 0) { void Write(ht* queue, int newvalue) { q* element = malloc(sizeof(q)); if (queue->size == 0) { queue->tail = queue->head = element; element->value = newvalue; element->prev = element->next = NULL; queue->size++; return; } element->prev = queue->tail; element->next = NULL; element->value = newvalue; queue->tail->next = element; queue->tail = element; queue->size++; } bool IsEmpty(ht* queue) { return (queue == NULL || queue->size == 0); } int Read(ht* queue) { if (IsEmpty(queue)) exit(1); return queue->head->value; } void DeleteElem(ht* queue) { if (IsEmpty(queue)) return; if (queue->size == 1) { free(queue->head); queue->head = queue->tail = NULL; queue->size = 0; return; }
C
#include "solucion.h" #include <stdio.h> #include <unistd.h> #include <sys/wait.h> int main(int argc, char** argv) { int x = 20; pid_t pid; pid=fork(); if (pid==0){ printf("soy el hijo\n calculo fibonacci de %d\n",x); printf("guardo el valor calculado en archivo 'archivo'\n"); printf("fibonacci(%d) = ",x); x = fibonacci(x); printf("%d\n",x); guardarEntero("archivo",x); } else { printf("soy el padre \n espero a que termine mi hijo\n"); wait(NULL); printf("fibonacci(%d)X100 =",x); x= leerEntero("archivo") * 100; printf ("%d\n",x); return 0; }
C
struct TrieNode { int val; struct TrieNode* next[26]; }; /** Initialize your data structure here. */ struct TrieNode* trieCreate(void) { struct TrieNode* t = calloc(1, sizeof(struct TrieNode)); } /** Inserts a word into the trie. */ void insert(struct TrieNode* root, char* word) { char* p = word; struct TrieNode* link; int x; link = root; while(p && *p) { x = *p - 'a'; if (!link->next[x]) { link->next[x] = trieCreate(); } link = link->next[x]; ++p; } link->val = 1; } /** Returns if the word is in the trie. */ bool search(struct TrieNode* root, char* word) { struct TrieNode* link = root; int x; char* p = word; while(p && *p) { x = *p - 'a'; if (!link->next[x]) return false; link = link->next[x]; ++p; } if (link->val == 1) return true; return false; } /** Returns if there is any word in the trie that starts with the given prefix. */ bool startsWith(struct TrieNode* root, char* prefix) { struct TrieNode* link = root; int x; char* p = prefix; while(p && *p) { x = *p - 'a'; if (!link->next[x]) return false; link = link->next[x]; ++p; } return true; } /** Deallocates memory previously allocated for the TrieNode. */ void trieFree(struct TrieNode* root) { } // Your Trie object will be instantiated and called as such: // struct TrieNode* node = trieCreate(); // insert(node, "somestring"); // search(node, "key"); // trieFree(node);
C
#include <stdio.h> int main(void) { int a = 10, b = 20; const int *pa = &a; // pa a Ų. printf(" a : %d\n", *pa); // ͸ Ͽ a pa = &b; // Ͱ b Ű Ѵ. printf(" b : %d\n", *pa); // ͸ Ͽ b a = 20; // a Ͽ ٲ۴. printf(" a : %d\n", *pa); // ͷ Ͽ ٲ return 0; }
C
/* * overflow.c * * Copyright (C) STMicroelectronics Limited 2003. All rights reserved. * * Queue thousands of distributed objects on a port and check that the * transports never loses a message it has committed to transmitting. * * NOTE: this test sends a I've finished message as part of its control * data. if the transport is losing messages this can cause the test to * lock up. */ #include "harness.h" #define TRACE(v) printf(MACHINE __FILE__ " (%d) - " #v " = %#010x\n", __LINE__, (unsigned) v) static EMBX_TRANSPORT transport; static EMBX_PORT inPort, outPort; #define NUM_BUFFERS 512 static void sendObjects(char *map) { int *buf; EMBX_HANDLE h; int i; EMBX_ERROR err; EMBX(Alloc(transport, NUM_BUFFERS, (void **) &buf)); EMBX(RegisterObject(transport, buf, NUM_BUFFERS, &h)); for (i=0; i<NUM_BUFFERS; i++) { err = EMBX_I(SendObject(outPort, h, i, 1)); assert(EMBX_SUCCESS == err || EMBX_NOMEM == err); map[i] = (err == EMBX_SUCCESS ? '-' : '#'); } map[NUM_BUFFERS] = '\0'; /* check that we really did overflow port capacity at some point */ assert('#' == map[NUM_BUFFERS-1]); while (EMBX_NOMEM == (err = EMBX_I(SendObject(outPort, h, 0, NUM_BUFFERS)))) { /* loop very fast (helps show we cannot break the memory interface) */ } assert(EMBX_SUCCESS == err); harness_sleep(1); harness_rendezvous(transport, inPort, outPort); EMBX(DeregisterObject(transport, h)); } static void receiveObjects(char *map) { EMBX_RECEIVE_EVENT event; memset(map, '#', NUM_BUFFERS); do { EMBX(ReceiveBlock(inPort, &event)); assert(EMBX_REC_OBJECT == event.type); if (1 == event.size) { map[event.offset] = '-'; } } while (1 == event.size); TRACE(event.size); assert(NUM_BUFFERS == event.size); map[NUM_BUFFERS] = '\0'; harness_sleep(1); harness_rendezvous(transport, inPort, outPort); } static void selfTest(void) { int *buf; EMBX_HANDLE h; int i; EMBX_ERROR err; EMBX_PORT in, out; char map[NUM_BUFFERS+1]; EMBX_RECEIVE_EVENT event; EMBX(CreatePort(transport, "local"LOCAL, &in)); EMBX(Connect(transport, "local"LOCAL, &out)); EMBX(Alloc(transport, NUM_BUFFERS, (void **) &buf)); EMBX(RegisterObject(transport, buf, NUM_BUFFERS, &h)); for (i=0; i<NUM_BUFFERS; i++) { err = EMBX_I(SendObject(out, h, i, 1)); assert(EMBX_SUCCESS == err || EMBX_NOMEM == err); map[i] = (EMBX_SUCCESS == err ? '-' : '#'); } map[NUM_BUFFERS] = '\0'; printf(MACHINE"loopback map\n%s\n", map); for (i=0; i<NUM_BUFFERS; i++) { if ('-' == map[i]) { EMBX(Receive(in, &event)); assert(EMBX_REC_OBJECT == event.type); assert(1 == event.size); assert(i == event.offset); } } /* prove there are no further messages */ EMBX_E(EMBX_INVALID_STATUS, Receive(in, &event)); EMBX(ClosePort(in)); EMBX(ClosePort(out)); } static void runTests(void) { EMBX_VOID *buffer; EMBX_RECEIVE_EVENT event; char sendMap[NUM_BUFFERS+4]; char recvMap[NUM_BUFFERS+4]; /* the master sends a vast number of messages while the slave waits */ SLAVE (harness_sleep(5)); MASTER(printf(MACHINE "(1) started sending\n")); MASTER(sendObjects(sendMap)); SLAVE (printf(MACHINE "(2) started receiving\n")); SLAVE (receiveObjects(recvMap)); MASTER(printf(MACHINE "(3) finished sending\n")); SLAVE (printf(MACHINE "(4) finished receiving\n")); MASTER(harness_sleep(5)); SLAVE (printf(MACHINE "(5) started sending\n")); SLAVE (sendObjects(sendMap)); MASTER(printf(MACHINE "(6) started receiving\n")); MASTER(receiveObjects(recvMap)); SLAVE (printf(MACHINE "(7) finished sending\n")); MASTER(printf(MACHINE "(8) finished receiving\n")); /* now swap the receive maps with our partner */ EMBX(Alloc(transport, sizeof(recvMap), &buffer)); memcpy(buffer, recvMap, sizeof(recvMap)); EMBX(SendMessage(outPort, buffer, sizeof(recvMap))); EMBX(ReceiveBlock(inPort, &event)); assert(EMBX_REC_MESSAGE == event.type); assert(sizeof(recvMap) == event.size); buffer = event.data; memcpy(recvMap, buffer, sizeof(recvMap)); EMBX(Free(buffer)); /* finally check that the messages received by our partner match * those that we transmitted */ SLAVE(harness_sleep(2)); printf(MACHINE "send map\n%s\n" MACHINE "receive map\n%s\n", sendMap, recvMap); assert(0 == strcmp(sendMap, recvMap)); selfTest(); } int main() { /* boot and connect */ harness_boot(); transport = harness_openTransport(); harness_connect(transport, "overflow", &inPort, &outPort); runTests(); /* tidy up and close down */ EMBX(ClosePort(inPort)); EMBX(ClosePort(outPort)); MASTER(harness_passed()); SLAVE (harness_waitForShutdown()); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *input_file; char line[1024]; double cv, dv, e, t, b, cv_from_file; // double integral, derivada; int st; int num_time_lags; int num_lines; int i, j; int num_train_samples, num_inputs; double *input; if (argc != 3) { fprintf(stderr, "Use: %s arquivoPID janelaTempo\n", argv[0]); exit(1); } num_time_lags = atoi(argv[2]); input_file = fopen(argv[1], "r"); // Count samples num_lines = 0; while (fgets(line, 1023, input_file) != NULL) num_lines++; rewind(input_file); // number of training pairs, number of inputs, number of outputs // // number of training pairs: num_lines - num_time_lags // number of inputs: (trottle, brake, cv) * num_time_lags = 3 itens * num_time_lags // number of outputs: 1 (predicted v) num_train_samples = num_lines - num_time_lags; num_inputs = num_time_lags * 3; printf("%d %d %d\n", num_train_samples, num_inputs, 1); input = (double *) malloc(num_inputs * sizeof(double)); i = 0; while (fgets(line, 1023, input_file) != NULL) { // VELOCITY (st, cv, dv, e, t, b): 0, 0.008662, 0.000000, -0.008662, 0.000000, 100.000000 // VELOCITY (st, cv, dv, e, i, d, t, b): 0, 0.058467, 0.000000, -0.058467, 0.000000, -1.465864, 0.000000, 50.000000 sscanf(line, "VELOCITY (st, cv, dv, e, t, b): %d, %lf, %lf, %lf, %lf, %lf", &st, &cv, &dv, &e, &t, &b); // sscanf(line, "VELOCITY (st, cv, dv, e, i, d, t, b): %d, %lf, %lf, %lf, %lf, %lf, %lf, %lf", &st, &cv, &dv, &e, &integral, &derivada, &t, &b); if (i >= num_inputs) { for (j = 0; j < num_inputs; j++) printf("%lf ", input[j]); printf(" %lf\n", cv); for (j = 0; j < (num_inputs - 3); j++) { input[j] = input[j + 3]; } input[num_inputs - 3] = t / 100.0; input[num_inputs - 2] = b / 100.0; input[num_inputs - 1] = cv / 5.0; } else { input[i++] = t / 100.0; input[i++] = b / 100.0; input[i++] = cv / 5.0; } } return (0); }
C
/************************************************************************* > File Name: test_execv.c > Author: > Mail: > Created Time: Tue 28 Jul 2015 09:54:15 AM CST ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<errno.h> int main(void) { int ret; printf("entering main process----\n"); char *argv[] = {"ls","-l","/home",NULL}; // ret = execv("/bin/ls",argv); ret = execvp("ls",argv); if(ret == -1) { perror("execvp error"); } printf("exiting main process-----\n"); return 0; }
C
#define bsize 8 const char *algorithms[5] = {"Classic", "Blocked", "SGEMM CBLAS", "SGEMM CUBLAS", "Strassen+CUBLAS"}; void StrassenAlgorithm(float *A, float *B, float *C, long nelem, long n, int depth, int nstop, cublasHandle_t &handle); void errChkCUBLAS(cublasStatus_t s, const char *msg){ if(s != CUBLAS_STATUS_SUCCESS){ printf("[CUBLAS] %s failed\n", msg); exit(EXIT_FAILURE); } } int getMove(){ int ret = 0, sup=MATRIX_WIDTH; while(sup/2>=2){ sup= sup/2; ret++; } return ret; } // print matrix in 2D visual form void printMatrix(float *M, int n, const char *msg){ if(n > PRINT_LIMIT){ return; } printf("%s:\n", msg); for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ long index = i*n + j; printf("%.1f ", M[index]); } printf("\n"); } printf("\n"); } // fill matrix with sequence of 0,1,2,3,4 numbers void fillElements(float *M, int n, float arg){ for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ long index = i*n + j; M[index] = (float)rand()/RAND_MAX; //M[index] = (i + j + 1)%5 +arg; } } } void constMatrix(float *M, int n, const int val){ for(long i = 0; i < (long)(n*n); ++i){ M[i] = val; } } // C = A + B void AddMatrix(float *A, float *B, float *C, int size){ //#pragma omp parallel //{ for(int i = 0; i < size; ++i){ C[i] = A[i] + B[i]; } //} } // C = A - B void SubMatrix(float *A, float *B, float *C, int size){ //#pragma omp parallel //{ for(int i = 0; i < size; ++i){ C[i] = A[i] - B[i]; } //} } // C = A x B void TrasposeMatrix(float *M, float *bt, int n){ for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ bt[n*j + i] = M[n* i + j]; } } } bool VerifyResults(float *C, float *goldC, int n){ for(int i = 0; i < n; ++i){ for(int j = 0; j < n; ++j){ long index = i*n + j; if(fabs(goldC[index] - C[index])/goldC[index] > TOLERANCE){ #ifdef DEBUG fprintf(stderr, "Verify: error at C[i=%i, j=%i] = %f != goldC[i=%i, j=%i] = %f\n", i, j, C[index], i, j, goldC[index]); #endif return false; } } } return true; } double MatmulBasic(float *A, float *B, float *C, int n){ double t1, t2; t1 = omp_get_wtime(); #pragma omp parallel for for (int i = 0; i < n; ++i){ for (int j = 0; j < n; ++j){ float acc=0; unsigned long q = n*i + j; for (int k = 0; k < n; ++k){ acc += A[n*i + k] * B[n*k + j]; } C[q] = acc; } } t2 = omp_get_wtime(); return t2-t1; } double MatmulBlock(float *A, float *B, float *C, int n){ double t1, t2; //#pragma omp for //printf("HERE BLOCK MATMUL"); int num = n/bsize; float *bt = (float *)malloc(n*n*sizeof(float)); //printMatrix(B, n, "B"); TrasposeMatrix(B, bt, n); //printMatrix(bt, n, "bt"); //printf("HERE READY FOR BLOCK\n"); t1 = omp_get_wtime(); for (int i = 0; i < num; ++i){ for (int j = 0; j < num; ++j){ for (int k = 0; k < bsize; ++k){ for (int m = 0; m < bsize; ++m){ double sum = 0.0; for (int r = 0; r < num; r++){ for (int p = 0; p < bsize; ++p){ //int i1 = i*bsize*n + r*bsize + k*n + p; //int i2 = j*bsize*n + r*bsize*n + m + p*n; //printf("I1: %i I2: %i\n",i1,i2); //printf(" %i %i %i %i %i %i %i %i %i %i \n",i,j,k,m,r,p,n,bsize,i1,i2); //sum+=a[i*bsize*n + r*bsize + k*n + p]*b[j*bsize + r*bsize*n + m + p*n]; sum+=A[i*bsize*n + r*bsize + k*n + p]*bt[j*bsize*n + r*bsize + m*n + p]; //printf("HERE\n"); } } C[i*bsize*n + j*bsize + k*n + m] = sum; } } } } //printf("HERE ENDED BLOCK\n"); t2 = omp_get_wtime(); free(bt); return t2-t1; } double MatmulCBLAS(float *A, float *B, float *C, long n){ double t1, t2; t1 = omp_get_wtime(); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, n, n, n, 1.0, A, n, B, n, 0, C, n); t2 = omp_get_wtime(); return t2-t1; } double MatmulStrassenGPU(float *A, float *B, float *C, long n, long nstop, cublasHandle_t &handle){ double t1, t2; t1 = omp_get_wtime(); #pragma omp parallel { #pragma omp single { StrassenAlgorithm(A, B, C, n*n, n, 0, nstop, handle); } } t2 = omp_get_wtime(); return t2-t1; } double MatmulCUBLAS(float *hA, float *hB, float *hC, long n, float *alpha, float *beta, cublasHandle_t &handle){ double t1, t2; float *dA, *dB, *dC; long nelem = n*n; cublasStatus_t stat; cudaMalloc((void**)&dA, nelem*sizeof(*hA)); cudaMalloc((void**)&dB, nelem*sizeof(*hB)); cudaMalloc((void**)&dC, nelem*sizeof(*hC)); stat = cublasSetMatrix(n, n, sizeof(*hA), hA, n, dA, n); errChkCUBLAS(stat, "MatmulCUBLAS cublasSetMatrix hA -> dA"); stat = cublasSetMatrix(n, n, sizeof(*hB), hB, n, dB, n); errChkCUBLAS(stat, "MatmulCUBLAS cublasSetMatrix hB -> dB"); stat = cublasSetMatrix(n, n, sizeof(*hC), hC, n, dC, n); errChkCUBLAS(stat, "MatmulCUBLAS cublasSetMatrix hC -> dC"); t1 = omp_get_wtime(); //stat = cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, n, alpha, dB, n, dA, n, beta, dC, n); stat = cublasGemmEx(handle, CUBLAS_OP_N, CUBLAS_OP_N, n, n, n, alpha, dB, CUDA_R_32F, n, dA, CUDA_R_32F, n, beta, dC, CUDA_R_32F, n, CUDA_R_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP); cudaDeviceSynchronize(); t2 = omp_get_wtime(); errChkCUBLAS(stat, "MatmulCUBLAS GemmEx"); //stat = cublasGetMatrix(n, n, sizeof(*hC), dC, n, hC, n); stat = cublasGetVector(nelem, sizeof(*hC), dC, 1, hC, 1); errChkCUBLAS(stat, "MatmulCUBLAS cublas copy dC -> hC"); return t2-t1; }
C
#include <stdio.h> int main() { char ar[] = "Pointer"; char *pi1, *pi2; pi1 = &ar[0]; pi2 = &ar[5]; printf("%c %c Ÿ %dԴϴ\n", *pi1, *pi2, pi2 - pi1); // P e Ÿ 5Դϴ return 0; } /* ͳ ȵ ϴ. ͳ ּҰ+ּҰ ̱ . ǹ̾ (Ϲ) Ͱ 迭 ٸ ҿ Ű ǹ̰ ִ. */
C
/* * /sys/regexps.h * Some useful regular expressions */ #ifndef _sys_regexps_h_ #define _sys_regexps_h_ /* * The following macros define the regular expression that define the view * of some frequent strings you might want to check for. * Example: if (IS_REGEXP(x,REGEXP_FLOAT)) write("It is a float!\n"); */ #define IS_REGEXP(proband,rgxp) sizeof(regexp(({ proband }),"^"+(rgxp)+"$")) #define REGEXP_OK(rgxp) (!!with_player(0,(#'regexp),({ ({ "" }),rgxp }))) // this is useful to quote any string to be interpreted literally by the // regexp functions #define QUOTE_FOR_REGEXP(str) regreplace(str,"([()[\\].*^$|\\\\])","\\\\\\1",1) // this does the same for single characters appearing between [ and ] #define QUOTE_CHARS_FOR_REGEXP(str) \ regreplace(regreplace(str,"\\]","\\]",1),"([^-])-(..*)","\\1\\2-",1) #define REGEXP_PLUS_MINUS_OR_NOT "([+-]|)" #define REGEXP_PERIOD "\\." #define REGEXP_PERIOD_OR_NOT "("REGEXP_PERIOD"|)" #define REGEXP_UNSIGNED_INT_OR_NOT "[0-9]*" #define REGEXP_UNSIGNED_INT "[0-9]"REGEXP_UNSIGNED_INT_OR_NOT #define REGEXP_INT REGEXP_PLUS_MINUS_OR_NOT\ REGEXP_UNSIGNED_INT #define REGEXP_MANTISSE REGEXP_PLUS_MINUS_OR_NOT\ "("\ "("\ REGEXP_UNSIGNED_INT\ REGEXP_PERIOD_OR_NOT\ REGEXP_UNSIGNED_INT_OR_NOT\ ")"\ "|"\ "("\ REGEXP_PERIOD\ REGEXP_UNSIGNED_INT\ ")"\ ")" #define REGEXP_FLOAT REGEXP_MANTISSE\ "("\ "[eE]"\ REGEXP_INT\ "|"\ ""\ ")" // the following has a bug. it does not recognize #define REGEXP_COMMENT_1 "/\\*"\ "("\ "(\\**[^/])*"\ "|"\ "[^*]*"\ ")"\ "\\**\\*/" #define REGEXP_COMMENT_2 "//[^\n]*\n" #define REGEXP_COMMENT "("\ REGEXP_COMMENT_1\ ")"\ "|"\ "("\ REGEXP_COMMENT_2\ ")" #define REGEXP_INNER_STRING "("\ "[^\"\\\\]"\ "|"\ "\\\\."\ ")*" #define REGEXP_STRING "\"" REGEXP_INNER_STRING "\"" #define REGEXP_INNER_CHAR "[^\'\\\\]"\ "|"\ "\\\\." #define REGEXP_CHAR "\'(" REGEXP_INNER_CHAR ")\'" #define REGEXP_PREP "\n#[^\n]*[^\\\\]\n" // preprocessor directive lines #define REGEXP_COMMENT_OR_STRING\ REGEXP_COMMENT\ "|"\ REGEXP_STRING #define REGEXP_COMMENT_OR_STRING_OR_CHAR\ REGEXP_COMMENT_OR_STRING\ "|"\ REGEXP_CHAR #define REGEXP_HEXDIGIT "[0-9a-zA-Z]" #define REGEXP_HEXDIGIT_OR_NOT "(" REGEXP_HEXDIGIT "|)" #define REGEXP_OCTDIGIT "[0-7]" #define REGEXP_OCTDIGIT_OR_NOT "(" REGEXP_OCTDIGIT "|)" #define REGEXP_QUOTED "\\\\"\ "("\ "[^x0-9]"\ "|"\ "x" REGEXP_HEXDIGIT REGEXP_HEXDIGIT_OR_NOT\ "|"\ REGEXP_OCTDIGIT REGEXP_OCTDIGIT_OR_NOT\ REGEXP_OCTDIGIT_OR_NOT\ ")" #define REGEXP_SENTENCE_END "[\\.!?]" /* * The following macro is to get all names from a list of names, no matter * how that list is separated (using commas, periods, spaces or whatever). * Example: * REGEXPLODE_LIST("rump rump fred") --> ({ "rump","rump","fred" }), * REGEXPLODE_LIST("rump ,rump, and fred") --> ({ "rump","rump","fred" }), * REGEXPLODE_LIST(" , rump, and fred..") --> ({ "","rump","fred","" }), * REGEXPLODE_LIST("") --> ({ "" }), * so you might want to subtract all empty strings from the result before * you process it. */ #define REGEXPLODE_LIST(input) (split_array(({ "" })+regexplode(input,\ REGEXP_SEPARATOR_OR_AND),2)[1]) #define REGEXP_SEPARATOR_OR_NOT "[ .,;|\t\n]*" #define REGEXP_SEPARATOR "[ .,;|\t\n]" REGEXP_SEPARATOR_OR_NOT #define REGEXP_SEPARATOR_OR_AND "("\ "("\ REGEXP_SEPARATOR\ "and"\ REGEXP_SEPARATOR\ ")"\ "|"\ REGEXP_SEPARATOR\ ")" #define REGEXP_CTIME "(Mon|Tue|Wed|Thu|Fri|Sat|Sun)"\ " (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"\ " [1-3 ][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]"\ " [1-2][0-9][0-9][0-9]" #define REGEXP_LETTER \ "a-zA-ZäâæÀÃÆÇéËÈïîÌñòÖÒÕßúÙý #define REGEXP_PARSER_WORD \ "["REGEXP_LETTER"0-9][-"REGEXP_LETTER"0-9'_]*["REGEXP_LETTER"0-9]|[^ \t\n]" #define REGEXP_TERMINAL_COLOUR_TOKEN "%\\^([^%]|(%%*[^%^]))*%%*\\^" #endif // _sys_regexps_h_
C
#include "../include/line.h" int main(int argc, char** argv) { char lines[argc+1][255]; predealLine(argc, argv, lines); char* filename = lines[1]; char* findstr = lines[2]; char fileline[1024]; int linecnt = 1; FILE *src = fopen(filename, "r"); while(!feof(src)) { fgets(fileline, 1024, src); if(feof(src)) { break; } if(strstr(fileline, findstr) != NULL) { printf("[%d]%s", linecnt, fileline); } linecnt++; } printf("\n"); return 0; }
C
#include <stdio.h> int main() { setbuf(stdout, NULL); int a, b; printf("Enter A value: "); printf("\n"); fflush(stdout); /**/ scanf("%d", &a); printf("Enter B value: "); printf("\n"); fflush(stdout); /**/ scanf("%d", &b); if (a % b == 0) { printf("divisible"); printf("\n"); fflush(stdout); /**/ } else { printf("not divisible"); printf("\n"); fflush(stdout); /**/ } }
C
#include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include <stdlib.h> #include "myCLib.h" uint8_t simple_function(void) { static int counter = 0; counter++; return counter; } uint8_t add_one(uint8_t value) { return value + 1; } void add_one_to_string(char *input) { printf("Input string: %s\n", input); for (int ii = 0; ii < strlen(input); ii++) { input[ii]++; } printf("Output string: %s\n", input); }
C
#include"look.h" void look_same_tip(pSword pshead) { printf("sum:%d\n",pshead->num); //遍历每个相同单词 pSword ptmp = pshead; int ftmp = 0; while(ptmp->next!=pshead) { if(ptmp->next->file_no!=ftmp) { printf("(%d;%d;",ptmp->next->file_no,ptmp->next->num+1); ftmp=ptmp->next->file_no; } printf("<%d>",ptmp->next->where); ptmp = ptmp->next; if(ftmp!=ptmp->next->file_no) printf(") "); } printf("\n"); } void look_word(pWord look_last,char *p) { pWord ptmp = look_last;//遍历所有不同单词,查找是否有相同 while(ptmp->next!=look_last) { if(strcmp(ptmp->next->wsave,p)==0) { printf("word found!\n"); look_same_tip(ptmp->next->same_words); return ; } ptmp = ptmp->next; } printf("not found this word!\n"); } void look_second(pSec plook_sec,char *p) { int i; for(i=0;i<13;i++) { if(i==char_deal_again(p[0])) { look_word(plook_sec->dword[i],p); return ; } } } void look(pFirst pfirst) { printf("please input word.\n"); char lname[20]; scanf("%s",lname); int i; for(i=0;i<4;i++) { if(i==char_deal(lname[0])) { look_second(pfirst->dsecond[i],lname); return ; } } }
C
#include <stdio.h> #define MAX_N 100 #define MAX_M 500 typedef struct{ int A[MAX_N][MAX_M]; int n,m; }Graph; void init_graph(Graph *G,int n,int m){ G->m=m; G->n=n; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ G->A[i][j]=0; } } } void add_edge(Graph *G,int e,int x,int y){ G->A[x][e]=1; G->A[y][e]=-1; } int degree(Graph *G,int x){ int deg=0; for(int i=1;i<= G->m;i++){ if(G->A[x][i]==1) deg++; } return deg; } int main(){ Graph G; int n,m,v,u,w,e,i,x; scanf("%d",&n); scanf("%d",&m); init_graph(&G,n,m); for(e=1;e<=m;e++){ scanf("%d%d",&u,&v); add_edge(&G,e,u,v); } w=0; for(i=1;i<=n;i++){ if(degree(&G,i)>w){ w=degree(&G,i); x=i; } } printf("%d has sent %d email(s).",x,w); }
C
#include "sort.h" /** * partition - set the pivot of the sub sort for the Lomuto algorithm * @array: an array of integers * @size: size of the array * @left: first index in the array to sort * @right: the last index in the array to sort * * Return: No value returned. */ int partition(int *array, size_t size, int left, int right) { int *pivot; int below, above, temp; pivot = array + right; below = above = left; for (; below < right; below++) { if (array[below] < *pivot) { if (above < below) { /* swap elements */ temp = array[below]; array[below] = array[above]; array[above] = temp; print_array(array, size); } above++; /* above */ } } if (array[above] > *pivot) { temp = array[above]; array[above] = *pivot; *pivot = temp; print_array(array, size); } return (above); } /** * lomuto_sub_sort - sub sort using Lomuto algorithm * @array: an array of integers * @size: size of the array * @lo: the first index in the array to sort * @hi: the last index in the array to sort * * Return: No value returned. */ void lomuto_sub_sort(int *array, size_t size, int lo, int hi) { int pivot; if (lo < hi) { pivot = partition(array, size, lo, hi); lomuto_sub_sort(array, size, lo, pivot - 1); lomuto_sub_sort(array, size, pivot + 1, hi); } } /** * quick_sort_hoare - Quick sort using the Hoare Partition scheme * @array: an array of integers * @size: size of the array * * Return: No value returned. */ void quick_sort_hoare(int *array, size_t size) { int lo, hi; lo = 0; hi = (int)size - 1; if (array == NULL || size < 2) return; lomuto_sub_sort(array, size, lo, hi); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<malloc.h> #include<conio.h> #define MaxVertexNum 100//󶥵Ϊ100 #define N 4000 //涨ĸߴΪ40000 struct close { int adjvex; int lowcost; }; struct close closedge[MaxVertexNum]; typedef char VertexType;//Ϊַ typedef int EdgeType;//ߵȨֵΪ typedef struct { VertexType vexs[MaxVertexNum];// EdgeType edges[MaxVertexNum][MaxVertexNum];//ڽӾ󣬼߱ int n,e;//ͱ }MGraph;//MGraphڽӾ洢ͼ void CreateMGraph(MGraph *G) { int i,j,k,quan; printf("붥ͱʽΪ<ո>\n"); scanf("%d%d",&(G->n),&(G->e));//붥ͱ printf("붥ϢʽΪ<س>\n"); fflush(stdin); for(i=0;i<G->n;i++) { scanf("\n%c",&(G->vexs[i]));//붥ϢϢ } printf("ĶϢΪ\n"); for(i=0;i<G->n;i++) printf("%5c",G->vexs[i]); printf("\n"); fflush(stdin); for(i=0;i<G->n;i++) for(j=0;j<G->n;j++) { if(i==j) G->edges[i][j]=0; else G->edges[i][j]=N;//ʼڽӾ } printf("ÿ߶Ӧ(ʽΪ)ʼ,ֹ,Ȩֵ\n"); for(k=0;k<G->e;k++) { scanf("%d,%d,%d",&i,&j,&quan);//eߣڽӾ G->edges[i][j]=quan; G->edges[j][i]=quan; } } void Prim02(MGraph g,int v) { int lowcost[N]; int closest[N],i,j,k; int min; for(i=0;i<g.n;i++) { lowcost[i]=g.edges[v][i]; closest[i]=v; } for(i=0;i<g.n;i++) printf("%5d",lowcost[i]); printf("\n"); for(i=1;i<g.n;i++) { min=N; for(j=0;j<g.n;j++) { if(lowcost[j] != 0 && lowcost[j]<min) { min=lowcost[j]; k=j; } } printf("ߣ%d%dȨֵΪ%d\n",closest[k],k,min); lowcost[k]=0; for(j=0;j<g.n;j++) { if(g.edges[k][j]!=0 && g.edges[k][j]<lowcost[j]) { lowcost[j]=g.edges[k][j]; closest[j]=k; } } } } int main() { MGraph G; int ii,ij; CreateMGraph(&G); printf("ĶΪ\n"); for(ii=0;ii<G.n;ii++) { printf("%c\n",G.vexs[ii]); } printf("\nڽӾΪ\n"); for(ii=0;ii<G.n;ii++) { for(ij=0;ij<G.n;ij++) printf("%5d",G.edges[ii][ij]); printf("\n"); } Prim02(G,0); }
C
/** * @file VS1053.c * @brief code for the SABT audio codec * @author Nick LaGrow (nlagrow) * @author Alex Etling (petling) * @author Kory Stiger (kstiger) */ #include "globals.h" #include "io.h" #include "audio.h" // The volume is controlled by 2 bytes - the MSB controls the left // audio channel and the LSB controls the right audio channel // Needs to be masked, bitshifted and assigned for proper volume control // Note that 0x00 is the highest volume, 0xFE is the lowest volume for a // channel #define VOL_INIT 0x18 #define VOL_MIN 0x50 // Set based on testing #define VOL_INCR 0x08 #define CHANGE_VOLUME(X) ((X) | (X) << 8) #define CURRENT_VOLUME(X) (X & 0xFF) static uint8_t mono_volume; static uint16_t stereo_volume; // TODO find more descriptive variable names volatile unsigned int temp1 = 0; volatile unsigned int temp2 = 0; volatile unsigned int temp3 = 0; volatile unsigned char temp4; volatile unsigned char temp5; volatile unsigned char temp_address; /** * @brief initialize the audio codec * @return unsigned char - return 0 on success * return 1 if not written properly to 0x03 * return 2 if not written properly to 0x0B * return 3 if not written properly to 0x0b * return 4 if not written properly to 0x00 */ unsigned char vs1053_initialize(void) { unsigned char retry; spi_deselect_all(); SPI_PORT &= ~_BV(MP3_RESET); // De assert RESET line (Chip in the reset state) _delay_ms(20); // Hold for 20ms SPI_PORT |= _BV(MP3_RESET); // Assert RESET line (Chip is powered now) spi_1x(); // Low speed mode _delay_ms(20); // Hold for 20ms retry = 0; while (vs1053_read_command(0x03) != 0x9800) { //REDO if not written properly // Set PLL register to 3.5 (preferred for normal operation) vs1053_write_command(0x03,0x9800); if (retry++ > 10) return 1; // try this 10 times } _delay_ms(20); retry = 0; while (vs1053_read_command(0x0B) != 0xFEFE) { // REDO if not written properly vs1053_write_command(0x0B, 0xfefe); // Total silence if (retry++ > 10) return 2; } vs1053_write_command(0x05, 0xac45); // Activate sample rate as 44.1kHz stereo retry = 0; mono_volume = VOL_INIT; stereo_volume = CHANGE_VOLUME(VOL_INIT); while (vs1053_read_command(0x0b) != stereo_volume) { // REDO if not written properly vs1053_write_command(0x0b, stereo_volume); // Set volume to a midrange value if (retry++ > 10) return 3; // try this for 10 times } retry = 0; while (vs1053_read_command(0x00) != 0x0800) { // REDO if not written properly vs1053_write_command(0x00, 0x0800); // Set mode reg to SDINEW mode and MICIN if (retry++ > 10 ) return 4; // try this for 10 times } _delay_ms(20); vs1053_software_reset(); spi_2x(); return 0; } void vs1053_software_reset(void) { vs1053_write_command(0x00, 0x0804); // Software reset via mode register _delay_ms(20); } /** * @brief this changes the sound files to make the volume go up. * Volume works in reverse for VS1053 - so 0 is hi and FEFE is low * @ref https://www.sparkfun.com/datasheets/Components/SMD/vs1053.pdf, look * on page 47 * @return bool - did sound file change properly */ bool vs1053_increase_vol(void) { int retry = 0; // Increase the global volume setting mono_volume = mono_volume - VOL_INCR; // Check for max volume we are allowing //mono_volume is an unsigned, so if you go belove 0, wraps around to high positive if (mono_volume <= VOL_INCR) mono_volume = VOL_INCR; stereo_volume = CHANGE_VOLUME(mono_volume); // Actually increase the volume while (vs1053_read_command(0x0B) != stereo_volume) { // REDO if not written properly vs1053_write_command(0x0B, stereo_volume); // Set the requested volume if (retry++ > 10) return false; } log_msg("[Audio] Volume: %x", stereo_volume); if (!playing_sound) play_system_audio(MP3_VOLUME); return true; } /** * @brief this changes the sound files to make the volume go down. * Volume works in reverse for VS1053 - so 0 is hi and FEFE is low * @ref https://www.sparkfun.com/datasheets/Components/SMD/vs1053.pdf look * on page 47 * @return bool - did sound file change properly */ bool vs1053_decrease_vol(void) { int retry = 0; //Decrease the global volume setting mono_volume = mono_volume + VOL_INCR; // Check for min volume setting //mono_volume is an unsigned, so if you go above FFFF, will wrap around to small number //Min_vol is assigned based off of testing. IF you go down by more then 9, vol_INCR, when set at //1000. Sound will go up for 4 down presses before becoming completely quiet. //make sure not to let this happen if (mono_volume >= VOL_MIN) mono_volume = VOL_MIN; stereo_volume = CHANGE_VOLUME(mono_volume); // Actually decrease the volume while (vs1053_read_command(0x0B) != stereo_volume) { // REDO if not written properly vs1053_write_command(0x0B, stereo_volume); // Set the requested volume if (retry++ > 10) return false; } log_msg("[Audio] Volume: %x", stereo_volume); if (!playing_sound) play_system_audio(MP3_VOLUME); return true; } /** * @brief ? * @param data - unsigned char, transmits data on SPI interface * @return Void */ void vs1053_write_data(unsigned char data) { spi_select_mp3_data(); spi_transmit(data); spi_deselect_all(); } /** * @brief ? * @param addr - unsigned char, address to write into * @param cmd - unsigned int, commmand to process * @return Void */ void vs1053_write_command(unsigned char addr, unsigned int cmd) { temp4 = (cmd & 0xFF00) >> 8; temp5 = (cmd & 0x00FF); temp_address = addr; spi_select_mp3_cmd(); spi_transmit(0x02); spi_transmit(addr); spi_transmit(temp4); spi_transmit(temp5); spi_deselect_all(); } /** * @brief ? * @param addr - unsigned char, address to read from * @return unsigned int - return combination of SPI_recieves */ unsigned int vs1053_read_command(unsigned char addr) { temp_address = addr; spi_select_mp3_cmd(); spi_transmit(0x03); spi_transmit(addr); temp1 = spi_receive(); temp2 = spi_receive(); temp3 = temp1 * 256 + temp2; spi_deselect_all(); return temp3; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> /* edges */ int ab; int ac; int bd; int cf; int fg; int de; int df; int ef; int fEND; int gEND; static unsigned t1, t2, t3; void func(int a1, int a2, int a3) { int i,j,k; if(a1){ ab++; i++; bd++; if(a2){ de++; j++; ef++; } else {df++;}; } else { ac++; k++; cf++; } if(a3){ fg++; k++; gEND++; } else {fEND++;}; } /* No profiling for code below*/ /* Input set 1 */ void input1() { t1 = 0.5 * RAND_MAX; t2 = 0.5 * RAND_MAX; t3 = 0.5 * RAND_MAX; } /* End input set 1*/ /* Input set 2 */ void input2() { t1 = 0.2 * RAND_MAX; t2 = 0.6 * RAND_MAX; t3 = 0.8 * RAND_MAX; } /* End input set 2*/ int main() { int i; unsigned a1, a2, a3; input1(); /* input2(); */ srand(time(NULL)); for(i=0; i<10000; i++){ a1 = (rand() > t1); a2 = (rand() > t2); a3 = (rand() > t3); func(a1, a2, a3); } /* Print out your profiling results here */ printf("edges:\n"); printf("ab: %d\n", ab); printf("ac: %d\n", ac); printf("bd: %d\n", bd); printf("cf: %d\n", cf); printf("de: %d\n", de); printf("df: %d\n", df); printf("fg: %d\n", fg); printf("fEND: %d\n", fEND); printf("gEND: %d\n", gEND); return EXIT_SUCCESS; }
C
/** * A ideia desse código é * definir qual número das entradas * tem o menor valor * Generated by: * Joaquim Breno */ #include <stdio.h> #include <locale.h> int main(void) { float x1, x2; setlocale(LC_ALL, "portuguese-brazilian"); printf("Olá, meu nome é Kodi o seu matemático digital! Siga meus passos e seu resultado será um sucesso.\n"); printf("Digite o primeiro valor:\n"); scanf("%f", &x1); printf("Digite o primeiro valor:\n"); scanf("%f", &x2); if (x1 > x2){ printf(" O primeiro %.2f número é maior que o segundo número %.2f!", x1, x2); } else if (x1 < x2){ printf(" O primeiro %.2f número é menor que o segundo número %.2f!", x1, x2); } else { printf("Poxa! Os números são iguais, seja mais criativo\n"); } return(0); }
C
/* module title: revjul.c * function name: char *revjul() * main() for demo * * author: Kim J. Brand * * revision history: * version/--date--/by reason-------------------------------------------- * 1.0 10/01/84 kb Common C Functions initial release * * compiled with: stdio.h * compiled by: * * linked with: int twodates() * linked by: * * problems: * * description: converts a Julian number into a date string * */ #include <stdio.h> #define DEMO #ifdef DEMO main() /* a simple demonstration main() */ { int jul; int base; char *revjul(); while (1) { printf("\nEnter Julian date: "); scanf("%d", &jul); printf("Enter base year: "); scanf("%d", &base); printf("Date = %s\n", revjul(jul,base)); } } #endif char *revjul(jul,year) /* returns pointer to string that */ int jul; /* is calendar date for this */ int year; /* Julian date in form: mm/dd/yy */ { /* number of days in each month */ /* indexed by the month in the year */ static int days[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; static char date[11]; /* a place for returned date string */ /* including the null, must be */ /* static or will evaporate */ int days_year; /* the days/year for a given year */ int n = 1; /* an index into the days/month */ setmem(date, sizeof(date), 0); /* must fill date with nulls so */ /* strlen knows where date ends */ days[2] = 28; /* fix February if changed */ do { /* calculate number of days for */ /* base year and all succeeding, */ /* calculates leap year */ if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) days_year = 366; else days_year = 365; year++, jul -= days_year; /* increment the year and */ } while (jul > 0); /* test that does not */ /* go over top */ year--, jul += days_year; /* reverse the effect of */ /* going too far */ if (days_year == 366) /* if the current year is */ days[2] = 29; /* leap, fix February */ do /* subtract days from each */ jul -= days[n++]; /* month until jul < 0 */ while (jul > 0); /* n holds month number */ --n, jul += days[n]; /* jul has day of month */ year = (year > 1999 ? year : year - 1900); sprintf(date, "%d/%d/%d", n, jul, year); /* at date build string */ return (date); /* that returns a pointer */ } /* to the string */ 
C
#include "CmacAesSubkeys.h" #include <string.h> #include "BitOperation.h" // See RFC4493, Fig 2.2 static uint8_t const_Zero[16] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; // See RFC4493, Fig 2.2 #define CONST_RB 0x87 int CmacAesSubkeys_CalculateLFromK(AES128_HANDLE aes_handle, uint8_t *L, size_t L_len) { AES128_CRYPTO_PARAMS params = {}; if (aes_handle == NULL) return -1; params.aes_handle = aes_handle; params.input = const_Zero; // params.input[0] = 1; params.input_len = sizeof(const_Zero); Aes128_Encrypt(&params, L, L_len); return 0; } int CmacAesSubkeys_CalculateK1FromL(uint8_t *L, size_t L_len, uint8_t *K1, size_t K1_len) { BitOperation_LogicalShiftLeftOne(L, L_len, K1, K1_len); if ( GET_MSBIT_8(L[0]) ) K1[15] ^= CONST_RB; return 0; } int CmacAesSubkeys_CalculateK2FromK1(uint8_t *K1, size_t K1_len, uint8_t *K2, size_t K2_len) { BitOperation_LogicalShiftLeftOne(K1, K1_len, K2, K2_len); if ( GET_MSBIT_8(K1[0]) ) K2[15] ^= CONST_RB; return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> //Funcion con el modelo matematico donde estan las sumatorias int maximizar(bool auxi, int ap[], int quantities[], char ingr[], int numOfDifferentIngredients, int pp[][numOfDifferentIngredients], FILE *fp3) { int suma = 0; int op3 = 2 * quantities[1]; int op4 = op3 + 3 * quantities[2]; int b = 0; int c = 0; bool prueba = auxi; for (int i = 0; i < quantities[1]; i++) { if (prueba == 1) { fputs("\nEl pedido ", fp3); fprintf(fp3, "%d", i); fputs(" contiene: ", fp3); } for (int j = 0; j < numOfDifferentIngredients; j++) { if ((pp[ap[2 * i]][j] || pp[ap[(2 * i) + 1]][j]) == 1){ if(prueba == 1){ fputs(ingr+(21*j), fp3); fputs(", ", fp3); } suma++; } } b++; } for (int i = 0; i < quantities[2]; i++) { if (prueba == 1) { fputs("\nEl pedido ", fp3); fprintf(fp3, "%d", i + b); fputs(" contiene: ", fp3); } for (int j = 0; j < numOfDifferentIngredients; j++) { if ((pp[ap[op3 + (3 * i)]][j] || pp[ap[op3 + (3 * i) + 1]][j] || pp[ap[op3 + (3 * i) + 2]][j]) == 1) { if (prueba == 1) { fputs(ingr + (21*j), fp3); fputs(", ", fp3); } suma++; } } c++; } for (int i = 0; i < quantities[3]; i++) { if (prueba == 1) { fputs("\nEl pedido ", fp3); fprintf(fp3, "%d", i + b + c); fputs(" contiene: ", fp3); } for (int j = 0; j < numOfDifferentIngredients; j++) { if ((pp[ap[op4 + (4 * i)]][j] || pp[ap[op4 + (4 * i) + 1]][j] || pp[ap[op4 + (4 * i) + 2]][j] || pp[ap[op4 + (4 * i) + 3]][j]) == 1) { if (prueba == 1) { fputs(ingr + (21*j), fp3); fputs(", ", fp3); } suma++; } } } return suma; } int factorial(int factorial) { int resultado = 1; while (factorial > 1) { resultado *= factorial; factorial--; } return resultado; } void nextiter(int array[], int arrPermutado[], int x) { int i = x - 1; duplicar(array, arrPermutado, x); while (i > 0 && arrPermutado[i - 1] >= arrPermutado[i]) { i--; } if (i <= 0) { return; } int j = x - 1; while (arrPermutado[j] <= arrPermutado[i - 1]) { j--; } int temp = arrPermutado[i - 1]; arrPermutado[i - 1] = arrPermutado[j]; arrPermutado[j] = temp; j = x - 1; while (i < j) { temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } } void duplicar(int ex[], int re[], int tam) { for (int i = 0; i < tam; i++) { re[i] = ex[i]; } }
C
#include<stdio.h> int main() { extern int a = 100; printf("THe value of a is %d\n", a); return (0); } // //7-18.c: In function ‘main’: //7-18.c:5:13: error: ‘a’ has both ‘extern’ and initializer //extern int a = 100; //
C
#ifndef SHELL_COLORS_H #define SHELL_COLORS_H #include <allegro5/allegro.h> /* This will store any color with two bytes for every part of the color. * There is a function to convert that to an ALLEGRO_COLOR in utils.c */ typedef enum Color { /*R G B A*/ RED = (int)0xF0322F00, BLUE = (int)0x268BF200, GREEN = (int)0x16AF0E00, YELLOW = (int)0xEEEE0000, GRAY = (int)0x66666600, WHITE = (int)0xDDDDDD00, WHEAT = (int)0xEFB57100, PURPLE = (int)0xB177B900, BACKGROUND_COLOR = (int)0x27282200 } Color; /* A global array of colors so it can be easily used to generate random colors */ extern const Color Colors[]; #endif
C
#include<stdio.h> int main() { int dog[100],a,i,d; printf("type your quantity of your number: \n"); scanf("%d",&a); for(int i=1; i<=a; i++) { scanf("%d",&dog[i]); } i=1; for( ; i<=a; i++) { if(dog[i]==0) { printf("yes zero is available\n"); d=0; } } if(d){ printf("zero not available");} }
C
/* * ===================================================================================== * * Filename: exploitable.c * * Version: 1.0 * Created: 09/27/2015 12:32:05 AM * Revision: none * Compiler: gcc * * Author: Taishi Nojima (tn246), taishi.nojima@yale.edu * * ===================================================================================== */ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> int main (int argc, char **argv){ char msg[1024]; static int test_value = 72, next_value = 0x11111111; strcpy(msg, argv[1]); printf(msg); printf("\n"); printf("[DEBUG] test_value @ 0x%08x = %d 0x%08x\n", (int)&test_value, test_value, test_value ); printf("[DEBUG] next_value @ 0x%08x = %d 0x%08x\n", (int)&next_value, next_value, next_value ); int (*ret)() = (int(*)())next_value; ret(); return 0; } /* * canopus@canopus:~/blackhat_python/pwn/format_str|master * ⇒ ./shellcode AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x. * AAAAbffff7c1.1a81d4.1a81d4.1a81d4.8.4c.41414141.252e7825.78252e78.2e78252e.252e7825.78252e78.2e78252e.252e7825. * [DEBUG] test_value @ 0x0804a028 = -72 0xffffffb8 * [DEBUG] next_value @ 0x0804a02c = 286331153 0x11111111 * [2] 921 segmentation fault (core dumped) ./shellcode AAAA%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x.%x. * * canopus@canopus:~/blackhat_python/pwn/format_str|master * ⇒ ./shellcode $(python fmt_exploit.py ./shellcode 7 0804a02c bfffff8d)))]]] */
C
#include <fcntl.h> ssize_t read(int fd,void * ptr,size_t len) __smallc __naked { #asm INCLUDE "fcntl.def" ld hl,6 add hl,sp ld a,ESPCMD_READ call __esp_send_cmd ld a,(hl) ;fd call __esp_send_byte dec hl ;sp+5 dec hl ;sp+4 dec hl ;sp+3 dec hl ;sp+2 ld a,(hl) ;length call __esp_send_byte inc hl ;sp+3 ld a,(hl) call __esp_send_byte ; Read result call __esp_read_byte and a jr z,not_failed ld hl,-1 ret not_failed: ; Read offered length call __esp_read_byte ld c,a call __esp_read_byte ld b,a push bc inc hl ;sp+4 ld a,(hl) ;ptr inc hl ld h,(hl) ld l,a ; And fill buffer for offered length loop: call __esp_read_byte ld (hl),a inc hl dec bc ld a,b or c jr nz,loop pop hl ;amount read ret #endasm }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwatkyn <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/02 08:43:53 by jwatkyn #+# #+# */ /* Updated: 2018/07/02 08:44:37 by jwatkyn ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include "../libft/includes/libft.h" # include "checker.h" # include <stdio.h> # define MAX 2147483647 # define MIN -2147483648 # define ABS(x) (x < 0 ? -x : x) # ifndef T_STACK_H # define T_STACK_H typedef struct s_stack { int content; struct s_stack *next; } t_stack; typedef struct s_moves { char *move; struct s_moves *next; } t_moves; typedef struct s_info { int min; int max; int min_count; int dir; int sizeA; int sizeB; t_stack *A; t_stack *B; t_moves *moves; } t_info; # endif t_stack *ft_getinfo(char** tab, int count, t_stack *A); int *ft_checkinfo(char **tab, int count); int *ft_intarray(char **tab, int count); void ERROR(void); t_stack *add_end(t_stack *head, int val); t_stack *create(int val); int is_sorted(t_stack *head, int dir); t_stack *add_begin(t_stack *head, int val); t_stack *del_end(t_stack *head); t_stack *del_begin(t_stack *head); t_stack *sort(t_stack *A, t_stack *B, t_info *info); t_stack *ft_sa(t_stack *A, t_info *info); t_stack *ft_sb(t_stack *B, t_info *info); t_stack *ft_ss(t_stack **A, t_stack *B, t_info *info); t_stack *ft_pa(t_stack *A, t_stack **B, t_info **info); t_stack *ft_pb(t_stack *B, t_stack **A, t_info **info); t_stack *ft_ra(t_stack *A, t_info *info); t_stack *ft_rb(t_stack *B, t_info *info); t_stack *ft_rr(t_stack **A, t_stack *B, t_info *info); t_stack *ft_rra(t_stack *A, t_info *info); t_stack *ft_rrb(t_stack *B, t_info *info); t_stack *ft_rrr(t_stack **A, t_stack *B, t_info *info); t_stack *quicksort(t_stack *A, t_stack *B, t_info *info); void free_array(char **array); void free_list(t_stack *A); t_stack *large_sort(t_stack *A, t_stack *B, t_info *info); t_moves *best_way_AtoB(t_stack *A, t_stack *B, t_info *info); void free_move(t_moves *move); int common(t_moves *move); int maxval(t_stack *stack); int minval(t_stack *stack); int maxplace(t_stack *stack); int minplace(t_stack *stack); int rot_type(int len, int pos, char **rot); int find_moves(t_stack *stack, int len, int val, char **rot); int stack_pos(t_stack *stack, int val); int size_stack(t_stack *stack); int median(t_stack *stack, int size); void swap_A(t_stack *A, t_stack *B, t_info *info, int len); int is_sorted_first(t_stack *head, int dir, int size); void ft_add_move(t_info *info, char *move); void ft_operation_optimize(t_moves *head, t_moves *del, int f, int x); void ft_print_and_free(t_moves *src); void print_stacks(t_stack *A, t_stack *B); #endif
C
#include <stdio.h> void main(int argc, char const *argv[]) { /* code */ int ch; FILE *fp; if (argc!=2) { /* code */ printf("error format,uasge:display filename\n"); } if ((fp=fopen(argv[1],"r"))==NULL) { /* code */ printf("the file <%s> can not be opened.\n",argv[1] ); return; } ch=fgetc(fp); while(ch!=EOF) { putchar(ch); ch=fgetc(fp); } fclose(fp); }
C
#include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <wiringPiSPI.h> #define CHANNEL 0 uint8_t snow[] = { 0, //00000000 40, //00101000 146, //10010010 84, //01010100 40, //00101000 84, //01010100 146, //10010010 40 //00101000 }; uint8_t buf[2]; void spi(uint8_t reg, uint8_t val) { buf[0] = reg; buf[1] = val; wiringPiSPIDataRW(CHANNEL, buf, 10); } void show() { for(int i=0; i < 8; i++) { //in rows spi(i+1,(char)(snow[i])); } } void clear() { for (int i = 0; i < 8; ++i) { spi(i+1, 0); } } void setupLEDMatrix(int channel) { if (wiringPiSPISetup(CHANNEL, 1000000) < 0) { fprintf (stderr, "SPI Setup failed: %s\n", strerror (errno)); exit(errno); } spi(0x09,0x00); //decode mode spi(0x0B,0x07); //scan limit spi(0x0A,0xF3); //brightness spi(0x0C,0x01); //shutdown mode spi(0x0F,0x00); //test mode } int main(int argc, char** argv) { setupLEDMatrix(CHANNEL); clear(); show(); sleep(3); clear(); return 0; }
C
#include<math.h> #include<stdio.h> #include<ctype.h> #include<stdlib.h> #include<string.h> #define TOKENSIZE 100 #define HASHMAX 1000 #define MAXINPUT 5000 struct node{ long i; /* to store integer value t = 'i' */ char *s; /* to store symbol t = 's' */ double f; /* to store floating value t = 'f' */ struct node *head; /* to store the address of first element of a list t = 'l' */ struct node *(*fptr) (struct node *); /* to store address of function t = 'F' */ struct node **currentEnv;/* to store address of current Environment array t = 'e' */ struct node *outerEnv; /* to store address of outer Environment Node t = 'e' */ struct node *parms; /* to store address of list of parameters t = 'p' */ struct node *body; /* to store address of list of body elements t = 'p' */ struct node *env; /* to store address of the current Environment Node t = 'p' */ char t; /* to specify whether the node has an int or a float or a symbol or a function pointer or an Environment or a Procedure */ struct node *next; /* to store the address of next node */ }; void repl(void); long hash(char *w); void checkProgram(char *p); struct node *newNode(char *w); struct node *isString(char *w); struct node *tokenize(char *p); struct node *isNumber(char *w); struct node *standard_env(void); void print(struct node *current); int length(struct node *current); struct node *parse(char *program); struct node *pop(struct node **href); struct node *copyNode(struct node *old); void appendNode(struct node **h, struct node *w); struct node *read_from_list(struct node **tokens); struct node **findEnv(char *w, struct node *envNode); struct node *eval(struct node *x, struct node *envNode); struct node *updateEnv(struct node *(*fptr) (struct node *), char *s); struct node *Env(struct node *parms, struct node *args, struct node *outerEnv); struct node *lt(struct node *head); struct node *gt(struct node *head); struct node *le(struct node *head); struct node *ge(struct node *head); struct node *min(struct node *head); struct node *max(struct node *head); struct node *len(struct node *head); struct node *cdr(struct node *head); struct node *car(struct node *head); struct node *mul(struct node *head); struct node *sub(struct node *head); struct node *add(struct node *head); struct node *cons(struct node *head); struct node *sine(struct node *head); struct node *expt(struct node *head); struct node *div_(struct node *head); struct node *logBe(struct node *head); struct node *power(struct node *head); struct node *cosine(struct node *head); struct node *absval(struct node *head); struct node *sqroot(struct node *head); struct node *begin(struct node *current); main() { repl(); // A prompt-read-eval-print loop } void repl(void) { char *quit; struct node *result; char program[MAXINPUT]; struct node *global_env; struct node *head = NULL; global_env = standard_env(); while("True"){ result = NULL; printf("\nlisp.in.c]=> "); if((quit = fgets(program,MAXINPUT,stdin)) == NULL){ printf("\nEnd of input stream reached\nMoriturus te saluto!!!\n"); exit(0); } printf("\n"); if(result = eval(parse(program),global_env)){ printf("Value: "); print(result); printf("\n"); } else printf("(nil)\n"); } } struct node *parse(char *program) { struct node *head = NULL; checkProgram(program); // checking syntax of the program head = tokenize(program); return read_from_list(&head); } void checkProgram(char *p) { int count = 0; while(*p){ if(*p == '(') ++count; else if(*p == ')') --count; ++p; } if(count != 0){ printf("error> unequal number of '(' and ')'!!! exiting...\n"); exit(0); } } struct node *tokenize(char *p) { char word[TOKENSIZE],*w; struct node *head = NULL; while(*p){ w = word; while(isspace(*p)) ++p; if(*p == '\0') return head; else if(*p == '(' || *p == ')'){ *w++ = *p++; *w = '\0'; appendNode(&head,newNode(word)); } else{ while(*p && !isspace(*p) && *p != '(' && *p != ')') *w++ = *p++; *w = '\0'; appendNode(&head,newNode(word)); } } return head; } struct node *read_from_list(struct node **tokens) { struct node *token; token = pop(tokens); if(token != NULL && (token->t == 's' || token->t == 'S') && strcmp(token->s,"(") == 0){ struct node *L = (struct node *)malloc(sizeof(struct node));; L->t = 'l'; L->head = NULL; L->next = NULL; while((*tokens)->t != 'S' || strcmp((*tokens)->s,")") != 0) appendNode(&(L->head),read_from_list(tokens)); pop(tokens); // pop off ')' return L; } else return token; } struct node *pop(struct node **href) { struct node *tmp = *href; if(tmp == NULL) return NULL; *href = (*href)->next; tmp->next = NULL; return tmp; } void appendNode(struct node **h, struct node *w) { struct node *current = *h; if(current == NULL){ *h = w; return; } while(current->next != NULL) current = current->next; current->next = w; } struct node *newNode(char *w) { struct node *h = NULL; if(h = isNumber(w)){ // int or float h->next = NULL; return h; } else return isString(w); // string or symbol } struct node *isNumber(char *w) { int i = 0; long sum = 0; long fra = 0; int sign = 1; struct node *new = NULL; if(*w == '-'){ sign = -1; if(*++w == '\0') // just a symbol "-" return new; } while(isdigit(*w)){ sum = sum * 10 + (*w - '0'); ++w; } if(*w == '\0'){ // integer new = (struct node *)malloc(sizeof(struct node)); new->i = sum * sign; new->t = 'i'; return new; } else if(*w == '.'){ ++w; while(isdigit(*w)){ fra = fra * 10.0 + (*w - '0'); ++w; ++i; } if(*w == '\0'){ // float new = (struct node *)malloc(sizeof(struct node)); new->f = ((double)sum + fra/pow(10,i)) * sign; new->t = 'f'; return new; } } return new; // neither an integer nor a float return NULL } struct node *isString(char *w) { char *str; int len = strlen(w); struct node *h = (struct node *)malloc(sizeof(struct node)); if(*w == '"' && *(w+len-1) == '"'){ str = (char *)calloc(len-1,sizeof(char)); strncpy(str,w+1,len-2); str[len-2] = '\0'; h->t = 's'; } else{ str = strdup(w); h->t = 'S'; } h->s = str; h->next = NULL; return h; } struct node *standard_env(void) { struct node *new = (struct node *)malloc(sizeof(struct node)); struct node **env = (struct node **)calloc(HASHMAX,sizeof(struct node *)); env[hash("+")] = updateEnv(add,"+"); env[hash("-")] = updateEnv(sub,"-"); env[hash("*")] = updateEnv(mul,"*"); env[hash("/")] = updateEnv(div_,"/"); env[hash(">")] = updateEnv(gt,">"); env[hash("<")] = updateEnv(lt,"<"); env[hash(">=")] = updateEnv(ge,">="); env[hash("<=")] = updateEnv(le,"<="); env[hash("sqrt")] = updateEnv(sqroot,"sqrt"); env[hash("abs")] = updateEnv(absval,"abs"); env[hash("pow")] = updateEnv(power,"pow"); env[hash("exp")] = updateEnv(expt,"exp"); env[hash("cos")] = updateEnv(cosine,"cos"); env[hash("sin")] = updateEnv(sine,"sin"); env[hash("log")] = updateEnv(logBe,"log"); env[hash("begin")] = updateEnv(begin,"begin"); env[hash("min")] = updateEnv(min,"min"); env[hash("max")] = updateEnv(max,"max"); env[hash("len")] = updateEnv(len,"len"); env[hash("cdr")] = updateEnv(cdr,"cdr"); env[hash("car")] = updateEnv(car,"car"); env[hash("cons")] = updateEnv(cons,"cons"); env[hash("pi")] = newNode("3.14"); new->t = 'e'; new->currentEnv = env; new->outerEnv = NULL; new->next = NULL; return new; } long hash(char *w) { int i = 0; long h = 0; char *s = w; while(*w){ h = h + (*w) * pow(10,i); w++; i++; } return h%HASHMAX; } struct node *updateEnv(struct node * (*fptr) (struct node *), char *s) { struct node *new = (struct node *)malloc(sizeof(struct node)); new->t = 'F'; new->fptr = fptr; new->s = strdup(s); new->next = NULL; return new; } struct node *eval(struct node *x, struct node *envNode) { if(x == NULL){ printf("x is nil\n"); return NULL; } if(x->t == 'S'){ // variable reference char *var = x->s; return findEnv(var,envNode)[hash(var)]; } else if(x->t != 'l') // constant literal return copyNode(x); else if(x->head->t == 'S' && strcmp(x->head->s,"quote") == 0){ // (quote exp) return x->head->next; } else if(x->head->t == 'S' && strcmp(x->head->s,"if") == 0){ // (if test conseq alt) struct node *test, *conseq, *alt, *cond; test = copyNode(x->head->next); conseq = copyNode(x->head->next->next); alt = x->head->next->next->next; cond = eval(test,envNode); switch(cond->t){ case 'i': if(cond->i) return eval(conseq,envNode); case 'f': if(cond->f) return eval(conseq,envNode); case 's': if(cond->s) return eval(conseq,envNode); } return eval(alt, envNode); } else if(x->head->t == 'S' && strcmp(x->head->s,"define") == 0){ // (define var exp) char *var = x->head->next->s; struct node *exp = x->head->next->next; envNode->currentEnv[hash(var)] = eval(exp, envNode); return NULL; } else if(x->head->t == 'S' && strcmp(x->head->s,"set!") == 0){ // (set! var exp) char *var = x->head->next->s; struct node *exp = x->head->next->next; findEnv(var,envNode)[hash(var)] = eval(exp, envNode); return NULL; } else if(x->head->t == 'S' && strcmp(x->head->s,"lambda") == 0){ // (lambda (var...) body) struct node *new = (struct node *)malloc(sizeof(struct node)); new->t = 'p'; new->parms = x->head->next->head; new->body = x->head->next->next; new->env = envNode; new->next = NULL; return new; } else{ // (proc arg...) struct node *proc, *current, *args = NULL; proc = eval(copyNode(x->head), envNode); current = x->head->next; while(current != NULL){ appendNode(&args,copyNode(eval(current,envNode))); current = current->next; } if(proc->t == 'p') return eval(proc->body,Env(proc->parms,args,proc->env)); else return (proc->fptr)(args); } } struct node *Env(struct node *parms, struct node *args, struct node *outerEnv) { struct node *newEnvNode = (struct node *)malloc(sizeof(struct node)); newEnvNode->t = 'e'; newEnvNode->currentEnv = (struct node **)calloc(HASHMAX,sizeof(struct node *)); newEnvNode->outerEnv = outerEnv; newEnvNode->next = NULL; while(parms != NULL && args != NULL){ newEnvNode->currentEnv[hash(parms->s)] = copyNode(args); parms = parms->next; args = args->next; } return newEnvNode; } struct node **findEnv(char *w, struct node *envNode) { struct node *env = NULL; if(envNode == NULL){ printf("error> Unbound variable: %s\n",w); exit(0); } if((env = envNode->currentEnv[hash(w)]) != NULL) return envNode->currentEnv; return findEnv(w,envNode->outerEnv); } struct node *copyNode(struct node *old) { if(old == NULL) return NULL; struct node *new = (struct node *)malloc(sizeof(struct node)); *new = *old; new->next = NULL; return new; } void print(struct node *current) { if(current == NULL) return; switch(current->t){ case 'i':// int printf(" %ld",current->i); break; case 'f':// float printf(" %f",current->f); break; case 'F':// function printf("<built-in function %s>",current->s); break; case 's':// string printf(" \"%s\"",current->s); break; case 'S':// symbol printf(" %s",current->s); break; case 'p':// procedure printf("<lisp.in.c.Procedure object at %p>",current); break; case 'l':// list printf(" ("); print(current->head); printf(" )"); break; } print(current->next); } int length(struct node *current) { int l = 0; while(current != NULL){ l++; current = current->next; } return l; } /****** build-in functions ******/ struct node *div_(struct node *head) { int l = 0; double result; int flagi = 0; int flagf = 0; long resulti = 1; double resultf = 1; struct node *new = NULL; struct node *current = head; while(current != NULL){ l++; if(current->t == 'f') flagf = 1; current = current->next; } if(l > 1){ switch(head->t){ case 'i': if(flagf) resultf = (double)head->i; else resulti = head->i; flagi = 1; break; case 'f': resultf = head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to / is not the correct type\n",head->s); exit(0); } head = head->next; } while(head != NULL){ switch(head->t){ case 'i': if(flagf) resultf /= (double)head->i; else resulti /= head->i; flagi = 1; break; case 'f': resultf /= head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to / is not the correct type\n",head->s); exit(0); } head = head->next; } new = (struct node *)malloc(sizeof(struct node)); if((flagi && flagf) || flagf){ new->t = 'f'; new->f = (double)resulti * resultf; } else if(flagi){ new->t = 'i'; new->i = resulti; } else{ new->t = 'i'; new->i = 1; } new->next = NULL; return new; } struct node *mul(struct node *head) { double result; int flagi = 0; int flagf = 0; long resulti = 1; double resultf = 1; struct node *new = NULL; while(head != NULL){ switch(head->t){ case 'i': resulti *= head->i; flagi = 1; break; case 'f': resultf *= head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to * is not the correct type\n",head->s); exit(0); } head = head->next; } new = (struct node *)malloc(sizeof(struct node)); if((flagi && flagf) || flagf){ new->t = 'f'; new->f = (double)resulti * resultf; } else if(flagi){ new->t = 'i'; new->i = resulti; } else{ new->t = 'i'; new->i = 1; } new->next = NULL; return new; } struct node *sub(struct node *head) { double result; int flagi = 0; int flagf = 0; long resulti = 0; double resultf = 0; struct node *new = NULL; if(length(head) > 1){ switch(head->t){ case 'i': resulti = head->i; flagi = 1; break; case 'f': resultf = head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to / is not the correct type\n",head->s); exit(0); } head = head->next; } while(head != NULL){ switch(head->t){ case 'i': resulti -= head->i; flagi = 1; break; case 'f': resultf -= head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to - is not the correct type.\n",head->s); exit(0); } head = head->next; } new = (struct node *)malloc(sizeof(struct node)); if((flagi && flagf) || flagf){ new->t = 'f'; new->f = (double)resulti + resultf; } else if(flagi){ new->t = 'i'; new->i = resulti; } else{ new->t = 'i'; new->i = 0; } new->next = NULL; return new; } struct node *add(struct node *head) { double result; int flagi = 0; int flagf = 0; long resulti = 0; double resultf = 0; struct node *new = NULL; while(head != NULL){ switch(head->t){ case 'i': resulti += head->i; flagi = 1; break; case 'f': resultf += head->f; flagf = 1; break; case 's': printf("error> The object \"%s\", passed as argument to + is not the correct type.\n",head->s); exit(0); } head = head->next; } new = (struct node *)malloc(sizeof(struct node)); if((flagi && flagf) || flagf){ new->t = 'f'; new->f = (double)resulti + resultf; } else if(flagi){ new->t = 'i'; new->i = resulti; } else{ new->t = 'i'; new->i = 0; } new->next = NULL; return new; } struct node *lt(struct node *head) { int l; double x,y; struct node *new = (struct node *)malloc(sizeof(struct node)); if((l = length(head)) < 2){ new->t = 'i'; new->i = 1; new->next = NULL; return new; } switch(head->t){ case 'i': x = (double)head->i; break; case 'f': x = head->f; break; case 's': printf("error> The object \"%s\", passed as the first argument to < is not the correct type.\n",head->s); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': y = (double)head->i; break; case 'f': y = head->f; break; case 's': printf("error> The object \"%s\", passed as argument to < is not the correct type.\n",head->s); exit(0); } if(x >= y){ new->t = 'i'; new->i = 0; new->next = NULL; return new; } x = y; head = head->next; } new->t = 'i'; new->i = 1; new->next = NULL; return new; } struct node *gt(struct node *head) { int l; double x,y; struct node *new = (struct node *)malloc(sizeof(struct node)); if((l = length(head)) < 2){ new->t = 'i'; new->i = 1; new->next = NULL; return new; } switch(head->t){ case 'i': x = (double)head->i; break; case 'f': x = head->f; break; case 's': printf("error> The object \"%s\", passed as the first argument to > is not the correct type.\n",head->s); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': y = (double)head->i; break; case 'f': y = head->f; break; case 's': printf("error> The object \"%s\", passed as argument to > is not the correct type.\n",head->s); exit(0); } if(x <= y){ new->t = 'i'; new->i = 0; new->next = NULL; return new; } x = y; head = head->next; } new->t = 'i'; new->i = 1; new->next = NULL; return new; } struct node *le(struct node *head) { int l; double x,y; struct node *new = (struct node *)malloc(sizeof(struct node)); if((l = length(head)) < 2){ new->t = 'i'; new->i = 1; new->next = NULL; return new; } switch(head->t){ case 'i': x = (double)head->i; break; case 'f': x = head->f; break; case 's': printf("error> The object \"%s\", passed as the first argument to <= is not the correct type.\n",head->s); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': y = (double)head->i; break; case 'f': y = head->f; break; case 's': printf("error> The object \"%s\", passed as argument to <= is not the correct type.\n",head->s); exit(0); } if(x > y){ new->t = 'i'; new->i = 0; new->next = NULL; return new; } x = y; head = head->next; } new->t = 'i'; new->i = 1; new->next = NULL; return new; } struct node *ge(struct node *head) { int l; double x,y; struct node *new = (struct node *)malloc(sizeof(struct node)); if((l = length(head)) < 2){ new->t = 'i'; new->i = 1; new->next = NULL; return new; } switch(head->t){ case 'i': x = (double)head->i; break; case 'f': x = head->f; break; case 's': printf("error> The object \"%s\", passed as the first argument to >= is not the correct type.\n",head->s); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': y = (double)head->i; break; case 'f': y = head->f; break; case 's': printf("error> The object \"%s\", passed as argument to >= is not the correct type.\n",head->s); exit(0); } if(x < y){ new->t = 'i'; new->i = 0; new->next = NULL; return new; } x = y; head = head->next; } new->t = 'i'; new->i = 1; new->next = NULL; return new; } struct node *logBe(struct node *head) { double result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\nlog has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = log(head->i); break; case 'f': result = log(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to log() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *sine(struct node *head) { double result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\nsin has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = sin(head->i); break; case 'f': result = sin(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to sin() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *cosine(struct node *head) { double result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\ncos has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = cos(head->i); break; case 'f': result = cos(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to cos() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *expt(struct node *head) { double result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\nexp has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = exp(head->i); break; case 'f': result = exp(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to exp() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *power(struct node *head) { int l; double x,y; double result; struct node *new = NULL; if((l = length(head)) != 2){ printf("error> \n\npow has been called with %d arguments; it requires exactly 2 argument\n",l); exit(0); } switch(head->t){ case 'i': x = (double)head->i; break; case 'f': x = head->f; break; case 's': printf("error> The object \"%s\", passed as the first argument to pow() is not the correct type.\n",head->s); exit(0); } switch(head->next->t){ case 'i': y = (double)head->next->i; break; case 'f': y = head->next->f; break; case 's': printf("error> The object \"%s\", passed as the second argument to pow() is not the correct type.\n",head->next->s); exit(0); } result = pow(x,y); new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *absval(struct node *head) { long result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\nabs has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = abs(head->i); break; case 'f': result = abs(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to abs() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'i'; new->i = result; new->next = NULL; return new; } struct node *sqroot(struct node *head) { double result; struct node *new = NULL; if(head->next != NULL){ printf("error> \n\nsqrt has been called with %d arguments; it requires exactly 1 argument\n",length(head)); exit(0); } switch(head->t){ case 'i': result = sqrt(head->i); break; case 'f': result = sqrt(head->f); break; case 's': printf("error> The object \"%s\", passed as the first argument to sqrt() is not the correct type.\n",head->s); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->t = 'f'; new->f = result; new->next = NULL; return new; } struct node *begin(struct node *current) { while(current->next != NULL) current = current->next; return current; } struct node *cons(struct node *head) { int l; if((l = length(head)) != 2){ printf("error> \n\ncons has been called with %d arguments; it requires exactly 2 argument\n",l); exit(0); } struct node *x = head; struct node *y = head->next; struct node *new = (struct node *)malloc(sizeof(struct node)); new->t = 'l'; new->head = x; new->next = NULL; if(y->t == 'l') x->next = y->head; else x->next = y; return new; } struct node *car(struct node *head) { if(head->t != 'l'){ printf("error> The object passed as the first argument to car, is not the correct type\n"); exit(0); } if(head->head == NULL){ printf("error> The object passed as the first argument to car, is not the correct type\n"); exit(0); } return copyNode(head->head); } struct node *cdr(struct node *head) { if(head->t != 'l'){ printf("error> The object passed as the first argument to cdr, is not the correct type\n"); exit(0); } struct node *new = (struct node *)malloc(sizeof(struct node)); new->t = 'l'; new->head = head->head->next; new->next = NULL; return new; } struct node *len(struct node *head) { struct node *new = NULL; if(head->t != 'l'){ printf("error> The object passed as an argument to length, is not a list\n"); exit(0); } new = (struct node *)malloc(sizeof(struct node)); new->i = length(head->head); new->t = 'i'; new->next = NULL; return new; } struct node *max(struct node *head) { double maxnum; struct node *maxNode = head; if(head == NULL){ printf("error> \n\nmax has been called with 0 arguments; it requires at least 1 argument\n"); exit(0); } switch(head->t){ case 'i': maxnum = (double)head->i; break; case 'f': maxnum = head->f; break; default: printf("error> The object passed as an argument to max, is not a real number\n"); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': if(maxnum < head->i){ maxnum = (double)head->i; maxNode = head; } break; case 'f': if(maxnum < head->f){ maxnum = head->f; maxNode = head; } break; default: printf("error> The object passed as an argument to max, is not a real number\n"); exit(0); } head = head->next; } return copyNode(maxNode); } struct node *min(struct node *head) { double minnum; struct node *minNode = head; if(head == NULL){ printf("error> min has been called with 0 arguments; it requires at least 1 argument\n"); exit(0); } switch(head->t){ case 'i': minnum = (double)head->i; break; case 'f': minnum = head->f; break; default: printf("error> The object passed as an argument to min, is not a real number\n"); exit(0); } head = head->next; while(head != NULL){ switch(head->t){ case 'i': if(minnum > head->i){ minnum = (double)head->i; minNode = head; } break; case 'f': if(minnum > head->f){ minnum = head->f; minNode = head; } break; default: printf("error> The object passed as an argument to max, is not a real number\n"); exit(0); } head = head->next; } return copyNode(minNode); }
C
#include <sys/stat.h> #include <fcntl.h> #include <stdio.h> void mycat(char* filename) { int file; char c; file = open(filename, O_RDONLY); if(file == -1) { printf("Error when open file.\n"); return ; } int flag = 0; flag = read(file, &c, sizeof(char)); while(flag != -1 && flag != 0) { printf("%c", c); flag = read(file, &c, sizeof(char)); } if(flag == -1) { printf("Error when read file.\n"); return ; } close(file); } int main(int argc, char* argv[]) { if(argc == 1) return 0; char* filename = argv[1]; mycat(filename); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <mpi.h> #define BLOCK_LOW(id,p,n) ((id)*(n)/(p)) #define BLOCK_HIGH(id,p,n) (BLOCK_LOW(((id)+1),p,n)-1) #define BLOCK_SIZE(id,p,n) ((BLOCK_LOW(((id)+1),p,n))-(BLOCK_LOW(id,p,n))) #define BLOCK_OWNER(index,p,n) (((p)*(index)+1)-1)/(n)) int main (int argc, char *argv[]) { long long int first, low_value, high_value, size,n, global_count, count, index, prime, proc0_size, temp, first_2, sqrt_n; long long int B = 50000; long long int i,j; int id, p; char *marked, *marked_2; double elapsed_time; MPI_Init (&argc, &argv); MPI_Barrier(MPI_COMM_WORLD); elapsed_time = -MPI_Wtime(); MPI_Comm_rank (MPI_COMM_WORLD, &id); MPI_Comm_size (MPI_COMM_WORLD, &p); if (argc != 2) { if (!id) printf ("Command line: %s <m>\n", argv[0]); MPI_Finalize(); exit (1); } n = atoll(argv[1]); low_value = 2 + BLOCK_LOW(id,p,n-1); if(low_value % 2 == 0) low_value++; // if low value is even, move to the next odd number high_value = 2 + BLOCK_HIGH(id,p,n-1); if(high_value % 2 == 0) high_value--; // if high value is even, move to the previous odd number, size = (high_value-low_value)/2+1; // we can't use the old macro as the low and high values have changed to only have an odd value sqrt_n = (long long int)sqrt(n)/2; proc0_size = (n-1)/p; if ((2 + proc0_size) < (long long int) sqrt((double) n)) { if (!id) printf ("Too many processes\n"); MPI_Finalize(); exit (1); } marked = (char *) malloc (size * sizeof(long long int)); if (marked == NULL) { printf ("Cannot allocate enough memory\n"); MPI_Finalize(); exit (1); } marked_2 = (char *) malloc (sqrt_n * sizeof(long long int)); if (marked_2 == NULL) { printf ("Cannot allocate enough memory\n"); MPI_Finalize(); exit (1); } for (i = 0; i < size; i++) marked[i] = 0; for (i = 0; i < sqrt_n; i++) marked_2[i] = 0; // if (!id) index = 0; all procs will have thier own index for ( j = first; j < size + B; j = j + B) { index = 0; prime = 3; do { if (prime*prime > low_value) { first = (prime* prime-3)/2 - (low_value-3)/2;} else { if (!(low_value % prime)) first = 0; if (prime > low_value%(2*prime)) first = (prime-(low_value%prime))/2; if (prime < low_value%(2*prime)) first =prime-(low_value%prime)/2;} for (i = j + first; i < j + B && i < size ; i += prime) marked[i] = 1; // find the next prime that can iterate between j and j + B first_2 = (prime * prime - 3)/2; // always low_value = 3 as it is in proc 0 for (i = first_2; i < sqrt_n; i += prime) marked_2[i] = 1; while (marked_2[++index]); prime = 2*index + 3; // e.g. 5 is at 1 so 3(1)+2 = 5, replace prime = index + 2; } while (prime * prime <= n); } count = 0; for (i = 0; i < size; i++) if (!marked[i]) count++; MPI_Reduce (&count, &global_count, 1, MPI_LONG_LONG_INT, MPI_SUM,0, MPI_COMM_WORLD); // changed data type to MPI_LONG_LONG_INT elapsed_time += MPI_Wtime(); free(marked); free(marked_2); if (!id) { printf ("%lld primes are less than or equal to %lld\n", global_count+1, n); // add 1 to the global count to account for prime 2 printf ("Total elapsed time: %10.6f\n", elapsed_time); } MPI_Finalize (); return 0; }
C
#include <stdio.h> #include <stdlib.h> double min(double a, double b); int main(){ double a, b; printf("give 2 number:\n"); //double 的转换说明符必须是%lf, //%f, %l都无法正确读取数值保存到变量中 scanf("%lf %lf", &a, &b); printf("the small one of %lf and %lf is %lf\n", a, b, min(a, b)); return 0; } double min(double a, double b){ return (a <= b) ? a: b; }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> #include<malloc.h> struct node { int data; struct node *right; struct node *left; }; struct node *start=NULL; struct node* count(struct node* start); struct node* insertb(); struct node *create() { struct node *p,*ptr; int num; printf("ENTER -1 TO END LOOP\n"); printf("enter the data\n"); scanf("%d",&num); while(num!=-1) { if(start==NULL) { p=(struct node*)malloc(sizeof(struct node)); p->left=NULL; p->data=num; p->right=NULL; start=p; } else { ptr=start; p=(struct node*)malloc(sizeof(struct node)); p->data=num; while(ptr->right!=NULL){ptr=ptr->right;} ptr->right=p; p->left=ptr; p->right=NULL; }printf("enter the data\n"); scanf("%d",&num); } } struct node* insertbeg() { struct node *p; p=(struct node *)malloc(sizeof(struct node)); printf("Enter data to be inserted : "); scanf("%d",&p->data); start->left=p; p->right=start; p->left=NULL; start=p; } void insertend() { struct node *p,*r; p=(struct node *)malloc(sizeof(struct node)); printf("Enter data to be inserted : "); scanf("%d",&p->data); r=start; while(r->right!=NULL) { r=r->right; } r->right=p; p->left=r; p->right=NULL; } struct node* insertb() { int num; struct node *p, *ptr, *preptr; p=(struct node *)malloc(sizeof(struct node)); printf("Enter data of node to insert before : "); scanf("%d",&num); printf("Enter data to be inserted : "); scanf("%d",&p->data); ptr=start; while(ptr->data!=num) { ptr=ptr->right; } p->right=ptr; p->left=ptr->left; ptr->left->right=p; ptr->left=p; } void inserta() { int num; struct node *p, *ptr, *preptr; p=(struct node *)malloc(sizeof(struct node)); printf("Enter data of node to insert after : "); scanf("%d",&num); printf("Enter data to be inserted : "); scanf("%d",&p->data); ptr=start; while(ptr->data!=num) { ptr=ptr->right; } p->left=ptr; p->right=ptr->right; ptr->right->left=p; ptr->right=p; } void deletebeg() { if(start==NULL) printf("Underflow"); else if(start->right==NULL) { printf("Deleted element : %d",start->data); free(start); start=NULL; } else { struct node *ptr; ptr=start; start=start->right; start->left=NULL; printf("Deleted element : %d",ptr->data); free(ptr); } } struct node* deleteb() { int num; struct node *p, *ptr, *temp; p=(struct node *)malloc(sizeof(struct node)); printf("Enter data of node to delete before : "); scanf("%d",&num); printf("Enter data to be deleted : "); scanf("%d",&p->data); if(start==NULL){printf("UNDERFLOW\n");} else if(start->right==NULL) { printf("Deleted element : %d",start->data); free(start); start=NULL; } else{ ptr=start; while(ptr->data!=num) { ptr=ptr->right; } temp=ptr->left; ptr->left=temp->left; temp->left->right=ptr; free(temp); } } struct node* deleteend() { if(start==NULL) {printf("Underflow");} else if(start->right==NULL) { printf("Deleted element : %d",start->data); free(start); start=NULL; } else{ struct node *ptr, *preptr; ptr=start; while(ptr->right!=NULL) { ptr=ptr->right; } ptr->left->right=NULL; printf("Deleted element : %d",ptr->data); free(ptr); } } /*struct node* count(struct node* start) { int c=0; struct node *ptr; ptr=start; while(ptr!=NULL) { ptr=ptr->link; c++; } printf("THERE ARE %d ELEMENTS IN THE LIST",c); } void search() { struct node *ptr; int val, c=0, flag; printf("Enter element to be searched"); scanf("%d",&val); ptr=start; while(ptr!=NULL) { if(val==ptr->data) {flag=(c+1); break; } else { ptr=ptr->link; c++; } } if(flag==0) printf("VALUE not present"); else printf("VALUE present at position : %d",flag); }*/ void display() { struct node* t; t=start; while(t!=NULL) { printf("\nTHE ELEMENTS ARE>>>>> %d ",t->data); t=t->right; } } /*struct node * copy(struct node * start) { struct node *ns, *ptr, *preptr, *new_node; ptr=start; ns=NULL; if(start==NULL) { printf("UNDERFLOW\n"); return start; } ns=(struct node *)malloc(sizeof(struct node)); ns->data = ptr->data; ns->link = NULL; ptr=ptr->link; while(ptr!=NULL) { new_node=(struct node *)malloc(sizeof(struct node)); preptr=ns; while(preptr->link != NULL) preptr = preptr->link; preptr->link = new_node; new_node->data = ptr->data; new_node->link = NULL; ptr=ptr->link; } printf("List HAS BEEN Copied!\n"); printf("New List>>>>"); display(ns); return start; }*/ int main() { int ch; do { printf("\nMENU\n1.CREATE 2.INSERT_BEG 3.INSERT_END 4.INSERT AFTER THE NODE 5.INSERT BEFORE THE NODE\n"); printf(" 6.DELETE FROM BEG 7. DELETE FROM END 8. DELETE BEFORE 9.DISPLAY 10.END\n"); printf("ENTER YOUR CHOICE\n "); scanf("%d",&ch); switch(ch) { case 1: create(); break; case 2: insertbeg(); break; case 3: insertend(); break; case 4: inserta(); break; case 5: insertb(); break; case 6: deletebeg(); break; case 7: deleteend(); break; case 8: deleteb(); break; case 9: display(); break; case 10: printf("EXIT"); break; default: printf("Incorrect input"); break; } }while(ch!=10); getch(); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #define PI 3.141592654 typedef struct { int col_no; int row_no; double **data; } Matrix; Matrix *matrix_init(int row_no, int col_no) { Matrix *matrix = (Matrix *)malloc(sizeof(Matrix)); matrix->col_no = col_no; matrix->row_no = row_no; matrix->data = (double **)malloc(row_no * sizeof(double *)); for (int i = 0; i < row_no; i++) matrix->data[i] = (double *)malloc(col_no * sizeof(double)); return matrix; } void matrix_set_all(Matrix *matrix, const double val) { for (int i = 0; i < matrix->row_no; i++) for (int j = 0; j < matrix->col_no; j++) matrix->data[i][j] = val; } Matrix *tri_symm_matrix_init(const double a[], const double b[], int n) { Matrix *matrix = matrix_init(n, n); matrix_set_all(matrix, 0); for (int i = 1; i < n - 1; i++) { matrix->data[i][i] = a[i]; matrix->data[i][i - 1] = b[i - 1]; matrix->data[i][i + 1] = b[i]; } matrix->data[0][0] = a[0]; matrix->data[0][1] = b[0]; matrix->data[n - 1][n - 1] = a[n - 1]; matrix->data[n - 1][n - 2] = b[n - 2]; return matrix; } Matrix *trans_matrix(const Matrix *matrix) { Matrix *trans = matrix_init(matrix->col_no, matrix->row_no); for (size_t i = 0; i < trans->row_no; i++) { for (size_t j = 0; j < trans->col_no; j++) { trans->data[i][j] = matrix->data[j][i]; } } return trans; } double complex *tri_symm_matrix_eigen(const Matrix *matrix) { if (matrix->row_no != matrix->col_no) return NULL; int n = matrix->row_no; double a = matrix->data[0][0]; double b = matrix->data[1][0]; double c = matrix->data[0][1]; double complex *eigenvals = (double complex *)malloc(n * sizeof(double complex)); double complex bc = b * c; for (int k = 0; k < n; k++) eigenvals[k] = a + 2 * csqrt(bc) * cos((k + 1) * PI / (n + 1)); return eigenvals; } void print(const Matrix *matrix) { for (int i = 0; i < matrix->row_no; i++) { for (int j = 0; j < matrix->col_no; j++) printf("%7.3g", matrix->data[i][j]); printf("\n"); } printf("\n"); } void vector_set_all(double *vec, double val, int n) { for (size_t i = 0; i < n; i++) vec[i] = val; } Matrix *scale_matrix(Matrix *matrix, double val) { Matrix *scaled = matrix_init(matrix->row_no, matrix->col_no); for (size_t i = 0; i < matrix->row_no; i++) { for (size_t j = 0; j < matrix->col_no; j++) { scaled->data[i][j] = matrix->data[i][j] * val; } } return scaled; } Matrix *multiple_matrix(Matrix *A, Matrix *B) { if (A->col_no != B->row_no) return NULL; int m = A->col_no; Matrix *C = matrix_init(A->row_no, B->col_no); for (size_t i = 0; i < A->row_no; i++) for (size_t j = 0; j < B->col_no; j++) for (size_t k = 0; k < m; k++) C->data[i][j] += A->data[i][k] * B->data[k][j]; return C; } Matrix *multiple_matrix_vec(Matrix *A, double *vec, int n) { if (A->col_no != n) return NULL; int m = A->row_no; Matrix *result = matrix_init(m, 1); matrix_set_all(result, 0); for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { result->data[i][0] += A->data[i][j] * vec[j]; } } return result; } Matrix *multiple_vec_matrix(Matrix *A, double *vec, int n) { if (A->row_no != n) return NULL; int m = A->col_no; Matrix *result = matrix_init(1, m); matrix_set_all(result, 0); for (size_t i = 0; i < m; i++) { for (size_t j = 0; j < n; j++) { result->data[0][i] += A->data[j][i] * vec[j]; } } return result; } Matrix *identity_matrix(int n) { Matrix *matrix = matrix_init(n, n); matrix_set_all(matrix, 0); for (size_t i = 0; i < n; i++) { matrix->data[i][i] = 1; } return matrix; } double *scale_vector(double *vector, double val, int n) { double *scaled = (double *)malloc(n * sizeof(double)); for (size_t i = 0; i < n; i++) { scaled[i] = vector[i] * val; } return scaled; } double norm2_vector(double *vec, int n) { double result = 0; for (size_t i = 0; i < n; i++) result += vec[i] * vec[i]; return sqrt(result); } double *vector_cpy(double *vector, int n) { double *copy = (double *)malloc(n * sizeof(double)); for (size_t i = 0; i < n; i++) copy[i] = vector[i]; return copy; } void matrix_sub(Matrix *A, Matrix *B, Matrix *result) { if (A->col_no != B->col_no || A->row_no != B->row_no) return; int n = A->row_no; int m = A->col_no; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < m; j++) { result->data[i][j] = A->data[i][j] - B->data[i][j]; } } } void matrix_sum(Matrix *A, Matrix *B, Matrix *result) { if (A->col_no != B->col_no || A->row_no != B->row_no) return; int n = A->row_no; int m = A->col_no; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < m; j++) { result->data[i][j] = A->data[i][j] + B->data[i][j]; } } } void matrix_to_vec(Matrix *A, double *vec, int n) { for (size_t i = 0; i < n; i++) { vec[i] = A->data[i][0]; } } void vec_to_matrix(Matrix *A, double *vec, int n) { for (size_t i = 0; i < n; i++) { A->data[i][0] = vec[i]; } } void print_vec(double *vec, int n) { printf("["); for (size_t i = 0; i < n; i++) { printf("%f ", vec[i]); } printf("]\n"); } void symm_lanczos_method(Matrix *A, double *vec, Matrix *T, Matrix *V) { if (A->col_no != A->row_no) return; int n = A->row_no; double a, b = 1; double **v = (double **)malloc((n + 1) * sizeof(double *)), *bv; Matrix *Av = matrix_init(n, 1), *bv_mat = matrix_init(n, 1), *vAv = matrix_init(1, 1), *iden = identity_matrix(n); v[0] = (double *)malloc(n * sizeof(double)); vector_set_all(v[0], 0, n); double *r = vector_cpy(vec, n); for (size_t i = 0; i < n; i++) { v[i + 1] = (double *)malloc(n * sizeof(double)); v[i + 1] = scale_vector(r, 1 / b, n); Av = multiple_matrix_vec(A, v[i + 1], n); vAv = multiple_vec_matrix(Av, v[i + 1], n); a = vAv->data[0][0]; T->data[i][i] = a; Av = scale_matrix(iden, a); matrix_sub(A, Av, Av); Av = multiple_matrix_vec(Av, v[i + 1], n); bv = scale_vector(v[i], b, n); vec_to_matrix(bv_mat, bv, n); matrix_sub(Av, bv_mat, Av); matrix_to_vec(Av, r, n); b = norm2_vector(r, n); if (i < n - 1) { T->data[i + 1][i] = b; T->data[i][i + 1] = b; } } for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n; j++) { V->data[i][j] = v[i + 1][j]; } } } float determinant(const Matrix *A, float k) { float s = 1, det = 0; Matrix *B = matrix_init(A->row_no, A->col_no); int i, j, m, n, c; if (k == 1) return A->data[0][0]; else { det = 0; for (c = 0; c < k; c++) { m = 0; n = 0; for (i = 0; i < k; i++) { for (j = 0; j < k; j++) { B->data[i][j] = 0; if (i != 0 && j != c) { B->data[m][n] = A->data[i][j]; if (n < (k - 2)) n++; else { n = 0; m++; } } } } det = det + s * (A->data[0][c] * determinant(B, k - 1)); s = -1 * s; } } return (det); } /*Finding transpose of matrix*/ Matrix *transpose(Matrix *A, Matrix *fac, float r) { int i, j; float d; Matrix *B = matrix_init(A->row_no, A->col_no); Matrix *inverse = matrix_init(A->row_no, A->col_no); for (i = 0; i < r; i++) { for (j = 0; j < r; j++) { B->data[i][j] = fac->data[j][i]; } } d = determinant(A, r); for (i = 0; i < r; i++) { for (j = 0; j < r; j++) { inverse->data[i][j] = B->data[i][j] / d; } } return inverse; } Matrix *hilb(int n) { Matrix *hilb = matrix_init(n, n); double tmp; for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < n; j++) { tmp = i + j + 1; hilb->data[i][j] = 1 / tmp; } } return hilb; } Matrix *inverse_matrix(Matrix *A, float f) { Matrix *B = matrix_init(A->row_no, A->col_no); Matrix *fac = matrix_init(A->row_no, A->col_no); int p, q, m, n, i, j; for (q = 0; q < f; q++) { for (p = 0; p < f; p++) { m = 0; n = 0; for (i = 0; i < f; i++) { for (j = 0; j < f; j++) { if (i != q && j != p) { B->data[m][n] = A->data[i][j]; if (n < (f - 2)) n++; else { n = 0; m++; } } } } fac->data[q][p] = pow(-1, q + p) * determinant(B, f - 1); } } return transpose(A, fac, f); } Matrix *diag(Matrix *A) { int n = A->row_no; Matrix *diag = matrix_init(n, n); matrix_set_all(diag, 0); for (size_t i = 0; i < n; i++) { diag->data[i][i] = A->data[i][i]; } return diag; } Matrix *upper(Matrix *A) { int n = A->row_no; int m = A->col_no; Matrix *upper = matrix_init(n, m); for (size_t i = 0; i < n; i++) { for (size_t j = i + 1; j < m; j++) { upper->data[i][j] = A->data[i][j]; } } return upper; } Matrix *lower(Matrix *A) { int n = A->row_no; int m = A->col_no; Matrix *lower = matrix_init(n, m); for (size_t i = 0; i < n; i++) { for (size_t j = 0; j < i; j++) { lower->data[i][j] = A->data[i][j]; } } return lower; } double *jacobi(Matrix *A, double *b, double *x0, const double tol) { int n = A->row_no; double *r_vec = (double *)malloc(n * sizeof(double)); double *x = vector_cpy(x0, n); Matrix *b_mat = matrix_init(n, 1), *r = matrix_init(n, 1); Matrix *ul = matrix_init(n, n); Matrix *x_mat = matrix_init(n, 1); Matrix *D = diag(A); Matrix *L = lower(A); Matrix *U = upper(A); matrix_sum(U, L, ul); Matrix *d_inv = inverse_matrix(D, n); Matrix *B_j = scale_matrix(d_inv, -1); B_j = multiple_matrix(B_j, ul); Matrix *b_j = multiple_matrix_vec(d_inv, b, n); Matrix *Ax0 = multiple_matrix_vec(A, x0, n); vec_to_matrix(b_mat, b, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); while (norm2_vector(r_vec, n) >= tol) { Matrix *Bx = multiple_matrix_vec(B_j, x, n); matrix_sum(Bx, b_j, x_mat); matrix_to_vec(x_mat, x, n); Ax0 = multiple_matrix_vec(A, x, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); } return x; } void vector_sum(double *vec1, double *vec2, double *result, int n) { for (size_t i = 0; i < n; i++) { result[i] = vec1[i] + vec2[i]; } } double *conj_grad(Matrix *A, double *b, double *x0, const double tol) { int n = A->row_no; double beta, a; double *r_vec = (double *)malloc(n * sizeof(double)); double *r_tmp = (double *)malloc(n * sizeof(double)); double *ap; double *x = vector_cpy(x0, n); Matrix *b_mat = matrix_init(n, 1), *r = matrix_init(n, 1), *p = matrix_init(n, 1); Matrix *r_tmp_mat, *w, *pt, *ptw, *aw, *bp; Matrix *Ax0 = multiple_matrix_vec(A, x0, n); vec_to_matrix(b_mat, b, n); matrix_sub(b_mat, Ax0, r); matrix_to_vec(r, r_vec, n); double *p_vec = vector_cpy(r_vec, n); while (norm2_vector(r_vec, n) * norm2_vector(r_vec, n) >= tol) { w = multiple_matrix_vec(A, p_vec, n); vec_to_matrix(p, p_vec, n); pt = trans_matrix(p); ptw = multiple_matrix(pt, w); a = norm2_vector(r_vec, n) * norm2_vector(r_vec, n) / ptw->data[0][0]; ap = scale_vector(p_vec, a, n); vector_sum(x, ap, x, n); aw = scale_matrix(w, a); r_tmp = vector_cpy(r_vec, n); matrix_sub(r, aw, r); matrix_to_vec(r, r_vec, n); beta = norm2_vector(r_vec, n) * norm2_vector(r_vec, n) / (norm2_vector(r_tmp, n) * norm2_vector(r_tmp, n)); bp = scale_matrix(p, beta); matrix_sum(r, bp, r); matrix_to_vec(p, p_vec, n); matrix_to_vec(r, r_vec, n); } return x; } double *gauss_seidel(Matrix *A, double *b, double *x0, const double tol) { int n = A->row_no; double *r_vec = (double *)malloc(n * sizeof(double)); double *x = vector_cpy(x0, n); Matrix *b_mat = matrix_init(n, 1), *r = matrix_init(n, 1); Matrix *dl = matrix_init(n, n); Matrix *x_mat = matrix_init(n, 1); Matrix *D = diag(A); Matrix *L = lower(A); Matrix *U = upper(A); matrix_sum(D, L, dl); Matrix *dl_inv = inverse_matrix(dl, n); Matrix *B_gs = scale_matrix(dl_inv, -1); B_gs = multiple_matrix(B_gs, U); Matrix *b_gs = multiple_matrix_vec(dl_inv, b, n); Matrix *Ax0 = multiple_matrix_vec(A, x0, n); vec_to_matrix(b_mat, b, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); while (norm2_vector(r_vec, n) >= tol) { Matrix *Bx = multiple_matrix_vec(B_gs, x, n); matrix_sum(Bx, b_gs, x_mat); matrix_to_vec(x_mat, x, n); Ax0 = multiple_matrix_vec(A, x, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); } return x; } double *sor_method(Matrix *A, double *b, double *x0, const double w, const double tol) { int n = A->row_no; double *r_vec = (double *)malloc(n * sizeof(double)); double *x = vector_cpy(x0, n); Matrix *b_mat = matrix_init(n, 1), *r = matrix_init(n, 1); Matrix *dl = matrix_init(n, n), *du = matrix_init(n, n); Matrix *x_mat = matrix_init(n, 1); Matrix *D = diag(A); Matrix *L = lower(A); Matrix *U = upper(A); Matrix *wL = scale_matrix(L, w); Matrix *wU = scale_matrix(U, w); Matrix *wD = scale_matrix(D, 1 - w); matrix_sum(D, wL, dl); Matrix *dl_inv = inverse_matrix(dl, n); matrix_sub(wD, wU, du); Matrix *B_sor = multiple_matrix(dl_inv, du); Matrix *wdl_inv = scale_matrix(dl_inv, w); Matrix *b_sor = multiple_matrix_vec(wdl_inv, b, n); Matrix *Ax0 = multiple_matrix_vec(A, x0, n); vec_to_matrix(b_mat, b, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); while (norm2_vector(r_vec, n) >= tol) { Matrix *Bx = multiple_matrix_vec(B_sor, x, n); matrix_sum(Bx, b_sor, x_mat); matrix_to_vec(x_mat, x, n); Ax0 = multiple_matrix_vec(A, x, n); matrix_sub(Ax0, b_mat, r); matrix_to_vec(r, r_vec, n); } return x; } int main() { // Matrix *iden = identity_matrix(2); // Matrix *one = matrix_init(2, 2); // double vec[] = {2, -1}; // matrix_set_all(one, 1); // Matrix *mat = matrix_init(3, 3); // mat->data[0][0] = 1; // mat->data[0][1] = 2; // mat->data[0][2] = 3; // mat->data[1][0] = 2; // mat->data[1][1] = 3; // mat->data[1][2] = 4; // mat->data[2][0] = 3; // mat->data[2][1] = 4; // mat->data[2][2] = 5; // Matrix *c = upper(mat); // print(c); /************************ Tridiagonal Symmetric Matrix Eigenvalues *************************************/ // double a[] = {2, 2, 2, 2}, b[] = {9, 4, 7}; // Matrix *mat = tri_symm_matrix_init(a, b, 4); // printf("The matrix is:\n"); // print(mat); // double complex *eigens = tri_symm_matrix_eigen(mat); // if(eigens == NULL) // return -1; // printf("The eigenvalues is:\n"); // for(int i = 0; i < mat->col_no; i++) // printf("%4.4f%+4.4fi\n", creal(eigens[i]), cimag(eigens[i])); // return 0; /************************* Lanczos Method *****************************************************************/ // Matrix *mat = matrix_init(3, 3); // mat->data[0][0] = 1; // mat->data[0][1] = 2; // mat->data[0][2] = 3; // mat->data[1][0] = 2; // mat->data[1][1] = 3; // mat->data[1][2] = 4; // mat->data[2][0] = 3; // mat->data[2][1] = 4; // mat->data[2][2] = 5; // double vec[] = {1, 0, 0}; // Matrix *T = matrix_init(3, 3); // Matrix *V = matrix_init(3, 3); // matrix_set_all(T, 0); // printf("Matrix A is:\n"); // print(mat); // symm_lanczos_method(mat, vec, T, V); // printf("Matrix T is:\n"); // print(T); // printf("Matrix V is:\n"); // print(V); /************************************ SOR Method ******************************/ Matrix *mat = matrix_init(3, 3); mat->data[0][0] = 5; mat->data[0][1] = 1; mat->data[0][2] = 1; mat->data[1][0] = 1; mat->data[1][1] = 5; mat->data[1][2] = 1; mat->data[2][0] = 1; mat->data[2][1] = 1; mat->data[2][2] = 5; Matrix *A = hilb(5); double b[] = {1, 1, 1, 1, 1}; double x0[] = {1, 1, 1, 1, 1}; double *res = conj_grad(A, b, x0, 0.0001); print_vec(res, 5); }
C
#include<stdio.h> #include"common.h" int stringLen(char *s){ int n; for (n=0; *s++;n++) ; return n; } char* strCopy(char *s,char *dist){ while((*dist++=*s++)) ; return dist; } int getLine(char *s,int max){ int c; int i = 0; while((c=getchar()) != '\n' && c != EOF){ *s++ = c; i++; } *s = '\0'; return i; } char* reverseString(char *s){ int length = stringLen(s); int start = 0; int end = length-1; char temp; while(start < length/2){ temp = s[start]; s[start++] = s[end]; s[end--] = temp; } return s; }
C
#define _GNU_SOURCE #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> // In dieser Funktion werden die Wertepaare abgezählt, // indem die entsprechenden Zeilen gezählt werden. // // Die Ausgabe dieser Funktion ist gleich der Anzahl der Wertepaare. int getNumberOfPoints(char *name) { FILE *fp; char *line = NULL; size_t len = 0; if ((fp = fopen(name, "r")) == NULL) { exit(EXIT_FAILURE); } int cnt = 0; while (getline(&line, &len, fp) != -1) { cnt++; } free(line); return cnt; } // In dieser Funktion werden die Wertepaare eingelesen und // in Form von Arrays x[N] und y[N] übergeben. void readFile(char *name, double x[], double y[]) { FILE *fp; char *line = NULL; size_t len = 0; if ((fp = fopen(name, "r")) == NULL) { exit(EXIT_FAILURE); } int cnt = 0; while (getline(&line, &len, fp) != -1) { sscanf(line, "%lf %lf", &x[cnt], &y[cnt]); cnt++; } free(line); } int main(int argc, char *argv[]) { // Abzählen der Wertepaare. int N = getNumberOfPoints("input.dat"); double x[N]; // Vektor für die Abstände der Messungen double y[N]; // Vektor für die gemessenen Werte // Einlesen der Daten. readFile("input.dat", x, y); // Laufvariablen int i, j; double D[N][N]; // für eine Matrix der Dimnsion NxN // Berechnen Sie die dividierten Differenzen: for (int i = 0; i < N; i++) { D[i][0] = y[i]; } for (int i = 1; i < N; i++) { for (int j = 1; j <= i; j++) { D[i][j] = (D[i][j - 1] - D[i - 1][j - 1]) / (x[i] - x[i - j]); } } // Geben Sie hier die dividierten Differenzen in Form einer Matrix aus: printf("\n Ausgabe der dividierten Differenzen D: \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { printf("%8.5lf", D[i][j]); } printf("\n"); } /*********************************************************************/ /* Zu Erinnerung: */ /* %3d - Ganzzahl mit 3 Stellen */ /* %.14lf - Fließkommazahl mit 14 Nachkommastellen */ /* \n - Neue Zeile */ /* Beispiel: printf("%3d: % .2lf % .2lf\n", Variablen); */ /* 000: -0.01 0.01 */ /*********************************************************************/ // Weisen Sie dem Vektor a die Polynomkoeffizienten aus den entsprechenden // Einträgen der Matrix D zu: double a[N]; // Vektor der Länge N for (int i = 0; i < N; i++) { a[i] = D[i][i]; } // Geben Sie das Polynom aus: printf("%.3lf", a[0]); for (int i = 1; i < N; i++) { printf("%.3lf", a[i]); for (size_t j = 0; j < i; j++) { printf("(x-%.1lf", x[j]); printf(")"); } printf("\n"); } printf("\n"); int useplotter = 1; if (useplotter) { // Plotten des Polynoms FILE *gp = popen("gnuplot -p", "w"); fprintf(gp, "set key right bottom box; set xrange [0:5]; set yrange [-8:3.5]; " "set xlabel \"x\"; set ylabel \"y\";\n"); fprintf(gp, "f(x) = "); for (i = 0; i < N; i++) { fprintf(gp, "+%lf", a[i]); for (j = 0; j < i; j++) { fprintf(gp, "*(x-%lf)", x[j]); } } fprintf(gp, ";\n"); fprintf(gp, "plot f(x) lc 3 ti \"Interpolation\", \"input.dat\" lc 4 ps 3 lw 2 " "ti \"data\";\n"); pclose(gp); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_ptr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ajordan- <ajordan-@student.42urduliz.com> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/10 13:20:43 by ajordan- #+# #+# */ /* Updated: 2021/10/19 14:54:45 by ajordan- ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" #include "libft.h" int ft_ptr_len(uintptr_t num) { int len; len = 0; while (num != 0) { len++; num = num / 16; } return (len); } void ft_put_ptr(uintptr_t num) { if (num >= 16) { ft_put_ptr(num / 16); ft_put_ptr(num % 16); } else { if (num <= 9) ft_putchar_fd((num + '0'), 1); else ft_putchar_fd((num - 10 + 'a'), 1); } } int ft_print_ptr(unsigned long long ptr) { int print_length; print_length = 0; print_length += write(1, "0x", 2); if (ptr == 0) print_length += write(1, "0", 1); else { ft_put_ptr(ptr); print_length += ft_ptr_len(ptr); } return (print_length); }
C
#include <stdio.h> #include <stdlib.h> #include "struct.h" // LIST_PERSONPERSONlj int add(LIST_PERSON** list, PERSON person) { // Kvȃm LIST_PERSON* newlist = (LIST_PERSON*)malloc(sizeof(LIST_PERSON)); if (newlist == NULL) { // mێs return -1; } // lݒ newlist->person = person; // ̃|C^NULLݒ newlist->next = NULL; // LIST̃|C^nextV[NĎ擾 while (*list != NULL) { list = &((*list)->next); } // LIST̃|C^nextɒljf[^̃|C^ݒ(AhXA邱ƂŒlj) *list = newlist; return 0; } // LIST_PERSOÑ int release(LIST_PERSON** list) { if (*list == NULL) { // LISTNULL̏ꍇΏۂߏI return -1; } LIST_PERSON* next; LIST_PERSON* del; // ̃|C^擾 next = (*list)->next; // S|C^̗̈ while (next != NULL) { // ̃AhXꍇ // ̃AhX폜ΏۂƂĎ擾 del = next; // ̎̃AhXێ next = next->next; // ̃AhX̃ free(del); } // ŏ̃ free(*list); return 0; }
C
/* Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "libaddb/addbp.h" #include "libaddb/addb-smap.h" #include <errno.h> #include <limits.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> /** * @brief Remove a smap database from a file tree. * * The call fails if any of the files to be removed don't look right * - don't have the right magic number, or extension, or if there are * additional files in the directory that shouldn't be there. * * This call is intended to surgically remove only a database * that we know is there. * * @param addb opaque database handle * @param path pathname of the SMAP directory. * @return 0 on success, a nonzero error code on error. */ int addb_smap_remove(addb_handle* addb, char const* path) { unsigned int partition = 0; char* partition_path; char* partition_base; size_t partition_base_n = 80; size_t const path_n = strlen(path); int err; partition_path = cm_malloc(addb->addb_cm, path_n + partition_base_n); if (!partition_path) { err = errno; cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "cm_malloc", errno, "addb: failed to allocate %lu bytes for partition file name", (unsigned long)path_n + partition_base_n); return err; } memcpy(partition_path, path, path_n); partition_base = partition_path + path_n; if (partition_base > partition_path && partition_base[-1] != '/') { *partition_base++ = '/'; partition_base_n--; } for (; partition < ADDB_GMAP_PARTITIONS_MAX; partition++) { addb_smap_partition_basename(addb, partition, partition_base, partition_base_n); if (unlink(partition_path)) { err = errno; if (ENOENT == err) err = 0; else cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "unlink", err, "addb: can't remove smap " "partition \"%s\"", partition_path); } } cm_free(addb->addb_cm, partition_path); err = addb_largefile_remove(path, addb->addb_cl, addb->addb_cm); if (err) cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "addb_largefile_remove", err, "unable to remove largefiles for \"%s\"", path); if (rmdir(path)) { if (!err) err = errno; cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "rmdir", errno, "unable to remove \"%s\"", path); } return err; } int addb_smap_truncate(addb_smap* sm, char const* path) { if (sm) { addb_handle* const addb = sm->sm_addb; addb_smap_partition* part = sm->sm_partition; addb_smap_partition* const part_end = sm->sm_partition + sm->sm_partition_n - 1; int err = 0; int e; for (; part < part_end; part++) if (part->part_td) { e = addb_tiled_backup(part->part_td, false); if (e) { if (!err) err = e; cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "addb_tiled_backup", e, "unable to turn off " "backup on \"%s\"", part->part_path); } } e = addb_smap_close(sm); if (e) { if (!err) err = e; cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "addb_smap_close", e, "unable to close \"%s\"", path); } e = addb_smap_remove(addb, path); if (e) { if (!err) err = e; cl_log_errno(addb->addb_cl, CL_LEVEL_ERROR, "addb_smap_remove", e, "unable to remove \"%s\"", path); } return err; } return 0; }
C
/* * Project: TJ Shell, a small Linux shell * File: tj_shell.c * Author: Tobias Johansson * Version: 1.0, 18 May 2015 * * Compilation: gcc -pedantic -ansi -Wall -Werror -O4 -D SIGDET=1 tj_shell.c */ #define _GNU_SOURCE #include <dirent.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> /* For detection of terminated background processes by signals sent from the child processes compile with SIGDET=1. If SIGDET is undefined or equals zero then termination will be detected by polling. */ #if SIGDET != 1 #define POLLING #endif #define STR_LEN (1023) #define MAX_CMDS (63) #define MAX_ARGS (63) /* per command */ #define PIPING (no_cmds > 1) #define FIRST_CMD (cmd == 1) #define MIDDLE_CMD (cmd > 1 && cmd < no_cmds) #define LAST_CMD (cmd == no_cmds) #define READ_END (0) #define WRITE_END (1) /*------------------------------------------------------------------------------ * PROTOTYPES */ /* Called from main */ void init(); void prompt(); /* Excecute commands */ int exec_cmdline(); int exec_cmd(); int fork_exec_wait(); void c_init(); int c_wait(); /* Built in commands */ void change_dir(); void check_env(); void term_all(); void put_fg(); /* Helper functions */ int child_process(); void get_env_cmd(); void malloc_strcpy(); void print_status(); void stdout_to_pipe(); void pipe_to_stdin(); void ten_ms_sleep(); void tokenize(); /*------------------------------------------------------------------------------ * GLOBAL VARIABLES */ pid_t shell_pid; /*------------------------------------------------------------------------------ * SIGNAL HANDLERS */ /* * Handles SIGCHLD signals or polling if SIGDET!=1. */ void sigchld_handler() { int status; pid_t c_pid; /* WUNTRACED: also return if a child has stopped WNOHANG: return immediately if no child has exited */ while ((c_pid = waitpid(WAIT_ANY, &status, WUNTRACED | WNOHANG)) > 0) { print_status(c_pid, status); } } /* * Handles SIGINT signals, that is usually Ctrl+C. */ void sigint_handler() { fprintf(stdout, "\n[Ctrl+C]\n"); term_all(); } /* * Handles SIGTSTP signals, that is usually Ctrl+Z. */ void sigtstp_handler() { fprintf(stdout, "\n[Ctrl+Z]\n"); if (kill(shell_pid, SIGSTOP) == -1) perror("kill"); } /*------------------------------------------------------------------------------ * MAIN */ /* * Drives the program. */ int main(int argc, char **argv) { init(argc); #ifdef POLLING fprintf(stdout, "\nWelcome to TJ Shell! (POLLING) \n\n"); #else fprintf(stdout, "\nWelcome to TJ Shell! (SIGDET=1) \n\n"); #endif while (1) { prompt(); ten_ms_sleep(10); #ifdef POLLING sigchld_handler(); #endif } } /*------------------------------------------------------------------------------ * CALLED FROM MAIN */ /* * Init. */ void init(int argc) { if (argc > 1) { fprintf(stderr, "init: TJ Shell does not take arguments\n"); exit(EXIT_FAILURE); } /* If not already: Set PGID=PID, this makes the shell process group leader. Take control of the terminal. */ shell_pid = getpid(); if (setpgid(shell_pid, shell_pid) == -1) { fprintf(stderr, "init: Could not set the shell process group leader\n"); exit(EXIT_FAILURE); } signal(SIGINT, sigint_handler); /* Ctrl+C: terminal interrupt signal */ signal(SIGQUIT, SIG_DFL); /* Ctrl+4: terminal quit signal */ signal(SIGTSTP, sigtstp_handler); /* Ctrl+Z: terminal stop signal */ signal(SIGTTIN, SIG_IGN); /* background process attempting read */ signal(SIGTTOU, SIG_IGN); /* background process attempting write */ #ifdef POLLING signal(SIGCHLD, SIG_DFL); /* child process terminated, stopped */ #else signal(SIGCHLD, sigchld_handler); #endif } /* * Prompt user, get command line and excecute commands. */ void prompt(void) { char c, cwd[STR_LEN+1], line[STR_LEN+1]; int i; if (shell_pid != getpid()) { fprintf(stderr, "prompt: Permission for child denied\n"); _exit(EXIT_FAILURE); } getcwd(cwd, sizeof(cwd)); fprintf(stdout, "%s> ", cwd); for (i = 0; (c = fgetc(stdin)) != '\n'; i++) { line[i] = c; } line[i] = '\0'; /* null-terminate string */ if (strlen(line) > 0) exec_cmdline(line); } /*------------------------------------------------------------------------------ * EXECUTE COMMANDS */ /* * Takes an unformatted command line and excecutes it. The function tokenize the * line for piping and by arguments. If any foreground child fail return a * number representing the command that failed there 1 represents the first, 2 * the second etc., otherwize return 0. */ int exec_cmdline(char const *line) { /* Allocates for arrays of MAX_X strings, last should point to NULL */ char **cmds = malloc((MAX_CMDS+1) * sizeof(char *)); char **args = malloc((MAX_ARGS+1) * sizeof(char *)); char s[STR_LEN+1]; int failed_cmd = 0, i, j, no_cmds, no_args; /* Get commands from the command line */ tokenize(cmds, &no_cmds, line, "|"); /* Execute commands one bye one */ for (i = 0; i < no_cmds; i++) { tokenize(args, &no_args, cmds[i], " "); if (no_args == 0) { failed_cmd = i + 1; fprintf(stderr, "exec_cmdline: Empty command\n"); break; } if (exec_cmd(args, no_args, i + 1, no_cmds) == -1) { failed_cmd = i + 1; sprintf(s, "%s", args[0]); for (j = 1; j < no_args; j++) sprintf(s, "%s %s", s, args[j]); fprintf(stderr, "exec_cmdline: Command '%s' failed\n", s); break; } } free(cmds); free(args); return failed_cmd; } /* * Takes a tokenized command, check for built in command and decides execution. * If foreground execution failed return -1, else 0. * * dtype const **var ⇒ var mutable, *var mutable, **var const * (var is a: pointer to pointer to const-dtype) */ int exec_cmd(char const **args, int no_args, int cmd, int no_cmds) { int background = 0; if (no_cmds == 1) { if (strcmp(args[0], "cd") == 0) { if (no_args == 1) {change_dir("~"); return 0;} if (no_args == 2) {change_dir(args[1]); return 0;} return -1; } if (strcmp(args[0], "checkEnv") == 0) { if (no_args <= 2) {check_env(args); return 0;} return -1; } if (strcmp(args[0], "exit") == 0) { if (no_args == 1) {term_all(); return 0;} return -1; } if (strcmp(args[0], "fg") == 0) { if (no_args == 2) {put_fg(args[1]); return 0;} return -1; } /* If background mode */ if (strcmp(args[no_args-1], "&") == 0) { if (no_args >= 2) { args[no_args-1] = NULL; /* replace "&" with NULL */ background = 1; } else { return -1; } } } /* All other commands: Fork-Exec-Wait (piping in background not allowed) */ return fork_exec_wait(args, cmd, no_cmds, background); } /* * Forks the process, the child executes a command and the parent waits the * child if background is set to 0. Piping can be made for following commands * there cmd is 1 for the first command and set 2 for second, etc. The variable * no_cmds should be set to number of commands for piping or 1 for a single * command. If foreground execution failed return -1, else 0. * * dtype *const *var ⇒ var mutable, *var const, **var mutable * (var is a: pointer to const-pointer to dtype) */ int fork_exec_wait(char *const *args, int cmd, int no_cmds, int background) { static int **pipe_fds, n; struct timeval t0; int i, return_value, status = 0; pid_t c_pid; if (PIPING && FIRST_CMD) { /* Allocates for no_cmds-1 pipes */ pipe_fds = malloc((no_cmds - 1) * sizeof(int *)); for (i = 0; i < (no_cmds - 1); i++) { /* Allocates for two file descriptors, read and write end */ pipe_fds[i] = malloc(2 * sizeof(int)); /* Retrive file descriptors */ if (pipe(pipe_fds[i]) == -1) { fprintf(stderr, "fork_exec_wait: Could not pipe\n"); exit(EXIT_FAILURE); } } n = 0; /* pipe count */ } if (PIPING && MIDDLE_CMD) n++; gettimeofday(&t0, NULL); /* start stopwatch */ /* Fork */ if ((c_pid = fork()) == -1) { fprintf(stderr, "fork_exec_wait: Could not fork\n"); exit(EXIT_FAILURE); } /* Exec (child) */ else if (c_pid == 0){ c_init(!background); if (PIPING) { if (FIRST_CMD) { stdout_to_pipe(pipe_fds[n]); } if (MIDDLE_CMD) { pipe_to_stdin(pipe_fds[n-1]); /* from prev */ stdout_to_pipe(pipe_fds[n]); /* to next */ } if (LAST_CMD) { pipe_to_stdin(pipe_fds[n]); } } /* The arrary position after the last argument must be set to NULL */ if (execvp(args[0], args) == -1) { _exit(EXIT_FAILURE); } } /* Wait (parent) */ else if (c_pid > 0) { if (PIPING) close(pipe_fds[n][WRITE_END]); /* widowing pipe */ if (!background && LAST_CMD) { fprintf(stdout, "[%d] Spawned in foreground\n", c_pid); status = c_wait(c_pid, &t0, 0); } else { fprintf(stdout, "[%d] Spawned in background\n", c_pid); } } if (!background && WEXITSTATUS(status) == EXIT_FAILURE) { return_value = -1; } else { return_value = 0; } if (PIPING && (LAST_CMD || (return_value == -1))) free(pipe_fds); return return_value; } /* * Init child. */ void c_init(int foreground) { /* Make the child leader of a new process group */ pid_t c_pid = getpid(); setpgid(c_pid, c_pid); if (foreground) { /* The child takes the terminal */ if (tcsetpgrp(STDIN_FILENO, getpgid(c_pid)) == -1) perror("tcsetpgrp"); } /* Signal handling to default */ signal(SIGINT , SIG_DFL); signal(SIGQUIT, SIG_DFL); signal(SIGTSTP, SIG_DFL); signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL); signal(SIGCHLD, SIG_DFL); } /* * Waits for a child in the foreground. If process is in background set cont=1 * for give over the terminal and continue the process, otherwise set 0. Returns * status from waitpid. */ int c_wait(pid_t c_pid, struct timeval const *t0, int cont) { int status; struct timeval t1, diff; if (cont) { if (tcsetpgrp(STDIN_FILENO, getpgid(c_pid)) == -1) perror("tcsetpgrp"); if (kill(c_pid, SIGCONT) == -1) perror("kill"); } /* Wait for childs death, WUNTRACED: also return if a child has stopped */ if (waitpid(c_pid, &status, WUNTRACED) > 0) { print_status(c_pid, status); if (t0 != NULL) { gettimeofday(&t1, NULL); /* stop stopwatch */ diff.tv_sec = t1.tv_sec - t0->tv_sec; diff.tv_usec = t1.tv_usec - t0->tv_usec; fprintf(stdout, "Run time was %.0f ms\n", diff.tv_sec * 1000.0 + diff.tv_usec / 1000.0); } } /* Reclaim the terminal */ if (tcsetpgrp(STDIN_FILENO, getpgid(shell_pid)) == -1) perror("tcsetpgrp"); return status; } /*------------------------------------------------------------------------------ * BUILT IN COMMANDS */ /* * Change directory. */ void change_dir(char const *path) { int i, path_len = strlen(path); char exec_path[STR_LEN+1], s[STR_LEN+1]; if (path[0] == '~') { /* Replace tilde by HOME environment */ for (i = 1; i < path_len + 1; i++) s[i-1] = path[i]; sprintf(exec_path, "%s%s", getenv("HOME"), s); } else { sprintf(exec_path, "%s", path); } if (chdir(exec_path) == -1) { fprintf(stderr, "change_dir: No such directory\n"); } } /* A built-in command "checkEnv" which executes "printenv | sort | pager" if no * arguments are given to the command. If arguments are passed to the command * then "printenv | grep <arguments> | sort | pager" executes. The pager * executed is selected primarily based on the value of the users "PAGER" * environment variable. If no such variable is set then first try to execute * "less" and if that fails "more". * * dtype const *const *var ⇒ var mutable, *var const, **var const * (var is a: pointer to const-pointer to const-dtype) */ void check_env(char const *const *args) { char line[STR_LEN+1], pager[STR_LEN+1]; int no_cmds = (args[1] == NULL ? 3 : 4); if (getenv("PAGER") != NULL) { sprintf(pager, "%s", getenv("PAGER")); } else { sprintf(pager, "less"); } get_env_cmd(line, args, pager); fprintf(stdout, "Actual command line: %s\n", line); if (exec_cmdline(line) == no_cmds && strcmp(pager, "less") == 0) { /* If less failed */ get_env_cmd(line, args, "more"); fprintf(stdout, "Actual command line: %s\n", line); exec_cmdline(line); } } /* * Terminates all children in an orderly manner. */ void term_all(void) { char path[STR_LEN+1]; DIR *dirp; FILE *fp; pid_t pid, ppid; struct dirent* dent; fprintf(stdout, "\nTJ Shell closing...\n\n"); if ((dirp = opendir("/proc")) == NULL) { fprintf(stderr, "term_all: Could not open '/proc'\n"); exit(EXIT_FAILURE); } /* Searches through all directories in /proc */ while((dent = readdir(dirp)) != NULL) { /* If numerical */ if (dent->d_name[0] >= '0' && dent->d_name[0] <= '9') { /* Take data from /proc/[pid]/stat, see URL below for more info. http://man7.org/linux/man-pages/man5/proc.5.html */ sprintf(path, "/proc/%s/stat", dent->d_name); fp = fopen(path,"r"); fscanf(fp, "%d %*s %*c %d", &pid, &ppid); fclose(fp); /* Kill if shell is parent to process */ if (shell_pid == ppid) if (kill(pid, SIGKILL) == -1) perror("kill"); } } closedir(dirp); ten_ms_sleep(10); /* wait for SIGKILL signals to terminate bg processes */ #ifdef POLLING sigchld_handler(); #endif exit(EXIT_SUCCESS); } /* * Put background process in the foreground. */ void put_fg(char const *s) { pid_t c_pid; sscanf(s, "%d", &c_pid); if (child_process(c_pid)) { c_wait(c_pid, NULL, 1); } else { fprintf(stderr, "put_fg: No such child\n"); } } /*------------------------------------------------------------------------------ * HELPER FUNCTIONS */ /* * Returns 1 if given pid is a child process, else 0. */ int child_process(pid_t c_pid) { char path[STR_LEN+1]; FILE *fp; pid_t ppid; sprintf(path, "/proc/%d/stat", c_pid); if ((fp = fopen(path,"r")) == NULL) return 0; fscanf(fp, "%*d %*s %*c %d", &ppid); fclose(fp); if (ppid == shell_pid) { return 1; } else { return 0; } } /* * Get command line for check of enviroment. * * dtype const *const *var ⇒ var mutable, var* const, var** const * (var is a: pointer to const-pointer to const-dtype) */ void get_env_cmd(char *line, char const *const *args, char const *pager) { if (args[1] == NULL) { sprintf(line, "printenv | sort | %s", pager); } else { sprintf(line, "printenv | sort | grep %s | %s", args[1], pager); } } /* * Takes dest a pointer to a string and src the source string. The function * allocates memory for dest and copies src to it. */ void malloc_strcpy(char **dest, char const *src) { if (src == NULL) {*dest = NULL; return;} *dest = malloc((strlen(src)+1) * sizeof(char)); /* +1 for null-terminated */ sprintf(*dest, "%s", src); } /* * Print childs wait status. */ void print_status(pid_t c_pid, int status) { if (WIFEXITED(status)) { fprintf(stdout, "[%d] Terminated normally\n", c_pid); } else if (WIFSIGNALED(status)) { fprintf(stdout, "[%d] Terminated by a signal\n", c_pid); } else if (WIFSTOPPED(status)) { fprintf(stdout, "[%d] Stopped\n", c_pid); } } /* * Pipes stdout to a pipe. */ void stdout_to_pipe(int const *pipe_fd) { close(pipe_fd[READ_END]); close(STDOUT_FILENO); if (dup2(pipe_fd[WRITE_END], STDOUT_FILENO) == -1) perror("dup2"); } /* * Pipes a pipe to stdin. */ void pipe_to_stdin(int const *pipe_fd) { close(pipe_fd[WRITE_END]); close(STDIN_FILENO); if (dup2(pipe_fd[READ_END], STDIN_FILENO) == -1) perror("dup2"); } /* * Sleeps ten milliseconds using nanosleep for so many times that is given. */ void ten_ms_sleep(int times) { int i; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 10000000; /* 10 ms */ /* Nanosleep gets interupted by signals */ for (i = 0; i < times; i++) { nanosleep(&ts, NULL); } } /* * Tokenizes a string for specified delimiters. The variable strs is an array of * unallocated strings and no_strs gives the number of output strings. The * allocation after the last string in strs is set to NULL. */ void tokenize(char **strs, int *no_strs, char const *input, char const *delim) { char *s; int i; malloc_strcpy(&s, input); malloc_strcpy(&strs[i = 0], strtok(s, delim)); while(strs[i] != NULL) { malloc_strcpy(&strs[++i], strtok(NULL, delim)); } *no_strs = i; free(s); }
C
#include "holberton.h" #include <stdlib.h> /** * string_nconcat - concat 2 strings up to n characters of 2nd * @s1: string 1 * @s2: string 2 * @n: number of characters of s2 to cat * Return: concatenated string or null if malloc fails */ char *string_nconcat(char *s1, char *s2, unsigned int n) { char *s3; int s3l, n1; unsigned int s2l, n2; if (s1 == NULL) s1 = ""; if (s2 == NULL) s2 = ""; s2l = _strlen(s2); if (s2l > n) s2l = n; s3l = _strlen(s1) + s2l; s3 = malloc(sizeof(char) * s3l + 1); if (s3 == NULL) { free(s3); return (NULL); } for (n1 = 0; s1[n1] != '\0'; n1++) s3[n1] = s1[n1]; for (n2 = 0; n2 < s2l; n1++, n2++) s3[n1] = s2[n2]; s3[s3l] = (char)0; return (s3); } /** * _strlen - count characters in array * @s: provided value in array * Return: length of array */ int _strlen(char *s) { int counter = 0; while (s[counter] != '\0') { counter++; } return (counter); }
C
#include <stdio.h> #include <stdlib.h> #include "ensemble.h" ensemble* creerEnsemble ( composante* c){ ensemble* e = (ensemble*)malloc(sizeof(ensemble)); e->tete = c; e->queue = c; c->ens = e; return e; } composante* trouverEnsemble (composante* c){ return( c->ens->tete ); } void Union(composante* c1,composante* c2){ composante* tmp = c2->ens->tete; c1->ens->queue->succ = tmp; c1->ens->queue = c2->ens->queue; while( tmp != NULL ){ tmp->ens = c1->ens; tmp = tmp->succ; } }
C
#include <stdio.h> int main(void){ int A, B, C, D; scanf("%d %d", &A, &B); scanf("%d %d", &C, &D); int DIFERENCA = A * B - C * D; printf("DIFERENCA = %d\n",DIFERENCA); return 0; }
C
#include "common.h" #include <avr/io.h> #include <util/delay.h> #include "leds.h" #include "gpio.h" #include "buttons.h" /****************************************************************** TIMER FUNCTIONS ******************************************************************/ // Global variable for timer volatile uint32_t ms_ticks = 0; // Red period is 1000 ms, Green period is 400 ms volatile uint32_t red_timer = RED_PERIOD; volatile uint32_t green_timer = GREEN_PERIOD; // PWM variables and constants #define TOP 0x00ff volatile uint32_t increment = TOP / 0x000f; volatile uint32_t new_duty_cycle = TOP / 2; volatile uint8_t direction = 0; /* * Timer 0 is used for the RED led. * Interrupt fires every 1 ms, 1000 Hz. */ void setup_timer_0(void) { // Set WGM bits for CTC mode - TIMER 0 CLEAR_BIT(TCCR0B, WGM02); // 0 SET_BIT(TCCR0A, WGM01); // 1 CLEAR_BIT(TCCR0A, WGM00); // 0 // Set CS Bits for prescalar 64 - TIMER 0 CLEAR_BIT(TCCR0B, CS02); // 0 SET_BIT(TCCR0B, CS01); // 1 SET_BIT(TCCR0B, CS00); // 1 // Set match to 250 - TIMER 0 OCR0A = (_16M / 64) / _kHz; // Enable Interrupt (mask) - TIMER 0 SET_BIT(TIMSK0, OCIE0A); } /* * Timer 1 is used for the GREEN2 led. * Controls PWM signal to adjust frequency */ void setup_timer_1(void) { // Set top value to 0xffff - TIMER 1 ICR1 = TOP; // Set WGM bits for PVM, phase correct - TIMER 1 SET_BIT(TCCR1B, WGM13); // 1 CLEAR_BIT(TCCR1B, WGM12); // 0 SET_BIT(TCCR1A, WGM11); // 1 CLEAR_BIT(TCCR1A, WGM10); // 0 // Set CS Bits for prescalar 1024 - TIMER 1 SET_BIT(TCCR1B, CS12); // 1 CLEAR_BIT(TCCR1B, CS11); // 0 SET_BIT(TCCR1B, CS10); // 1 // Set COM Bits for clear on compare match - TIMER 1 SET_BIT(TCCR1A, COM1B1); // 1 CLEAR_BIT(TCCR1A, COM1B0); // 0 // Set duty cycle - TIMER 1 // this is set by button C release // Should fluctuate between 0 and 0xffff OCR1B = new_duty_cycle; } /* * Timer 3 is used for the YELLOW led. * Interrupt fires every 250 ms, 2 Hz. */ void setup_timer_3(void) { // Set WGM bits for CTC mode - TIMER 3 CLEAR_BIT(TCCR3B, WGM33); // 0 SET_BIT(TCCR3B, WGM32); // 1 CLEAR_BIT(TCCR3A, WGM31); // 0 CLEAR_BIT(TCCR3A, WGM30); // 0 // Set CS Bits for prescalar 256 - TIMER 3 SET_BIT(TCCR3B, CS32); // 1 CLEAR_BIT(TCCR3B, CS31); // 0 CLEAR_BIT(TCCR3B, CS30); // 0 // Set match 31,250- TIMER 3 OCR3A = (_16M / 256) / YELLOW_HZ; // Enable Interrupt (mask) - TIMER 3 SET_BIT(TIMSK3, OCIE3A); } /* Timer 0: * 1000 Hz, every 1 ms * RED led */ ISR(TIMER0_COMPA_vect) { ms_ticks++; } /* Timer 3: * 2 Hz, every 250 ms * YELLOW led */ ISR(TIMER3_COMPA_vect) { led_toggle(&_yellowl); gpio_toggle(&_yellowg); } /****************************************************************** BUTTON FUNCTIONS ******************************************************************/ // Flags uint8_t aPress = 0; uint8_t cPress = 0; /* Button A Release */ void flagA(void) { aPress = 1; } /* Button C Release */ void flagC(void) { cPress = 1; } void setup_buttonA(void) { /* Initalize buttonA */ initialize_button(&_buttonA); /* Enable the PCINT for buttonA */ enable_pcint(&_interruptA); /* Connect buttonA to the appropriate interrupt actions */ // Release setup_button_action(&_interruptA, RELEASE, flagA); } void setup_buttonC(void) { /* Initalize buttonC */ initialize_button(&_buttonC); /* Enable the PCINT for buttonC */ enable_pcint(&_interruptC); /* Connect the buttonC to the appropriate interrupt actions */ // Release C setup_button_action(&_interruptC, RELEASE, flagC); } /****************************************************************** ALL INITIALIZATION ******************************************************************/ /* Set WGM bits in TCCRnA & TCCRnB, * Set Prescalar and Match, and * Enable Interrupt for Timer 1 & 3 */ void initialize_timers(void) { setup_timer_0(); setup_timer_1(); setup_timer_3(); } /* Initalize only buttonA and buttonC because they are connected to PCINT. * NOTE: button C and the RED led are on the same line. * Enable the PCINT for buttons A and C. This sets up for PCINT ISR. * Connect the buttons to the appropriate interrupt actions. */ // Only need Button A for lab 4...! void initialize_buttons(void) { setup_buttonA(); setup_buttonC(); } void initialize_system(void) { /* LEDS */ //initialize_led(YELLOWL); //initialize_led(GREENL); //initialize_led(REDL); /* GPIOS */ initialize_gpio(GREEN2); initialize_gpio(YELLOWG); initialize_gpio(GREENG); initialize_gpio(REDG); /* LED sanity check */ //light_show_led(); light_show_gpio(); /* Set up Timer 0 and Timer 3 */ initialize_timers(); /* Set up Button A and Button C */ initialize_buttons(); } /****************************************************************** MAIN ******************************************************************/ int main(void) { // This prevents the need to reset after flashing USBCON = 0; // Set up LEDs, timers, and buttons initialize_system(); // Enables all interrupts sei(); while(1) { // RED TIMER - toggle every 500 ms if (ms_ticks >= red_timer) { //led_toggle(&_redl); gpio_toggle(&_redg); red_timer = ms_ticks + RED_PERIOD; } // BUTTON A - toggle green gpio 5 times if (aPress) { int i = 0; while (i < 10) { if (ms_ticks >= green_timer) { //led_toggle(&_greenl); gpio_toggle(&_greeng); green_timer = ms_ticks + GREEN_PERIOD; i++; } } aPress = 0; } // BUTTON C - adjust PWM frequency if (cPress) { if (direction) { new_duty_cycle += INCREMENT; if (new_duty_cycle >= TOP) { direction = 0; new_duty_cycle = TOP; } cPress = 0; } else { new_duty_cycle += -INCREMENT; if (new_duty_cycle <= 0 || new_duty_cycle > TOP) { direction = 1; new_duty_cycle = 0; } cPress = 0; } } OCR1B = new_duty_cycle; } // end while(1) } /* end main() */
C
/* ** EPITECH PROJECT, 2020 ** MY GET NBR CHAR ** File description: ** NO DESCRIPTION FOUND */ int my_getnbrchar(char str) { if (str < '0' && str > '9' ) return (0); else return (str - 48); }
C
#include <mysql.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { MYSQL *conn; int err; MYSQL_RES *resultado; MYSQL_ROW row; conn = mysql_init(NULL); if (conn==NULL) { printf ("Error al crear la conexion: %u %s\n", mysql_errno(conn), mysql_error(conn)); exit (1); } conn = mysql_real_connect (conn, "localhost","root", "mysql", "Juego",0, NULL, 0); if (conn==NULL) { printf ("Error al inicializar la conexion: %u %s\n", mysql_errno(conn), mysql_error(conn)); exit (1); } char nombre[20]; printf ("Dame el nombre de un jugador\n"); scanf ("%s", nombre); char consulta [80]; strcpy (consulta,"SELECT DISTINCT Partida.ganador FROM Jugador,Partida,Historial WHERE Jugador.nombre = '"); strcat (consulta, nombre); strcat (consulta,"'AND Jugador.id = Historial.idJ AND Historial.idP = Partida.id AND Jugador.nombre!=Partida.ganador"); err=mysql_query (conn, consulta); if (err!=0) { printf ("Error al consultar datos de la base %u %s\n", mysql_errno(conn), mysql_error(conn)); exit (1); } resultado = mysql_store_result (conn); row = mysql_fetch_row (resultado); if (row == NULL) printf ("No se han obtenido datos en la consulta\n"); else printf ("Los que han ganado a %s son:\n", nombre); while (row !=NULL) { printf ("%s\n", row[0]); row = mysql_fetch_row (resultado); } mysql_close (conn); exit(0); }