language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> int main() { int i, j, x, y, k, hcf, lcm; printf("Enter two integers\n"); scanf("%d%d", &x, &y); i = x; j = y; while (j != 0) { k = j; j = i % j; i = k; } hcf = i; lcm = (x*y)/hcf; printf("highest common factor of %d and %d = %d\n", x, y, hcf); printf("Least common multiple of %d and %d = %d\n", x, y, lcm); return 0; }
C
#include <stdio.h> #include "complex.h" /* function mult2 that takes two complex structures, a and b, and returns a complex structure representing their product. [Recall if a = x1 + y1 i and b = x2 + y2 i, then a * b = (x1 * x2 - y1 * y2) + (x1 * y2 + x2 * y1) i ] */ int main(void) { test(); return 0; } complex mult2(complex *a, complex *b) { complex c; c.x = a->x*b->x - a->y*b->y; c.y = a->x*b->y+a->y*b->x; return c; }; /* function square that takes a complex structure and returns the square of that structure */ complex square(complex a) { complex sq; sq.x = a.x*a.x - a.y*a.y; sq.y = 2*a.x*a.y; return sq; }; /* function add2 that takes two complex structures, a and b, and returns a complex structure representing their sum. [Recall if a = x1 + y1 i and b = x2 + y2 i, then a + b = (x1 + x2) + (y1 + y2) i ] */ complex add2(complex *a, complex *b) { complex add; add.x = a->x + b->x; add.y = a->y+b->y; return add; }; /* function juliamap that takes two complex structures, z and c, and returns a complex structure representing the juliamap: z^2 + c. */ complex juliamap(complex a, complex b) { complex jm, a_tmp; a_tmp = square(a); jm = add2(&a_tmp, &b); return jm; }; /* complex_print that takes a complex structure, z, and prints the string "z = x + y i" where x and y are its real and imaginary parts. */ void complex_print(const complex z) { printf ("z = %.1Lf+%.1Lfi\n",z.x,z.y); }; /* function test that demonstrates that the functions (mult2, square, add2, juliamap, complex_to_str) work as desired by printing to the screen. */ void test() { complex a, b; a.x = 2.0; a.y = 3.0; b.x = 4; b.y = 5; printf("Input a and b where a + ib is the first complex number.\n"); printf("a = "); scanf("%Lf", &a.x); printf("b = "); scanf("%Lf", &a.y); printf("Input c and d where c + id is the second complex number.\n"); printf("c = "); scanf("%Lf", &b.x); printf("d = "); scanf("%Lf", &b.y); printf ("You have entered the complex numbers entered are :%.1Lf %+.1Lf and %.1Lf %+.1Lfi\n", a.x,a.y,b.x,b.y); printf ("The multiplication of complex numbers is :%.1Lf %+.1Lfi\n", mult2(&a,&b).x, mult2(&a,&b).y); printf ("The square of complex number is :%.1Lf %+.1Lfi\n", square(a).x, square(a).y); printf ("The addition of complex numbers are :%.1Lf %+.1Lfi\n", add2(&a,&b).x, add2(&a,&b).y); printf ("The juliamap of complex numbers are :%.1Lf %+.1Lfi\n", juliamap(a,b).x, juliamap(a,b).y); complex_print(a); complex_print(b); }
C
#include <stdio.h> #include <string.h> #include "../src/runtime-copy.c" #include <assert.h> // which indices we are currently on for one of the tensors, // given the indices we are on for the result tensor nat *curr_ind_tens(T *t, nat ind, int offset, nat *current_ind) { nat *t_ind = malloc(sizeof(nat) * (t->rank)); memset(t_ind, 0, sizeof(nat) * (t->rank)); for (int i = 0; i < ind; i++) { t_ind[i] = current_ind[i+offset]; } for (int j = ind+1; j < t->rank; j++) { t_ind[j] = current_ind[j-1+offset]; } return t_ind; } // res[0] = startInd // res[1] = product // shape and curr_ind must be from the same tensor nat *find_ind_and_prod(nat *shape, nat *curr_ind, nat rank, nat ind) { nat *res = malloc(sizeof(nat) * 2); memset(res, 0, sizeof(nat) * 2); int prod = 1; nat sum = 0; for (int i = rank-1; i >= 0; i--) { if (i < rank-1) prod *= shape[i+1]; sum += prod * curr_ind[i]; } res[0] = sum; res[1] = 1; for (int j = ind+1; j < rank; j++) { res[1] *= shape[j]; } return res; } T *contract_rec(T *t1, T *t2, T *res, nat ind1, nat ind2, nat *new_shape, nat new_rank, nat c, nat *current_ind) { if (c == new_rank) { nat offset = t1->rank; nat *curr_ind_t1 = curr_ind_tens(t1, ind1, 0, current_ind); nat *curr_ind_t2 = curr_ind_tens(t2, ind2, offset-1, current_ind); nat *ind_and_prod1 = find_ind_and_prod(t1->shape, curr_ind_t1, t1->rank, ind1); nat *ind_and_prod2 = find_ind_and_prod(t2->shape, curr_ind_t2, t2->rank, ind2); nat *ind_and_prod = find_ind_and_prod(new_shape, current_ind, new_rank, 0); for (int i = 0; i < t1->shape[ind1]; i++) { res->array[ind_and_prod[0]] += t1->array[ind_and_prod1[0] + ind_and_prod1[1] * i] * t2->array[ind_and_prod2[0] + ind_and_prod2[1] * i]; } free(curr_ind_t1); free(curr_ind_t2); free(ind_and_prod1); free(ind_and_prod2); free(ind_and_prod); } if (c < new_rank) { for (int i = 0; i < new_shape[c]; i++) { current_ind[c] = i; res = contract_rec(t1, t2, res, ind1, ind2, new_shape, new_rank, c+1, current_ind); } } return res; } T *contract(T *t1, T *t2, nat ind1, nat ind2, nat *new_shape, nat new_rank) { nat curr_ind[new_rank]; memset(curr_ind, 0, sizeof(nat) * new_rank); int size = 1; for (int i = 0; i < new_rank; i++) { size *= new_shape[i]; } double arr[size]; memset(arr, 0.0, sizeof(double) * size); T *res = talloc(new_rank, new_shape, arr); return contract_rec(t1, t2, res, ind1, ind2, new_shape, new_rank, 0, curr_ind); } int main() { nat s[] = {2, 4, 3}; double vals[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0}; T *someT = talloc(3, s, vals); nat s2[] = {2, 3, 4}; /*double vals2[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0};*/ double vals2[] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0}; T *otherT = talloc(3, s2, vals2); nat new_shape[] = {2, 4, 2, 4}; T *res = contract(someT, otherT, 2, 1, new_shape, 4); print_tensor(res); tdelete(someT); tdelete(otherT); tdelete(res); return 0; }
C
#include "../headers/core.h" mpi_env_t get_mpi_env(int numtasks, int root, int rank, int length){ mpi_env_t* env = (mpi_env_t*) malloc(sizeof(mpi_env_t)); env->numtasks = numtasks; env->root = root; env->rank = rank; int chunk = length / numtasks; //if i'm the last one if(rank == (numtasks - 1)){ chunk = length - (chunk * (numtasks - 1)); } env->chunk = chunk; env->receive_buffer = (int*) malloc(sizeof(int)*chunk); if(rank == 0){ env->offsets = (int*) malloc(sizeof(int)*numtasks); env->buffer_sizes = (int*) malloc(sizeof(int)*numtasks); for(int i = 0; i < numtasks; i++){ env->offsets[i] = i * chunk; } for(int i = 0; i < (numtasks - 1); i++){ env->buffer_sizes[i] = chunk; } env->buffer_sizes[numtasks - 1] = length - (chunk * (numtasks - 1)); } syslog(LOG_NOTICE, "ENV: Process %d --> chunk: %d\n", rank, chunk); return *env; } void normalize(int old_min, int old_max, int new_min, int new_max, mpi_env_t env){ double factor = (float)(new_max - new_min) / (float)(old_max - old_min); int* receive_buffer = env.receive_buffer; int chunk = env.chunk; int i; int chunk_size = chunk / omp_get_max_threads(); syslog(LOG_NOTICE, "NORM: Process %d --> using %d threads\n", env.rank, omp_get_max_threads()); #pragma omp parallel for \ schedule(static, chunk_size) \ shared(receive_buffer) \ private(i) \ firstprivate(new_min, factor, old_min) for(i = 0; i < chunk; i++){ receive_buffer[i] = (receive_buffer[i] - old_min) * factor + new_min; } } int get_max(mpi_env_t env){ int* receive_buffer = env.receive_buffer; int chunk = env.chunk; int global_max = 0; int local_max = 0; syslog(LOG_NOTICE, "MAX: Process %d --> using %d threads\n", env.rank, omp_get_max_threads()); #pragma omp parallel shared(receive_buffer, local_max) { int submax = 0, i; #pragma omp for for (i = 0; i < chunk; i++) { if (receive_buffer[i] > submax) submax = receive_buffer[i]; } syslog(LOG_NOTICE, "MAX: Process %d --> Thread %d --> submax: %d\n", env.rank, omp_get_thread_num(), submax); #pragma omp critical if(submax > local_max) local_max = submax; } syslog(LOG_NOTICE, "MAX: Process %d --> local_max: %d\n", env.rank, local_max); MPI_Allreduce(&local_max, &global_max, 1, MPI_INT, MPI_MAX, MPI_COMM_WORLD); syslog(LOG_NOTICE, "MAX: Process %d --> global_max: %d\n", env.rank, global_max); return global_max; } int get_min(mpi_env_t env){ int* receive_buffer = env.receive_buffer; int chunk = env.chunk; int global_min = 255; int local_min = 255; syslog(LOG_NOTICE, "MIN: Process %d --> using %d threads\n", env.rank, omp_get_max_threads()); #pragma omp parallel shared(receive_buffer, local_min) { int submin = 255, i; #pragma omp for for (i = 0; i < chunk; i++) { if (receive_buffer[i] < submin) submin = receive_buffer[i]; } syslog(LOG_NOTICE, "MIN: Process %d --> Thread %d --> submin: %d\n", env.rank, omp_get_thread_num(), submin); #pragma omp critical if(submin < local_min) local_min = submin; } syslog(LOG_NOTICE, "MIN: Process %d --> local_min: %d\n", env.rank, local_min); MPI_Allreduce(&local_min, &global_min, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD); syslog(LOG_NOTICE, "MIN: Process %d --> global_min: %d\n", env.rank, global_min); return global_min; } void scatter_pixels(int* pixels, mpi_env_t env){ int* buffer_sizes = env.buffer_sizes; int* offsets = env.offsets; int* receive_buffer = env.receive_buffer; int chunk = env.chunk; int root = env.root; MPI_Scatterv(pixels, buffer_sizes, offsets, MPI_INT, receive_buffer, chunk, MPI_INT, root, MPI_COMM_WORLD); } void gather_pixels(int* pixels, mpi_env_t env){ int* buffer_sizes = env.buffer_sizes; int* offsets = env.offsets; int* receive_buffer = env.receive_buffer; int chunk = env.chunk; int root = env.root; MPI_Gatherv(receive_buffer, chunk, MPI_INT, pixels, buffer_sizes, offsets, MPI_INT, root, MPI_COMM_WORLD); }
C
#include <stdio.h> int main() { char str[] = "Hello world"; printf("%s \n", str); printf("%10s \n", str); printf("%.10s \n", str); printf("%-10s \n", str); printf("%-15s \n", str); printf("%15.10s \n", str); printf("%-15.10s\n", str); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct node { char string[100]; int freq; struct node *next; }Node; int insert(Node **H,char *w) { Node *x; if((*H)==NULL) { (*H)=(Node*)malloc(sizeof(Node)); strcpy((*H)->string,w); (*H)->freq=1; (*H)->next=NULL; } else { Node *current=*H,*prev=NULL; while(current!=NULL) { if(strcmp(w,current->string)==0) { current->freq=(current->freq)+1; break; } x=current; current=current->next; } if(current==NULL) { x->next=(Node*)malloc(sizeof(Node)); strcpy(x->next->string,w); x->next->freq=1; x->next->next=NULL; } } return 0; } int display(Node **H) { if((*H)==NULL) printf("Error !!"); else { Node *current=*H; while(current!=NULL) { printf("%s\t%d",(current->string),(current->freq)); current=current->next; printf("\n"); } } return 0; } int main() { int i,j=0,n; Node *H=NULL; char w[100],a[100]; printf("Enter string:"); gets(w); printf("Enter the length of the word :"); scanf("%d",&n); for(i=0;i<strlen(w);i++) { if(w[i]==' ') { a[j]='\0'; if(strlen(a)==n) insert(&H,a); j=0; } else if(i==strlen(w)-1) { a[j]=w[i]; j++; a[j]='\0'; if(strlen(a)==n) insert(&H,a); } else if((w[i]!=' ')&&(i!=strlen(w)-1)) { a[j]=w[i]; j++; } } display(&H); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #define STRING_SIZE 512 #define BOLD_RED "\e[1;31m" #define RESET "\e[0m" typedef struct item { int key; char string[STRING_SIZE]; } item; typedef struct hash_table { item **arr; int capacity; } hash_table; item dummy_item = {-1, "\0"}; hash_table *create_hash_table(int); item *create_item(int, char *); int hash(int, int); bool insert(hash_table *, int, char *); bool search(hash_table *, int); item delete(hash_table *, int); void display(hash_table *); void print_item(item *); int main() { int size, choice, key; char value[STRING_SIZE]; printf("\t\tHash table with linear probing\n"); printf("Enter the size of the hash table: "); scanf("%d", &size); if (size <= 0) { printf(BOLD_RED "error:" RESET " size can only be positive integers\n"); exit(1); } hash_table *ht = create_hash_table(size); while (true) { printf("1: Insert\n"); printf("2: Delete\n"); printf("3: Search\n"); printf("4: Display\n"); printf("-1: Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch (choice) { case 1: printf("Enter the key: "); scanf("%d", &key); getchar(); printf("Enter the value: "); scanf("%[^\n]s", value); insert(ht, key, value); break; case 2: printf("Enter the key: "); scanf("%d", &key); delete(ht, key); break; case 3: printf("Enter the key: "); scanf("%d", &key); search(ht, key); break; case 4: display(ht); break; case -1: exit(0); default: printf(BOLD_RED "error:" RESET " invalid option\n"); } printf("\n"); } } hash_table *create_hash_table(int capacity) { hash_table *ht = (hash_table *) malloc(sizeof(hash_table)); ht->capacity = capacity; ht->arr = (item **) malloc(capacity * sizeof(item *)); for (int i = 0; i < ht->capacity; i++) ht->arr[i] = NULL; return ht; } void display(hash_table *ht) { bool empty = true; for (int i = 0; i < ht->capacity; i++) { if (ht->arr[i] && ht->arr[i]->key != -1) { empty = false; print_item(ht->arr[i]); } } if (empty) printf("Hash table is empty\n"); } int hash(int key, int size) { if (key < 0) { printf(BOLD_RED "error:" RESET " key unhashable\n"); exit(1); } return (key % size); } bool insert(hash_table *ht, int key, char *string) { int index = hash(key, ht->capacity); int i = index; while (ht->arr[i]) { if (ht->arr[i]->key == key || ht->arr[i]->key == -1) { if (ht->arr[i]->key == key) free(ht->arr[i]); ht->arr[i] = create_item(key, string); return true; } i = (i + 1) % ht->capacity; if (i == index) { printf(BOLD_RED "error:" RESET " hash table is full\n"); return false; } } ht->arr[i] = create_item(key, string); return true; } item *create_item(int key, char *string) { item *new_item = (item *) malloc(sizeof(item)); new_item->key = key; strcpy(new_item->string, string); return new_item; } item delete(hash_table *ht, int key) { int index = hash(key, ht->capacity); int i = index; item result = dummy_item; while (ht->arr[i]) { if (ht->arr[i]->key == key) { result = *(ht->arr[i]); free(ht->arr[i]); ht->arr[i] = &dummy_item; return result; } i = (i + 1) % ht->capacity; if (i == index) break; } printf(BOLD_RED "error:" RESET " Key not found\n"); return result; } bool search(hash_table *ht, int key) { int index = hash(key, ht->capacity); int i = index; while (ht->arr[i]) { if (ht->arr[i]->key == key) { print_item(ht->arr[i]); return true; } i = (i + 1) % ht->capacity; if (i == index) break; } printf(BOLD_RED "error:" RESET " Key not found\n"); return false; } void print_item(item *p) { printf("%d: %s\n", p->key, p->string); }
C
/****************************************************** LEDԳTX2440A ÷ 豸ƣTX2440-led Գƣled ֻһҲΪ0 1 led 0ĸȫ led 1: ĸȫ 1ʾյƣ2ʾ led 1 0һյ led 4 1: յ *******************************************************/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/ioctl.h> int main(int argc, char **argv) { unsigned int on; unsigned int led_num; int fd; fd = open("/dev/TX2440-led", 0); if (fd < 0) { perror("open device led"); exit(1); } if (argc == 2) { sscanf(argv[1], "%d", &on); if (on < 2) { ioctl(fd, on+3, 0); } else { printf("Usage: led led_num 0|1 or led 0|1\n"); exit(1); } } if (argc == 3) { sscanf(argv[1], "%d", &led_num); sscanf(argv[2], "%d", &on); if ((on < 2) && (led_num>0 || led_num < 4)) ioctl(fd, on, (led_num-1)); else { printf("Usage: led led_num 0|1 or led 0|1\n"); exit(1); } } close(fd); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char space, *prime; short low, high, temp, i, j; freopen( "function.in", "r", stdin ); freopen( "function.out", "w", stdout ); scanf( "%hd %hd", &low, &high ); if ( low > high ) { temp = low; low = high; high = temp; } if ( low != high ) { prime = ( char* )malloc( high - 3 ); memset( prime, 1, high - 3 ); for ( i = 3; i * i < high; i += 2 ) { if ( prime[ i - 3 ] ) { for ( j = i * i; j < high; j += 2 * i ) { prime[ j - 3 ] = 0; } } } space = 0; for ( i = low % 2 ? low + 2 : low + 1; i < high; i += 2 ) { if ( prime[ i - 3 ] ) { if ( space ) { putchar( ' ' ); } else { space = 1; } printf( "%hd", i ); } } if ( space ) { putchar( '\n' ); } } return 0; }
C
#include <stdio.h> int max(); int min(); void main() { int a, b, c; scanf("%d%d%d", &a, &b, &c); int max_s = max(a, b, c); int min_s = min(a, b, c); if (a+b>max_s && a+c>max_s && b+c>max_s) { if (a-b<min_s && a-c<min_s && b-c<min_s) { printf("YES"); } else { printf("ERROR DATA"); } } else { printf("ERROR DATA"); } } int max(a, b, c) { if (a <= b) { a = b; } if (a <= c) { a = c; } return a; } int min(a, b, c) { if (a >= b) { a = b; } if (a >= c) { a = c; } return a; }
C
#include "Decoder.h" int deserialize_int(unsigned char * buffer, int loc) { int value = buffer[loc] << 24; value += buffer[loc+1] << 16; value += buffer[loc+2] << 8; value += buffer[loc+3]; return value; } short deserialize_shr(unsigned char * buffer, int loc) { short value = buffer[loc] << 8; value += buffer[loc +1]; return value; } char deserialize_char(unsigned char * buffer, int loc) { char ret = buffer[loc]; return ret; } /*char * deserialize_substr(unsigned char * buffer, int begin, int end) { char * substring = malloc(end - begin + 1); int i=begin, loc = 0; while(i < end) { substring[loc] = buffer[i]; ++i; ++loc; } substring[end - begin] = '\0'; return substring; }*/ int deserialize_request(unsigned char * buffer, char tml, char id, char op_code, char num_ops, short operand_one, short operand_two) { tml = deserialize_char(buffer, 0); id = deserialize_char(buffer, 1); op_code = deserialize_char(buffer, 2); num_ops = deserialize_char(buffer, 3); operand_one = deserialize_shr(buffer, 4); operand_two = deserialize_shr(buffer, 6); return 0; }
C
//Problem Statement :: Program to multiply two matrices #include <stdio.h> #define N 2 int multiplicationMatrix(int A[][N],int B[][N],int C[][N]) { for(int i=0;i<N;i++) { for(int j=0;j<N;j++) { C[i][j] = 0; for(int k=0;k<N;k++) { C[i][j] += A[i][k]*B[k][j]; } } } //return C; } int main() { int A[N][N]={{1,2}, {3,4}}; int B[N][N]={{1,1}, {1,1}}; int C[N][N]; multiplicationMatrix(A,B,C); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%d ", C[i][j]); printf("\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> int suma(int n) { if (n > 1) return n + suma(n - 1); else return 1; } int factorial(int n) { if (n > 1) return n * factorial(n - 1); else return 1; } int suma_cifrelor(int n) { if (n < 10) return n; else return n % 10 + suma_cifrelor(n / 10); } int main() { printf("%d\n", suma(4)); printf("%d\n", factorial(5)); printf("%d\n", suma_cifrelor(234)); system("pause"); return 0; }
C
/* pamwipeout.c - read a bitmap and replace it with a gradient between two ** edges ** ** Copyright (C) 2011 by Willem van Schaik ([email protected]) ** ** Permission to use, copy, modify, and distribute this software and its ** documentation for any purpose and without fee is hereby granted, provided ** that the above copyright notice appear in all copies and that both that ** copyright notice and this permission notice appear in supporting ** documentation. This software is provided "as is" without express or ** implied warranty. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <math.h> #include "pm_c_util.h" #include "mallocvar.h" #include "shhopt.h" #include "pam.h" enum Direction {DIR_LR, DIR_TB}; struct cmdlineInfo { /* All the information the user supplied in the command line, in a form easy for the program to use. */ const char *inputFileName; /* '-' if stdin */ enum Direction direction; /* top-bottom or left-right */ }; static void parseCommandLine(int argc, const char ** argv, struct cmdlineInfo * const cmdlineP ) { /*---------------------------------------------------------------------------- Parse program command line described in Unix standard form by argc and argv. Return the information in the options as *cmdlineP. If command line is internally inconsistent (invalid options, etc.), issue error message to stderr and abort program. Note that the strings we return are stored in the storage that was passed to us as the argv array. We also trash *argv. -----------------------------------------------------------------------------*/ optEntry *option_def; /* Instructions to pm_optParseOptions3 on how to parse our options. */ optStruct3 opt; unsigned int option_def_index; unsigned int lr, tb; MALLOCARRAY_NOFAIL(option_def, 100); option_def_index = 0; /* incremented by OPTENT3 */ OPTENT3(0, "lr", OPT_FLAG, NULL, &lr, 0); OPTENT3(0, "tb", OPT_FLAG, NULL, &tb, 0); opt.opt_table = option_def; opt.short_allowed = FALSE; /* We have no short (old-fashioned) options */ opt.allowNegNum = FALSE; /* We have no parms that are negative numbers */ pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0); /* Uses and sets argc, argv, and some of *cmdlineP and others. */ if (!lr && !tb) pm_error("You must specify either -lr or -tb"); else if (lr && tb) pm_error("You may not specify both -lr and -tb"); else cmdlineP->direction = lr ? DIR_LR : DIR_TB; if (argc-1 < 1) cmdlineP->inputFileName = "-"; else { cmdlineP->inputFileName = argv[1]; if (argc-1 > 1) pm_error("Too many arguments: %u. " "The only possible argument is the " "optional input file name", argc-1); } } static void wipeImgByRow (struct pam const inpam, tuple ** const tuples) { double const h = (double) inpam.height; unsigned int row; unsigned int col; for (row = 0; row < inpam.height; ++row) { double const y = (double) row; for (col = 0; col < inpam.width; ++col) { unsigned int i; for (i = 0; i < inpam.depth; ++i) { sample const top = tuples[0][col][i]; sample const bot = tuples[inpam.height - 1][col][i]; tuples[row][col][i] = (int) floor(((h - y) / h) * (double) top + (y / h) * (double) bot); } } } } static void wipeRowByCol(struct pam const inpam, tuple ** const tuples, tuple * const tuplerow) { double const w = (double) inpam.width; unsigned int col; for (col = 0; col < inpam.width; ++col) { double const x = (double) col; unsigned int i; for (i = 0; i < inpam.depth; ++i) { sample const lft = tuplerow[0][i]; sample const rgt = tuplerow[inpam.width - 1][i]; tuplerow[col][i] = (int) floor( ((w - x) / w) * (double) lft + (x / w) * (double) rgt ); } } } static void wipeoutTb(FILE * const ifP, FILE * const ofP) { /* top-bottom we have to read the full image */ struct pam inpam, outpam; tuple ** tuples; tuples = pnm_readpam(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); outpam = inpam; outpam.file = ofP; wipeImgByRow(inpam, tuples); pnm_writepam(&outpam, tuples); pnm_freepamarray(tuples, &inpam); } static void wipeoutLr(FILE * const ifP, FILE * const ofP) { /* left-right we can read row-by-row */ struct pam inpam, outpam; tuple ** tuples; tuple * tuplerow; unsigned int row; pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type)); outpam = inpam; outpam.file = ofP; pnm_writepaminit(&outpam); tuplerow = pnm_allocpamrow(&inpam); for (row = 0; row < inpam.height; ++row) { pnm_readpamrow(&inpam, tuplerow); wipeRowByCol(inpam, tuples, tuplerow); pnm_writepamrow(&outpam, tuplerow); } pnm_freepamrow(tuplerow); } int main(int argc, const char *argv[]) { struct cmdlineInfo cmdline; FILE * ifP; pm_proginit(&argc, argv); parseCommandLine(argc, argv, &cmdline); ifP = pm_openr(cmdline.inputFileName); switch (cmdline.direction) { case DIR_TB: wipeoutTb(ifP, stdout); break; case DIR_LR: wipeoutLr(ifP, stdout); break; } pm_close(ifP); pm_close(stdout); return 0; }
C
/* <imval.c> 27mar91 jm Original code. 26feb92 jm Added radecfmt code. 14aug92 jm Modified wipradecfmt() to return pointer to a static duration string rather than a local scope one. Routines: float wipimval ARGS(( float **image, int nx, int ny, float xpos, float ypos, float tr[], LOGICAL *error )); char *wipradecfmt ARGS(( float position )); */ #include "wip.h" /* Global Variables needed just for this file */ /* Code */ #ifdef PROTOTYPE float wipimval(float **image, int nx, int ny, float xpos, float ypos, float tr[], LOGICAL *error) #else float wipimval(image, nx, ny, xpos, ypos, tr, error) float **image; int nx, ny; float xpos, ypos; float tr[]; LOGICAL *error; #endif /* PROTOTYPE */ { int x, y; float value, pos, den; *error = TRUE; value = 0.0; den = ((tr[1] * tr[5]) - (tr[2] * tr[4])); if (den != 0.0) { pos = (tr[5] * (xpos - tr[0])) - (tr[2] * (ypos - tr[3])); x = NINT(pos / den); pos = (tr[1] * (ypos - tr[3])) - (tr[4] * (xpos - tr[0])); y = NINT(pos / den); x--; /* Go from 1 index based to 0 based. */ y--; /* Go from 1 index based to 0 based. */ if ((y >= 0) && (y < ny)) { if ((x >= 0) && (x < nx)) { value = image[y][x]; *error = FALSE; } } } return(value); } #ifdef PROTOTYPE char *wipradecfmt(float position) #else char *wipradecfmt(position) float position; #endif /* PROTOTYPE */ { char *ptr; static char string[STRINGSIZE]; int sign, nsig; int radec, minutes, tensofseconds; float seconds; double dnsig; LOGICAL error; dnsig = wipgetvar("nsig", &error); nsig = (error == TRUE) ? 2 : NINT(dnsig); sign = (position < 0) ? -1 : 1; seconds = ABS(position); radec = seconds / 3600.0; seconds -= (radec * 3600.0); minutes = seconds / 60.0; seconds -= (minutes * 60.0); tensofseconds = seconds / 10.0; radec *= sign; if (!tensofseconds) nsig--; if (INT(seconds) == 0) nsig--; if (nsig < 0) nsig = 0; ptr = wipleading(wipfpfmt(seconds, nsig)); if (tensofseconds) { SPrintf(string, "%d %02d %s", radec, minutes, ptr); } else { SPrintf(string, "%d %02d 0%s", radec, minutes, ptr); } return(string); }
C
#include "D:\proga\library.h" #include <stdio.h> int maxflow(graph_user graphik, int first_node, int second_node){ graph_user graph = copy_graph(graphik); int count_node = func_count_node(graph); int metka = 1; int i,k; int line[count_node]; int yes[count_node]; int p = 0; while (metka != 0){ for (i = 0; i < count_node; i++) line[i] = -1; for (i = 0; i < count_node; i++) yes[i] = 0; yes[first_node-1] = 1; line[0] = first_node; int var_temp = 0; i = first_node; int h; int lmetka = 0; int counter = 0; do{ h = 0; for (k = 1; k <= count_node; k++) { if ((existence(graph,i,k) == 1) && (yes[k-1] == 0) && (character(graph, "weight", i, k) > 0)){ yes[k-1] = 1; line[++var_temp] = k; i = k; h = 1; counter = 0; break; } } if (!h){ if ((var_temp == 0) && (line[1] == -1)){ metka = 0; break; } if (counter == 1){ metka = 0; break; } i = line[--var_temp]; if (i == first_node) counter++; } } while (i != second_node); if (metka == 0) break; for (i = 1; i < count_node; i++) if (line[i] != -1) lmetka++; i = 0; int min = 1024; while (i < lmetka){ int l = character(graph, "weight", line[i], line[i+1]); if (l < min) min = l; i++; } i = 0; while (i < lmetka){ int l = character(graph, "weight", line[i], line[i+1]); delete_edge(graph, line[i], line[i+1]); if (l > min) add_edge_graph(graph, line[i], line[i+1], 1, l - min); if (existence(graph,line[i+1], line[i]) == 1){ int m = character(graph, "weight", line[i+1], line[i]); delete_edge(graph, line[i+1], line[i]); add_edge_graph(graph, line[i+1], line[i], 1, m+min); } else add_edge_graph(graph, line[i+1], line[i], 1, min); i++; } } int potok = 0; for (i = 1; i < count_node; i++) if (existence(graphik,i,second_node) == 1) potok += character(graphik, "weight", i, second_node) - character(graph, "weight", i, second_node); delete_graph(graph); return potok; } void main(int argc, char* argv[]) { char* file = argv[1]; graph_user graphik = reader_graph_matrix(file); int first_node,second_node; while(1){ scanf("%d", &first_node); if (first_node == 0) break; scanf("%d", &second_node); if (second_node == 0) break; printf("%d\n", maxflow(graphik,first_node,second_node)); } delete_graph(graphik); }
C
/* Input:4 5 Output: 2 4 6 8 10 1 3 5 7 9 2 4 6 8 10 1 3 5 7 9 */ #include <stdio.h> void Pattern3(int iRow,int iCol) { int i=0,j=0; for(i=1; i<=iRow; i++) { for(j=1; j<=iCol; j++) { if(i%2 != 0) { printf("%d ",j*2); } else { printf("%d ",j*2-1); } } printf("\n"); } } int main() { int iValue1=0,iValue2=0; printf("Enter the Rows:"); scanf("%d",&iValue1); printf("Enter the Columns:"); scanf("%d",&iValue2); Pattern3(iValue1,iValue2); return 0; }
C
#define MAXFORMULA 100 void readFormula(struct treeNode *currentTreeNode, char formula[], int *index); void printFormula(struct treeNode *currentTreeNode); struct treeNode { char element; struct treeNode *leftSon; struct treeNode *rightSon; }; void openFile(){ char formula[MAXFORMULA]; FILE *fp; fp=fopen("formula.txt", "r"); if(!fp) printf("File Not Found!\n"); else { while(fgets(formula,MAXFORMULA,fp)!=NULL) { struct treeNode *rootFormula=(struct treeNode *)malloc(sizeof(struct treeNode)); int index=0; readFormula(rootFormula,formula,&index); printFormula(rootFormula); printf("\n"); } } } void readFormula(struct treeNode *currentTreeNode, char formula[], int *index){ // A = implication, B = conjunction, C = disjunction, D = negation // E = AF, F = AG, G = EF, H = EG // I = AU, J = EU, K = AS, L = ES if((formula[*index]>='a')&&(formula[*index]<='z')){ currentTreeNode->element = formula[*index]; currentTreeNode->rightSon = NULL; currentTreeNode->leftSon = NULL; } else if((formula[*index]=='A')||(formula[*index]=='B')||(formula[*index]=='C')||(formula[*index]=='I')||(formula[*index]=='J')||(formula[*index]=='K')||(formula[*index]=='L')){ currentTreeNode->element = formula[*index]; struct treeNode *ls = (struct treeNode *)malloc(sizeof(struct treeNode)); (*index)++; readFormula(ls,formula,index); currentTreeNode->leftSon = ls; struct treeNode *rs = (struct treeNode *)malloc(sizeof(struct treeNode)); (*index)++; readFormula(rs,formula,index); currentTreeNode->rightSon = rs; } else if((formula[*index]=='D')||(formula[*index]=='E')||(formula[*index]=='F')||(formula[*index]=='G')||(formula[*index]=='H')){ currentTreeNode->element = formula[*index]; struct treeNode *s = (struct treeNode *)malloc(sizeof(struct treeNode)); (*index)++; readFormula(s,formula,index); currentTreeNode->leftSon = s; currentTreeNode->rightSon = NULL; } } void printFormula(struct treeNode *currentTreeNode){ if (currentTreeNode->element=='A'){ printf("("); printFormula(currentTreeNode->leftSon); printf(" -> "); printFormula(currentTreeNode->rightSon); printf(")"); } else if (currentTreeNode->element=='B'){ printf("("); printFormula(currentTreeNode->leftSon); printf(" And "); printFormula(currentTreeNode->rightSon); printf(")"); } else if (currentTreeNode->element=='C'){ printf("("); printFormula(currentTreeNode->leftSon); printf(" Or "); printFormula(currentTreeNode->rightSon); printf(")"); } else if (currentTreeNode->element=='D'){ printf(" Not "); printf("("); printFormula(currentTreeNode->leftSon); printf(")"); } else printf("%c",currentTreeNode->element); }
C
#include "merge.h" #include "record.h" //manager fields should be already initialized in the caller int merge_runs (MergeManager * merger){ int result; //stores SUCCESS/FAILURE returned at the end //1. go in the loop through all input files and fill-in initial buffers if (init_merge (merger)!=SUCCESS) return FAILURE; while (merger->current_heap_size > 0) { //heap is not empty HeapElement smallest; Record next; //here next comes from input buffer if(get_top_heap_element (merger, &smallest)!=SUCCESS) return FAILURE; result = get_next_input_element (merger, smallest.run_id, &next); if (result==FAILURE) return FAILURE; if(result==SUCCESS) {//next element exists, may also return EMPTY if(insert_into_heap (merger, smallest.run_id, &next)!=SUCCESS) return FAILURE; } merger->output_buffer [merger->current_output_buffer_position].uid1=smallest.UID1; merger->output_buffer [merger->current_output_buffer_position].uid2=smallest.UID2; merger->current_output_buffer_position++; //staying on the last slot of the output buffer - next will cause overflow if(merger->current_output_buffer_position == merger-> output_buffer_capacity ) { if(flush_output_buffer(merger)!=SUCCESS) { return FAILURE; merger->current_output_buffer_position=0; } } } //flush what remains in output buffer if(merger->current_output_buffer_position > 0) { //printf("last buffer size%d uid1 %d uid2 %d\n", merger->current_output_buffer_position, merger->output_buffer[1].uid1, merger->output_buffer[1].uid2); if(flush_output_buffer(merger)!=SUCCESS) return FAILURE; } clean_up(merger); return SUCCESS; } int get_top_heap_element (MergeManager * merger, HeapElement * result){ HeapElement item; int child, parent; if(merger->current_heap_size == 0){ printf( "UNEXPECTED ERROR: popping top element from an empty heap\n"); return FAILURE; } *result=merger->heap[0]; //to be returned //now we need to reorganize heap - keep the smallest on top item = merger->heap [--merger->current_heap_size]; // to be reinserted parent =0; if(merger->sort_uid == 1){ while ((child = (2 * parent) + 1) < merger->current_heap_size) { // if there are two children, compare them if (child + 1 < merger->current_heap_size && (compare_heap_elements1(&(merger->heap[child]),&(merger->heap[child + 1]))>0)) ++child; // compare item with the larger if (compare_heap_elements1(&item, &(merger->heap[child]))>0) { merger->heap[parent] = merger->heap[child]; parent = child; } else break; } }else if(merger->sort_uid == 2){ while ((child = (2 * parent) + 1) < merger->current_heap_size) { // if there are two children, compare them if (child + 1 < merger->current_heap_size && (compare_heap_elements2(&(merger->heap[child]),&(merger->heap[child + 1]))>0)) ++child; // compare item with the larger if (compare_heap_elements2(&item, &(merger->heap[child]))>0) { merger->heap[parent] = merger->heap[child]; parent = child; } else break; } }else{ while ((child = (2 * parent) + 1) < merger->current_heap_size) { // if there are two children, compare them if (child + 1 < merger->current_heap_size && (compare_heap_elements3(&(merger->heap[child]),&(merger->heap[child + 1]))>0)) ++child; // compare item with the larger if (compare_heap_elements3(&item, &(merger->heap[child]))>0) { merger->heap[parent] = merger->heap[child]; parent = child; } else break; } } merger->heap[parent] = item; return SUCCESS; } int insert_into_heap (MergeManager * merger, int run_id, Record *input){ HeapElement new_heap_element; int child, parent; //printf("heap uid1 %d uid2 %d\n", input->uid1, input->uid2); new_heap_element.UID1 = input->uid1; new_heap_element.UID2 = input->uid2; new_heap_element.run_id = run_id; if (merger->current_heap_size == merger->heap_capacity) { printf( "Unexpected ERROR: heap is full\n"); return FAILURE; } child = merger->current_heap_size++; /* the next available slot in the heap */ if(merger->sort_uid == 1){ while (child > 0) { parent = (child - 1) / 2; if (compare_heap_elements1(&(merger->heap[parent]),&new_heap_element)>0) { merger->heap[child] = merger->heap[parent]; child = parent; } else break; } }else if(merger->sort_uid == 2){ while (child > 0) { parent = (child - 1) / 2; if (compare_heap_elements2(&(merger->heap[parent]),&new_heap_element)>0) { merger->heap[child] = merger->heap[parent]; child = parent; } else break; } }else{ while (child > 0) { parent = (child - 1) / 2; if (compare_heap_elements3(&(merger->heap[parent]),&new_heap_element)>0) { merger->heap[child] = merger->heap[parent]; child = parent; } else break; } } merger->heap[child]= new_heap_element; return SUCCESS; } /* ** TO IMPLEMENT */ int init_merge (MergeManager * manager) { FILE *fp; int i; for(i = 0; i < manager->heap_capacity; i++){ char k[100]; char * filename = (char *) calloc(121,sizeof(char)); sprintf(k,"%d",manager->input_file_numbers[i]); strcat(filename,manager->input_prefix); strcat(filename,k); strcat(filename,".dat"); if (!(fp = fopen (filename , "rb" ))){ free(filename); return FAILURE; }else{ fseek(fp, manager->current_input_file_positions[i]*sizeof(Record), SEEK_SET); int result = fread (manager->input_buffers[i], sizeof(Record), manager->input_buffer_capacity, fp); if(result <= 0){ manager->current_heap_size--; } manager->current_input_file_positions[i] = result; manager->total_input_buffer_elements[i] = result; insert_into_heap(manager, manager->input_file_numbers[i], &manager->input_buffers[i][manager->current_input_buffer_positions[i]]); manager->current_input_buffer_positions[i]++; } fclose(fp); free(filename); } return SUCCESS; } int flush_output_buffer (MergeManager * manager) { FILE *fp_write; if (!(fp_write = fopen (manager->output_file_name , "a" ))){ return FAILURE; } fwrite(manager->output_buffer, sizeof(Record), manager->current_output_buffer_position, fp_write); fflush (fp_write); fclose(fp_write); manager->current_output_buffer_position = 0; return SUCCESS; } int get_next_input_element(MergeManager * manager, int file_number, Record *result) { if(manager->current_input_buffer_positions[file_number] == manager->total_input_buffer_elements[file_number]){ manager->current_input_buffer_positions[file_number] = 0; if(refill_buffer (manager, file_number)!=SUCCESS){ return FAILURE; } if(manager->current_input_file_positions[file_number] == -1){ return EMPTY; } } *result = manager->input_buffers[file_number][manager->current_input_buffer_positions[file_number]]; manager->current_input_buffer_positions[file_number]++; return SUCCESS; } int refill_buffer (MergeManager * manager, int file_number) { FILE *fp_read; char k[100]; sprintf(k,"%d",manager->input_file_numbers[file_number]); char * filename = (char *) calloc(121,sizeof(char)); strcat(filename,manager->input_prefix); strcat(filename,k); strcat(filename,".dat"); if (!(fp_read = fopen (filename , "rb" ))){ free(filename); return FAILURE; }else{ fseek(fp_read, manager->current_input_file_positions[file_number]*sizeof(Record), SEEK_SET); int result = fread (manager->input_buffers[file_number], sizeof(Record), manager->input_buffer_capacity, fp_read); if(result <= 0){ manager->current_input_file_positions[file_number] = -1; }else{ manager->current_input_file_positions[file_number]+= result; manager->total_input_buffer_elements[file_number] = result; } } free(filename); fclose(fp_read); return SUCCESS; } void clean_up (MergeManager * merger) { //printf("clean up\n"); free(merger->heap); int i; for(i = 0; i < merger->heap_capacity; i++){ free(merger->input_buffers[i]); } for(i = 0; i < merger->heap_capacity; i++){ char k[100]; char * filename = (char *) calloc(121,sizeof(char)); sprintf(k,"%d",merger->input_file_numbers[i]); strcat(filename,merger->input_prefix); strcat(filename,k); strcat(filename,".dat"); remove(filename); free(filename); } free(merger->input_buffers); free(merger->output_buffer); free(merger); } int compare_heap_elements2 (HeapElement *a, HeapElement *b) { if(a->UID2 > b->UID2){ return 1; } if(a->UID2 == b->UID2){ if(a->UID1 > b->UID1){ return 1; } } return 0; } int compare_heap_elements1 (HeapElement *a, HeapElement *b) { if(a->UID1 > b->UID1){ return 1; } if(a->UID1 == b->UID1){ if(a->UID2 > b->UID2){ return 1; } } return 0; } int compare_heap_elements3(HeapElement *a, HeapElement *b){ if(a->UID2 > b->UID2){ return 1; } return 0; }
C
#include "../include/shell.h" extern size_t my_offset; int printing_command = FALSE; typedef void(*commandFnct)(void); static struct { char* name; char* description; PROCESS task_function; } commands[NUM_COMMANDS] = { { "help", "Display system commands", help }, { "echo", "Prints string", echo }, // { "shortcuts","Display keyboard shorcuts", shortcuts }, { "top","Display ongoing look at processor activity in real time.", top }, { "kill", "Kills the proces with PID = PIDn .", pkill }, { "imprimeUnos", "Process that prints 1s forever", imprimeUnos }, { "clearScreen", "Erase all the content of the actual TTY", clear_screen }, { "ls", "Show files in CWD", ls }, { "mkdir", "Creates a new directory", mkdir }, { "touch", "Creates a new empty file", touch }, { "cd", "Change directory", cd }, { "rm", "Delete fileA", rm }, { "lsRemoved", "Show all files (including deleted)", lsRemoved }, { "rmHard", "Remove the file the hard way", rmHard }, { "rmRec", "Removes files and directories recursively", rmRecursive }, { "vh", "Shows the version history of the file", vh },{ "revert", "Revert to a previous version", revert }, {"cp", "Copy files", cp }, {"mv", "Move files", mv }, {"ln", "Make a soft-link to a file", ln } }; void shell(void) { Task_t * c_t = get_current_task(); ttyScreen_t * screen = getScreen(c_t); shellLine_t * lineBuffer = getLineBuffer(c_t); char c; command_t * a = (command_t *) malloc(sizeof(command_t)); char * current_dir = getcwd(); printf("BrunOS tty%d:%s~$ ", c_t->tty_number, current_dir); free(current_dir); while ((c = getc()) != '\n') { switch (c) { case '\b': if (lineBuffer->pos > 0) { lineBuffer->buffer[--lineBuffer->pos] = 0; putc('\b'); } break; case '\t': parse_command(a); auto_complete(a); break; default: if (lineBuffer->pos < lineBuffer->size - 1) { lineBuffer->buffer[lineBuffer->pos++] = c; lineBuffer->buffer[lineBuffer->pos] = 0; } putc(c); break; } } putc('\n'); parse_command(a); run_command(a); lineBuffer->pos = 0; erase_buffer(); } char * getcwd() { inode_t * pinode = get_current_task()->cwd->parent; fileentry_t * fe; int len = 0; char * ans; if (pinode != NULL) { int i = 0; while ((fe = fsGetFileentry(pinode, i++)) != NULL) { if (fe->inode_number == get_current_task()->cwd->inode_number) break; free(fe); } len = strlen(fe->name); ans = (char *) malloc(len + 1); strcpy(ans, fe->name); free(fe); } else { len = 1; ans = (char *) malloc(len + 1); strcpy(ans, "/"); } return ans; } void erase_buffer() { shellLine_t * lineBuffer = getLineBuffer(get_current_task()); int i = 0; for (i = 0; i < LINEBUF_LEN; i++) { lineBuffer->buffer[i] = 0; } } void parse_command(command_t * c) { shellLine_t * lineBuffer = getLineBuffer(get_current_task()); int initpos = 0; /* Remover espacios en blanco */ while ((lineBuffer->buffer[initpos] == ' ') && (++initpos < LINEBUF_LEN - 1)) ; sscanf(&lineBuffer->buffer[initpos], "%s %s", c->name, c->args); } int run_command(command_t * command) { int i; if (streq(command->name, "")) return 0; int len = strlen(command->name); bool isBackground = (command->name[len - 1] == '&') ? true : false; if (isBackground) { command->name[len - 1] = '\0'; } for (i = 0; i < NUM_COMMANDS; i++) { if (streq(command->name, commands[i].name)) { StartNewTask(commands[i].name, commands[i].task_function, command->args, isBackground); return 1; } } printfcolor(ERROR_COLOR, "%s: command not found\n", command->name); clearCommand(command); return 1; } void auto_complete(command_t *command) { Task_t * c_t = get_current_task(); ttyScreen_t * screen = getScreen(c_t); shellLine_t * lineBuffer = getLineBuffer(c_t); int i, j, size, lenght, eq = TRUE; lenght = strlen(command->name); char * commName; if (streq(command->name, "")) return; for (i = 0; i < NUM_COMMANDS; i++) { commName = commands[i].name; for (j = 0; j < lenght && eq == TRUE; j++) { if (command->name[j] != commName[j]) eq = FALSE; if (j == strlen(commName) - 1) eq = FALSE; } if (eq == TRUE) { size = strlen(lineBuffer->buffer); erase_buffer(); clearfromto(screen->wpos - size * 2, screen->wpos); lineBuffer->pos = 0; lenght = strlen(commName); for (j = 0; j < lenght; j++) { lineBuffer->buffer[lineBuffer->pos++] = commName[j]; lineBuffer->buffer[lineBuffer->pos] = 0; putc(commName[j]); } } eq = !eq; } command->name[0] = 0; } void clearCommand(command_t * command) { int i = 0; for (i = 0; i < LINEBUF_LEN; i++) { command->name[i] = 0; command->args[i] = 0; } } int divideByZero(int argc, char *argv) { erase_buffer(); int x = 1; int y = 1; int z = x / --y; } int clear_screen(int argc, char *argv) { ttyScreen_t * screen = getScreen(get_current_task()); clearScreen(); clearScreenBuffer(); print_header(); printTicks(); screen->wpos = TTY_SCREEN_SSTART; move_cursor(screen->wpos / 2); } int invalidOpCode(int argc, char *argv) { _invop(); return EXIT_SUCCESS; } int echo(int argc, char *argv) { printfcolor(COMMAND_COLOR, "%s\n", argv); return EXIT_SUCCESS; } //int mouse(int argc, char *argv) { // printfcolor( // MARINE_COLOR, // "********************************************************************************\n"); // printfcolor(COMMAND_COLOR, "Mouse usage: \n\n"); // printfcolor(ERROR_COLOR, "%s", commands[0].name); // // printfcolor(ERROR_COLOR, "Left Click"); // printfcolor(MARINE_COLOR, "\t\t => \t"); // printfcolor(COMMAND_COLOR, "Increments the timer tick frecuency\n"); // // printfcolor(ERROR_COLOR, "Right Click"); // printfcolor(MARINE_COLOR, "\t\t => \t"); // printfcolor(COMMAND_COLOR, "Decrements the timer tick frecuency\n"); // // printfcolor( // MARINE_COLOR, // "\n********************************************************************************\n"); // return EXIT_SUCCESS; // //} //int shortcuts(int argc, char *argv) { // printfcolor( // MARINE_COLOR, // "********************************************************************************\n"); // printfcolor(COMMAND_COLOR, "Keyboard shortcuts: \n\n"); // // printfcolor(ERROR_COLOR, "F1"); // printfcolor(MARINE_COLOR, "\t\t\t\t => \t"); // printfcolor(COMMAND_COLOR, "Goes to TTY #1\n"); // // printfcolor(ERROR_COLOR, "F2"); // printfcolor(MARINE_COLOR, "\t\t\t\t => \t"); // printfcolor(COMMAND_COLOR, "Goes to TTY #2\n"); // // printfcolor(ERROR_COLOR, "F3"); // printfcolor(MARINE_COLOR, "\t\t\t\t => \t"); // printfcolor(COMMAND_COLOR, "Goes to TTY #3\n"); // // printfcolor(ERROR_COLOR, "F4"); // printfcolor(MARINE_COLOR, "\t\t\t\t => \t"); // printfcolor(COMMAND_COLOR, "Goes to TTY #4\n"); // // printfcolor(ERROR_COLOR, "text + TAB"); // printfcolor(MARINE_COLOR, "\t\t => \t"); // printfcolor(COMMAND_COLOR, "Autocomplete command\n"); // // printfcolor(ERROR_COLOR, "CTRL + SHIFT"); // printfcolor(MARINE_COLOR, "\t => \t"); // printfcolor(COMMAND_COLOR, "Change keyboard language (ES | EN)\n"); // // printfcolor( // MARINE_COLOR, // "\n********************************************************************************\n"); // return EXIT_SUCCESS; //} int help(int argc, char *argv) { int i; // printfcolor( // MARINE_COLOR, // "********************************************************************************\n"); printfcolor(COMMAND_COLOR, "Available commands: \n\n"); int len = 0; for (i = 0; i < NUM_COMMANDS; i++) { len = strlen(commands[i].name) / 4; printfcolor(ERROR_COLOR, "%s", commands[i].name); if (len < 1) printfcolor(MARINE_COLOR, "\t\t\t"); else if (len < 2) printfcolor(MARINE_COLOR, "\t\t"); else if (len < 3) printfcolor(MARINE_COLOR, "\t"); printfcolor(MARINE_COLOR, " => \t"); printfcolor(COMMAND_COLOR, "%s\n", commands[i].description); } // printfcolor( // MARINE_COLOR, // "\n********************************************************************************\n"); return EXIT_SUCCESS; } int top(int argc, char *argv) { Task_t* processes = get_processes(); int i; // printfcolor( // MARINE_COLOR, // "********************************************************************************\n"); printfcolor(COMMAND_COLOR, "PID\t\t\tName\t\t\t\tStatus\t\t\tPriority\n\n"); for (i = 0; i < MAX_PROCESSES; i++) { if (processes[i].state != TaskEmpty) { printfcolor( ((processes[i].state == TaskReady) ? COMMAND_COLOR : (processes[i].state == TaskTerminated) ? ERROR_COLOR : MARINE_COLOR), "%d\t\t\t%s\t\t\t\t%s\t\t\t%d\n", processes[i].pid, processes[i].name, ((processes[i].state == TaskReady) ? "Ready" : (processes[i].state == TaskTerminated) ? "Terminated" : "Suspended"), processes[i].priority); } } // printfcolor( // MARINE_COLOR, // "\n********************************************************************************\n"); return EXIT_SUCCESS; } int pkill(int argc, char *argv) { atomize(); int pid = atoi(argv); if (terminate_task(pid) == EXIT_SUCCESS) { printfcolor(COMMAND_COLOR, "PID: %d has been successfully killed.\n", pid); } else { printfcolor(ERROR_COLOR, "PID: %d could not be killed.\n", pid); } unatomize(); return EXIT_SUCCESS; } int imprimeUnos(int argc, char *argv) { _Sti(); while (1) { printf("1"); } return EXIT_SUCCESS; } int pagefault(int argc, char * argv) { return pagefault(argc, argv); } int ls(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->cwd; fileentry_t * currentFile = NULL; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL) { // printf("En LS: -%s-, state: %d, inode: %d, position: %d, type: %d\n", currentFile->name, currentFile->state, currentFile->inode_number, currentFile->position, currentFile->type); if (currentFile->state != ABSENT) { if (currentFile->type == DIR_TYPE) { printfcolor(DIR_COLOR, "%s ", currentFile->name); } else if (currentFile->type == FILE_TYPE) { printfcolor(FILE_COLOR, "%s ", currentFile->name); } else if (currentFile->type == LINK_TYPE) { printfcolor(LINK_COLOR, "%s ", currentFile->name); } } free(currentFile); } printf("\n"); } int lsRemoved(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->cwd; fileentry_t * currentFile = NULL; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL) { // printf("En LS: -%s-, state: %d, inode: %d\n", currentFile->name, currentFile->state, currentFile->inode_number); if (currentFile->state == ABSENT) { printfcolor(ERROR_COLOR, "(%s) ", currentFile->name); } else if (currentFile->type == DIR_TYPE) { printfcolor(DIR_COLOR, "%s ", currentFile->name); } else if (currentFile->type == FILE_TYPE) { printfcolor(FILE_COLOR, "%s ", currentFile->name); } else if (currentFile->type == LINK_TYPE) { printfcolor(LINK_COLOR, "%s ", currentFile->name); } free(currentFile); } printf("\n"); } int mkdir(int argc, char *argv) { int ret = fsMkdir(argv, get_current_task()->cwd); switch (ret) { case NOT_ENOUGH_SPACE_IN_DIR: printfcolor(ERROR_COLOR, "ERROR: Directory is full.\n"); break; case NO_SPACE: printfcolor(ERROR_COLOR, "ERROR: Disk is full.\n"); break; case NO_FILENAME: printfcolor(ERROR_COLOR, "ERROR: Invalid directory name.\n"); break; case FILE_ALREADY_EXISTS: printfcolor(ERROR_COLOR, "ERROR: Directory already exists.\n"); break; } } int touch(int argc, char *argv) { int ret = fsMkfile(argv, get_current_task()->cwd); switch (ret) { case NOT_ENOUGH_SPACE_IN_DIR: printfcolor(ERROR_COLOR, "ERROR: Directory is full.\n"); break; case NO_SPACE: printfcolor(ERROR_COLOR, "ERROR: Disk is full.\n"); break; case NO_FILENAME: printfcolor(ERROR_COLOR, "ERROR: Invalid filename.\n"); break; case FILE_ALREADY_EXISTS: printfcolor(ERROR_COLOR, "ERROR: File already exists.\n"); break; } } int cd(int argc, char *argv) { inode_t ** cwd_inode = &(get_current_task()->parent->cwd); fileentry_t * currentFile = NULL; bool found = FALSE; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(*cwd_inode, i++)) != NULL && !found) { if (currentFile->type == DIR_TYPE && streq(argv, currentFile->name) == TRUE && (currentFile->state == PRESENT)) { found = TRUE; break; } free(currentFile); } if (found) { // Change the directory of the parent of current_task inode_t * aux = (inode_t *) getInodeByNumber(currentFile->inode_number); if (aux != NULL){ (*cwd_inode) = aux; } else { printfcolor(ERROR_COLOR, "FATAL: Disk corruption.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } } int rm(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL && !found) { if (currentFile->type == FILE_TYPE && streq(argv, currentFile->name) == TRUE && (currentFile->state == PRESENT)) { found = TRUE; break; } free(currentFile); } if (found) { fsRemove(cwd_inode, currentFile); free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } } int rmHard(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL && !found) { if (currentFile->type == FILE_TYPE && streq(argv, currentFile->name) == TRUE ) { found = TRUE; break; } free(currentFile); } if (found) { if(fsRemoveHard(cwd_inode, currentFile) == EXIT_FAILURE) { printfcolor(ERROR_COLOR, "ERROR: The file is being linked.\n"); } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } } int rmRecursive(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL && !found) { if (streq(argv, currentFile->name) == TRUE && (currentFile->state == PRESENT)) { found = TRUE; break; } free(currentFile); } // printf("CFI:%d--CFP:%d\n", currentFile->inode_number, getInodeByNumber(currentFile->inode_number)->parent->inode_number); // printf("CFTy:%d\n", currentFile->type); // printf("CWD: %d--CWDP: %d\n", cwd_inode->inode_number, (cwd_inode->parent == NULL) ? -1: cwd_inode->parent->inode_number); if (found) { if (!(((currentFile->inode_number == cwd_inode->inode_number) && (currentFile->type == DIR_TYPE)) || ((currentFile->inode_number == cwd_inode->parent->inode_number) && (currentFile->type == DIR_TYPE)))) { fsRecursiveRemoveHardWrapper(cwd_inode, currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: You can't remove that.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } } int vh(int argc, char *argv) { inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL && !found) { if (streq(argv, currentFile->name) == TRUE && currentFile->type == FILE_TYPE) { found = TRUE; break; } free(currentFile); } if (found) { if (!((currentFile->inode_number == cwd_inode->inode_number && currentFile->type == DIR_TYPE) || (currentFile->inode_number == cwd_inode->parent->inode_number && currentFile->type == DIR_TYPE))) { inode_t * file = getInodeForEntry(currentFile); int current_rev = file->rev_no; // printfcolor( // MARINE_COLOR, // "********************************************************************************\n"); printfcolor(WHITE_TXT, "Revision\t\t\tName\t\t\tSize\t\t\tStatus\n"); do{ printfcolor((file->rev_no == current_rev) ? COMMAND_COLOR : ERROR_COLOR, "%d\t\t\t\t\t", file->rev_no); printfcolor((file->rev_no == current_rev) ? COMMAND_COLOR : ERROR_COLOR, "%s\t\t\t\t", file->name); printfcolor((file->rev_no == current_rev) ? COMMAND_COLOR : ERROR_COLOR, "%d\t\t\t\t", (file == NULL) ? -1: file->size ); printfcolor((file->rev_no == current_rev) ? COMMAND_COLOR : ERROR_COLOR, "%s\n", (file->status == ABSENT) ? "Absent": "Present" ); }while((file = fsGetPrevVersion(file)) != NULL); // printfcolor( // MARINE_COLOR, // "\n********************************************************************************\n"); } else { printfcolor(ERROR_COLOR, "ERROR: That file does not have version history.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int revert(int argc, char *argv){ char c; int i = 0; char param1[LINEBUF_LEN -2]; // File char param2[LINEBUF_LEN -2]; // Version number while((c=*argv++) != ' ' && c != '\0'){ param1[i++] = c; } i = 0; while((c=*argv++) != ' ' && c != '\0'){ param2[i++] = c; } if(param1[0] == '\0' || param2[0] == '\0'){ return EXIT_FAILURE; } inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int revision = atoi(param2); i = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, i++)) != NULL && !found) { if (streq(param1, currentFile->name) == TRUE && currentFile->type == FILE_TYPE) { found = TRUE; break; } free(currentFile); } if (found) { if (!((currentFile->inode_number == cwd_inode->inode_number && currentFile->type == DIR_TYPE) || (currentFile->inode_number == cwd_inode->parent->inode_number && currentFile->type == DIR_TYPE))) { fsRevert(cwd_inode, currentFile, revision); } else { printfcolor(ERROR_COLOR, "ERROR: That file does not have version history.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int cp(int argc, char *argv){ char c; int i = 0; char param1[LINEBUF_LEN -2]; // File char param2[LINEBUF_LEN -2]; // Dest while((c=*argv++) != ' ' && c != '\0'){ param1[i++] = c; } i = 0; while((c=*argv++) != ' ' && c != '\0'){ param2[i++] = c; } if(param1[0] == '\0' || param2[0] == '\0'){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy: param1 = -%s-, param2=-%s-\n", param1, param2); return EXIT_FAILURE; } // Prevent recursive calls if(streq(param1, param2)){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy or recursive instruction attempt.\n"); return EXIT_FAILURE; } /* First search for the file to copy */ inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int j = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param1, currentFile->name) == TRUE && (currentFile->state == PRESENT) && currentFile->type == FILE_TYPE ) { found = TRUE; break; } free(currentFile); } if (found) { /* Now search for the directory to copy the file */ cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentDirFile = NULL; found = FALSE; j = 0; while ((currentDirFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param2, currentDirFile->name) == TRUE && currentDirFile->type == DIR_TYPE) { found = TRUE; break; } free(currentDirFile); } if (found) { fsCopy(getInodeForEntry(currentDirFile), currentFile); free(currentDirFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such destination directory.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int mv(int argc, char *argv){ char c; int i = 0; char param1[LINEBUF_LEN -2]; // File char param2[LINEBUF_LEN -2]; // Dest while((c=*argv++) != ' ' && c != '\0'){ param1[i++] = c; } i = 0; while((c=*argv++) != ' ' && c != '\0'){ param2[i++] = c; } if(param1[0] == '\0' || param2[0] == '\0'){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy: param1 = -%s-, param2=-%s-\n", param1, param2); return EXIT_FAILURE; } // Prevent recursive calls if(streq(param1, param2)){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy or recursive instruction attempt.\n"); return EXIT_FAILURE; } /* First search for the file to copy */ inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; bool found = FALSE; int j = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param1, currentFile->name) == TRUE && (currentFile->state == PRESENT) && currentFile->type == FILE_TYPE ) { found = TRUE; break; } free(currentFile); } if (found) { /* Now search for the directory to copy the file */ cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentDirFile = NULL; found = FALSE; j = 0; while ((currentDirFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param2, currentDirFile->name) == TRUE) { found = TRUE; break; } free(currentDirFile); } if (found) { if(currentDirFile->type == DIR_TYPE){ fsCopy(getInodeForEntry(currentDirFile), currentFile); rmRecursive(1, param1); free(currentDirFile); return EXIT_SUCCESS; }else{ printfcolor(ERROR_COLOR, "ERROR: Filename already exists.\n"); free(currentDirFile); return EXIT_FAILURE; } } else { // Rename the file in the current directory fsRename(cwd_inode, currentFile, param2); return EXIT_SUCCESS; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } int ln(int argc, char *argv){ char c; int i = 0; char param1[LINEBUF_LEN -2]; // File char param2[LINEBUF_LEN -2]; // Dest while((c=*argv++) != ' ' && c != '\0'){ param1[i++] = c; } i = 0; while((c=*argv++) != ' ' && c != '\0'){ param2[i++] = c; } if(param1[0] == '\0' || param2[0] == '\0'){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy: param1 = -%s-, param2=-%s-\n", param1, param2); return EXIT_FAILURE; } // Prevent recursive calls if(streq(param1, param2)){ printfcolor(ERROR_COLOR, "ERROR: Incorrect syntax for copy or recursive instruction attempt.\n"); return EXIT_FAILURE; } /* First search for the file to copy */ inode_t * cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentFile = NULL; int ino_no = 0; bool found = FALSE; int j = 0; while ((currentFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param1, currentFile->name) == TRUE && (currentFile->state == PRESENT)) { ino_no = currentFile->inode_number; found = TRUE; break; } free(currentFile); } if (found) { /* Now search for the directory to copy the file */ cwd_inode = get_current_task()->parent->cwd; fileentry_t * currentDirFile = NULL; found = FALSE; j = 0; while ((currentDirFile = (fileentry_t *) fsGetFileentry(cwd_inode, j++)) != NULL && !found) { if (streq(param2, currentDirFile->name) == TRUE && currentDirFile->type == DIR_TYPE) { found = TRUE; break; } free(currentDirFile); } if (!found) { fsAddLink(cwd_inode, getInodeByNumber(ino_no), param2); free(currentDirFile); } else { printfcolor(ERROR_COLOR, "ERROR: Already exists a file with such name.\n"); return EXIT_FAILURE; } free(currentFile); } else { printfcolor(ERROR_COLOR, "ERROR: No such file or directory.\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
C
//C program John Woltz // Comp 530 // On my honor, I pledge that I have neither given nor received unauthorized aid on this assignment #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #define MAX_INPUT 80 main(){ char fileName[MAX_INPUT]; int childPID; char *holder; char *args[MAX_INPUT]; char input[MAX_INPUT]; int fileCounter = 0; int arraySequence =0; int charSequence=0; int holderSequence=0; int i = 0; while(1==1){ printf("%c ",'%'); fgets(input, MAX_INPUT, stdin); i=0; while(i<MAX_INPUT){ if(input[i]==EOF){ exit(0); } i++; } args[i] = strtok(input," "); while(args[i]!=NULL) { args[++i] = strtok(NULL," "); } i=0; childPID=fork(); if(childPID==0){ execvp(args[0],args); printf("%s\n", "File Not Resolved"); exit(0); } else{ charSequence=0; holderSequence=0; arraySequence=0; fileCounter=0; while(i<MAX_INPUT){ // A loop to empty the args string before waiting args[i]=0; i++; } i=0; wait(); } }}
C
/* дһ򣬰ΪַȡֱEOFóӡÿַASCIIʮֵ * עASCIIпոַǰַǷǴӡַҪ⴦Щַ * ǴӡַǻзƱֱӡ\n\tʹÿַš * 磬ASCIIlCtrl+AʾΪAAעAASCֵCtrl+Aֵ64 * ǴӡַҲƵĹϵȥÿһзʱͿʼһ֮⣬ÿдӡ10ֵ */ #include <stdio.h> #include <stdlib.h> int main() { char ch; FILE * fp; fp = fopen("d:\\123.txt","r"); if(fp == NULL) { printf("ļʧܣ\n"); exit(1); } int count = 0; while((ch = getc(fp)) != EOF) { if (ch == '\n') { printf("\\n=%d\n", ch, ch); count = 0; } else if(ch == '\t') printf("\\t=%d\t", ch); else if (ch < 32) printf("%c%c=%d\t", ch+64, ch+64, ch); else printf("%c=%d\t", ch, ch); count++; if(count == 10) { putchar(10); count = 0; } } return 0; }
C
# include <stdlib.h> # include <stdio.h> int main( int argc, char ** argv ) { unsigned long int iFactorielle = 1; unsigned int iNombre = 0; unsigned int i = 0; printf( "Entrer un nombre entre 0 et 15 : " ); scanf( "%d", &iNombre ); if( ( iNombre >= 0 ) && ( iNombre <= 15 ) ) { for( i = 1; i <= iNombre; i++ ) { iFactorielle *= i; } printf( "%d! = %ld\n", iNombre, iFactorielle ); } else { printf( "Valeur incorrecte\n" ); } return EXIT_SUCCESS; }
C
/** * \file InputSource.h * * \author Raphael Montanari * \date 23/05/2013 * * Enum InputSource header file. */ #ifndef INPUT_SOURCE_H #define INPUT_SOURCE_H /** * \enum InputSource * \brief The source video input. **/ enum class InputSource { NONE, /**< Not capturing images. */ CAMERA, /**< Capturing images from a camera. */ FILE, /**< Capturing images from a video file. */ ROS /**< Capturing images from a ROS Node. */ }; #endif /* INPUT_SOURCE_H */
C
#include <stdio.h> #include <stdlib.h> //Fazendo um programa de reajuste salarial //Se cargo = 1 : 7% - Se cargo = 2 : 9% - Se cargo = 3 : 5% - Se cargo = 4 : 12% int main() { int cargo; float salario, reajuste, salarioa; printf("Informe o seu cargo: "); scanf("%d", &cargo); printf("\nInforme seu salario atual: "); scanf("%f", &salario); if (cargo==1) { reajuste=(salario*0.07); } else if(cargo==2) { reajuste=(salario*0.09); } else if(cargo==3) { reajuste=(salario*0.05); } else{ reajuste=(salario*0.12); } (salarioa=salario+reajuste); printf("\nO reajuste e: %.2f e o salario atualizado e: %.2f\n",reajuste, salarioa); }
C
#include <stdio.h> #define max 100 struct stack { int top; int a[max]; }s; //void push(int *,int); //int pop(int *); //int isstackempty(int *); //int isstackfull(int *); //void display(int *); int isstackempty(struct stack *s1) { if(s1->top==-1) return 1; else return 0; } int isstackfull(struct stack *s1) { if(s1->top==(max-1)) return 1; else return 0; } void push(struct stack *s1,int value) { if(isstackfull(s1)) return ; else { s1->top=(s1->top)+1; s1->a[s1->top]=value; } } int pop(struct stack *s1) { if(isstackempty(s1)) return ; else{ int k=s1->a[s1->top]; s1->top=(s1->top)-1; return k; } } void display(struct stack *s1) { for( int i=s1->top;i>=0;i--) { printf(" the stasj is %d\n",s1->a[i]); } } int main() { s.top=-1; push(&s,1); push (&s,2); push(&s,3); int p=pop(&s); printf("the pop ele is %d",p); display(&s); //printf("stack is%d ",T); return 0; }
C
/* * * Task 2 ANSI Terminal Control Sequences * */ //------------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------------ #include "stm32f769xx.h" #include "hello.h" #include<stdint.h> void red(){ // print char color red printf("\033[1;31m"); } void yellow(){ //print char color yellow printf("\033[1;33m"); } void top_msg(){ //top message printed printf("\n"); printf(" PRESS <ESC> OR <CTL>+[ TO QUIT\n"); printf("\n"); printf("\033[6;0H"); } int main(void) { Sys_Init(); char choice; int row = 12; int init_char = 0; printf("\033[0;33;44m"); printf("\033[2J\033[;H"); fflush(stdout); top_msg(); while(1) { choice = getchar(); //get input // quit the programm with ESC pr "^+["" if (choice == 0x1B) {return 1;} // For the case which the char is not printable if(choice < 0x21 || choice > 0x7E){ if (row < 25){ printf("\033[5;33;44m"); //set blinking, font and background color printf("\033[%d;1H",row); if (row < 24){ // when the line is less than 24 // set underline printf("The keyboard character $%02x is \e[4m\'not printable\'\e[0m\a\n",choice); row++; } else{ // when the line is 24 printf("The keyboard character $%02x is \e[4m\'not printable\'\e[0m\a",choice); fflush(stdout); row++; } } else{ // when the number of line is larger than 24 printf("\033[5;33;44m");//set attribute blinking printf("\033[12;24r"); printf("\033M"); //scroll up printf("\033[24;1H"); printf("\033[k"); //erase new line for blue background printf("\n"); // activate scroll up and erase printf("\033[24;1H"); printf("The keyboard character $%02x is \e[4m\'not printable\'\e[0m\a", choice); fflush(stdout); //print the new line } } else { if (init_char == 0){ //First time print on the screen printf("\033[6;0H"); printf("\033[0;33;44m"); printf("\rThe keyboard character is "); red(); // set the char red putchar(choice); yellow(); printf("\r\n"); init_char = 1; // set the varibale to indicate the line is printed once } else{ printf("\033[6;27H"); //change only the input character printf("\033[k"); printf("\033[0;31;44m"); putchar(choice); printf("\n"); printf("\033[0;33;44m"); } } } }
C
#include <stdio.h> void main(){ float a,b,c,area,t; printf("֣"); scanf("%f%f%f,",&a,&b,&c); printf("a=%.2f,b=%.2f,c=%.2f",a,b,c); if(a+b>c&&a+c>b&&b+c>a){ t = (a+b+c)/2.0; area = sqrt(t*(t-a)*(t-b)*(t-c)); printf("\n"); printf("Ϊ:%.4f",area); printf("\n"); if(a==b&&a==c){ printf("ȱ"); } else if(a*a+b*b==c*c||a*a+c*c==b*b||b*b+c*c==a*a){ printf("ֱ"); }else if(a==b||a==c||b==c){ printf(""); }else{ printf(""); } }else{ printf("ܹ"); } }
C
#define _DEFAULT_SOURCE /* for snprintf(3) */ #include "ast.h" #include "ramfuck.h" #include "symbol.h" #include <stdio.h> #include <stdlib.h> #include <string.h> /* * AST allocation and initialization functions. */ struct ast *ast_value_new(struct value *value) { struct ast_value *n; if ((n = malloc(sizeof(struct ast_value)))) { n->tree.node_type = AST_VALUE; n->tree.value_type = value->type; n->value = *value; } return (struct ast *)n; } struct ast *ast_var_new(struct symbol_table *symtab, size_t sym, size_t size) { struct ast_var *n; if ((n = malloc(sizeof(struct ast_var)))) { n->tree.node_type = AST_VAR; n->tree.value_type = symtab->symbols[sym]->type; n->symtab = symtab; n->sym = sym; n->size = size ? size : value_type_sizeof(n->tree.value_type); } return (struct ast *)n; } struct ast *ast_cast_new(enum value_type value_type, struct ast *child) { struct ast_cast *n; if ((n = malloc(sizeof(struct ast_cast)))) { ((struct ast *)n)->node_type = AST_CAST; ((struct ast *)n)->value_type = value_type; ((struct ast_unary *)n)->child = child; } return (struct ast *)n; } struct ast *ast_deref_new(struct ast *child, enum value_type value_type, struct target *target) { struct ast_deref *n; if ((n = malloc(sizeof(struct ast_deref)))) { ((struct ast *)n)->node_type = AST_DEREF; ((struct ast *)n)->value_type = value_type; ((struct ast_unary *)n)->child = child; n->target = target; } return (struct ast *)n; } struct ast *ast_unary_new(enum ast_type node_type, struct ast *child) { struct ast_unary *n; if ((n = malloc(sizeof(struct ast_unary)))) { n->tree.node_type = node_type; n->child = child; } return (struct ast *)n; } struct ast *ast_binary_new(enum ast_type node_type, struct ast *left, struct ast *right) { struct ast_binary *n; if ((n = malloc(sizeof(struct ast_binary)))) { n->tree.node_type = node_type; n->left = left; n->right = right; } return (struct ast *)n; } /* * Delete. */ static void ast_leaf_delete(struct ast *this) { free(this); } static void ast_unary_delete(struct ast *this) { ast_delete(((struct ast_unary *)this)->child); free(this); } static void ast_binary_delete(struct ast *this) { ast_delete(((struct ast_binary *)this)->left); ast_delete(((struct ast_binary *)this)->right); free(this); } void (*ast_delete_funcs[AST_TYPES])(struct ast *) = { /* AST_VALUE */ ast_leaf_delete, /* AST_VAR */ ast_leaf_delete, /* AST_CAST */ ast_unary_delete, /* AST_DEREF */ ast_unary_delete, /* AST_NEG */ ast_unary_delete, /* AST_NOT */ ast_unary_delete, /* AST_COMPL */ ast_unary_delete, /* AST_ADD */ ast_binary_delete, /* AST_SUB */ ast_binary_delete, /* AST_MUL */ ast_binary_delete, /* AST_DIV */ ast_binary_delete, /* AST_MOD */ ast_binary_delete, /* AST_AND */ ast_binary_delete, /* AST_XOR */ ast_binary_delete, /* AST_OR */ ast_binary_delete, /* AST_SHL */ ast_binary_delete, /* AST_SHR */ ast_binary_delete, /* AST_EQ */ ast_binary_delete, /* AST_NEQ */ ast_binary_delete, /* AST_LT */ ast_binary_delete, /* AST_GT */ ast_binary_delete, /* AST_LE */ ast_binary_delete, /* AST_GE */ ast_binary_delete, /* AST_AND_COND */ ast_binary_delete, /* AST_OR_COND */ ast_binary_delete }; /* * AST printing. */ void ast_print(struct ast *ast) { char buf[BUFSIZ]; size_t len = ast_snprint(ast, buf, sizeof(buf)); if (len < sizeof(buf)) { fwrite(buf, sizeof(char), len, stdout); } else { char *p = malloc(len+1); if (p) { if (ast_snprint(ast, p, len+1) == len) { fwrite(p, sizeof(char), len, stdout); } else { errf("ast: inconsistent ast_snprint() results"); } free(p); } else { errf("ast: out-of-memory"); } } } static size_t ast_value_snprint(struct ast *this, char *out, size_t size) { size_t len = 0; struct value *value = &((struct ast_value *)this)->value; const char *type = value_type_to_string(this->value_type); if (size && len < size-1) len += snprintf(out+len, size-len, "(%s)", type); else len += snprintf(NULL, 0, "(%s)", type); if (size && len < size-1) len += value_to_string(value, out+len, size-len); else len += value_to_string(value, NULL, 0); return len; } static size_t ast_var_snprint(struct ast *this, char *out, size_t size) { struct ast_var *var = (struct ast_var *)this; const char *type = value_type_to_string(this->value_type); const char *name = symbol_name(var->symtab->symbols[var->sym]); return snprintf(out, size, "(%s)%s", type, name); } static size_t ast_cast_snprint(struct ast *this, char *out, size_t size) { const char *type; struct ast *child = ((struct ast_unary *)this)->child; size_t len = 0; if (size && len < size-1) { len += ast_snprint(child, out, size); } else len += ast_snprint(child, NULL, 0); type = value_type_to_string(this->value_type); if (size && len < size-1) len += snprintf(out+len, size-len, " (%s)", type); else len += snprintf(NULL, 0, " (%s)", type); return len; } static size_t ast_unary_snprint(struct ast *this, const char *op, char *out, size_t size) { size_t len = 0; struct ast *child = ((struct ast_unary *)this)->child; if (size && len < size-1) { len += ast_snprint(child, out, size); } else len += ast_snprint(child, NULL, 0); if (size && len < size-1) len += snprintf(out+len, size-len, " %s", op); else len += snprintf(NULL, 0, " %s", op); return len; } static size_t ast_deref_snprint(struct ast *this, char *out, size_t size) { const char *type; struct ast *child = ((struct ast_unary *)this)->child; size_t len = 0; if (size && len < size-1) { len += ast_snprint(child, out, size); } else len += ast_snprint(child, NULL, 0); type = value_type_to_string(this->value_type); if (size && len < size-1) len += snprintf(out+len, size-len, " *(%s *)", type); else len += snprintf(NULL, 0, " *(%s *)", type); return len; } static size_t ast_binary_snprint(struct ast *this, const char *op, char *out, size_t size) { size_t len = 0; struct ast *left = ((struct ast_binary *)this)->left; struct ast *right = ((struct ast_binary *)this)->right; if (size && len < size-1) len += ast_snprint(left, out, size); else len += ast_snprint(left, NULL, 0); if (size && len < size-1) len += snprintf(out+len, size-len, " "); else len += snprintf(NULL, 0, " "); if (size && len < size-1) len += ast_snprint(right, out+len, size-len); else len += ast_snprint(right, NULL, 0); if (size && len < size-1) len += snprintf(out+len, size-len, " %s", op); else len += snprintf(NULL, 0, " %s", op); return len; } static size_t ast_neg_snprint(struct ast *this, char *out, size_t size) { return ast_unary_snprint(this, "u-", out, size); } static size_t ast_not_snprint(struct ast *this, char *out, size_t size) { return ast_unary_snprint(this, "!", out, size); } static size_t ast_compl_snprint(struct ast *this, char *out, size_t size) { return ast_unary_snprint(this, "~", out, size); } static size_t ast_add_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "+", out, size); } static size_t ast_sub_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "-", out, size); } static size_t ast_mul_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "*", out, size); } static size_t ast_div_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "/", out, size); } static size_t ast_mod_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "%", out, size); } static size_t ast_and_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "&", out, size); } static size_t ast_xor_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "^", out, size); } static size_t ast_or_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "|", out, size); } static size_t ast_shl_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "<<", out, size); } static size_t ast_shr_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, ">>", out, size); } static size_t ast_eq_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "==", out, size); } static size_t ast_neq_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "!=", out, size); } static size_t ast_lt_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "<", out, size); } static size_t ast_gt_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, ">", out, size); } static size_t ast_le_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "<=", out, size); } static size_t ast_ge_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, ">=", out, size); } static size_t ast_and_cond_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "&&", out, size); } static size_t ast_or_cond_snprint(struct ast *this, char *out, size_t size) { return ast_binary_snprint(this, "||", out, size); } size_t (*ast_snprint_funcs[AST_TYPES])(struct ast *, char *, size_t) = { /* AST_VALUE */ ast_value_snprint, /* AST_VAR */ ast_var_snprint, /* AST_CAST */ ast_cast_snprint, /* AST_DEREF */ ast_deref_snprint, /* AST_NEG */ ast_neg_snprint, /* AST_NOT */ ast_not_snprint, /* AST_COMPL */ ast_compl_snprint, /* AST_ADD */ ast_add_snprint, /* AST_SUB */ ast_sub_snprint, /* AST_MUL */ ast_mul_snprint, /* AST_DIV */ ast_div_snprint, /* AST_MOD */ ast_mod_snprint, /* AST_AND */ ast_and_snprint, /* AST_XOR */ ast_xor_snprint, /* AST_OR */ ast_or_snprint, /* AST_SHL */ ast_shl_snprint, /* AST_SHR */ ast_shr_snprint, /* AST_EQ */ ast_eq_snprint, /* AST_NEQ */ ast_neq_snprint, /* AST_LT */ ast_lt_snprint, /* AST_GT */ ast_gt_snprint, /* AST_LE */ ast_le_snprint, /* AST_GE */ ast_ge_snprint, /* AST_AND_COND */ ast_and_cond_snprint, /* AST_OR_COND */ ast_or_cond_snprint };
C
#include <stdio.h> #include <stdlib.h> int board[50]; int cache[50][50]; int ENF = -987654321; int playGame(int left, int right){ int * ret = &cache[left][right]; int leftChoice, rightChoice; if(left > right) return 0; if(*ret != ENF) return *ret; if(left == right) return board[left]; leftChoice = board[left] - playGame(left+1, right); rightChoice = board[right] - playGame(left, right-1); *ret = leftChoice > rightChoice ? leftChoice : rightChoice; if(right-left+1 >= 2){ leftChoice = -playGame(left+2, right); rightChoice = -playGame(left, right-2); *ret = leftChoice > *ret ? leftChoice : *ret; *ret = rightChoice > *ret ? rightChoice : *ret; } return *ret; } int main() { int caseNum; scanf("%d", &caseNum); int answer[caseNum]; for(int i=0; i<caseNum; i++){ int length; scanf("%d", &length); for(int j=0; j<length; j++) scanf("%d", &board[j]); for(int a=0; a<50; a++) for(int b=0; b<50; b++) cache[a][b] = ENF; answer[i] = playGame(0, length-1); } for(int i=0; i<caseNum; i++) printf("%d\n", answer[i]); return 0; }
C
#include <unistd.h> #include "../../commons/src/dbg.h" #include "minunit.h" #include "../src/lib/mip_route_table.h" char *test_MIPRouteTable_create() { MIPRouteTable *table = MIPRouteTable_create(1); mu_assert(table != NULL, "Table pointer should not be NULL"); MIPRouteTable_destroy(table); return NULL; } char *test_MIPRouteTable_update() { MIP_ADDRESS result = 0; int rc = 0; MIPRouteTable *table = MIPRouteTable_create(); rc = MIPRouteTable_update(table, 1, 1, 0); result = MIPRouteTable_get_next_hop(table, 1); mu_assert(result == 1, "Wrong next hop returned"); MIPRouteTable_destroy(table); return NULL; } char *test_MIPRouteTable_dvr(){ MIPRouteTable *table1 = MIPRouteTable_create(); MIPRouteTable *table2 = MIPRouteTable_create(); table2->table_address = 2; MIPRouteTable_update(table1, 1, 255, 0); MIPRouteTable_update(table1, 2, 2, 1); MIPRouteTable_update(table1, 3, 3, 5); MIPRouteTable_update(table2, 2, 255, 0); MIPRouteTable_update(table2, 1, 1, 1); MIPRouteTable_update(table2, 3, 3, 1); MIPRouteTable_update_routing(table1, table2); printf("table1:\n"); MIPRouteTable_print(table1); mu_assert(MIPRouteTable_get_next_hop(table1, 3) == 2, "Wrong route to node 3"); MIPRouteTable_destroy(table1); MIPRouteTable_destroy(table2); return NULL; } char *test_MIPRouteTable_print(){ MIPRouteTable *table = MIPRouteTable_create(); MIPRouteTable_update(table, 110, 255, 1); MIPRouteTable_update(table, 25, 3, 5); MIPRouteTable_update(table, 40, 3, 1); MIPRouteTable_print(table); MIPRouteTable_destroy(table); return NULL; } char *test_MIPRouteTable_create_package(){ MIPRouteTable *table = MIPRouteTable_create(); MIPRouteTable_update(table, 1, 255, 0); MIPRouteTable_update(table, 2, 2, 1); MIPRouteTable_update(table, 3, 3, 5); MIPRouteTable_update(table, 4, 3, 1); MIPRouteTablePackage *package = MIPRouteTable_create_package(table); mu_assert(package != NULL, "TablePackage is NULL"); mu_assert(package->entries[0].destination == 1 && package->entries[0].cost == 0, "Wrong destination"); mu_assert(package->entries[3].destination == 4 && package->entries[3].cost == 1, "Wrong destination"); printf("Size of package: %d\n", sizeof(MIPRouteTablePackage)); MIPRouteTable *table2 = MIPRouteTablePackage_create_table(package); mu_assert(table2 != NULL, "New table is NULL"); mu_assert(MIPRouteTable_get_next_hop(table, 4) == MIPRouteTable_get_next_hop(table2, 4), "Failed to convert package to table"); MIPRouteTable_destroy(table); MIPRouteTable_destroy(table2); MIPRouteTablePackage_destroy(package); return NULL; } char *test_MIPRouteTable_remove_old_entries(){ MIPRouteTable *table = MIPRouteTable_create(); table->entry_max_age_milli = 0; MIPRouteTable_update(table, 1, 255, 0); MIPRouteTable_update(table, 2, 2, 1); MIPRouteTable_update(table, 3, 3, 5); MIPRouteTable_update(table, 4, 3, 1); sleep(1); MIPRouteTable_remove_old_entries(table); mu_assert(table->entries->count == 1, "Number of addresses in table is not 1"); MIPRouteTable_destroy(table); return NULL; } char *all_tests(){ mu_suite_start(); mu_run_test(test_MIPRouteTable_create); mu_run_test(test_MIPRouteTable_update); mu_run_test(test_MIPRouteTable_dvr); mu_run_test(test_MIPRouteTable_print); mu_run_test(test_MIPRouteTable_create_package); mu_run_test(test_MIPRouteTable_remove_old_entries); return NULL; } RUN_TESTS(all_tests);
C
/** 2014 Neil Edelman This is the simulation of a client. @author Neil @version 1 @since 2014 */ #include <stdlib.h> /* malloc free */ #include <stdio.h> /* fprintf */ #include <string.h> /* str* */ #include <ctype.h> /* toupper */ #include <unistd.h> /* sleep */ #include <pthread.h> #include "Spool.h" #include "Job.h" #include "Client.h" struct Client { pthread_t thread; int is_running; int id; char name[16]; int ms_idle; int pages_min; int pages_max; int prints; }; static const int min_page = 1; static const int max_page = 10; static const int time_between_prints = 1; /* s */ static const int min_prints = 1; static const int max_prints = 3; /* private */ static int unique = 1; /* counter to assign id */ /* these are loosely based on orcish from Smaug1.8 */ static const char *words[] = { /* max chars 4 */ "uk", "all", "uk", "ul", "um", "orc", "uruk", "ee", "ou", "eth", "om", "ith", "uuk", "ath", "ohk", "uth", "um", "th", "gn", "oo", "uu", "ar", "arg", "en", "yth", "ion", "um", "es", "ac", "ch", "k", "ul", "um", "ick", "uk", "of", "tuk", "ove", "aah", "ome", "ask", "my", "mal", "me", "mok", "to", "sek", "hi", "come", "vak", "bat", "buy", "muk", "kham", "kzam" }; static const int words_size = sizeof(words) / sizeof(char *); static const char *suffixes[] = { /* max chars 7 */ "agh", "ash", "bag", "ronk", "bubhosh", "burz", "dug", "durbat", "durb", "ghash", "gimbat", "gimb", "-glob", "glob", "gul", "hai", "ishi", "krimpat", "krimp", "lug", "nazg", "nazgul", "olog", "shai", "sha", "sharku", "snaga", "thrakat", "thrak", "gorg", "khalok", "snar", "kurta", "ness", "-dug", "-gimb" }; static const int suffixes_size = sizeof(suffixes) / sizeof(char *); static void *thread(struct Client *client); static int random_int(const int a, const int b); static void random_name(char *name); /* public */ /** constructor @return an object or a null pointer if the object couldn't be created */ struct Client *Client(void) { struct Client *client; if(!(client = malloc(sizeof(struct Client)))) { perror("Client constructor"); Client_(&client); return 0; } client->is_running= 0; client->id = unique++; client->ms_idle = time_between_prints; client->pages_min = min_page; client->pages_max = max_page; client->prints = random_int(min_prints, max_prints); random_name(client->name); fprintf(stderr, "Client: new, %s (%d) #%p.\n", client->name, client->id, (void *)client); /*fixme! post(empty);*/ return client; } /** destructor @param client_ptr a reference to the object that is to be deleted */ void Client_(struct Client **client_ptr) { struct Client *client; if(!client_ptr || !(client = *client_ptr)) return; if(client->is_running) { void *value; pthread_join(client->thread, &value); client->is_running = 0; fprintf(stderr, "~Client: %s thread return #%p, erase #%p.\n", client->name, value, (void *)client); } else { fprintf(stderr, "~Client: %s (not running) erase #%p.\n", client->name, (void *)client); } free(client); *client_ptr = client = 0; } /** @return name */ const char *ClientGetName(const struct Client *c) { return c ? c->name : "(null)"; } /** run the client @return non-zero on success */ int ClientRun(struct Client *c) { if(!c || c->is_running) return 0; pthread_create(&c->thread, 0, (void *(*)(void *))&thread, c); c->is_running = -1; return -1; } /* private */ /** the client thead @param client @return null */ static void *thread(struct Client *client) { struct Job *job; if(!client || client->prints <= 0) return 0; for( ; ; ) { job = Job(client, random_int(client->pages_min, client->pages_max)); if(!SpoolPushJob(job)) return (void *)-1; if(--client->prints <= 0) break; sleep(client->ms_idle); } printf("%s signing off.\n", client->name); return 0; } /** @param a @param b @return random number in [a, b], uniformly distributed */ static int random_int(const int a, const int b) { /* not thread safe (just be careful) */ int r = (int)(((float)rand() / RAND_MAX) * (float)(b - a + 1)) + a; /* in case rand returned RAND_MAX */ return r > b ? b : r; } /** come up with random names @param name the string that's going to hold it, must be at least 2*max(words4) + max(suffixes7) + 1 long (cur 16) */ static void random_name(char *name) { int i; /* fixme: there's no gauratee that these are unique, but it doesn't really matter */ i = rand() % words_size; strcpy(name, words[i]); i = rand() % words_size; strcat(name, words[i]); i = rand() % suffixes_size; strcat(name, suffixes[i]); name[0] = toupper(name[0]); }
C
#include<stdio.h> int main() { int numOfProcess,burstTime[10],waitingTime[10],turnAroundTime[10],averageWaitingTime=0,i,j; do{ printf("Number of processes:"); scanf("%d",&numOfProcess); if (numOfProcess>10 || numOfProcess <1) { printf("Please enter a process number between 1 and 10 !!!\n"); printf("\n"); } } while(numOfProcess>10 || numOfProcess <1); printf("\nEnter Burst Times for per Processor\n"); for(i=0; i<numOfProcess; i++) { printf("P(%d):",i+1); scanf("%d",&burstTime[i]); } waitingTime[0]=0;//waiting time first unit is 0 //Waiting time evaluations for(i=1; i<numOfProcess; i++) { waitingTime[i]=0; for(j=0;j<i;j++) waitingTime[i]+=burstTime[j]; } printf("\nProcess Number Burst Time Waiting Time TurnAround Time"); //Turnaround time evaluating for(i=0; i<numOfProcess; i++) { turnAroundTime[i]= burstTime[i]+ waitingTime[i]; averageWaitingTime += waitingTime[i]; printf("\nP(%d) \t\t\t%d\t\t%d\t\t%d",i+1,burstTime[i],waitingTime[i],turnAroundTime[i]); } averageWaitingTime /= i; printf("\n\nAverage Waiting Time: %d",averageWaitingTime); printf("\n"); return 0; }
C
#pragma once #include "Joycon.h" //Returns new Joycon struct joycon_t make_joycon(const struct hid_device_info* dev) { if (dev == NULL) { perror("Device cannot be NULL pointer."); exit(1); } joycon_t jc; if (dev->product_id == JOYCON_L_BT) { const char name[32] = "Joy-Con (L)"; strcpy_s(jc.name, sizeof(jc.name), name); jc.type = JC_LEFT; } else if (dev->product_id == JOYCON_R_BT) { const char name[32] = "Joy-Con (R)"; strcpy_s(jc.name, sizeof(jc.name), name); jc.type = JC_RIGHT; } jc.serial = _wcsdup(dev->serial_number); jc.handle = hid_open_path(dev->path); jc.global_packet_number = 0; if (jc.handle == NULL) { perror("Couldn't open device handle"); exit(1); } return jc; } //Cleans up after using makeJoycon void delete_joycon(joycon_t* jc) { if (jc != NULL) { hid_close(jc->handle); jc->handle = NULL; free(jc->serial); jc->serial = NULL; } } void send_command(joycon_t* jc, int command, uint8_t* data, int len) { unsigned char buf[COMMAND_BUF_SIZE]; memset(buf, 0, COMMAND_BUF_SIZE); /* One byte for command and 63 bytes for data. */ buf[0] = command; if (data && len != 0) { memcpy(buf + 1, data, len); } int result = hid_write(jc->handle, buf, len + 1); result = hid_read(jc->handle, buf, COMMAND_BUF_SIZE); if (data) { memcpy(data, buf, COMMAND_BUF_SIZE); } } void send_subcommand(joycon_t* jc, int command, int subcommand, uint8_t* data, int len) { uint8_t buf[COMMAND_BUF_SIZE]; memset(buf, 0, COMMAND_BUF_SIZE); buf[0] = command; //0x01 for everything, 0x10 for rumble buf[1] = jc->global_packet_number; jc->global_packet_number++; jc->global_packet_number %= 0xF; uint8_t rumbleData[8] = { 0x00, 0x01, 0x40, 0x40, 0x00, 0x01, 0x40, 0x40 }; memcpy(buf + 2, rumbleData, 8); buf[10] = subcommand; memcpy(buf + 11, data, len); int result = hid_write(jc->handle, buf, COMMAND_BUF_SIZE); result = hid_read(jc->handle, buf, len); if (data) { memcpy(data, buf, len); } } void set_lights(joycon_t* jc, uint8_t bytefield) { uint8_t buff[1] = { bytefield }; send_subcommand(jc, 0x01, 0x30, buff, 1); } //basic position X = 2225, Y = 1835 void get_analog_stick_position(joycon_t* jc, uint16_t* X, uint16_t* Y) { uint8_t buff[362]; memset(buff, 0, 362); send_subcommand(jc, 0x01, 0x00, buff, 362); if (buff[0] == 0x21 || buff[0] == 0x30 || buff[0] == 0x31) { //check the packet ID uint8_t* data = buff + (jc->type == JC_LEFT ? 6 : 9); *Y = data[0] | ((data[1] & 0xF) << 8); *X = (data[1] >> 4) | (data[2] << 4); } } //byte 1 // 00000001 = DOWN // 00000010 = RIGHT // 00000100 = LEFT // 00001000 = UP // 00010000 = SL // 00100000 = SR // // byte2 // 00000001 = MINUS // = PLUS? // = LEFT STICK // = RIGHT STICK // = HOME // = CAPTURE // = L/R // = ZL/ZR uint8_t get_buttons_status(joycon_t* jc, buttons_info_t* btn_info_out) { uint8_t buff[12]; memset(buff, 0, 12); int res = hid_read_timeout(jc->handle, buff, 12, 10); if (res && buff[0] == 0x3F) { //check if packet is a status packet btn_info_out->DOWN = (buff[1] & 1) != 0; btn_info_out->RIGHT = (buff[1] & (1 << 1)) != 0; btn_info_out->LEFT = (buff[1] & (1 << 2)) != 0; btn_info_out->UP = (buff[1] & (1 << 3)) != 0; btn_info_out->SL = (buff[1] & (1 << 4)) != 0; btn_info_out->SR = (buff[1] & (1 << 5)) != 0; btn_info_out->MINUS_PLUS = ((buff[2] & 1) | (buff[2] & (1 << 1))) != 0; btn_info_out->STICK = ((buff[2] & (1 << 2)) | (buff[2] & (1 << 3))) != 0; btn_info_out->HOME_CAPTURE = ((buff[2] & (1 << 4)) | (buff[2] & (1 << 5))) != 0; btn_info_out->R_L = (buff[2] & (1 << 6)) != 0; btn_info_out->ZR_ZL = (buff[2] & (1 << 7)) != 0; btn_info_out->STICK_POS = buff[3]; } } // WIP: dopisac obsluge reszty przyciskow uint8_t get_buttons_status_ext(joycon_t* jc, buttons_info_ext_t* btn_info_out) { uint8_t buff[256]; memset(buff, 0, sizeof(buff)); send_subcommand(jc, 0x01, 0x00, buff, 256); if (buff[0] == 0x21 || buff[0] == 0x30 || buff[0] == 0x31) { //check the packet ID uint8_t* data = buff + (jc->type == JC_LEFT ? 6 : 9); btn_info_out->ANALOG_STICK_Y = data[0] | ((data[1] & 0xF) << 8); btn_info_out->ANALOG_STICK_X = (data[1] >> 4) | (data[2] << 4); btn_info_out->buttons_info.DOWN = (buff[3] & 1) != 0; btn_info_out->buttons_info.RIGHT = (buff[3] & (1 << 1)) != 0; btn_info_out->buttons_info.LEFT = (buff[3] & (1 << 2)) != 0; btn_info_out->buttons_info.UP = (buff[3] & (1 << 3)) != 0; btn_info_out->buttons_info.SL = (buff[3] & (1 << 4)) != 0; btn_info_out->buttons_info.SR = (buff[3] & (1 << 5)) != 0; return 0; } return 1; }
C
#include <stdio.h> enum tresholds_t { TRESHOLDS_FIRST = 10, TRESHOLDS_SECOND, TRESHOLDS_THIRD = 20 }; void sort(int* values, int* indexes, int n) { int i; int j; for (i = 0; i < (n - 1); i++) { for (j = i + 1; j < n; j++) { if (values[i] - values[j] < 0) { int tmp; tmp = values[i]; values[i] = values[j]; values[j] = tmp; tmp = indexes[i]; indexes[i] = indexes[j]; indexes[j] = tmp; } } } } void print(int* values, int* indexes, int n) { int i = 0; printf("Up to the first treshold: "); while (values[i] > TRESHOLDS_THIRD && i < n) { printf("%d(%d) ", values[i], indexes[i]); i++; } printf("\n"); printf("Up to the second treshold: "); while (values[i] > TRESHOLDS_SECOND && i < n) { printf("%d(%d) ", values[i], indexes[i]); i++; } printf("\n"); printf("Up to the third treshold: "); while (values[i] > TRESHOLDS_FIRST && i < n) { printf("%d(%d) ", values[i], indexes[i]); i++; } } void main() { int values[30000]; int indexes[30000]; int i; int n; printf("Number of elements: "); scanf("%d", &n); printf("\n"); for (i = 0; i < n; i++) { printf("%d. element: ", i); scanf("%d", &values[i]); indexes[i] = i; printf("\n"); } sort(values, indexes, n); print(values, indexes, n); }
C
#include "Epoll.h" /** * epoll初始化 */ int epoll_init() { int epoll_fd = epoll_create(EPOLL_MAX_NUM); if(epoll_fd < 0){ printf("epoll_create failed in %s\n", __func__); return -1; } printf("\nepoll_init successful!\n"); return epoll_fd; } /** * 初始化event_arg */ struct event_arg* event_arg_create(int epoll_fd, int fd, unsigned int event, void* arg, void* (*callback)(void * arg), char* buf, int buf_len) { struct event_arg * new_event = (struct event_arg *)malloc(sizeof(struct event_arg)); if(!new_event){ return NULL; } new_event->epoll_fd = epoll_fd; new_event->fd = fd; new_event->event = event; new_event->arg = arg; new_event->callback = callback; new_event->buf = buf; new_event->buf_len = buf_len; new_event->is_chat = 0; return new_event; } /** * 向epoll注册监听的描述符 */ int epoll_add_fd(int epoll_fd, struct event_arg* arg) { struct epoll_event write_event; write_event.events = arg->event | EPOLLET; write_event.data.ptr = arg; if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, arg->fd, &write_event) < 0) { printf("epoll_add_fd failed\n"); return -1; } return 0; } /** * 从epoll删除注册的描述符 */ int epoll_del_fd(int epoll_fd, int del_fd) { if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, del_fd, NULL) < 0){ printf("delete fd from epoll failed in %s\n", __func__); return -1; } return 0; } /** * epoll监听 */ int epoll_wait_events(int epoll_fd, struct epoll_event* event_table, int max_ev_num, struct threadpool* pool) { int n_ready = epoll_wait(epoll_fd, event_table, max_ev_num, -1); if(n_ready < 0){ printf("epoll_wait failed\n"); return -1; } printf("%d events ready\n", n_ready); struct event_arg *back_arg = NULL; for(int i = 0; i < n_ready; ++i){ back_arg = (struct event_arg *)(event_table[i].data.ptr); //printf("0x%x 0x%x\n", back_arg->event, event_table[i].events); if(event_table[i].events == back_arg->event){ threadpool_add_task(pool, back_arg->callback, back_arg); //printf("add task successful\n"); } } return 0; }
C
/* Program Description: Client process that accepts arithmetic expressions from the user, * sends to the server and displays the result recieved from the server. * * Authors: Asmit De (10/CSE/53) * Samik Some (10/CSE/93) * * Date: August 17, 2013 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> int main() { struct sockaddr_in serv_addr; int sockfd, i; char buffer[100]; if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Unable to create socket"); exit(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); serv_addr.sin_port = htons(55393); if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("Unable to connect to server"); exit(1); } while(1) { printf("\nEnter arithmetic expression or -1 to exit: "); for(i = 0; i < 100; i++) buffer[i] = '\0'; fgets(buffer, 100, stdin); buffer[strlen(buffer) - 1] = '\0'; fflush(stdin); send(sockfd, buffer, strlen(buffer) + 1, 0); if(!strcmp(buffer, "-1")) break; for(i = 0; i < 100; i++) buffer[i] = '\0'; recv(sockfd, buffer, 100, 0); printf("Result: %s\n", buffer); } close(sockfd); return 0; }
C
#include <functions.h> void test_stack(int argc,char * argv[],char** env) { int i=0; // while(env[i]!=0){ // printf("%s\n", env[i++]); // } printf("ARGC:%d ARGV:%x\n", argc, (unsigned int)argv); for (i = 0; i < argc; i++) printf("Argv[%d] = %x pointing at %s \n", i, (unsigned int)argv[i], argv[i]); }
C
/** * pagerank.h to announce the functions of pagerank * */ #ifndef _PAGERANK_H_ #define _PAGERANK_H_ #include<stdio.h> #include<stdlib.h> #include<string.h> #define LEN 1000 typedef struct graph { char urlname[LEN]; int numberOfHyperlinks; struct graph ** hyperlinks; struct graph * next; }graph; typedef struct wordlist { char word[LEN]; struct wordlist * next; }wordlist; /* * get the url node pointer in graph by pos and return its address */ graph * getNode(graph * head, int pos); /* * check if the root contains link to leaf * if it is true,return 1, else return 0 */ int containsLink(graph * root, graph * leaf); /* * Read "web pages" from the collection in inputing file * and build a graph structure using Adjacency List Representation * N = number of urls in the collection * For each url pi in the collection to calculate it's properity * after generations * output the result to a file named pagerankList.txt */ void PageRank(graph * head, double d, double diffPR, int maxIterations); graph * find(graph * head, char * url); void AddHyperlinks(graph * node, graph * head); graph * GenerateGraph(char * filename); void AddReference(graph * head); #endif
C
#include "stdio.h" #include "string.h" //memcpy function defined in this lib int main(void) { char a[]= "test"; char b[sizeof(a)];// need to set the size if not assign initial values memcpy(b, a, sizeof(b)); //void *memcpy(void *str1, const void *str2, size_t n) printf("b array: %s\n",b); }
C
#include "stm32f10x.h" #include "stm32f10x_rcc.h" #include "stm32f10x_gpio.h" #include "iic2.h" #include "delay.h" /*********************************************************** * : IIC_GPIO_Config() * : IICʼ * : * : * ޸: * ע: ***********************************************************/ void I2C_GPIO_Config(void) { GPIO_InitTypeDef GPIO_InitStructure; /********************ٶȴIIC**********************/ #ifdef ACCELERATION RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB |RCC_APB2Periph_GPIOA, ENABLE); /* Configure I2C1 pins: SCL and SDA */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD; GPIO_Init(GPIOB, &GPIO_InitStructure); #endif } /*********************************************************** * : I2C_delay() * : IICʱ * : * : * ޸: * ע: ***********************************************************/ void I2C_delay(void) { u8 i = 50; //Żٶ ͵5д while(i) { i--; } } /*********************************************************** * : I2C_Start() * : IICʼ * : * : * ޸: * ע: ***********************************************************/ int I2C_Start(void) { SDA_H; I2C_delay(); SCL_H; I2C_delay(); SDA_L; I2C_delay(); SCL_L; I2C_delay(); return 0; } /*********************************************************** * : Stop() * : IICֹͣ * : * : * ޸: * ע: ***********************************************************/ void I2C_Stop(void) { SCL_L; I2C_delay(); SDA_L; I2C_delay(); SCL_H; I2C_delay(); SDA_H; I2C_delay(); } /*********************************************************** * : I2C_Ack() * : Ӧź * : * : * ޸: * ע: ***********************************************************/ void I2C_Ack(void) { SCL_L; I2C_delay(); SDA_L; //SDA͵ƽ I2C_delay(); SCL_H; //SCLߵƽ I2C_delay(); SCL_L; I2C_delay(); } /*********************************************************** * : I2C_NoAck() * : ȷź * : * : * ޸: * ע: ***********************************************************/ void I2C_NoAck(void) { SCL_L; I2C_delay(); SDA_H; I2C_delay(); SCL_H; I2C_delay(); SCL_L; I2C_delay(); } /*********************************************************** * : I2C_WaitAck() * : ȴ豸Ӧź * : * : 1ΪACK,0ΪACK * ޸: * ע: ***********************************************************/ int I2C_WaitAck(void) { SCL_L; I2C_delay(); SDA_H; I2C_delay(); SCL_H; I2C_delay(); if(SDA_read) { SCL_L; return 1; } SCL_L; return 0; } /*********************************************************** * : I2C_SendByte() * : Ͱλ * : SendByte Ҫ͵ֽ * : * ޸: * ע: ***********************************************************/ void I2C_SendByte(u8 SendByte) //ݴӸλλ// { u8 i=8; while(i--) { SCL_L; I2C_delay(); if(SendByte&0x80) { SDA_H; } else { SDA_L; } SendByte<<=1; I2C_delay(); SCL_H; I2C_delay(); } } /*********************************************************** * : I2C_ReceiveByte() * : ȡλ * : * : * ޸: * ע: ***********************************************************/ u8 I2C_ReceiveByte(void) //ݴӸλλ// { u8 i=8; u8 ReceiveByte=0; SDA_H; while(i--) { ReceiveByte<<=1; SCL_L; I2C_delay(); SCL_H;//ʱ SCLΪߵƽ I2C_delay(); if(SDA_read) { ReceiveByte|=0x01; } } return ReceiveByte; }
C
#include <stdio.h> int main(){ int n, resto, palin = 0; int ris = 0, ex = 10; int div; scanf("%d", &n); div = n/ex; while(div != 0 && !palin){ div = n/ex; resto = n % ex; ris = ris*10 + (resto/(ex/10)); if(ris == n) palin = 1; ex = ex*10; } printf("\n%d\n", palin); return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { printf("Nome do executavel: %s\n",argv[0]); for (int i = 1; i < argc; ++i) { printf("Parametro #%d: %s\n",i, argv[i]); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: isidibe- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/09 12:00:43 by isidibe- #+# #+# */ /* Updated: 2017/11/11 11:54:36 by isidibe- ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" #include <stdlib.h> static int ft_wordsnbr(char const *s, char c) { size_t i; int j; i = 0; j = 1; while (s[i] != '\0') { if (s[i] == c) j++; i++; } return (j); } static int ft_taille(char const *s, char c, int i) { size_t j; j = 1; while (s[i] != c) { j++; i++; } return (j); } static char *ft_dup(char const *s, char c, int i) { char *dup; int j; j = 0; dup = (char*)malloc(sizeof(char*) * ft_taille(s, c, i) + 1); if (!dup) return (NULL); while (s[i] != '\0' && s[i] != c) { dup[j] = s[i]; j++; i++; } dup[j] = '\0'; return (dup); } char **ft_strsplit(char const *s, char c) { size_t i; int j; char **str; i = 0; j = 0; if (!s) return (NULL); str = (char**)malloc(sizeof(char**) * ft_wordsnbr(s, c) + 1); if (!str) return (NULL); while (s[i] != '\0') { if (s[i] != c) { str[j] = ft_dup(s, c, i); while (s[i] != c && s[i] != '\0') i++; j++; } if (s[i] != '\0') i++; } str[j] = 0; return (str); }
C
/* * auth.c * * Created on: Jul 7, 2016 * Author: admin_user */ #define _GNU_SOURCE #include <crypt.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include "ocslock.h" #include "ocslog.h" #include "auth.h" void __attribute__((constructor)) initialize(void); static int delete_entry(char *filename, const char *username); static int shadow_append(struct spwd *sp); static void generate_salt(char *salt); int file_restore(char *filename); int file_remove(char *filename); int file_exists(const char *filename, int *error_code); int file_io_op(const auth_file_op action, const char *filename, long length, char *buffer); /****************************************************************************** * Function Name: app_specific_error * Purpose: convert application error into char pointer * In parameters: err, error offset * Return value: pointer to error or default error * Comments/Notes: *******************************************************************************/ char * app_specific_error(int err) { if (err < MAX_ERROR_SUPPORT && err > 0) return (char *)app_error_str[err]; else return (char *)app_error_str[DEFAULT_ERR_IDX]; } /****************************************************************************** * Function Name: salt_size * Purpose: gets the size of the salt used for passwd encryption. * In parameters: salt, input array consisting of string to search * Return value: failed if something failed, salt location otherwise * Comments/Notes: supports salt up to maximum salt for this library *******************************************************************************/ int salt_size(char *salt) { int i = 3; for (; i <= SALT_SIZE; i++) if (salt[i] == '$') { return i; } return -1; } /****************************************************************************** * Function Name: current_day_count * Purpose: day count used for password aging. * Output parameters: dcnt: day count * Comments/Notes: *******************************************************************************/ static void current_day_count(int *dcnt) { time_t date_time; /* get current time */ date_time = time(NULL); date_time = (((date_time / 60) / 60) / 24); *dcnt = (int)date_time; } /****************************************************************************** * Function Name: ocs_group_id * Purpose: check if target group name matches ocs group name * In parameters: groupname, name of target ocs group * Out parameters: g_id, Id of group * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: does array lookup on group_names *******************************************************************************/ int ocs_group_id(const char *groupname, int *g_id) { if (groupname == NULL) { log_fnc_err(FAILURE, "%s: ocs_group_id: null group name.\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } int idx = 0; for (; idx < MAX_GROUP_SUPPORT; idx++) { if (strcmp(groupname, group_names[idx]) == SUCCESS) { *g_id = ocs_group_ids[idx]; return SUCCESS; } } return UNKNOWN_ERROR; } /****************************************************************************** * Function Name: ocs_group_member * Purpose: check if user is a member of a given ocs group * In parameters: groupname, name of target ocs group * username, name of user to check * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: ocs groups do not use linux groups in tradition sense, * it just enums users with primary group id matching predefined * ocs group id *******************************************************************************/ int ocs_group_member(const char *groupname, const char *username) { if (username == NULL || groupname == NULL) { log_fnc_err(FAILURE, "%s: invalid input group or user name\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } int g_id = 0; int *group_ptr = &g_id; if (ocs_group_id(groupname, group_ptr) != 0) { log_fnc_err(FAILURE, "%s: non-ocs group group_member.\n", app_specific_error(UNSUPPORTED)); return UNSUPPORTED; } struct passwd pw; struct passwd *result; char buffer[256]; size_t length = sizeof(buffer); if (getpwnam_r(username, &pw, buffer, length, &result) == SUCCESS) { if (result != NULL) { if (pw.pw_gid == g_id) return SUCCESS; } else { log_fnc_err(FAILURE, "%s: group_member() getpwnam_r returned null.\n", app_specific_error(NULL_OBJECT)); return NULL_OBJECT; } } return FAILURE; } /****************************************************************************** * Function Name: group_members * Purpose: returns all members in a given group * In parameters: groupname, name of target group * Out parameters: length, pointer to size of output char array * members, pointer to user name char array * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int ocs_group_members(const char *groupname, const int *length, char *members) { int response = 0; if (groupname == NULL || members == NULL) { log_fnc_err(FAILURE, "%s: invalid input group name\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } int gid = 0; int *group_ptr = &gid; if (ocs_group_id(groupname, group_ptr) != 0) { log_fnc_err(FAILURE, "%s: non-ocs group group_member.\n", app_specific_error(UNSUPPORTED)); return UNSUPPORTED; } FILE *fhandle; fhandle = fopen(USER_FILE, "r"); if (!fhandle) { log_fnc_err(FAILURE, "%s: read and append open passwd failed\n", app_specific_error(FILE_IO_ERROR)); return FILE_IO_ERROR; } int idx = 0; int count = 0; struct passwd *pwd; while ((pwd = fgetpwent(fhandle))) { if (pwd->pw_gid == gid) { idx += (strlen(pwd->pw_name) + 1); if (idx > *length) { log_fnc_err(FAILURE, "%s: input members buffer too small for user list\n", app_specific_error(INPUT_BUFF_SIZE)); response = INPUT_BUFF_SIZE; break; } if (count != 0) strncat(members, ", ", sizeof(char)); strncat(members, pwd->pw_name, USERNAME_MAX_LEN); count++; } } fclose(fhandle); return response; } int ocs_change_role(const char *username, const char *groupname) { if (username == NULL || groupname == NULL) { log_fnc_err(FAILURE, "%s: invalid input group or user name\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } /* exit if not root group id */ if (getegid() != 0) { log_fnc_err(FAILURE, "%s: only admin can remove user.", app_specific_error(FUNCTION_ERR)); return FAILURE; } FILE *fhandle; int response = 0; int g_id = 0; int *group_ptr = &g_id; if (ocs_group_id(groupname, group_ptr) != 0) { log_fnc_err(FAILURE, "%s: non-ocs group group_member. \n", app_specific_error(UNSUPPORTED)); return UNSUPPORTED; } if (strcmp(username, "root") == SUCCESS) { log_fnc_err(FAILURE, "%s: root can only be admin\n", app_specific_error(INVALID_OPERATION)); return INVALID_OPERATION; } struct passwd pw; struct passwd *result; int lck_held = 0; char buffer[256]; size_t length = sizeof(buffer); if ((response = getpwnam_r(username, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { if (pw.pw_gid == g_id) { return response; } else { pw.pw_gid = g_id; /* ocs lock and hold so u_id isn't stolen by concurrent add_user */ if ((response = ocs_lock(USR_ACCNT)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to obtain ocs_lock(USR_ACCNT) error: %d", app_specific_error(FUNCTION_ERR), response); goto end_clean; } lck_held = 1; /* remove user record from passwd only */ if ((response = delete_entry(USER_FILE, username)) != 0) { /* will auto roll back on write failure */ log_fnc_err(FAILURE, "%s: unable to remove user from: %s\n", app_specific_error(response), USER_FILE); goto end_clean; } /* add updated user to passwd only */ fhandle = fopen(USER_FILE, "a+"); if (!fhandle) { log_fnc_err(FAILURE, "%s: read and append open passwd failed\n", app_specific_error(FILE_IO_ERROR)); response = FILE_IO_ERROR; goto end_clean; } if ((response = putpwent(&pw, fhandle)) != 0) { log_fnc_err(FAILURE, "%s: unable to add user to passwd: %s error %d\n", app_specific_error(FUNCTION_ERR), username, response); } fflush(fhandle); fclose(fhandle); memset(buffer, 0, sizeof(buffer)); result = NULL; if ((response = getpwnam_r(username, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { if (pw.pw_gid == g_id) { response = file_remove(USER_FILE); } else { if ((response = file_restore(USER_FILE)) == SUCCESS) { log_fnc_err(FAILURE, "%s: roll back user modification due to function error in ocs_change_role.\n", app_specific_error(FUNCTION_ERR)); response = FUNCTION_ERR; } } } else { log_fnc_err(FAILURE, "%s: null error getting second getpwnam_r in ocs_change_role.\n", app_specific_error(FUNCTION_ERR)); response = FUNCTION_ERR; } } else { log_fnc_err(FAILURE, "%s: error getting second getpwnam_r in ocs_change_role.\n", app_specific_error(FUNCTION_ERR)); response = FUNCTION_ERR; } } } else { log_fnc_err(FAILURE, "%s: null error getting getpwnam_r in ocs_change_role.\n", app_specific_error(FUNCTION_ERR)); response = FUNCTION_ERR; } } end_clean: if (lck_held > 0) if (ocs_unlock(USR_ACCNT) != SUCCESS) { log_fnc_err(FAILURE, "ocs_change_role - ocs_unlock(USR_ACCNT) failed\n"); } return response; } /****************************************************************************** * Function Name: check_root * Purpose: checks if uid is zero * Return value: FAILED user not verified as root, SUCCESS user is root * Comments/Notes: *******************************************************************************/ int check_root() { if (geteuid() == 0) return 0; else return 1; } /****************************************************************************** * Function Name: get_username_from_id * Purpose: returns user name from user id * In parameters: user_id, id of target group * lenght, size of input char array * Out parematers: username, pointer to username char array * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_username_from_id(const uid_t user_id, const size_t length, char *username) { if (username == NULL) { log_fnc_err(FAILURE, "%s: provide user name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } if (user_id == 0) { strcpy(username, "root"); return 0; } int response; struct passwd pw; struct passwd *result; char buffer[256]; size_t len = sizeof(buffer); if ((response = getpwuid_r(user_id, &pw, buffer, len, &result)) == SUCCESS) { if (result != NULL) { strncpy(username, pw.pw_name, length); return response; } else { log_fnc_err(FAILURE, "%s: getpwuid_r null object user id: %d", app_specific_error(NULL_OBJECT), user_id); return NULL_OBJECT; } } return FAILURE; } /****************************************************************************** * Function Name: get_groupname_from_id * Purpose: returns group name from group id * In parameters: group_id, id of target group * length, size of input char array * Out parameters: groupname, pointer to group name array * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_groupname_from_id(const gid_t group_id, const size_t length, char *groupname) { int idx = 0; for (; idx < MAX_GROUP_SUPPORT; idx++) { if (group_id == ocs_group_ids[idx]) { strncpy(groupname, group_names[idx], length); return SUCCESS; } } return FAILURE; } /****************************************************************************** * Function Name: get_groupid_from_name * Purpose: returns group id from group name * In parameters: username, pointer to groupname array * Out parameters: id, pointer to group id * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_groupid_from_name(const char *groupname, gid_t *id) { return ocs_group_id(groupname, (int*) id); } /****************************************************************************** * Function Name: get_current_username * Purpose: returns user name of calling process * In parameters: username, pointer to username array * length, size of username pointer * Out parameters: username, user name of calling process * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_current_username(char *username, size_t length) { uid_t user_id = geteuid(); return get_username_from_id(user_id, length, username); } /****************************************************************************** * Function Name: get_user_id * Purpose: gets user id from user name * In parameters: username, input target username * Out parameters: userid, the pw_uid for the user * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_userid_from_name(const char *username, uid_t *userid) { int response; if (username == NULL) { log_fnc_err(FAILURE, "%s: username name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } struct passwd pw; struct passwd *result; char buffer[256]; size_t length = sizeof(buffer); if ((response = getpwnam_r(username, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { *userid = pw.pw_uid; return response; } else { return NULL_OBJECT; } } else { log_fnc_err(FAILURE, "%s: getpwnam_r error: %s %d\n", app_specific_error(FUNCTION_ERR), username, response); return FUNCTION_ERR; } return FAILURE; } /****************************************************************************** * Function add_user * Purpose: adds a user to the passwd, shadow and group file. * In parameters: populated spwd structure * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int add_user(const char *username, const char *groupname, const char *password) { FILE *fhandle; int response; int lck_held = 0; /* exit if not root group id */ if (getegid() != 0) { log_fnc_err(FAILURE, "%s: only admin can remove user.", app_specific_error(FUNCTION_ERR)); return FAILURE; } if (username == NULL || password == NULL) { log_fnc_err(FAILURE, "%s: provide valid username and password\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } uid_t userid; if (get_userid_from_name(username, &userid) == SUCCESS) { log_fnc_err(FAILURE, "%s: user already exists: %s Id: %d", app_specific_error(INVALID_OPERATION), username, userid); return INVALID_OPERATION; } int name_length = 0; unsigned char letter = 0x20; char* temp_user = (char *)username; /* check user name 0-9, A-Z, a-z) */ while (*++temp_user) { letter = *temp_user; if ((letter >= 0x41 && letter <= 0x5A) || (letter >= 0x30 && letter <= 0x39) || (letter >= 0x61 && letter <= 0x7A)) { } else { log_fnc_err(FAILURE, "%s: illegal character in username\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } name_length++; } if (name_length < USERNAME_MIN_LEN || name_length > USERNAME_MAX_LEN) { log_fnc_err(FAILURE, "%s: illegal user name length: %s min length: %d max length: %d\n", app_specific_error(INVALID_PARAM), username, USERNAME_MIN_LEN, USERNAME_MAX_LEN); return INVALID_PARAM; } int groupid = -1; if ((response = ocs_group_id(groupname, &groupid)) != SUCCESS) { log_fnc_err(FAILURE, "%s: error: %d invalid group name: %s\n", app_specific_error(FUNCTION_ERR), response, groupname); return FUNCTION_ERR; } char homedir[USERNAME_MAX_LEN + 7]; snprintf(homedir, sizeof(homedir), "/home/%s", username); struct passwd pw; pw.pw_name = (char *)username; pw.pw_passwd = (char*)"x"; /*x indicates etc/shadow */ pw.pw_gid = groupid; pw.pw_gecos = "ocscli account"; pw.pw_shell = USER_SHELL; pw.pw_dir = homedir; pw.pw_uid = groupid; /* pw_uid id 0, hack to make more root users */ /* lock the pwd before getting the pid, to prevent dups*/ if ((response = ocs_lock(USR_ACCNT)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to obtain ocs_lock(USR_ACCNT) error: %d", app_specific_error(FUNCTION_ERR), response); goto end_clean; } lck_held = 1; fhandle = fopen(USER_FILE, "a+"); if (!fhandle) { log_fnc_err(FAILURE, "%s: read and append open passwd failed\n", app_specific_error(FILE_IO_ERROR)); response = FAILURE; goto end_clean; } /* if not admin, create user and group id */ if (groupid != OCS_ADMIN_ID){ struct passwd *pwd; pw.pw_uid = MIN_ID + 1; /* get avail uid */ while ((pwd = fgetpwent(fhandle))) { if ((pwd->pw_uid >= pw.pw_uid) && (pwd->pw_uid < MAX_ID)) { pw.pw_uid = ++pwd->pw_uid; } } } if ((response = putpwent(&pw, fhandle)) != SUCCESS) { log_fnc_err(FAILURE, "%s: error: %d, unable to add user to passwd: %s\n", app_specific_error(FUNCTION_ERR), response, username); } if (fflush(fhandle) != SUCCESS && fclose(fhandle) != SUCCESS) { log_fnc_err(FAILURE, "%s: error: %d, unable to flush and close passwd: %s\n", app_specific_error(FUNCTION_ERR), response, username); } /* update shadow */ if (response == SUCCESS) { struct spwd sp; memset(&sp, 0, sizeof(sp)); int daycnt = 0; current_day_count(&daycnt); /* generate a salt */ char salt[40]; char *saltptr = salt; generate_salt(saltptr); struct crypt_data data; data.initialized = 0; sp.sp_namp = pw.pw_name; sp.sp_pwdp = (char*)crypt_r((const char*)password, saltptr, &data); sp.sp_lstchg = daycnt; sp.sp_min = 0; sp.sp_max = 99999; sp.sp_warn = 7; sp.sp_inact = -1; sp.sp_expire = -1; sp.sp_flag = -1; response = shadow_append(&sp); if (response == SUCCESS) { if (mkdir(pw.pw_dir, 0755) == 0) { chown(pw.pw_dir, pw.pw_uid, pw.pw_gid); chmod(pw.pw_dir, 02755); } } } end_clean: if (lck_held > 0) if (ocs_unlock(USR_ACCNT) != SUCCESS) { log_fnc_err(FAILURE, "add_user - ocs_unlock(USR_ACCNT) failed\n"); } return response; } /****************************************************************************** * Function Name: remove_user * Purpose: removes user from passwd, shodow, group file. * In parameters: username, target user to remove * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int remove_user(const char *username) { int response = 0; int lck_held = 0; if (username == NULL) { log_fnc_err(FAILURE, "%s: username name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } if (strcmp(username, "root") == SUCCESS) { log_fnc_err(FAILURE, "%s: root cannot be removed\n", app_specific_error(INVALID_OPERATION)); return INVALID_OPERATION; } /* exit if not root group id */ if (getegid() != 0) { log_fnc_err(FAILURE, "%s: only admin can remove user.", app_specific_error(FUNCTION_ERR)); return FAILURE; } if ((response = ocs_lock(USR_ACCNT)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to obtain ocs_lock(USR_ACCNT) error: %d", app_specific_error(FUNCTION_ERR), response); goto end_clean; } lck_held = 1; uid_t userid; if (get_userid_from_name(username, &userid) != SUCCESS) { log_fnc_err(FAILURE, "%s: user does not exist: %s", app_specific_error(INVALID_OPERATION), username); response = INVALID_OPERATION; goto end_clean; } if ((response = delete_entry(USER_FILE, username)) != 0) { /* error reported in delete entry, just log info if needed */ log_info("unable to remove user from: %s\n", USER_FILE); goto end_clean; } if ((response = delete_entry(SHADOW_FILE, username)) != 0) { log_info("unable to remove user from: %s\n", SHADOW_FILE); goto end_clean; } // remove the users home directory, but don't complain if it's not there. char homedir[USERNAME_MAX_LEN + 7]; snprintf(homedir, sizeof(homedir), "/home/%s", username); remove(homedir); /* if the user doesn't exist delete the backups */ if (get_userid_from_name(username, &userid) != SUCCESS) { if ((response = file_remove(USER_FILE)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to remove backup file %s", app_specific_error(FUNCTION_ERR), USER_FILE); goto end_clean; } if ((response = file_remove(SHADOW_FILE)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to remove backup file %s", app_specific_error(FUNCTION_ERR), SHADOW_FILE); goto end_clean; } } else { log_fnc_err(FAILURE, "%s: user still exists: %s", app_specific_error(FUNCTION_ERR), username); response = FUNCTION_ERR; goto end_clean; } end_clean: if (lck_held > 0) if (ocs_unlock(USR_ACCNT) != SUCCESS) { log_fnc_err(FAILURE, "remove_user - ocs_unlock(USR_ACCNT) failed\n"); } return response; } /****************************************************************************** * Function Name: update_password * Purpose: updates user password in shadow file * In parameters: username, name of target user to update password * password, new unencrypted password * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int update_password(const char *username, const char *password) { int response = 0; int lck_held = 0; /* exit if not root group id */ if (getegid() != 0) { log_fnc_err(FAILURE, "%s: only admin can remove user.", app_specific_error(FUNCTION_ERR)); return FAILURE; } char buffer[256]; struct spwd spw; struct spwd *result; getspnam_r(username, &spw, buffer, sizeof(buffer), &result); if (!result) { log_fnc_err(FAILURE, "%s: unable to locate user pwd\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } char salt[40]; char *saltptr = salt; generate_salt(saltptr); int daycnt = 0; current_day_count(&daycnt); struct crypt_data data; data.initialized = 0; result->sp_pwdp = (char*)crypt_r((const char*)password, saltptr, &data); result->sp_lstchg = daycnt; result->sp_inact = -1; result->sp_expire = -1; /* lckpwdf isn't thread safe, using semaphore instead, and hold so uid isn't stolen by concurrent add_user */ if ((response = ocs_lock(USR_ACCNT)) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to obtain ocs_lock(USR_ACCNT) error: %d", app_specific_error(FUNCTION_ERR), response); goto end_clean; } lck_held = 1; if ((response = delete_entry(SHADOW_FILE, username)) != SUCCESS) { /* delete entry will automatically restore if write fails */ log_info("unable to remove user from: %s\n", SHADOW_FILE); goto end_clean; } response = shadow_append(result); if (response == SUCCESS) { /* verify success or restore */ if ((response = verify_authentication(username, password)) != SUCCESS) file_remove(SHADOW_FILE); else file_restore(SHADOW_FILE); } end_clean: if (lck_held > 0) if (ocs_unlock(USR_ACCNT) != SUCCESS) { log_fnc_err(FAILURE, "remove_user - ocs_unlock(USR_ACCNT) failed\n"); } return response; } /****************************************************************************** * Function Name: verify_username_permission * Purpose: returns the user primary group for permissions * In parameters: username, name of user to verify * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int verify_username_permission(const char *username, int *group_id) { int response; if (!username) { log_fnc_err(FAILURE, "%s: user name cannot be null\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } struct passwd pw; struct passwd *result; char buffer[256]; size_t length = sizeof(buffer); if ((response = getpwnam_r(username, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { /* root is ocs admin by default */ /* most uid will be admin */ if (pw.pw_uid == 0) { *group_id = OCS_ADMIN_ID; return response; } int idx = 0; for (; idx < MAX_GROUP_SUPPORT; idx++) { if (pw.pw_gid == ocs_group_ids[idx]) { *group_id = pw.pw_gid; return response; } } log_fnc_err(FAILURE, "%s: user: %s not ocs group member\n", app_specific_error(UNSUPPORTED), username); response = FAILURE; } else { log_fnc_err(FAILURE, "%s: ocs_verify_permission getpwnam_r(%s) returned null\n", app_specific_error(NULL_OBJECT), username); response = NULL_OBJECT; } } else { log_fnc_err(FAILURE, "%s: ocs_verify_permission getpwnam_r(%s) returned: %d\n", app_specific_error(FUNCTION_ERR), username, response); return response; } return response; } /****************************************************************************** * Function Name: verify_caller_permission * Purpose: returns the calling process primary group for permissions * In parameters: username, name of user to verify * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int verify_caller_permission(int *group_id) { int response; struct passwd pw; struct passwd *result; char buffer[256]; size_t length = sizeof(buffer); uid_t user_id; user_id = getuid(); if ((response = getpwuid_r(user_id, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { /* check admin by default */ if (pw.pw_uid == 0) { *group_id = OCS_ADMIN_ID; return response; } int idx = 0; for (; idx < MAX_GROUP_SUPPORT; idx++) { if (pw.pw_gid == ocs_group_ids[idx]) { *group_id = pw.pw_gid; return response; } } log_fnc_err(FAILURE, "%s: user id: %d not ocs group member\n", app_specific_error(UNSUPPORTED), user_id); response = FAILURE; } else { log_fnc_err(FAILURE, "%s: ocs_verify_permission getpwuid_r(%d) returned null\n", app_specific_error(NULL_OBJECT), user_id); response = NULL_OBJECT; } } else { log_fnc_err(FAILURE, "%s: ocs_verify_permission getpwuid_r(%d) returned: %d\n", app_specific_error(FUNCTION_ERR), user_id, response); return response; } return response; } /****************************************************************************** * Function Name: verify_authentication * Purpose: authenticates user login * In parameters: username and password to verify * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int verify_authentication(const char *username, const char *password) { char buffer[256]; struct spwd spw; struct spwd *result; /* salt size and termination */ char salt[SALT_SIZE + 1]; char *saltprt; saltprt = salt; getspnam_r(username, &spw, buffer, sizeof(buffer), &result); if (!result) { log_fnc_err(FAILURE, "%s: unable to locate user pwd\n", app_specific_error(NULL_OBJECT)); return NULL_OBJECT; } int salt_length = 0; salt_length = salt_size(result->sp_pwdp); if (salt_length < 0 || salt_length > SALT_SIZE) { salt_length = SALT_SIZE; } /* just get the salt from pw string */ strncpy(saltprt, result->sp_pwdp, salt_length); salt[salt_length] = '\0'; struct crypt_data data; data.initialized = 0; if (strcmp(crypt_r(password, saltprt, &data), result->sp_pwdp) == SUCCESS) { return SUCCESS; } return FAILURE; } /****************************************************************************** * Function Name: shadow_append * Purpose: appends an entry to the shodow file. * In parameters: populated spwd structure * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ static int shadow_append(struct spwd *sp) { int response = 0; FILE *fhandle; if (!sp) { log_fnc_err(FAILURE, "%s: password encryption failed\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } fhandle = fopen(SHADOW_FILE, "a+"); if (!fhandle) { log_fnc_err(FAILURE, "%s: unable to open shadow\n", app_specific_error(FILE_IO_ERROR)); return FILE_IO_ERROR; } if ((response = putspent(sp, fhandle)) != SUCCESS) { log_fnc_err(FAILURE, "%s: failed to add user pw to shadow: %d\n", app_specific_error(FILE_IO_ERROR), response); } fflush(fhandle); fclose(fhandle); return response; } /****************************************************************************** * Function Name: delete_entry * Purpose: Removes an entry from a file, /etc/passwd, /etc/shadow, * etc/group * In parameters: filename, name of the target file. * username, user name of line to remove/locate. * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: i don't know of another way to do this, * delete a line, read it into a buffer, remove the line * and write back. *******************************************************************************/ static int delete_entry(char *filename, const char *username) { int response = 1; long length = 0; int recovery_req = 0; int file; char *buffer; FILE *handle; handle = fopen(filename, "r"); if (!handle) { log_fnc_err(FAILURE, "%s: file open error: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } if (fseek(handle, 0L, SEEK_END) == SUCCESS) { if ((length = ftell(handle)) == -1) { log_fnc_err(FAILURE, "%s: unable to determine size of file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = -1; goto end_clean; } } if (length > 0 && length < MAX_FILE_BUFFER) buffer = (char *)malloc((length + 1) * sizeof(char)); if (!buffer) { log_fnc_err(FAILURE, "%s: unable to allocate buffer for file: %s\n", app_specific_error(INVALID_OPERATION), filename); response = INVALID_OPERATION; goto end_clean; } if (fseek(handle, 0L, SEEK_SET) != SUCCESS) { log_fnc_err(FAILURE, "%s: io error seeking file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } fread(buffer, length, sizeof(char), handle); if (ferror(handle) != 0) { log_fnc_err(FAILURE, "%s: io error reading file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } fclose(handle); // append : to name name char srchname[USERNAME_MAX_LEN + 2]; snprintf(srchname, USERNAME_MAX_LEN, "\n%s:", username); char *skip_start; char *skip_end; int start_idx, end_idx; if (strncmp(buffer, &srchname[1], strlen(srchname) - 1) == SUCCESS) skip_start = strstr(buffer, &srchname[1]); else skip_start = strstr(buffer, srchname); if (!skip_start) { log_fnc_err(FAILURE, "%s: unable to find name entry: %s\n", app_specific_error(FILE_IO_ERROR), username); response = INVALID_OPERATION; goto end_clean; } skip_start++; skip_end = strchr(skip_start, '\n'); if (!skip_end) { log_fnc_err(FAILURE, "%s: unable to find name termination: %s\n", app_specific_error(INVALID_OPERATION), username); response = INVALID_OPERATION; goto end_clean; } /* pointer subtraction to get index */ start_idx = (skip_start - buffer); end_idx = (skip_end - buffer) + 1; response = FAILURE; /* create backup file */ if ((response = file_io_op(AUTH_BACKUP, filename, length, buffer)) == SUCCESS) { file = open(filename, O_WRONLY | O_CREAT | O_TRUNC); if (file < SUCCESS) { log_fnc_err(FAILURE, "%s: io error opening file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; recovery_req = 1; goto end_clean; } if (lseek(file, 0L, SEEK_SET) == -1) { log_fnc_err(FAILURE, "%s: unable to seek to filename of file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } if (write(file, buffer, start_idx) != start_idx) { log_fnc_err(FAILURE, "%s: unable to write length to file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; recovery_req = 1; goto end_clean; } if (write(file, &buffer[end_idx], (length - end_idx)) != (length - end_idx)) { log_fnc_err(FAILURE, "%s: unable to write length to file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; recovery_req = 1; goto end_clean; } /* flag clean exit */ response = close(file); } else { log_fnc_err(FAILURE, "%s: unable to cteate backup to file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; } end_clean: if (!buffer) free(buffer); if (!handle) fclose(handle); if (file > 0) { close(file); } if (recovery_req == 1) { file_restore(filename); } return response; } /****************************************************************************** * Function Name: generate_salt * Purpose: creates the salt for password encryption. * In parameters: salt, input array which is modified by the void * Out parameters: salt, modified contents of input array * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ static void generate_salt(char *salt) { char state_buffer[RANDOM_BUFF]; struct random_data data; memset(&data, 0, sizeof(struct random_data)); int seed = (int)(getpid() + clock()); initstate_r(seed, state_buffer, RANDOM_BUFF, &data); strcpy(salt, "$6$"); /* SHA-512 */ int result; while (1) { random_r(&data, &result); strcat(salt, l64a(result)); if (strlen(salt) >= SALT_SIZE) { salt[SALT_SIZE] = '\0'; break; } } } /****************************************************************************** * Function Name: file_io_op * Purpose: performs file backup and restore operation. * In parameters: action, backup or restore original * filename, original file name * length, length of input buffer * buffer, file contents. * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int file_io_op(const auth_file_op action, const char *filename, long length, char *buffer) { struct stat sb; int response = SUCCESS; mode_t perms; int handle; char *target; if (stat(filename, &sb) != SUCCESS) { log_fnc_err(FAILURE, "%s: unable to gather file stat: %s\n", app_specific_error(INVALID_OPERATION), filename); response = INVALID_OPERATION; goto end_fnc; } perms = sb.st_mode; if (strcmp(filename, SHADOW_FILE) == SUCCESS) { if (action == AUTH_BACKUP) target = SHADOW_BAK; else target = SHADOW_FILE; } else if (strcmp(filename, USER_FILE) == SUCCESS) { if (action == AUTH_BACKUP) target = USER_BAK; else target = USER_FILE; } else { log_fnc_err(FAILURE, "%s: io error opening file: %s\n", app_specific_error(FILE_IO_ERROR), USER_BAK); response = FILE_IO_ERROR; goto end_fnc; } if (target != NULL) { handle = open(target, O_WRONLY | O_CREAT | O_TRUNC, perms); if (handle < SUCCESS) { log_fnc_err(FAILURE, "%s: io error opening file: %s\n", app_specific_error(FILE_IO_ERROR), target); response = FILE_IO_ERROR; goto end_fnc; } if (lseek(handle, 0L, SEEK_SET) == -1) { log_fnc_err(FAILURE, "%s: unable to seek to beginning of file: %s\n", app_specific_error(FILE_IO_ERROR), target); response = FILE_IO_ERROR; goto end_fnc; } if (write(handle, buffer, length) != length) { log_fnc_err(FAILURE, "%s: unable to write length to file: %s\n", app_specific_error(FILE_IO_ERROR), target); response = FILE_IO_ERROR; goto end_fnc; } } end_fnc: if (handle >= SUCCESS) { close(handle); } return response; } /****************************************************************************** * Function Name: file_remove * Purpose: removes back-up of original file. does not remove original. * In parameters: filename, original file name (not backup) * Return value: FAILURE code if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int file_remove(char *filename) { int response; char *target; int err_no = 0; if (strcmp(filename, SHADOW_FILE) == SUCCESS) { target = SHADOW_BAK; } else if (strcmp(filename, USER_FILE) == SUCCESS) { target = USER_BAK; } else { target = filename; } if (target != NULL) { /* check exists */ response = file_exists(target, &err_no); if (response == SUCCESS) { if ((response = remove(target)) != SUCCESS) { log_fnc_err(FAILURE, "%s: could not remove file: %s\n", strerror(errno), target); response = FILE_IO_ERROR; } } else { /* file does not exist */ if (err_no == ENOENT) response = SUCCESS; /* exists but access denied */ else if (err_no == EACCES) { log_fnc_err(FAILURE, "%s: access denied when removing file: %s\n", app_specific_error(INVALID_OPERATION), target); response = INVALID_OPERATION; } else { log_fnc_err(FAILURE, "%s: access(%s) to file failed\n", app_specific_error(INVALID_OPERATION), target); response = INVALID_OPERATION; } } } else { log_fnc_err(FAILURE, "%s: filename cannot be null\n", app_specific_error(INVALID_PARAM)); response = INVALID_PARAM; } return response; } /****************************************************************************** * Function Name: file_restore * Purpose: performs file restore using file_io_op * In parameters: filename, original file name * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int file_restore(char *filename) { int response = SUCCESS; long length = 0; char *buffer; FILE *handle; char *source; if (strcmp(filename, SHADOW_FILE) == SUCCESS) { source = SHADOW_BAK; } else if (strcmp(filename, USER_FILE) == SUCCESS) { source = USER_BAK; } else { log_fnc_err(FAILURE, "%s: io error opening file: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } handle = fopen(source, "r"); if (!handle) { log_fnc_err(FAILURE, "%s: file open error: %s\n", app_specific_error(FILE_IO_ERROR), source); response = FILE_IO_ERROR; goto end_clean; } if (fseek(handle, 0L, SEEK_END) == SUCCESS) { if ((length = ftell(handle)) == -1) { log_fnc_err(FAILURE, "%s: unable to determine size of file: %s\n", app_specific_error(FILE_IO_ERROR), source); response = -1; goto end_clean; } } if (length > 0 && length < MAX_FILE_BUFFER) buffer = (char *)malloc((length + 1) * sizeof(char)); if (!buffer) { log_fnc_err(FAILURE, "%s: unable to allocate buffer for file: %s\n", app_specific_error(INVALID_OPERATION), source); response = INVALID_OPERATION; goto end_clean; } if (fseek(handle, 0L, SEEK_SET) != SUCCESS) { log_fnc_err(FAILURE, "%s: io error seeking file: %s\n", app_specific_error(FILE_IO_ERROR), source); response = FILE_IO_ERROR; goto end_clean; } fread(buffer, length, sizeof(char), handle); if (ferror(handle) != 0) { log_fnc_err(FAILURE, "%s: io error reading file: %s\n", app_specific_error(FILE_IO_ERROR), source); response = FILE_IO_ERROR; goto end_clean; } fclose(handle); if (file_io_op(AUTH_RESTORE, filename, length, buffer) != SUCCESS) { log_fnc_err(FAILURE, "%s: file restore failed: %s\n", app_specific_error(FILE_IO_ERROR), filename); response = FILE_IO_ERROR; goto end_clean; } else { response = file_remove(filename); } end_clean: if (!buffer) free(buffer); if (!handle) fclose(handle); return response; } /****************************************************************************** * Function Name: file_exists * Purpose: checks if a file exists * In parameters: filename; name of file to check * out paraeters: error_code: errno on failure. * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int file_exists(const char *filename, int *error_code) { int response = access(filename, F_OK); *error_code = 0; if (response != SUCCESS) { *error_code = errno; /* file does not exist */ if (errno == ENOENT) response = SUCCESS; /* exists but access denied */ else if (errno == EACCES) { log_fnc_err(FAILURE, "%s: access denied when removing file: %s\n", app_specific_error(INVALID_OPERATION), filename); response = INVALID_OPERATION; } else { log_fnc_err(FAILURE, "%s: access(%s) to file failed\n", app_specific_error(INVALID_OPERATION), filename); response = INVALID_OPERATION; } } else { return SUCCESS; } return response; } /****************************************************************************** * Function Name: roll_back_recovery * Purpose: performs file restore of passwd and shadow file. function * only called by EOWNERDEAD on mutex. if process dies during * manipulation (write back) of passwd or shadow file, corruption * can occur. * In parameters: none * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: should not be called outside of mutex holder. designed for * mutex EOWNERDEAD *******************************************************************************/ int roll_back_recovery(void) { int response = SUCCESS; int error_code = 0; if (file_exists(SHADOW_BAK, &error_code) == SUCCESS) response = file_restore(SHADOW_FILE); if (response == SUCCESS) { if (file_exists(USER_BAK, &error_code) == SUCCESS) response = file_restore(USER_FILE); } return response; } /****************************************************************************** * Function Name: initialize * Purpose: called by constructor to set the EOWNERDEAD recovery function * In parameters: none * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ void initialize(void) { config_mutex_rec(roll_back_recovery); } /****************************************************************************** * Function Name: get_user_group_id * Purpose: returns primary group Id associated with user name * In parameters: username, char array of username. * Out parematers: group_id, primary group Id for user name. * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_user_group_id(const char *username, int *group_id) { int response; if (username == NULL) { log_fnc_err(FAILURE, "%s: username name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } struct passwd pw; struct passwd *result; char buffer[256]; size_t length = sizeof(buffer); if ((response = getpwnam_r(username, &pw, buffer, length, &result)) == SUCCESS) { if (result != NULL) { *group_id = pw.pw_gid; return response; } else { return NULL_OBJECT; } } else { log_fnc_err(FAILURE, "%s: getpwnam_r error: %s %d\n", app_specific_error(FUNCTION_ERR), username, response); return FUNCTION_ERR; } return FAILURE; } /****************************************************************************** * Function Name: get_user_group_name * Purpose: returns primary group name associated with user name * In parameters: username, char array of username. * Out parematers: groupname, primary group name for user name. * Return value: FAILED if something failed, SUCCESS otherwise * Comments/Notes: *******************************************************************************/ int get_user_group_name(const char *username, int length, char *groupname) { int response; if (username == NULL) { log_fnc_err(FAILURE, "%s: username name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } if (groupname == NULL) { log_fnc_err(FAILURE, "%s: group name parameter\n", app_specific_error(INVALID_PARAM)); return INVALID_PARAM; } if (length > MAX_GROUP_LENGTH) length = MAX_GROUP_LENGTH; struct passwd pw; struct passwd *result; char buffer[256]; size_t buf_len = sizeof(buffer); if ((response = getpwnam_r(username, &pw, buffer, buf_len, &result)) == SUCCESS) { if (result != NULL) { /* lookup the group name from the header file */ int idx = 0; for (; idx < MAX_GROUP_SUPPORT; idx++) { if (pw.pw_gid == ocs_group_ids[idx]){ strncpy(groupname, group_names[idx],length); return SUCCESS; } } return UNKNOWN_ERROR; } else { return NULL_OBJECT; } } else { log_fnc_err(FAILURE, "%s: getpwnam_r error: %s %d\n", app_specific_error(FUNCTION_ERR), username, response); return FUNCTION_ERR; } return FAILURE; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* dict_new.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: asougako <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/01/25 16:51:12 by asougako #+# #+# */ /* Updated: 2017/01/30 18:15:23 by asougako ### ########.fr */ /* */ /* ************************************************************************** */ /* ** Return a new ditionary holding paired words(char *) ** and definitions(any type). ** Format must contain flags indicating each definitions types. */ #include "./libft.h" /* ** Return the flag index. */ static int get_flag_index(char *flag) { int index; static char *flag_str[] = { "vo", "sc", "ss", "si", "sl", "sq",\ "uc", "us", "ui", "ul", "uq",\ "sd", "dd", "ld",\ "pc", "ps", "pi", "pl", "pq", "pv", ""}; index = 0; while (*flag_str[index] != '\0') { if (ft_strstr(flag_str[index], flag) != NULL) return (index); index++; } return (0); } /* ** Separate next flag in format, return it's index. */ static int get_next_flag(char *format) { char *next_perc; char *next_next_perc; char *flag; if ((next_perc = ft_strchr(format, '%')) == NULL || *(next_perc + 1) == 0) return (0); if ((next_next_perc = ft_strchr(next_perc + 1, '%')) == NULL) { flag = ft_strdup(next_perc + 1); format = ft_memset(format, '\0', 1); } else { flag = ft_strndup(next_perc + 1, next_next_perc - (next_perc + 1)); format = ft_strcpy(format, next_next_perc); } return (get_flag_index(flag)); } /* ** Create a new dict list with type field filled. */ static t_list *get_types(char *format, t_list **dict) { t_list *lst_link; t_dictionary *dict_content; char *format_cpy; int flag; format_cpy = ft_strdup(format); while ((flag = get_next_flag(format_cpy)) != 0) { if (!(dict_content = (t_dictionary*)malloc(sizeof(*dict_content)))) return (NULL); (*dict_content).word = NULL; (*dict_content).definition.uq = 0ULL; (*dict_content).type = flag; (*dict_content).next = NULL; lst_link = ft_lstnew(dict_content, sizeof(*dict_content)); ft_lstadd_tail(dict, lst_link); } ft_strdel(&format_cpy); return (*dict); } /* ** Retrieve variadics arguments with the right type. */ #define TYP (*(t_dictionary*)(*dict).content).type #define DEF (*(t_dictionary*)(*dict).content).definition #define GET_ARG(DT,SF,CT,AT) TYP == DT ? DEF.SF = (CT)va_arg(ap, AT) : 0 static void get_args(va_list ap, t_list *dict) { while (dict != NULL) { (*(t_dictionary*)(*dict).content).word = va_arg(ap, char *); GET_ARG(d_char, sc, char, int); GET_ARG(d_short, ss, short, int); GET_ARG(d_int, si, int, int); GET_ARG(d_long, sl, long, long); GET_ARG(d_long_long, sq, long long, long long); GET_ARG(d_u_char, uc, unsigned char, unsigned int); GET_ARG(d_u_short, us, unsigned short, unsigned int); GET_ARG(d_u_int, ui, unsigned int, unsigned int); GET_ARG(d_u_long, ul, unsigned long, unsigned long); GET_ARG(d_u_long_long, uq, unsigned long long, unsigned long long); GET_ARG(d_float, sd, float, double); GET_ARG(d_double, dd, double, double); GET_ARG(d_long_double, ld, long double, long double); GET_ARG(d_char_ptr, pc, char *, char *); GET_ARG(d_short_ptr, ps, short *, short *); GET_ARG(d_int_ptr, pi, int *, int *); GET_ARG(d_long_ptr, pl, long *, long *); GET_ARG(d_long_long_ptr, pq, long long *, long long *); GET_ARG(d_void_ptr, pv, void *, void *); dict = (*dict).next; } return; } t_list *ft_dict_new(char *format, ...) { t_list *dict; va_list ap; va_start(ap, format); dict = NULL; dict = get_types(format, &dict); get_args(ap, dict); va_end(ap); return (dict); }
C
// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later /* * Copyright 2013-2015 IBM Corp. */ #define BUFSZ 50 #include <stdlib.h> #include <assert.h> #include <string.h> #include <stdio.h> int test_memset(char* buf, int c, size_t s); int test_memchr(const void *ptr, int c, size_t n, void* expected); int test_memcmp(const void *ptr1, const void *ptr2, size_t n, int expected); int test_strcmp(const void *ptr1, const void *ptr2, int expected); int test_strchr(const char *s, int c, char *expected); int test_strrchr(const char *s, int c, char *expected); int test_strcasecmp(const char *s1, const char *s2, int expected); int test_strncasecmp(const char *s1, const char *s2, size_t n, int expected); int test_memmove(void *dest, const void *src, size_t n, const void *r, const void *expected, size_t expected_n); int main(void) { char *buf; char *buf2; buf = malloc(100); assert(test_memset(buf, 0x42, 100) == 0); free(buf); buf = malloc(128); assert(test_memset(buf, 0, 128) == 0); assert(test_memset(buf+1, 0, 127) == 0); free(buf); buf = malloc(1024); assert(test_memset(buf, 0, 1024) == 0); free(buf); buf = malloc(20); strncpy(buf, "Hello World!", 20); assert(test_memchr(buf, 'o', strlen(buf), buf+4)); assert(test_memchr(buf, 'a', strlen(buf), NULL)); assert(test_memcmp(buf, "Hello World!", strlen(buf), 0)); assert(test_memcmp(buf, "Hfllow World", strlen(buf), -1)); assert(test_strcmp(buf, "Hello World!", 0)); assert(test_strcmp(buf, "Hfllow World", -1)); assert(test_strchr(buf, 'H', buf)); assert(test_strchr(buf, 'e', buf+1)); assert(test_strchr(buf, 'a', NULL)); assert(test_strchr(buf, '!', buf+11)); assert(test_strrchr(buf, 'H', buf)); assert(test_strrchr(buf, 'o', buf+7)); assert(test_strrchr(buf, 'a', NULL)); assert(test_strrchr(buf, 'l', buf+9)); assert(test_strrchr(buf, '!', buf+11)); assert(test_strcasecmp(buf, "Hello World!", 0)); assert(test_strcasecmp(buf, "HELLO WORLD!", 0)); assert(test_strcasecmp(buf, "IELLO world!", -1)); assert(test_strcasecmp(buf, "HeLLo WOrlc!", 1)); assert(test_strncasecmp(buf, "Hello World!", strlen(buf), 0)); assert(test_strncasecmp(buf, "HELLO WORLD!", strlen(buf), 0)); assert(test_strncasecmp(buf, "IELLO world!", strlen(buf), -1)); assert(test_strncasecmp(buf, "HeLLo WOrlc!", strlen(buf), 1)); assert(test_strncasecmp(buf, "HeLLo WOrlc!", 0, 0)); assert(test_strncasecmp(buf, "HeLLo WOrlc!", 1, 0)); assert(test_strncasecmp(buf, "HeLLo WOrlc!", 2, 0)); assert(test_strncasecmp(buf, "HeLLp WOrlc!", 5, -1)); free(buf); buf = malloc(20); buf2 = malloc(20); strncpy(buf, "Hello", 20); strncpy(buf2, " World!", 20); assert(test_memmove(buf + 5, buf2, strlen(buf2), buf, "Hello World!", strlen("Hello World!"))); strncpy(buf, "HHello World!", 20); assert(test_memmove(buf, buf+1, strlen("Hello World!"), buf, "Hello World!", strlen("Hello World!"))); strncpy(buf, "0123456789", 20); assert(test_memmove(buf+1, buf , strlen("0123456789"), buf, "00123456789", strlen("00123456789"))); free(buf); free(buf2); return 0; }
C
#include<stdio.h> int main() { int a[5] = {1,20,3,4,5}; // This is the array of numbers int max_val = a[0]; // We store the max_value in a[0] int i; // We define the loop counter for (i = 1; i < 5; i++){ // Structure of the for loop if (max_val < a[i]){ // if max_value is less than a[i], we change the max_value so it contains a[i] max_val = a[i]; } } return max_val; }
C
#include "do_op.h" int choose_func(char *str) { if (!ft_strncmp(str, "+", 1)) return (0); if (!ft_strncmp(str, "-", 1)) return (1); if (!ft_strncmp(str, "/", 1)) return (2); if (!ft_strncmp(str, "*", 1)) return (3); if (!ft_strncmp(str, "%", 1)) return (4); else return (-1); } int main(int argc, char *argv[]) { void (*f[5])(int, int); int num_1; int num_2; int decide_opt; if (argc != 4) return (0); num_1 = ft_atoi(argv[1]); num_2 = ft_atoi(argv[3]); f[0] = func_plus; f[1] = func_minus; f[2] = func_div; f[3] = func_mult; f[4] = func_mod; decide_opt = choose_func(argv[2]); if (decide_opt < 0) { ft_putstr("0\n"); return (0); } f[decide_opt](num_1, num_2); ft_putchar('\n'); return (0); }
C
/* Internet Programming 2015/2016 * * Assignment 1 * Authors: Baris Can Vural, Floris Turkenburg * VUNetID: bvl250, ftg600 */ #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/types.h> #include <pthread.h> pthread_mutex_t mutex; void display(char *str) { char *tmp; for (tmp = str; *tmp; tmp++) { write(1, tmp, 1); usleep(100); } } void *thread_function(void *param) { int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); display("Bonjour monde\n"); pthread_mutex_unlock(&mutex); } } int main() { pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutex_init(&mutex, &mutex_attr); pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&thread, &attr, thread_function, NULL); int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); display("Hello world\n"); pthread_mutex_unlock(&mutex); } pthread_join(thread, NULL); pthread_mutex_destroy(&mutex); return 0; }
C
/* Names: Tyler Andrews, Brennan Campbell, and Tyler Tetens * Title: Experiment #4 - Fat File System */ #include "AT89C51RC2.h" #include <stdio.h> #include "main.h" #include "PORT.H" #include "UART.h" #include "SPI.h" #include "SDCard.h" #include "print_bytes.h" #include "Directory_Functions_struct.h" #include "Read_Sector.h" #include "print_bytes.h" #include "Long_Serial_In.h" #include <string.h> FS_values_t idata Drive_values; /*********************************************************************** DESC: Returns a pointer to the global structure Drive_values to export to other files INPUT: void RETURNS: Pointer to the structure Drive_values CAUTION: ************************************************************************/ FS_values_t * Export_Drive_values(void) { return &Drive_values; } uint8_t read8(uint16_t offset, uint8_t * array_name) { uint8_t return_value; return_value = array_name[offset]; return return_value; } uint16_t read16(uint16_t offset, uint8_t * array_name) { uint32_t return_value; uint8_t temp, index; return_value=0; // little endian to big endian // loop for 2 bytes for(index=0;index<2;index++) { temp=*(array_name+offset+(1-index)); return_value=return_value<<8; return_value|=temp; } return return_value; } uint32_t read32(uint16_t offset, uint8_t * array_name) { uint32_t return_value; uint8_t temp, index; return_value=0; // little endian to big endian // loop for 4 bytes for(index=0;index<4;index++) { temp=*(array_name+offset+(3-index)); return_value=return_value<<8; return_value|=temp; } return return_value; } /*********************************************************************** DESC: Prints all short file name entries for a given directory INPUT: Starting Sector of the directory and the pointer to a block of memory in xdata that can be used to read blocks from the SD card RETURNS: uint16_t number of entries found in the directory CAUTION: Supports FAT16, SD_shift must be set before using this function ************************************************************************/ uint16_t Print_Directory(uint32_t Sector_num, uint8_t xdata * array_in) { uint32_t Sector, max_sectors; uint16_t i, entries; uint8_t temp8, j, attr, out_val, error_flag; uint8_t * values; values=array_in; entries=0; i=0; if (Drive_values.FATtype==FAT16) // included for FAT16 compatibility { max_sectors=Drive_values.RootDirSecs; // maximum sectors in a FAT16 root directory } else { max_sectors=Drive_values.SecPerClus; } Sector=Sector_num; error_flag=Read_Sector(Sector, Drive_values.BytesPerSec, values); if(error_flag==no_errors) { do { temp8=read8(0+i,values); // read first byte to see if empty if((temp8!=0xE5)&&(temp8!=0x00)) { attr=read8(0x0b+i,values); if((attr&0x0E)==0) // if hidden, system or Vol_ID bit is set do not print { entries++; printf("%5d. ",entries); // print entry number with a fixed width specifier for(j=0;j<8;j++) { out_val=read8(i+j,values); // print the 8 byte name putchar(out_val); } if((attr&0x10)==0x10) // indicates directory { for(j=8;j<11;j++) { out_val=read8(i+j,values); putchar(out_val); } printf("[DIR]\n"); } else // print a period and the three byte extension for a file { putchar(0x2E); for(j=8;j<11;j++) { out_val=read8(i+j,values); putchar(out_val); } putchar(0x0d); putchar(0x0a); } } } i=i+32; // next entry if(i>510) { Sector++; if((Sector-Sector_num)<max_sectors) { error_flag=Read_Sector(Sector,Drive_values.BytesPerSec,values); if(error_flag!=no_errors) { entries=0; // no entries found indicates disk read error temp8=0; // forces a function exit } i=0; } else { entries=entries|more_entries; // set msb to indicate more entries in another cluster temp8=0; // forces a function exit } } }while(temp8!=0); } else { printf("Error has occured"); entries=0; // no entries found indicates disk read error } return entries; } /*********************************************************************** DESC: Uses the same method as Print_Directory to locate short file names, but locates a specified entry and returns and cluster INPUT: Starting Sector of the directory, an entry number and a pointer to a block of memory in xdata that can be used to read blocks from the SD card RETURNS: uint32_t with cluster in lower 28 bits. Bit 28 set if this is a directory entry, clear for a file. Bit 31 set for error. CAUTION: ************************************************************************/ uint32_t Read_Dir_Entry(uint32_t Sector_num, uint16_t Entry, uint8_t xdata * array_in) { uint32_t Sector, max_sectors, return_clus; uint16_t i, entries; uint8_t temp8, attr, error_flag; uint8_t * values; values=array_in; entries=0; i=0; return_clus=0; if (Drive_values.FATtype==FAT16) // included for FAT16 compatibility { max_sectors=Drive_values.RootDirSecs; // maximum sectors in a FAT16 root directory } else { max_sectors=Drive_values.SecPerClus; } Sector=Sector_num; error_flag=Read_Sector(Sector,Drive_values.BytesPerSec,values); if(error_flag==no_errors) { do { temp8=read8(0+i,values); // read first byte to see if empty if((temp8!=0xE5)&&(temp8!=0x00)) { attr=read8(0x0b+i,values); if((attr&0x0E)==0) // if hidden do not print { entries++; if(entries==Entry) { if(Drive_values.FATtype==FAT32) { return_clus=read8(21+i,values); return_clus=return_clus<<8; return_clus|=read8(20+i,values); return_clus=return_clus<<8; } return_clus|=read8(27+i,values); return_clus=return_clus<<8; return_clus|=read8(26+i,values); attr=read8(0x0b+i,values); if(attr&0x10) return_clus|=directory_bit; temp8=0; // forces a function exit } } } i=i+32; // next entry if(i>510) { Sector++; if((Sector-Sector_num)<max_sectors) { error_flag=Read_Sector(Sector,Drive_values.BytesPerSec,values); if(error_flag!=no_errors) { return_clus=no_entry_found; temp8=0; } i=0; } else { temp8=0; // forces a function exit } } }while(temp8!=0); } else { return_clus=no_entry_found; } if(return_clus==0) return_clus=no_entry_found; return return_clus; } uint8_t Mount_Drive(uint8_t xdata * array_name) { uint8_t temp_8; uint8_t error_flag; // Below are constants from BPB used for calculations // for the values in struct FS_values_t uint16_t RsvdSectorCount; uint8_t NumFATS; uint16_t RootEntryCnt; uint16_t TotalSectors16; uint16_t FATsz16; uint32_t TotalSectors32; uint32_t FATsz32; uint32_t FATSz; //Ran out of space so now some vars are in xdata uint32_t xdata TotSec; uint32_t xdata DataSec; uint32_t RootCluster; uint32_t RelativeSectors; uint32_t CountofClus; // Read in BPB or MBR error_flag = Read_Sector(0, 512, array_name); // Check for BPB or MBR temp_8 = read8(0,array_name); if((temp_8!=0xEB)&&(temp_8!=0xE9)) { RelativeSectors = read32(0x01C6,array_name); error_flag = Read_Sector(RelativeSectors ,512,array_name); temp_8 = read8(0,array_name); if((temp_8!=0xEB)&&(temp_8!=0xE9)) { printf("Error BPB not Found!\r\n"); } else { printf("BPB Found!\r\n"); } } // All the BPB calculations are below Drive_values.BytesPerSec = read16(0x0B,array_name); Drive_values.SecPerClus = read8(0x0D,array_name); RsvdSectorCount = read16(0x0E,array_name); NumFATS = read8(0x10,array_name); RootEntryCnt = read16(0x11,array_name); TotalSectors16 = read16(0x13,array_name); FATsz16 = read16(0x16,array_name); TotalSectors32 = read32(0x20,array_name); FATsz32 = read32(0x24,array_name); RootCluster = read32(0x2C, array_name); Drive_values.StartofFAT = RsvdSectorCount + RelativeSectors; Drive_values.RootDirSecs = ((RootEntryCnt*32) + (Drive_values.BytesPerSec-1))/Drive_values.BytesPerSec; Drive_values.FirstDataSec = RsvdSectorCount + (NumFATS*FATsz32) + Drive_values.RootDirSecs + RelativeSectors; Drive_values.FirstRootDirSec = ((RootCluster-2)*Drive_values.SecPerClus)+Drive_values.FirstDataSec; Drive_values.FATshift = FAT32_shift; //Checks FAT Size to use if(FATsz16 != 0) { FATSz = FATsz16; } else { FATSz = FATsz32; } //Checks which TotalSectors to use if(TotalSectors16 != 0) { TotSec = TotalSectors16; } else { TotSec = TotalSectors32; } //Calculates Number of Data Sectors for CountofClus DataSec = (TotSec - (RsvdSectorCount + ((NumFATS * FATSz) + Drive_values.RootDirSecs))); //Calculates CountofClus to use for determining FATtype CountofClus = DataSec / Drive_values.SecPerClus; //Determines FAT type if(CountofClus < 65525) { //FAT16 Drive_values.FATtype = FAT16; error_flag = FAT_Unsupported; } else { //FAT32 Drive_values.FATtype = FAT32; } return error_flag; } uint32_t First_Sector (uint32_t Cluster_num) { uint32_t FirstSecCluster; if(Cluster_num==0) { FirstSecCluster = Drive_values.FirstRootDirSec; } else { FirstSecCluster = ((Cluster_num-2)*Drive_values.SecPerClus)+Drive_values.FirstDataSec; } return FirstSecCluster; } uint32_t Find_Next_Clus(uint32_t Cluster_num, uint8_t xdata * array_name) { uint32_t return_clus; uint16_t FAToffset; uint32_t sector = ((Cluster_num*4)/Drive_values.BytesPerSec)+Drive_values.StartofFAT; Read_Sector(sector,Drive_values.BytesPerSec,array_name); FAToffset = (uint16_t) ((4*Cluster_num)%Drive_values.BytesPerSec); return_clus = (read32(FAToffset,array_name)&0x0FFFFFFF); return return_clus; } uint8_t Open_File(uint32_t Cluster, uint8_t xdata * array_in) { uint8_t error_flag = no_errors; uint32_t sector_num; uint32_t first_sec_num; do { first_sec_num = First_Sector(Cluster); sector_num = first_sec_num; while(sector_num!=Drive_values.SecPerClus+first_sec_num) { error_flag = Read_Sector(sector_num,Drive_values.BytesPerSec, array_in); sector_num++; } Cluster = Find_Next_Clus(Cluster,array_in); }while(Cluster!=0x0FFFFFFF); return error_flag; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> typedef struct dado { char categoria[200]; char inicio[11]; char fim[11]; int Km; int id; char placa[8]; char modelo[100]; char fabricante[200]; char disp[2]; int ocp; char ar[2]; }dados; void zera_id(dados carro[]){ int i; for(i=0; i<900; i++){ carro[i].id=0; } } int list(dados carro[]){ int i; for(i=0; i<900; i++){ if(carro[i].id == 0){ return i; } } } int Busca_id(int idr, dados carro[]){ int i; for(i=0; i<900; i++){ if(carro[i].id == idr){ return i; } } } int Busca_id_igual(int idr, dados carro[]){ int i, count=0; for(i=0; i<900; i++){ if(carro[i].id == idr){ count++; } } if(count>=2){ return idr; } else return -1; } void Inserir(struct dado carro[] ){ int a, b; dados car; a=list(carro); do{ puts("Insira o id do carro\n"); scanf("%d", &carro[a].id); b=Busca_id_igual(carro[a].id, carro); if(carro[a].id == carro[b].id){ puts("carros com ids iguais por favor digite outro\n"); } }while(carro[a].id == carro[b].id); puts("Insira a placa do carro\n"); scanf("%s", carro[a].placa); fflush(stdin); puts("Insira o fabricante do carro\n"); scanf("%s", carro[a].fabricante); fflush(stdin); puts("Insira o modelo do carro\n"); scanf("%s", carro[a].modelo); fflush(stdin); puts("O carro esta disponivel?(s/n)\n"); scanf("%s", carro[a].disp); fflush(stdin); puts("Insira a categoria do carro\n"); scanf("%s", carro[a].categoria); fflush(stdin); puts("Insira o numero de passageiros comportados\n"); scanf("%d", &carro[a].ocp); fflush(stdin); puts("O carro possui ar condicionado? (s/n)"); scanf("%s", carro[a].ar); fflush(stdin); puts("Insira a quilometragem do carro\n"); scanf("%d", &carro[a].Km); fflush(stdin); if(strcmp(carro[a].disp, "S") == 1){ strcpy(carro[a].inicio,"0/0/0"); strcpy(carro[a].fim,"0/0/0"); }else{ puts("Insira a data de incio da reserva(dd/mm/aa)\n"); scanf("%s", carro[a].inicio); puts("Insira a data do termino da reserva(dd/mm/aa)\n"); scanf("%s", carro[a].fim); } } void Remover(dados carro[]){ int idr, a, b, i; puts("Insira o id do carro a ser removido"); scanf("%d", &idr); a=Busca_id(idr, carro); b=list(carro); for(i=a; i<b; i++){ strcpy(carro[i].fabricante,carro[i+1].fabricante ); carro[i].id = carro[i+1].id; strcpy(carro[i].categoria, carro[i+1].categoria ); carro[i].Km = carro[i+1].Km; strcpy(carro[i].fim, carro[i+1].fim ); strcpy(carro[i].inicio, carro[i+1].inicio ); } puts("\n"); } void Listar_tds(dados carro[]){ int i, a; a=list(carro); for(i=0; i<a; i++){ printf(" Id = %d \n Placa: %d \n Fabricante : %s \n Modelo : %s \n Disponibilidade : %s \n Categoria = %s \n Capacidade : %d \n Ar Condicionado : %s \n Quilometragem = %d \n Reserva\n Inicio = %s Fim = %s", carro[i].id, carro[i].placa, carro[i].fabricante, carro[i].modelo, carro[i].disp, carro[i].categoria, carro[i].ocp, carro[i].ar, carro[i].Km, carro[i].inicio, carro[i].fim); puts("\n"); } getchar(); } void Listar_disp(dados carro[]){ int i, a; a=list(carro); for(i=0; i<a; i++){ if(strcmp(carro[i].disp, "N") == 1){ printf(" Id = %d \n Placa: %d \n Fabricante : %s \n Modelo : %s \n Disponibilidade : %s \n Categoria = %s \n Capacidade : %d \n Ar Condicionado : %s \n Quilometragem = %d \n", carro[i].id, carro[i].placa, carro[i].fabricante, carro[i].modelo, carro[i].disp, carro[i].categoria, carro[i].ocp, carro[i].ar, carro[i].Km); puts("\n"); } } getchar(); } void Listar_cat(dados carro[]){ char cat[30]; int i, a; a=list(carro); puts("Insira a categoria dos veculos a serem listados\n"); scanf("%s", cat); for(i=0; i<a; i++){ if(strcmp(carro[i].categoria, cat) == 0){ printf(" Id = %d \n Placa: %d \n Fabricante : %s \n Modelo : %s \n Disponibilidade : %s \n Categoria = %s \n Capacidade : %d \n Ar Condicionado : %s \n Quilometragem = %d \n Reserva\n Inicio = %s Fim = %s", carro[i].id, carro[i].placa, carro[i].fabricante, carro[i].modelo, carro[i].disp, carro[i].categoria, carro[i].ocp, carro[i].ar, carro[i].Km, carro[i].inicio, carro[i].fim); puts("\n"); if(strcmp(carro[i].disp, "S") == 1){ printf("Reserva:\n\n Incio : %s | Fim : %s", carro[i].inicio, carro[i].fim); } } } getchar(); } int Ver(dados carro[]){ int idr, a; puts("Insira o id do carro a ser verificado\n"); scanf("%d", &idr); a=Busca_id(idr, carro); if(strcmp(carro[a].disp, "S") == 1){ puts("o carro no esta reservado\n"); }else{ printf(" incio : %s \n termino : %s", carro[a].inicio, carro[a].fim); } getchar(); } void Reservar(dados carro[]){ int idr, a; puts("Insira o id do carro a ser reservado\n"); scanf("%d", &idr); a=Busca_id(idr, carro); if(strcmp(carro[a].disp, "S") == 1){ puts("o carro j esta reservado"); }else{ puts("Insira a data de incio da reserva(dd/mm/aa)\n"); scanf("%s", carro[a].inicio); puts("Insira a data do termino da reserva(dd/mm/aa)\n"); scanf("%s", carro[a].fim); strcpy(carro[a].disp, "N"); } } void Liberar(dados carro[]){ int idr, a; puts("Insira o id do carro a ser retirado a reserva\n"); scanf("%d", &idr); a=Busca_id(idr, carro); strcpy(carro[a].inicio,"0/0/0"); strcpy(carro[a].fim,"0/0/0"); strcpy(carro[a].disp, "N"); } void Ler_arq(dados carro[]){ int i=0; FILE *arq; arq = fopen("listacarros.dat", "r"); while(!feof(arq)){ fscanf(arq, "%d %s %s %s \n", &carro[i].id, carro[i].placa, carro[i].fabricante, carro[i].modelo ); fscanf(arq,"%s %s %d %s \n", &carro[i].disp, carro[i].categoria, &carro[i].ocp, carro[i].ar); fscanf(arq, "%d \n", &carro[i].Km); fscanf(arq,"%s %s \n", carro[i].inicio, carro[i].fim); i++; } fclose(arq); } void Escrever_arq(dados carro[]){ int i, a; FILE *arq; arq = fopen("listacarros.dat", "w"); a=list(carro); for(i=0;i<a;i++){ fprintf(arq, "%d %s %s %s \n", carro[i].id, carro[i].placa, carro[i].fabricante, carro[i].modelo ); fprintf(arq,"%s %s %d %s \n", carro[i].disp, carro[i].categoria, carro[i].ocp, carro[i].ar); fprintf(arq, "%d \n", carro[i].Km); fprintf(arq,"%s %s \n", carro[i].inicio, carro[i].fim); } fclose(arq); } int main(){ dados carro[900]; zera_id(carro); setlocale(LC_ALL,""); int op, T=1; Ler_arq(carro); do{ getchar(); puts("Locadora de carros\n\n"); puts("1 -- Iserir novo veiculo no sistema\n"); puts("2 -- Remover veculo do sistema\n"); puts("3 -- Listar todos os veculos\n"); puts("4 -- Listar veculos disponiveis\n"); puts("5 -- Listar veculos por categoria\n"); puts("6 -- Verifica a devoluo de um veculo\n"); puts("7 -- Reserva de um veculo\n"); puts("8 -- Liberar a reserva de um veculo\n"); puts("9 -- Fechar aplicao\n"); puts("Digite a opo desejada\n "); scanf("%d", &op); switch(op){ case 1 : 1 ;{ Inserir(carro); break; } case 2 : 2;{ Remover(carro); break; } case 3 : 3;{ Listar_tds(carro); break; } case 4 : 4;{ Listar_disp(carro); break; } case 5 : 5;{ Listar_cat(carro); break; } case 6 : 6;{ Ver(carro); break; } case 7 : 7;{ Reservar(carro); break; } case 8 : 8;{ Liberar(carro); break; } case 9 : 9;{ T = 0; break; } default : puts("Entrada invalida"); break; } }while(T != 0); Escrever_arq(carro); }
C
#include "holberton.h" /** * rev_string - invert the order of character of a string * @s: string to change */ void rev_string(char *s) { int a, b; char inicio, fin; a = 0; b = 0; while (s[a] != '\0') { ++a; } for (a = (a - 1) ; a >= b ; a--) { fin = s[a]; inicio = s[b]; s[b] = fin; s[a] = inicio; b++; } }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #define NAME_SIZE 80 int main() { FILE *fp; char fname[NAME_SIZE]; char ch; printf("enter the file name: "); if (scanf("%s", fname) == 0) { printf("no filename entered, process exit!\n"); exit(EXIT_FAILURE); } if ((fp = fopen(fname, "r+")) == NULL) { printf("can't open the file %s\n", fname); exit(EXIT_FAILURE); } while((ch = getc(fp)) != EOF) { if (islower(ch)) { fseek(fp, -1, SEEK_CUR); ch = (char)toupper(ch); putc(ch, fp); } } printf("Done!\n"); return 0; }
C
struct ListNode{ int val; struct ListNode* next; }; /*recur: top->down*/ // struct ListNode* merge(struct ListNode* left, struct ListNode* right){ // struct ListNode dummy = {-1, NULL}; // struct ListNode* tail = &dummy; // while(left && right){ // //insert the smaller val // if(left->val > right->val){ // //insert at tail // tail->next = right; // right = right->next; // tail = tail->next; // } // else{ // tail->next = left; // left = left->next; // tail = tail->next; // } // } // tail->next = left ? left : right; // return dummy.next; // } // struct ListNode* sortList(struct ListNode* head) { // if(!head || !head->next) return head; // struct ListNode* slow = head, *fast = head->next; // struct ListNode* mid = NULL; // while(fast && fast->next){ // slow = slow->next; // fast = fast->next->next; // } // mid = slow->next; /*the right part head*/ // slow->next = NULL; /*cut*/ // return merge(sortList(head), sortList(mid)); // } /*iterative: bottom->up*/ typedef struct{ struct ListNode* head; struct ListNode* tail; }Pair; struct ListNode* split(struct ListNode* head, int n){ while(--n && head) head = head->next; struct ListNode* rest = head ? head->next : NULL; if(head) head->next = NULL; return rest; } Pair merge(struct ListNode* left, struct ListNode* right){ struct ListNode dummy = {-1, NULL}; struct ListNode* tail = &dummy; while(left && right){ if(left->val > right->val){ tail->next = right; right = right->next; tail = tail->next; } else{ tail->next = left; left = left->next; tail = tail->next; } } tail->next = left ? left : right; while(tail->next) tail = tail->next; Pair pair = {dummy.next, tail}; return pair; } struct ListNode* sortList(struct ListNode* head) { if(!head || !head->next) return head; int len = 1; struct ListNode* cur = head; while(cur = cur->next) len++; struct ListNode dummy = {-1, head}; struct ListNode* l, *r, *tail; for (int n = 1; n < len; n <<= 1){ cur = dummy.next; tail = &dummy; while(cur){ l = cur; r = split(l, n); cur = split(r, n); Pair merged = merge(l, r); tail->next = merged.head; tail = merged.tail; } } return dummy.next; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "hash_map.h" enum { ITEM_EMPTY = 0, ITEM_DELETE, ITEM_USED, }; struct hash_item { uint64_t hash_code; int8_t flag; int8_t key_and_val[0]; }; struct hash_map { hash_func _hash_function; hash_key_eq _key_cmp_function; hash_on_remove _on_remove; uint32_t slot_size; uint32_t size; uint32_t key_size; uint32_t val_size; uint32_t item_size; uint32_t expand_size; struct hash_item *_items; }; #define GET_KEY(HASH_MAP,ITEM) ((void*)(ITEM)->key_and_val) #define GET_VAL(HASH_MAP,ITEM) ((void*)&(ITEM)->key_and_val[(HASH_MAP)->key_size]) #define GET_ITEM(ITEMS,ITEM_SIZE,SLOT) ((struct hash_item*)&((int8_t*)(ITEMS))[ITEM_SIZE*SLOT]) #define HASH_MAP_INDEX(HASH_CODE,SLOT_SIZE) (HASH_CODE % SLOT_SIZE) hash_map_t hash_map_create(uint32_t slot_size,uint32_t key_size, uint32_t val_size,hash_func hash_function,hash_key_eq key_cmp_function, hash_on_remove _hash_on_remove) { hash_map_t h = (hash_map_t)malloc(sizeof(*h)); if(!h) return 0; h->slot_size = slot_size; h->size = 0; h->_hash_function = hash_function; h->_key_cmp_function = key_cmp_function; h->_on_remove = _hash_on_remove; h->key_size = key_size; h->val_size = val_size; h->item_size = sizeof(struct hash_item) + key_size + val_size; h->_items = calloc(slot_size,h->item_size); h->expand_size = h->slot_size - h->slot_size/4; if(!h->_items) { free(h); return 0; } return h; } void hash_map_destroy(hash_map_t *h) { uint32_t i = 0; struct hash_item *item; if((*h)->_on_remove) { for( ; i < (*h)->slot_size; ++i) { item = GET_ITEM((*h)->_items,(*h)->item_size,i); if(item->flag == ITEM_USED) (*h)->_on_remove(GET_KEY(*h,item),GET_VAL(*h,item)); } } free((*h)->_items); free(*h); *h = 0; } static int32_t _hash_map_insert(hash_map_t h,void* key,void* val,uint64_t hash_code) { uint32_t slot = HASH_MAP_INDEX(hash_code,h->slot_size); uint32_t check_count = 0; struct hash_item *item = 0; while(check_count < h->slot_size) { item = GET_ITEM(h->_items,h->item_size,slot); if(item->flag != ITEM_USED) { //ҵλ item->flag = ITEM_USED; memcpy(item->key_and_val,key,h->key_size); memcpy(&(item->key_and_val[h->key_size]),val,h->val_size); item->hash_code = hash_code; //printf("check_count:%d\n",check_count); return 0; } else if(hash_code == item->hash_code && h->_key_cmp_function(key,GET_KEY(h,item)) == 0) break;//Ѿڱд slot = (slot + 1)%h->slot_size; check_count++; } //ʧ return -1; } static int32_t _hash_map_expand(hash_map_t h) { uint32_t old_slot_size = h->slot_size; struct hash_item *old_items = h->_items; uint32_t i = 0; h->slot_size <<= 1; h->_items = calloc(h->slot_size,h->item_size); if(!h->_items) { h->_items = old_items; h->slot_size >>= 1; return -1; } for(; i < old_slot_size; ++i) { struct hash_item *_item = GET_ITEM(old_items,h->item_size,i); if(_item->flag == ITEM_USED) _hash_map_insert(h,GET_KEY(h,_item),GET_VAL(h,_item),_item->hash_code); } h->expand_size = h->slot_size - h->slot_size/4; free(old_items); return 0; } int32_t hash_map_insert(hash_map_t h,void *key,void *val) { uint64_t hash_code = h->_hash_function(key); if(h->slot_size < 0x80000000 && h->size >= h->expand_size) //ռʹó3/4չ _hash_map_expand(h); if(h->size >= h->slot_size) return -1; if(_hash_map_insert(h,key,val,hash_code) == 0) { ++h->size; return 0; } return -1; } static struct hash_item *_hash_map_find(hash_map_t h,void *key) { uint64_t hash_code = h->_hash_function(key); uint32_t slot = HASH_MAP_INDEX(hash_code,h->slot_size); uint32_t check_count = 0; struct hash_item *item = 0; while(check_count < h->slot_size) { item = GET_ITEM(h->_items,h->item_size,slot); if(item->flag == ITEM_EMPTY) return 0; if(item->hash_code == hash_code && h->_key_cmp_function(key,GET_KEY(h,item)) == 0) { if(item->flag == ITEM_DELETE) return 0; else return item; } slot = (slot + 1)%h->slot_size; check_count++; } return 0; } hash_map_iter hash_map_find(hash_map_t h,void* key) { struct hash_item *item = _hash_map_find(h,key); hash_map_iter iter = {0,0}; if(item) { iter.data1 = h; iter.data2 = item; } return iter; } int32_t hash_map_remove(hash_map_t h,void* key) { struct hash_item *item = _hash_map_find(h,key); if(item) { item->flag = ITEM_DELETE; --h->size; if(h->_on_remove) h->_on_remove(GET_KEY(h,item),GET_VAL(h,item)); return 0; } return -1; } int32_t hash_map_erase(hash_map_t h,hash_map_iter iter) { if(iter.data1 && iter.data2) { hash_map_t h = (hash_map_t)iter.data1; struct hash_item *item = (struct hash_item *)iter.data2; if(h->_on_remove) h->_on_remove(GET_KEY(h,item),GET_VAL(h,item)); item->flag = ITEM_DELETE; --h->size; return 0; } return -1; } int32_t hash_map_is_vaild_iter(hash_map_iter iter) { return iter.data1 && iter.data2; } void* hash_map_iter_get_val(hash_map_iter iter) { hash_map_t h = (hash_map_t)iter.data1; struct hash_item *item = (struct hash_item *)iter.data2; return GET_VAL(h,item); } void hash_map_iter_set_val(hash_map_iter iter,void *data) { hash_map_t h = (hash_map_t)iter.data1; struct hash_item *item = (struct hash_item *)iter.data2; void *old_val = GET_VAL(h,item); if(data != old_val) { void *ptr = (void*)&((item)->key_and_val[(h)->key_size]); memcpy(ptr,data,h->val_size); } }
C
#include <stdlib.h> #include <stdio.h> typedef struct LISTA{ struct LISTA *prox; struct LISTA *ante; int L; }LISTA; void insereFim(LISTA* *list, int tamanho); void trocaVagao(LISTA* *list, int tamanho); void iniciaLista(LISTA* *list); int main(void){ LISTA* list; int N, i; scanf("%d", &N); for(i = 0;i < N; i ++){ iniciaLista(&list); int tamanho, j; scanf("%d",&tamanho); if(tamanho >= 0 && tamanho <=50){ for(j = 0; j < tamanho; j++){ insereFim(&list, tamanho); } trocaVagao(&list, tamanho); } } } void iniciaLista(LISTA* *list){ *list = NULL; } void insereFim(LISTA* *list, int tamanho){ LISTA* no = (LISTA*)malloc(sizeof(LISTA)); int aux; scanf("%d",&aux); if(aux >= 1 && aux <= tamanho){ no->L = aux; if(*list==NULL){ *list = no; no->prox=no; no->ante=no; } else{ no->prox = *list; no->ante = (*list)->ante; (*list)->ante->prox=no; (*list)->ante = no; } } } void trocaVagao(LISTA* *list, int tamanho){ LISTA* p = *list; LISTA* q; int cont=0; while(p->prox != *list){ q = p->prox; do{ if(p->L > q->L){ int aux; aux = p->L; p->L = q->L; q->L = aux; cont++; } q = q->prox; }while(q!= *list); p = p->prox; } printf("Optimal train swapping takes %d swaps.\n",cont); }
C
#include <stdio.h> void power2(int number, int power); int main(void) { printf("sizeof(unsigned int) = %d bits\n", sizeof(unsigned int) * 8); printf("sizeof(int) = %d\n", sizeof(int) * 8); puts(""); power2(2, 0); power2(2, 1); power2(2, 2); power2(2, 3); power2(2, 4); } void power2(int number, int power) { unsigned int value = number << power; unsigned int mask = 1 << 31; printf("%10u = ", value); for (unsigned int c = 1; c <= 32; ++c) { putchar(value & mask ? '1' : '0'); value <<= 1; if (c % 8 == 0) { putchar(' '); } } printf("%d * 2^%d = %d\n", number, power, number << power); }
C
/* * NAME * mallocWarn * reallocWarn * * AUTHOR * I. Henson */ #include "config.h" #include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include "libstring.h" #include "logErrorMsg.h" /** * @private */ void * mallocWarn(int nbytes) { void *ptr; if(nbytes <= 0) { return (void *)NULL; } else if((ptr = malloc(nbytes)) == (void *)0) { char error[200]; if(errno > 0) { snprintf(error, 200, "malloc error: %s", strerror(errno)); } else { snprintf(error, 200, "malloc error on %d bytes", nbytes); } logErrorMsg(LOG_ERR, error); return (void *)NULL; } return ptr; } /** * @private */ void * reallocWarn(void *ptr, int nbytes) { if(nbytes <= 0) { return ptr; } else if(ptr == (void *)NULL) { return(mallocWarn(nbytes)); } else if((ptr = realloc(ptr, nbytes)) == (void *)0) { char error[200]; if(errno > 0) { snprintf(error, 200, "malloc error: %s", strerror(errno)); } else { snprintf(error, 200, "malloc error on %d bytes", nbytes); } logErrorMsg(LOG_ERR, error); return (void *)NULL; } return ptr; }
C
/* * datasize.c -- print the size of common data items * This runs with any Linux kernel (not any Unix, because of <linux/types.h>) * * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet * Copyright (C) 2001 O'Reilly & Associates * * The source code in this file can be freely used, adapted, * and redistributed in source or binary form, so long as an * acknowledgment appears in derived source files. The citation * should list that the code comes from the book "Linux Device * Drivers" by Alessandro Rubini and Jonathan Corbet, published * by O'Reilly & Associates. No warranty is attached; * we cannot take responsibility for errors or fitness for use. */ #include <stdio.h> #include <sys/utsname.h> // #include <linux/types.h> int main(int argc, char **argv) { struct utsname name; uname(&name); /* never fails :) */ printf("a=%s -\n",name.sysname); printf("a=%s-\n",name.nodename); printf("a=%s-\n",name.release); printf("a=%s-\n",name.version); printf("a=%s-\n",name.machine); return 0; }
C
#include <stdio.h> #include <stdlib.h> int whileloop(int x); int dowhileloop(int x); int forloop(int x); int main(void) { int x=5; whileloop(x); printf("-------\n"); dowhileloop(x); printf("-------\n"); forloop(x); return 0; } int whileloop(int x) { int y; while(y<x) { y++; printf("%i\n",y); } } int dowhileloop(int x) { int y=0; do { y++; printf("%i\n",y); } while(y<x); } int forloop(int x) { int y; for(y=0;y<=x;++y) { printf("%i\n",y); } }
C
/** * @brief Add a new colorselector to the parent * * @param parent The parent object * @return The new object or NULL if it cannot be created * * @ingroup Colorselector */ EAPI Evas_Object *elm_colorselector_add(Evas_Object *parent); /** * Set color to colorselector * * @param obj Colorselector object * @param r r-value of color * @param g g-value of color * @param b b-value of color * @param a a-value of color * * @ingroup Colorselector */ EAPI void elm_colorselector_color_set(Evas_Object *obj, int r, int g, int b, int a); /** * Get current color from colorselector * * @param obj Colorselector object * @param r integer pointer for r-value of color * @param g integer pointer for g-value of color * @param b integer pointer for b-value of color * @param a integer pointer for a-value of color * * @ingroup Colorselector */ EAPI void elm_colorselector_color_get(const Evas_Object *obj, int *r, int *g, int *b, int *a); /** * Set Colorselector's mode. * * @param obj Colorselector object * @param mode Elm_Colorselector_Mode * * Colorselector supports three modes palette only, selector only and both. * * @ingroup Colorselector */ EAPI void elm_colorselector_mode_set(Evas_Object *obj, Elm_Colorselector_Mode mode); /** * Get Colorselector's mode. * * @param obj Colorselector object * @return mode The current mode of colorselector * * @ingroup Colorselector */ EAPI Elm_Colorselector_Mode elm_colorselector_mode_get(const Evas_Object *obj); /** * Add a new color item to palette. * * @param obj The Colorselector object * @param r r-value of color * @param g g-value of color * @param b b-value of color * @param a a-value of color * @return A new color palette Item. * * @ingroup Colorselector */ EAPI Elm_Object_Item *elm_colorselector_palette_color_add(Evas_Object *obj, int r, int g, int b, int a); /** * Clear the palette items. * * @param obj The Colorselector object * * @ingroup Colorselector */ EAPI void elm_colorselector_palette_clear(Evas_Object *obj); /** * Get list of palette items. * * @param obj The Colorselector object * @return The list of color palette items. * * Note That palette item list is internally managed by colorselector widget and * it should not be freed/modified by application. * * @since 1.9 * * @ingroup Colorselector */ EAPI const Eina_List *elm_colorselector_palette_items_get(const Evas_Object *obj); /** * Get the selected item in colorselector palette. * * @param obj The Colorselector object * @return The selected item, or NULL if none is selected. * * @since 1.9 * @ingroup Colorselector */ EAPI Elm_Object_Item *elm_colorselector_palette_selected_item_get(const Evas_Object *obj); /** * Set current palette's name * * @param obj The Colorselector object * @param palette_name Name of palette * * When colorpalette name is set, colors will be loaded from and saved to config * using the set name. If no name is set then colors will be loaded from or * saved to "default" config. * * @ingroup Colorselector */ EAPI void elm_colorselector_palette_name_set(Evas_Object *obj, const char *palette_name); /** * Get current palette's name * * @param obj The Colorselector object * @return Name of palette * * Returns the currently set palette name using which colors will be * saved/loaded in to config. * * @ingroup Colorselector */ EAPI const char *elm_colorselector_palette_name_get(const Evas_Object *obj);
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> int generate(char * filename,int record_length,int number_of_records){ FILE * handle = fopen(filename, "ab+"); if(handle==NULL){ perror(filename); return 1; } char * record = malloc(record_length); for(int i=0;i<number_of_records;i++){ for(int j=0;j<record_length;j++){ record[j]=rand(); } fwrite(record,sizeof(char),record_length,handle); } return 0; } int main(int argc, char **argv){ char * file = argv[1]; char * record_length = argv[2]; char * number_of_records = argv[3]; if(strlen(file) == 0 || strlen(record_length)==0 || strlen(number_of_records)==0){ printf("Bad arguments\n"); return 1; } srand(time(NULL)); generate(file,atoi(record_length),atoi(number_of_records)); return 0; }
C
/*Implementar una función que reciba una cadena representando un número hexadecimal y retorne el valor decimal de la misma. La función debe invocarse desde un programa interactivo.*/ #include <stdio.h> #include <math.h> #include <string.h> int HexToDeg(char hex[17]){ long long decimal; int i = 0, value, len; decimal = 0; len = strlen(hex); len--; for(i=0; hex[i]!='\0'; i++) { if(hex[i]>='0' && hex[i]<='9') { value = hex[i] - 48; } else if(hex[i]>='a' && hex[i]<='f') { value = hex[i] - 97 + 10; } else if(hex[i]>='A' && hex[i]<='F') { value = hex[i] - 65 + 10; } decimal += value * pow(16, len); len--; } return decimal; } int main() { char hex[17]; puts("Ingresa un numero hexadecimal"); scanf("%s", hex); printf("Tu numero en decimal es = %d\n", HexToDeg(hex)); }
C
#include <stdlib.h> #include <dbg.h> #include <string.h> #include <linkedlist.h> tNode* addNodeSpaceship(tNode** current, struct Spaceship *s) { Spaceship *heaps = malloc(sizeof(Spaceship)); check_mem(heaps); memcpy(heaps, s, sizeof(Spaceship)); tNode* newnode = malloc(sizeof(tNode) - 1 + sizeof(Spaceship*)); check_mem(newnode); tNode stru = {.next = NULL, .prev = NULL, .payload_type = PAYLOAD_SHIP}; *newnode = stru; Spaceship **nodeship = (Spaceship **) &newnode->payload; /* log_info("pointer to be assigned to: %p", *current); */ *nodeship = heaps; if(!*current) { (*current) = newnode; } else { tNode *last = *current; while(last->next) { last = last->next; } last->next = newnode; newnode->prev = last; } return newnode; error: return NULL; } void freePayload(tNode *node) { switch (node->payload_type) { case PAYLOAD_SHIP: { Spaceship **nodeship = (Spaceship **) &node->payload; free(*nodeship); break; } case PAYLOAD_BLAST: { Blast **nodeblast = (Blast **) &node->payload; free(*nodeblast); break; } default: break; } } tNode* removeNode(tNode** start, tNode* interm) { tNode* res = interm->next; if(interm == NULL) return NULL; if(interm->prev == NULL && interm == *start) { if(interm->next == NULL) { *start = NULL; freePayload(interm); free(interm); } else { *start = interm->next; interm->next->prev = interm->prev; freePayload(interm); free(interm); } } else if (interm->prev != NULL){ log_info("pointer modification 2"); interm->prev->next = interm->next; if(interm->next) { interm->next->prev = interm->prev; } freePayload(interm); free(interm); } else { sentinel("unreachable removeNOde %p (interm) %p (*start)", interm, *start); } return res; error: return NULL; } tNode* addNodeBlast(tNode** current, struct Blast *s) { Blast *heaps = malloc(sizeof(Blast)); check_mem(heaps); memcpy(heaps, s, sizeof(Blast)); tNode* newnode = malloc(sizeof(tNode) - 1 + sizeof(Blast*)); check_mem(newnode); tNode stru = {.next = NULL, .prev = NULL, .payload_type = PAYLOAD_BLAST}; *newnode = stru; Blast **nodeship = (Blast **) &newnode->payload; /* log_info("pointer to be assigned to: %p", *current); */ *nodeship = heaps; if(!*current) { (*current) = newnode; } else { tNode *last = *current; while(last->next) { last = last->next; } last->next = newnode; newnode->prev = last; } return newnode; error: return NULL; } tNode* get_nth(tNode* start, int index) { tNode* curr = start; for (int i = 0; (curr != NULL && i < index); ++i) { curr = curr->next; } return curr; } Blast* getBlast(tNode *node) { switch (node->payload_type) { case PAYLOAD_BLAST: { Blast **nodeship = (Blast **) &node->payload; return *nodeship; } default: return NULL; } } Spaceship* getShip(tNode *node) { switch (node->payload_type) { case PAYLOAD_SHIP: { Spaceship **nodeship = (Spaceship **) &node->payload; return *nodeship; } default: return NULL; } } void freeList(tNode *node) { if(node->next) { freeList(node->next); } freePayload(node); free(node); }
C
#include "skiList.h" static char skiListID; typedef struct _pulleyNode { struct _pulleyNode* prev; struct _pulleyNode* next; }PulleyNode_t; typedef struct _listHead{ PulleyNode_t pulley; size_t listSize; size_t dataSize; void* headID; }ListHead_t; typedef struct _listNode{ PulleyNode_t pulley; void* nodeID; char data[0]; }ListNode_t; #define __identifyHead(_pHead) ((_pHead) && ((ListHead_t*)_pHead)->headID == &skiListID) #define __identifyNode(_pHead, _pNode) ((_pNode) && (_pNode) != (_pHead) && ((ListNode_t*)(_pNode))->nodeID == (_pHead)) #define __swapNode(_pNode1, _pNode2) do{ \ __swapPos(_pNode1, _pNode2); \ __swapValue(_pNode1, _pNode2); \ }while(0) #define __swapValue(_val1, _val2) do{ \ typeof(_val1) _tmp = (_val1); \ (_val1) = (_val2); \ (_val2) = _tmp; \ }while(0) static void inline __initNode(PulleyNode_t* node) { node->prev = node->next = node; } static void inline __insertNode(PulleyNode_t* front, PulleyNode_t* node, PulleyNode_t* back) { front->next = node; back->prev = node; node->prev = front; node->next = back; } static void inline __insertList(PulleyNode_t* front, PulleyNode_t* start, PulleyNode_t* end, PulleyNode_t* back) { front->next = start; back->prev = end; start->prev = front; end->next = back; } static void inline __deleteNode(PulleyNode_t* front, PulleyNode_t* back) { front->next = back; back->prev = front; } static void inline __rotatePrev(PulleyNode_t* node) { __deleteNode(node->prev, node->next); __insertNode(node->prev->prev, node, node->prev); } static void inline __rotateNext(PulleyNode_t* node) { __deleteNode(node->prev, node->next); __insertNode(node->next, node, node->next->next); } static void inline __swapPos(PulleyNode_t* node1, PulleyNode_t* node2) { if(node1 == node2)return; else if(node1->next == node2)__rotateNext(node1); else if(node1->prev == node2)__rotatePrev(node1); else{ __swapValue(*node1, *node2); node1->prev->next = node1; node1->next->prev = node1; node2->prev->next = node2; node2->next->prev = node2; } } static int inline __is_empty(PulleyNode_t* head) { return head->next == head; } skiHandler_t skiList_create(size_t dataSize) { ListHead_t* pListHead = malloc(sizeof(ListHead_t)); if(pListHead == NULL)goto malloc_failed; pListHead->dataSize = dataSize; pListHead->listSize = 0; pListHead->headID = &skiListID; __initNode(&pListHead->pulley); malloc_failed: return pListHead; } skiPosition_t skiList_insert(skiHandler_t handler, skiPosition_t pos, void* data) { if(!__identifyHead(handler))goto list_failed; ListHead_t* pListHead = handler; if(handler != pos && !__identifyNode(handler, pos))goto list_failed; PulleyNode_t* pEntry = pos; ListNode_t* pListNode = malloc(sizeof(ListNode_t) + pListHead->dataSize); if(pListNode == NULL)goto list_failed; __insertNode(pEntry->prev, &pListNode->pulley, pEntry); if(data)memcpy(pListNode->data, data, pListHead->dataSize); pListNode->nodeID = handler; pListHead->listSize++; return (skiPosition_t)pListNode; list_failed: return NULL; } skiPosition_t skiList_delete(skiHandler_t handler, skiPosition_t pos, void* data) { if(!__identifyHead(handler))goto list_failed; if(!__identifyNode(handler, pos))goto list_failed; ListHead_t* pListHead = handler; PulleyNode_t* pNode = pos; ListNode_t* pListNode = pos; if(pListHead->listSize == 0)goto list_failed; pos = pNode->next; __deleteNode(pNode->prev, pNode->next); __initNode(pNode); if(data)memcpy(data, pListNode->data, pListHead->dataSize); pListNode->nodeID = NULL; free(pNode); pListHead->listSize--; return (skiPosition_t)pos; list_failed: return NULL; } skiPosition_t skiList_pushBack(skiHandler_t handler, void* data) { if(!__identifyHead(handler))return NULL; return skiList_insert(handler, ((PulleyNode_t*)handler), data); } skiPosition_t skiList_pushFront(skiHandler_t handler, void* data) { if(!__identifyHead(handler))return NULL; return skiList_insert(handler, ((PulleyNode_t*)handler)->next, data); } skiPosition_t skiList_popBack(skiHandler_t handler, void* data) { if(!__identifyHead(handler))return NULL; return skiList_delete(handler, ((PulleyNode_t*)handler)->prev, data); } skiPosition_t skiList_popFront(skiHandler_t handler, void* data) { if(!__identifyHead(handler))return NULL; return skiList_delete(handler, ((PulleyNode_t*)handler)->next, data); } skiPosition_t skiList_search(skiHandler_t handler, void* data, skiFunc2_t cmpFunc) { if(!__identifyHead(handler))goto list_failed; //ListHead_t* pListHead = handler; PulleyNode_t* pHead = handler, *cursor = NULL; for(cursor = pHead->next; cursor != pHead; cursor = cursor->next){ if(0 == cmpFunc(((ListNode_t*)cursor)->data, data))break; } return cursor; list_failed: return NULL; } int skiList_foreach(skiHandler_t handler, skiFunc2_t func2, void* arg) { if(!__identifyHead(handler) || !func2)goto list_failed; PulleyNode_t* pHead = handler, *cursor = NULL; for(cursor = pHead->next; cursor != pHead; cursor = cursor->next){ if(func2(((ListNode_t*)cursor)->data, arg))break; } return func2(NULL, arg); list_failed: return 0; } void skiList_clear(skiHandler_t handler, skiFunc1_t clearFunc) { if(!__identifyHead(handler))return; ListHead_t* pListHead = handler; PulleyNode_t* pHead = handler; ListNode_t* pListNode = NULL; //while(pHead->next != pHead){ for(PulleyNode_t* cursor = pHead; cursor->next != pHead;){ pListNode = (ListNode_t*)cursor->next; if(clearFunc && clearFunc(pListNode->data)){ cursor = (PulleyNode_t*)pListNode; }else{ __deleteNode(pListNode->pulley.prev, pListNode->pulley.next); __initNode(&pListNode->pulley); pListNode->nodeID = NULL; free(pListNode); } } pListNode = NULL; pListHead->listSize = 0; } void skiList_destroy(skiHandler_t handler) { if(!__identifyHead(handler))return; ListHead_t* pListHead = handler; skiList_clear(handler, NULL); pListHead->headID = NULL; free(handler); } void* skiList_at(skiHandler_t handler, skiPosition_t pos) { if(!__identifyHead(handler))goto list_failed; if(!__identifyNode(handler, pos))goto list_failed; return ((ListNode_t*)pos)->data; list_failed: return NULL; } skiPosition_t skiList_begin(skiHandler_t handler) { if(!__identifyHead(handler))goto list_failed; PulleyNode_t* pos = ((PulleyNode_t*)handler)->next; if(pos == handler)goto list_failed; return pos; list_failed: return NULL; } skiPosition_t skiList_end(skiHandler_t handler) { if(!__identifyHead(handler))goto list_failed; PulleyNode_t* pos = ((PulleyNode_t*)handler)->prev; if(pos == handler)goto list_failed; return pos; list_failed: return NULL; } skiPosition_t skiList_next(skiHandler_t handler, skiPosition_t pos) { if(!__identifyHead(handler))goto list_failed; if(!__identifyNode(handler, pos))goto list_failed; pos = ((PulleyNode_t*)pos)->next; if(pos == handler)goto list_failed; return pos; list_failed: return NULL; } skiPosition_t skiList_prev(skiHandler_t handler, skiPosition_t pos) { if(!__identifyHead(handler))goto list_failed; if(!__identifyNode(handler, pos))goto list_failed; pos = ((PulleyNode_t*)pos)->prev; if(pos == handler)goto list_failed; return pos; list_failed: return NULL; } size_t skiList_size(skiHandler_t handler) { if(!__identifyHead(handler))return 0; return ((ListHead_t*)handler)->listSize; } static int __copy_node(void* data, void* handler) { if(data)skiList_pushBack(handler, data); return 0; } skiHandler_t skiList_copy(skiHandler_t handler) { if(!__identifyHead(handler))goto list_failed; ListHead_t* pListHead = handler; ListHead_t* pListHeadNew = skiList_create(pListHead->dataSize); if(pListHeadNew == NULL)goto list_failed; skiList_foreach(pListHead, __copy_node, pListHeadNew); return pListHeadNew; list_failed: return NULL; } #if 0 //unused but mark here static void __quick_sort(PulleyNode_t* start, PulleyNode_t* end, skiFunc2_t cmpFunc) { if(start->next == end || start == end)return; PulleyNode_t* front = start, *back = end->prev; while(1){ while(front != back && cmpFunc(((ListNode_t*)start)->data, ((ListNode_t*)back)->data) <= 0) back = back->prev; while(front != back && cmpFunc(((ListNode_t*)start)->data, ((ListNode_t*)front)->data) >= 0) front = front->next; if(front == back)break; __swapNode(front, back); } __swapNode(start, front); __quick_sort(start, front->next, cmpFunc); __quick_sort(front->next, end, cmpFunc); } #endif static void __insert_sort(PulleyNode_t* pHead, skiFunc2_t cmpFunc) { PulleyNode_t* sorted = NULL; PulleyNode_t* cursor = NULL; PulleyNode_t* anchor = NULL; for(sorted = pHead->next; sorted->next != pHead;){ for(anchor = cursor = sorted->next; cursor->prev != pHead; cursor = cursor->prev) if(cmpFunc(((ListNode_t*)cursor->prev)->data, ((ListNode_t*)anchor)->data) < 0) break; if(cursor == sorted->next)sorted = cursor; else{ __deleteNode(anchor->prev, anchor->next); __insertNode(cursor->prev, anchor, cursor); } } } static void __merge_sort(PulleyNode_t* pHead, size_t size, skiFunc2_t cmpFunc) { if(size <= 1)return; if(size <= 11)return __insert_sort(pHead, cmpFunc); size_t subSize = size / 2; PulleyNode_t tHead = {&tHead, &tHead}; PulleyNode_t* tCursor = pHead->prev; PulleyNode_t* mCursor = pHead->next; //find middle pointer while(subSize--)mCursor = mCursor->next; //cut list into 2 __deleteNode(mCursor->prev, tCursor->next); __insertList(&tHead, mCursor, tCursor, &tHead); //sort each sub list __merge_sort(pHead, size/2, cmpFunc); __merge_sort(&tHead, size/2 + (size&1), cmpFunc); //merge 2 sorted lists into 1 mCursor = pHead->next; while(!__is_empty(&tHead)){ tCursor = tHead.next; while(mCursor != pHead && cmpFunc(((ListNode_t*)mCursor)->data, ((ListNode_t*)tCursor)->data) <= 0) mCursor = mCursor->next; if(mCursor == pHead){ __insertList(mCursor->prev, tHead.next, tHead.prev, mCursor); __initNode(&tHead); break; } while(tCursor != &tHead && cmpFunc(((ListNode_t*)tCursor)->data, ((ListNode_t*)mCursor)->data) < 0) tCursor = tCursor->next; __insertList(mCursor->prev, tHead.next, tCursor->prev, mCursor); __deleteNode(&tHead, tCursor); } } #if 0 //for test sort void skiList_sort_st1(skiHandler_t handler, skiFunc2_t cmpFunc) { if(!__identifyHead(handler) || cmpFunc == NULL)return; __insert_sort(handler, cmpFunc); } void skiList_sort_st2(skiHandler_t handler, skiFunc2_t cmpFunc) { if(!__identifyHead(handler) || cmpFunc == NULL)return; __tim_sort(handler, cmpFunc); } #endif void skiList_sort(skiHandler_t handler, skiFunc2_t cmpFunc) { if(!__identifyHead(handler) || cmpFunc == NULL)return; //__quick_sort(((PulleyNode_t*)handler)->next, ((PulleyNode_t*)handler), cmpFunc); __merge_sort(handler, ((ListHead_t*)handler)->listSize, cmpFunc); } skiPosition_t skiList_arrange(skiHandler_t handler, void* data, skiFunc2_t cmpFunc) { if(!__identifyHead(handler) || !data)goto list_failed; ListHead_t* pListHead = handler; PulleyNode_t* pHead = &pListHead->pulley; PulleyNode_t* cursor = NULL; for(cursor = pHead->next; cursor != pHead; cursor = cursor->next){ if(cmpFunc(data, ((ListNode_t*)cursor)->data) < 0)break; } return skiList_insert(handler, cursor, data); list_failed: return NULL; } void skiList_reverse(skiHandler_t handler) { if(handler == NULL)return; PulleyNode_t* pHead = handler; PulleyNode_t* front = pHead->next, *back = pHead->prev; ListHead_t* pListHead = handler; if(pListHead->listSize & 1){ while(front != back){ __swapNode(front, back); front = front->next; back = back->prev; } }else{ while(front->prev != back){ __swapNode(front, back); front = front->next; back = back->prev; } } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "Interpreter/Interpreter.h" #include "Interpreter/Functions.h" #include "Parser/Parser.h" #include "Util/StringBuffer.h" bool check_let_args (ParseTree* args); Value* function_append (Environment* environment, ParseTree* args) { // Empty list case if (args->numChildren == 1) { return value_create_list_empty(); } Value* list = value_create_list_empty(); for (int i = args->numChildren-1; i > 0; --i) { // Evaluate argument Value* newList = evaluate(args->children[i], environment); if (newList == NULL) { value_release(list); return NULL; } // Listify it if necessary if (newList->type != LIST_VALUE) { newList = value_create_list(newList, value_create_list_empty()); value_release(newList->head); } // Append the current list to it Value* end = newList; while (end->tail->head != NULL) { end = end->tail; } value_release(end->tail); end->tail = list; list = newList; } return list; } Value* function_and (Environment* environment, ParseTree* args) { Value* returnVal = value_create_bool(true); for (int i = 1; i < args->numChildren; ++i) { value_release(returnVal); returnVal = evaluate(args->children[i], environment); if (returnVal == NULL) { return returnVal; } if (returnVal->type == BOOLEAN_VALUE && returnVal->boolVal == false) { return returnVal; } } return returnVal; } Value* function_begin (Environment* environment, ParseTree* args) { // You're allowed to just have (begin) and return nothing Value* exprVal = value_create(NULL_VALUE); for (int i = 1; i < args->numChildren; ++i) { value_release(exprVal); exprVal = evaluate(args->children[i], environment); } return exprVal; } Value* function_car (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren != 2) { return NULL; } Value* list = evaluate(args->children[1], environment); if (list == NULL) { return NULL; } if (list->type != LIST_VALUE) { value_release(list); return NULL; } Value* head = list->head; if (head != NULL) { value_reserve(head); } value_release(list); return head; } Value* function_cdr (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren != 2) { return NULL; } Value* list = evaluate(args->children[1], environment); if (list == NULL) { return NULL; } if (list->type != LIST_VALUE) { value_release(list); return NULL; } Value* tail = list->tail; if (tail != NULL) { value_reserve(tail); } value_release(list); return tail; } /// Generic function for numerical comparison functions /// @param comparison specifies the type of comparison to execute /// 0: = /// 1: < /// 2: > /// 3: <= /// 4: >= Value* function_comparator (Environment* environment, ParseTree* args, int comparison) { // Check arguments if (args->numChildren < 3) { return NULL; } bool result = true; // Evaluate the first argument Value* arg1 = evaluate(args->children[1], environment); if (arg1 == NULL) { return NULL; } if (arg1->type != FLOAT_VALUE && arg1->type != INTEGER_VALUE) { value_release(arg1); return NULL; } double arg1Val = 0; double arg2Val = 0; // Get value of first argument if (arg1->type == FLOAT_VALUE) { arg1Val = arg1->floatVal; } else if (arg1->type == INTEGER_VALUE) { arg1Val = (float)arg1->intVal; } value_release(arg1); // Loop through the list of arguments, performing the comparison on every two arguments for (int i = 2; i < args->numChildren; ++i) { // Evaluate and check second argument Value* arg2 = evaluate(args->children[i], environment); if (arg2 == NULL) { return NULL; } if (arg2->type != FLOAT_VALUE && arg2->type != INTEGER_VALUE) { value_release(arg2); return NULL; } // Get value of second argument if (arg2->type == FLOAT_VALUE) { arg2Val = arg2->floatVal; } else if (arg2->type == INTEGER_VALUE) { arg2Val = (float)arg2->intVal; } value_release(arg2); // Perform comparison switch (comparison) { case 0: result = result && arg1Val == arg2Val; break; case 1: result = result && arg1Val < arg2Val; break; case 2: result = result && arg1Val > arg2Val; break; case 3: result = result && arg1Val <= arg2Val; break; case 4: result = result && arg1Val >= arg2Val; break; default: return NULL; } arg1Val = arg2Val; } // Return the result of the comparisons return value_create_bool(result); } Value* function_cons (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren != 3) { return NULL; } Value* item1 = evaluate(args->children[1], environment); if (item1 == NULL) { return NULL; } Value* item2 = evaluate(args->children[2], environment); if (item2 == NULL) { value_release(item1); return NULL; } Value* list = value_create_list(item1,item2); value_release(item1); value_release(item2); return list; } Value* function_cond (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren < 2) { return NULL; } for (int i = 1; i < args->numChildren; ++i) { if (args->children[i]->children[0]->token != NULL && args->children[i]->children[0]->token->type == SYMBOL_VALUE) { if (i != args->numChildren - 1 && strcmp(args->children[i]->children[0]->token->symbol, "else") == 0) { return NULL; } } } for (int i = 1; i < args->numChildren; ++i) { if (args->children[i]->numChildren < 1) { return NULL; } if (args->children[i]->children[0]->token != NULL && args->children[i]->children[0]->token->type == SYMBOL_VALUE) { if (i == args->numChildren - 1 && strcmp(args->children[i]->children[0]->token->symbol, "else") == 0) { return evaluate(args->children[i]->children[1], environment); } } // Evaluate and check condition Value* condition = evaluate(args->children[i]->children[0], environment); if (condition == NULL) { return NULL; } if (condition->type != BOOLEAN_VALUE || condition->boolVal) { value_release(condition); return evaluate(args->children[i]->children[1], environment); } } return value_create(NULL_VALUE); } Value* function_define (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren != 3) { return NULL; } ParseTree* var = args->children[1]; ParseTree* val = args->children[2]; if (var->token == NULL || var->token->type != SYMBOL_VALUE) { return NULL; } // Evaluate value and store in variable Value* value = evaluate(val, environment); if (value == NULL) { return NULL; } environment_set(environment, var->token->symbol, value); value_release(value); return value_create(NULL_VALUE); } Value* function_display (Environment* environment, ParseTree* args) { // Check and evaluate argument if (args->numChildren != 2) { return NULL; } Value* value = evaluate(args->children[1], environment); if (value == NULL) { return NULL; } // Print and release value if (value->type == STRING_VALUE) { printf("%s\n", value->string); } else { value_print(value); printf("\n"); } value_release(value); return value_create(NULL_VALUE); } Value* function_divide (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren < 2) { return NULL; } // Multiplicative inverse case if (args->numChildren == 2) { Value* v = evaluate(args->children[1], environment); Value* result; if (v == NULL) { return NULL; } if (v->type == INTEGER_VALUE && (v->intVal == 1 || v->intVal == -1)) { result = value_create_int(v->intVal); } else if (v->type == INTEGER_VALUE || v->type == FLOAT_VALUE) { result = value_create_float(1.0 / v->intVal); } else { result = NULL; } value_release(v); return result; } // Actual quotient cases else { double quotient = 1; bool integer = true; for (int i = 1; i < args->numChildren; ++i) { // Evaluate and check argument Value* value = evaluate(args->children[i], environment); if (value == NULL) { parsetree_print(args->children[i]); return NULL; } if (value->type != FLOAT_VALUE && value->type != INTEGER_VALUE) { value_release(value); return NULL; } // Dividend case if (i == 1) { if (value->type == FLOAT_VALUE) { quotient = value->floatVal; integer = false; } else if (value->type == INTEGER_VALUE) { quotient = value->intVal; } } // Divisor case else { if (value->type == FLOAT_VALUE) { quotient /= value->floatVal; integer = false; } else if (value->type == INTEGER_VALUE) { quotient /= value->intVal; if ((int)quotient % value->intVal != 0) { integer = false; } } } value_release(value); } // Return quotient as the correct type if (integer) { return value_create_int(quotient); } else { return value_create_float(quotient); } } } Value* function_greaterthan (Environment* environment, ParseTree* args) { return function_comparator(environment, args, 2); } Value* function_greaterthaneqto (Environment* environment, ParseTree* args) { return function_comparator(environment, args, 4); } Value* function_if (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren != 4) { return NULL; } // Evaluate and check condition Value* condition = evaluate(args->children[1], environment); if (condition == NULL) { return NULL; } if (condition->type != BOOLEAN_VALUE) { value_release(condition); return NULL; } // Evaluate and return the right case bool cond = condition->boolVal; value_release(condition); if (cond) { return evaluate(args->children[2], environment); } else { return evaluate(args->children[3], environment); } } Value* function_lambda (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren < 3) { return NULL; } // Check parameter list for (int i = 0; i < args->children[1]->numChildren; ++i) { if (args->children[1]->children[i]->token == NULL) { return NULL; } if (args->children[1]->children[i]->token->type != SYMBOL_VALUE) { return NULL; } } // Prepare parameter list and code int numParams = args->children[1]->numChildren; char** params = malloc(numParams * sizeof(char**)); for (int i = 0; i < numParams; ++i) { params[i] = strdup(args->children[1]->children[i]->token->symbol); } return value_create_lambda(environment, numParams, params, args); } Value* function_lessthan (Environment* environment, ParseTree* args) { return function_comparator(environment, args, 1); } Value* function_lessthaneqto (Environment* environment, ParseTree* args) { return function_comparator(environment, args, 3); } Value* function_let (Environment* environment, ParseTree* args) { // Check arguments if (!check_let_args(args)) { return NULL; } ParseTree* vars = args->children[1]; // Create environment from bindings Environment* env = environment_create(environment); for (int i = 0; i < vars->numChildren; ++i) { char* var = vars->children[i]->children[0]->token->symbol; ParseTree* val = vars->children[i]->children[1]; Value* value = evaluate(val, environment); if (value == NULL) { environment_release(env); return NULL; } environment_set(env, var, value); value_release(value); } return evaluate_bodies(args, env); } Value* function_letrec (Environment* environment, ParseTree* args) { // Check arguments if (!check_let_args(args)) { return NULL; } ParseTree* vars = args->children[1]; // Initialize environment with undefineds Environment* env = environment_create(environment); for (int i = 0; i < vars->numChildren; ++i) { Value* value = value_create(UNDEF_VALUE); environment_set(env, vars->children[i]->children[0]->token->symbol, value); value_release(value); } // Evaluate and store actual values for (int i = 0; i < vars->numChildren; ++i) { Value* value = evaluate(vars->children[i]->children[1], env); if (value == NULL) { environment_release(env); return NULL; } environment_set(env, vars->children[i]->children[0]->token->symbol, value); value_release(value); } return evaluate_bodies(args, env); } Value* function_letstar (Environment* environment, ParseTree* args) { // Check arguments if (!check_let_args(args)) { return NULL; } ParseTree* vars = args->children[1]; // Create sequential environments from bindings Environment* env = environment_create(environment); for (int i = 0; i < vars->numChildren; ++i) { // Evaluate and store in current environment char* var = vars->children[i]->children[0]->token->symbol; ParseTree* val = vars->children[i]->children[1]; Value* value = evaluate(val, env); if (value == NULL) { environment_release(env); return NULL; } environment_set(env, var, value); // Create fresh environment env = environment_create(env); environment_release(env->parent); value_release(value); } return evaluate_bodies(args, env); } Value* function_list (Environment* environment, ParseTree* args) { // Check number of arguments if (args->numChildren < 2) { return NULL; } Value* builtList = value_create_list_empty(); for (int i = args->numChildren - 1; i > 0; --i) { Value* item = evaluate(args->children[i], environment); if (item == NULL) { value_release(builtList); return NULL; } Value* listTemp = value_create_list_empty(); listTemp->head = item; listTemp->tail = builtList; builtList = listTemp; } return builtList; } Value* function_load (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren != 2) { return NULL; } if (args->children[1]->token->type != STRING_VALUE) { return NULL; } // Load file in top environment while (environment->parent != NULL) { environment = environment->parent; } bool success = load_file(environment, args->children[1]->token->string); if (!success) { return NULL; } return value_create(NULL_VALUE); } Value* function_minus (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren < 2) { return NULL; } // Sum everything up double sum = 0; bool integer = true; for (int i = 1; i < args->numChildren; ++i) { // Evaluate and check argument Value* value = evaluate(args->children[i], environment); if (value == NULL) { return NULL; } if (value->type != FLOAT_VALUE && value->type != INTEGER_VALUE) { value_release(value); return NULL; } // Add (or subtract) value from total double v; if (value->type == FLOAT_VALUE) { v = value->floatVal; integer = false; } else if (value->type == INTEGER_VALUE) { v = value->intVal; } if (i != 1 || args->numChildren == 2) { v *= -1; } sum += v; value_release(value); } // Return sum as the correct type if (integer) { return value_create_int(sum); } else { return value_create_float(sum); } } Value* function_modulo (Environment* environment, ParseTree* args) { // Check that there are two arguments if (args->numChildren != 3) { return NULL; } // Evaluate arguments and check for null cases Value* arg1 = evaluate(args->children[1], environment); if (arg1 == NULL) { return NULL; } if (arg1->type != INTEGER_VALUE) { value_release(arg1); return NULL; } Value* arg2 = evaluate(args->children[2], environment); if (arg2 == NULL) { value_release(arg1); return NULL; } if (arg2->type != INTEGER_VALUE) { value_release(arg1); value_release(arg2); return NULL; } int result = arg1->intVal % arg2->intVal; value_release(arg1); value_release(arg2); return value_create_int(result); } Value* function_null (Environment* environment, ParseTree* args) { // Check that there's only a single argument if (args->numChildren != 2) { return NULL; } // Evaluate argument and test for null-ness Value* value = evaluate(args->children[1], environment); if (value == NULL) { return NULL; } bool null = false; if (value->type == LIST_VALUE && value->head == NULL && value->tail == NULL) { null = true; } value_release(value); return value_create_bool(null); } Value* function_numequals (Environment* environment, ParseTree* args) { return function_comparator(environment, args, 0); } Value* function_or (Environment* environment, ParseTree* args) { Value* returnVal = value_create_bool(false); for (int i = 1; i < args->numChildren; ++i) { value_release(returnVal); returnVal = evaluate(args->children[i], environment); if (returnVal->type != BOOLEAN_VALUE || returnVal->boolVal == true) { return returnVal; } } return returnVal; } Value* function_plus (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren < 2) { return NULL; } // Sum everything up double sum = 0; bool integer = true; for (int i = 1; i < args->numChildren; ++i) { // Evaluate and check argument Value* value = evaluate(args->children[i], environment); if (value == NULL) { return NULL; } if (value->type != FLOAT_VALUE && value->type != INTEGER_VALUE) { value_release(value); return NULL; } // Add value to total if (value->type == FLOAT_VALUE) { sum += value->floatVal; integer = false; } else if (value->type == INTEGER_VALUE) { sum += value->intVal; } value_release(value); } // Return sum as the correct type if (integer) { return value_create_int(sum); } else { return value_create_float(sum); } } Value* function_quote (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren != 2) { return NULL; } // Evaluate and return Value* value = evaluate_list(args->children[1]); if (value == NULL) { return NULL; } return value; } Value* function_setbang (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren != 3) { return NULL; } ParseTree* var = args->children[1]; ParseTree* val = args->children[2]; if (var->token == NULL || var->token->type != SYMBOL_VALUE) { return NULL; } // Evaluate and replace Value* value = evaluate(val, environment); if (value == NULL) { return NULL; } environment_set(environment, var->token->string, value); return value_create(NULL_VALUE); } Value* function_times (Environment* environment, ParseTree* args) { // Check arguments if (args->numChildren < 2) { return NULL; } // Sum everything up double prod = 1; bool integer = true; for (int i = 1; i < args->numChildren; ++i) { // Evaluate and check argument Value* value = evaluate(args->children[i], environment); if (value == NULL) { return NULL; } if (value->type != FLOAT_VALUE && value->type != INTEGER_VALUE) { value_release(value); return NULL; } // Multiply value into total if (value->type == FLOAT_VALUE) { prod *= value->floatVal; integer = false; } else if (value->type == INTEGER_VALUE) { prod *= value->intVal; } value_release(value); } // Return product as the correct type if (integer) { return value_create_int(prod); } else { return value_create_float(prod); } } Value* function_zero (Environment* environment, ParseTree* args) { // Check and evaluate argument if (args->numChildren != 2) { return NULL; } Value* value = evaluate(args->children[1], environment); if (value == NULL) { return NULL; } // Return result bool result = false; if (value->type == INTEGER_VALUE) { result = value->intVal == 0; } if (value->type == FLOAT_VALUE) { result = value->floatVal == 0; } value_release(value); return value_create_bool(result); } bool check_let_args (ParseTree* args) { // Check number of arguments if (args->numChildren < 3) { return false; } ParseTree* vars = args->children[1]; // Check bindings if (vars->token != NULL) { return false; } for (int i = 0; i < vars->numChildren; ++i) { if (vars->children[i]->token != NULL) { return false; } ParseTree* var = vars->children[i]->children[0]; ParseTree* val = vars->children[i]->children[1]; if (var->token == NULL) { return false; } if (var->token->type != SYMBOL_VALUE) { return false; } } // Hooray! return true; }
C
/* Copyright 2012-2014 Scianta Analytics LLC All Rights Reserved. Reproduction or unauthorized use is prohibited. Unauthorized use is illegal. Violators will be prosecuted. This software contains proprietary trade and business secrets. Module: saLinearRegression Description: Perform Linear Regression to generate an algorithm of the type y = A*x + B. Return A, B, std estimate of error as a structure. Functions: External: saLinearRegressioncreateLR saLinearRegressionGetLine Internal: computeResiduals */ #include <stdlib.h> #include <math.h> #include "saLinearRegression.h" /** * Reads in a sequence of pairs of double numbers and computes the * best fit (least squares) line y = ax + b through the set of points. * Also computes the correlation coefficient and the standard errror * of the regression coefficients. **/ inline void computeResiduals(saLinearRegressionTypePtr, double, double, double, double); saLinearRegressionTypePtr saLinearRegressionCreateLR(double X[], double Y[], int numPoints) { saLinearRegressionTypePtr lrPtr = malloc(sizeof(saLinearRegressionType)); lrPtr->numPoints = numPoints; lrPtr->xAxis = X; lrPtr->yAxis = Y; lrPtr->coefA = 0.0; lrPtr->coefB = 0.0; lrPtr->R = 0.0; lrPtr->stdError_CoefA = 0.0; lrPtr->stdError_CoefB = 0.0; return(lrPtr); } /*** * saLinearRegressionGetLine(). Computes the regression properties and * returns the slope and the x-intercept for the equation. This * way of returning the regression equation allows us to add * an addData() method later to incrementally compute the linear * regression line (which will be important in the behavior model). ***/ void saLinearRegressionGetLine(saLinearRegressionTypePtr lrPtr) { // //--------------------------------------------------------------- //--first pass: compute the sum of the x and y values and also // the sum of the squares for the x-axis (data value) stream. //--------------------------------------------------------------- // double sumx = 0.0; double sumy = 0.0; double sumx2 = 0.0; int n; for(n=0; n<lrPtr->numPoints; n++) { sumx += lrPtr->xAxis[n]; sumx2 += lrPtr->xAxis[n] * lrPtr->xAxis[n]; sumy += lrPtr->yAxis[n]; } double xbar = sumx / lrPtr->numPoints; double ybar = sumy / lrPtr->numPoints; // //--------------------------------------------------------------- //--second pass: compute the correlations and develop the //--slope and the intercept for the line. //--------------------------------------------------------------- // double xxbar = 0.0; double yybar = 0.0; double xybar = 0.0; int i; for(i=0; i < lrPtr->numPoints; i++) { xxbar += (lrPtr->xAxis[i] - xbar) * (lrPtr->xAxis[i] - xbar); yybar += (lrPtr->yAxis[i] - ybar) * (lrPtr->yAxis[i] - ybar); xybar += (lrPtr->xAxis[i] - xbar) * (lrPtr->yAxis[i] - ybar); } // //--------------------------------------------------------------- //--now we compute the coefficients and then the residual data //--used to measure the degrees of error in the estimates. //--------------------------------------------------------------- // // y = ((m_coefA) * x) + m_coefB // lrPtr->coefA = xybar / xxbar; lrPtr->coefB = ybar - lrPtr->coefA * xbar; //coeff[0]=lrPtr->coefA; //--slope //coeff[1]=lrPtr->coefB; //--intercept computeResiduals(lrPtr, xbar, ybar, yybar, xxbar); } /*** * computeResiduals(). Given the properties of the regression line, we now * loop back across the data points and create an estimate for each actual * point (see the 'fit' variable which is the result of the regression * equation applied to each data point). From this fit we compute the * Pearson's r for the x and y streams as well as the standard error of * estimate for the slop and the intercept. ***/ inline void computeResiduals(saLinearRegressionTypePtr lrPtr, double xbar, double ybar, double yybar, double xxbar) { int df = lrPtr->numPoints - 2; //--degrees of freedom double rss = 0.0; //--residual sum of squares double ssr = 0.0; //--regression sum of squares int i; for(i=0; i < lrPtr->numPoints; i++) { double fit = lrPtr->coefA * lrPtr->xAxis[i] + lrPtr->coefB; rss += (fit - lrPtr->yAxis[i]) * (fit - lrPtr->yAxis[i]); ssr += (fit - ybar) * (fit - ybar); } lrPtr->R = pow(ssr / yybar, 0.5); double svar = rss / df; double svar1 = svar / xxbar; double svar0 = svar/lrPtr->numPoints + xbar*xbar*svar1; lrPtr->stdError_CoefA = sqrt(svar1); lrPtr->stdError_CoefB = sqrt(svar0); }
C
#include <stdlib.h> #include <stdint.h> #include <string.h> #include <assert.h> #include <cairo.h> #include <gdk-pixbuf/gdk-pixbuf.h> static void *img_expand24(int width, int height, int stride, const void *bytes) { uint8_t *rgb = malloc(width*height*3); if(rgb == NULL) return NULL; int adjust = stride - 3*width; const uint8_t *p = bytes; uint8_t *q = rgb; while(p < (const uint8_t *)bytes + width*height) { const uint8_t *end = p + width; while(p < end) { *q++ = *p; *q++ = *p; *q++ = *p; p++; } q += adjust; } return rgb; } static void *img_expand32(int width, int height, int stride, const void *bytes) { uint32_t *rgb = malloc(width*height*4); if(rgb == NULL) return NULL; int adjust = stride - 4*width; const uint8_t *p = bytes; uint32_t *q = rgb; while(p < (const uint8_t *)bytes + width*height) { const uint8_t *end = p + width; while(p < end) *q++ = 0x010101 * (*p++); q = (uint32_t *)((uint8_t *)q + adjust); } return rgb; } static void *img_collapse24(int width, int height, int stride, const void *rgb) { uint8_t *bytes = malloc(width*height); if(bytes == NULL) return NULL; int adjust = stride - 3*width; uint8_t *p = bytes; const uint8_t *q = rgb; while(p < bytes + width*height) { const uint8_t *end = p + width; while(p < end) { *p++ = *q; q += 3; } q += adjust; } return bytes; } int img_read(const char *filename, int *widthp, int *heightp, uint8_t **bytesp) { GdkPixbuf *pb = gdk_pixbuf_new_from_file(filename, NULL); if(pb == NULL) return -1; if(gdk_pixbuf_get_n_channels(pb) != 3 || gdk_pixbuf_get_bits_per_sample(pb) != 8 || gdk_pixbuf_get_has_alpha(pb) != FALSE) { g_object_unref(G_OBJECT(pb)); return -1; } uint8_t *data = gdk_pixbuf_get_pixels(pb); int width = gdk_pixbuf_get_width(pb), height = gdk_pixbuf_get_height(pb), stride = gdk_pixbuf_get_rowstride(pb); uint8_t *bytes = img_collapse24(width, height, stride, data); if(bytes == NULL) { g_object_unref(G_OBJECT(pb)); return -1; } g_object_unref(G_OBJECT(pb)); *widthp = width; *heightp = height; *bytesp = bytes; return 0; } int img_write(const char *filename, int width, int height, const uint8_t *bytes) { int fnamelen = strlen(filename); char *type; if(fnamelen>=4 && strcmp(".pgm", filename+fnamelen-4) == 0) type = "pgm"; else if(fnamelen>=4 && strcmp(".png", filename+fnamelen-4) == 0) type = "png"; else if(fnamelen>=4 && strcmp(".jpg", filename+fnamelen-4) == 0) type = "jpeg"; else return -1; void *rgb = img_expand24(width, height, 3*width, bytes); if(rgb == NULL) return -1; GdkPixbuf *pb = gdk_pixbuf_new_from_data(rgb, GDK_COLORSPACE_RGB, FALSE, 8, width, height, 3*width, NULL,NULL); if(!pb) { free(rgb); return -1; } if(!gdk_pixbuf_save(pb, filename, type, NULL, NULL)) { g_object_unref(G_OBJECT(pb)); free(rgb); return -1; } g_object_unref(G_OBJECT(pb)); free(rgb); return 0; } static inline int mini(int a, int b) { return a < b ? a : b; } uint32_t img_checksum(int width, int height, const uint8_t *bytes) { uint32_t sum1 = 0xffff, sum2 = 0xffff; int len = width*height/2; const uint16_t *ptr = (const uint16_t *)bytes; while (len) { int block = mini(360, len); len -= block; while(block--) sum1 += *ptr++, sum2 += sum1; sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); } if(width*height%2 == 1) sum1 += bytes[width*height-1], sum2 += sum1; sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); sum1 = (sum1 & 0xffff) + (sum1 >> 16); sum2 = (sum2 & 0xffff) + (sum2 >> 16); return sum2 << 16 | sum1; } static void *memdup(const void *buf, size_t size) { void *ret = malloc(size); if(ret == NULL) return NULL; memcpy(ret, buf, size); return ret; } static cairo_user_data_key_t img_free_cairo_buffer_key; cairo_surface_t *img_make_surface(int width, int height, const void *bytes, int gray) { void *data; int stride; cairo_format_t format; if(gray) { format = CAIRO_FORMAT_RGB24; stride = cairo_format_stride_for_width(format, width); data = img_expand32(width, height, stride, bytes); } else { format = CAIRO_FORMAT_ARGB32; stride = cairo_format_stride_for_width(format, width); assert(stride == sizeof(uint32_t)*width); data = memdup(bytes, width*height*sizeof(uint32_t)); } if(data == NULL) return NULL; cairo_surface_t *surface = cairo_image_surface_create_for_data(data, format, width, height, stride); if(cairo_surface_status(surface) == CAIRO_STATUS_NO_MEMORY) { free(data); return NULL; } cairo_surface_set_user_data(surface, &img_free_cairo_buffer_key, data, free); return surface; }
C
// // fskmodem_waterfall_example.c // // This example demostrates the M-ary frequency-shift keying // (MFSK) modem in liquid by showing the resulting spectral // waterfall. // #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <math.h> #include "liquid.h" // print usage/help message void usage() { printf("fskmodem_waterfall_example -- frequency-shift keying waterfall example\n"); printf("options:\n"); printf(" -h : print help\n"); printf(" -m <bps> : bits/symbol, default: 2\n"); printf(" -b <bw> : signal bandwidth default: 0.2\n"); printf(" -n <num> : number of data symbols, default: 80\n"); printf(" -s <snr> : SNR [dB], default: 40\n"); } int main(int argc, char*argv[]) { // options unsigned int m = 2; // number of bits/symbol unsigned int num_symbols = 400; // number of data symbols float SNRdB = 30.0f; // signal-to-noise ratio [dB] float bandwidth = 0.10; // frequency spacing int dopt; while ((dopt = getopt(argc,argv,"hm:b:n:s:")) != EOF) { switch (dopt) { case 'h': usage(); return 0; case 'm': m = atoi(optarg); break; case 'b': bandwidth = atof(optarg); break; case 'n': num_symbols = atoi(optarg); break; case 's': SNRdB = atof(optarg); break; default: exit(1); } } unsigned int i; unsigned int j; // derived values unsigned int M = 1 << m; // constellation size unsigned int k = 500 * M; // samples per symbol (highly over-sampled) float nstd = powf(10.0f, -SNRdB/20.0f); // noise std. dev. // validate input if (k < M) { fprintf(stderr,"errors: %s, samples/symbol must be at least modulation size (M=%u)\n", __FILE__,M); exit(1); } else if (k > 2048) { fprintf(stderr,"errors: %s, samples/symbol exceeds maximum (2048)\n", __FILE__); exit(1); } else if (M > 1024) { fprintf(stderr,"errors: %s, modulation size (M=%u) exceeds maximum (1024)\n", __FILE__, M); exit(1); } else if (bandwidth <= 0.0f || bandwidth >= 0.5f) { fprintf(stderr,"errors: %s, bandwidht must be in (0,0.5)\n", __FILE__); exit(1); } // create spectral waterfall object unsigned int nfft = 1 << liquid_nextpow2(k); int wtype = LIQUID_WINDOW_HAMMING; unsigned int wlen = nfft/2; unsigned int delay = nfft/2; unsigned int time = 512; spwaterfallcf periodogram = spwaterfallcf_create(nfft,wtype,wlen,delay,time); spwaterfallcf_print(periodogram); // create modulator/demodulator pair fskmod mod = fskmod_create(m,k,bandwidth); float complex buf_tx[k]; // transmit buffer float complex buf_rx[k]; // transmit buffer // modulate, demodulate, count errors for (i=0; i<num_symbols; i++) { // generate random symbol unsigned int sym_in = rand() % M; // modulate fskmod_modulate(mod, sym_in, buf_tx); // add noise for (j=0; j<k; j++) buf_rx[j] = buf_tx[j] + nstd*(randnf() + _Complex_I*randnf())*M_SQRT1_2; // estimate power spectral density spwaterfallcf_write(periodogram, buf_rx, k); } // export output files spwaterfallcf_export(periodogram,"fskmodem_waterfall_example"); // destroy objects spwaterfallcf_print(periodogram); fskmod_destroy(mod); return 0; }
C
#include <stdio.h> #define N 10 int main(void) { double *p, ident[N][N]; int num_zeros = N; for (p = ident[0]; p < ident[N]; p++) if (num_zeros == N) { *p = 1.0; num_zeros = 0; } else { *p = 0.0; num_zeros++; } return 0; }
C
#include<stdio.h> void main(void) { int sum=100,i=0,n=100; // printf("n=");scanf("%d",&n); while(i<=n){ sum+=i++; } printf("sum 1 to %d=%d\n",n,sum); }
C
#include "rc/buf.h" #include "tn/error.h" // -------------------------------------------------------------------------------------------------------------- int rc_buf_setup(rc_buf_t *buf, uint16_t capacity) { TN_ASSERT(buf); TN_GUARD(aws_byte_buf_init(&buf->bb, aws_default_allocator(), capacity)); buf->bb.buffer[0] = '\0'; buf->pos = 0; return TN_SUCCESS; } // -------------------------------------------------------------------------------------------------------------- void rc_buf_cleanup(rc_buf_t *buf) { TN_ASSERT(buf); aws_byte_buf_clean_up(&buf->bb); } // -------------------------------------------------------------------------------------------------------------- uint16_t rc_buf_length(rc_buf_t *buf) { TN_ASSERT(buf); return (uint16_t)buf->bb.len; } // -------------------------------------------------------------------------------------------------------------- uint16_t rc_buf_capacity(rc_buf_t *buf) { TN_ASSERT(buf); return (uint16_t)buf->bb.capacity; } // -------------------------------------------------------------------------------------------------------------- char *rc_buf_slice(rc_buf_t *buf, uint16_t offset) { TN_ASSERT(buf && aws_byte_buf_is_valid(&buf->bb)); TN_GUARD(offset > buf->bb.len); return (buf->bb.buffer + offset); } // -------------------------------------------------------------------------------------------------------------- void rc_buf_clear(rc_buf_t *buf) { TN_ASSERT(buf); aws_byte_buf_reset(&buf->bb, false); buf->pos = 0; } // -------------------------------------------------------------------------------------------------------------- int rc_buf_insert(rc_buf_t *buf, char c) { TN_ASSERT(buf && aws_byte_buf_is_valid(&buf->bb)); TN_GUARD(buf->pos >= buf->bb.capacity - 1); const uint16_t copylen = (uint16_t)buf->bb.len - buf->pos; if (copylen) memmove(buf->bb.buffer + buf->pos + 1, buf->bb.buffer + buf->pos, copylen); buf->bb.buffer[buf->pos] = c; buf->bb.len++; buf->pos++; buf->bb.buffer[buf->bb.len] = '\0'; return TN_SUCCESS; } // -------------------------------------------------------------------------------------------------------------- int rc_buf_delete(rc_buf_t *buf) { TN_ASSERT(buf && aws_byte_buf_is_valid(&buf->bb)); const uint16_t copylen = (uint16_t)buf->bb.len - buf->pos - 1; TN_GUARD(copylen > buf->bb.len); if (copylen) memmove(buf->bb.buffer + buf->pos, buf->bb.buffer + buf->pos + 1, copylen); buf->bb.len--; buf->bb.buffer[buf->bb.len] = '\0'; return TN_SUCCESS; } // -------------------------------------------------------------------------------------------------------------- uint16_t rc_buf_cursor_get(rc_buf_t *buf) { TN_ASSERT(buf); return buf->pos; } // -------------------------------------------------------------------------------------------------------------- int rc_buf_cursor_set(rc_buf_t *buf, uint16_t pos) { TN_ASSERT(buf); TN_GUARD(pos > buf->bb.len); buf->pos = pos; return TN_SUCCESS; }
C
#include <dlfcn.h> #include <stdio.h> typedef struct Point* (_make_point)( int x, int y); typedef struct Point* (_free_point)(struct Point* p); typedef double (_get_distance)( struct Point* a, struct Point* b); int main(int argc, char *argv[]) { void *myso = dlopen("./libpoints.dylib", RTLD_NOW); _make_point *make_point = dlsym(myso, "make_point"); _free_point *free_point = dlsym(myso, "free_point"); _get_distance *get_distance = dlsym(myso, "get_distance"); struct Point* a = make_point(10,10); struct Point* b = make_point(20,20); double d = get_distance(a,b); printf("distance: %f\n", d); free_point(a); free_point(b); dlclose(myso); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* spot.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kyekim <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/09 13:32:02 by kyekim #+# #+# */ /* Updated: 2021/05/23 19:04:38 by kyekim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../minirt.h" #include "../math/vector.h" #define RADIUS 42 t_object *spot_(t_light light) { t_hittable h; t_spot *s; h.geometry = _spot; h.material = emissive_(multiply(light.color, light.brightness)); h.pointer = malloc(sizeof(t_spot)); s = h.pointer; if (!s) quit(MALLOC, "spot_()"); s->light = light; return (object_(h)); } t_bool is_lit(t_point *p, t_light *light) { static const float radius_squared = RADIUS * RADIUS; t_vector v; v = subtract(*p, light->center); return (dot(v, v) < radius_squared); } t_bool hit_spot(t_spot *s, t_ray *r, t_range range, t_hit *contact) { t_point point; float distance; distance = length(subtract(r->origin, s->light.center)); point = at(r, distance); if (is_in(distance, range) && is_lit(&point, &s->light)) { contact->distance = distance; contact->point = s->light.center; return (true); } return (false); } void hit_spots(t_object *current, t_ray *r, t_range range, t_hit *contact) { t_color *emittor; while (current) { if (hit_spot(current->object.pointer, r, range, contact)) { emittor = &contact->material.emittor; *emittor = add(*emittor, *emittor); } current = current->next; } }
C
#include "Board.h" /** @name create_board @brief stores the memory needed for a board @param width the number of columns @param height the number of rows @param number_neighbours the number of live neighbours that a cell needs to start living @param posible_neighbours an array of posible neighbours that a cell needs to continue living @return a board */ board * create_board(int width, int height, int* number_neighbours, int lenght1,int *posible_neighbours,int lenght2){ board * b = (board *) calloc(1,sizeof(board)); if (b==NULL) return NULL; b->width = width; b->height = height; b->number_neighbours = number_neighbours; b->lenght_number_neighbours = lenght1; b->posible_neighbours = posible_neighbours; b->lenght_posible_neighbours = lenght2; b->l = create_list(); return b; } /** @name neighs @brief it obtains the neighbours of a cell @param b the board @param c the cell @return a list of cells that are neighbours of the cell */ list * neighs(board b,cell c){ int i,j; int newx; int newy; list *l = create_list(); cell *c2; for (i=-1;i< 2;i++){ for (j = -1; j < 2; j++){ if (i != 0 || j != 0) {/*Avoid repetitions*/ newx=i+c.x; newy=j+c.y; if (newx >= b.width) continue; /*newx = 0;*/ if (newy >= b.height) continue; /*newy = 0;*/ if (newx < 0) continue; /*newx = b.width-1;*/ if (newy < 0) continue; /*newy = b.height-1;*/ c2 = create_cell(newx,newy); insert_first_list(l,c2); destroy_cell(c2); } } } return l; } /** @name is_empty @brief checks if a cell is dead @param b the board @param c the cell @return true if is dead false otherwise */ BOOL is_empty(board b, cell *c){ if (is_alive(b, c)==TRUE) return FALSE; return TRUE; } /** @name is_alive @brief checks if a cell is alive @param b the board @param c the cell @return true if is alive false otherwise */ BOOL is_alive(board b, cell *c){ node *p=b.l->first; while (p!=NULL){ if (equals_cell(c,p->element)==TRUE) return TRUE; p=p->next; } return FALSE; } /** @name live_neighbours @brief it obtains the number of alive neighbours of a cell @param b the board @param c the cell @return the number of neighbours */ int live_neighbours(board b, cell c){ int result = 0; list * l = neighs(b,c); node *p = l->first; while (p != NULL){ if (is_alive(b,(p->element))==TRUE) result++; p=p->next; } destroy_list(l); return result; } /** @name survivors @brief it obtains the number of survivors of a board @param b the board @return the list of survivors */ list * survivors(board b){ node *board_lst = b.l->first; int i; int number; list * result = create_list(); while (board_lst != NULL){ number = live_neighbours(b, *(board_lst->element)); for (i=0;i<b.lenght_posible_neighbours;i++){ if (number == b.posible_neighbours[i]){ insert_first_list(result,(board_lst->element)); } } board_lst = board_lst->next; } return result; } /** @name remove_duplicates @brief it removes duplicates from a list @param b the board @return the list of survivors */ list * remove_duplicates(list *l){ list * l2 = create_list(); node *p = l->first; while (p != NULL){ if (!search_list(*l2, p->element)) insert_first_list(l2, p->element); p=p->next; } destroy_list(l); return l2; } /** @name births @brief calculates the cells that have been created @param b the board @return the list of new cells */ list * births (board b){ int j; node * p = b.l->first; list * result = create_list(); int n; /*Sublists*/ list * aux = NULL; node * p2 = NULL; while (p != NULL){ /*For each cell in the list*/ aux = neighs(b,*(p->element)); /*Obtain the neighbours*/ p2 = aux->first; while (p2 != NULL){ if (search_list(*result, p2->element) == FALSE && is_empty(b, (p2->element))){ n = live_neighbours(b, *(p2->element)); for (j = 0 ; j< b.lenght_number_neighbours;j++){ if (n == b.number_neighbours[j]) insert_first_list(result,p2->element); } } p2 = p2->next;; } destroy_list(aux); p=p->next; } return result; } /** @name next_generation @brief returns the births and the survivors of a board @param b the board @return the list of new cells */ void next_generation(board *b){ list * result = survivors(*b); list * aux = births(*b); concat_list(result , aux); destroy_list(aux); destroy_list(b->l); b->l = result; } /** @name print_board_terminal @brief prints the board in the terminal @param b the board @return void */ void print_board_terminal(board *b){ node *p=b->l->first; while (p != NULL){ print_terminal_cell(*(p->element)); p=p->next; } } /** @name destroy_board @brief frees the memory that a board is using @param b the board @return void */ void destroy_board(board * b){ destroy_list(b->l); free(b->posible_neighbours); free(b->number_neighbours); free(b); } /** @name read_from_file @brief reads a board from a file @param path the path of the file @return void */ board * read_from_file(char * path){ int width = 1; int height = 1; int count =1; FILE *file=NULL; board *b; char c; if (path == NULL) return NULL; file = fopen(path, "r"); int * n = (int *) calloc(2,sizeof(int)); //Game 23/3 n[0] = 2; n[1] = 3; int * n2 = (int *) calloc(1,sizeof(int)); n2[0]=3; b= create_board(105, 35, n2,1,n,2); while ((c = getc(file)) != EOF){ if (c=='\n'){ count=0; height++; width=MAX(width,count); } if (c == 'O'){ cell* c = create_cell(count,height); insert_first_list(b->l,c); destroy_cell(c); } count++; } fclose(file); return b; }
C
#include <stdio.h> int main(void) { int i; float niz[7], suma = 0; // Promenljive u vezi zadatka for(i = 0; i < 7; i++) { printf("Unesite niz[%d] = ", i); scanf("%f", &niz[i]); } i = 0; // Vraćanje na vrednost 0! while(i < 7) { suma += niz[i]; i += 2; } printf("Suma iznosi: %f", suma); return 0; }
C
#include "getSetFunctions.h" #include <dlog.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> void error(char *msg) { perror(msg); exit(0); } char* concat(const char *s1, const char *s2) { char *result = malloc(strlen(s1)+strlen(s2)+1); strcpy(result,s1); strcpy(result,s2); return result; } void set_temp(int temp) { int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char *hostname; char buf[BUFSIZE]; portno = 8893; //atoi(argv[2]); dlog_print(DLOG_INFO, "MyTag", "portno successful."); /* socket: create the socket */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error("ERROR opening socket"); /* gethostbyname: get the server's DNS entry */ hostname = "localhost"; server = gethostbyname(hostname); dlog_print(DLOG_INFO, "MyTag", "server successful."); //server = "010.018.081.007"; /*if (server == NULL) { fprintf(stderr,"ERROR, no such host as %s\n", hostname); exit(0); }*/ /* build the server's Internet address */ bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(portno); /* connect: create a connection with the server */ if (connect(sockfd, &serv_addr, sizeof(serv_addr)) < 0) dlog_print(DLOG_ERROR, "MyTag", "connection error occurred"); dlog_print(DLOG_INFO, "MyTag", "connect successful."); /* get message line from the user */ //printf("Please enter msg: "); //fgets(buf, BUFSIZE, stdin); bzero(buf, BUFSIZE); /* char s1[23] = "set thermostat des tmp "; char s2[4]; sprintf(s2,"%d",temp); char* uf = concat(s1,s2); */ char* uf = "set thermostat des 80"; /* send the message line to the server */ n = write(sockfd, buf, strlen(buf)); if (n < 0) dlog_print(DLOG_ERROR, "MyTag", "error occurred at socket"); free(uf); /* print the server's reply */ bzero(buf, BUFSIZE); n = read(sockfd, buf, BUFSIZE); if (n < 0) error("ERROR reading from socket"); printf("Echo from server: %s", buf); close(sockfd); //return 0; }
C
//////////////////////////////////////////////////////////////////////////////// // Comments // Explores whether atof() can handle negative numbers. // Works! //////////////////////////////////////////////////////////////////////////////// // Libraries #include <stdio.h> #include <stdlib.h> //////////////////////////////////////////////////////////////////////////////// int main(void) { char s[] = "-1234.5678"; printf("%s + %d = %f\n", s, (int)(atof(s)), atof(s) - (int)(atof(s))); return 0; }
C
#include<stdio.h> int main() { char str[100]; int I,J=0; printf("Enter A String : "); gets(str); while(str[J] != '\0') J++; printf("\nReverse Of Given String Is : "); for(I=J-1; I>=0; I--) printf("%c",str[I]); printf("\n"); return 0; }
C
#include<stdio.h> #include<math.h> void main() { float a,b,c,p,q,d; printf("Quadratic equation is ax^2 + bx + c=0\n"); printf("a is coefficient of x^2 and b is coefficient of x and c is constant\n"); printf("\na="); scanf("%f",&a); printf("\nb="); scanf("%f",&b); printf("\nc="); scanf("%f",&c); p=((+sqrt(b*b-4*a*c)-b)/2*a); q=((-sqrt(b*b-4*a*c)-b)/2*a); d=(b*b-4*a*c); if(d>0) {if(d=0) printf("Roots are equal and they are %f and %d",p,q); else printf("%f and %f are the root of the quadratic equation",p,q); } else printf("Roots are Imaginary"); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "memo.h" #include "matriz_vector.h" #include "utils.h" #include "met_num.h" int main(int argc, char **argv) { if(argc < 5) { printf("Error. Ejecuta: %s [Nombre del archivo] [Número de iteraciones] [Tolerancia] [Tipo de Hessiana].\n", argv[0]); return 0; } char files_name[30]; strcpy(files_name, argv[1]); int iter_max = atoi(argv[2]); double tol = atof(argv[3]); int hess_type = atoi(argv[4]); int n; double *x0 = read_init_point(files_name, &n); double **H = create_matrix(n, n, double); if(hess_type == 1) { get_Hessian(H, x0, n); } else { Hessian_aprox(H, x0, 0.00001, n); } double **H_inv = get_inverse(H, n); BFGS(x0, rosenbrock, get_gradient, H_inv, n, iter_max, tol); free_vector(x0); free_matrix(H); free_matrix(H_inv); return 0; }
C
/* * Serial drivers for ATmega640 family, with software FIFOs for * receive and transmit. * * Author: Ken Tindell * Copyright (c) 2014-2015 JK Energy Ltd. * Licensed under MIT License. */ #include <udi_cdc.h> #include "usb_serial.h" #include <min/min_transmit_cmds.h> /* Sending process: * - A FIFO for sending * - "Character sent" interrupt reads a character from the FIFO (if there * is one) and puts it in the UART data buffer * - Application layer writes to the FIFO; if it was empty it triggers the * "sent" interrupt (or writes directly to the UART) * * Receiving process: * - A FIFO for receiving * - A "character received" interrupt reads the UART buffer and writes to * the FIFO (writes to full are ignored and character discarded) * - Application layer polls the FIFO to see if there are enough characters * to process */ struct fifo { uint8_t *buf; /* Space allocated to FIFO */ uint8_t size; /* Size of FIFO */ uint8_t head; /* Indexes first free byte (unless full) */ uint8_t tail; /* Indexes last filled byte (unless empty) */ uint8_t used; /* Between 0..size */ uint8_t max_used; /* Maximum space used in the FIFO */ }; #define FIFO_EMPTY(f) ((f)->used == 0) #define FIFO_FULL(f) ((f)->used == (f)->size) #define FIFO_USED(f) ((f)->used) static void fifo_init(struct fifo *f, uint8_t buf[], uint8_t size) { f->used = 0; f->head = f->tail = 0; f->buf = buf; f->size = size; f->max_used = 0; } static void fifo_write(struct fifo *f, uint8_t b) { if(!FIFO_FULL(f)) { /* Only proceed if there's space */ f->used++; /* Keep track of the number of used bytes in the FIFO */ f->buf[f->head++] = b; /* Add to where head indexes */ if(f->head == f->size) { /* If head goes off the end of the FIFO buffer then wrap it */ f->head = 0; } } if(f->used > f->max_used) { /* For diagnostics keep a high-water mark of used space */ f->max_used = f->used; } } static uint8_t fifo_read(struct fifo *f) { uint8_t ret = 0; if(!FIFO_EMPTY(f)) { /* Only proceed if there's something there */ f->used--; /* Keep track of the used space */ ret = f->buf[f->tail++]; if(f->tail == f->size) { /* Wrap tail around if it goes off the end of the buffer */ f->tail = 0; } } return ret; } static struct fifo tx_fifo; static struct fifo rx_fifo; static uint8_t tx_buf[TX_FIFO_MAXSIZE]; static uint8_t rx_buf[RX_FIFO_MAXSIZE]; #define LOCK_INTERRUPTS() {cpu_irq_disable();} /* NB: SIDE-EFFECT MACRO! */ #define UNLOCK_INTERRUPTS() {cpu_irq_enable();} /* Main setup of ATmega640 USART * * Hardwired to asynchronous and not using clock doubler so will do 16 samples on receive (better for noise tolerance). * The baud parameter will be written straight into the baud rate register. */ //void init_serial(uint16_t baud) void init_serial() { /* Initialize FIFOs for UART */ fifo_init(&tx_fifo, tx_buf, TX_FIFO_MAXSIZE); fifo_init(&rx_fifo, rx_buf, RX_FIFO_MAXSIZE); } /* Handle interrupt generated when the transmit buffer is free to write to. */ int8_t serial_isend(uint8_t port) { uint8_t used = tx_fifo.used; /* Called when the transmit buffer can be filled */ if (used > 0) { uint8_t byte; byte = fifo_read(&tx_fifo); // Transfer UART RX fifo to CDC TX if (!udi_cdc_is_tx_ready()) { // Fifo full udi_cdc_signal_overrun(); return -2; } else { udi_cdc_putc(byte); } used = tx_fifo.used; if(used == 1U) { /* If it was just one byte in the FIFO then it will now be empty; stop interrupts until FIFO becomes not empty */ } } else if (used <= 1U) { /* There was either nothing to send (spurious interrupt) or else there is nothing to send now so must disable the UDREn interrupt * to stop interrupts - must be re-enabled when FIFO becomes not empty */ //UCSRnB(UART) &= ~(1U << UDRIEn); return -1; } return 0; } /* Handle receive interrupt. * * The CPU must handle the received bytes as fast as they come in (on average): there is no flow control. */ int8_t serial_ireceive(uint8_t port) { int val; /* TODO handle the error flags (DORn should be logged - it indicates the interrupt handling isn't fast enough; parity error frames should be discarded) */ // report_printf("rx.."); if (!udi_cdc_is_rx_ready()) return -1; // Make sure we consume all bytes.. while (udi_cdc_is_rx_ready()) { /* This read also clears down the interrupt */ val = udi_cdc_getc(); /* Write byte to FIFO; if there is no room in the FIFO the byte is discarded */ fifo_write(&rx_fifo, (uint8_t) val); // report_printf("rx: %02X", (uint8_t) val); } return 0; } /* Send n bytes to the given USART from the given source. Returns the number of bytes actually buffered. */ uint8_t serial_send(uint8_t *src, uint8_t n) { uint8_t written = 0; /* Interrupts are locked out only through the body of the loop so that transmission can * start as soon as there is data to send, which happens concurrently with filling the * FIFO */ while (n--) { LOCK_INTERRUPTS(); if (FIFO_FULL(&tx_fifo)) { n = 0; /* No space left, terminate the sending early */ } else { fifo_write(&tx_fifo, *(src++)); /* The FIFO is not empty so enable 'transmit buffer ready' interrupt * (may already be enabled but safe to re-enable it anyway). */ serial_isend(0); written++; } UNLOCK_INTERRUPTS(); } return written; } /* Read up to n bytes from the given USART into the given destination. Returns the number of bytes actually read. */ uint8_t serial_receive(uint8_t *dest, uint8_t n) { uint8_t read = 0; while (n--) { LOCK_INTERRUPTS(); if (FIFO_EMPTY(&rx_fifo)) { n = 0; /* Nothing left, terminate early */ } else { *(dest++) = fifo_read(&rx_fifo); read++; } UNLOCK_INTERRUPTS(); } return read; } uint8_t serial_send_space(void) { uint8_t ret; LOCK_INTERRUPTS(); ret = tx_fifo.size - tx_fifo.used; UNLOCK_INTERRUPTS(); return ret; } uint8_t serial_receive_ready(void) { uint8_t ret; LOCK_INTERRUPTS(); ret = rx_fifo.used; UNLOCK_INTERRUPTS(); return ret; }
C
#include "common.h" sNodeTree* gNodes; int gSizeNodes = 0; int gUsedNodes = 0; void init_nodes() { const int node_size = 32; if(gUsedNodes == 0) { gNodes = (sNodeTree*)xcalloc(1, sizeof(sNodeTree)*node_size); gSizeNodes = node_size; gUsedNodes = 1; // 0 of index means null } } void free_nodes() { if(gUsedNodes > 0) { int i; for(i=1; i<gUsedNodes; i++) { switch(gNodes[i].mNodeType) { case kNodeTypeBlock: if(gNodes[i].uValue.sBlock.mNodes) free(gNodes[i].uValue.sBlock.mNodes); free(gNodes[i].uValue.sBlock.mSource.mBuf); break; /* case kNodeTypeSwitch: free(gNodes[i].uValue.sSwitch.mSwitchExpression); break; */ default: break; } } free(gNodes); gSizeNodes = 0; gUsedNodes = 0; } } // return node index unsigned int alloc_node() { if(gSizeNodes == gUsedNodes) { int new_size = (gSizeNodes+1) * 2; gNodes = (sNodeTree*)xrealloc(gNodes, sizeof(sNodeTree)*new_size); gSizeNodes = new_size; } return gUsedNodes++; } unsigned int sNodeTree_create_int_value(int value, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeIntValue; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.mIntValue = value; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_char_value(char value, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCharValue; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.mCharValue = value; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_add(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAdd; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_sub(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeSub; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_mult(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeMult; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_div(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDiv; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_mod(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeMod; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_lshift(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLShift; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_rshift(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeRShift; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_or(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeOr; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_xor(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeXor; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_and(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAnd; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_pre_create_function(unsigned int function_params, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFunction; sVarTable* lv_table = init_var_table(); gNodes[node].uValue.sFunction.mLVTable = lv_table; cinfo.lv_table = lv_table; gNodes[node].uValue.sFunction.mNumParams = gNodes[function_params].uValue.sFunctionParams.mNumParams; int i; for(i=0; i<gNodes[function_params].uValue.sFunctionParams.mNumParams; i++) { sParserParam* param = gNodes[function_params].uValue.sFunctionParams.mParams + i; xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mName, param->mName, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mTypeName, param->mTypeName, VAR_NAME_MAX); char* var_name = param->mName; char* param_type = param->mTypeName; sNodeType* var_type = create_node_type_with_class_name(param_type); if(var_type == NULL || var_type->mClass == NULL) { fprintf(stderr, "%s %d: Invalid type name %s\n", gSName, yylineno, var_name); return FALSE; } BOOL constant = var_type->mConstant; BOOL global = FALSE; int index = -1; void* llvm_value = NULL; if(!add_variable_to_table(lv_table, var_name, var_type, llvm_value, index, global, constant)) { fprintf(stderr, "overflow variable table10"); return FALSE; } } return node; } unsigned int sNodeTree_create_function(unsigned int node, char* fun_name, char* fun_base_name, unsigned int function_params, char* result_type_name, unsigned int node_block, BOOL var_arg, BOOL inline_, BOOL static_, BOOL inherit_, BOOL generics, BOOL method_generics, char* sname, int sline) { xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sFunction.mVarArg = var_arg; gNodes[node].uValue.sFunction.mInline = inline_; gNodes[node].uValue.sFunction.mInherit = inherit_; gNodes[node].uValue.sFunction.mStatic = static_; gNodes[node].uValue.sFunction.mCoroutine = FALSE; gNodes[node].uValue.sFunction.mGenerics = generics; gNodes[node].uValue.sFunction.mMethodGenerics = method_generics; gNodes[node].uValue.sFunction.mExternal = FALSE; xstrncpy(gNodes[node].uValue.sFunction.mName, fun_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mBaseName, fun_base_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mResultTypeName, result_type_name, VAR_NAME_MAX); gNodes[node].uValue.sFunction.mNodeBlock = node_block; cinfo.pre_compiling_generics_function = generics || method_generics; if(!pre_compile(node, &cinfo)) { fprintf(stderr, "%s %d: faield to pre-compile\n", gSName, yylineno); exit(2); } if(!pre_compile_block(node_block, &cinfo)) { fprintf(stderr, "%s %d: faield to pre-compile\n", gSName, yylineno); exit(2); } cinfo.pre_compiling_generics_function = FALSE; return node; } unsigned int sNodeTree_create_block(BOOL create_lv_table, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeBlock; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sBlock.mSizeNodes = 32; gNodes[node].uValue.sBlock.mNumNodes = 0; gNodes[node].uValue.sBlock.mCreateLVTable = create_lv_table; gNodes[node].uValue.sBlock.mNodes = (unsigned int*)xcalloc(1, sizeof(unsigned int)*32); sBuf_init(&gNodes[node].uValue.sBlock.mSource); return node; } void append_node_to_node_block(unsigned int node_block, unsigned int node) { if(node == 0) { return; } if(gNodes[node_block].uValue.sBlock.mSizeNodes <= gNodes[node_block].uValue.sBlock.mNumNodes) { unsigned int new_size = gNodes[node_block].uValue.sBlock.mSizeNodes * 2; gNodes[node_block].uValue.sBlock.mNodes = (unsigned int*)xrealloc(gNodes[node_block].uValue.sBlock.mNodes, sizeof(unsigned int)*new_size); memset(gNodes[node_block].uValue.sBlock.mNodes + gNodes[node_block].uValue.sBlock.mSizeNodes, 0, sizeof(unsigned int)*(new_size-gNodes[node_block].uValue.sBlock.mSizeNodes)); gNodes[node_block].uValue.sBlock.mSizeNodes = new_size; } gNodes[node_block].uValue.sBlock.mNodes[gNodes[node_block].uValue.sBlock.mNumNodes] = node; gNodes[node_block].uValue.sBlock.mNumNodes++; } unsigned int sNodeTree_create_function_params(char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFunctionParams; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sFunctionParams.mNumParams = 0; memset(&gNodes[node].uValue.sFunctionParams.mParams, 0, sizeof(sParserParam)*PARAMS_MAX); return node; } void append_param_to_function_params(unsigned int function_params, char* type_name, char* name) { int num_params = gNodes[function_params].uValue.sFunctionParams.mNumParams; xstrncpy(gNodes[function_params].uValue.sFunctionParams.mParams[num_params].mName, name, VAR_NAME_MAX); xstrncpy(gNodes[function_params].uValue.sFunctionParams.mParams[num_params].mTypeName, type_name, VAR_NAME_MAX); gNodes[function_params].uValue.sFunctionParams.mNumParams++; if(gNodes[function_params].uValue.sFunctionParams.mNumParams >= PARAMS_MAX) { fprintf(stderr, "overflow parametor number\n"); exit(2); } } unsigned int sNodeTree_create_external_function(char* fun_name, unsigned int function_params, char* result_type_name, BOOL var_arg, BOOL inherite_, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeExternalFunction; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sFunction.mVarArg = var_arg; gNodes[node].uValue.sFunction.mInherit = inherite_; gNodes[node].uValue.sFunction.mCoroutine = FALSE; gNodes[node].uValue.sFunction.mGenerics = FALSE; gNodes[node].uValue.sFunction.mMethodGenerics = FALSE; gNodes[node].uValue.sFunction.mExternal = TRUE; xstrncpy(gNodes[node].uValue.sFunction.mName, fun_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mBaseName, fun_name, VAR_NAME_MAX); gNodes[node].uValue.sFunction.mNumParams = gNodes[function_params].uValue.sFunctionParams.mNumParams; int i; for(i=0; i<gNodes[function_params].uValue.sFunctionParams.mNumParams; i++) { sParserParam* param = gNodes[function_params].uValue.sFunctionParams.mParams + i; xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mName, param->mName, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mTypeName, param->mTypeName, VAR_NAME_MAX); } xstrncpy(gNodes[node].uValue.sFunction.mResultTypeName, result_type_name, VAR_NAME_MAX); gNodes[node].uValue.sFunction.mNodeBlock = 0; return node; } unsigned int sNodeTree_create_return(unsigned int right, unsigned int middle, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeReturn; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = right; gNodes[node].mMiddle = middle; return node; } unsigned int sNodeTree_create_store_variable(char* var_name, char* type_name, unsigned int right, BOOL alloc, BOOL global, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeStoreVariable; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sStoreVariable.mVarName, var_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sStoreVariable.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].uValue.sStoreVariable.mAlloc = alloc; gNodes[node].uValue.sStoreVariable.mGlobal = global; gNodes[node].mLeft = 0; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_params(char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeParams; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sParams.mNumParams = 0; memset(&gNodes[node].uValue.sParams.mParams, 0, sizeof(unsigned int)*PARAMS_MAX); return node; } void append_param_to_params(unsigned int params, unsigned int param) { int num_params = gNodes[params].uValue.sParams.mNumParams; gNodes[params].uValue.sParams.mParams[num_params] = param; gNodes[params].uValue.sParams.mNumParams++; if(gNodes[params].uValue.sParams.mNumParams >= PARAMS_MAX) { fprintf(stderr, "overflow parametor number\n"); exit(2); } } void append_param_to_params_at_head(unsigned int params, unsigned int param) { int num_params = gNodes[params].uValue.sParams.mNumParams; gNodes[params].uValue.sParams.mNumParams++; if(gNodes[params].uValue.sParams.mNumParams >= PARAMS_MAX) { fprintf(stderr, "overflow parametor number\n"); exit(2); } int i; for(i=num_params-1; i>0; i--) { gNodes[params].uValue.sParams.mParams[i] = gNodes[params].uValue.sParams.mParams[i-1]; } gNodes[params].uValue.sParams.mParams[0] = param; } unsigned int sNodeTree_create_function_call(char* fun_name, unsigned int params, BOOL message_passing, BOOL inherit_, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFunctionCall; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sFunctionCall.mMessagePassing = message_passing; gNodes[node].uValue.sFunctionCall.mLambdaCall = FALSE; gNodes[node].uValue.sFunctionCall.mInherit = inherit_; xstrncpy(gNodes[node].uValue.sFunctionCall.mFunName, fun_name, VAR_NAME_MAX); if(params > 0) { gNodes[node].uValue.sFunctionCall.mNumParams = gNodes[params].uValue.sParams.mNumParams; int i; for(i=0; i<gNodes[params].uValue.sParams.mNumParams; i++) { gNodes[node].uValue.sFunctionCall.mParams[i] = gNodes[params].uValue.sParams.mParams[i]; } } else { gNodes[node].uValue.sFunctionCall.mNumParams = 0; } return node; } unsigned int sNodeTree_create_load_variable(char* var_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLoadVariable; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sLoadVariable.mVarName, var_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_c_string(char* value, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCStringValue; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.mStrValue, value, 512); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_if(unsigned int if_exp, unsigned int if_block, int elif_num, unsigned int* elif_exps, unsigned int* elif_blocks, unsigned int else_block, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeIf; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sIf.mIfExp = if_exp; gNodes[node].uValue.sIf.mIfBlock = if_block; gNodes[node].uValue.sIf.mElifNum = elif_num; int i; for(i=0; i<elif_num; i++) { gNodes[node].uValue.sIf.mElifExps[i] = elif_exps[i]; gNodes[node].uValue.sIf.mElifBlocks[i] = elif_blocks[i]; } gNodes[node].uValue.sIf.mElseBlock = else_block; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_true(char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeTrue; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_false(char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFalse; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_null(char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeNull; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_object(char* type_name, unsigned int object_num, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCreateObject; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sCreateObject.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].mLeft = object_num; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_typedef(char* name, char* type_name, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeTypeDef; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; xstrncpy(gNodes[node].uValue.sTypeDef.mTypeName, type_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sTypeDef.mName, name, VAR_NAME_MAX); return node; } unsigned int sNodeTree_create_clone(unsigned int left, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeClone; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_delete(unsigned int left, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDelete; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_coroutine(unsigned int function_params, char* result_type_name, unsigned int node_block, BOOL var_arg, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCoroutine; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; static int coroutine_num = 0; coroutine_num++; char fun_name[VAR_NAME_MAX]; snprintf(fun_name, VAR_NAME_MAX, "coroutine%d", coroutine_num); gNodes[node].uValue.sFunction.mVarArg = var_arg; gNodes[node].uValue.sFunction.mInline = FALSE; gNodes[node].uValue.sFunction.mStatic = TRUE; gNodes[node].uValue.sFunction.mCoroutine = TRUE; gNodes[node].uValue.sFunction.mGenerics = FALSE; gNodes[node].uValue.sFunction.mInherit = FALSE; gNodes[node].uValue.sFunction.mExternal = FALSE; xstrncpy(gNodes[node].uValue.sFunction.mName, fun_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mBaseName, fun_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mResultTypeName, result_type_name, VAR_NAME_MAX); gNodes[node].uValue.sFunction.mNodeBlock = node_block; if(function_params > 0) { gNodes[node].uValue.sFunction.mNumParams = gNodes[function_params].uValue.sFunctionParams.mNumParams; int i; for(i=0; i<gNodes[function_params].uValue.sFunctionParams.mNumParams; i++) { sParserParam* param = gNodes[function_params].uValue.sFunctionParams.mParams + i; xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mName, param->mName, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sFunction.mParams[i].mTypeName, param->mTypeName, VAR_NAME_MAX); } } else { gNodes[node].uValue.sFunction.mNumParams = 0; } int num_params = gNodes[node].uValue.sFunction.mNumParams; return node; } unsigned int sNodeTree_create_struct_fields(char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFields; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sFields.mNumFields = 0; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } void append_field_to_fields(unsigned int fields, char* name, char* type_name) { int num_fields = gNodes[fields].uValue.sFields.mNumFields; xstrncpy(gNodes[fields].uValue.sFields.mNameFields[num_fields], name, VAR_NAME_MAX); xstrncpy(gNodes[fields].uValue.sFields.mTypeFields[num_fields], type_name, VAR_NAME_MAX); gNodes[fields].uValue.sFields.mNumFields++; if(gNodes[fields].uValue.sFields.mNumFields >= STRUCT_FIELD_MAX) { fprintf(stderr, "overflow field number\n"); exit(2); } } unsigned int sNodeTree_create_struct(char* struct_name, unsigned int fields, BOOL generics, BOOL anonymous, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeStruct; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sStruct.mName, struct_name, VAR_NAME_MAX); gNodes[node].uValue.sStruct.mFields = fields; gNodes[node].uValue.sStruct.mAnonymous = anonymous; gNodes[node].uValue.sStruct.mGenerics = generics; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_union(char* struct_name, unsigned int fields, BOOL anonymous, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeUnion; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sStruct.mName, struct_name, VAR_NAME_MAX); gNodes[node].uValue.sStruct.mFields = fields; gNodes[node].uValue.sStruct.mAnonymous = anonymous; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_define_variable(char* type_name, char* var_name, BOOL global, BOOL extern_, unsigned int init_value, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDefineVariable; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sDefineVariable.mVarName, var_name, VAR_NAME_MAX); xstrncpy(gNodes[node].uValue.sDefineVariable.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].uValue.sDefineVariable.mGlobal = global; gNodes[node].uValue.sDefineVariable.mExtern = extern_; gNodes[node].uValue.sDefineVariable.mInitValue = init_value; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; BOOL readonly = FALSE; BOOL constant = FALSE; void* llvm_value = NULL; int index = -1; return node; } unsigned int sNodeTree_create_equals(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeEquals; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_not_equals(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeNotEquals; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_gt(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeGT; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_lt(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLT; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_ge(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeGE; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_le(unsigned int left, unsigned int right, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLE; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_lambda_call(unsigned int lambda_node, unsigned int params, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFunctionCall; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = lambda_node; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; gNodes[node].uValue.sFunctionCall.mMessagePassing = FALSE; gNodes[node].uValue.sFunctionCall.mLambdaCall = TRUE; gNodes[node].uValue.sFunctionCall.mInherit = FALSE; xstrncpy(gNodes[node].uValue.sFunctionCall.mFunName, "", VAR_NAME_MAX); if(params > 0) { gNodes[node].uValue.sFunctionCall.mNumParams = gNodes[params].uValue.sParams.mNumParams; int i; for(i=0; i<gNodes[params].uValue.sParams.mNumParams; i++) { gNodes[node].uValue.sFunctionCall.mParams[i] = gNodes[params].uValue.sParams.mParams[i]; } } else { gNodes[node].uValue.sFunctionCall.mNumParams = 0; } return node; } unsigned int sNodeTree_create_load_field(char* name, unsigned int left_node, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLoadField; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sLoadField.mVarName, name, VAR_NAME_MAX); gNodes[node].mLeft = left_node; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_store_field(char* var_name, unsigned int left_node, unsigned int right_node, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeStoreField; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sStoreField.mVarName, var_name, VAR_NAME_MAX); gNodes[node].mLeft = left_node; gNodes[node].mRight = right_node; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_and_and(unsigned int left_node, unsigned int right_node, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAndAnd; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left_node; gNodes[node].mRight = right_node; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_or_or(unsigned int left_node, unsigned int right_node, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeOrOr; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left_node; gNodes[node].mRight = right_node; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_logical_denial(unsigned int left, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLogicalDenial; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_complement(unsigned int left, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeComplement; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_derefference(unsigned int left, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDerefference; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_refference(unsigned int left, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeRefference; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_plus_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypePlusEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_minus_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeMinusEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_mult_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeMultEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_div_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDivEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_mod_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeModEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_and_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAndEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_xor_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeXorEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_or_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeOrEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_lshift_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLShiftEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_rshift_eq(unsigned int left, unsigned int right, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeRShiftEq; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left; gNodes[node].mRight = right; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_load_array_element(unsigned int array, unsigned int index_node[], int num_dimention, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeLoadElement; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sLoadElement.mArrayDimentionNum = num_dimention; int i; for(i=0; i<num_dimention; i++) { gNodes[node].uValue.sLoadElement.mIndex[i] = index_node[num_dimention-i-1]; } gNodes[node].mLeft = array; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_store_element(unsigned int array, unsigned int index_node[], int num_dimention, unsigned int right_node, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeStoreElement; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sStoreElement.mArrayDimentionNum = num_dimention; int i; for(i=0; i<num_dimention; i++) { gNodes[node].uValue.sStoreElement.mIndex[i] = index_node[num_dimention-i-1]; } gNodes[node].mLeft = array; gNodes[node].mRight = right_node; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_array_initializer(int left, char* var_name, int num_array_value, unsigned int* array_values, BOOL global, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeArrayInitializer; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sArrayInitializer.mVarName, var_name, VAR_NAME_MAX); gNodes[node].uValue.sArrayInitializer.mNumArrayValue = num_array_value; memcpy(gNodes[node].uValue.sArrayInitializer.mArrayValues, array_values, sizeof(unsigned int)*INIT_ARRAY_MAX); gNodes[node].uValue.sArrayInitializer.mGlobal = global; gNodes[node].mLeft = left; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_while_statment(unsigned int expression_node, unsigned int while_node_block, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeWhile; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sWhile.mExpressionNode = expression_node; gNodes[node].uValue.sWhile.mWhileNodeBlock = while_node_block; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_do_while_expression(unsigned int expression_node, unsigned int while_node_block, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDoWhile; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sWhile.mExpressionNode = expression_node; gNodes[node].uValue.sWhile.mWhileNodeBlock = while_node_block; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_switch_statment(unsigned int expression_node, int num_switch_expression, unsigned int* switch_expression, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeSwitch; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sSwitch.mExpression = expression_node; memcpy(gNodes[node].uValue.sSwitch.mSwitchExpression, switch_expression, sizeof(unsigned int)*SWITCH_STASTMENT_NODE_MAX); gNodes[node].uValue.sSwitch.mNumSwitchExpression = num_switch_expression; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_case_expression(unsigned int expression_node, BOOL first_case, BOOL last_case, BOOL case_after_return, unsigned int first_statment, BOOL last_statment, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCase; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sCase.mExpression = expression_node; gNodes[node].uValue.sCase.mLastCase = last_case; gNodes[node].uValue.sCase.mFirstCase = first_case; gNodes[node].uValue.sCase.mCaseAfterReturn = case_after_return; gNodes[node].uValue.sCase.mFirstStatment = first_statment; gNodes[node].uValue.sCase.mLastStatment = last_statment; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_for_statment(unsigned int expression_node1, unsigned int expression_node2, unsigned int expression_node3, unsigned int for_node_block, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeFor; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].uValue.sFor.mExpressionNode = expression_node1; gNodes[node].uValue.sFor.mExpressionNode2 = expression_node2; gNodes[node].uValue.sFor.mExpressionNode3 = expression_node3; gNodes[node].uValue.sFor.mForNodeBlock = for_node_block; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_break_expression(char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeBreak; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_continue_expression(char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeContinue; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_cast(char* type_name, unsigned int left_node, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeCast; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = left_node; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; xstrncpy(gNodes[node].uValue.sCast.mTypeName, type_name, VAR_NAME_MAX); return node; } unsigned int sNodeTree_create_sizeof1(char* type_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeSizeOf1; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sSizeOf.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_isheap(char* type_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeIsHeap; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sIsHeap.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_sizeof2(char* var_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeSizeOf2; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sSizeOf.mVarName, var_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_alignof1(char* type_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAlignOf1; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sAlignOf.mTypeName, type_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_alignof2(char* var_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeAlignOf2; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sAlignOf.mVarName, var_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_conditional(unsigned int conditional, unsigned int value1, unsigned int value2, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeConditional; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = conditional; gNodes[node].mRight = value1; gNodes[node].mMiddle = value2; return node; } unsigned int sNodeTree_create_dummy_heap(unsigned int object_node, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeDummyHeap; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = object_node; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_managed(char* var_name, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeManaged; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; xstrncpy(gNodes[node].uValue.sManaged.mVarName, var_name, VAR_NAME_MAX); gNodes[node].mLeft = 0; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_borrow(unsigned int object_node, char* sname, int sline) { unsigned node = alloc_node(); gNodes[node].mNodeType = kNodeTypeBorrow; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = object_node; gNodes[node].mRight = 0; gNodes[node].mMiddle = 0; return node; } unsigned int sNodeTree_create_store_value_to_address(unsigned int address_node, unsigned int right_node, char* sname, int sline) { unsigned int node = alloc_node(); gNodes[node].mNodeType = kNodeTypeStoreAddress; xstrncpy(gNodes[node].mSName, sname, PATH_MAX); gNodes[node].mLine = sline; gNodes[node].mLeft = address_node; gNodes[node].mRight = right_node; gNodes[node].mMiddle = 0; return node; } void show_node(unsigned int node) { switch(gNodes[node].mNodeType) { case kNodeTypeIntValue: printf("int value %d\n", gNodes[node].uValue.mIntValue); break; case kNodeTypeBlock: { printf("block num nodes %d\n", gNodes[node].uValue.sBlock.mNumNodes); int i; for(i=0; i<gNodes[node].uValue.sBlock.mNumNodes; i++) { show_node(gNodes[node].uValue.sBlock.mNodes[i]); } } break; case kNodeTypeFunction: { printf("function name %s num_params %d\n", gNodes[node].uValue.sFunction.mName, gNodes[node].uValue.sFunction.mNumParams); puts("result_type"); puts(gNodes[node].uValue.sFunction.mResultTypeName); puts("params"); printf("num_params %d\n", gNodes[node].uValue.sFunction.mNumParams); int i; for(i=0; i<gNodes[node].uValue.sFunction.mNumParams; i++) { sParserParam* param = gNodes[node].uValue.sFunction.mParams + i; printf("param #%d\n", i); puts(param->mName); puts(param->mTypeName); } puts("block"); show_node(gNodes[node].uValue.sFunction.mNodeBlock); puts("block end"); } break; case kNodeTypeAdd: puts("add"); puts("left"); show_node(gNodes[node].mLeft); puts("right"); show_node(gNodes[node].mRight); break; case kNodeTypeSub: puts("sub"); puts("left"); show_node(gNodes[node].mLeft); puts("right"); show_node(gNodes[node].mRight); break; case kNodeTypeMult: puts("mult"); puts("left"); show_node(gNodes[node].mLeft); puts("right"); show_node(gNodes[node].mRight); break; case kNodeTypeDiv: puts("div"); puts("left"); show_node(gNodes[node].mLeft); puts("right"); show_node(gNodes[node].mRight); break; case kNodeTypeReturn: puts("return"); puts("left"); show_node(gNodes[node].mLeft); break; case kNodeTypeStoreVariable: puts("store variable"); break; default: printf("node type %d\n", gNodes[node].mNodeType); break; } }
C
#include <stdio.h> #include <stdlib.h> #include <log.h> #include "sparse_matrix.h" t_sm_node new_node(unsigned int pos, unsigned int value) { t_sm_node node; node.pos = pos; node.value = value; return node; } void free_node(t_sm_node *node) { /* free(*node); *node = NULL; */ } void print_node(t_sm_node n) { printf("(%u,%u)", n.pos, n.value); } t_sm_line cons_line(t_sm_node node, t_sm_line previous) { t_sm_line nl = malloc(sizeof(*nl)); if (nl == NULL) { //FATAL("Not enough memory"); exit(1); } else { NODE_SM_LINE(nl) = node; NEXT_SM_LINE(nl) = previous; return nl; } } void free_line(t_sm_line *line) { if (IS_EMPTY_SM_LINE(*line)) { return ; } else { t_sm_line *next = &NEXT_SM_LINE(*line); free_node(&NODE_SM_LINE(*line)); free_line(next); free(*line); } } void display_line_aux(t_sm_line l) { if (IS_EMPTY_SM_LINE(l)) { } else { print_node(NODE_SM_LINE(l)); display_line_aux(NEXT_SM_LINE(l)); } } void display_line_nl(t_sm_line l) { printf("<"); display_line_aux(l); printf(">\n"); } unsigned int sm_line_get_value(t_sm_line line, int column) { if (IS_EMPTY_SM_LINE(line)) { return 0; } else if (column < POS_SM_LINE(line)) { return 0; } else if (POS_SM_LINE(line) == column) { return VALUE_SM_LINE(line); } else { return sm_line_get_value(NEXT_SM_LINE(line), column); } } void sm_line_set_value(t_sm_line *line, int column, unsigned int value) { if (IS_EMPTY_SM_LINE(*line)) { *line = cons_line(new_node(column, value), *line); return ; } else if (column < POS_SM_LINE(*line)) { *line = cons_line(new_node(column, value), *line); return ; } else if (POS_SM_LINE(*line) == column) { VALUE_SM_LINE(*line) = value; return ; } else { sm_line_set_value(&NEXT_SM_LINE(*line), column, value); return ; } } /*************************************/ t_sparse_matrix new_sparse_matrix(int lines) { int i; t_sparse_matrix sm = malloc(sizeof(*sm)); sm->nbr_lines = lines; sm->lines = malloc(lines*sizeof(t_sm_line)); for (i = 0; i < lines; i++) { SM_LINE(sm, i) = EMPTY_SM_LINE; } return sm; } void free_sparse_matrix(t_sparse_matrix *sm) { int i; for (i = 0; i < SM_NBR_LINES(*sm); i++) { free_line(&SM_LINE(*sm, i)); } free((*sm)->lines); free(*sm); *sm = NULL; } unsigned int sm_get_value(t_sparse_matrix sm, int column, int line) { return sm_line_get_value(sm->lines[line], column); } void sm_set_value(t_sparse_matrix sm, int column, int line, unsigned int value) { if (value > 0) { return sm_line_set_value(&(sm->lines[line]), column, value); } } #if 0 int main() { t_sm_line line = EMPTY_SM_LINE; t_sparse_matrix sm; display_line_nl(line); sm_line_set_value(&line, 5, 17); display_line_nl(line); sm_line_set_value(&line, 3, 27); display_line_nl(line); sm_line_set_value(&line, 7, 14); display_line_nl(line); sm_line_set_value(&line, 7, 27); display_line_nl(line); sm_line_set_value(&line, 3, 23); display_line_nl(line); sm_line_set_value(&line, 5, 25); display_line_nl(line); printf("%u\n", sm_line_get_value(line, 3)); printf("%u\n", sm_line_get_value(line, 4)); printf("%u\n", sm_line_get_value(line, 5)); printf("%u\n", sm_line_get_value(line, 9)); free_line(&line); printf("TEST SM\n"); sm = new_sparse_matrix(20); printf("%u\n\n", sm_get_value(sm, 5, 10)); sm_set_value(sm, 5, 10, 14); printf("%u\n", sm_get_value(sm, 5, 10)); printf("%u\n\n", sm_get_value(sm, 5, 12)); sm_set_value(sm, 5, 12, 15); sm_set_value(sm, 5, 8, 13); printf("%u\n", sm_get_value(sm, 5, 8)); printf("%u\n", sm_get_value(sm, 5, 10)); printf("%u\n", sm_get_value(sm, 5, 11)); printf("%u\n", sm_get_value(sm, 5, 12)); free_sparse_matrix(&sm); return 0; } #endif
C
/** ************************************************************ ************************************************************ ************************************************************ * 文件名: EdpKit.c * * 作者: 张继瑞 * * 日期: 2017-09-13 * * 版本: V1.1 * * 说明: EDP协议 * * 修改记录: V1.1:将strncpy替换为memcpy,解决潜在bug ************************************************************ ************************************************************ ************************************************************ **/ //协议头文件 #include "EdpKit.h" //C库 #include <string.h> //========================================================== // 函数名称: EDP_NewBuffer // // 函数功能: 申请内存 // // 入口参数: edpPacket:包结构体 // size:大小 // // 返回参数: 无 // // 说明: 1.可使用动态分配来分配内存 // 2.可使用局部或全局数组来指定内存 //========================================================== void EDP_NewBuffer(EDP_PACKET_STRUCTURE *edpPacket, uint32 size) { uint32 i = 0; if(edpPacket->_data == NULL) { edpPacket->_memFlag = MEM_FLAG_ALLOC; edpPacket->_data = (uint8 *)EDP_MallocBuffer(size); if(edpPacket->_data != NULL) { edpPacket->_len = 0; edpPacket->_size = size; for(; i < edpPacket->_size; i++) edpPacket->_data[i] = 0; } } else { edpPacket->_memFlag = MEM_FLAG_STATIC; for(; i < edpPacket->_size; i++) edpPacket->_data[i] = 0; edpPacket->_len = 0; if(edpPacket->_size < size) edpPacket->_data = NULL; } } //========================================================== // 函数名称: EDP_DeleteBuffer // // 函数功能: 释放数据内存 // // 入口参数: edpPacket:包结构体 // // 返回参数: 无 // // 说明: 当使用的局部或全局数组时不释放内存 //========================================================== void EDP_DeleteBuffer(EDP_PACKET_STRUCTURE *edpPacket) { if(edpPacket->_memFlag == MEM_FLAG_ALLOC) EDP_FreeBuffer(edpPacket->_data); edpPacket->_data = NULL; edpPacket->_len = 0; edpPacket->_size = 0; edpPacket->_memFlag = MEM_FLAG_NULL; } //========================================================== // 函数名称: EDP_UnPacketRecv // // 函数功能: EDP数据接收类型判断 // // 入口参数: dataPtr:接收的数据指针 // // 返回参数: 0-成功 其他-失败原因 // // 说明: //========================================================== uint8 EDP_UnPacketRecv(uint8 *dataPtr) { return dataPtr[0]; } //========================================================== // 函数名称: EDP_PacketConnect1 // // 函数功能: 登录方式1组包 // // 入口参数: devid:设备ID // apikey:APIKEY // cTime:连接保持时间 // edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint1 EDP_PacketConnect1(const int8 *devid, const int8 *apikey, uint16 cTime, EDP_PACKET_STRUCTURE *edpPacket) { uint8 devid_len = strlen(devid); uint8 apikey_len = strlen(apikey); //分配内存--------------------------------------------------------------------- EDP_NewBuffer(edpPacket, 56); if(edpPacket->_data == NULL) return 1; //Byte0:连接类型-------------------------------------------------------------- edpPacket->_data[0] = CONNREQ; edpPacket->_len++; //Byte1:剩余消息长度---------------------------------------------------------- edpPacket->_data[1] = 13 + devid_len + apikey_len; edpPacket->_len++; //Byte2~3:协议名长度---------------------------------------------------------- edpPacket->_data[2] = 0; edpPacket->_data[3] = 3; edpPacket->_len += 2; //Byte4~6:协议名-------------------------------------------------------------- strncat((int8 *)edpPacket->_data + 4, "EDP", 3); edpPacket->_len += 3; //Byte7:协议版本-------------------------------------------------------------- edpPacket->_data[7] = 1; edpPacket->_len++; //Byte8:连接标志-------------------------------------------------------------- edpPacket->_data[8] = 0x40; edpPacket->_len++; //Byte9~10:连接保持时间------------------------------------------------------- edpPacket->_data[9] = MOSQ_MSB(cTime); edpPacket->_data[10] = MOSQ_LSB(cTime); edpPacket->_len += 2; //Byte11~12:DEVID长度--------------------------------------------------------- edpPacket->_data[11] = MOSQ_MSB(devid_len); edpPacket->_data[12] = MOSQ_LSB(devid_len); edpPacket->_len += 2; //Byte13~13+devid_len:DEVID--------------------------------------------------- strncat((int8 *)edpPacket->_data + 13, devid, devid_len); edpPacket->_len += devid_len; //Byte13+devid_len~13+devid_len+2:APIKEY长度---------------------------------- edpPacket->_data[13 + devid_len] = MOSQ_MSB(apikey_len); edpPacket->_data[14 + devid_len] = MOSQ_LSB(apikey_len); edpPacket->_len += 2; //Byte15+devid_len~15+devid_len+apikey_len:APIKEY----------------------------- strncat((int8 *)edpPacket->_data + 15 + devid_len, apikey, apikey_len); edpPacket->_len += apikey_len; return 0; } //========================================================== // 函数名称: EDP_PacketConnect2 // // 函数功能: 登录方式2组包 // // 入口参数: devid:设备ID // auth_key:鉴权信息 // cTime:连接保持时间 // edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint1 EDP_PacketConnect2(const int8 *proid, const int8 *auth_key, uint16 cTime, EDP_PACKET_STRUCTURE *edpPacket) { uint8 proid_len = strlen(proid); uint8 authkey_len = strlen(auth_key); //分配内存--------------------------------------------------------------------- EDP_NewBuffer(edpPacket, 56); if(edpPacket->_data == NULL) return 1; //Byte0:连接类型-------------------------------------------------------------- edpPacket->_data[0] = CONNREQ; edpPacket->_len++; //Byte1:剩余消息长度---------------------------------------------------------- edpPacket->_data[1] = 15 + proid_len + authkey_len; edpPacket->_len++; //Byte2~3:协议名长度---------------------------------------------------------- edpPacket->_data[2] = 0; edpPacket->_data[3] = 3; edpPacket->_len += 2; //Byte4~6:协议名-------------------------------------------------------------- strncat((int8 *)edpPacket->_data + 4, "EDP", 3); edpPacket->_len += 3; //Byte7:协议版本-------------------------------------------------------------- edpPacket->_data[7] = 1; edpPacket->_len++; //Byte8:连接标志-------------------------------------------------------------- edpPacket->_data[8] = 0xC0; edpPacket->_len++; //Byte9~10:连接保持时间------------------------------------------------------- edpPacket->_data[9] = MOSQ_MSB(cTime); edpPacket->_data[10] = MOSQ_LSB(cTime); edpPacket->_len += 2; //Byte11~12:DEVID长度--------------------------------------------------------- edpPacket->_data[11] = 0; edpPacket->_data[12] = 0; edpPacket->_len += 2; //Byte13~14:PROID长度--------------------------------------------------------- edpPacket->_data[13] = MOSQ_MSB(proid_len); edpPacket->_data[14] = MOSQ_LSB(proid_len); edpPacket->_len += 2; //Byte15~15+proid_len:RPOID--------------------------------------------------- strncat((int8 *)edpPacket->_data + 15, proid, proid_len); edpPacket->_len += proid_len; //Byte15+devid_len~15+proid_len+1:APIKEY长度---------------------------------- edpPacket->_data[15 + proid_len] = MOSQ_MSB(authkey_len); edpPacket->_data[16 + proid_len] = MOSQ_LSB(authkey_len); edpPacket->_len += 2; //Byte17+proid_len~17+proid_len+apikey_len:APIKEY----------------------------- strncat((int8 *)edpPacket->_data + 17 + proid_len, auth_key, authkey_len); edpPacket->_len += authkey_len; return 0; } //========================================================== // 函数名称: EDP_UnPacketConnectRsp // // 函数功能: 连接回复解包 // // 入口参数: rev_data:接收到的数据 // // 返回参数: 登录结果 // // 说明: //========================================================== uint8 EDP_UnPacketConnectRsp(uint8 *rev_data) { //0 连接成功 //1 验证失败:协议错误 //2 验证失败:设备ID鉴权失败 //3 验证失败:服务器失败 //4 验证失败:用户ID鉴权失败 //5 验证失败:未授权 //6 验证失败:授权码无效 //7 验证失败:激活码未分配 //8 验证失败:该设备已被激活 //9 验证失败:重复发送连接请求包 return rev_data[3]; } int32 WriteRemainlen(uint8 *buf, uint32 len_val, uint16 write_pos) { int32 remaining_count = 0; uint8 byte = 0; do { byte = len_val % 128; len_val = len_val >> 7; /* If there are more digits to encode, set the top bit of this digit */ if (len_val > 0) { byte = byte | 0x80; } buf[write_pos++] = byte; remaining_count++; } while(len_val > 0 && remaining_count < 5); return --write_pos; } int32 ReadRemainlen(int8 *buf, uint32 *len_val, uint16 read_pos) { uint32 multiplier = 1; uint32 len_len = 0; uint8 onebyte = 0; *len_val = 0; do { onebyte = buf[read_pos++]; *len_val += (onebyte & 0x7f) * multiplier; multiplier <<= 7; len_len++; if (len_len > 4) { return -1;/*len of len more than 4;*/ } } while((onebyte & 0x80) != 0); return read_pos; } //========================================================== // 函数名称: EDP_PacketSaveJson // // 函数功能: 封装协议头 // // 入口参数: devid:设备ID(可为空) // send_buf:json缓存buf // send_len:json总长 // type_bin_head:bin文件的消息头 // type:类型 // edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: 当不为Type2的时候,type_bin_head可为NULL //========================================================== uint8 EDP_PacketSaveData(const int8 *devid, int16 send_len, int8 *type_bin_head, SaveDataType type, EDP_PACKET_STRUCTURE *edpPacket) { int16 remain_len = 0; uint8 devid_len = strlen(devid); if(type == 2 && type_bin_head == NULL) return 1; if(type == 2) EDP_NewBuffer(edpPacket, strlen(type_bin_head)); else EDP_NewBuffer(edpPacket, send_len + 24); if(edpPacket->_data == NULL) return 2; //Byte0:消息类型-------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = SAVEDATA; if(devid) { if(type == 2) remain_len = 12 + strlen(type_bin_head) + send_len; else remain_len = 8 + send_len + devid_len; //剩余消息长度------------------------------------------------------------- edpPacket->_len += WriteRemainlen(edpPacket->_data, remain_len, edpPacket->_len); //标志--bit7:1-有devid,0-无devid bit6:1-有消息编号,0-无消息编号---- edpPacket->_data[edpPacket->_len++] = 0xC0; //DEVID长度--------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = 0; edpPacket->_data[edpPacket->_len++] = devid_len; //DEVID------------------------------------------------------------------ strncat((int8 *)edpPacket->_data + edpPacket->_len, devid, devid_len); edpPacket->_len += devid_len; //消息编号---------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = MSG_ID_HIGH; edpPacket->_data[edpPacket->_len++] = MSG_ID_LOW; } else { if(type == 2) remain_len = 10 + strlen(type_bin_head) + send_len; else remain_len = 6 + send_len; //剩余消息长度------------------------------------------------------------ edpPacket->_len += WriteRemainlen(edpPacket->_data, remain_len, edpPacket->_len); //标志--bit7:1-有devid,0-无devid bit6:1-有消息编号,0-无消息编号---- edpPacket->_data[edpPacket->_len++] = 0x40; //消息编号---------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = MSG_ID_HIGH; edpPacket->_data[edpPacket->_len++] = MSG_ID_LOW; } edpPacket->_data[edpPacket->_len++] = type; if(type == 2) { uint8 type_bin_head_len = strlen(type_bin_head); uint8 i = 0; //消息头长度--------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = MOSQ_MSB(type_bin_head_len); edpPacket->_data[edpPacket->_len++] = MOSQ_LSB(type_bin_head_len); //消息头------------------------------------------------------------------- for(; i < type_bin_head_len; i++) edpPacket->_data[edpPacket->_len++] = type_bin_head[i]; //图片长度----------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = (uint8)(send_len >> 24); edpPacket->_data[edpPacket->_len++] = (uint8)(send_len >> 16); edpPacket->_data[edpPacket->_len++] = (uint8)(send_len >> 8); edpPacket->_data[edpPacket->_len++] = (uint8)send_len; } else { //json长度----------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = MOSQ_MSB(send_len); edpPacket->_data[edpPacket->_len++] = MOSQ_LSB(send_len); } return 0; } //========================================================== // 函数名称: EDP_PacketPushData // // 函数功能: PushData功能组包 // // 入口参数: devid:设备ID // msg:推送数据 // msg_len:推送的数据长度 // edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint8 EDP_PacketPushData(const int8 *devid, const int8 *msg, uint32 msg_len, EDP_PACKET_STRUCTURE *edpPacket) { uint32 remain_len = 2 + strlen(devid) + msg_len; uint8 devid_len = strlen(devid); uint16 i = 0; uint16 size = 5 + strlen(devid) + msg_len; if(devid == NULL || msg == NULL || msg_len == 0) return 1; EDP_NewBuffer(edpPacket, size); if(edpPacket->_data == NULL) return 2; //Byte0:pushdata类型----------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = PUSHDATA; //剩余长度---------------------------------------------------------------------- edpPacket->_len += WriteRemainlen(edpPacket->_data, remain_len, edpPacket->_len); //DEVID长度--------------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = MOSQ_MSB(devid_len); edpPacket->_data[edpPacket->_len++] = MOSQ_LSB(devid_len); //写入DEVID--------------------------------------------------------------------- for(; i < devid_len; i++) edpPacket->_data[edpPacket->_len++] = devid[i]; //写入数据---------------------------------------------------------------------- for(i = 0; i < msg_len; i++) edpPacket->_data[edpPacket->_len++] = msg[i]; return 0; } //========================================================== // 函数名称: EDP_UnPacketPushData // // 函数功能: PushData功能解包 // // 入口参数: rev_data:收到的数据 // src_devid:源devid缓存 // req:命令缓存 // req_len:命令长度 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint8 EDP_UnPacketPushData(uint8 *rev_data, int8 **src_devid, int8 **req, uint32 *req_len) { int32 read_pos = 0; uint32 remain_len = 0; uint16 devid_len = 0; //Byte0:PushData消息------------------------------------------------------------ if(rev_data[read_pos++] != PUSHDATA) return 1; //读取剩余长度-------------------------------------------------------------------- read_pos = ReadRemainlen((int8 *)rev_data, &remain_len, read_pos); if(read_pos == -1) return 2; //读取源devid长度----------------------------------------------------------------- devid_len = (uint16)rev_data[read_pos] << 8 | rev_data[read_pos + 1]; read_pos += 2; //分配内存------------------------------------------------------------------------ *src_devid = (int8 *)EDP_MallocBuffer(devid_len + 1); if(*src_devid == NULL) return 3; //读取源devid--------------------------------------------------------------------- memset(*src_devid, 0, devid_len + 1); memcpy(*src_devid, (const int8 *)rev_data + read_pos, devid_len); read_pos += devid_len; remain_len -= 2 + devid_len; //分配内存------------------------------------------------------------------------ *req = (int8 *)EDP_MallocBuffer(remain_len + 1); if(*req == NULL) { EDP_FreeBuffer(*src_devid); return 4; } //读取命令------------------------------------------------------------------------ memset(*req, 0, remain_len + 1); memcpy(*req, (const int8 *)rev_data + read_pos, remain_len); read_pos += remain_len; *req_len = remain_len; return 0; } //========================================================== // 函数名称: EDP_UnPacketCmd // // 函数功能: 下发命令解包 // // 入口参数: rev_data:收到的数据 // cmdid:cmdid // cmdid_len:cmdid长度 // req:命令 // req_len:命令长度 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint8 EDP_UnPacketCmd(uint8 *rev_data, int8 **cmdid, uint16 *cmdid_len, int8 **req, uint32 *req_len) { uint32 remain_len = 0; int32 read_pos = 0; //Byte0:PushData消息------------------------------------------------------------ if(rev_data[read_pos++] != CMDREQ) return 1; //读取剩余长度-------------------------------------------------------------------- read_pos = ReadRemainlen((int8 *)rev_data, &remain_len, read_pos); if(read_pos == -1) return 2; //读取cmdid长度------------------------------------------------------------------- *cmdid_len = (uint16)rev_data[read_pos] << 8 | rev_data[read_pos + 1]; read_pos += 2; //分配内存------------------------------------------------------------------------ *cmdid = (int8 *)EDP_MallocBuffer(*cmdid_len + 1); if(*cmdid == NULL) return 3; //读取cmdid----------------------------------------------------------------------- memset(*cmdid, 0, *cmdid_len + 1); memcpy(*cmdid, (const int8 *)rev_data + read_pos, *cmdid_len); read_pos += *cmdid_len; //读取req长度--------------------------------------------------------------------- *req_len = (uint32)rev_data[read_pos] << 24 | (uint32)rev_data[read_pos + 1] << 16 | (uint32)rev_data[read_pos + 2] << 8 | (uint32)rev_data[read_pos + 3]; read_pos += 4; //分配内存------------------------------------------------------------------------ *req = (int8 *)EDP_MallocBuffer(*req_len + 1); if(*req == NULL) { EDP_FreeBuffer(*cmdid); return 4; } //读取req------------------------------------------------------------------------- memset(*req, 0, *req_len + 1); memcpy(*req, (const int8 *)rev_data + read_pos, *req_len); read_pos += *req_len; return 0; } //========================================================== // 函数名称: EDP_PacketCmdResp // // 函数功能: 命令回复组包 // // 入口参数: cmdid:命令的cmdid(随命令下发) // cmdid_len:cmdid长度 // req:命令 // req_len:命令长度 // edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint1 EDP_PacketCmdResp(const int8 *cmdid, uint16 cmdid_len, const int8 *resp, uint32 resp_len, EDP_PACKET_STRUCTURE *edpPacket) { uint32 remain_len = cmdid_len + resp_len + (resp_len ? 6 : 2); EDP_NewBuffer(edpPacket, remain_len + 5); if(edpPacket->_data == NULL) return 1; //Byte0:CMDRESP消息------------------------------------------------------------ edpPacket->_data[edpPacket->_len++] = CMDRESP; //写入剩余长度------------------------------------------------------------------ edpPacket->_len += WriteRemainlen(edpPacket->_data, remain_len, edpPacket->_len); //写入cmdid长度------------------------------------------------------------------ edpPacket->_data[edpPacket->_len++] = cmdid_len >> 8; edpPacket->_data[edpPacket->_len++] = cmdid_len & 0x00FF; //写入cmdid---------------------------------------------------------------------- memcpy((int8 *)edpPacket->_data + edpPacket->_len, cmdid, cmdid_len); edpPacket->_len += cmdid_len; if(resp_len) { //写入req长度----------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = (uint8)(resp_len >> 24); edpPacket->_data[edpPacket->_len++] = (uint8)(resp_len >> 16); edpPacket->_data[edpPacket->_len++] = (uint8)(resp_len >> 8); edpPacket->_data[edpPacket->_len++] = (uint8)(resp_len & 0x00FF); //写入req--------------------------------------------------------------------- memcpy((int8 *)edpPacket->_data + edpPacket->_len, resp, resp_len); edpPacket->_len += resp_len; } return 0; } //========================================================== // 函数名称: EDP_PacketPing // // 函数功能: 心跳请求组包 // // 入口参数: edpPacket:包指针 // // 返回参数: 0-成功 1-失败 // // 说明: //========================================================== uint1 EDP_PacketPing(EDP_PACKET_STRUCTURE *edpPacket) { EDP_NewBuffer(edpPacket, 2); if(edpPacket->_data == NULL) return 1; //Byte0:PINGREQ消息------------------------------------------------------------ edpPacket->_data[edpPacket->_len++] = PINGREQ; //Byte1:0---------------------------------------------------------------------- edpPacket->_data[edpPacket->_len++] = 0; return 0; }
C
/* Public domain */ /* * This application demonstrates use of the AG_Pane container widget. */ #include "agartest.h" static AG_Window * SettingsWindow(void *obj, AG_Pane *paneHoriz, AG_Pane *paneVert) { const char *actions[] = { "EXPAND_DIV1", "EXPAND_DIV2", "DIVIDE_EVEN", "DIVIDE_PCT", NULL }; AG_Window *win; /* Settings window */ if ((win = AG_WindowNew(0)) == NULL) { return (NULL); } AG_WindowSetCaption(win, "AG_Pane(3) settings"); AG_LabelNew(win, 0, "(Horiz. Pane) Resize action:"); AG_RadioNewUint(win, 0, actions, (void *)&paneHoriz->resizeAction); AG_LabelNew(win, 0, "(Horiz. Pane) Flags:"); AG_CheckboxNewFlag(win, 0, "DIV1FILL", &paneHoriz->flags, AG_PANE_DIV1FILL); AG_CheckboxNewFlag(win, 0, "FRAME", &paneHoriz->flags, AG_PANE_FRAME); AG_CheckboxNewFlag(win, 0, "UNMOVABLE", &paneHoriz->flags, AG_PANE_UNMOVABLE); AG_SeparatorNewHoriz(win); AG_LabelNew(win, 0, "(Vert. Pane) Resize action:"); AG_RadioNewUint(win, 0, actions, (void *)&paneVert->resizeAction); AG_LabelNew(win, 0, "(Vert. Pane) Flags:"); AG_CheckboxNewFlag(win, 0, "DIV1FILL", &paneVert->flags, AG_PANE_DIV1FILL); AG_CheckboxNewFlag(win, 0, "FRAME", &paneVert->flags, AG_PANE_FRAME); AG_CheckboxNewFlag(win, 0, "UNMOVABLE", &paneVert->flags, AG_PANE_UNMOVABLE); return (win); } static int TestGUI(void *obj, AG_Window *win) { AG_Pane *paneHoriz, *paneVert; AG_Window *winSettings; /* Divide the window horizontally */ paneHoriz = AG_PaneNewHoriz(win, AG_PANE_EXPAND); { /* Divide the left pane vertically */ paneVert = AG_PaneNewVert(paneHoriz->div[0], AG_PANE_EXPAND); AG_LabelNew(paneVert->div[0], 0, "Left/Top"); AG_LabelNew(paneVert->div[1], 0, "Left/Bottom"); AG_PaneMoveDividerPct(paneVert, 30); } AG_LabelNew(paneHoriz->div[1], 0, "Right"); AG_PaneMoveDividerPct(paneHoriz, 50); AG_WindowSetGeometry(win, -1, -1, 320, 240); AG_WindowShow(win); if ((winSettings = SettingsWindow(obj, paneHoriz, paneVert)) != NULL) { AG_WindowAttach(win, winSettings); AG_WindowShow(winSettings); } return (0); } const AG_TestCase paneTest = { "pane", N_("Test the AG_Pane(3) container widget"), "1.4.2", 0, sizeof(AG_TestInstance), NULL, /* init */ NULL, /* destroy */ NULL, /* test */ TestGUI, NULL /* bench */ };
C
int sum(int n) /*@ requires n >= 0 ensures res = n * (n+1) * (n+2) /3; */ { if (n ==0) return 3; else return n*(n+1) + sum(n-1); }
C
#define Measure 2 //Mode select #include <Servo.h> // Include Servo library Servo myservo; // These two ends are used for chao sheng bo chuan gan qi int URECHO = 4; // PWM Output 0-25000US,Every 50US represent 1cm int URTRIG = 5; // PWM trigger pin int sensorPin = A0; // select the input pin for the potentiometer int sensorValue = 0; // variable to store he value coming from the sensor int EnablePin1 = 11; int EnablePin2 = 3; int wall = 0; // left wall; int pos = 0; // the degree of the 舵机 int in[4] = {7, 8 , 12, 13}; //小车的右边位0度,左边为180度 void setup() { Serial.begin(9600); // Sets the baud rate to 9600 pinMode(URTRIG,OUTPUT); // A low pull on pin COMP/TRIG digitalWrite(URTRIG,HIGH); // Set to HIGH pinMode(URECHO, INPUT); myservo.attach(6); // Set to HIGH // In1 In2 In3 In4 pinMode(in[0], OUTPUT); pinMode(in[1], OUTPUT); pinMode(in[2], OUTPUT); pinMode(in[3], OUTPUT); pinMode(EnablePin1, OUTPUT); // right pinMode(EnablePin2, OUTPUT); // left myservo.write(0); pos = 0; if(getDistance() < 40) { //wall is on the right Serial.println("right wall"); wall = 1; } else { // wall is on the left Serial.println("left wall"); myservo.write(180); pos = 180; } delay(1000) analogWrite(EnablePin1, 80); analogWrite(EnablePin2, 80); move_straight(); } void loop() { int distance = getDistance(); myservo.write(pos); move_straight(); if (distance < 10) { //距离很小时转向 if (wall == 0) { //wall is on the left turn_right(); delay(500); move_straight(); delay(500); turn_left(); delay(500); } else { //wall is on the right turn_left(); delay(500); move_straight(); delay(500); turn_right(); delay(500); } } else if (distance < 60) { //距离再10到50之间直走 move_straight(); delay(500); } else { //距离很大时转向 if (wall == 0) { //wall is on the left delay(500); turn_left(); delay(500); move_straight(); delay(500); turn_right(); delay(500); } else { //wall is on the right turn_right(); delay(500); move_straight(); delay(500); turn_left(); delay(500); } } } void turn_left() { pos += 60; // 舵机先转60度 myservo.write(pos); analogWrite(EnablePin2, 60); delay(60); analogWrite(EnablePin2, 80) } void turn_right() { pos -= 60; // 舵机先转60度 analogWrite(EnablePin1, 60); delay(60); analogWrite(EnablePin1, 80) } void move_straight() { pos = 90; myservo.write(pos); digitalWrite(in[0], LOW); digitalWrite(in[1], HIGH); digitalWrite(in[2], LOW); digitalWrite(in[3], HIGH); } int getDistance() { digitalWrite(URTRIG, LOW); digitalWrite(URTRIG, HIGH); int DistanceMeasured; unsigned long LowLevelTime = pulseIn(URECHO, LOW) ; if(LowLevelTime>=45000) { return 9999; } else { DistanceMeasured = LowLevelTime /50; Serial.print(DistanceMeasured); Serial.println("cm"); return DistanceMeasured; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /* 表达式转换 算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。 输入格式: 输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。 输出格式: 在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。 输入样例: 2+3*(7-4)+8/4 输出样例: 2 3 7 4 - * + 8 4 / + */ //此题开始有一个测试点未过,因为只考虑了-有两种形式,符号和运算符;对于+,未考虑其为符号 //我想说的是,真是为了出题而出题,虽然代码量没有因此增加,但正数把符号+加上,滑稽...... char stack[30]; int top=-1; int getnum(char data[],int loc)//返回此运算数的字符形式有几个字符 { if((data[loc]=='-'||data[loc]=='+')&&loc-1>=0&&(isdigit(data[loc-1])||data[loc-1]==')'))//+和-的特殊情况,此时为运算符,不是符号 return 0; int count=0; if(data[loc]=='-'||data[loc]=='+'){ count++; loc++; } while(data[loc]&&strchr("+-*/()",data[loc])==NULL){ count++; loc++; } return count; } void deal(char ch) { if(ch=='+'){ while(top>=0&&stack[top]!='(') printf(" %c",stack[top--]); stack[++top]='+'; } else if(ch=='-'){ while(top>=0&&stack[top]!='(') printf(" %c",stack[top--]); stack[++top]='-'; } else if(ch=='*'){ while(top>=0&&stack[top]!='('&&stack[top]!='+'&&stack[top]!='-') printf(" %c",stack[top--]); stack[++top]='*'; } else if(ch=='/'){ while(top>=0&&stack[top]!='('&&stack[top]!='+'&&stack[top]!='-') printf(" %c",stack[top--]); stack[++top]='/'; } return; } int main() { int i,j; int flag=0;//用来判断此字符前输不输出空格 char data[30];//原始数据 gets(data); for(i=0;data[i];i++){ int num; if((num=getnum(data,i))!=0){//如果为运算数 char temp[30];//存运算数的字符串形式 for(j=0;j<num;j++) temp[j]=data[i+j]; temp[j]='\n'; i=i+num-1;//更新i double result=atof(temp); if(flag) printf(" %g",result); else printf("%g",result); flag=1; } else if(data[i]=='(') stack[++top]='(';//(入栈 else if(data[i]==')'){//()内运算符出栈 while(stack[top]!='('){ printf(" %c",stack[top--]); } top--; } else if(strchr("+-*/",data[i])!=NULL){//为运算符 deal(data[i]); } } for(int i=top;i>=0;i--)//弹出栈内剩余运算符 printf(" %c",stack[i]); return 0; }
C
#include <stdio.h> int main(int argc, char *argv[]) { int a = 2; int b = 3; printf("a / b = %.3f\n", a/b); // causa um Warning. Tipo de resposta incompatível. Resultado inesperado. printf("a / b = %.3f\n", (double) a/b); return 0; }
C
/* 07:˽Ƽ 鿴 ύ ͳ ʱ: 1000ms ڴ: 65536kB 2008걱˻ᣬA˶ԱnľĿ (1n17)ҪͳһAõĽͭĿ ܽ n1У1AĿnnУ ÿһǸùijһõĽͭĿ һոֿ 1У4ΪAõĽͭ ܽһոֿ 3 1 0 3 3 1 0 0 3 0 4 4 3 11 */ #include <stdio.h> int main () { int n,i,j,a[4],b[4]={0},sum; scanf("%d",&n); for (i=1;i<=n;i++){ for(j=1;j<=3;j++){ scanf("%d",&a[j]); b[j]+=a[j]; sum+=a[j]; } } printf("%d %d %d %d",b[1],b[2],b[3],sum); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <string.h> #include <stdlib.h> #include "ChildCheck.h" #include "v1.h" #define SIZE_ROWS 9 #define SIZE_COLS 9 int main(int argc, char* argv[]) { if (argc < 1) { dup2(11, STDOUT_FILENO); printf("Error no input for childCheck...\n"); exit(1); } readSodukusFromPipe(argv[0]); } void readSodukusFromPipe(char* task) { int sodukuOnTheWay; scanf("%d", &sodukuOnTheWay); cleanBuffer(); while (sodukuOnTheWay == 0) { // if you are here there is another Soduku to read manageSodukuFromPipe(task); scanf("%d", &sodukuOnTheWay); } cleanBuffer(); } void cleanBuffer() { dup2(11, STDOUT_FILENO); printf("\n"); //clean the buffer dup2(10, STDOUT_FILENO); } void manageSodukuFromPipe(char* task) { int num; int soduku[9][9]; int i, j; int ans; int test; for (i = 0; i < SIZE_ROWS; i++) { for (j = 0; j < SIZE_COLS; j++) { scanf("%d", &num); soduku[i][j] = num; } } test = atoi(task); switch (test) { case 0: ans = checkRows((int*) soduku); //here we write the answer to pipe printf("%d\n", ans); break; case 1: ans = checkCols((int*) soduku); //here we write the answer to pipe printf("%d\n", ans); break; case 2: ans = checkSquares((int*) soduku); //here we write the answer to pipe printf("%d\n", ans); break; } } int checkRows(int* mat) { int i, sum = 0; for (i = 0; i < SIZE_ROWS; i++) { sum += checkOneRow(mat + i * SIZE_COLS); } if (sum == 9) return 1; else return 0; } int checkOneRow(int* row) { int res[9] = { 0 }; int i; for (i = 0; i < 9; i++) { int n = (row[i]) - 1; if (res[n] == 0) { res[n]++; } else { return 0; } } return 1; } int checkCols(int* mat) { int j, sum = 0; for (j = 0; j < SIZE_COLS; j++) { sum += checkOneCol(mat, j); } if (sum == 9) return 1; else return 0; } int checkOneCol(int* mat, int j) { int i; int res[9] = { 0 }; for (i = 0; i < SIZE_ROWS; i++) { int n = *(mat + i * SIZE_COLS + j) - 1; if (res[n] == 0) { res[n]++; } else { return 0; } } return 1; } int checkSquares(int* mat) { int i, j, sum = 0; for (i = 0; i < SIZE_ROWS; i += 3) { for (j = 0; j < SIZE_COLS; j += 3) { sum += checkOneSquare(mat + i * SIZE_COLS + j); } } if (sum == 9) return 1; else return 0; } int checkOneSquare(int* mat) { int i, j; int res[9] = { 0 }; for (i = 0; i < SIZE_ROWS / 3; i++) { for (j = 0; j < SIZE_COLS / 3; j++) { if (res[*(mat + (SIZE_ROWS * i + j)) - 1] == 0) { res[*(mat + (SIZE_COLS * i + j)) - 1]++; } else { return 0; } } } return 1; } void printMatrix(int* mat) { int i, j; printf("\n"); for (i = 0; i < SIZE_ROWS; i++) { for (j = 0; j < SIZE_COLS; j++) { printf("%d ", *(mat + i * SIZE_COLS + j)); } printf("\n"); } printf("\n\n"); }
C
/* * Code generated from Atmel Start. * * This file will be overwritten when reconfiguring your Atmel Start project. * Please copy examples or other code you want to keep to a separate file * to avoid losing it when reconfiguring. */ #ifndef ATMEL_START_PINS_H_INCLUDED #define ATMEL_START_PINS_H_INCLUDED #include <port.h> /** * \brief Set J12_18 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_18_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(0, pull_mode); } /** * \brief Set J12_18 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_18_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(0, dir); } /** * \brief Set J12_18 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_18_set_level(const bool level) { PORTA_set_pin_level(0, level); } /** * \brief Toggle output level on J12_18 * * Toggle the pin level */ static inline void J12_18_toggle_level() { PORTA_toggle_pin_level(0); } /** * \brief Get level on J12_18 * * Reads the level on a pin */ static inline bool J12_18_get_level() { return PORTA_get_pin_level(0); } /** * \brief Set J12_17 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_17_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(1, pull_mode); } /** * \brief Set J12_17 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_17_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(1, dir); } /** * \brief Set J12_17 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_17_set_level(const bool level) { PORTA_set_pin_level(1, level); } /** * \brief Toggle output level on J12_17 * * Toggle the pin level */ static inline void J12_17_toggle_level() { PORTA_toggle_pin_level(1); } /** * \brief Get level on J12_17 * * Reads the level on a pin */ static inline bool J12_17_get_level() { return PORTA_get_pin_level(1); } /** * \brief Set J12_16 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_16_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(2, pull_mode); } /** * \brief Set J12_16 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_16_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(2, dir); } /** * \brief Set J12_16 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_16_set_level(const bool level) { PORTA_set_pin_level(2, level); } /** * \brief Toggle output level on J12_16 * * Toggle the pin level */ static inline void J12_16_toggle_level() { PORTA_toggle_pin_level(2); } /** * \brief Get level on J12_16 * * Reads the level on a pin */ static inline bool J12_16_get_level() { return PORTA_get_pin_level(2); } /** * \brief Set J12_15 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_15_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(3, pull_mode); } /** * \brief Set J12_15 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_15_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(3, dir); } /** * \brief Set J12_15 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_15_set_level(const bool level) { PORTA_set_pin_level(3, level); } /** * \brief Toggle output level on J12_15 * * Toggle the pin level */ static inline void J12_15_toggle_level() { PORTA_toggle_pin_level(3); } /** * \brief Get level on J12_15 * * Reads the level on a pin */ static inline bool J12_15_get_level() { return PORTA_get_pin_level(3); } /** * \brief Set J12_14 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_14_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(4, pull_mode); } /** * \brief Set J12_14 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_14_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(4, dir); } /** * \brief Set J12_14 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_14_set_level(const bool level) { PORTA_set_pin_level(4, level); } /** * \brief Toggle output level on J12_14 * * Toggle the pin level */ static inline void J12_14_toggle_level() { PORTA_toggle_pin_level(4); } /** * \brief Get level on J12_14 * * Reads the level on a pin */ static inline bool J12_14_get_level() { return PORTA_get_pin_level(4); } /** * \brief Set J12_13 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_13_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(5, pull_mode); } /** * \brief Set J12_13 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_13_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(5, dir); } /** * \brief Set J12_13 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_13_set_level(const bool level) { PORTA_set_pin_level(5, level); } /** * \brief Toggle output level on J12_13 * * Toggle the pin level */ static inline void J12_13_toggle_level() { PORTA_toggle_pin_level(5); } /** * \brief Get level on J12_13 * * Reads the level on a pin */ static inline bool J12_13_get_level() { return PORTA_get_pin_level(5); } /** * \brief Set J12_12 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_12_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(6, pull_mode); } /** * \brief Set J12_12 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_12_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(6, dir); } /** * \brief Set J12_12 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_12_set_level(const bool level) { PORTA_set_pin_level(6, level); } /** * \brief Toggle output level on J12_12 * * Toggle the pin level */ static inline void J12_12_toggle_level() { PORTA_toggle_pin_level(6); } /** * \brief Get level on J12_12 * * Reads the level on a pin */ static inline bool J12_12_get_level() { return PORTA_get_pin_level(6); } /** * \brief Set J12_11 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_11_set_pull_mode(const enum port_pull_mode pull_mode) { PORTA_set_pin_pull_mode(7, pull_mode); } /** * \brief Set J12_11 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_11_set_dir(const enum port_dir dir) { PORTA_set_pin_dir(7, dir); } /** * \brief Set J12_11 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_11_set_level(const bool level) { PORTA_set_pin_level(7, level); } /** * \brief Toggle output level on J12_11 * * Toggle the pin level */ static inline void J12_11_toggle_level() { PORTA_toggle_pin_level(7); } /** * \brief Get level on J12_11 * * Reads the level on a pin */ static inline bool J12_11_get_level() { return PORTA_get_pin_level(7); } /** * \brief Set M406A2 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M406A2_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(0, pull_mode); } /** * \brief Set M406A2 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M406A2_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(0, dir); } /** * \brief Set M406A2 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M406A2_set_level(const bool level) { PORTB_set_pin_level(0, level); } /** * \brief Toggle output level on M406A2 * * Toggle the pin level */ static inline void M406A2_toggle_level() { PORTB_toggle_pin_level(0); } /** * \brief Get level on M406A2 * * Reads the level on a pin */ static inline bool M406A2_get_level() { return PORTB_get_pin_level(0); } /** * \brief Set M406A1 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M406A1_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(1, pull_mode); } /** * \brief Set M406A1 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M406A1_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(1, dir); } /** * \brief Set M406A1 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M406A1_set_level(const bool level) { PORTB_set_pin_level(1, level); } /** * \brief Toggle output level on M406A1 * * Toggle the pin level */ static inline void M406A1_toggle_level() { PORTB_toggle_pin_level(1); } /** * \brief Get level on M406A1 * * Reads the level on a pin */ static inline bool M406A1_get_level() { return PORTB_get_pin_level(1); } /** * \brief Set M406A0 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M406A0_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(2, pull_mode); } /** * \brief Set M406A0 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M406A0_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(2, dir); } /** * \brief Set M406A0 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M406A0_set_level(const bool level) { PORTB_set_pin_level(2, level); } /** * \brief Toggle output level on M406A0 * * Toggle the pin level */ static inline void M406A0_toggle_level() { PORTB_toggle_pin_level(2); } /** * \brief Get level on M406A0 * * Reads the level on a pin */ static inline bool M406A0_get_level() { return PORTB_get_pin_level(2); } /** * \brief Set M407E2 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M407E2_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(3, pull_mode); } /** * \brief Set M407E2 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M407E2_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(3, dir); } /** * \brief Set M407E2 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M407E2_set_level(const bool level) { PORTB_set_pin_level(3, level); } /** * \brief Toggle output level on M407E2 * * Toggle the pin level */ static inline void M407E2_toggle_level() { PORTB_toggle_pin_level(3); } /** * \brief Get level on M407E2 * * Reads the level on a pin */ static inline bool M407E2_get_level() { return PORTB_get_pin_level(3); } /** * \brief Set M407E1 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M407E1_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(4, pull_mode); } /** * \brief Set M407E1 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M407E1_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(4, dir); } /** * \brief Set M407E1 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M407E1_set_level(const bool level) { PORTB_set_pin_level(4, level); } /** * \brief Toggle output level on M407E1 * * Toggle the pin level */ static inline void M407E1_toggle_level() { PORTB_toggle_pin_level(4); } /** * \brief Get level on M407E1 * * Reads the level on a pin */ static inline bool M407E1_get_level() { return PORTB_get_pin_level(4); } /** * \brief Set M407A2 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M407A2_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(5, pull_mode); } /** * \brief Set M407A2 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M407A2_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(5, dir); } /** * \brief Set M407A2 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M407A2_set_level(const bool level) { PORTB_set_pin_level(5, level); } /** * \brief Toggle output level on M407A2 * * Toggle the pin level */ static inline void M407A2_toggle_level() { PORTB_toggle_pin_level(5); } /** * \brief Get level on M407A2 * * Reads the level on a pin */ static inline bool M407A2_get_level() { return PORTB_get_pin_level(5); } /** * \brief Set M407A1 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M407A1_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(6, pull_mode); } /** * \brief Set M407A1 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M407A1_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(6, dir); } /** * \brief Set M407A1 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M407A1_set_level(const bool level) { PORTB_set_pin_level(6, level); } /** * \brief Toggle output level on M407A1 * * Toggle the pin level */ static inline void M407A1_toggle_level() { PORTB_toggle_pin_level(6); } /** * \brief Get level on M407A1 * * Reads the level on a pin */ static inline bool M407A1_get_level() { return PORTB_get_pin_level(6); } /** * \brief Set M407A0 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M407A0_set_pull_mode(const enum port_pull_mode pull_mode) { PORTB_set_pin_pull_mode(7, pull_mode); } /** * \brief Set M407A0 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M407A0_set_dir(const enum port_dir dir) { PORTB_set_pin_dir(7, dir); } /** * \brief Set M407A0 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M407A0_set_level(const bool level) { PORTB_set_pin_level(7, level); } /** * \brief Toggle output level on M407A0 * * Toggle the pin level */ static inline void M407A0_toggle_level() { PORTB_toggle_pin_level(7); } /** * \brief Get level on M407A0 * * Reads the level on a pin */ static inline bool M407A0_get_level() { return PORTB_get_pin_level(7); } /** * \brief Set J12_3 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_3_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(0, pull_mode); } /** * \brief Set J12_3 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_3_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(0, dir); } /** * \brief Set J12_3 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_3_set_level(const bool level) { PORTC_set_pin_level(0, level); } /** * \brief Toggle output level on J12_3 * * Toggle the pin level */ static inline void J12_3_toggle_level() { PORTC_toggle_pin_level(0); } /** * \brief Get level on J12_3 * * Reads the level on a pin */ static inline bool J12_3_get_level() { return PORTC_get_pin_level(0); } /** * \brief Set J12_4 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_4_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(1, pull_mode); } /** * \brief Set J12_4 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_4_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(1, dir); } /** * \brief Set J12_4 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_4_set_level(const bool level) { PORTC_set_pin_level(1, level); } /** * \brief Toggle output level on J12_4 * * Toggle the pin level */ static inline void J12_4_toggle_level() { PORTC_toggle_pin_level(1); } /** * \brief Get level on J12_4 * * Reads the level on a pin */ static inline bool J12_4_get_level() { return PORTC_get_pin_level(1); } /** * \brief Set J12_5 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_5_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(2, pull_mode); } /** * \brief Set J12_5 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_5_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(2, dir); } /** * \brief Set J12_5 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_5_set_level(const bool level) { PORTC_set_pin_level(2, level); } /** * \brief Toggle output level on J12_5 * * Toggle the pin level */ static inline void J12_5_toggle_level() { PORTC_toggle_pin_level(2); } /** * \brief Get level on J12_5 * * Reads the level on a pin */ static inline bool J12_5_get_level() { return PORTC_get_pin_level(2); } /** * \brief Set J12_6 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_6_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(3, pull_mode); } /** * \brief Set J12_6 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_6_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(3, dir); } /** * \brief Set J12_6 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_6_set_level(const bool level) { PORTC_set_pin_level(3, level); } /** * \brief Toggle output level on J12_6 * * Toggle the pin level */ static inline void J12_6_toggle_level() { PORTC_toggle_pin_level(3); } /** * \brief Get level on J12_6 * * Reads the level on a pin */ static inline bool J12_6_get_level() { return PORTC_get_pin_level(3); } /** * \brief Set J12_7 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_7_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(4, pull_mode); } /** * \brief Set J12_7 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_7_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(4, dir); } /** * \brief Set J12_7 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_7_set_level(const bool level) { PORTC_set_pin_level(4, level); } /** * \brief Toggle output level on J12_7 * * Toggle the pin level */ static inline void J12_7_toggle_level() { PORTC_toggle_pin_level(4); } /** * \brief Get level on J12_7 * * Reads the level on a pin */ static inline bool J12_7_get_level() { return PORTC_get_pin_level(4); } /** * \brief Set J12_8 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_8_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(5, pull_mode); } /** * \brief Set J12_8 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_8_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(5, dir); } /** * \brief Set J12_8 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_8_set_level(const bool level) { PORTC_set_pin_level(5, level); } /** * \brief Toggle output level on J12_8 * * Toggle the pin level */ static inline void J12_8_toggle_level() { PORTC_toggle_pin_level(5); } /** * \brief Get level on J12_8 * * Reads the level on a pin */ static inline bool J12_8_get_level() { return PORTC_get_pin_level(5); } /** * \brief Set J12_9 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_9_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(6, pull_mode); } /** * \brief Set J12_9 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_9_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(6, dir); } /** * \brief Set J12_9 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_9_set_level(const bool level) { PORTC_set_pin_level(6, level); } /** * \brief Toggle output level on J12_9 * * Toggle the pin level */ static inline void J12_9_toggle_level() { PORTC_toggle_pin_level(6); } /** * \brief Get level on J12_9 * * Reads the level on a pin */ static inline bool J12_9_get_level() { return PORTC_get_pin_level(6); } /** * \brief Set J12_10 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void J12_10_set_pull_mode(const enum port_pull_mode pull_mode) { PORTC_set_pin_pull_mode(7, pull_mode); } /** * \brief Set J12_10 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void J12_10_set_dir(const enum port_dir dir) { PORTC_set_pin_dir(7, dir); } /** * \brief Set J12_10 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void J12_10_set_level(const bool level) { PORTC_set_pin_level(7, level); } /** * \brief Toggle output level on J12_10 * * Toggle the pin level */ static inline void J12_10_toggle_level() { PORTC_toggle_pin_level(7); } /** * \brief Get level on J12_10 * * Reads the level on a pin */ static inline bool J12_10_get_level() { return PORTC_get_pin_level(7); } /** * \brief Set EXTINT pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void EXTINT_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(0, pull_mode); } /** * \brief Set EXTINT data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void EXTINT_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(0, dir); } /** * \brief Set EXTINT level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void EXTINT_set_level(const bool level) { PORTD_set_pin_level(0, level); } /** * \brief Toggle output level on EXTINT * * Toggle the pin level */ static inline void EXTINT_toggle_level() { PORTD_toggle_pin_level(0); } /** * \brief Get level on EXTINT * * Reads the level on a pin */ static inline bool EXTINT_get_level() { return PORTD_get_pin_level(0); } /** * \brief Set ADCRDY pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADCRDY_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(1, pull_mode); } /** * \brief Set ADCRDY data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADCRDY_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(1, dir); } /** * \brief Set ADCRDY level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADCRDY_set_level(const bool level) { PORTD_set_pin_level(1, level); } /** * \brief Toggle output level on ADCRDY * * Toggle the pin level */ static inline void ADCRDY_toggle_level() { PORTD_toggle_pin_level(1); } /** * \brief Get level on ADCRDY * * Reads the level on a pin */ static inline bool ADCRDY_get_level() { return PORTD_get_pin_level(1); } /** * \brief Set ADCDO pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADCDO_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(2, pull_mode); } /** * \brief Set ADCDO data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADCDO_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(2, dir); } /** * \brief Set ADCDO level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADCDO_set_level(const bool level) { PORTD_set_pin_level(2, level); } /** * \brief Toggle output level on ADCDO * * Toggle the pin level */ static inline void ADCDO_toggle_level() { PORTD_toggle_pin_level(2); } /** * \brief Get level on ADCDO * * Reads the level on a pin */ static inline bool ADCDO_get_level() { return PORTD_get_pin_level(2); } /** * \brief Set ADCDI pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADCDI_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(3, pull_mode); } /** * \brief Set ADCDI data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADCDI_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(3, dir); } /** * \brief Set ADCDI level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADCDI_set_level(const bool level) { PORTD_set_pin_level(3, level); } /** * \brief Toggle output level on ADCDI * * Toggle the pin level */ static inline void ADCDI_toggle_level() { PORTD_toggle_pin_level(3); } /** * \brief Get level on ADCDI * * Reads the level on a pin */ static inline bool ADCDI_get_level() { return PORTD_get_pin_level(3); } /** * \brief Set ADCSC pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADCSC_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(4, pull_mode); } /** * \brief Set ADCSC data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADCSC_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(4, dir); } /** * \brief Set ADCSC level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADCSC_set_level(const bool level) { PORTD_set_pin_level(4, level); } /** * \brief Toggle output level on ADCSC * * Toggle the pin level */ static inline void ADCSC_toggle_level() { PORTD_toggle_pin_level(4); } /** * \brief Get level on ADCSC * * Reads the level on a pin */ static inline bool ADCSC_get_level() { return PORTD_get_pin_level(4); } /** * \brief Set LED1 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void LED1_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(5, pull_mode); } /** * \brief Set LED1 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void LED1_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(5, dir); } /** * \brief Set LED1 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void LED1_set_level(const bool level) { PORTD_set_pin_level(5, level); } /** * \brief Toggle output level on LED1 * * Toggle the pin level */ static inline void LED1_toggle_level() { PORTD_toggle_pin_level(5); } /** * \brief Get level on LED1 * * Reads the level on a pin */ static inline bool LED1_get_level() { return PORTD_get_pin_level(5); } /** * \brief Set CUR1_10 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void CUR1_10_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(6, pull_mode); } /** * \brief Set CUR1_10 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void CUR1_10_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(6, dir); } /** * \brief Set CUR1_10 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void CUR1_10_set_level(const bool level) { PORTD_set_pin_level(6, level); } /** * \brief Toggle output level on CUR1_10 * * Toggle the pin level */ static inline void CUR1_10_toggle_level() { PORTD_toggle_pin_level(6); } /** * \brief Get level on CUR1_10 * * Reads the level on a pin */ static inline bool CUR1_10_get_level() { return PORTD_get_pin_level(6); } /** * \brief Set ADCCLK pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADCCLK_set_pull_mode(const enum port_pull_mode pull_mode) { PORTD_set_pin_pull_mode(7, pull_mode); } /** * \brief Set ADCCLK data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADCCLK_set_dir(const enum port_dir dir) { PORTD_set_pin_dir(7, dir); } /** * \brief Set ADCCLK level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADCCLK_set_level(const bool level) { PORTD_set_pin_level(7, level); } /** * \brief Toggle output level on ADCCLK * * Toggle the pin level */ static inline void ADCCLK_toggle_level() { PORTD_toggle_pin_level(7); } /** * \brief Get level on ADCCLK * * Reads the level on a pin */ static inline bool ADCCLK_get_level() { return PORTD_get_pin_level(7); } /** * \brief Set RxD0 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void RxD0_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(0, pull_mode); } /** * \brief Set RxD0 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void RxD0_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(0, dir); } /** * \brief Set RxD0 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void RxD0_set_level(const bool level) { PORTE_set_pin_level(0, level); } /** * \brief Toggle output level on RxD0 * * Toggle the pin level */ static inline void RxD0_toggle_level() { PORTE_toggle_pin_level(0); } /** * \brief Get level on RxD0 * * Reads the level on a pin */ static inline bool RxD0_get_level() { return PORTE_get_pin_level(0); } /** * \brief Set TxD0 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void TxD0_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(1, pull_mode); } /** * \brief Set TxD0 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void TxD0_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(1, dir); } /** * \brief Set TxD0 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void TxD0_set_level(const bool level) { PORTE_set_pin_level(1, level); } /** * \brief Toggle output level on TxD0 * * Toggle the pin level */ static inline void TxD0_toggle_level() { PORTE_toggle_pin_level(1); } /** * \brief Get level on TxD0 * * Reads the level on a pin */ static inline bool TxD0_get_level() { return PORTE_get_pin_level(1); } /** * \brief Set TxE pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void TxE_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(2, pull_mode); } /** * \brief Set TxE data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void TxE_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(2, dir); } /** * \brief Set TxE level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void TxE_set_level(const bool level) { PORTE_set_pin_level(2, level); } /** * \brief Toggle output level on TxE * * Toggle the pin level */ static inline void TxE_toggle_level() { PORTE_toggle_pin_level(2); } /** * \brief Get level on TxE * * Reads the level on a pin */ static inline bool TxE_get_level() { return PORTE_get_pin_level(2); } /** * \brief Set RES1K pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void RES1K_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(3, pull_mode); } /** * \brief Set RES1K data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void RES1K_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(3, dir); } /** * \brief Set RES1K level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void RES1K_set_level(const bool level) { PORTE_set_pin_level(3, level); } /** * \brief Toggle output level on RES1K * * Toggle the pin level */ static inline void RES1K_toggle_level() { PORTE_toggle_pin_level(3); } /** * \brief Get level on RES1K * * Reads the level on a pin */ static inline bool RES1K_get_level() { return PORTE_get_pin_level(3); } /** * \brief Set RES1OHM pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void RES1OHM_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(4, pull_mode); } /** * \brief Set RES1OHM data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void RES1OHM_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(4, dir); } /** * \brief Set RES1OHM level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void RES1OHM_set_level(const bool level) { PORTE_set_pin_level(4, level); } /** * \brief Toggle output level on RES1OHM * * Toggle the pin level */ static inline void RES1OHM_toggle_level() { PORTE_toggle_pin_level(4); } /** * \brief Get level on RES1OHM * * Reads the level on a pin */ static inline bool RES1OHM_get_level() { return PORTE_get_pin_level(4); } /** * \brief Set TCL pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void TCL_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(5, pull_mode); } /** * \brief Set TCL data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void TCL_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(5, dir); } /** * \brief Set TCL level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void TCL_set_level(const bool level) { PORTE_set_pin_level(5, level); } /** * \brief Toggle output level on TCL * * Toggle the pin level */ static inline void TCL_toggle_level() { PORTE_toggle_pin_level(5); } /** * \brief Get level on TCL * * Reads the level on a pin */ static inline bool TCL_get_level() { return PORTE_get_pin_level(5); } /** * \brief Set M406E pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M406E_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(6, pull_mode); } /** * \brief Set M406E data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M406E_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(6, dir); } /** * \brief Set M406E level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M406E_set_level(const bool level) { PORTE_set_pin_level(6, level); } /** * \brief Toggle output level on M406E * * Toggle the pin level */ static inline void M406E_toggle_level() { PORTE_toggle_pin_level(6); } /** * \brief Get level on M406E * * Reads the level on a pin */ static inline bool M406E_get_level() { return PORTE_get_pin_level(6); } /** * \brief Set M406A3 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M406A3_set_pull_mode(const enum port_pull_mode pull_mode) { PORTE_set_pin_pull_mode(7, pull_mode); } /** * \brief Set M406A3 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M406A3_set_dir(const enum port_dir dir) { PORTE_set_pin_dir(7, dir); } /** * \brief Set M406A3 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M406A3_set_level(const bool level) { PORTE_set_pin_level(7, level); } /** * \brief Toggle output level on M406A3 * * Toggle the pin level */ static inline void M406A3_toggle_level() { PORTE_toggle_pin_level(7); } /** * \brief Get level on M406A3 * * Reads the level on a pin */ static inline bool M406A3_get_level() { return PORTE_get_pin_level(7); } /** * \brief Set FREE pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void FREE_set_pull_mode(const enum port_pull_mode pull_mode) { PORTF_set_pin_pull_mode(0, pull_mode); } /** * \brief Set FREE data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void FREE_set_dir(const enum port_dir dir) { PORTF_set_pin_dir(0, dir); } /** * \brief Set FREE level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void FREE_set_level(const bool level) { PORTF_set_pin_level(0, level); } /** * \brief Toggle output level on FREE * * Toggle the pin level */ static inline void FREE_toggle_level() { PORTF_toggle_pin_level(0); } /** * \brief Get level on FREE * * Reads the level on a pin */ static inline bool FREE_get_level() { return PORTF_get_pin_level(0); } /** * \brief Set LED2 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void LED2_set_pull_mode(const enum port_pull_mode pull_mode) { PORTF_set_pin_pull_mode(1, pull_mode); } /** * \brief Set LED2 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void LED2_set_dir(const enum port_dir dir) { PORTF_set_pin_dir(1, dir); } /** * \brief Set LED2 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void LED2_set_level(const bool level) { PORTF_set_pin_level(1, level); } /** * \brief Toggle output level on LED2 * * Toggle the pin level */ static inline void LED2_toggle_level() { PORTF_toggle_pin_level(1); } /** * \brief Get level on LED2 * * Reads the level on a pin */ static inline bool LED2_get_level() { return PORTF_get_pin_level(1); } /** * \brief Set EDATA pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void EDATA_set_pull_mode(const enum port_pull_mode pull_mode) { PORTF_set_pin_pull_mode(2, pull_mode); } /** * \brief Set EDATA data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void EDATA_set_dir(const enum port_dir dir) { PORTF_set_pin_dir(2, dir); } /** * \brief Set EDATA level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void EDATA_set_level(const bool level) { PORTF_set_pin_level(2, level); } /** * \brief Toggle output level on EDATA * * Toggle the pin level */ static inline void EDATA_toggle_level() { PORTF_toggle_pin_level(2); } /** * \brief Get level on EDATA * * Reads the level on a pin */ static inline bool EDATA_get_level() { return PORTF_get_pin_level(2); } /** * \brief Set EN_EDATA pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void EN_EDATA_set_pull_mode(const enum port_pull_mode pull_mode) { PORTF_set_pin_pull_mode(3, pull_mode); } /** * \brief Set EN_EDATA data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void EN_EDATA_set_dir(const enum port_dir dir) { PORTF_set_pin_dir(3, dir); } /** * \brief Set EN_EDATA level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void EN_EDATA_set_level(const bool level) { PORTF_set_pin_level(3, level); } /** * \brief Toggle output level on EN_EDATA * * Toggle the pin level */ static inline void EN_EDATA_toggle_level() { PORTF_toggle_pin_level(3); } /** * \brief Get level on EN_EDATA * * Reads the level on a pin */ static inline bool EN_EDATA_get_level() { return PORTF_get_pin_level(3); } /** * \brief Set M408A0 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M408A0_set_pull_mode(const enum port_pull_mode pull_mode) { PORTG_set_pin_pull_mode(0, pull_mode); } /** * \brief Set M408A0 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M408A0_set_dir(const enum port_dir dir) { PORTG_set_pin_dir(0, dir); } /** * \brief Set M408A0 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M408A0_set_level(const bool level) { PORTG_set_pin_level(0, level); } /** * \brief Toggle output level on M408A0 * * Toggle the pin level */ static inline void M408A0_toggle_level() { PORTG_toggle_pin_level(0); } /** * \brief Get level on M408A0 * * Reads the level on a pin */ static inline bool M408A0_get_level() { return PORTG_get_pin_level(0); } /** * \brief Set M408A1 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M408A1_set_pull_mode(const enum port_pull_mode pull_mode) { PORTG_set_pin_pull_mode(1, pull_mode); } /** * \brief Set M408A1 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M408A1_set_dir(const enum port_dir dir) { PORTG_set_pin_dir(1, dir); } /** * \brief Set M408A1 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M408A1_set_level(const bool level) { PORTG_set_pin_level(1, level); } /** * \brief Toggle output level on M408A1 * * Toggle the pin level */ static inline void M408A1_toggle_level() { PORTG_toggle_pin_level(1); } /** * \brief Get level on M408A1 * * Reads the level on a pin */ static inline bool M408A1_get_level() { return PORTG_get_pin_level(1); } /** * \brief Set M408A2 pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M408A2_set_pull_mode(const enum port_pull_mode pull_mode) { PORTG_set_pin_pull_mode(2, pull_mode); } /** * \brief Set M408A2 data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M408A2_set_dir(const enum port_dir dir) { PORTG_set_pin_dir(2, dir); } /** * \brief Set M408A2 level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M408A2_set_level(const bool level) { PORTG_set_pin_level(2, level); } /** * \brief Toggle output level on M408A2 * * Toggle the pin level */ static inline void M408A2_toggle_level() { PORTG_toggle_pin_level(2); } /** * \brief Get level on M408A2 * * Reads the level on a pin */ static inline bool M408A2_get_level() { return PORTG_get_pin_level(2); } /** * \brief Set M408E pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void M408E_set_pull_mode(const enum port_pull_mode pull_mode) { PORTG_set_pin_pull_mode(3, pull_mode); } /** * \brief Set M408E data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void M408E_set_dir(const enum port_dir dir) { PORTG_set_pin_dir(3, dir); } /** * \brief Set M408E level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void M408E_set_level(const bool level) { PORTG_set_pin_level(3, level); } /** * \brief Toggle output level on M408E * * Toggle the pin level */ static inline void M408E_toggle_level() { PORTG_toggle_pin_level(3); } /** * \brief Get level on M408E * * Reads the level on a pin */ static inline bool M408E_get_level() { return PORTG_get_pin_level(3); } /** * \brief Set ADRESET pull mode * * Configure pin to pull up, down or disable pull mode, supported pull * modes are defined by device used * * \param[in] pull_mode Pin pull mode */ static inline void ADRESET_set_pull_mode(const enum port_pull_mode pull_mode) { PORTG_set_pin_pull_mode(4, pull_mode); } /** * \brief Set ADRESET data direction * * Select if the pin data direction is input, output or disabled. * If disabled state is not possible, this function throws an assert. * * \param[in] direction PORT_DIR_IN = Data direction in * PORT_DIR_OUT = Data direction out * PORT_DIR_OFF = Disables the pin * (low power state) */ static inline void ADRESET_set_dir(const enum port_dir dir) { PORTG_set_pin_dir(4, dir); } /** * \brief Set ADRESET level * * Sets output level on a pin * * \param[in] level true = Pin level set to "high" state * false = Pin level set to "low" state */ static inline void ADRESET_set_level(const bool level) { PORTG_set_pin_level(4, level); } /** * \brief Toggle output level on ADRESET * * Toggle the pin level */ static inline void ADRESET_toggle_level() { PORTG_toggle_pin_level(4); } /** * \brief Get level on ADRESET * * Reads the level on a pin */ static inline bool ADRESET_get_level() { return PORTG_get_pin_level(4); } #endif /* ATMEL_START_PINS_H_INCLUDED */
C
/** * @copyright * Copyright (c) 2016-2021 Stanislav Ivochkin * * Licensed under the MIT License (see LICENSE) */ #ifndef EMBEDJSON_AMALGAMATE #pragma once #include "common.h" #endif /* EMBEDJSON_AMALGAMATE */ /** * JSON lexer. Transforms input stream of bytes into a stream * of tokens defined by JSON grammar. * * For instance, a string {[:"foo"10 will be transformed into * a series "open curly bracket", "open bracket", "colon", * "string 'foo'", "integer 10". * * Lexer does not take into consideration meaning of the tokens, * so a string "{{{{" will be successfully handled. Syntax checks * are performed by a higher-level abstraction - parser. * * @note JSON strings are not accumulated by the lexer - only user * provided buffers are used to provide string values to the caller. * That's why each JSON string value is transformed into a possibly * empty series of embedjson_tokenc calls. * * A new string chunk is created each time one of the following events occurs: * - a buffer provided for embedjson_lexer_push function is parsed * to the end, while lexer is in the LEXER_STATE_IN_STRING state; * - ASCII escape sequence is found in the string; * - Unicode escape sequence is found in the string. * * For the user's convenience, two supplementary methods that wrap a sequence of * embedjson_tokenc calls are invoked by the lexer during parsing: * - embedjson_tokenc_begin * - embedjson_tokenc_end */ typedef struct embedjson_lexer { unsigned char state; unsigned char offset; char unicode_cp[2]; unsigned char encoding : 3; unsigned char magic_bytes_read : 3; char minus : 1; char exp_minus : 1; char exp_not_empty : 1; /** * Magic sequence for encoding guessing */ union { char as_char[4]; int as_int; } magic; embedjson_int_t int_value; unsigned long long frac_value; unsigned short frac_power; unsigned short exp_value; #if EMBEDJSON_VALIDATE_UTF8 /** * Number of bytes remaining to complete multibyte UTF-8 sequence */ unsigned char nb; /** * Corner cases for shortest possible UTF-8 encoding issue. * * See http://www.unicode.org/versions/corrigendum1.html for detailed * explanation of the issue and provided solution. * * Possible values are: * * @li 1 - for code points U+0800..U+0FFF. For these code points three bytes * are needed for encoding. If the first byte value is \xe0 (11100000), then * allowed values for the second byte are not \x80..\xbf, but \xa0..\xbf. * * @li 2 - for code points U+10000..U+3FFFF. For these code points four bytes * are needed for encoding. If the first byte value is \xf0 (11110000), then * allowed values for the second byte are not \x80..\xbf, but \x90..\xbf. * * @li 3 - for code points U+100000..U+10FFFF. If the first byte value * is \xf4, then allowed values for the second byte are not \x80..\xbf, * but \x80..\x8f. */ unsigned char cc; #endif } embedjson_lexer; /** * JSON token type */ typedef enum { EMBEDJSON_TOKEN_OPEN_CURLY_BRACKET, EMBEDJSON_TOKEN_CLOSE_CURLY_BRACKET, EMBEDJSON_TOKEN_OPEN_BRACKET, EMBEDJSON_TOKEN_CLOSE_BRACKET, EMBEDJSON_TOKEN_COMMA, EMBEDJSON_TOKEN_COLON, EMBEDJSON_TOKEN_TRUE, EMBEDJSON_TOKEN_FALSE, EMBEDJSON_TOKEN_NULL } embedjson_tok; /** * Called by embedjson_push for each data chunk to parse. * * Results are returned by calling a family of embedjson_token* * functions: * - embedjson_token * - embedjson_tokenc * - embedjson_tokenc_begin * - embedjson_tokenc_end * - embedjson_tokenf * - embedjson_tokeni * * Errors that occurs during parsing are returned via embedjson_error call. * * @note If error occurs, lexer state remain unchanged */ EMBEDJSON_STATIC int embedjson_lexer_push(embedjson_lexer* lexer, const char* data, embedjson_size_t size); /** * Called by embedjson_finalize to indicate that all data has been submitted to * lexer. * * Results are returned as in the embedjson_lexer_push function. */ EMBEDJSON_STATIC int embedjson_lexer_finalize(embedjson_lexer* lexer); /** * Called from embedjson_lexer_push for each successfully parsed any token * that does not have a value. * * A list of possibly returned token types: * - EMBEDJSON_TOKEN_OPEN_CURLY_BRACKET, * - EMBEDJSON_TOKEN_CLOSE_CURLY_BRACKET, * - EMBEDJSON_TOKEN_OPEN_BRACKET, * - EMBEDJSON_TOKEN_CLOSE_BRACKET, * - EMBEDJSON_TOKEN_COMMA, * - EMBEDJSON_TOKEN_COLON, * - EMBEDJSON_TOKEN_TRUE, * - EMBEDJSON_TOKEN_FALSE, * - EMBEDJSON_TOKEN_NULL */ EMBEDJSON_STATIC int embedjson_token(embedjson_lexer* lexer, embedjson_tok token, const char* position); /** * Called from embedjson_lexer_push for each successfully parsed * string chunk. * * A pointer to buffer that contains string chunk data and it's size are * provided to the callback * * @see embedjson_tokenc_begin, embedjson_tokenc_end */ EMBEDJSON_STATIC int embedjson_tokenc(embedjson_lexer* lexer, const char* data, embedjson_size_t size); /** * Called from embedjson_lexer_push for each successfully parsed * integer value. * * @see embedjson_tokenf */ EMBEDJSON_STATIC int embedjson_tokeni(embedjson_lexer* lexer, embedjson_int_t value, const char* position); /** * Called from embedjson_lexer_push for each successfully parsed * floating-point value. * * @see embedjson_tokeni */ EMBEDJSON_STATIC int embedjson_tokenf(embedjson_lexer* lexer, double value, const char* position); /** * Called from embedjson_lexer_push when a beginning of the string token is * spotted. * * @see embedjson_tokenc, embedjson_tokenc_end */ EMBEDJSON_STATIC int embedjson_tokenc_begin(embedjson_lexer* lexer, const char* position); /** * Called from embedjson_lexer_push when string parsing is complete. * * From the user's perspective, a sequence of embedjson_tokenc calls * will always end with a single embedjson_tokenc_end call. * The call indicate that all chunks of the string were parsed. * * @see embedjson_tokenc, embedjson_tokenc_begin */ EMBEDJSON_STATIC int embedjson_tokenc_end(embedjson_lexer* lexer, const char* position); #if EMBEDJSON_BIGNUM /** * Called from embedjson_lexer_push when a beginning of the big number * token is spotted. * * @see embedjson_tokenbn, embedjson_tokenbn_end */ EMBEDJSON_STATIC int embedjson_tokenbn_begin(embedjson_lexer* lexer, const char* position, embedjson_int_t initial_value); /** * Called from embedjson_lexer_push for each successfully parsed * big number chunk. * * A pointer to buffer that contains big number chunk data and it's size are * provided to the callback */ EMBEDJSON_STATIC int embedjson_tokenbn(embedjson_lexer* lexer, const char* data, embedjson_size_t size); /** * Called from embedjson_lexer_push when big number parsing is complete. * * From the user's perspective, a sequence of embedjson_tokenbn calls * will always end with a single embedjson_tokenbn_end call. * The call indicate that all chunks of the big number were parsed. * * @see embedjson_tokenbn, embedjson_tokenbn_begin */ EMBEDJSON_STATIC int embedjson_tokenbn_end(embedjson_lexer* lexer, const char* position); #endif /* EMBEDJSON_BIGNUM */
C
So it looks like we need to iterate through each if statement and produce thedesired input at that step before moving on First thought for inputChar is to look up ASCII range Lowest = 32 for ' ' Highest = 125 for '}' Set up rand() to generate integers and then return the value I originally planned to set a (min, max) range for rand(), but C is fast enough that I realized it would just take a few milliseconds longer if I only set a top range Got to state 9 in about 2 seconds. Now for inputString Looks like a 6-index string with 5 chars and a null terminator It's tempting to just return the string "reset" I ended up allocating 6 bytes on the stack with "char myString[6], filled in the first 5 indices with random integers, added a null terminator, and returned it. This passed the value of string back into main() without losing the value as the stack returned I realized that rand() could work quicker if I limited the values between 101 ('e') and 115 ('s') Started wondering why it was taking so long, then I double-checked the ASCII chart and realized that I excluded the 't' value 116. That would explain it Fixed the issue and on the next run it finished on iteration 579,422 Thanks for reading!
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ocarlos- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/05 12:07:56 by ocarlos- #+# #+# */ /* Updated: 2021/03/14 10:59:39 by ocarlos- ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" /* ** A function which returns a line read from a file descriptor, ** without the newline ** ** RETURN VALUES ** 1 : A line has been read ** 0 : EOF has been reached ** -1 : An error happened */ char *ft_getln(char *s) { int i; char *str; char *rstr; i = 0; while (s[i] != '\n' && s[i] != '\0') i++; if (!(str = (char *)malloc(sizeof(char) * (i + 1)))) return (NULL); rstr = str; while (i--) *str++ = *s++; *str = '\0'; return (rstr); } char *ft_getst(char *s) { char *str; while (*s != '\n' && *s != '\0') s++; if (*s != '\0') s++; str = ft_gnl_strdup(s); return (str); } t_lndata ft_mainloop(t_lndata ln) { while ((ft_gnl_strchr(ln.s)) != 1 && ln.ret != 0) { if ((ln.ret = read(ln.fd, ln.buf, BUFFER_SIZE)) == -1) { free(ln.buf); ln.ret = -1; return (ln); } ln.buf[ln.ret] = '\0'; ln.s = ft_gnl_strjoin(ln.s, ln.buf); } free(ln.buf); return (ln); } int get_next_line(int fd, char **line) { static t_lndata ln; char *tmp; ln.ret = 1; ln.fd = fd; if (!line || ln.fd < 0 || BUFFER_SIZE <= 0) return (-1); if (!(ln.buf = (char *)malloc(sizeof(char) * (BUFFER_SIZE + 1)))) return (-1); ln = ft_mainloop(ln); if (ln.ret == -1) return (-1); *line = ft_getln(ln.s); tmp = ln.s; if (ln.ret == 0) { free(ln.s); ln.s = NULL; return (0); } ln.s = ft_getst(ln.s); free(tmp); return (1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: clorin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/18 10:14:39 by clorin #+# #+# */ /* Updated: 2021/04/21 15:49:25 by bahaas ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/minishell.h" static char *add_car(char *str, char c, int pos) { char *new; int j; new = ft_strnew(ft_strlen(str) + 1); if (!new) return (NULL); j = 0; while (j < pos) { new[j] = str[j]; j++; } new[j++] = c; while (str[pos]) new[j++] = str[pos++]; return (new); } void create_line(long c, t_termcaps *tc) { char car[2]; char *new; car[0] = c; car[1] = '\0'; new = NULL; if (!tc->line) tc->line = ft_strdup(car); else { new = add_car(tc->line, (char)c, tc->cur_pos); ft_strdel(&tc->line); tc->line = ft_strdup(new); ft_strdel(&new); } tc->cur_pos++; } void print_line(t_termcaps *tc, t_ms *ms) { int start; int pos_x; int pos_y; set_cursor_position(tc, tc->start_col, tc->start_row); start = prompt(ms) + tc->start_col; if (tc->line) write(STDOUT, tc->line, ft_strlen(tc->line)); clear_line(); pos_x = (start + tc->cur_pos) % tc->size_col; pos_y = ((start + tc->cur_pos) / tc->size_col) + tc->start_row; set_cursor_position(tc, pos_x, pos_y); }
C
#include <stdio.h> int main() { double x, y; //Змінні x = 2; if (x>1) //Якщо х більше 1 { y = 1; } else if (x < -1) //Якщо х меньше -1 { y = -1 / x; } else //Для х від -1 до 1 { y = x * x; } }
C
#include <stdlib.h> #include <assert.h> #include "malloc_integrity_check.h" #define ABS(value) ( ((value) >= 0) ? (value) : (-(value)) ) extern LIST_HEAD(, mem_chunk) chunk_list; extern mem_block_t* get_back_boundary_tag_of_block(mem_block_t* block); extern mem_block_t** get_back_boundary_tag_address(mem_block_t* block); extern mem_block_t* get_right_block_addr(mem_block_t* block); void walk_the_chunk(mem_chunk_t* chunk) { mem_block_t* iter = &chunk->ma_first; int block_number = 0; assert(iter->mb_size == 0); assert((size_t)iter == (size_t)get_back_boundary_tag_of_block(iter)); assert((size_t)iter->mb_data + ABS(iter->mb_size) == (size_t)get_back_boundary_tag_address(iter)); iter = get_right_block_addr(iter); block_number++; do{ assert(ABS(iter->mb_size) >= (int32_t)MIN_BLOCK_SIZE); assert(ABS(iter->mb_size) % 8 == 0); assert((size_t)iter == (size_t)get_back_boundary_tag_of_block(iter)); assert((size_t)iter->mb_data + ABS(iter->mb_size) == (size_t)get_back_boundary_tag_address(iter)); iter = get_right_block_addr(iter); block_number++; } while(iter->mb_size != 0); assert(iter->mb_size == 0); assert((size_t)iter == (size_t)get_back_boundary_tag_of_block(iter)); assert((size_t)iter->mb_data + ABS(iter->mb_size) == (size_t)get_back_boundary_tag_address(iter)); assert((size_t)iter + sizeof(void*) == (size_t)chunk + (size_t)chunk->size + sizeof(mem_chunk_t) - sizeof(void*)); } void check_integrity(){ mem_chunk_t* chunk; int i = 0; LIST_FOREACH(chunk, &chunk_list, ma_node){ walk_the_chunk(chunk); i++; } }