language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#define _DEFAULT_SOURCE #define _LARGEFILE64_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/resource.h> #include <string.h> #include <stdint.h> #include <stdbool.h> // See https://www.kernel.org/doc/Documentation/vm/pagemap.txt typedef struct PagemapEntry { uint64_t pfn : 55; bool softDirty : 1; bool pageExclusivelyMapped : 1; uint8_t zero : 4; bool filePageOrSharedAnon : 1; bool swapped : 1; bool present : 1; } __attribute((packed)) PagemapEntry_t; static void Usage() { const char* usage = "mm <file>"; printf("%s\n", usage); } static void InfoLog(const char* fmt, ...) { printf("INFO: "); va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); printf("\n"); } static void GetPhysicalAddress(char* addr, char* buf) { char pagemap[50]; int fd = 0; int pageSize = getpagesize(); size_t pageIndex = (uint64_t)addr / pageSize; size_t pageOffset = (uint64_t)addr % pageSize; PagemapEntry_t entry; sprintf(pagemap, "/proc/%d/pagemap", getpid()); fd = open(pagemap, O_RDONLY); if (fd < 0) { perror("Cannot open pagemap file"); exit(1); } InfoLog("Open pagemap at: %s", pagemap); if (pread(fd, &entry, sizeof(entry), pageIndex * sizeof(entry)) != sizeof(entry)) { perror("Cannot read entry"); exit(1); } uint64_t phys = 0; if (entry.present) { phys = entry.pfn * pageIndex + pageOffset; } else { InfoLog("Cannot find physical address of %p. ", addr); } sprintf(buf, "0x%016lx", phys); } int main(int argc, char *argv[]) { struct stat sb; char* addr; char physAddr[16]; if (argc != 2) { Usage(); exit(1); } const char* filename = argv[1]; int fd = open(filename, O_RDONLY); if (fd < 0) { perror("Cannot open file"); exit(1); } InfoLog("File to map: %s", filename); if (fstat(fd, &sb) == -1) { perror("Cannot stat file"); exit(1); } if (sb.st_size / getpagesize() > RLIMIT_MEMLOCK) { InfoLog("The file you try to map will occupy more than " "RLIMIT_MEMLOCK (%d) pages. Locking will fail.", RLIMIT_MEMLOCK); } addr = mmap(NULL, sb.st_size, PROT_READ, MAP_SHARED|MAP_LOCKED,//|MAP_POPULATE, fd, 0); if (addr == MAP_FAILED) { perror("Cannot mmap"); exit(1); } GetPhysicalAddress(addr, physAddr); InfoLog("File %s mapped to virtual address %p (physical address %s)", filename, addr, physAddr); puts("Press a key to exit..."); getchar(); puts("Goodbye"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main (int argc, char const* argv[]) { int c, n, t, i, ans; scanf("%d", &c); // 计数输出 while (c--) { scanf("%d", &n); ans = 0; for (i = 0; i < n; i++) { scanf("%d", &t); ans += t; } printf("%d\n", ans); } return 0; }
C
#include <endian.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #include <math.h> #include <sys/time.h> #include <omp.h> #define calcIndex(width, x,y) ((y)*(width) + (x)) long TimeSteps; void writeVTK2(long timestep, double *data, char prefix[1024], long w, long h) { char filename[2048]; int x, y; long offsetX = 0; long offsetY = 0; float deltax = 1.0; float deltay = 1.0; long nxy = w * h * sizeof(float); snprintf(filename, sizeof(filename), "%s-%05ld%s", prefix, timestep, ".vti"); FILE* fp = fopen(filename, "w"); fprintf(fp, "<?xml version=\"1.0\"?>\n"); fprintf(fp, "<VTKFile type=\"ImageData\" version=\"0.1\" byte_order=\"LittleEndian\" header_type=\"UInt64\">\n"); fprintf(fp, "<ImageData WholeExtent=\"%d %d %d %d %d %d\" Origin=\"0 0 0\" Spacing=\"%le %le %le\">\n", offsetX, offsetX + w, offsetY, offsetY + h, 0, 0, deltax, deltax, 0.0); fprintf(fp, "<CellData Scalars=\"%s\">\n", prefix); fprintf(fp, "<DataArray type=\"Float32\" Name=\"%s\" format=\"appended\" offset=\"0\"/>\n", prefix); fprintf(fp, "</CellData>\n"); fprintf(fp, "</ImageData>\n"); fprintf(fp, "<AppendedData encoding=\"raw\">\n"); fprintf(fp, "_"); fwrite((unsigned char*) &nxy, sizeof(long), 1, fp); for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { float value = data[calcIndex(w, x, y)]; fwrite((unsigned char*) &value, sizeof(float), 1, fp); } } fprintf(fp, "\n</AppendedData>\n"); fprintf(fp, "</VTKFile>\n"); fclose(fp); } void show(double* currentfield, int w, int h) { printf("\033[H"); int x, y; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) printf( currentfield[calcIndex(w, x, y)] ? "\033[07m \033[m" : " "); //printf("\033[E"); printf("\n"); } fflush(stdout); } void evolve(double* currentfield, double* newfield, int w, int h) { int x, y, ii, jj, index_x, index_y; int counter; for (y = 0; y < h; y++) { #pragma omp parallel for private(ii,jj,index_x,index_y,counter) for (x = 0; x < w; x++) { counter = 0; // get neighboring cells for (ii = -1; ii <= 1; ii++) { for (jj = -1; jj <= 1; jj++) { if ((ii) == 0 && (jj == 0)) continue; // dont check cell itself index_x = x + jj; index_y = y + ii; // apply periodic boundary if (index_x < 0) { // x direction index_x += w; } else if (index_x >= w) { index_x -= w; } if (index_y < 0) { // y direction index_y += h; } else if (index_y >= h) { index_y -= h; } if (currentfield[calcIndex(w, index_x, index_y)]) { counter += 1; } } } if (currentfield[calcIndex(w, x, y)] == 1) { // cell ALIVE if ((counter == 2) || (counter == 3)) { newfield[calcIndex(w, x, y)] = 1; } else { newfield[calcIndex(w, x, y)] = 0; } } else if (currentfield[calcIndex(w, x, y)] == 0) { // cell DEAD if (counter == 3) { newfield[calcIndex(w, x, y)] = 1; } else { newfield[calcIndex(w, x, y)] = 0; } } else { printf("something is wrong\n"); exit(0); } } } } /* void evolve_mpi_parallel(double* currentfield, double* newfield, int w, int h){ // calculate start and end indices of domain of each thread // bsp 3 x 4 Zerlegung int nDomains_x = 3; int nDomains_y = 4; int n_omp_threads = nDomains_y * nDomains_x; omp_set_num_threads(n_omp_threads); // Use 4 threads for all consecutive parallel regions int cells_per_domain_x = w / nDomains_x; int cells_per_domain_y = h / nDomains_y; int start_x = cells_per_domain_x * }*/ void filling(double* currentfield, int w, int h) { int i; for (i = 0; i < h * w; i++) { currentfield[i] = (rand() < RAND_MAX / 2) ? 1 : 0; ///< init domain randomly } } void game(int w, int h) { double *currentfield = calloc(w * h, sizeof(double)); double *newfield = calloc(w * h, sizeof(double)); //printf("size unsigned %d, size long %d\n",sizeof(float), sizeof(long)); filling(currentfield, w, h); long t; for (t = 0; t < TimeSteps; t++) { // show(currentfield, w, h); // Field_printField(currentfield,w,h); evolve(currentfield, newfield, w, h); printf("%ld timestep\n", t); writeVTK2(t, currentfield, "gol", w, h); // usleep(150000); //SWAP double *temp = currentfield; currentfield = newfield; newfield = temp; } free(currentfield); free(newfield); } int main(int c, char **v) { int w = 0, h = 0; if (c > 1) w = atoi(v[1]); ///< read width if (c > 2) h = atoi(v[2]); ///< read height TimeSteps = atoi(v[3]); if (w <= 0) w = 30; ///< default width if (h <= 0) h = 30; ///< default height game(w, h); } void Field_printField(double* currentfield, int w, int h) { for (int i = 0; i < w; i++) { for (int j = 0; j < h; j++) { if (currentfield[calcIndex(w, i, j)] == 1) printf("X"); else { printf("O"); } } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <sys/prctl.h> #include <time.h> #include <inttypes.h> #include <sys/mman.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> int temp_data = 100; static int temp_bss; void print_addr ( void ) { int local_var = 100; int *code_segment_address = ( int* ) &print_addr; int *data_segment_address = &temp_data; int *bss_address = &temp_bss; int *stack_segment_address = &local_var; printf ( "\nAddress of various segments:" ); printf ( "\n\tCode Segment : %p" , code_segment_address ); printf ( "\n\tData Segment : %p" , data_segment_address ); printf ( "\n\tBSS : %p" , bss_address ); printf ( "\n\tStack Segment : %p\n" , stack_segment_address ); } int main ( ) { char a = '0'; printf("pid:%d\n",getpid()); print_addr (); scanf("%c", &a); uintptr_t addr = (uintptr_t) mmap(NULL,4194304, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0); if ((void *)addr == MAP_FAILED) { perror("mmap failed!"); exit(0); } printf("mmap-ed region:%" PRIx64 "\n", addr); int status = prctl(PR_SET_MM, PR_SET_MM_START_CODE, addr, 0, 0); scanf("%c", &a); if (status<0) perror("prctl failed!"); print_addr (); while(1); return 0; }
C
/** * @Author: wayne * @Date: 26-04-2017 * @Project: Expression Evaluation * @Filename: data_structures.c * @Last modified by: wayne * @Last modified time: 02-05-2017 */ #include <stdio.h> #include <stdlib.h> #include "data_structures.h" /*Stack Contents*/ void stack_contents(OPSTACK *opstack, VALSTACK *valstack) { /*Value Stack Contents*/ printf("VALSTACK\n"); for (int i = 0; i <= valstack->top; i++) { printf("%d-->%f\n", i, valstack->value_stack[i]); } /*Operator Stack Contents*/ printf("OPSTACK\n"); for (int i = 0; i <= opstack->top; i++) { printf("%d-->%c\n", i, opstack->operator_stack[i]); } } /*Value Stack Functions*/ void value_push(double val, VALSTACK *valstack) { if (valstack->top<MAX_VAL_STACK && valstack->top >=-1) { /*push to stack top*/ valstack->value_stack[++valstack->top] = val; } else if (valstack->top>MAX_VAL_STACK) { perror("Value Stack exceeded"); exit(-1); } } double value_pop(VALSTACK *valstack) { double popval = -9999; if (valstack->top >= 0 && valstack->top <= MAX_VAL_STACK) { /*pop from stack*/ popval = valstack->value_stack[valstack->top]; valstack->value_stack[valstack->top] = 0; valstack->top--; } else if (valstack->top <0) { perror("Invalid Expression:Value Stack Already Empty"); //exit(-1); } return popval; } /*Operator Stack Functions*/ void operator_push(char op, OPSTACK *opstack) { if (opstack->top<MAX_OP_STACK && opstack->top>=-1) { /*push to stack*/ opstack->operator_stack[++opstack->top] = op; } else if (opstack->top>MAX_OP_STACK) { perror("Operator Stack exceeded"); exit(-1); } } char operator_pop(OPSTACK *opstack) { char pop_op = -1; if (opstack->top >= 0 && opstack->top <= MAX_OP_STACK) { /*pop from stack*/ pop_op = opstack->operator_stack[opstack->top]; opstack->operator_stack[opstack->top] = '\0'; opstack->top--; } else if (opstack->top<0) { perror("Invalid Expression:Operator Stack Already Empty"); //exit(-1); } return pop_op; }
C
#ifndef _TYPES_INCLUDED #define _TYPES_INCLUDED #include <stdint.h> #include <stdio.h> #include <string.h> typedef unsigned char uchar; typedef unsigned int uint; typedef struct string_s { uchar *str; uint len; } string_t; typedef struct hash_s { size_t size; elements *elt; } hash_t; #define init_string(str)\ str.str = NULL;\ str.len = 0 #define NULL_STRING(name)\ string_t name = {.str = NULL, .len = 0} int string_to_hex(string_t str, string_t hex); int hex_to_string(string_t str, string_t hex); #define OK 0 #define ERR -1 #define ERR_NULL -2 #define ERR_NOMEM -3 #endif
C
#include<stdio.h> int main(){ int n = 16; int soDinh = 4; int kcach = n/soDinh; int dem = 0; for(int i = 0; i <= n / 2; i++){ printf("\n"); for(int j = 0; j<= n; j++){ if((j + i)% kcach == 0 || (j - i)% kcach == 0){ printf(" %d ",j); }else { printf(" - "); } dem++; } } printf("\n"); return 0; }
C
#include<dictionary.h> int max(int a,int b){ return (a>b?a:b); } int height(Record* root){ if(!root) return -1; else return root->height; } Record* singleRotateLeft(Record* x){ Record* w=x->left; x->left=w->right; w->right=x; x->height=max(height(x->left),height(x->right))+1; w->height=max(height(w->left),x->height)+1; return w; } Record* singleRotateRight(Record* w){ Record* x=w->right; w->right=x->left; x->left=w; w->height=max(height(w->right),height(w->left))+1; x->height=max(height(x->right),w->height)+1; return x; } Record* doubleRotateLeft(Record* z){ z->left=singleRotateRight(z->left); return singleRotateLeft(z); } Record* doubleRotateRight(Record* z){ z->right=singleRotateLeft(z->right); return singleRotateRight(z); } Record* add(Record* root,char data[]) { if(!root) { root=(Record*)malloc(sizeof(Record)); if(!root) { printf("memory error\n"); return NULL; } else { root->height=0; root->count=1; root->left=root->right=NULL; strcpy(root->keyword,data); } } else if(strcmp(data,root->keyword)<0) { root->left=add(root->left,data); if((height(root->left)-height(root->right))==2) { if(strcmp(data,root->left->keyword)<0) root=singleRotateLeft(root); else root=doubleRotateLeft(root); } } else if(strcmp(data,root->keyword)>0) { root->right=add(root->right,data); if((height(root->right)-height(root->left))==2) { if(strcmp(data,root->right->keyword)>0) root=singleRotateRight(root); else root=doubleRotateRight(root); } } else if(strcmp(data,root->keyword)==0){ root->count++; } root->height=max(height(root->left),height(root->right))+1; return root; }
C
#include <stdio.h> #include <conio.h> #include <string.h> #define LINE_BUFFER_SIZE 102400 #define MAX_PASSWORD_LENGTH 1000 #define MAX_FILEPATH_LENGTH 1000 #define MAX_ACTION_COMMAND_LENGTH 5 int main() { // Get passwort to be searched for char password[MAX_PASSWORD_LENGTH]; printf("Enter the Passwort to be searched for: "); fgets(password, MAX_PASSWORD_LENGTH, stdin); if (strlen(password) <= 0) { printf("Password is empty!\n"); getchar(); return 1; } else { // Remove Newline if (password[strlen(password) - 1] == '\n') password[strlen(password) - 1] = '\0'; } // Next, get Filepath to the Password file List char filePath[MAX_FILEPATH_LENGTH]; printf("Enter Path to your Password List File: "); fgets(filePath, MAX_FILEPATH_LENGTH, stdin); if (strlen(filePath) <= 0) { printf("Filepath is empty!\n"); getchar(); return 2; } else { // Remove Newline if (filePath[strlen(filePath) - 1] == '\n') filePath[strlen(filePath) - 1] = '\0'; // Remove Leading " while (filePath[0] == '"') { int filePathLength = strlen(filePath); for (int i = 1; i <= filePathLength; i++) { filePath[i - 1] = filePath[i]; } } // Remove Following " while (filePath[strlen(filePath) - 1] == '"') filePath[strlen(filePath) - 1] = '\0'; } // Open File FILE* passwordList; passwordList = fopen(filePath, "rb"); if (passwordList == NULL) { // Throw Error if not possible to open printf("Error opening File!\n"); getchar(); return 3; } // Some Vars for the Loop int endOfFile = 0; int passwordFound = 0; long currentLine = 0; long lineBufferOverflow = 0; // Start and reprint info printf("Checking file: "); printf(filePath); printf("\nFor password: "); printf(password); printf("\nFor large files, this can take a while!\n"); // Endless checking loop for(;;) { char lineBuffer[LINE_BUFFER_SIZE]; int readPosition = 0; // Almost endless line search loop. Ends on EOF or line ending, filling up line buffer for(;;) { if (readPosition == LINE_BUFFER_SIZE-1) { // => Buffer Overflow, take notice lineBufferOverflow++; break; } // Get next char int currentChar = fgetc(passwordList); // End of File? if (currentChar == EOF) { printf("End of File reached!\n"); endOfFile = 1; break; } lineBuffer[readPosition++] = currentChar; lineBuffer[readPosition] = '\0'; if (currentChar == '\n') { currentLine++; break; } } if (strstr(lineBuffer, password) != NULL) { passwordFound = 1; printf("Found at Line %i and Line Buffer Overflow (should be 0) of %i\n", currentLine, lineBufferOverflow); printf("Line containing Password: "); printf(lineBuffer); /* printf("\nContinue? (Y\\N): "); char inputBuffer[MAX_ACTION_COMMAND_LENGTH]; fgets(inputBuffer, MAX_ACTION_COMMAND_LENGTH, stdin); if (strlen(inputBuffer) <= 0 || inputBuffer[0] != 'Y') { printf("Stopping search.\n"); break; } */ } if (endOfFile == 1) break; } fclose(passwordList); if (passwordFound == 0) { printf("Great, password is not in the List!\n"); } printf("End of Program\n"); getchar(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> void create_sample_file(void){ FILE* p= fopen("sample.dat","w+"); if(p){ fclose(p); } } /* *********************************** */ #define TRUE 1 typedef struct { int month; int day; int year; } date; typedef struct { char name[80]; char street[80]; char city[80]; int acct_no; char acct_type; float oldbalance; float newbalance; float payment; date lastpayment; } record; record readscreen( record customer); void writefile(record customer); FILE *fpt; int main(int argc,char **argv){ create_sample_file(); int flag = TRUE; record customer; fpt = fopen("records.dat", "w"); /* enter date and assign initial values */ printf("CUSTOMER BILLING SYSTEM - INITILIZATION\n\n"); printf("Please enter today\'s date (mm/dd/yyyy): "); scanf("%d/%d/%d", &customer.lastpayment.month, &customer.lastpayment.day, &customer.lastpayment.year); customer.newbalance = 0; customer.payment = 0; customer.acct_type = 'C'; while(flag) { /* Enter customer's name and write to data file */ printf("\nName (enter \'END\' when finished): "); scanf(" %[^\n]", customer.name); fprintf(fpt, "\n%s\n", customer.name); /* test for stopping condition */ if (strcmp(customer.name, "END") == 0) break; customer = readscreen(customer); writefile(customer); } fclose(fpt); return 0; } record readscreen(record customer) { printf("Street: "); scanf(" %[^\n]", customer.street); printf("City: "); scanf(" %[^\n]", customer.city); printf("Account number: "); scanf("%d", &customer.acct_no); printf("Current balance: "); scanf("%f", &customer.oldbalance); return customer; } void writefile(record customer) { fprintf(fpt, "%s\n", customer.street); fprintf(fpt, "%s\n", customer.city); fprintf(fpt, "%d\n", customer.acct_no); fprintf(fpt, "%c\n", customer.acct_type); fprintf(fpt, "%.2f\n", customer.oldbalance); fprintf(fpt, "%.2f\n", customer.newbalance); fprintf(fpt, "%.2f\n", customer.payment); fprintf(fpt, "%d/%d/%d\n", customer.lastpayment.month, customer.lastpayment.day, customer.lastpayment.year); return; }
C
#include <stdio.h> int main(int argc, char **argv) { int *p; int x = 13; //p = (int*) 0x12ff80; p = &x; // naslov od x *p=42; printf("%d\n", x); printf("%p\n", p); int a[10]; printf("%p %p\n", a, &a[1]); int *pa; pa = a; pa[1] = 7; // isto kot *(pa+1)=7, a[1]=7 printf("a[1] = %d\n", a[1]); }
C
#include <stdio.h> #include <stdlib.h> int main() { int age = 15; if(age >= 18) //si l'âge est supérieur ou égale à 18... { printf("vous êtes majeurs !\n"); } else //sinon... { printf("Ah c'est bête, vous êtes mineurs...\n"); } return 0; }
C
// c0027 // by @thititon // status: approved by @kewaleeeiei #include<stdio.h> int main(){ int month[12]={31,28,31,30,31,30,31,31,30,31,30,31},i,m,d,day,sta=0; printf("input : "); scanf("%d",&day); d=day; if (day<1 || day>365){ sta=1; printf("output : Error."); } else{ for(i=0,m=1;i<12;i++){ if (d-month[i]>0){ d=d-month[i]; m++; } else break; } printf("output : %02d/%02d/60\n",d,m); if((day-1)%30==0){ sta=1; printf("Full Moon Phase."); } else if((day-9)%30==0){ sta=1; printf("Third Quarter Phase"); } else if((day-16)%30==0){ sta=1; printf("NEW Moon Phase."); } else if ((day-24)%30==0){ sta=1; printf("First Quarter Phase."); } } if (sta!=1){ day=day%31; if ((day>0&&day<10)||(day>=9&&day<=16)) printf("The moon is waning."); else if((day>=16&&day<=24)||(day>=24&&day<=31)) printf("The moon is waxing."); } }
C
/*7- Escreva um pequeno programa que l do teclado uma string e imprimir quantos caracteres dessa string so dgitos. Por exemplo: ENTRADA: "Niteri, 06 de maro de 2004" EXIBIR: A frase "Niteri, 06 de maro de 2004" tem 6 dgitos*/ #include <locale.h> #include <string.h> #include <stdio.h> #include <conio.h> int main(){ setlocale(LC_ALL,"Portuguese"); char string[80]; int i,j,flag=0,tam; char num[10]={'0','1','2','3','4','5','6','7','8','9'}; printf("Digite a frase: "); gets(string); fflush(stdin); //Pega tamanho da string tam=strlen(string); /*for(i=0;i<tam;i++){ if(string[i] == '0' ||string[i] == '1' || string[i] == '2' || string[i] == '3' || string[i] == '4' || string[i] == '5' || string[i] == '6' || string[i] == '7' || string[i] == '8' || string[i] == '9') flag++; }*/ //Flag - Jeito mais fcil for(i=0;i<tam;i++){ for(j=0;j<10;j++){ if(string[i] == num[j]){ flag++; } } } printf("\nTotal de Digitos: %d",flag); printf("\n\n\n"); printf("\n|===============================================================================|"); printf("\n| --[ 2019 Rafael Neves All Rights Reserved (github.com/rafaelfneves)]-- |"); printf("\n|===============================================================================|\n"); return 0; }
C
/*20. Write a program to find sum of n elements entered by the user. To write this program, allocate memory dynamically using malloc() / calloc() functions or new operator. */ #include <stdio.h> #include <stdlib.h> //included for memory allocation int main(){ int n, sum = 0; int*ptr; //declaring pointer to point to addresses for elements printf("Enter number of terms:"); scanf("%d", &n); ptr = (int*) malloc (n * sizeof(int)); //allocating memory according to the number of terms printf("Enter %d terms:", n); //while loop to enter the elements in the memory created and then adding to sum while(n > 0){ scanf("%d", ptr); sum += *ptr; n--; //decrementing the number of terms for each memory allocated ptr++; //incrementing the memory address for each element } free(ptr); printf("Sum of elements: %d", sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> // I ran command "ulimit -n 50" before running this program int main() { int i=0, j=0; for(i=0; i< 100; i++) { j=open("fork.c", O_RDONLY); if(j == -1) { perror("Error"); break; } printf("%d\n", j); } return 0; }
C
#include <stdio.h> #include <string.h> #include "mpi.h" int main(int argc, char *argv[]) { int name, p; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD, &name); MPI_Comm_size(MPI_COMM_WORLD, &p); printf("Hola mundo, desde el proceso %d de %d\n",name,p); MPI_Finalize(); return 0; }
C
#include <stdio.h> int main() { int num, f1, f2, f3; do { printf("Digite um numero: "); scanf("%d", &num); if(num<=0) { printf("\nDigite um numero positivo!"); } } while (num<=0); printf("\n0 - 1 - "); f1=0; f2=1; num=num-2; for(int cont=0; cont<=num; cont++) { f3=f2+f1; printf("%i - ",f3); f1=f2; f2=f3; } printf ("\n"); return 0; }
C
#include "MultiStage.h" void init_Graph_MS(pG_MS *pG, int vexnum, int edgnum) { int i,j; (*pG)->vexnum = vexnum; (*pG)->edgnum = edgnum; (*pG)->matrix = (int **)malloc(sizeof(int *)*vexnum); (*pG)->vmsg = (VerMsg *)malloc(sizeof(VerMsg)*(vexnum+1)); //邻接矩阵初始化 for(i=0; i<vexnum; i++) { (*pG)->matrix[i] = (int *)malloc(sizeof(int)*vexnum); for(j=0; j<vexnum; j++) { if(i == j) (*pG)->matrix[i][j] = 0; else (*pG)->matrix[i][j] = INF; } } // for(i=1; i<=vexnum; i++) //顶点信息数组[1~vexnum] { (*pG)->vmsg[i].cost = 0; (*pG)->vmsg[i].next = 0; } } void print_matrix(pG_MS pG) { int row,col; int vnum = pG->vexnum; printf("the matrix:\n"); for(row=0; row<vnum; row++) { for(col=0; col<vnum; col++) { if(pG->matrix[row][col] != INF) printf("%d ",pG->matrix[row][col]); else printf("INF "); } printf("\n"); } } void print_path(pG_MS pG, int end) { int i = 1; printf("the shortest route:v1-->"); while(pG->vmsg[i].next != end) { printf("v%d-->",pG->vmsg[i].next); i = pG->vmsg[i].next; } printf("v%d = %d",end,pG->vmsg[1].cost); } void creat_Graph_MS(pG_MS *pG) { int start,end,weight,edgenum; printf("input the start,end,and weight of each edges:\n"); while(edgenum != (*pG)->edgnum) { scanf("%d%d%d",&start,&end,&weight); if(start<1 || end<1 || start>(*pG)->vexnum || end>(*pG)->vexnum || weight<0) { printf("the value is not legal, please input again\n"); // scanf("%d%d%d",&start,&end,&weight); continue; } (*pG)->matrix[start-1][end-1] = weight; //如果是无向图,加上(*pG)->matrix[end-1][start-1] = weight; edgenum++; } } void ms_graph(pG_MS *pG,int end) { int i,j,min; for(i=end-1; i>=1; i--) { min = INF; for(j=i+1; j<=end; j++) { if((*pG)->matrix[i-1][j-1]!=INF && (*pG)->matrix[i-1][j-1] + (*pG)->vmsg[j].cost < min) { min = (*pG)->matrix[i-1][j-1] + (*pG)->vmsg[j].cost; (*pG)->vmsg[i].next = j; } } (*pG)->vmsg[i].cost = min; } }
C
#include<stdio.h> int main(void) { float number; printf("Enter a floating-point value:"); scanf_s("%f",&number); printf("fixed-point notation:%f\n",number); printf("exponential notation:%e\n", number); printf("p notation:%a", number); return 0; }
C
/*A Distribuidora de Combustíveis Ave Maria ira dar um aumento em função da quantidade de combustível comprado anualmente por seus clientes. Os postos que consomem em média até 50.000 litros de combustível ao mês, terão aumento de 20%. Os postos que consomem acima desta média, 12% de aumento. A distribuidora ira fornecer o nome do posto e seu consumo anual. Calcule e escreva qual será o preço do litro de combustível para o posto, levando-se em conta que hoje a distribuidora cobra R$3.63 por litro. */ #include <stdio.h> int main() { float consumoMensal, consumoAnual, precoAumento, precoAtual = 3.63; char nome[15]; printf("Qual o nome do posto?\n"); scanf("%s", nome); printf("Qual foi o consumo mensal médio do posto?\n"); scanf("%f", &consumoMensal); consumoAnual = consumoMensal * 12; if(consumoMensal <= 50000){ precoAumento = precoAtual * 1.2; }else{ precoAumento = precoAtual * 1.12; } printf("O posto %s tem um consumo anual médio de %.2f litros\nO preço do litro de combustível nesse posto será de: R$ %.2f", nome, consumoAnual, precoAumento); return 0; }
C
#ifndef LIST_H_INCLUDED #define LIST_H_INCLUDED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <locale.h> #define M 124 #define N 5 struct LNode { int id; char *name;// char *surname; // int age; // int number; // float salary; // (. ) float height; // int *goals; // ( 5 ) struct LNode *next; }; struct LHead { int cnt; struct LNode *first; struct LNode *last; }; typedef struct LNode Node; typedef struct LHead Head; int menu_main(); // int menu_intput(); // int menu_1(); // int menu_2(); // int Read_Field(char *); // void Read_Value(char *); // int scanID(int *); // id Head *MakeHead(); // Node *MakeNode(); // int ReadFile(Head *, Node *, int *, int *); // Node *ReadNode(char *, int *); // void NodePrint(Node *, int); // void KartPrint(Head *, int *); // void InsertAfter(Head *, Node *, int); // void ChangeAfterInsert(Head *, int, int *); // goals void clearNode(Head *, Node *); // void DeleteNode(Head *, int); // void ChangeAfterDelete(Head *, int, int *); // goals Node *FindNodeById(Head *, int); // int FindNodesByField(Head *, char *(*Fname)(Node *), int, char *, int *); // int ChangeValue(Node *, char *, int, int); // char *name(Node *); // name char *surname(Node *); // surname char *age(Node *); // age char *number(Node *); // number char *salary(Node *); // salary char *height(Node *); // height int Sort1_6(Head *, Node *, char *(*Fname)(Node *), int, int, int *); // void Sort7(Head *, Node *, int, int *); // goals int rewriteFile(FILE *, Head *, int *); // #endif // LIST_H_INCLUDED
C
#include<stdio.h> #include"SLinkList.h" int main(void) { int a1[6] = {1,2,3,4,5,6}; SLinkList SL; int e; InitSList(SL); CreatSList(SL,6,a1); PrintSList(SL); //Clear ClearSList(SL); PrintSList(SL); if(SListEmpty(SL)) printf("链表空\n"); else printf("链表非空\n"); // InitSList(SL); CreatSList(SL,6,a1); PrintSList(SL); printf("表长:%d\n",SListLength(SL)); GetElem(SL,3,&e); printf("链表的第3个元素是:%d\n",e); printf("将0插入第4个位置\n"); printf("插入前:"); PrintSList(SL); printf("插入后:"); InsertElem(SL,4,0); PrintSList(SL); printf("删除第1个元素\n"); printf("删除前:"); PrintSList(SL); DeleteElem(SL,1,&e); printf("删除后:"); PrintSList(SL); printf("删除的元素为:%d\n",e); return 0; }
C
#include "holberton.h" /** * flip_bits - returns the number of bits you would need to flip to get * @n: first number * @m: second number * Return: returns the number of bits you would need to flip to get from one */ unsigned int flip_bits(unsigned long int n, unsigned long int m) { unsigned long int flip, i, j = 0; flip = n ^ m; for (i = 0; i < 9999; i++) { if ((flip & 1) == 1) j++; flip = flip >> 1; } return (j); }
C
// max-subarray.c #include <stdio.h> #include <assert.h> #include <limits.h> #include "max-subarray.h" static void max_subarray_int_cross (const int* array, size_t start, size_t mid, size_t end, max_subarray_result_int_t* result) { assert((start < mid) && (mid < end)); int left_sum = INT_MIN; int sum = 0; for (ssize_t i = mid - 1; i >= (ssize_t)start; i--) { sum += array[i]; if (sum > left_sum) { left_sum = sum; result->start = i; } } int rigth_sum = INT_MIN; sum = 0; for (size_t i = mid; i < end; i++) { sum += array[i]; if (sum > rigth_sum) { rigth_sum = sum; result->end = i; } } result->end++; result->sum = left_sum + rigth_sum; } int max_subarray_int (const int* array, size_t start, size_t end, max_subarray_result_int_t* result) { if ((NULL == array) || (start >= end)) { return -1; } if (start == (end - 1)) { result->start = start; result->end = end; result->sum = array[start]; } else { max_subarray_result_int_t left; max_subarray_result_int_t rigth; max_subarray_result_int_t cross; size_t mid = (start + end) >> 1; max_subarray_int(array, start, mid, &left); max_subarray_int(array, mid, end, &rigth); max_subarray_int_cross(array, start, mid, end, &cross); if ((left.sum >= rigth.sum) && (left.sum >= cross.sum)) { *result = left; } else if (cross.sum >= rigth.sum) { *result = cross; } else { *result = rigth; } } return 0; } int max_subarray_int_r (const int* array, size_t start, size_t end, max_subarray_result_int_t* result) { if ((NULL == array) || (start >= end)) { return -1; } result->start = start; result->end = start; result->sum = array[start]; size_t cur_start = start; int cur_sum = array[start]; for (size_t i = start + 1; i < end; i++) { if (cur_sum < 0) { cur_start = i; cur_sum = array[i]; } else { cur_sum += array[i]; } if (cur_sum > result->sum) { result->start = cur_start; result->end = i; result->sum = cur_sum; } } result->end++; return 0; } // end of file
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstmap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tkarri <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/08 20:24:15 by tkarri #+# #+# */ /* Updated: 2019/04/12 17:53:18 by tkarri ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" static t_list *free_all(t_list *root) { t_list *curr; while (root != NULL) { curr = root; root = root->next; free(curr); curr = NULL; } return (NULL); } t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)) { t_list *curr; t_list *root; t_list *new; root = NULL; if (!(lst && f)) return (NULL); root = (t_list *)malloc(sizeof(t_list)); if (root == NULL) return (NULL); root = f(lst); curr = root; lst = lst->next; while (lst) { if ((new = (t_list *)malloc(sizeof(t_list))) == NULL) return (free_all(root)); new = f(lst); curr->next = new; curr = curr->next; lst = lst->next; } return (root); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi_base.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ebarguil <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/19 19:54:16 by ebarguil #+# #+# */ /* Updated: 2020/09/23 15:08:05 by ebarguil ### ########.fr */ /* */ /* ************************************************************************** */ int error(char *base) { int i; int j; i = 0; if (base[i] == '\0' || base[i + 1] == '\0') return (1); while (base[i] != '\0') { if ((base[i] >= 9 && base[i] <= 13) || base[i] == ' ') return (1); if (base[i] == '-' || base[i] == '+') return (1); j = 0; while (base[j] != '\0') { if (base[i] == base[j] && i != j) return (1); j++; } i++; } return (0); } int char_val(char c, char *base) { int i; i = 0; while (base[i] != '\0') { if (c == base[i]) return (i); i++; } return (-1); } int base_len(char *base) { int i; i = 0; while (base[i] != '\0') i++; return (i); } int ft_atoi(char *str, char *base) { int i; int neg; int res; int val; i = 0; while ((str[i] >= 9 && str[i] <= 13) || str[i] == ' ') i++; neg = 0; while (str[i] == '+' || str[i] == '-') { if (str[i] == '-') neg++; i++; } res = 0; while ((val = char_val(str[i], base)) > -1) { res = res * base_len(base) + val; i++; } if (neg % 2 == 1) res *= -1; return (res); } int ft_atoi_base(char *str, char *base) { int res; if (error(base) == 1) return (0); res = ft_atoi(str, base); return (res); }
C
void Get_grey_index(); void Get_grey_index() { int j,k; struct Grey_indices *select,*probable,*reject; struct Grey *grey_priority; float index; //calculating the grey index in select category select=head_select; for(j=0;j<AIRPORT_NO;j++) { select->grey_index=0; grey_priority=head_grey; for(k=0;k<total_grey_indices;k++) { switch(k) { case 0: index=select->demand_index; break; case 1: index=select->cost_index; break; case 2: index=select->time_index; break; /* case 3: index=select->network_design_index; break; */ case 3: index=select->route_priority_index; break; default : { printf("\n Error in reading grey indices priorities in get_grey-index\n Please check the input data"); getch(); exit(1); } }//end of switch //grey index is the weightage sum of all the indices select->grey_index+=(grey_priority->priority*index); grey_priority=grey_priority->next_grey; } select=select->next_ap_grey; } //calculating the grey index in probable category probable=head_probable; for(j=0;j<AIRPORT_NO;j++) { probable->grey_index=0; grey_priority=head_grey; for(k=0;k<total_grey_indices;k++) { switch(k) { case 0: index=probable->demand_index; break; case 1: index=probable->cost_index; break; case 2: index=probable->time_index; break; /* case 3: index=probable->network_design_index; break; */ case 3: index=probable->route_priority_index; break; default : { printf("\n Error in reading grey indices priorities in get_grey_index\n Please check the input data"); getch(); exit(1); } }//end of switch //grey index is the weightage sum of all the indices probable->grey_index+=(grey_priority->priority*index); grey_priority=grey_priority->next_grey; } probable=probable->next_ap_grey; } //calculating the grey index in reject category reject=head_reject; for(j=0;j<AIRPORT_NO;j++) { reject->grey_index=0; grey_priority=head_grey; for(k=0;k<total_grey_indices;k++) { switch(k) { case 0: index=reject->demand_index; break; case 1: index=reject->cost_index; break; case 2: index=reject->time_index; break; /* case 3: index=reject->network_design_index; break; */ case 3: index=reject->route_priority_index; break; default : { printf("\n Error in reading grey indices priorities in get_grey_index\n Please check the input data"); getch(); exit(1); } }//end of switch //grey index is the weightage sum of all the indices reject->grey_index+=(grey_priority->priority*index); grey_priority=grey_priority->next_grey; } reject=reject->next_ap_grey; } //printing the grey index information if(user_choice==YES) { FILE *fprocess=fopen("Output/PROCESS.txt","a"); if(fprocess==NULL) { printf("\n Cann't open the file Output/PROCESS in get_grey_index"); getch(); exit(1); } fprintf(fprocess,"\n Grey index in different categories : ( Select \\ Probable \\ Reject)"); select=head_select; reject=head_reject; probable=head_probable; fprintf(fprocess,"\n"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",select->grey_index); select=select->next_ap_grey; } fprintf(fprocess," \t\t"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",probable->grey_index); probable=probable->next_ap_grey; } fprintf(fprocess," \t\t"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",reject->grey_index); reject=reject->next_ap_grey; } fclose(fprocess); }//end of if(user_choice==YES) } //end of function /* fprintf(fprocess,"\n\n grey Index in Select Category"); select=head_select; for(i=0;i<AIRPORT_NO;i++) { fprintf(fprocess,"\n"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",select->grey_index); select=select->next_ap_grey; } } fprintf(fprocess,"\n\n grey Index in Probable Category"); probable=head_probable; for(i=0;i<AIRPORT_NO;i++) { fprintf(fprocess,"\n"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",probable->grey_index); probable=probable->next_ap_grey; } } fprintf(fprocess,"\n\n grey Index in Reject Category"); reject=head_reject; for(i=0;i<AIRPORT_NO;i++) { fprintf(fprocess,"\n"); for(j=0;j<AIRPORT_NO;j++) { fprintf(fprocess," %.2f\t",reject->grey_index); reject=reject->next_ap_grey; } } fclose(fprocess); }//end of if(user_choice==YES) }//end of function */
C
//*************************************************** /** while文 課題 * https://monozukuri-c.com/langc-while/ * 10月29日 */ //*************************************************** #include <stdio.h> void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; }; void calc_lcm(int num1, int num2) { int count = 1; while (1) { if (count % num1 != 0) { count++; continue; } if (count % num2 != 0) { count++; continue; } printf("最小公倍数 %d, %d ==> %d\n", num1, num2, count); break; } } int main(void) { int number1 = 11; int number2 = 34; int r, temp; int x = number1 * number2; if (number1 < number2) { swap(&number1, &number2); } r = number1 % number2; while (r != 0) { number1 = number2; number2 = r; r = number1 % number2; } printf("最大公約数 %d\n", number2); printf("最小公倍数 %d\n", x / number2); calc_lcm(11, 34); return 0; }
C
#include <stdio.h> #include <stdlib.h> int is_leap_year(int year) { return (year%4==0)&&(year%100!=0)||(year%400==0); } int main(void) { int year, month, day, n; int numdaysmonth[]={31,28,31,30,31,30,31,31,30,31,30,31}; printf("Current date <year month day>? "); scanf("%d%d%d",&year,&month,&day); if(month<=0||month>12) exit(1); else if(is_leap_year(year)==1&&month==2&&day>29) exit(1); else if(day>numdaysmonth[month-1]||day<=0) exit(1); printf("How many days you want to shift <+/->? "); scanf("%d",&n); if(is_leap_year(year)==1) numdaysmonth[1]=29; if(n>=0) { day+=n; if(is_leap_year(year)==1) numdaysmonth[1]=29; for(; day>numdaysmonth[month-1] ;) { day-=numdaysmonth[month-1]; month+=1; if (month>12) { month=1; year+=1; if(is_leap_year(year)==1) numdaysmonth[1]=29; } } printf("New date = %d %d %d",year,month,day); } else { day+=n; if(is_leap_year(year)==1) numdaysmonth[1]=29; for(; day<0 ;) { month-=1; day+=numdaysmonth[month-1]; if (month<=0) { month+=12; year-=1; if(is_leap_year(year)==1) numdaysmonth[1]=29; } } printf("New date = %d %d %d",year,month,day); } return 0; }
C
#include <stdio.h> #include <pthread.h> int a,b; void add(){printf("a+b: %d\n", a+b);} void sub(){printf("a-b: %d\n", a-b);} int main(){ printf("Enter a, b\n"); scanf("%d%d",&a,&b); pthread_t tid1,tid2; printf("--> Main process\n"); pthread_create(&tid1,NULL,add,NULL); pthread_create(&tid2,NULL,sub,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); printf("--> Main process\n"); }
C
/************************************************************************* * * @FileName Csr1010.c * @Date 2017.03.10 * @Author DS.Chin * @Description * Communicate to CSR1010 * Receive data from APP * Send dato to APP * ***************************************************************************/ #include "Csr1010.h" /* <-------------Gloable Variables-------------------> */ _TypeStructRcv RcvData; _TypeStructSnd SndData; _Flag RcvFlag; _Uint8 ChkSumReply[4]; /* <-------------File Variables----------------------> */ idata _Uint8 RcvBuffer[RCV_BYTE_MAX]; enum ENUM_STATUS { RCV_IDLE, RCV_STT, RCV_END, RCV_ERR }RcvByteStatus; /********************************************************* * * @FunctionName Csr1010_Init * *****/ void Csr1010_Init(void) { SndData.SndByteDoneFlag = FALSE; } /********************************************************** * * @FunctionName Uart_Interrupt * ****/ void Uart_Interrupt(void) interrupt 15 { /* When receive interrupt flag been set */ if (RI_1) { RI_1 = RESET; Csr1010_Rcv_Byte(); } /* When send interrput flag been set */ if (TI_1) { TI_1 = RESET; SndData.SndByteDoneFlag = FALSE; } return; } /*********************************************************** * * @FunctionName Csr1010_Rcv_Byte * ****/ static void Csr1010_Rcv_Byte(void) { static _Uint8 ByteCnt; _Uint8 RcvBufferTemp = 0; // move receive data to RcvBuffer RcvBufferTemp = SBUF_1; // start to receive data when receive status is idle if (RcvByteStatus == RCV_IDLE) { if (RcvBufferTemp == 0xFD) { RcvByteStatus = RCV_STT; ByteCnt = 0; } } // receive the data else if (RcvByteStatus == RCV_STT) { if (RcvBufferTemp == 0xFE) RcvByteStatus = RCV_END; /* Rcv End */ else if (ByteCnt >= 6) RcvByteStatus = RCV_ERR; /* Rcv Err */ else RcvBuffer[ByteCnt++] = RcvBufferTemp; /* Rcving */ } } /************************************************************ * * @FunctionName Csr1010_Rcv_Data * ****/ void Csr1010_Rcv_Data(void) { static _Uint8 RcvSttHoldTime; _Uint8 TempCnt = 0; /* Exit when receive status is idle or working */ if (RcvByteStatus == RCV_IDLE) { RcvSttHoldTime = 0; return; } /* Hold time after received, if timer > 1second, received err, then clear the data */ if (RcvByteStatus == RCV_STT) { RcvSttHoldTime++; if (RcvSttHoldTime > 100) { RcvSttHoldTime = 0; RcvByteStatus = RCV_IDLE; } return; } /* received error */ if (RcvByteStatus == RCV_ERR) { for (TempCnt = 0; TempCnt < 6; TempCnt++) RcvBuffer[TempCnt] = 0; // clear the buffer RcvByteStatus = RCV_IDLE; // clear the status return; } /* received success */ if (RcvByteStatus == RCV_END) { RcvFlag = TRUE; for (TempCnt = 0; TempCnt < 6; TempCnt++) // move the buffer to rcvdata { RcvData.DataBuf[TempCnt] = RcvBuffer[TempCnt]; RcvBuffer[TempCnt] = 0; } RcvByteStatus = RCV_IDLE; // clear status } } /*********************************************************** * * @FunctionName Csr1010_Snd_Data * *****/ void Csr1010_Snd_Data(void) { _Uint8 TempCnt = 0; /* when snd data is idle , exit */ if (SndData.SndStatus == SND_IDLE) { return; } /* type send LA1 */ if (SndData.SndStatus == SND_TYPE) { // Send type command "LA1" Csr1010_Snd_Byte(0xFC); Csr1010_Snd_Byte(DEVICE_NAME_ONE); Csr1010_Snd_Byte(DEVICE_NAME_TWO); Csr1010_Snd_Byte(DEVICE_NUM); for (TempCnt = 0; TempCnt < 4; TempCnt++) { Csr1010_Snd_Byte(ChkSumReply[TempCnt]); } Csr1010_Snd_Byte(0xFE); // Send power on command after type command sent completed SndData.SndStatus = SND_NORMAL; return; } /* Send normally */ if (SndData.SndStatus == SND_NORMAL) { Csr1010_Snd_Byte(0xFD); for (TempCnt = 0; TempCnt < 8; TempCnt++) Csr1010_Snd_Byte(SndData.DataBuf[TempCnt]); Csr1010_Snd_Byte(0xFE); SndData.SndStatus = SND_IDLE; } } /****************************************************** * * @Function Name Csr1010_Snd_Byte * ****/ static void Csr1010_Snd_Byte(_Uint8 SndBuf) { while (SndData.SndByteDoneFlag); SBUF_1 = SndBuf; SndData.SndByteDoneFlag = TRUE; }
C
#include <stdio.h> #include <string.h> #include "helpers.h" #include "rle.h" /************************************************************* * FUNCTIONS DEFINED FOR THE PURPOSE OF MANIPULATING RLE * OBJECTS *************************************************************/ /************************************************************* * Desc : Function to create a new Frame object and * assign memory for all the channels. It gets the * current_frame_data, splits it into RGB. * * Params : dimensions - The Pixel size of each frame * *current_frame_data - decompressed VPackbit data * * Return : frame - pointer to the newly created frame object **************************************************************/ Frame * new_frame(int dimensions, unsigned char *current_frame_data) { Frame *frame = rle_malloc(sizeof(frame), "New Frame"); frame -> red = (unsigned char *) rle_malloc(dimensions * sizeof(unsigned char), "Red data"); frame -> green = (unsigned char *) rle_malloc(dimensions * sizeof(unsigned char), "Green data"); frame -> blue = (unsigned char *) rle_malloc(dimensions * sizeof(unsigned char), "Blue data"); split_rgb_values(current_frame_data, frame, dimensions); return frame; } /********************************************************* * Desc : Function to free all memory allocated to an * Rle Object (Struct) * * Params : *rle - Pointer to RLE Object * * Return : None *********************************************************/ void free_rle_object(Rle *rle) { int num = rle -> num_images ; while(--num > 0) { rle_free(rle -> frames[num] -> red, "red"); rle_free(rle -> frames[num] -> green, "green"); rle_free(rle -> frames[num] -> blue, "blue"); rle_free(rle -> frames[num], "frame"); } rle_free(rle -> header -> property, "property"); rle_free(rle -> header, "header"); rle_free(rle, "rle"); }
C
// // Created by 网安 胡洋 on 2020/10/6. // #include "header.h" #include "stdio.h" #include "stdlib.h" AST* makempty(){ AST* p; if(p = malloc(sizeof(AST))){ p->type = 0; p->value = 0; p->fellow = 0; p->firstson = 0; return p; } else { printf("cant make empty ast"); return 0; } } AST* insert(AST* p, int type, int value,int mode){// mode 0 for fellow, 1 for son AST* p1; if(p1 = malloc(sizeof(AST))){ p1 ->type = type; p1->value = value; p1-> fellow = 0; p1-> firstson = 0; if(mode)p->firstson = p1; else p->fellow = p1; } else { printf("cant insert"); return 0; } } AST* parse(Token * tp) { AST* p = makempty(); if(p){ p->type = Program; while(tp->type) p = insert(p,global_decl,0,1); tp = glo_decl(p,tp); } return p ; } Token * glo_decl(AST* p,Token* tp) { int flag =1; if(is_type(tp->type)){ if((tp+1)->type == '(') { p = insert(p,function_defined,0,flag); tp = func_def(p,tp); if(flag)flag--; } else { p = insert(p,variable_decl,0,flag); tp = vari_decl(p,tp); if(flag)flag--; } } else { printf("error! 'type' needed!"); return 0; } return tp; } Token * func_def(AST * p, Token * tp) { p = insert(p,tp->type,tp->value,1);//insert type tp++; p = insert(p,tp->type,tp->value,0);//insert id tp++; if(tp->type == '(') { p = insert(p,parameter_decl,0,0);//insert parameter-list tp = para_decl(p,tp); if( tp->type == '{' ) { p = insert(p,body_decl,0,0); tp = bd_st(p,tp); } else { printf("function body part needs '{}'"); return 0; } } return tp; } Token * para_decl(AST* p,Token* tp) { p = insert(p,tp->type,tp->value,1);//type tp++; p = insert(p,tp->type,tp->value,0);//id tp++; while(tp->type == ','){ p = insert(p,tp->type,tp->value,0);//type tp++; p = insert(p,tp->type,tp->value,0);//id tp++; } return ++tp;//ignore ) } Token * bd_st(AST* p,Token* tp ) { tp = stmt(p,tp); return tp; } Token * stmt(AST*p ,Token* tp) { //emtpy_exp //break char flag = 1; while( tp->type != '}'){ if (tp->type == If){ p = insert(p,ifst,0,flag); tp = if_st(p,tp); if(flag)flag--; } else if (tp->type == While) { p = insert(p,whilest,0,flag); tp = while_st(p,tp); if(flag)flag--; } else if (tp->type == For){ p = insert(p,forst,0,flag); tp = for_st(p,tp); if(flag)flag--; } else if (tp->type == Return){ p = insert(p,retexp,0,flag); tp = ret_exp(p,tp); if(flag)flag--; } else if (tp->type == Continue){ p = insert(p,ctn,0,flag); tp+=2; // ignore ; if(flag)flag--; } else if(tp->type == Break){ p = insert(p,brk, 0, flag); tp+=2; //ignore ; if(flag)flag--; } else//exp { p = insert(p,exp,0,flag); tp = exp_st(p,tp); if(flag)flag--; } } return ++tp;//ignore } } Token * if_st(AST* p,Token * tp) { tp+=2; p = insert(p,condition,0,1); tp = exp_st(p,tp);//condition if( tp->type =='{'){ p = insert(p,stmt_st, 0,0); tp= stmt(p,tp); } else { p = insert(p,exp,0,0); tp = exp_st(p,tp); } if(tp->type == Else){ p = insert(p,elst,0,0); tp++; if(tp->type=='{'){ tp = stmt(p,tp); } else { tp = exp_st(p,tp); } } return tp; } Token * while_st(AST *p, Token* tp) { tp+= 2; p = insert(p,condition,0,1); tp = exp_st(p,tp); if( (tp)->type =='{'){ p = insert(p,stmt_st, 0,0); tp= stmt(p,tp); } else { p = insert(p,exp,0,0); tp = exp_st(p,tp); } return tp; } Token * for_st(AST*p, Token * tp) { tp+=2; p = insert(p,forfdo,0,1); tp = exp_st(p,tp); p = insert(p,condition,0,0); tp = exp_st(p,tp); p = insert(p,fordo,0,0); tp = exp_st(p,tp); if(tp->type == '{'){ p = insert(p,stmt_st,0,0); tp = stmt(p,tp); } else{ p = insert(p,exp,0,0); tp = exp_st(p,tp); } return tp; } Token* ret_exp(AST *p, Token* tp) { tp++; //turn to exp part tp = exp_st(p,tp); return tp; } Token* exp_st(AST*p,Token*tp) { int a=0; if(tp->type != ';'){ p = insert(p,tp->type,tp->value,1); tp++; while(tp->type != Id && in_field(tp->type)) { if(tp->type == '(')a++; else if(tp-> type ==')') { a--; if (a<0) break; // to recognize paralist } p =insert(p,tp->type,tp->value,0); tp++; } } return ++tp; //ignore ; or ) } Token* vari_decl(AST*p, Token* tp) { p = insert(p,p->type,p->value,1); while(is_varidecl(tp->type)) { p = insert(p,p->type,p->value,0); tp++; } return tp; } int is_type(int tocheck) { if(tocheck >=Char && tocheck<= Float)return 1; else return 0; } int is_varidecl(int a ) { if(a == Id|| a==',')return 1; return 0; } int in_field(int a) //used in exp { if(a>= Assign && a<= Mod || a=='[' || a==']' // [ ] for array || a=='~'|| a==',' || a=='(' || a==')' )return 1; else return 0; }
C
#include "main.h" /** * puts2 - print string by first charactert on line others nextline * @str: string */ void puts2(char *str) { int i; i = 0; while (*(str + i) != '\0') { if (i % 2 == 0) _putchar(*(str + i)); i++; } _putchar('\n'); }
C
#ifndef _PROBUTILS_H #define _PROBUTILS_H /* =================================================================== */ /* Probability Utils */ /* =================================================================== */ /* GetCND */ /* ------ */ /* This gets us the cumulative normal distribution using the erf and * erfc functions. */ inline double GetCND(double x, double mean, double stddev) { double z = (x - mean) / stddev; if (z >= 0.0) return 0.5 + 0.5 * erf(z / sqrt(2.0)); else return 0.5 * erfc(-z / sqrt(2.0)); } /* GetProbND */ /* --------- */ /* Gets us the value of the normal distribution at x. */ inline double GetProbND(double x, double mean, double stddev) { double denom = sqrt(2.0 * M_PI) * stddev * exp((x-mean)*(x-mean) / (2.0 * stddev*stddev)); return 1.0 / denom; } /** * Returns the value of a uniform distribution */ inline double GetProbUniform(double n) { return 1.0 / n; } /** * Returns the value of an exponential distribution */ inline double GetProbExponential(double x, double lambda) { return lambda * exp(-lambda * x); } #endif
C
#include "scheduler.h" #include <stdio.h> /* required for file operations */ #include <time.h> #include <stdbool.h> #include "configLoad.h" #include "print2screen.h" #include "mathAlgo.h" static volatile int dummy; scheduler_t sData; static bool initDone ; void init_threads(); threadData_t Athread; threadData_t Bthread; threadData_t Cthread; threadData_t Dthread; threadData_t Ethread; void init_threads(){ // set threads to active config.threadbuffer[0] = true; config.threadbuffer[1] = true; config.threadbuffer[2] = true; config.threadbuffer[3] = true; config.threadbuffer[4] = true; // put threads into array /* threads_arr[0] = &Athread; threads_arr[1] = &Bthread; threads_arr[2] = &Cthread; threads_arr[3] = &Dthread; threads_arr[4] = &Ethread;*/ // Load workload units into global structures Athread.totalTerms = 50*config.workLoad[0]; Athread.currPiValue = 0; printf("ATotalTerms %d\n", Athread.totalTerms); Bthread.totalTerms = 50*config.workLoad[1]; Bthread.currPiValue = 0; printf("BTotalTerms %d\n", Bthread.totalTerms); Cthread.totalTerms = 50*config.workLoad[2]; Cthread.currPiValue = 0; printf("CTotalTerms %d\n", Cthread.totalTerms); Dthread.totalTerms = 50*config.workLoad[3]; Dthread.currPiValue = 0; printf("DTotalTerms %d\n", Dthread.totalTerms); Ethread.totalTerms = 50*config.workLoad[4]; Ethread.currPiValue = 0; printf("ETotalTerms %d\n", Ethread.totalTerms); } void algo() { double percentage; threadData_t currentThread; // read percentage from file if(config.preemptive == 0) { percentage = config.quantum; } else { // Means its preemptive percentage = 100; } if(sData.threadID == 0) { currentThread = Athread; } if(sData.threadID == 1) { currentThread = Bthread; } if(sData.threadID == 2) { currentThread = Cthread; } if(sData.threadID == 3) { currentThread = Dthread; } if(sData.threadID == 4) { currentThread = Ethread; } calculatePI(&currentThread , percentage); // TODO ERASE THE FOLLOWING LINES FOR PRODUCTION CODE /* unsigned i; for(i = 0; i<10; i++ ) { printf("Current thread is: %d, data: %d\n", sData.threadID, i); // wait until task slice ends dummy = 1 ; while(dummy ); }*/ } void restoreState(unsigned idx) { int retval = 1; if(5 == idx) { retval = 5; } siglongjmp(sData.env[idx], retval); return; } int saveState(unsigned idx) { // giving thread idx and value to return int ret; void * ptr; ret = sigsetjmp(sData.env[idx], 1); // modify the stack to not interfere with current execution if( 0 != ret && 5 != idx ) { //ptr = (&sData.env[idx]+JB_SP ); //*ptr = (uint32_t ) (&stack[idx][STACK_SIZE -1]); } return ret; } int lottery() { // for now implementing round robin int winner=0; winner = sData.threadID+1; winner =0; if( winner >= MAX_THREADS ) winner = 0; // calculate a winner return winner; } //unsigned lottery (void) //{ // // unsigned totalactivos = 0; // unsigned winthread = 0; // unsigned winner = 0; // // /* En caso ningun thread este activo */ // if (!config.threadbuffer[0] && !config.threadbuffer[1] && !config.threadbuffer[2] && !config.threadbuffer[3] && !config.threadbuffer[4]) { // winthread = 0; // winner = 0; // return winthread; // } // // /* Determina el total de tiquetes que seran evaluados para obtener el ganador */ // if (config.threadbuffer[0]) totalactivos = config.tickets[0]; // if (config.threadbuffer[1]) totalactivos = (totalactivos + config.tickets[1]); // if (config.threadbuffer[2]) totalactivos = (totalactivos + config.tickets[2]); // if (config.threadbuffer[3]) totalactivos = (totalactivos + config.tickets[3]); // if (config.threadbuffer[4]) totalactivos = (totalactivos + config.tickets[4]); // // /* Realiza la rifa y se obtiene de manera aleatoria el boleto ganador */ // do { // winner = rand() % totalactivos; // } while (winner == 0); // // /* Determina segun el boleto cual es el thread ganador */ // /* Casos en q puede ganar thread 1 */ // if (config.threadbuffer[0] && winner <= config.tickets[0]) { // winthread = 1; // return winthread; // } // // /* Casos en q puede ganar thread 2 */ // // if (config.threadbuffer[0] && config.threadbuffer[1] && winner <= (config.tickets[1]+config.tickets[0])) { // winthread = 2; // return winthread; // } // if (!config.threadbuffer[0] && config.threadbuffer[1] && winner <= config.tickets[1]) { // winthread = 2; // return winthread; // } // // /* Casos en q puede ganar thread 3 */ // // if (config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[2])) { // winthread = 3; // return winthread; // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2] && winner <= (config.tickets[0]+config.tickets[2])) { // winthread = 3; // return winthread; // } // } // } // if (!config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2] && winner <= (config.tickets[1]+config.tickets[2])) { // winthread = 3; // return winthread; // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2] && winner <= config.tickets[2]) { // winthread = 3; // return winthread; // } // } // } // // /* Casos en q puede ganar thread 4 */ // // if (config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[2]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[0]+config.tickets[2]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[0]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // } // } // if (!config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[1]+config.tickets[2]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[1]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= (config.tickets[2]+config.tickets[3])) { // winthread = 4; // return winthread; // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3] && winner <= config.tickets[3]) { // winthread = 4; // return winthread; // } // } // } // } // // /* Casos en q puede ganar thread 5 */ // // if (config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[2]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[2]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[1]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[2]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[2]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[0]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // } // } // if (!config.threadbuffer[0]) { // if (config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[1]+config.tickets[2]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[1]+config.tickets[2]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[1]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[1]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // } // if (!config.threadbuffer[1]) { // if (config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[2]+config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[2]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // } // if (!config.threadbuffer[2]) { // if (config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= (config.tickets[3]+config.tickets[4])) { // winthread = 5; // return winthread; // } // } // if (!config.threadbuffer[3]) { // if (config.threadbuffer[4] && winner <= config.tickets[4]) { // winthread = 5; // return winthread; // } // } // } // } // } // // return winthread; //} void preemtiveTime() { // unsigned quantum; // quantum = config.quantum; // ualarm(quantum); //getitimer(ITIMER_VIRTUAL,&sData.timer); printf("setting the timer\n"); sData.timer.it_value.tv_sec = 0; sData.timer.it_value.tv_usec = 100000; sData.timer.it_interval.tv_sec = 0; sData.timer.it_interval.tv_usec = 100000; setitimer(ITIMER_VIRTUAL, &sData.timer, 0); return; } // placeholder bool invalidateThread (unsigned ID) { bool Done = false; if (ID == 1) config.threadbuffer[0] = false; if (ID == 2) config.threadbuffer[1] = false; if (ID == 3) config.threadbuffer[2] = false; if (ID == 4) config.threadbuffer[3] = false; if (ID == 5) config.threadbuffer[4] = false; Done = !(config.threadbuffer[0] | config.threadbuffer[1] | config.threadbuffer[2] | config.threadbuffer[3] | config.threadbuffer[4]); return Done; } void schedulerInit() { unsigned thread; initDone = true; for( thread = 0; thread < MAX_THREADS ; thread ++ ) { sData.taskInit[thread] = false; } init_threads(); } /*************************************************** * * Lottery Scheduler * ***************************************************/ void scheduler(int v) { int ret; bool allDone = false; printf("Getting the alarm for thread: %d\n", sData.threadID ); // Save the state ret = saveState(sData.threadID); if( 1 == ret ) { printf("restoring state %d\n", sData.threadID); // return to resume execution // in the thread return; } if( 5 == ret ) { // the case to return from the scheduler to the main return; } dummy = 0; if( !initDone ) { printf("entering init\n"); schedulerInit(); } sData.threadID = lottery(); // Catch the timer signal signal(SIGVTALRM, scheduler); // Set timer preemtiveTime(); printf("sigalm passed\n"); if( !sData.taskInit[sData.threadID] ) { printf("initializing thread: %d\n", sData.threadID); sData.taskInit[sData.threadID] = true; // when reaching this part the task finished execution // call function for first time algo(); initscr(); print2screen(&Athread,&Bthread,&Cthread,&Dthread,&Ethread,sData.threadID); printf("\ntask %d is done\n", sData.threadID); allDone = invalidateThread(sData.threadID); // enters if all the threads had completed their job allDone = 1;// tmp measure //change the stack ptr to the old position restoreState(6); if(allDone) { return; } } else { // Restore the state restoreState(sData.threadID); } return; }
C
#include <locale.h> #define CHAR_MAX 127 struct lconv* localeconv(void) { static struct lconv lc; struct lconv *lcp = &lc; lcp->decimal_point = "."; lcp->thousands_sep = ""; lcp->grouping = ""; lcp->int_curr_symbol = ""; lcp->currency_symbol = ""; lcp->mon_decimal_point = "."; lcp->mon_thousands_sep = ""; lcp->mon_grouping = ""; lcp->positive_sign = "+"; lcp->negative_sign = "-"; lcp->int_frac_digits = CHAR_MAX; lcp->frac_digits = CHAR_MAX; lcp->p_cs_precedes = CHAR_MAX; lcp->p_sep_by_space = CHAR_MAX; lcp->n_cs_precedes = CHAR_MAX; lcp->n_sep_by_space = CHAR_MAX; lcp->p_sign_posn = CHAR_MAX; lcp->n_sign_posn = CHAR_MAX; return lcp; }
C
#include "monty.h" /** * sub- 2nd - 1st = 2nd * @line:line arguments came from * @head:input */ void sub(stack_t **head, unsigned int line) { stack_t *temp; if ((*head) == NULL) { dprintf(STDERR_FILENO, "L%u: can't sub, stack too short\n", line); quickExit(*head, willy.words, EXIT_FAILURE); } if ((*head)->next == NULL) { dprintf(STDERR_FILENO, "L%u: can't sub, stack too short\n", line); quickExit(*head, willy.words, EXIT_FAILURE); } temp = (*head); (*head) = (*head)->next; (*head)->n = ((*head)->n) - (temp->n); free(temp); }
C
/* * forkex.c - an example of using fork to create processes and execute new tasks * Author: Jordan Long * */ #include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> #include <string.h> /** * count the number of arguments. */ int countArguments(const char *commandLine) { int num=0; return num; } /** * given a pointer to a string, find the start of the next argument and the end of the argument, * malloc a new string of that length, and return it the new string. */ const char *nextArgument(const char *currentString) { } /** * given a command line string, call on countArguments to count the # of arguments present, * mallocate an array of pointers to hold that # of string pointers, call on * nextArgument that number of times, storing the resulting pointer to a string into each element of the array. */ char **buildCommandLine(const char *commandLine) { int i = 0; char *p = strtok (commandLine, " "); char *array[10]; while (p != NULL) { array[i++] = p; p = strtok (NULL, " "); } } /* * Takes in the command and arguments and forks the parent process. */ void createForkedProcess(char *arguments) { //Fork child process from parent pid_t pid = fork( ); //If pid goes negative, fork has failed. Throws error and exits. if (pid < 0) { perror("Error: fork failed."); exit(-1); } // pid is 0? a new process was created, and this copy is it if (pid == 0) { execute(arguments); // this should never return - so if it doesn't, something bad happened. abort( ); } // pid is not 0? then it is the pid of the child else { int status; printf("Waiting for command to finish.\n"); waitpid(pid, &status, 0); printf("This is still the parent: child exited with status %x\n", status); } } /* * Takes the command and arguments and executes it. */ void execute(const char *arguments) { if(execvp(arguments[0], arguments) < 0) { perror("Could not execute command."); } } /* * Main class for the project. Takes in user input and stores it in a char array. Then calls the fork method. */ int main(int argc, char **argv, char **envp) { //Ask user for command and arguments char commandLine[40]; printf ("Enter a command and arguments to run: "); scanf ("%s", commandLine); buildCommandLine(commandLine); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* func_misc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vkryvono <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/22 19:03:00 by vkryvono #+# #+# */ /* Updated: 2019/06/30 14:31:09 by vkryvono ### ########.fr */ /* */ /* ************************************************************************** */ #include "functions.h" static int cmp_number(void const *champion_content, void const *sample_content) { t_champion const *champion; t_champion const *sample; champion = champion_content; sample = sample_content; return (champion->number == sample->number); } void func_live(t_carriage *carriage) { t_operation *operation; t_champion sample; t_list *survivor; get_argval(carriage); operation = &carriage->operation; carriage->live = g_game.cycle_counter; g_game.live_counter++; survivor = NULL; if (-operation->argv[0] > 0 && -operation->argv[0] <= g_game.players_amount) { sample.number = -operation->argv[0]; survivor = ft_lstfind(g_game.players, &sample, cmp_number); g_game.survivor = (survivor->content) ? survivor->content : g_game.survivor; } if (g_flag & FLAG_VERBOSE_4) ft_printf("P%5i | live %i\n", carriage->id, operation->argv[0]); if (survivor == NULL) return ; if (g_flag & FLAG_VERBOSE_1) ft_printf("Player %d (%s) is said to be alive\n", -operation->argv[0], g_game.survivor->header->prog_name); } void func_zjmp(t_carriage *carriage) { t_operation *operation; get_argval(carriage); operation = &carriage->operation; if (carriage->carry) { carriage->pos = (carriage->pos - get_arglen(operation) + (operation->argv[0] % IDX_MOD) + MEM_SIZE) % MEM_SIZE; if (g_flag & FLAG_VERBOSE_4) ft_printf("P%5i | zjmp %i OK\n", carriage->id, operation->argv[0]); return ; } if (g_flag & FLAG_VERBOSE_4) ft_printf("P%5i | zjmp %i FAILED\n", carriage->id, operation->argv[0]); } void func_aff(t_carriage *carriage) { t_operation *operation; int32_t *argv; get_argval(carriage); operation = &carriage->operation; argv = operation->argv; if (check_arg(operation->argt[0], operation->argv[0]) != T_REG) return ; if (g_flag & FLAG_AFF) ft_printf("%c\n", (char)(carriage->reg[argv[0] - 1] % 256)); if (g_flag & FLAG_VERBOSE_4) ft_printf("P%5d | aff r%d\n", carriage->id, argv[0] - 1); }
C
/** Function to shift the current view to the left/right. * * http://lists.suckless.org/dev/1104/7590.html * * @param: "arg->i" stores the number of tags to shift right (positive value) * or left (negative value) */ void shiftview(const Arg *arg) { Arg shifted; if(arg->i > 0) // left circular shift shifted.ui = (selmon->tagset[selmon->seltags] << arg->i) | (selmon->tagset[selmon->seltags] >> (LENGTH(tags) - arg->i)); else // right circular shift shifted.ui = selmon->tagset[selmon->seltags] >> (- arg->i) | selmon->tagset[selmon->seltags] << (LENGTH(tags) + arg->i); view(&shifted); }
C
#include "mylib.h" int main() { /* int age; char name[100]; int count = sscanf("name:ccc age:51", "name:%s age:%d", name, &age); printf("count=%d\n", count); printf("name=%s age=%d\n", name, age); */ char op[100]; int lmin, lmax; int count = sscanf("list 3 5", "%s %d %d", op, &lmin, &lmax); printf("count=%d\n", count); printf("op=%s lmin=%d lmax=%d\n", op, lmin, lmax); }
C
#include <stddef.h> #include <stdint.h> #include <stdlib.h> void neuralops_image_crop( size_t in_width, size_t in_height, size_t chan, size_t crop_w, size_t crop_h, ptrdiff_t offset_x, ptrdiff_t offset_y, const float *in_pixels, float *out_pixels) { size_t p = 0; for (size_t a = 0; a < chan; a++) { for (size_t v = 0; v < crop_h; v++) { for (size_t u = 0; u < crop_w; u++) { ptrdiff_t x = offset_x + u; ptrdiff_t y = offset_y + v; if (x < 0 || x >= in_width || y < 0 || y >= in_height) { out_pixels[p] = 0.0f; } else { out_pixels[p] = in_pixels[x + in_width * (y + in_height * a)]; } p += 1; } } } } void neuralops_image_flip( size_t width, size_t height, size_t chan, const float *in_pixels, float *out_pixels) { size_t p = 0; for (size_t a = 0; a < chan; a++) { for (size_t y = 0; y < height; y++) { for (size_t x = 0; x < width; x++) { out_pixels[p] = in_pixels[(width - x - 1) + width * (y + height * a)]; p += 1; } } } }
C
#include <stdio.h> #include <gsl/gsl_blas.h> typedef unsigned int bool; #define false 0 #define true 1 //gcc -Wall -02 mpenrose.c -o penrose -lgsl -lgslcblas -lm // Función que muestra en consola una matriz (estructura propia de libreria gsl) void mostrar_matriz(const gsl_matrix *m) { for (int i = 0; i < m->size1; i++) { for (int j = 0; j < m->size2; j++) { printf("%f\t", gsl_matrix_get(m, i, j)); } printf("\n"); } } void mostrar_vector(const gsl_vector *v){ printf("vector:\n"); for(int i = 0 ;i<v->size ; i++){ printf("%f\t", gsl_vector_get(v, i)); } printf("\n"); } gsl_matrix* penrose(gsl_matrix* A){ unsigned int n = A->size2; unsigned int m = A->size1; double prec_machine = 1E-10; gsl_matrix *V, *Sigma_inv, *U, *A_pinv; gsl_vector *_tmp_vec, *s; gsl_matrix *_tmp_mat; gsl_matrix * VS_product; bool transpose = false; //validate size of matrix if(n > m){ transpose = true; _tmp_mat = gsl_matrix_alloc(n, m); gsl_matrix_transpose_memcpy(_tmp_mat, A); n = A->size1; m = A->size2; printf("indices m: %d, n: %d \n",m,n ); A = _tmp_mat; mostrar_matriz(A); } V = gsl_matrix_alloc(n, n); U = gsl_matrix_alloc(m, m); s = gsl_vector_alloc(n); gsl_matrix_set_zero(U); _tmp_vec = gsl_vector_alloc(n); gsl_linalg_SV_decomp(A, V, s, _tmp_vec); printf("\n Matriz V\n"); mostrar_matriz(V); printf("\n Matriz S\n"); mostrar_vector(s); printf("\n Matriz U\n"); mostrar_matriz(A); //llena la matriz U for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { gsl_matrix_set(U, i, j, gsl_matrix_get(A, i, j)); } } //create sigma inverse function Sigma_inv = gsl_matrix_alloc(n,m); gsl_matrix_set_zero(Sigma_inv); for(int i = 0;i<s->size;i++){ if(gsl_vector_get(s,i)>prec_machine){ gsl_matrix_set(Sigma_inv,i,i,1/ gsl_vector_get(s,i)); } else{ gsl_matrix_set(Sigma_inv,i,i,0.0); } } printf("Matriz Sigma\n"); mostrar_matriz(Sigma_inv); printf("\n Matriz U\n"); mostrar_matriz(U); /* Compute C = A B */ // gsl_blas_dgemm (CblasNoTrans, CblasNoTrans,1.0, &A.matrix, &B.matrix, 0.0, &C.matrix); VS_product = gsl_matrix_alloc(n, m); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1., V, Sigma_inv, 0., VS_product); if (transpose){ A_pinv = gsl_matrix_alloc(m,n); //U*(V*S⁺)ᵀ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., U, VS_product, 0., A_pinv); } else{ A_pinv = gsl_matrix_alloc(n,m); //V*S⁺*Uᵀ gsl_blas_dgemm(CblasNoTrans, CblasTrans, 1., VS_product, U, 0., A_pinv); } //A_pinv= V * Sigma_inv * U_transpose return A_pinv; } int main() { int m,n; // Número de filas y columnas de la matriz de usuario printf("Introduzca el número de filas de la matriz: "); scanf("%d",&m); const unsigned int M = m; printf("Introduzca el número de columnas de la matriz: "); scanf("%d",&n); const unsigned int N = n; const double rcond = 1E-15; gsl_matrix *A = gsl_matrix_alloc(M,N); // Matriz de usuario gsl_matrix *A_pinv; // Matriz de pseudo-inversa printf("Introduzca los elementos de la matriz A(%dx%d)\n",m,n); double elem; for(int i=0; i<M; i++){ for(int j=0; j<N; j++){ printf("a%d,%d: ", i+1,j+1); scanf("%lf", &elem); gsl_matrix_set(A, i, j, elem); } } printf("\n Matriz de usuario\n"); mostrar_matriz(A); printf("\nCalculando Inversa de Moore-Penrose\n"); A_pinv = penrose(A); //mostrar_matriz(A_pinv); printf("\nRESULTADO Inversa de Moore-Penrose\n"); mostrar_matriz(A_pinv); printf("Fin.\n"); return 0; }
C
#include <stdio.h> int pow_self(int x,int n){ int mul=1; while(n){ mul*=x; n--; } return mul; }; int main(){ int m,n; printf("Enter base and power : "); scanf("%d %d",&m,&n); printf("The result is : %d",pow_self(m,n)); return 0; }
C
#include <lib.h> #include <stdlib.h> #include "thread_queue.h" #include "../scheduler.h" typedef struct thread_queue_node * thread_queue_node_t; typedef struct thread_queue * thread_queue_t; struct thread_queue_node { thread_t thread; void * extra_info; thread_queue_node_t next; thread_queue_node_t prev; }; struct thread_queue { thread_queue_node_t first; thread_queue_node_t last; int size; }; thread_queue_t new_thread_queue() { thread_queue_t ret = (thread_queue_t)k_malloc(sizeof(struct thread_queue)); if(ret == NULL) { #ifdef THREAD_QUEUE_DEBUG_MSG k_log("Couldn't allocate space for thread_queue!\n"); #endif return NULL; } ret->first = ret->last = NULL; ret->size = 0; return ret; } int free_thread_queue(thread_queue_t tq) { thread_t aux_thread; while((aux_thread=poll_thread_queue(tq)) != NULL) { terminate_thread(aux_thread); } k_free(tq); return 1; } int offer_thread_queue(thread_queue_t tq, thread_t thread, void * extra_info) { thread_queue_node_t new_node = (thread_queue_node_t)k_malloc(sizeof(struct thread_queue_node)); if(new_node == NULL) { #ifdef THREAD_QUEUE_DEBUG_MSG k_log("Couldn't allocate space for thread_queue_node!\n"); #endif return -1; } new_node->thread = thread; new_node->extra_info = extra_info; if(tq->first == NULL) { tq->first = new_node; tq->last = new_node; new_node->next = NULL; new_node->prev = NULL; } else { tq->last->next = new_node; new_node->prev = tq->last; new_node->next = NULL; tq->last = new_node; } tq->size++; return 1; } void * peek_extra_info_thread_queue(thread_queue_t tq) { if(tq->first == NULL) return NULL; return tq->first->extra_info; } thread_t poll_thread_queue(thread_queue_t tq) { thread_t ret; if(tq->first == NULL) return NULL; if(tq->first == tq->last) { ret = tq->first->thread; k_free(tq->first); tq->first = NULL; tq->last = NULL; } else { ret = tq->first->thread; tq->first=tq->first->next; k_free(tq->first->prev); tq->first->prev = NULL; } tq->size--; return ret; } thread_t peek_thread_queue(thread_queue_t tq) { if(tq->first == NULL) return NULL; return tq->first->thread; } int is_empty_thread_queue(thread_queue_t tq) { return tq->first == NULL; } int remove_thread_queue(thread_queue_t tq, thread_t thread) { thread_queue_node_t curr; if(tq == NULL) return -1; if(is_empty_thread_queue(tq)) return -1; curr = tq->first; do { if(curr->thread->tid == thread->tid) { if(curr == tq->first && curr == tq->last) { tq->first = NULL; tq->last = NULL; } else if(curr == tq->first) { tq->first = tq->first->next; tq->first->prev = NULL; } else if(curr == tq->last) { tq->last = tq->last->prev; tq->last->next = NULL; } else { curr->next->prev = curr->prev; curr->prev->next = curr->next; } k_free(curr); return 1; } else { curr = curr->next; } } while(curr != NULL); return -1; }
C
#include<stdio.h> #include<conio.h> #define size 10 int main(){ int a[size]; int i, large; printf("Enter 10 Numbers: \n"); scanf("%d",&a[0]); large = a[0]; for(i=1;i<size;i++){ scanf("%d",&a[i]); if(a[i]>large){ large = a[i]; } } printf("\n %d is the largest number.",large); getch(); return 0; }
C
/**************************************************************************** * * * Secure Memory Management * * Copyright Peter Gutmann 1995-2015 * * * ****************************************************************************/ #if defined( INC_ALL ) #include "crypt.h" #include "acl.h" #include "kernel.h" #else #include "crypt.h" #include "kernel/acl.h" #include "kernel/kernel.h" #endif /* Compiler-specific includes */ /* The minimum and maximum amount of secure memory that we can ever allocate. A more normal upper bound is 1K, however the SSL session cache constitutes a single large chunk of secure memory that goes way over this limit */ #define MIN_ALLOC_SIZE 8 #define MAX_ALLOC_SIZE 8192 /* Memory block flags. These are: FLAG_LOCKED: The memory block has been page-locked to prevent it from being swapped to disk and will need to be unlocked when it's freed. FLAG_PROTECTED: The memory is read-only, enforced by running a checksum over it that's stored at the end of the user-visible block */ #define MEM_FLAG_NONE 0x00 /* No memory flag */ #define MEM_FLAG_LOCKED 0x01 /* Memory block is page-locked */ #define MEM_FLAG_PROTECTED 0x02 /* Memory block can't be changed */ #define MEM_FLAG_MAX 0x03 /* Maximum possible flag value */ /* To support page locking and other administration tasks we need to store some additional information with the memory block. We do this by reserving an extra memory block at the start of the allocated block and saving the information there. The information stored in the extra block is flags that control the use of the memory block, the size of the block, and pointers to the next and previous pointers in the list of allocated blocks (this is used by the thread that walks the block list touching each one). We also insert a canary at the start and end of each allocated memory block to detect memory overwrites and modification, which is just a checksum of the memory header that doubles as a canary (which also makes it somewhat unpredictable). The resulting memory block looks as follows: External mem.ptr | Canary v v +-------+---+-----------------------+---+ | Hdr |###| Memory |###| +-------+---+-----------------------+---+ ^ ^ | |<----------- memHdrPtr->size --------->| | | memPtr (BYTE *) | memHdrPtr (MEM_INFO_HDR *) memTrlPtr (MEM_INFO_TRL *) */ typedef struct { SAFE_FLAGS flags; /* Flags for this memory block. The memory header is checksummed so we don't strictly have to use safe flags, but we do it anyway for appearances' sake */ int size; /* Size of the block (including the size of the header and trailer) */ DATAPTR prev, next; /* Next, previous memory block */ int checksum; /* Header checksum+canary for spotting overwrites */ } MEM_INFO_HEADER; typedef struct { int checksum; /* Memory block checksum or canary (= header chks) */ } MEM_INFO_TRAILER; #if INT_MAX <= 32767 #define MEM_ROUNDSIZE 4 #elif INT_MAX <= 0xFFFFFFFFUL #define MEM_ROUNDSIZE 8 #else #define MEM_ROUNDSIZE 16 #endif /* 16/32/64-bit systems */ #define MEM_INFO_HEADERSIZE roundUp( sizeof( MEM_INFO_HEADER ), MEM_ROUNDSIZE ) #define MEM_INFO_TRAILERSIZE sizeof( MEM_INFO_TRAILER ) /**************************************************************************** * * * OS-Specific Memory Locking * * * ****************************************************************************/ /* Many OSes support locking pages in memory, the following helper functions implement this locking */ #if defined( __MAC__ ) #include <Memory.h> /* The Mac has two functions for locking memory, HoldMemory() (which makes the memory ineligible for paging) and LockMemory() (which makes it ineligible for paging and also immovable). We use HoldMemory() since it's slightly more friendly, but really critical applications could use LockMemory() */ static void lockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); #if !defined( CALL_NOT_IN_CARBON ) || CALL_NOT_IN_CARBON if( HoldMemory( memPtr, memHdrPtr->size ) == noErr ) SET_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ); #endif /* Non Mac OS X memory locking */ } static void unlockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); /* If the memory was locked, unlock it now */ #if !defined( CALL_NOT_IN_CARBON ) || CALL_NOT_IN_CARBON if( TEST_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ) ) UnholdMemory( memPtr, memHdrPtr->size ); #endif /* Non Mac OS X memory locking */ } #elif defined( __MSDOS__ ) && defined( __DJGPP__ ) #include <dpmi.h> #include <go32.h> static void lockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); /* Under 32-bit MSDOS use the DPMI functions to lock memory */ if( _go32_dpmi_lock_data( memPtr, memHdrPtr->size ) == 0) SET_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ); } static void unlockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); /* Under 32-bit MSDOS we *could* use the DPMI functions to unlock memory, but as many DPMI hosts implement page locking in a binary form (no lock count maintained), it's better not to unlock anything at all. Note that this may lead to a shortage of virtual memory in long-running applications */ } #elif defined( __UNIX__ ) /* Since the function prototypes for the SYSV/Posix mlock() call are stored all over the place depending on the Unix version it's easier to prototype it ourselves here rather than trying to guess its location */ #if defined( __osf__ ) || defined( __alpha__ ) #include <sys/mman.h> #elif defined( sun ) #include <sys/mman.h> #include <sys/types.h> #else int mlock( void *address, size_t length ); int munlock( void *address, size_t length ); #endif /* Unix-variant-specific includes */ /* Under many Unix variants the SYSV/Posix mlock() call can be used, but only by the superuser (with occasional OS-specific variants, for example under some newer Linux variants the caller needs the specific CAP_IPC_LOCK privilege rather than just generally being root). OSF/1 has mlock(), but this is defined to the nonexistant memlk() so we need to special-case it out. QNX (depending on the version) either doesn't have mlock() at all or it's a dummy that just returns -1, so we no-op it out. Aches, A/UX, PHUX, Linux < 1.3.something, and Ultrix don't even pretend to have mlock(). Many systems also have plock(), but this is pretty crude since it locks all data, and also has various other shortcomings. Finally, PHUX has datalock(), which is just a plock() variant. Linux 2.6.32 has a kernel bug in which, under high disk-load conditions (100% disk usge) and with multiple cryptlib threads performing memory locking/unlocking the process can get stuck in the "D" state, a.k.a. TASK_UNINTERRUPTIBLE, which is an uninterruptible disk I/O sleep state. If the process doesn't snap out of it when the I/O completes then it's necessary to reboot the machine to clear the state. To help find this issue use: ps -eo ppid,pid,user,stat,pcpu,comm,wchan:32 which shows D-state processes via the fourth column, the last column will show the name of the kernel function in which the process is currently sleeping (also check dmesg for kernel Oops'es) */ #if defined( _AIX ) || defined( __alpha__ ) || defined( __aux ) || \ defined( _CRAY ) || defined( __CYGWIN__ ) || defined( __hpux ) || \ ( defined( __linux__ ) && OSVERSION < 2 ) || \ defined( _M_XENIX ) || defined( __osf__ ) || \ ( defined( __QNX__ ) && OSVERSION <= 6 ) || \ defined( __TANDEM_NSK__ ) || defined( __TANDEM_OSS__ ) || \ defined( __ultrix ) #define mlock( a, b ) 1 #define munlock( a, b ) #endif /* Unix OS-specific defines */ /* In theory we could also tell the kernel to treat the memory specially if this facility is available. In practice this doesn't really work though because madvise() works on a granularity of page boundaries, despite the appearance of working on arbitrary memory regions. This means that unless the start address is page-aligned, it'll fail. In addition it functions at a much lower level than malloc(), so if we madvise() malloc'd memory we'll end up messing with the heap in ways that will break memory allocation. For example MADV_WIPEONFORK will wipe the entire page or page range containing the heap that the client gets, corrupting the heap on fork. What this means is that we'd need to mmap() memory in order to madvise() on it, and then implement our own allocator on top of that. Or, every time we allocate anything, make it a full page, again via mmap(). The chances of something going wrong when we do our own memory management are probably a lot higher than the chances of something ending up in a core dump when we don't: #if defined( __linux__ ) && defined( _BSD_SOURCE ) && 0 // Tell the kernel to exclude this memory region from core dumps if // possible #ifdef MADV_DONTDUMP #include <sys/mman.h> ( void ) madvise( void *addr, size_t length, MADV_DONTDUMP ); #endif // MADV_DONTDUMP */ static void lockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); if( !mlock( ( void * ) memHdrPtr, memHdrPtr->size ) ) SET_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ); } static void unlockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); /* If the memory was locked, unlock it now */ if( TEST_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ) ) munlock( ( void * ) memHdrPtr, memHdrPtr->size ); } #elif defined( __WIN32__ ) && !defined( NT_DRIVER ) /* For the Win32 debug build we enable extra checking for heap corruption. This isn't anywhere near as good as proper memory checkers like Bounds Checker, but it can catch some errors */ #if !defined( NDEBUG ) && !defined( NT_DRIVER ) && !defined( __BORLANDC__ ) #define USE_HEAP_CHECKING #include <crtdbg.h> #endif /* Win32 debug version */ /* Get the start address of a page and, given an address in a page and a size, determine on which page the data ends. These are used to determine which pages a memory block covers */ #if defined( _MSC_VER ) && ( _MSC_VER >= 1400 ) #define PTR_TYPE INT_PTR #else #define PTR_TYPE long #endif /* Newer versions of VC++ */ #define getPageStartAddress( address ) \ ( ( PTR_TYPE ) ( address ) & ~( pageSize - 1 ) ) #define getPageEndAddress( address, size ) \ getPageStartAddress( ( PTR_TYPE ) address + ( size ) - 1 ) /* Under Win95/98/ME the VirtualLock() function was implemented as 'return( TRUE )' ("Thank Microsoft kids" - "Thaaaanks Bill"), but we don't have to worry about those Windows versions any more. Under Win32/ Win64 the function does actually work, but with a number of caveats. The main one is that it was originally intended that VirtualLock() only locks memory into a processes' working set, in other words it guarantees that the memory won't be paged while a thread in the process is running, and when all threads are pre-empted the memory is still a target for paging. This would mean that on a loaded system a process that was idle for some time could have the memory unlocked by the system and swapped out to disk (actually with older Windows incarnations like NT, their somewhat strange paging strategy meant that it could potentially get paged even on a completely unloaded system. Even on relatively recent systems the gradual creeping takeover of free memory for disk buffers/cacheing can cause problems, something that was still affecting Win64 systems during the Windows 7 time frame. Ironically the 1GB cache size limit on Win32 systems actually helped here because the cache couldn't grow beyond this size and most systems had more than 1GB of RAM, while on Win64 systems without this limit there was more scope for excessive reads and writes to consume all available memory due to cacheing). The lock-into-working-set approach was the original intention, however the memory manager developers never got around to implementing the unlock-if-all-threads idle part. The behaviour of VirtualLock() was evaluated back under Win2K and XP by trying to force data to be paged under various conditions, which were unsuccesful, so VirtualLock() under these OSes seems to be fairly effective in keeping data off disk. In newer versions of Windows the contract for VirtualLock() was changed to match the actual implemented behaviour, so that now "pages are guaranteed not to be written to the pagefile while they are locked". An additional concern is that although VirtualLock() takes arbitrary memory pointers and a size parameter, the locking is done on a per-page basis so that unlocking a region that shares a page with another locked region means that both reqions are unlocked. Since VirtualLock() doesn't do reference counting (emulating the underlying MMU page locking even though it seems to implement an intermediate layer above the MMU so it could in theory do this), the only way around this is to walk the chain of allocated blocks and not unlock a block if there's another block allocated on the same page. Ick. For the NT kernel driver, the memory is always allocated from the non- paged pool so there's no need for these gyrations. In addition to VirtualLock() we could also use VirtualAlloc(), however this allocates in units of the allocation granularity, which is in theory system-dependent and obtainable via the dwAllocationGranularity field in the SYSTEM_INFO structure returned by GetSystemInfo() but in practice on x86 systems is always 64K, this means the memory is nicely aligned for efficient access but wastes 64K for every allocation */ static void lockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); if( VirtualLock( ( void * ) memHdrPtr, memHdrPtr->size ) ) SET_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ); } static void unlockMemory( INOUT MEM_INFO_HEADER *memHdrPtr ) { KERNEL_DATA *krnlData = getKrnlData(); MEM_INFO_HEADER *currentBlockPtr; PTR_TYPE block1PageAddress, block2PageAddress; const int pageSize = getSysVar( SYSVAR_PAGESIZE ); assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER ) ) ); /* If the memory block isn't locked, there's nothing to do */ if( !TEST_FLAG( memHdrPtr->flags, MEM_FLAG_LOCKED ) ) return; /* Because VirtualLock() works on a per-page basis, we can't unlock a memory block if there's another locked block on the same page. The only way to manage this is to walk the block list checking to see whether there's another block allocated on the same page. Although in theory this could make freeing memory rather slow, in practice there are only a small number of allocated blocks to check so it's relatively quick, especially compared to the overhead imposed by the lethargic VC++ allocator. The only real disadvantage is that the allocation objects remain locked while we do the free, but this isn't any worse than the overhead of touchAllocatedPages(). Note that the following code assumes that an allocated block will never cover more than two pages, which is always the case. First we calculate the addresses of the page(s) in which the memory block resides */ block1PageAddress = getPageStartAddress( memHdrPtr ); block2PageAddress = getPageEndAddress( memHdrPtr, memHdrPtr->size ); if( block1PageAddress == block2PageAddress ) block2PageAddress = 0; /* Walk down the block list checking whether the page(s) contain another locked block */ for( currentBlockPtr = DATAPTR_GET( krnlData->allocatedListHead ); \ currentBlockPtr != NULL; currentBlockPtr = DATAPTR_GET( currentBlockPtr->next ) ) { const PTR_TYPE currentPage1Address = \ getPageStartAddress( currentBlockPtr ); PTR_TYPE currentPage2Address = \ getPageEndAddress( currentBlockPtr, currentBlockPtr->size ); if( currentPage1Address == currentPage2Address ) currentPage2Address = 0; /* If there's another block allocated on either of the pages, don't unlock it */ if( block1PageAddress == currentPage1Address || \ block1PageAddress == currentPage2Address ) { block1PageAddress = 0; if( !block2PageAddress ) break; } if( block2PageAddress == currentPage1Address || \ block2PageAddress == currentPage2Address ) { block2PageAddress = 0; if( !block1PageAddress ) break; } } /* Finally, if either page needs unlocking, do so. The supplied size is irrelevant since the entire page the memory is on is unlocked */ if( block1PageAddress ) VirtualUnlock( ( void * ) block1PageAddress, 16 ); if( block2PageAddress ) VirtualUnlock( ( void * ) block2PageAddress, 16 ); } #else /* For everything else we no-op it out */ #define lockMemory( memHdrPtr ) #define unlockMemory( memHdrPtr ) #endif /* OS-specific page-locking handling */ /**************************************************************************** * * * OS-Specific Nonpageable Allocators * * * ****************************************************************************/ /* Some OSes handle page-locking by explicitly locking an already-allocated address range, others require the use of a special allocate-nonpageable- memory function. For the latter class we redefine the standard clAlloc()/clFree() macros to use the appropriate OS-specific allocators */ #if defined( __BEOS__xxx ) /* See comment below */ /* BeOS' create_area(), like most of the low-level memory access functions provided by different OSes, functions at the page level so we round the size up to the page size. We can mitigate the granularity somewhat by specifying lazy locking, which means that the page isn't locked until it's committed. In pre-open-source BeOS, areas were bit of a security tradeoff because they were globally visible(!!!) through the use of find_area(), so that any other process in the system could find them. An attacker could always find the app's malloc() arena anyway because of this, but putting data directly into areas made the attacker's task somewhat easier. Open- source BeOS fixed this, mostly because it would have taken extra work to make areas explicitly globally visible and no-one could see a reason for this, so it's somewhat safer there. However, the implementation of create_area() in the open-source BeOS seems to be rather flaky (simply creating an area and then immediately destroying it again causes a segmentation violation) so it may be necessary to turn it off for some BeOS releases. In more recent open-source BeOS releases create_area() simply maps to mmap(), and that uses a function convert_area_protection_flags() to convert the BeOS to Posix flags which simply discards everything but AREA_READ, AREA_WRITE, and AREA_EXEC, so it appears that create_area() can no longer allocate non-pageable memory. If the original behaviour is ever restored then the code will need to be amended to add the following member to MEM_INFO_HEADER: area_id areaID; // Needed for page locking under BeOS and save the areaID after the create_area() call: memHdrPtr->areaID = areaID; */ #define clAlloc( string, size ) beosAlloc( size ) #define clFree( string, memblock ) beosFree( memblock ) static void *beosAlloc( const int size ) { void *memPtr = NULL; area_id areaID; areaID = create_area( "memory_block", &memPtr, B_ANY_ADDRESS, roundUp( size + MEM_INFO_HEADERSIZE, B_PAGE_SIZE ), B_LAZY_LOCK, B_READ_AREA | B_WRITE_AREA ); if( areaID < B_NO_ERROR ) return( NULL ); return( memPtr ); } static void beosFree( void *memPtr ) { MEM_INFO_HEADER *memHdrPtr = memPtr; area_id areaID; areaID = memHdrPtr->areaID; zeroise( memPtr, memHdrPtr->size ); delete_area( areaID ); } #elif defined( __CHORUS__ ) /* ChorusOS is one of the very few embedded OSes with paging capabilities, fortunately there's a way to allocate nonpageable memory if paging is enabled */ #include <mem/chMem.h> #define clAlloc( string, size ) chorusAlloc( size ) #define clFree( string, memblock ) chorusFree( memblock ) static void *chorusAlloc( const int size ) { KnRgnDesc rgnDesc = { K_ANYWHERE, size + MEM_INFO_HEADERSIZE, \ K_WRITEABLE | K_NODEMAND }; if( rgnAllocate( K_MYACTOR, &rgnDesc ) != K_OK ) return( NULL ); return( rgnDesc.startAddr ); } static void chorusFree( void *memPtr ) { MEM_INFO_HEADER *memHdrPtr = memPtr; KnRgnDesc rgnDesc = { K_ANYWHERE, 0, 0 }; rgnDesc.size = memHdrPtr->size; rgnDesc.startAddr = memPtr; zeroise( memPtr, memHdrPtr->size ); rgnFree( K_MYACTOR, &rgnDesc ); } #endif /* OS-specific nonpageable allocation handling */ /**************************************************************************** * * * Utility Functions * * * ****************************************************************************/ /* Calculate the checksum for a memory header block */ STDC_NONNULL_ARG( ( 1 ) ) \ static int checksumMemHdr( INOUT MEM_INFO_HEADER *memHdrPtr ) { const int memHdrChecksum = memHdrPtr->checksum; int checksum; memHdrPtr->checksum = 0; checksum = checksumData( memHdrPtr, MEM_INFO_HEADERSIZE ); memHdrPtr->checksum = memHdrChecksum; return( checksum ); } /* Set the checksum for a block of memory */ STDC_NONNULL_ARG( ( 1 ) ) \ static void setMemChecksum( INOUT MEM_INFO_HEADER *memHdrPtr ) { MEM_INFO_TRAILER *memTrlPtr; assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER * ) ) ); memHdrPtr->checksum = 0; /* Set mutable members to zero */ memHdrPtr->checksum = checksumData( memHdrPtr, MEM_INFO_HEADERSIZE ); memTrlPtr = ( MEM_INFO_TRAILER * ) \ ( ( BYTE * ) memHdrPtr + memHdrPtr->size - MEM_INFO_TRAILERSIZE ); memTrlPtr->checksum = memHdrPtr->checksum; } /* Check that a memory block is in order */ CHECK_RETVAL_BOOL STDC_NONNULL_ARG( ( 1 ) ) \ static BOOLEAN checkMemBlockHdr( INOUT MEM_INFO_HEADER *memHdrPtr ) { const MEM_INFO_TRAILER *memTrlPtr; int checksum; assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER * ) ) ); /* Make sure that the general header information is valid. This is a quick check for obviously-invalid blocks, as well as ensuring that a corrupted size member doesn't result in us reading off into the weeds */ if( memHdrPtr->size < MEM_INFO_HEADERSIZE + MIN_ALLOC_SIZE + \ MEM_INFO_TRAILERSIZE || \ memHdrPtr->size > MEM_INFO_HEADERSIZE + MAX_ALLOC_SIZE + \ MEM_INFO_TRAILERSIZE ) return( FALSE ); if( !CHECK_FLAGS( memHdrPtr->flags, MEM_FLAG_NONE, MEM_FLAG_MAX ) ) return( FALSE ); /* Everything seems kosher so far, check that the header hasn't been altered */ checksum = checksumMemHdr( memHdrPtr ); if( checksum != memHdrPtr->checksum ) return( FALSE ); /* Check that the trailer hasn't been altered */ memTrlPtr = ( MEM_INFO_TRAILER * ) \ ( ( BYTE * ) memHdrPtr + memHdrPtr->size - MEM_INFO_TRAILERSIZE ); if( memHdrPtr->checksum != memTrlPtr->checksum ) return( FALSE ); return( TRUE ); } /* Insert and unlink a memory block from a list of memory blocks, with appropriate updates of memory checksums and other information. We keep the code for this in distinct functions to make sure that an exception- condition doesn't force an exit without the memory mutex unlocked */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \ static int insertMemBlock( INOUT MEM_INFO_HEADER **allocatedListHeadPtr, INOUT MEM_INFO_HEADER **allocatedListTailPtr, INOUT MEM_INFO_HEADER *memHdrPtr ) { MEM_INFO_HEADER *allocatedListHead = *allocatedListHeadPtr; MEM_INFO_HEADER *allocatedListTail = *allocatedListTailPtr; assert( isWritePtr( allocatedListHeadPtr, sizeof( MEM_INFO_HEADER * ) ) ); assert( allocatedListHead == NULL || \ isWritePtr( allocatedListHead, sizeof( MEM_INFO_HEADER ) ) ); assert( isWritePtr( allocatedListTailPtr, sizeof( MEM_INFO_HEADER * ) ) ); assert( allocatedListTail == NULL || \ isWritePtr( allocatedListTail, sizeof( MEM_INFO_HEADER ) ) ); assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER * ) ) ); /* Precondition: The memory block list is empty, or there's at least a one-entry list present */ REQUIRES( ( allocatedListHead == NULL && allocatedListTail == NULL ) || \ ( allocatedListHead != NULL && allocatedListTail != NULL ) ); /* If it's a new list, set up the head and tail pointers and return */ if( allocatedListHead == NULL ) { /* In yet another of gcc's endless supply of compiler bugs, if the following two lines of code are combined into a single line then the write to the first value, *allocatedListHeadPtr, ends up going to some arbitrary memory location and only the second write goes to the correct location (completely different code is generated for the two writes) This leaves krnlData->allocatedListHead as a NULL pointer, leading to an exception being triggered the next time that it's accessed */ #if defined( __GNUC__ ) && ( __GNUC__ == 4 ) *allocatedListHeadPtr = memHdrPtr; *allocatedListTailPtr = memHdrPtr; #else *allocatedListHeadPtr = *allocatedListTailPtr = memHdrPtr; #endif /* gcc 4.x compiler bug */ return( CRYPT_OK ); } /* It's an existing list, add the new element to the end */ REQUIRES( checkMemBlockHdr( allocatedListTail ) ); DATAPTR_SET( allocatedListTail->next, memHdrPtr ); setMemChecksum( allocatedListTail ); DATAPTR_SET( memHdrPtr->prev, allocatedListTail ); *allocatedListTailPtr = memHdrPtr; /* Postcondition: The new block has been linked into the end of the list */ ENSURES( DATAPTR_GET( allocatedListTail->next ) == memHdrPtr && \ DATAPTR_GET( memHdrPtr->prev ) == allocatedListTail && \ DATAPTR_ISNULL( memHdrPtr->next ) ); return( CRYPT_OK ); } CHECK_RETVAL STDC_NONNULL_ARG( ( 1, 2, 3 ) ) \ static int unlinkMemBlock( INOUT MEM_INFO_HEADER **allocatedListHeadPtr, INOUT MEM_INFO_HEADER **allocatedListTailPtr, INOUT MEM_INFO_HEADER *memHdrPtr ) { MEM_INFO_HEADER *allocatedListHead = *allocatedListHeadPtr; MEM_INFO_HEADER *allocatedListTail = *allocatedListTailPtr; MEM_INFO_HEADER *nextBlockPtr = DATAPTR_GET( memHdrPtr->next ); MEM_INFO_HEADER *prevBlockPtr = DATAPTR_GET( memHdrPtr->prev ); assert( isWritePtr( allocatedListHeadPtr, sizeof( MEM_INFO_HEADER * ) ) ); assert( allocatedListHead == NULL || \ isWritePtr( allocatedListHead, sizeof( MEM_INFO_HEADER ) ) ); assert( isWritePtr( allocatedListTailPtr, sizeof( MEM_INFO_HEADER * ) ) ); assert( allocatedListTail == NULL || \ isWritePtr( allocatedListTail, sizeof( MEM_INFO_HEADER ) ) ); assert( isWritePtr( memHdrPtr, sizeof( MEM_INFO_HEADER * ) ) ); REQUIRES( DATAPTR_ISVALID( memHdrPtr->next ) ); REQUIRES( DATAPTR_ISVALID( memHdrPtr->prev ) ); /* If we're removing the block from the start of the list, make the start the next block */ if( memHdrPtr == allocatedListHead ) { REQUIRES( prevBlockPtr == NULL ); *allocatedListHeadPtr = nextBlockPtr; } else { REQUIRES( prevBlockPtr != NULL && \ DATAPTR_GET( prevBlockPtr->next ) == memHdrPtr ); /* Delete from the middle or end of the list */ REQUIRES( checkMemBlockHdr( prevBlockPtr ) ); DATAPTR_SET( prevBlockPtr->next, nextBlockPtr ); setMemChecksum( prevBlockPtr ); } if( nextBlockPtr != NULL ) { REQUIRES( DATAPTR_GET( nextBlockPtr->prev ) == memHdrPtr ); REQUIRES( checkMemBlockHdr( nextBlockPtr ) ); DATAPTR_SET( nextBlockPtr->prev, prevBlockPtr ); setMemChecksum( nextBlockPtr ); } /* If we've removed the last element, update the end pointer */ if( memHdrPtr == allocatedListTail ) { REQUIRES( nextBlockPtr == NULL ); *allocatedListTailPtr = prevBlockPtr; } /* Clear the current block's pointers, just to be clean */ DATAPTR_SET( memHdrPtr->next, NULL ); DATAPTR_SET( memHdrPtr->prev, NULL ); return( CRYPT_OK ); } #if 0 /* Currently unused, in practice would be called from a worker thread that periodically touches all secure-data pages */ /* Walk the allocated block list touching each page. In most cases we don't need to explicitly touch the page since the allocated blocks are almost always smaller than the MMU's page size and simply walking the list touches them, but in some rare cases we need to explicitly touch each page */ static void touchAllocatedPages( void ) { KERNEL_DATA *krnlData = getKrnlData(); MEM_INFO_HEADER *memHdrPtr; const int pageSize = getSysVar( SYSVAR_PAGESIZE ); /* Lock the allocation object to ensure that other threads don't try to access them */ MUTEX_LOCK( allocation ); /* Walk down the list (which implicitly touches each page). If the allocated region is larger than the page size, explicitly touch each additional page */ for( memHdrPtr = krnlData->allocatedListHead; memHdrPtr != NULL; memHdrPtr = memHdrPtr->next ) { /* If the allocated region has pages beyond the first one (which we've already touched by accessing the header), explicitly touch those pages as well */ if( memHdrPtr->size > pageSize ) { BYTE *memPtr = ( BYTE * ) memHdrPtr + pageSize; int memSize = memHdrPtr->size; /* Touch each page. The rather convoluted expression in the loop body is to try and stop it from being optimised away - it always evaluates to true since we only get here if allocatedListHead != NULL, but hopefully the compiler won't be able to figure that out */ LOOP_LARGE( memSize = memHdrPtr->size, memSize > pageSize, memSize -= pageSize ) { if( *memPtr || krnlData->allocatedListHead != NULL ) memPtr += pageSize; ENSURES( LOOP_BOUND_OK ); } } } /* Unlock the allocation object to allow access by other threads */ MUTEX_UNLOCK( allocation ); } #endif /* 0 */ /**************************************************************************** * * * Init/Shutdown Functions * * * ****************************************************************************/ /* Create and destroy the secure allocation information */ CHECK_RETVAL \ int initAllocation( void ) { KERNEL_DATA *krnlData = getKrnlData(); int status; assert( isWritePtr( krnlData, sizeof( KERNEL_DATA ) ) ); /* Clear the allocated block list head and tail pointers */ DATAPTR_SET( krnlData->allocatedListHead, NULL ); DATAPTR_SET( krnlData->allocatedListTail, NULL ); /* Initialize any data structures required to make the allocation thread- safe */ MUTEX_CREATE( allocation, status ); ENSURES( cryptStatusOK( status ) ); return( CRYPT_OK ); } void endAllocation( void ) { KERNEL_DATA *krnlData = getKrnlData(); /* Destroy any data structures required to make the allocation thread- safe */ MUTEX_DESTROY( allocation ); } /**************************************************************************** * * * Secure Memory Allocation Functions * * * ****************************************************************************/ /* A safe malloc function that performs page locking if possible */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \ int krnlMemalloc( OUT_BUFFER_ALLOC_OPT( size ) void **pointer, IN_LENGTH int size ) { KERNEL_DATA *krnlData = getKrnlData(); MEM_INFO_HEADER *allocatedListHeadPtr, *allocatedListTailPtr; MEM_INFO_HEADER *memHdrPtr; BYTE *memPtr; const int alignedSize = roundUp( size, MEM_ROUNDSIZE ); const int memSize = MEM_INFO_HEADERSIZE + alignedSize + \ MEM_INFO_TRAILERSIZE; int status; static_assert( MEM_INFO_HEADERSIZE >= sizeof( MEM_INFO_HEADER ), \ "Memlock header size" ); /* Make sure that the parameters are in order */ if( !isWritePtr( pointer, sizeof( void * ) ) ) retIntError(); REQUIRES( size >= MIN_ALLOC_SIZE && size <= MAX_ALLOC_SIZE ); /* Clear return values */ *pointer = NULL; /* Allocate and clear the memory */ REQUIRES( rangeCheck( memSize, 1, MAX_INTLENGTH ) ); if( ( memPtr = clAlloc( "krnlMemAlloc", memSize ) ) == NULL ) return( CRYPT_ERROR_MEMORY ); memset( memPtr, 0, memSize ); /* Set up the memory block header and trailer */ memHdrPtr = ( MEM_INFO_HEADER * ) memPtr; INIT_FLAGS( memHdrPtr->flags, MEM_FLAG_NONE ); memHdrPtr->size = memSize; DATAPTR_SET( memHdrPtr->next, NULL ); DATAPTR_SET( memHdrPtr->prev, NULL ); /* Try to lock the pages in memory */ lockMemory( memHdrPtr ); /* Lock the memory list */ MUTEX_LOCK( allocation ); /* Check safe pointers */ if( !DATAPTR_ISVALID( krnlData->allocatedListHead ) || \ !DATAPTR_ISVALID( krnlData->allocatedListTail ) ) { MUTEX_UNLOCK( allocation ); clFree( "krnlMemAlloc", memPtr ); DEBUG_DIAG(( "Kernel memory data corrupted" )); retIntError(); } /* Insert the new block into the list */ allocatedListHeadPtr = DATAPTR_GET( krnlData->allocatedListHead ); allocatedListTailPtr = DATAPTR_GET( krnlData->allocatedListTail ); status = insertMemBlock( &allocatedListHeadPtr, &allocatedListTailPtr, memHdrPtr ); if( cryptStatusError( status ) ) { MUTEX_UNLOCK( allocation ); clFree( "krnlMemAlloc", memPtr ); retIntError(); } DATAPTR_SET( krnlData->allocatedListHead, allocatedListHeadPtr ); DATAPTR_SET( krnlData->allocatedListTail, allocatedListTailPtr ); /* Calculate the checksums for the memory block */ setMemChecksum( memHdrPtr ); /* Perform heap sanity-checking if the functionality is available */ #ifdef USE_HEAP_CHECKING /* Sanity check to detect memory chain corruption */ assert( _CrtIsValidHeapPointer( memHdrPtr ) ); assert( DATAPTR_ISNULL( memHdrPtr->next ) ); assert( DATAPTR_GET( krnlData->allocatedListHead ) == \ DATAPTR_GET( krnlData->allocatedListTail ) || \ _CrtIsValidHeapPointer( DATAPTR_GET( memHdrPtr->prev ) ) ); #endif /* USE_HEAP_CHECKING */ MUTEX_UNLOCK( allocation ); *pointer = memPtr + MEM_INFO_HEADERSIZE; return( CRYPT_OK ); } /* A safe free function that scrubs memory and zeroes the pointer. "You will softly and suddenly vanish away And never be met with again" - Lewis Carroll, "The Hunting of the Snark" */ CHECK_RETVAL STDC_NONNULL_ARG( ( 1 ) ) \ int krnlMemfree( INOUT_PTR void **pointer ) { KERNEL_DATA *krnlData = getKrnlData(); MEM_INFO_HEADER *allocatedListHeadPtr, *allocatedListTailPtr; MEM_INFO_HEADER *memHdrPtr; BYTE *memPtr; int status; assert( isReadPtr( pointer, sizeof( void * ) ) ); /* Make sure that the parameters are in order */ if( !isReadPtr( pointer, sizeof( void * ) ) || \ !isReadPtr( *pointer, MIN_ALLOC_SIZE ) ) retIntError(); /* Recover the actual allocated memory block data from the pointer */ memPtr = ( ( BYTE * ) *pointer ) - MEM_INFO_HEADERSIZE; if( !isReadPtr( memPtr, MEM_INFO_HEADERSIZE ) ) retIntError(); memHdrPtr = ( MEM_INFO_HEADER * ) memPtr; /* Lock the memory list */ MUTEX_LOCK( allocation ); /* Check safe pointers */ if( !DATAPTR_ISVALID( krnlData->allocatedListHead ) || \ !DATAPTR_ISVALID( krnlData->allocatedListTail ) ) { MUTEX_UNLOCK( allocation ); DEBUG_DIAG(( "Kernel memory data corrupted" )); retIntError(); } /* Make sure that the memory header information and canaries are valid */ if( !checkMemBlockHdr( memHdrPtr ) ) { MUTEX_UNLOCK( allocation ); /* The memory block doesn't look right, don't try and go any further */ DEBUG_DIAG(( "Attempt to free invalid memory segment at %lX inside " "memory block at %lX", *pointer, memHdrPtr )); retIntError(); } /* Perform heap sanity-checking if the functionality is available */ #ifdef USE_HEAP_CHECKING /* Sanity check to detect memory chain corruption */ assert( _CrtIsValidHeapPointer( memHdrPtr ) ); assert( DATAPTR_ISNULL( memHdrPtr->next ) || \ _CrtIsValidHeapPointer( DATAPTR_GET( memHdrPtr->next ) ) ); assert( DATAPTR_ISNULL( memHdrPtr->prev ) || \ _CrtIsValidHeapPointer( DATAPTR_GET( memHdrPtr->prev ) ) ); #endif /* USE_HEAP_CHECKING */ /* Unlink the memory block from the list */ allocatedListHeadPtr = DATAPTR_GET( krnlData->allocatedListHead ); allocatedListTailPtr = DATAPTR_GET( krnlData->allocatedListTail ); status = unlinkMemBlock( &allocatedListHeadPtr, &allocatedListTailPtr, memHdrPtr ); if( cryptStatusOK( status ) ) { DATAPTR_SET( krnlData->allocatedListHead, allocatedListHeadPtr ); DATAPTR_SET( krnlData->allocatedListTail, allocatedListTailPtr ); } MUTEX_UNLOCK( allocation ); /* Zeroise the memory (including the memlock info), free it, and zero the pointer */ zeroise( memPtr, memHdrPtr->size ); unlockMemory( memHdrPtr ); clFree( "krnlMemFree", memPtr ); *pointer = NULL; return( status ); }
C
#include<stdio.h> int fact(int n) { int i,fact=1; for(i=1;i<=n;i++) fact*=i; return fact; } int rec_fact(int n) { if(n==0||n==1) return 1; else return n*rec_fact(n-1); } int main() { int n; printf("Enter a number\n"); scanf("%d",&n); printf("Factorial of %d using non recursive function = %d \n Using recursive function = %d",n,fact(n),rec_fact(n)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf_sets.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: anowak <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/18 05:10:02 by anowak #+# #+# */ /* Updated: 2015/03/14 20:33:38 by anowak ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" int set_options(const char *restrict format, t_conv *new) { int i; i = 0; while (format[i] && ft_strchr("#0-+ ", format[i])) { if (format[i] == '#') new->sharp = 1; if (format[i] == '0') new->zero = 1; if (format[i] == '-') new->minus = 1; if (format[i] == '+') { new->plus = 1; new->space = 0; } if (format[i] == ' ' && !new->plus) new->space = 1; i++; } return (i); } int set_width(const char *restrict format, t_conv *new, t_pf *pf) { int i; i = 0; if (*format) { if (*format == '*') { new->width = (int)va_arg(pf->ap, int); if (new->width < 0) new->minus = 1; new->width = ft_abs(new->width); i++; } else if (ft_isdigit(*format)) { new->width = ft_atoi_neg(format); new->width = -new->width; while (ft_isdigit(*(format + i))) i++; } } return (i); } int set_long_size(const char *restrict format, t_conv *new) { if (*format == 'h' && *(format + 1) == 'h') { if (!(new->size)) new->size = 'H'; return (2); } else if (*format == 'l' && *(format + 1) == 'l') { new->size = 'L'; return (2); } else return (0); } int set_size(const char *restrict format, t_conv *new) { int ret; ret = 0; if (*format) { if (*(format + 1)) ret = set_long_size(format, new); if (ret == 2) return (ret); if (ft_strchr("hljz", *format)) { if (*format == 'h' && !(new->size)) new->size = 'h'; else if (*format == 'l' || *format == 'j' || *format == 'z') new->size = *format; return (1); } } return (0); } int set_type(const char *restrict format, t_conv *new) { if (*format) { new->type = *format; return (1); } return (0); }
C
/*Scrivere un programma che legge da tastiera 5 numeri interi e scrive sullo schermo la loro somma e la loro media. Il programma dovra' utilizzare solo 2 variabili . */ #include <stdio.h> int main() { int numero; int somma = 0; printf("Inserisci 5 numeri e ti dirò somma e media\n"); for(int i=0; i<5; i++) { printf("Inserisci un numero\n"); printf("%d° : ",i+1); scanf("%d",&numero); somma += numero; } printf("La somma è: %d\nla media è: %d\n",somma,somma/5); return 0; }
C
// Obj /d/ruzhou/npc/obj/jiuxi.c // llm 99/07/09 inherit ITEM; #include <ansi.h> void create() { set_name("酒席", ({ "jiuxi" })); if( clonep() ) set_default_object(__FILE__); else { set("long", "這是一桌五色齊全、香味四溢、豐盛的酒席。\n" HIG"八味拼盤(pingpan) 珍品杲羹(guogeng) 紅燒蹄膀(tipang)\n" "松子桂魚(guiyu) 香菇菜心(caixing) 清燉甲魚(jiayu)\n" "人蔘雞湯(jitang) 翠玉豆腐(doufu) 海蔘青蟹(qingxie)\n"NOR); set("unit", "桌"); set("value",1000); set("no_drop",1); set("no_get","你也太黑心了吧?竟想扛走這一桌的酒席?弄得動嗎?\n"); } setup(); } void init() { add_action("do_eat", "eat"); } int do_eat(string arg) { object me=this_player(); if( me->is_busy() ) return notify_fail("你上一個動作還沒有完成。\n"); if( query("food", me) >= me->max_food_capacity() ) return notify_fail("你已經吃太飽了,還想吃什麼?\n"); switch(arg) { case "pingpan": message_vision("$N輕輕挑出一塊拼盤冷菜,夾進嘴裏津津有味地嚼起來。\n",me); addn("food", 8, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 1, me); break; case "guogeng": message_vision("$N舀了一勺珍品果羹,“啊!”真是又香又甜。\n",me); addn("food", 2, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 8, me); break; case "tipang": message_vision("$N叉了一大塊的紅燒蹄膀,狼吞虎嚥地吃了下去。\n",me); addn("food", 20, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 2, me); break; case "guiyu": message_vision("$N夾出一塊松子桂魚,只覺入嘴滑嫩,鮮美無比。\n",me); addn("food", 10, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 2, me); break; case "caixing": message_vision("$N細心地挑了一些色香俱全的香菇菜心,慢慢地品味着,真香。\n",me); addn("food", 10, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 2, me); break; case "jiayu": message_vision("$N一下子挖出一塊甲魚,急不可耐地塞進嘴裏。\n",me); addn("food", 20, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 4, me); break; case "jitang": message_vision("$N湊着香味大大地嚐了一口人蔘雞湯,果真是鮮美無比。\n",me); addn("food", 2, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 15, me); break; case "doufu": message_vision("$N夾起一筷翠玉豆腐含在嘴裏,一臉的幸福滿足的神情。\n",me); addn("food", 8, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 1, me); break; case "qingxie": message_vision("$N悶着頭,剝開青蟹殼,一口一口地吮吸裏面鮮美的汁肉。\n",me); addn("food", 10, me); if( query("water", me)<me->max_water_capacity() ) addn("water", 1, me); break; default: write("你想吃什麼?菜上那麼多菜都不吃?\n"); break; } return 1; }
C
/*******************************************Libraries************************************/ #include <stdio.h> /**************************************Function Prototypes*******************************/ int factorial( int n ); /*********************************************Main***************************************/ int main() { int obj, box, comb; printf("This program calculates the r-combinations of a set with n distinct elements.\n"); do { printf("Enter the number (n) of distinct elements (n >= 0): "); scanf("%d", &obj); printf("\nEnter the value for r (0 <= r <= n): "); scanf("%d", &box); printf("\n"); if( obj < 0 ) printf("The number of distinct elements must be greater than or equal to 0. \n"); if( box < 0 || box > obj ) printf("The value of r must be greater than or equal to 0 and less than or equal to the number of distinct elements. \n"); }while( obj < 0 || box < 0 || box > obj ); comb = (factorial( obj ) / ( factorial( box ) * factorial( obj - box ))); printf("The number of %d-combinations for a set of %d distinct elements is: %d. \n", box, obj, comb); }//main /*******************************************Factorial************************************/ int factorial( int n ) { int x; int fact = 1; for( x = n; x > 0; x-- ) fact *= x; return fact; }//factorial
C
#include "pwa.h" #include "pwa_config.h" #include "typedef.h" s16 pwa_interp(PWA_CONST_SEG_ATTR const pwa_descriptor_t *pwa, s16 x) { /* calculate 'x' relative to start of the domain */ /* cast to u16 to enforce modular arithmetic instead of integer overflow */ u16 dx = (u16)x - (u16)pwa->min_d; u16 idx; s16 y; /* saturate 'x' below domain interval */ if(x < pwa->min_d) { dx = 0U; } /* calculate interval index = dx/step */ idx = dx >> pwa->step_d; /* calculate dx relative to start of interval */ dx = dx & pwa->msk_s; /* saturate 'x' above domain interval */ if(idx >= pwa->n_fn) { y = (*pwa->fn)[pwa->n_fn]; } else { /* 'x' is inside the domain */ s16 y1 = (*pwa->fn)[idx]; s16 y2 = (*pwa->fn)[idx+1U]; /* rounds half towards infinity */ if(y2 > y1) { u16 dy = (u16)y2 - (u16)y1; dy = (u16)(((u32)dy*dx + pwa->half_s) >> pwa->step_d); y = y1 + (s16)dy; } else { u16 dy = (u16)y1 - (u16)y2; dy = (u16)(((u32)dy*dx + pwa->half_s) >> pwa->step_d); y = y1 - (s16)dy; } } return y; }
C
#include <stdio.h> #include <stdlib.h> void plustwo(int one, int two); int main(int argc, char const *argv[]) { /* code */ int one = atoi(argv[1]); int two = atoi(argv[2]); plustwo(one, two); return 0; } void plustwo(int one, int two) { int t = one + two; printf("(%d) + (%d) = %d\n",one, two, t); }
C
#include "structure.h" #include "vecteur.h" #include "traitement.h" #include "pile.h" neurone* allouer_neurone(int nbrPoint){ neurone *n = malloc(sizeof(neurone)); n->v = malloc(nbrPoint*sizeof(double)); // n->distance = 0; n->nom = malloc(64*sizeof(char)); return n; } int nbrNeurone(int nbrVecteur){ return 5*(int)sqrt(nbrVecteur); } // neurone** tab_neurone(double* vecteur,int nbrVecteur,double borneS,double borneI){ // printf("--------------Tableau neurone ---------------\n"); // int nPoint = 4; // int nbrN = nbrNeurone(nbrVecteur); // neurone** tab_neurone = malloc(nbrN*sizeof(neurone*)); // neurone* neurone = allouer_neurone(nPoint); // srand(time(0)); // for (int l = 0;l<nbrN;l++){ // for(int i = 0;i<nPoint;i++){ // neurone->v[i]=nombre_aleatoire(vecteur[i]-borneI,vecteur[i]+borneS); // } // tab_neurone[l] = neurone; // // printf("%f , %f , %f , %f \n",tab_neurone[l]->v[0],tab_neurone[l]->v[1],tab_neurone[l]->v[2],tab_neurone[l]->v[3] ); // } // return tab_neurone; // } grilleN* allouer_grille(int hauteur,int largeur,int nPoint){ grilleN *grille = malloc(sizeof(grilleN)); grille->neurone = malloc(hauteur*sizeof(neurone*)); if(grille->neurone !=NULL){ for(int i=0;i<hauteur;i++){ grille->neurone[i] = (neurone *)malloc(largeur*sizeof(neurone)); } for (int i = 0 ;i < hauteur ; i++) { for (int j = 0; j < largeur; j++) { // grille->neurone[i][j] = malloc(sizeof(neurone)); grille->neurone[i][j].v = malloc(nPoint*(sizeof(double))); grille->neurone[i][j].nom = malloc(64*sizeof(char)); } } } return grille; } grilleN* grille_neurone(int largeur,int hauteur,int nPoint,double* vm,double borneI,double borneS){ printf("--------------- MATRICE DE NEURONES ----------------\n"); grilleN *grille = allouer_grille(hauteur,largeur,nPoint); // srand(time(0)); for(int i=0;i<hauteur;i++){ // for(int j=0;j<largeur;j++){ for(int k=0;k<nPoint;k++){ grille->neurone[i][j].v[k] = nombre_aleatoire(vm[k]-borneI,vm[k]+borneS); // grille->neurone[i][j].nom = ". " ; // printf("%f ", grille->neurone[i][j].v[k]); } } } return grille; } pile* bmu(data_vect** t,grilleN *g, int largeur, int hauteur, int nPoint,int posData){ pile* bm = NULL; double distance_min = 999.99; // ON PEUT AUSSI METTRRE A LA PREMIERE CASE DE LA MATRICE . double tmpDistance = 0.0; for(int i=0;i<hauteur;i++){ for(int j=0;j<largeur;j++){ tmpDistance = distance_euclidien(g->neurone[i][j].v,t[posData]->v,nPoint); if(distance_min == tmpDistance){ push(&bm,distance_min,i,j); } else if(tmpDistance < distance_min){ distance_min = tmpDistance; clear(&bm); push(&bm,distance_min,i,j); } } } // if(length(bm)>1){ // int posAl = (int)(rand()%length(bm)); // printf("length %d , %d posAl\n",length(bm),posAl ); // printf("apress ssss\n"); // return getElementFormPosition(bm,posAl); // } // else { // printf("apres s\n"); // return bm; // } return bm; } double getAlpha(int iteration,int totalIteration, double alphaInit){ return alphaInit * (double)(1.0-(double)iteration/(double)totalIteration); } int rayon(int taille,int pourcentage){ int rayonMax = (taille*pourcentage)/100; int voisinMin = 8; int rayon = 0; int r = (rayon*voisinMin); while(r < rayonMax) { r += (rayon * voisinMin); if(r < rayonMax) rayon++; // printf("%d \n",rayon ); } // if(rayon == 0 ) { // rayon = 1; // } rayon = (rayon == 0) ? 1 : rayon; // printf("Rayon : %d \n",rayon ); return rayon; } void voisinage(grilleN* n,double* vecteur,int largeur, int hauteur, int nPoint,pile* bmu,int rayon,double alpha){ int xInf,yInf,xSup,ySup; xInf = bmu->posX-rayon; if(xInf<0){ xInf = 0; } yInf = bmu->posY-rayon; if(yInf<0){ yInf = 0; } xSup = bmu->posX+rayon; if(xSup>=hauteur){ // xSup = largeur; xSup = hauteur-1; } ySup = bmu->posY+rayon; if(ySup>=largeur){ // ySup = hauteur; ySup = largeur-1; } // printf("X %d : %d , %d \n",bmu->posX,xInf, xSup ); // printf("Y %d : %d , %d \n",bmu->posY,yInf, ySup ); for(int x=xInf;x<=xSup;x++){ for(int y=yInf;y<=ySup;y++){ for(int i=0;i<nPoint;i++){ n->neurone[x][y].v[i] += alpha * (vecteur[i] - n->neurone[x][y].v[i]); } } } } void affichage(grilleN* n,int largeur,int hauteur){ for(int i = 0;i<hauteur;i++){ for(int j=0;j<largeur;j++){ if(strcmp("Iris-virginica",n->neurone[i][j].nom) == 0){ printf("S "); } else if(strcmp("Iris-setosa",n->neurone[i][j].nom) == 0){ printf("O "); } else if(strcmp("Iris-versicolor",n->neurone[i][j].nom) == 0){ printf("M "); } else { printf(". "); } } printf("\n"); } } void affichage_(grilleN* n,int largeur,int hauteur){ for(int i = 0;i<hauteur;i++){ for(int j=0;j<largeur;j++){ printf("%s",n->neurone[i][j].nom ); } printf("\n"); } } void apprentissage(grilleN* n,data_vect** t,int largeur,int hauteur,int nPoint,int nbV,int tirageMax){ int *tab = tableau_sans_doublons(nbV); int rayon_ = rayon(tirageMax,50); int nbIterTotal = (500 * nbV) * 0.5; int phase = nbIterTotal * 0.25; double alpha = 0.0; double alpha_init = 0.7; printf("Début \n"); affichage(n,largeur,hauteur); printf("\n"); for(int i=0;i<nbIterTotal;i++){ melanger_tableau(tab,nbV); if(i<=phase){ if(rayon_>1){ if(i==(phase*1/3)){ rayon_--; } else if(i==(phase*2/3)){ rayon_--; } } alpha = getAlpha(i,phase,alpha_init); } else { alpha = getAlpha(i,nbIterTotal,alpha_init)*0.1; rayon_ = 1; } pile* b = NULL; for(int j=0;j<nbV;j++){ b = bmu(t,n,largeur,hauteur,nPoint,tab[j]); n->neurone[b->posX][b->posY].nom = t[tab[j]]->nom; // strcpy(n->neurone[b->posX][b->posY]->nom,t[tab[j]]->nom); voisinage(n,t[tab[j]]->v,largeur,hauteur,nPoint,b,rayon_,alpha); clear(&b); } if(i == 0){ printf("Premiére étape : \n"); affichage(n,largeur,hauteur); printf("\n"); } if(i+1 == 12500){ printf("---------------------- \n" ); affichage(n,largeur,hauteur); printf("\n"); } if(i== nbIterTotal-1){ system("clear"); printf("Résultat final : \n"); affichage(n,largeur,hauteur); printf("\n"); printf("Pour Iris-virginica la lettre est : S \n"); printf("Pour Iris-setosa la lettre est : O \n" ); printf("Pour Iris-versicolor la lettre est : M \n" ); printf("\n"); } } } void afficherV(data_vect** v){ for(int i =0;i<150;i++){ printf("%s %d ",v[i]->nom,i ); } printf("\n" ); }
C
/*Mateus Agostinho dos Anjos //NUSP: 9298191 //Compilado com: gcc -Wall -ansi -pedantic -O2 -o ep1 ep1.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> /*constantes utilizadas */ #define gap -2 #define mismatch -1 #define match 1 #define SPACE '-' /*variaveis globais */ char *alignS; char *alignT; char *revS; char *revT; /*funcao que calcula o maximo entre a, b, c */ int max(int a, int b, int c) { if (a >= b && a >= c) return a; else if (b >= c) return b; else return c; } /*funcao que faz avaliacao de s[i] e t[j] */ int p(int i, int j, char *s, char *t) { if (s[i] == t[j]) return match; else return mismatch; } /*funcao que calcula a melhor pontuacao para um alinhamento //local entre s[1...i] e t[1...j]. Os indices i, j sao //armazenados em *x e *y */ void melhorPontuacao(char *s, char *t, int *x, int *y) { int *a; int i, j, m, n, anterior, temp, pontuacaoMax, iMax = 0, jMax = 0; m = (int) (strlen(s)); n = (int) (strlen(t)); pontuacaoMax = (m+n) * (-2); a = malloc (n * (int)sizeof(int)); for (j = 0; j <= n; j++) { a[j] = j * gap; } for (i = 1; i <= m; i++) { anterior = a[0]; a[0] = i * gap; for (j = 1; j <= n; j++) { temp = a[j]; a[j] = max((a[j] + gap), (anterior + p(i-1, j-1, s, t)), (a[j-1] + gap)); if (a[j] >= pontuacaoMax) { iMax = i; jMax = j; pontuacaoMax = a[j]; } anterior = temp; } } /*o indice inicial deste programa eh 0, enquanto o //indice dos algoritmos do livro comecam de 1 */ *x = iMax - 1; *y = jMax - 1; return; } /*funcao retirada do livro que calcula o bestScore do alinhamento //entre s[a..b] e t[c..d] */ void bestScore(char *s, int a, int b, char *t, int c, int d, int *fixSim) { int i, j, m, n, anterior, temp; m = b - a; n = d - c; for (j = 0; j <= n; j++) { fixSim[j] = j * gap; } for (i = 1; i <= m; i++) { anterior = fixSim[0]; fixSim[0] = i * gap; for (j = 1; j <= n; j++) { temp = fixSim[j]; fixSim[j] = max((fixSim[j] + gap), (anterior + p(i-1, j-1, s, t)), (fixSim[j-1] + gap)); anterior = temp; } } return; } /*funcao que inverte uma string x */ char *inverte(char *x) { char *inv; int i, j = 0; inv = malloc (strlen(x) * sizeof(char)); for (i = (strlen(x) - 1); i >= 0; i--) { inv[j] = x[i]; j++; } return inv; } /*Algoritmo 3.6 do livro (Setubal) //queremos alinhar s[a..b] com t[c..d] sendo a, b, c, d //inteiros encontrados previamente utilizando os alinhamentos //locais */ int align(char *s, char *t, int a, int b, int c, int d, int start, int end) { int posMax, vMax, i, j, middle; int *prefSim, *suffSim; char typeMax; prefSim = malloc ((b-a) * (int)sizeof(int)); suffSim = malloc ((d-c) * (int)sizeof(int)); /*se alguma sequencia for vazia, alinhamos o remanescente com gap */ if ((b - a) <= 0 || (d - c) <= 0) { end = start + max((b - a), (d - c), -10000); } else { /*pegamos aproximadamente o meio da sequencia */ i = floor((a + b)/2); /*Pagina 60 do livro diz: //BestScore(s[a..i-1], t[c..d], prefSim) returns in prefSim the //similarities between s[a..i-1] and t[c..j] for all j in c-1..d. */ bestScore(s, a, i-1, t, c, d, prefSim); /*Pagina 60 do livro diz: //BestScoreRev(s[i+1..b], t[c..d], suffSim) returns in suffSim the //similarities between s[i+1..b] and t[j+1..d] for all j in c-1..d //veja que para c-1 -> j+1 = (c-1) + 1 -> j+1 = c */ bestScore(s, i+1, b, t, c, d, suffSim);/*BestScoreRev*/ /*Seguindo o que esta no pseudoCodigo do livro temos: */ posMax = c - 1; typeMax = SPACE; vMax = prefSim[c-1] + gap + suffSim[c-1]; for (j = c; j <= d; j++) { if (prefSim[j-1] + p(i, j, s, t) + suffSim[j] > vMax) { posMax = j; typeMax = s[i]; vMax = prefSim[j-1] + p(i, j, s, t) + suffSim[j]; } if (prefSim[j] + gap + suffSim[j] > vMax) { posMax = j; typeMax = SPACE; vMax = prefSim[j] + gap + suffSim[j]; } } middle = (a+(i-1))/2; if (typeMax == SPACE) { end = align(s, t, a, i - 1, c, posMax, start, middle); alignS[middle] = s[i]; alignT[middle] = SPACE; end = align(s, t, i + 1, b, posMax + 1, d, middle + 1, end); } else { /*typeMax == SYMBOL*/ end = align(s, t, a, i - 1, c, posMax - 1, start, middle); alignS[middle] = s[i]; alignT[middle] = t[posMax]; end = align(s, t, i + 1, b, posMax + 1, d, middle + 1, end); } } return end; } /*funcao que imprime o alinhamento encontrado */ void imprimeAlinhamento(int n) { int i; printf("Alinhamento:\n"); for (i = 0; i < n; i++) { if (alignS[i] != 0) printf("%c", alignS[i]); else { printf("-"); } } printf("\n"); for (i = 0; i < n; i++) { if (alignT[i] != 0) printf("%c", alignT[i]); else { printf("-"); } } printf("\n"); return; } int main(int argv, char **argc) { char *s, *t; int a, b, c, d, n; /*as duas sequencias a serem alinhadas */ s = "ACTG"; t = "GCTC"; n = max(strlen(s), strlen(t), 0); /*Global*/ alignS = malloc (n * sizeof(char)); alignT = malloc (n * sizeof(char)); revS = malloc (strlen(s) * sizeof(char)); revT = malloc (strlen(t) * sizeof(char)); revS = inverte(s); revT = inverte(t); melhorPontuacao(s, t, &b, &d); melhorPontuacao(revS, revT, &a, &c); /*meus indices comecam do 0, enquanto o //algoritmo do livro indexa o inicio de 1 //por isso algumas operacoes desse tipo */ a = ((strlen(s) - 1) - a); c = ((strlen(t) - 1) - c); printf("s = %s\n", s); printf("t = %s\n", t); /*O alinhamento deve ser feito para s[a...b] e t[c...d] */ n = align(s, t, a, b, c, d, 1, max((b-a), (d-c), 0)); imprimeAlinhamento(n); /*liberando memoria*/ free(alignS); free(alignT); return 0; }
C
#include "link_list.h" typedef ListNode* PtrToListNode; #pragma region 通用 //----------------------------------------------------- void ListError(const char* errMsg) { perror(errMsg); } //----------------------------------------------------- void ListFailError(const char* errMsg) { perror(errMsg); exit(-1); } //----------------------------------------------------- //将数据封装成结点 inline PtrToListNode MakeListNode(ListElementType elem) { PtrToListNode p = calloc(1, sizeof(ListNode)); if (p) { p->ELement = elem; } else { ListFailError("Alloc Error!\n"); } return p; } //----------------------------------------------------- //判断某个位置是否位于链表的结尾 _Bool PosInListIsLast(ListPosition P) { return P->Next == NULL; } //----------------------------------------------------- //销毁某个结点 void DestroyListNode(PtrToListNode p) { //free(p->ELement); free(p); } //----------------------------------------------------- //获取链表的第一个节点的位置 ListElementType FirstOfList(List L) { return RetrieveFromListPos(HeadOfList(L)); } //获取链表的最后一个元素 ListElementType FinalOfList(List L) { return RetrieveFromListPos(TailOfList(L)); } //----------------------------------------------------- //从节点位置取出元素的值 ListElementType RetrieveFromListPos(ListPosition P) { return P->ELement; } //----------------------------------------------------- //打印链表 void DisplayList(List L, void(*pDisplayFunc)(ListPosition)) { for (ListPosition p = HeadOfList(L); p; p = p->Next) { pDisplayFunc(p); } } //遍历链表 void ListForEach(List L, void(*pFunc)(ListPosition)) { for (ListPosition p = HeadOfList(L); p; p = p->Next) { pFunc(p); } } //带参遍历链表 void ListForEachWithArg(List L, void(*pFunc)(ListPosition, void*), void* arg) { for (ListPosition p = HeadOfList(L); p; p = p->Next) { pFunc(p, arg); } } //----------------------------------------------------- //查找某个元素的位置 ListPosition FindIf(_Bool(*pFunc)(), List L) { for (ListPosition P = HeadOfList(L); P; P = P->Next) { if (pFunc(P->ELement)) return P; } return NULL; } //----------------------------------------------------- /* 链表快速排序 */ //----------------------------------------------------- static void SwapNode(PtrToListNode p1, PtrToListNode p2) { ListElementType tmp = p1->ELement; p1->ELement = p2->ELement; p2->ELement = tmp; } //----------------------------------------------------- void static SortListBase(PtrToListNode pHead, PtrToListNode pEnd, int(*pCmp)(ListElementType, ListElementType)) { if (pHead) { if (pHead != pEnd) { PtrToListNode pIndex = pHead; for (PtrToListNode pGo = pHead->Next; pGo != pEnd; pGo = pGo->Next) { if (pCmp(pGo->ELement, pHead->ELement) > 0) { pIndex = pIndex->Next; SwapNode(pGo, pIndex); } } SwapNode(pIndex, pHead); SortListBase(pHead,pIndex, pCmp); SortListBase(pIndex->Next, pEnd, pCmp); } } } void SortList(List lst, int(*pCmp)(ListElementType, ListElementType)) { #ifdef SINGLE_LINK_LIST SortListBase(HeadOfList(lst), NULL, pCmp); #elif DOUBLE_LINK_LIST SortListBase(lst.Head, lst.Tail, pCmp); #endif } #pragma endregion #ifdef SINGLE_LINK_LIST //----------------------------------------------------- //初始化链表 void InitList(List* L) { *L = NULL; } //----------------------------------------------------- //判断链表是否为空 _Bool ListIsEmpty(List L) { return L == NULL; } //----------------------------------------------------- //查找某个元素的位置 ListPosition FindInList(ListElementType X, List L) { for (ListPosition P = L; P; P = P->Next) { if (P->ELement == X) return P; } return NULL; } //----------------------------------------------------- //从链表中删除某个元素 void DeleteFromList(ListElementType X, List L) { ListPosition P, TmpCell; P = FindPrePosFromList(X, L); if (!PosInListIsLast(P)) { TmpCell = P->Next; P->Next = TmpCell->Next; free(TmpCell); } } //----------------------------------------------------- //尾插入元素 List PushBack(ListElementType X, List L) { if (!L)//如果空 { L = MakeListNode(X); } else { PtrToListNode p; for (p = L; p->Next; p = p->Next) ; p->Next = MakeListNode(X); } return L; } //----------------------------------------------------- //查找某个元素的上一个位置 ListPosition FindPrePosFromList(ListElementType X, List L) { for (ListPosition P = L; P->Next; P = P->Next) { if (P->Next->ELement == X) return P; } return NULL; } //----------------------------------------------------- //头插入元素 List PushFront(ListElementType X, List L) { if (!L) { L = MakeListNode(X); } else { PtrToListNode p = MakeListNode(X); p->Next = L; L = p; } return L; } //----------------------------------------------------- //删除尾部 List PopBack(List L) { if (!L) //空表 { //do nothing } else if (!L->Next)//有1个元素 { DestroyListNode(HeadOfList(L)); L = NULL; } else //2个以上 { PtrToListNode p; for (p = L; p->Next->Next; p = p->Next) ; DestroyListNode(p->Next); p->Next = NULL; } return L; } //----------------------------------------------------- //删除头部 List PopFront(List L) { if (ListIsEmpty(L)) { perror("List has nothing\n"); return L; } PtrToListNode p = HeadOfList(L)->Next; DestroyListNode(HeadOfList(L)); return p; } //尾插入元素 int ListPushBack(ListElementType X, List* L) { if (!L) { return -1; } if (!*L)//如果空 { *L = MakeListNode(X); } else { PtrToListNode p; for (p = HeadOfList(*L); p->Next; p = p->Next) ; p->Next = MakeListNode(X); } return 0; } //头插入元素 int ListPushFront(ListElementType X, List* L) { if (!L) { return -1; } if (!*L) { *L = MakeListNode(X); } else { PtrToListNode p = MakeListNode(X); p->Next = *L; *L = p; } return 0; } //删除尾部 int ListPopBack(List* L) { if (!L || !*L) //空表 { return -1; } else if (!(*L)->Next)//有1个元素 { DestroyListNode(HeadOfList(*L)); *L = NULL; } else //2个以上 { PtrToListNode p; for (p = HeadOfList(*L); p->Next->Next; p = p->Next) ; DestroyListNode(p->Next); p->Next = NULL; } return 0; } //删除头部 int ListPopFront(List* L) { if (ListIsEmpty(*L)) { perror("List has nothing\n"); return -1; } PtrToListNode p = HeadOfList(*L)->Next; DestroyListNode(HeadOfList(*L)); (*L) = p; return 0; } //----------------------------------------------------- //往某个位置放入某个元素 void InsertToList(ListElementType X, ListPosition P) { if (!P) { perror("Position is null!\n"); return; } PtrToListNode TmpCell = MakeListNode(X); if (TmpCell) { TmpCell->ELement = X; TmpCell->Next = P->Next; P->Next = TmpCell; } } //----------------------------------------------------- //清空链表 int DestroyList(List* L) { if (!ListIsEmpty(*L)) { for (ListPosition pcur = HeadOfList(*L), pbark; pcur; pcur = pbark) { pbark = pcur->Next; free(pcur); } } *L = NULL; return 0; } //----------------------------------------------------- //获取链表头节点位置 ListPosition HeadOfList(List L) { return L; } //----------------------------------------------------- //返回上一个位置 ListPosition AdvanceOfListPos(ListPosition P, List L) { for (ListPosition pt = L; pt; pt = pt->Next) { if (P == pt->Next) return pt; } return NULL; } //获取链表尾结点位置 ListPosition TailOfList(List L) { ListPosition p = L; if (p) { for (; p->Next; p = p->Next) ;//Do nothing } return p; } //----------------------------------------------------- unsigned int ListSize(List L) { ListPosition p = HeadOfList(L); unsigned int len = 0; while (p) { ++len; p = p->Next; } return len; } #elif DOUBLE_LINK_LIST //----------------------------------------------------- //初始化链表 void InitList(List* L) { if (L) { L->Head = L->Tail = NULL; L->Length = 0; } } //----------------------------------------------------- //判断链表是否为空 _Bool ListIsEmpty(List L) { return L.Head == NULL; } //----------------------------------------------------- //查找某个元素的位置 ListPosition FindInList(ListElementType X, List L) { for (ListPosition P = HeadOfList(L); P; P = P->Next) { if (P->ELement == X) return P; } return NULL; } ListPosition RFindInList(ListElementType X, List L) { for (ListPosition P = TailOfList(L); P; P = P->Pre) { if (P->ELement == X) return P; } return NULL; } //----------------------------------------------------- //查找某个元素的上一个位置 ListPosition FindPrePosFromList(ListElementType X, List L) { for (ListPosition P = HeadOfList(L); P->Next; P = P->Next) { if (P->Next->ELement == X) return P; } return NULL; } //----------------------------------------------------- //尾插入元素 List PushBack(ListElementType X, List L) { if (ListIsEmpty(L))//如果空 { L.Head = MakeListNode(X); L.Tail = L.Head; } else { PtrToListNode NewNode = MakeListNode(X); TailOfList(L)->Next = NewNode; NewNode->Pre = TailOfList(L); L.Tail = NewNode; } ++L.Length; return L; } //----------------------------------------------------- //头插入元素 List PushFront(ListElementType X, List L) { if (ListIsEmpty(L))//如果空 { L.Head = MakeListNode(X); L.Tail = L.Head; } else { PtrToListNode NewNode = MakeListNode(X); HeadOfList(L)->Pre = NewNode; NewNode->Next = HeadOfList(L); L.Head = NewNode; } ++L.Length; return L; } //----------------------------------------------------- //删除尾部 List PopBack(List L) { if (ListIsEmpty(L)) //空表 { //do nothing } else if (L.Head == L.Tail)//有1个元素 { DestroyListNode(HeadOfList(L)); L.Tail = L.Head = NULL; L.Length = 0; } else //2个以上 { PtrToListNode Barkup = TailOfList(L)->Pre; DestroyListNode(TailOfList(L)); L.Tail = Barkup; --L.Length; } return L; } //----------------------------------------------------- //删除头部 List PopFront(List L) { if (ListIsEmpty(L)) { perror("List has nothing\n"); return L; } PtrToListNode Barkup = HeadOfList(L)->Next; DestroyListNode(HeadOfList(L)); L.Head = Barkup; --L.Length; return L; } //尾插入元素 int ListPushBack(ListElementType X, List* L) { if (!L) { return -1; } if (ListIsEmpty(*L))//如果空 { L->Head = MakeListNode(X); L->Tail = L->Head; } else { PtrToListNode NewNode = MakeListNode(X); TailOfList(*L)->Next = NewNode; NewNode->Pre = TailOfList(*L); L->Tail = NewNode; } ++L->Length; return 0; } //头插入元素 int ListPushFront(ListElementType X, List* L) { if (!L) { return -1; } if (ListIsEmpty(*L))//如果空 { L->Head = MakeListNode(X); L->Tail = L->Head; } else { PtrToListNode NewNode = MakeListNode(X); HeadOfList(*L)->Pre = NewNode; NewNode->Next = HeadOfList(*L); L->Head = NewNode; } ++L->Length; return 0; } //删除尾部 int ListPopBack(List* L) { if (!L) { return -1; } if (ListIsEmpty(*L)) //空表 { //do nothing } else if (L->Head == L->Tail)//有1个元素 { DestroyListNode(HeadOfList(*L)); L->Tail = L->Head = NULL; L->Length = 0; } else //2个以上 { PtrToListNode Barkup = TailOfList(*L)->Pre; DestroyListNode(TailOfList(*L)); L->Tail = Barkup; --L->Length; } return 0; } //删除头部 int ListPopFront(List* L) { if (!L) { return -1; } if (ListIsEmpty(*L)) { perror("List has nothing\n"); return -1; } PtrToListNode Barkup = HeadOfList(*L)->Next; DestroyListNode(HeadOfList(*L)); L->Head = Barkup; --L->Length; return 0; } //----------------------------------------------------- //往某个位置放入某个元素 void InsertToList(ListElementType X, ListPosition P) { if (!P) { perror("Position is null!\n"); return; } PtrToListNode TmpCell = MakeListNode(X); if (TmpCell) { TmpCell->ELement = X; if (P->Next)//不是最后一个位置 { P->Next->Pre = TmpCell; TmpCell->Next = P->Next; P->Next = TmpCell; TmpCell->Pre = P; } else { P->Next = TmpCell; TmpCell->Pre = P; } //TmpCell->Next = P->Next; //P->Pre->Next = TmpCell; //P->Pre = TmpCell; } } //----------------------------------------------------- //获取链表头节点位置 ListPosition HeadOfList(List L) { return L.Head; } //----------------------------------------------------- //返回上一个位置 ListPosition AdvanceOfListPos(ListPosition P) { return P->Pre; } //---------------------------------------------------- //获取链表尾结点位置 ListPosition TailOfList(List L) { return L.Tail; } //----------------------------------------------------- unsigned int ListSize(List L) { return L.Length; } //----------------------------------------------------- //清空链表 int DestroyList(List* L) { if (!L) { return -1; } if (!ListIsEmpty(*L)) { for (ListPosition pcur = HeadOfList(*L), pbark; pcur; pcur = pbark) { pbark = pcur->Next; free(pcur); } } L->Head = L->Tail = NULL; L->Length = 0; return 0; } #endif // SINGLE_LINKE_LIST
C
/*******************/ /* ͼƬļϳ */ /*******************/ /* ļԶƵʽȡԶƵʽд뵽һļУʵһļݣͨĺ׺ļij */ #include <stdio.h> #include <stdlib.h> int main4() { FILE *f_pic, *f_file, *f_finish; char pic_name[20], file_name[20], finish_name[20], ch; printf("Please input compose image name: "); scanf("%s", pic_name); printf("\nPlease input compose other file name: "); scanf("%s", file_name); printf("\nPlease input compose finish file name: "); scanf("%s", finish_name); if (!(f_pic = fopen(pic_name, "rb"))) { printf("Con not open %s!", pic_name); exit(0); } if (!(f_file = fopen(file_name, "rb"))) { printf("Con not open %s!", file_name); exit(0); } if (!(f_finish = fopen(finish_name, "wb"))) { printf("Con not open %s!", finish_name); exit(0); } while (!(feof(f_pic))) { ch = fgetc(f_pic); fputc(ch, f_finish); } fclose(f_pic); while (!(feof(f_file))) { ch = fgetc(f_file); fputc(ch, f_finish); } fclose(f_file); fclose(f_finish); return 0; }
C
#include <stdio.h> #define MAX_LINEA 80 #define MAX_FRASE 40 int main(int argc, char *argv[]) { int a, b; char frase[MAX_FRASE+1]; char linea[MAX_LINEA+1]; printf("Dame el valor de un entero: "); gets(linea); sscanf(linea, "%d", &a); printf("Introduce ahora una frase: "); gets(frase); printf("Ahora dame el valor de otro entero: "); gets(linea); sscanf(linea, "%d", &b); printf("Enteros leidos: %d y %d\n", a, b); printf("Frase leida: '%s'\n", frase); return 0; }
C
#include "../includes/ft_printf.h" int ft_printf(const char *format, ...) { t_printf list; int i; int j; i = 0; va_start(list.argc, format); list.i = 0; list.format = (char *)format; init_struct_functions(&list); init_display_functions(&list); list.count = 0; while (list.format[list.i] != '\0') { if (list.format[list.i] == '%') { init_struct(&list); if (list.format[list.i + 1] != '\0') list.i++; while ((is_conversion(list) == -1) && (list.format[list.i] != '\0')) { if ((j = is_flag(list)) != -1) { if (list.format[list.i + 1] == 'l' || list.format[list.i + 1] == 'h') list.i++; list.add_functions[j](&list); } list.i++; } if ((j = is_conversion(list)) > -1) list.display[j](&list); } else { list.count++; ft_putchar(list.format[list.i]); } list.i++; } return (list.count); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* util.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rlintill <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/29 17:19:37 by rlintill #+# #+# */ /* Updated: 2020/02/13 16:18:22 by rlintill ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" char *space_offset(t_env *env, char *res, int minus, int flag_char) { char *offset; int leng; offset = NULL; leng = ft_strlen(res); if (flag_char) leng = 1; if (minus && !env->is_precision) leng++; if (env->offset - leng > 0) { offset = ft_memalloc((size_t)(env->offset - leng + 1)); offset = ft_memset(offset, ' ', env->offset - leng); offset[env->offset - leng + 1] = '\0'; if (!env->minus) res = ft_strjoin(offset, res); else res = ft_strjoin(res, offset); env->res += (env->offset - leng); } if (offset != NULL) ft_memdel((void*)&offset); return (res); } char *zero_offset(t_env *env, char *res, int minus) { char *offset; int leng; offset = NULL; leng = ft_strlen(res); if (minus || (env->zero && env->plus)) leng += 1; if (env->offset - leng > 0) { offset = ft_memalloc((size_t)(env->offset - leng + 1)); offset = ft_memset(offset, '0', env->offset - leng); offset[env->offset - leng + 1] = '\0'; if (!env->minus) res = ft_strjoin(offset, res); env->res += (env->offset - leng); } if (minus) { res = ft_strjoin("-", res); env->res++; } if (offset != NULL) ft_memdel((void*)&offset); return (res); } char *precision(t_env *env, char *res, int minus) { char *offset; int leng; offset = NULL; leng = ft_strlen(res); if (env->precision - leng > 0) { offset = ft_memalloc((size_t)(env->precision - leng + 1)); offset = ft_memset(offset, '0', env->precision - leng); offset[env->precision - leng + 1] = '\0'; res = ft_strjoin(offset, res); env->res += (env->precision - leng); } if (minus) { res = ft_strjoin("-", res); env->res++; } if (offset != NULL) ft_memdel((void*)&offset); return (res); } void plus_minus(t_env *env, char **res, int minus, int num) { if (!minus && env->plus && num >= 0) { *res = ft_strjoin("+", *res); env->res++; } } void space(t_env *env, char **res, int minus) { if (env->space && !minus) { *res = ft_strjoin(" ", *res); env->res++; } }
C
#include "edna.h" size_t bufgetpos(Buffer *buf) { assert(buf != NULL); return buf->pos; } size_t bufgetlen(Buffer *buf) { assert(buf != NULL); return buf->len; } Line * bufprobe(Buffer *buf, size_t off) { assert(buf != NULL); if (off > buf->len) return NULL; return walk(buf->top, off); } int bufseek(Buffer *buf, int whence, long off) { int dir; Line *(*get)(Line *); Line *li; assert(buf != NULL); assert(off > 0 || whence != BUF_SET); assert(off < 0 || whence != BUF_END); if (off == 0) return 0; switch (whence) { case BUF_SET: li = buf->top; break; case BUF_CUR: li = buf->cur; break; case BUF_END: li = buf->bot; break; default: return -1; } if (off > 0) { get = getnext; dir = 1; } else { get = getprev; dir = -1; } for (;;) { li = get(li); if (li == NULL) break; buf->cur = li; buf->pos += dir; if (--off == 0) break; } if (off == 0) return 0; else return -1; } int bufseekline(Buffer *buf, Line *li) { size_t off; Line *tmp; off = 0; for (tmp = buf->top; tmp && tmp != li; tmp = getnext(tmp)) ++off; if (!tmp) return -1; buf->pos = off; buf->cur = tmp; return 0; } Line * buftell(Buffer *buf) { return buf->cur; }
C
//a153: T902**************************************************************************************************** /* #include <iostream> using namespace std; int main() { printf("數字: 16 40 38 6 30 11"); } */ #include<stdio.h> #include<stdlib.h> #include<time.h> int main() { int a[6], i, j; srand(time(NULL)); for(i=0;i<6;i++){ a[i]=rand()%49+1; for(j=6;j>=0;j--) if(a[i]==a[j]&&i!=j){ a[i]=rand()%49+1; } printf("%d ",a[i]); } return 0; }
C
#include <stdio.h> #ifndef N #define N 256 #endif int findFirstRepeated(unsigned char[]); int main(void) { findFirstRepeated("0012"); return 0; } int findFirstRepeated(unsigned char sentence []) { unsigned char allChars [N] = {0}; //arreglo de caracteres para contar en 0's unsigned char *ptr; unsigned char tmp; unsigned char found = 0; unsigned char allRep = 0; printf("La oracion es: %s\n", sentence); for(ptr=sentence; *ptr!=0, found!=1; ptr++){ tmp = (int)*ptr; allChars[tmp]++; if(allChars[tmp]>1){ printf("\n \nWe found one"); printf("The first character found was: %c\n", tmp); return 1; } } return 1; }
C
/* * main.c * * Created on: 31 May 2016 * Author: ajuaristi <[email protected]> */ #include <stdio.h> #include <signal.h> #include <getopt.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <linux/videodev2.h> #include <sys/stat.h> #include "utils.h" #include "appbase.h" #include "uvc.h" #define DEFAULT_WAIT_TIME 5 int stop; #define SHOULD_STOP(v) (stop = v) #define IS_STOPPED() (stop) static char *create_debug_filename() { #define COUNT_LIMIT 9 static unsigned int count = 0; char filename_template[] = "picture"; size_t size = sizeof(filename_template) + 2; char *filename = ec_malloc(size); snprintf(filename, size, "%s.%d", filename_template, count++); if (count > COUNT_LIMIT) count = 0; return filename; #undef COUNT_LIMIT } static void write_to_disk(const unsigned char *data, size_t size) { FILE *f; char *filename = create_debug_filename(); f = fopen(filename, "w"); if (f) { fwrite(data, size, 1, f); fclose(f); fprintf(stderr, "DEBUG: Frame written to file '%s'\n", filename); } free(filename); } static void print_usage_and_exit(const char *name) { if (name) { printf("Usage: %s [OPTIONS] <app name> <username> <password>\n" "Options:\n" " -w secs Sleep this amount of seconds between shots\n" " -d Display debug messages\n" " -s Take one single shot and exit\n" " -j Convert frames to JPEG\n" " -S Stream as fast as possible\n", name); } exit(1); } static void sighandler(int s) { char *signame; switch (s) { case SIGINT: signame = "SIGINT"; break; case SIGQUIT: signame = "SIGQUIT"; break; case SIGTERM: signame = "SIGTERM"; break; case SIGABRT: signame = "SIGABRT"; break; case SIGTRAP: signame = "SIGTRAP"; break; default: signame = NULL; break; } if (signame) fprintf(stderr, "Received %s. Exiting.", signame); else fprintf(stderr, "Received %d. Exiting.", s); /* Stop! */ SHOULD_STOP(1); } static void do_stream(struct appbase *ab, bool jpeg) { struct camera *c; c = uvc_open(); if (!c) fatal("Could not find any camera for capturing pictures"); c->frame = uvc_alloc_frame(320, 240, V4L2_PIX_FMT_YUYV); if (!c->frame) fatal("Could not allocate enough memory for frames"); if (!uvc_init(c)) fatal("Could not start camera for streaming"); while (!IS_STOPPED() && uvc_capture_frame(c)) { if (jpeg) frame_convert_yuyv_to_jpeg(c->frame); if (!appbase_push_frame(ab, c->frame->frame_data, c->frame->frame_bytes_used, &c->frame->capture_time)) { fprintf(stderr, "ERROR: Could not capture frame\n"); break; } c->frame->frame_bytes_used = 0; } uvc_close(c); } void do_capture(struct appbase *ab, unsigned int wait_time, bool oneshot, bool jpeg, bool debug) { struct camera *c; struct frame *f; while (!IS_STOPPED()) { c = uvc_open(); if (!c) fatal("Could not find any camera for capturing pictures"); c->frame = uvc_alloc_frame(320, 240, V4L2_PIX_FMT_YUYV); if (!c->frame) fatal("Could not allocate enough memory for frames"); if (!uvc_init(c)) fatal("Could not start camera for streaming"); if (uvc_capture_frame(c)) { f = c->frame; if (jpeg) frame_convert_yuyv_to_jpeg(f); if (!appbase_push_frame(ab, f->frame_data, f->frame_bytes_used, &f->capture_time)) fprintf(stderr, "ERROR: Could not send frame\n"); if (debug) write_to_disk(f->frame_data, f->frame_bytes_used); memset(f->frame_data, 0, f->frame_size); f->frame_bytes_used = 0; } else { fprintf(stderr, "ERROR: Could not capture frame\n"); } uvc_close(c); if (oneshot) break; /* * sleep(3) should not interfere with our signal handlers, * unless we're also handling SIGALRM */ sleep(wait_time); } } int main(int argc, char **argv) { int opt; char *endptr; long int wait_time = DEFAULT_WAIT_TIME; bool debug = false, oneshot = false, stream = false, jpeg = false; struct sigaction sig; struct appbase *ab; /* Parse command-line options */ while ((opt = getopt(argc, argv, "w:dsSj")) != -1) { switch (opt) { case 'w': wait_time = strtol(optarg, &endptr, 10); if (*endptr || wait_time < 0) print_usage_and_exit(argv[0]); break; case 'd': debug = true; break; case 's': oneshot = true; break; case 'S': stream = true; break; case 'j': jpeg = true; break; default: print_usage_and_exit(argv[0]); break; } } /* Set signal handlers and set stop condition to zero */ SHOULD_STOP(0); memset(&sig, 0, sizeof(sig)); sig.sa_handler = sighandler; sig.sa_flags = SA_RESETHAND; sigemptyset(&sig.sa_mask); sigaction(SIGINT, &sig, NULL); sigaction(SIGQUIT, &sig, NULL); sigaction(SIGTERM, &sig, NULL); sigaction(SIGABRT, &sig, NULL); sigaction(SIGTRAP, &sig, NULL); /* Set up Appbase handle * We need the app name, username and password to build the REST URL, and these * should came now as parameters. We expect optind to point us to the first one. */ if (argc - optind < 3) print_usage_and_exit(argv[0]); ab = appbase_open( argv[optind], // app name argv[optind + 1], // username argv[optind + 2], // password false); // streaming off if (!ab) fatal("Could not log into Appbase"); if (debug) { appbase_enable_progress(ab, true); appbase_enable_verbose(ab, true); } if (stream) do_stream(ab, jpeg); else do_capture(ab, wait_time, oneshot, jpeg, debug); appbase_close(ab); return 0; }
C
#include<stdio.h> #include<stdbool.h> /** * Definition for singly-linked list. */ struct ListNode { int val; struct ListNode *next; }; struct ListNode* removeElements(struct ListNode* head, int val){ struct ListNode *pNode = head; struct ListNode *pCur = NULL; struct ListNode *pPre = NULL; if(NULL == head) { return NULL; } while(pNode) { if(pNode->val != val) { break; } else { pNode = pNode->next; } } pCur = pNode; pPre = pNode; while(pCur) { if(pCur->val == val) { pPre->next = pCur->next; } else { pPre = pCur; } pCur = pCur->next; } return pNode; }
C
#include <stdio.h> #include <signal.h> void handler(int signo) { // unsafe, just for demo printf("handler\n"); } /** * Demonstrates that custom handlers for SIGCONT are deferred until SIGCONT is * unblocked, even though the signal will still wake the process immediatley */ int main(int argc, char* argv[]){ sigset_t block_set, prev_set; struct sigaction sa; // block SIGCONT sigemptyset(&block_set); sigaddset(&block_set, SIGCONT); sigprocmask(SIG_BLOCK, &block_set, &prev_set); // create handler for SIGCONT sa.sa_handler = handler; sigaction(SIGCONT, &sa, NULL); printf("stopping...\n"); raise(SIGSTOP); printf("process resumed by SIGCONT\n"); // unblock SINGCONT, this should trigger handler sigprocmask(SIG_SETMASK, &prev_set, NULL); }
C
/*----------------------------------------------------------------- LOG GEM - Graphics Environment for Multimedia GemFuncUtil.h - contains functions for graphics - part of GEM Copyright (c) 1997-2000 Mark Danks. [email protected] Copyright (c) Gnther Geiger. [email protected] Copyright (c) 2001-2002 IOhannes m zmoelnig. forum::fr::umlute. IEM. [email protected] For information on usage and redistribution, and for a DISCLAIMER OF ALL WARRANTIES, see the file, "GEM.LICENSE.TERMS" in this distribution. -----------------------------------------------------------------*/ #ifndef INCLUDE_GEMFUNCUTIL_H_ #define INCLUDE_GEMFUNCUTIL_H_ #ifdef __APPLE__ #include <Carbon/Carbon.h> #endif #include "Base/GemExportDef.h" /* this should be included for ALL platforms: * should we define __MMX__ for windows in there ? */ #include "config.h" #include "GemSIMD.h" #include "GemMath.h" // for rand() #include <stdlib.h> /////////////////////////////////////////////////////////////////////////////// // powerOfTwo // get the next higher 2^n-number (if value is'nt 2^n by itself) /////////////////////////////////////////////////////////////////////////////// inline int powerOfTwo(int value) { /* int x = 1; // while(x <= value) x <<= 1; while(x < value) x <<= 1; return(x); */ // optimization from "Hacker's Delight" // - above loop executes in 4n+3 instructions, where n is the power of 2 of returned int // - below code is branch-free and only 12 instructions! value = value - 1; value = value | (value >> 1); value = value | (value >> 2); value = value | (value >> 4); value = value | (value >> 8); value = value | (value >> 16); return (value + 1); } /////////////////////////////////////////////////////////////////////////////// // min/max functions // /////////////////////////////////////////////////////////////////////////////// #ifndef MIN inline int MIN(int x, int y) { return (x<y)?x:y; } inline float MIN(float x, float y) { return (x<y)?x:y; } #endif #ifndef MAX inline int MAX(int x, int y) { return (x>y)?x:y; } inline float MAX(float x, float y) { return (x>y)?x:y; } #endif inline unsigned char TRI_MAX(unsigned char v1, unsigned char v2, unsigned char v3){ if (v1 > v2 && v1 > v3) return(v1); if (v2 > v3) return(v2); return(v3); } inline unsigned char TRI_MIN(unsigned char v1, unsigned char v2, unsigned char v3){ if (v1 < v2 && v1 < v3) return(v1); if (v2 < v3) return(v2); return(v3); } /////////////////////////////////////////////////////////////////////////////// // Clamp functions // /////////////////////////////////////////////////////////////////////////////// ////////// // Clamp a value high inline unsigned char CLAMP_HIGH(int x) { return((unsigned char )((x > 255) ? 255 : x)); } ////////// // Clamp a value low inline unsigned char CLAMP_LOW(int x) { return((unsigned char )((x < 0) ? 0 : x)); } ////////// // Clamp an int to the range of an unsigned char inline unsigned char CLAMP(int x) { return((unsigned char)((x > 255) ? 255 : ( (x < 0) ? 0 : x))); } ////////// // Clamp a float to the range of an unsigned char inline unsigned char CLAMP(float x) { return((unsigned char)((x > 255.f) ? 255.f : ( (x < 0.f) ? 0.f : x))); } ////////// // Clamp a float to 0. <= x <= 1.0 inline float FLOAT_CLAMP(float x) { return((x > 1.f) ? 1.f : ( (x < 0.f) ? 0.f : x)); } ///////// // Clamp the Y channel of YUV (16%235) inline unsigned char CLAMP_Y(int x) { return((unsigned char)((x > 235) ? 235 : ( (x < 16) ? 16 : x))); } /////////////////////////////////////////////////////////////////////////////// // Multiply and interpolation // /////////////////////////////////////////////////////////////////////////////// ////////// // Exactly multiply two unsigned chars // This avoids a float value (important on Intel...) // From Alvy Ray Smith paper inline unsigned char INT_MULT(unsigned int a, unsigned int b) { int t = (unsigned int)a * (unsigned int)b + 0x80; return((unsigned char)(((t >> 8) + t) >> 8)); } ////////// // Exactly LERPs two values // This avoids a float value (important on Intel...) // From Alvy Ray Smith paper inline unsigned char INT_LERP(unsigned int p, unsigned int q, unsigned int a) { return((unsigned char)(p + INT_MULT(a, q - p))); } ////////// // Floating point LERP inline float FLOAT_LERP(float p, float q, float a) { return( a * (q - p) + p); } /////////////////////////////////////////////////////////////////////////////// // Step function // /////////////////////////////////////////////////////////////////////////////// inline int stepFunc(float x, float a) { return(x >= a); } inline int stepFunc(int x, int a) { return(x >= a); } inline int stepFunc(unsigned char x, unsigned char a) { return(x >= a); } /////////////////////////////////////////////////////////////////////////////// // Pulse function // /////////////////////////////////////////////////////////////////////////////// inline int pulseFunc(float x, float a, float b) { return(stepFunc(a, x) - stepFunc(b, x)); } inline int pulseFunc(int x, int a, int b) { return(stepFunc(a, x) - stepFunc(b, x)); } inline int pulseFunc(unsigned char x, unsigned char a, unsigned char b) { return(stepFunc(a, x) - stepFunc(b, x)); } /////////////////////////////////////////////////////////////////////////////// // Clamp function // /////////////////////////////////////////////////////////////////////////////// inline float clampFunc(float x, float a, float b) { return(x < a ? a : (x > b ? b : x)); } inline int clampFunc(int x, int a, int b) { return(x < a ? a : (x > b ? b : x)); } inline unsigned char clampFunc(unsigned char x, unsigned char a, unsigned char b) { return(x < a ? a : (x > b ? b : x)); } inline void* clampFunc(void* x, void* a, void* b) { return(x < a ? a : (x > b ? b : x)); } /* inline int GateInt(int nValue,int nMin,int nMax) inline float GateFlt(float nValue,float nMin,float nMax) inline void* GatePtr(void* pValue,void* pMin,void* pMax) */ /////////////////////////////////////////////////////////////////////////////// // absolute integer // /////////////////////////////////////////////////////////////////////////////// inline int AbsInt(int inValue) { return (inValue>0)?inValue:-inValue; } static inline int GetSign(int inValue) { return (inValue<0)?-1:1; } /////////////////////////////////////////////////////////////////////////////// // wrapping functions for integers // /////////////////////////////////////////////////////////////////////////////// inline int GetTiled(int inValue,const int nMax) { int nOutValue=(inValue%nMax); if (nOutValue<0)nOutValue=((nMax-1)+nOutValue); return nOutValue; } inline int GetMirrored(int inValue,const int nMax) { const int nTwoMax=(nMax*2); int nOutValue=GetTiled(inValue,nTwoMax); if (nOutValue>=nMax)nOutValue=((nTwoMax-1)-nOutValue); return nOutValue; } /////////////////////////////////////////////////////////////////////////////// // 2D-algebra // /////////////////////////////////////////////////////////////////////////////// static inline void Get2dTangent(float inX,float inY,float* poutX,float* poutY) { *poutX=inY; *poutY=-inX; } /////////////////////////////////////////////////////////////////////////////// // 2D-dot product /////////////////////////////////////////////////////////////////////////////// static inline float Dot2d(float Ax,float Ay,float Bx,float By) { return ((Ax*Bx)+(Ay*By)); } /////////////////////////////////////////////////////////////////////////////// // 2D-vector normalization /////////////////////////////////////////////////////////////////////////////// static inline void Normalise2d(float* pX,float* pY) { const float MagSqr=Dot2d(*pX,*pY,*pX,*pY); float Magnitude=(float)sqrt(MagSqr); if (Magnitude<=0.0f) { Magnitude=0.001f; } const float RecipMag=1.0f/Magnitude; *pX*=RecipMag; *pY*=RecipMag; } /////////////////////////////////////////////////////////////////////////////// // higher algebra // /////////////////////////////////////////////////////////////////////////////// inline float GetRandomFloat(void) { return rand()/static_cast<float>(RAND_MAX); } /////////////////////////////////////////////////////////////////////////////// // Smooth step function (3x^2 - 2x^3) // /////////////////////////////////////////////////////////////////////////////// GEM_EXTERN extern float smoothStep(float x, float a, float b); GEM_EXTERN extern int smoothStep(int x, int a, int b); GEM_EXTERN extern unsigned char smoothStep(unsigned char x, unsigned char a, unsigned char b); /////////////////////////////////////////////////////////////////////////////// // Bias function // // Remap unit interval (curve) // If a == 0.5, then is linear mapping. /////////////////////////////////////////////////////////////////////////////// GEM_EXTERN extern float biasFunc(float x, float a); /////////////////////////////////////////////////////////////////////////////// // Gain function // // Remap unit interval (S-curve) // Will always return 0.5 when x is 0.5 // If a == 0.5, then is linear mapping. /////////////////////////////////////////////////////////////////////////////// GEM_EXTERN extern float gainFunc(float x, float a); /////////////////////////////////////////////////////////////////////////////// // Linear function // // val should be 0 <= val <= 1. // ret should point at a float of enough dimensions to hold the returned value // For instance, numDimen == 2, should have a ret[2] // numDimen is the number of dimensions to compute // npnts is the number of points per dimension. // /////////////////////////////////////////////////////////////////////////////// GEM_EXTERN extern void linearFunc(float val, float *ret, int numDimen, int npnts, float *pnts); /////////////////////////////////////////////////////////////////////////////// // Spline function // // val should be 0 <= val <= 1. // ret should point at a float of enough dimensions to hold the returned value // For instance, numDimen == 2, should have a ret[2] // numDimen is the number of dimensions to compute // nknots is the number of knots per dimension. // There must be at least four knots! // // Thanks to // _Texturing and Modeling: A Procedural Approach_ // David S. Ebert, Ed. /////////////////////////////////////////////////////////////////////////////// GEM_EXTERN extern void splineFunc(float val, float *ret, int numDimen, int nknots, float *knot); /////////////////////////////////////////////////////////////////////////////// // Pixel access functions // /////////////////////////////////////////////////////////////////////////////// // // Accelerated Pixel Manipulations // This is sort on a vector operation on 8 chars at the same time .... could be // implemented in MMX // Alpha channel is not added !! (would be nr 3 and 7) #define ADD8_NOALPHA(a,b) \ ((unsigned char*)(a))[0] = CLAMP_HIGH((int)((unsigned char*)(a))[0] + ((unsigned char*)(b))[0]);\ ((unsigned char*)(a))[1] = CLAMP_HIGH((int)((unsigned char*)(a))[1] + ((unsigned char*)(b))[1]);\ ((unsigned char*)(a))[2] = CLAMP_HIGH((int)((unsigned char*)(a))[2] + ((unsigned char*)(b))[2]);\ ((unsigned char*)(a))[4] = CLAMP_HIGH((int)((unsigned char*)(a))[4] + ((unsigned char*)(b))[4]);\ ((unsigned char*)(a))[5] = CLAMP_HIGH((int)((unsigned char*)(a))[5] + ((unsigned char*)(b))[5]);\ ((unsigned char*)(a))[6] = CLAMP_HIGH((int)((unsigned char*)(a))[6] + ((unsigned char*)(b))[6]);\ #define SUB8_NOALPHA(a,b) \ ((unsigned char*)(a))[0] = CLAMP_LOW((int)((unsigned char*)(a))[0] - ((unsigned char*)(b))[0]);\ ((unsigned char*)(a))[1] = CLAMP_LOW((int)((unsigned char*)(a))[1] - ((unsigned char*)(b))[1]);\ ((unsigned char*)(a))[2] = CLAMP_LOW((int)((unsigned char*)(a))[2] - ((unsigned char*)(b))[2]);\ ((unsigned char*)(a))[4] = CLAMP_LOW((int)((unsigned char*)(a))[4] - ((unsigned char*)(b))[4]);\ ((unsigned char*)(a))[5] = CLAMP_LOW((int)((unsigned char*)(a))[5] - ((unsigned char*)(b))[5]);\ ((unsigned char*)(a))[6] = CLAMP_LOW((int)((unsigned char*)(a))[6] - ((unsigned char*)(b))[6]);\ #define ADD8(a,b) \ ((unsigned char*)(a))[0] = CLAMP_HIGH((int)((unsigned char*)(a))[0] + ((unsigned char*)(b))[0]);\ ((unsigned char*)(a))[1] = CLAMP_HIGH((int)((unsigned char*)(a))[1] + ((unsigned char*)(b))[1]);\ ((unsigned char*)(a))[2] = CLAMP_HIGH((int)((unsigned char*)(a))[2] + ((unsigned char*)(b))[2]);\ ((unsigned char*)(a))[3] = CLAMP_HIGH((int)((unsigned char*)(a))[3] + ((unsigned char*)(b))[3]);\ ((unsigned char*)(a))[4] = CLAMP_HIGH((int)((unsigned char*)(a))[4] + ((unsigned char*)(b))[4]);\ ((unsigned char*)(a))[5] = CLAMP_HIGH((int)((unsigned char*)(a))[5] + ((unsigned char*)(b))[5]);\ ((unsigned char*)(a))[6] = CLAMP_HIGH((int)((unsigned char*)(a))[6] + ((unsigned char*)(b))[6]);\ ((unsigned char*)(a))[7] = CLAMP_HIGH((int)((unsigned char*)(a))[7] + ((unsigned char*)(b))[7]);\ #define SUB8(a,b) \ ((unsigned char*)(a))[0] = CLAMP_LOW((int)((unsigned char*)(a))[0] - ((unsigned char*)(b))[0]);\ ((unsigned char*)(a))[1] = CLAMP_LOW((int)((unsigned char*)(a))[1] - ((unsigned char*)(b))[1]);\ ((unsigned char*)(a))[2] = CLAMP_LOW((int)((unsigned char*)(a))[2] - ((unsigned char*)(b))[2]);\ ((unsigned char*)(a))[3] = CLAMP_LOW((int)((unsigned char*)(a))[3] - ((unsigned char*)(b))[3]);\ ((unsigned char*)(a))[4] = CLAMP_LOW((int)((unsigned char*)(a))[4] - ((unsigned char*)(b))[4]);\ ((unsigned char*)(a))[5] = CLAMP_LOW((int)((unsigned char*)(a))[5] - ((unsigned char*)(b))[5]);\ ((unsigned char*)(a))[6] = CLAMP_LOW((int)((unsigned char*)(a))[6] - ((unsigned char*)(b))[6]);\ ((unsigned char*)(a))[7] = CLAMP_LOW((int)((unsigned char*)(a))[7] - ((unsigned char*)(b))[7]);\ #ifdef __APPLE__ //Ian Ollman's function to determine the cache prefetch for altivec vec_dst() inline UInt32 GetPrefetchConstant( int blockSizeInVectors, int blockCount, int blockStride ) { return ((blockSizeInVectors << 24) & 0x1F000000) | ((blockCount << 16) & 0x00FF0000) | (blockStride & 0xFFFF); } #endif #endif // for header file
C
#include "mds.h" /* * Create the two main hashes "file hash" and "client hash" */ void mds_init() { mds_files = fh_create(); mds_clients = ch_create(); } /* * Add a client C and file F to the MDS and link them together. * Note: it's possible that the client is either exits or the * file f already exists, this is all taken into account in this * method. if they exist add the record, if they are new to the * MDS add an create the appropriate links. */ void mds_put(client *c, file *f) { file *fp = fh_get(mds_files, f->filename); client *cp = ch_get(mds_clients, c->id); /* new client & new file */ if (cp == NULL && fp == NULL) { ch_put(mds_clients, c); fh_put(mds_files, f); c->files = fll_create(); f->clients = cll_create(); fll_add(c->files, f); cll_addFirst(f->clients, c); /* new client & existing file */ } else if (cp == NULL && fp != NULL) { ch_put(mds_clients, c); c->files = fll_create(); fll_add(c->files, fp); cll_addFirst(fp->clients, c); /* existing client & new file */ } else if (cp != NULL && fp == NULL) { fh_put(mds_files, f); f->clients = cll_create(); fll_add(cp->files, f); cll_addFirst(f->clients, cp); /*existing client & existing file */ } else { fll_add(cp->files, fp); cll_addFirst(fp->clients, cp); } } /* * Add a new client to the MDS */ void mds_put_client(client *c) { if (ch_get(mds_clients, c->id) == NULL) { ch_put(mds_clients, c); c->files = fll_create(); } } /* * Return a host (client) that has the file <filename> * in it's working directory. if no such client exists * the method returns NULL. * * Note: We have implemented a dynamic queue to huristically * balance the load on the hosts, a host that has been picked * is pushed to the end of the queue. this is not optimal but * under standard conditions it gives good results most of the * time. */ client *mds_get(char *filename) { clientLink *cl; client *c = NULL; file *f = fh_get(mds_files, filename); if (f != NULL) { cl = f->clients->head->next; c = cl->c; cll_remove(cl); /* rotate the hosts (clients) list */ cll_addLast(f->clients, c); /* for load balancing */ return c; } return c; } client *mds_get_client(int id) { return ch_get(mds_clients, id); } file *mds_get_file(char *filename) { return fh_get(mds_files, filename); } /* * Returns a list of all file names available throughout the entire MDS */ char **mds_get_file_list() { int i; file *f; int j = 0; char **fileList = (char **)malloc(mds_files->curr_size * sizeof(char *)); for (i = 0; i < mds_files->max_size; i++) { if (mds_files->map[i] != NULL) { f = mds_files->map[i]->head->next; for (; f != mds_files->map[i]->tail; f = f->next) { fileList[j++] = f->filename; } } } return fileList; } /* * Removes Client c form the MDS, this method automatically updates both * the "client hash" and the "file hash" - removing "c" as a possible * host of it's files. if a certain file had only "c" as a sourch the file * is also removed from the MDS. * * Note: since we are using the linked hashes the computational complexity * of this operation is in directo proportion to to the number of files "c" * was hosting. */ void mds_remove(client *c) { file *f; clientLink *cl; fileLink *iter; if (ch_get(mds_clients, c->id) != NULL) { iter = c->files->head->next; for (; iter != c->files->tail; iter = iter->next) { f = iter->f; cl = f->clients->head; for (; cl != f->clients->tail; cl = cl->next) { if (cl->c == c) { cll_remove(cl); } } if (cll_isEmpty(f->clients)) { fh_remove(mds_files, f->filename); } } ch_remove(mds_clients, c->id); } } /* * clearing the memory before shutting down the server. */ void mds_clear() { fh_clear(mds_files); ch_clear(mds_clients); free(mds_files); free(mds_clients); } /* * Return the number of files currently listed in the server's * Main Data Structure (MDS) */ int mds_get_size() { return mds_files->curr_size; }
C
#include"Heap.h" //ѣµ㷨 //ǰڵΪ void AdjustDown2(int* a, int n, int root)//nΪС//rootΪڵ { int parent = root; int child = parent * 2 + 1; while (child<n) { //ҳǸ if (child + 1<n && a[child + 1] > a[child])//жĸС { ++child; } if (a[child] > a[parent]) { int tmp = a[child]; a[child] = a[parent]; a[parent] = tmp; parent = child; child = parent * 2 + 1; } else { break; } } } void test() { int arr[] = { 27, 15, 19, 18, 28, 34, 65, 49, 25, 37 }; Heap hp; HeapGreate(&hp, arr, 10); HeadPrint(&hp); HeapPush(&hp, 14); HeadPrint(&hp); HeapPush(&hp, 67); HeadPrint(&hp); printf("ѶԪΪ%d\n", HeapTop(&hp)); HeapPop(&hp); HeadPrint(&hp); printf("ԪУ%d\n", HeapSize(&hp)); //ӡHeap for (int i = 0; i < 11; ++i) { printf("%d ", HeapTop(&hp)); HeapPop(&hp); } printf("\n"); //ӡarr HeapSort(arr, 10); for (int i = 0; i < sizeof(arr)/sizeof(int); ++i) { printf("%d ", arr[i]); } printf("\n"); } int main() { test(); system("pause"); return 0; }
C
#include <efi.h> #include <efilib.h> EFI_STATUS efi_main (EFI_HANDLE image, EFI_SYSTEM_TABLE *systab) { INTN Argc, i; CHAR16 **Argv; InitializeLib(image, systab); Argc = GetShellArgcArgv(image, &Argv); Print(L"Argument:\n"); Print(L" Argc=%d\n", Argc); for (i = 0 ; i < Argc ; ++i) Print(L" Argv[%d] = '%s'\n", i, Argv[i]); return EFI_SUCCESS; }
C
#include <stdio.h> void left(char *d,char *s,int n) { for(size_t i=0;i<n;i++) { *d=*s; d++; s++; } return; } int main(int argc, char*argv[]) { char str1[]="exercises"; char str2[32]="abcdefghijklmn"; char str3[32]="abcdefghijklmn"; left(str2,str1,5); puts(str2); left(str3,str1,10); puts(str3); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char str[60]; int R,i; while(scanf("%s", &str) != EOF) { i = 0; R = 0; while(str[i]) { if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u') R++; else if(str[i]=='1' || str[i]=='3' || str[i]=='5' || str[i]=='7' || str[i]=='9') R++; i++; } printf("%d\n",R); } return 0; }
C
#include "iostm8l152c6.h" #include <intrinsics.h> // __enable_interrupt () /** * CLK_DIVR, * 3 , 5 */ #define CLK_DIV_1 0x00 #define CLK_DIV_2 0x01 #define CLK_DIV_4 0x02 #define CLK_DIV_8 0x03 #define CLK_DIV_16 0x04 #define CLK_DIV_32 0x05 #define CLK_DIV_64 0x06 #define CLK_DIV_128 0x07 /** * , CLK_SWR, - * SWBSY . Reset value HSI. */ #define HSI 0x01 #define LSI 0x02 #define HSE 0x04 #define LSE 0x08 #define RX_BUFFER_SIZE 1 // char rx_buffer[RX_BUFFER_SIZE]; // unsigned char read_enable = 0; unsigned char rx_wr_index; // char flag = 0; , int main( void ) { /* GPIO */ PC_DDR &= ~(1 << 2); // Rx PC_DDR |= (1 << 3); // Tx // PC7 PC_DDR |= (1 << 7); PC_CR1 |= (1 << 7); PC_ODR |= (1 << 7); /* */ CLK_CKDIVR = CLK_DIV_1; // , 1 CLK_SWCR_bit.SWEN = 1; // //CLK_SWR = HSE; // HSE CLK_SWR = HSI; // HSE /* HSE, - HSE, */ while (CLK_SWCR_bit.SWBSY == 1); /** , CLK_PCKENR1 * PCKEN17 -- DAC * PCKEN16 -- BEEP * PCKEN15 -- USART1 * PCKEN14 -- SPI1 * PCKEN13 -- I2C1 * PCKEN12 -- TIM4 * PCKEN11 -- TIM3 * PCKEN10 -- TIM2 */ CLK_PCKENR1_bit.PCKEN15 = 1; // USART1 /* UART */ USART1_CR1_bit.M = 0; // word length 0: 8 , 1: 9 USART1_CR3_bit.STOP1 = 0; // USART1_CR3_bit.STOP0 = 0; // 00 - 1 , 01 - Reserved, 10 - 2, 11 - 1.5 /* UART 9600 bps * 16000000 / 9600 = 1666.6 (0x0683 16- ) */ USART1_BRR2 = 0x03; USART1_BRR1 = 0x68; /* UART Tx Rx GPIO USART1_CR2 */ USART1_CR2_bit.TEN = 1; // USART1_CR2_bit.REN = 1; // USART1_CR2_bit.RIEN = 1; // __enable_interrupt(); // while (1) {} } /* UART */ #pragma vector = USART_R_RXNE_vector __interrupt void uart_rx_interrupt(void) { char data; // data = USART1_DR; // data /* */ if (data == '*') { rx_wr_index = 0; // read_enable = 1; // } /* $*/ if ((data == '$') && read_enable == 1) { read_enable = 0; // } /* , read_enable */ if (read_enable == 1) { rx_buffer[rx_wr_index++] = data; // } /* if (flag) { PC_ODR |= (1 << 7); } else PC_ODR &= ~(1 << 7); flag = ~flag; */ }
C
#include "stdint.h" #include "stdio.h" #include "stdlib.h" #include "string.h" #include <time.h> #include <unistd.h> #define i32 int32_t #define p1 "\e[1;31m" #define p2 "\e[1;32m" #define p3 "\e[1;33m" #define p4 "\e[1;34m" #define p5 "\e[1;35m" #define p6 "\e[1;36m" #define p7 "\e[1;41m" #define p8 "\e[1;45m" #define reset "\e[0;0m" typedef struct _lrc { i32 color; char lyric[99]; useconds_t time; useconds_t offset; } lrc; typedef struct _ppl { char name[30]; } ppl; int main() { char *colors[8] = {p1, p2, p3, p4, p5, p6, p7, p8}; printf("Open a LRC file: "); FILE *ly = NULL; char filename[100] = "0"; fgets(filename, 99, stdin); filename[strcspn(filename, "\n")] = '\0'; char *dot = strrchr(filename, '.'); if (!dot || strncmp(dot, ".lrc", 4) != 0) { printf("File is not a .lrc file!\n"); return 0; } if ((ly = fopen(filename, "r")) == NULL) { perror("Couldn't open the file :"); return 0; } i32 used = 0; // store how many singers i32 singing = -1; // index the one is singing i32 cnt = 0; // lyrics count lrc lyrics[300]; // store lyrics information memset(lyrics, 0, sizeof(lrc)); char input[300]; memset(input, 0, sizeof(input)); ppl names[8]; memset(names, 0, sizeof(ppl)); i32 firstline = 1; while (!feof(ly)) { fgets(input, 299, ly); while (firstline) { i32 len = strlen(input); //printf("%d\n", len); if ((input[2] - '0' >= 0 && input[2] - '0' <= 9) || input[len - 3] == ':') { firstline = 0; break; } else { fgets(input, 299, ly); } } if (strchr(input, '[') == NULL && strchr(input, ':') == NULL) { //printf("cnt=%d\n", cnt); continue; } if (strchr(input, '[') == NULL) { //printf("1\n"); i32 found = 0; for (i32 i = 0; i < used + 1; i++) if (strncmp(names[i].name, input, 29) == 0) { found = 1; singing = i; break; } if (!found) { //printf("%d -> %d\n", singing, used); strncpy(names[used].name, input, strlen(input)); singing = used; //printf("%d\n\n", singing); used++; } } else { lyrics[cnt].time = 0; lyrics[cnt].color = singing; char *ptr = NULL; i32 time = 0; time += strtol(&input[1], &ptr, 10) * 60; ptr++; time += strtol(ptr, &ptr, 10); time *= 100; ptr++; time += strtol(ptr, &ptr, 10); ptr++; lyrics[cnt].time = time; lyrics[cnt].offset = time; if (cnt != 0) lyrics[cnt].time -= lyrics[cnt - 1].offset; strncpy(lyrics[cnt].lyric, ptr, strlen(ptr)); cnt++; } } for (i32 i = 0; i < cnt; i++) { usleep(lyrics[i].time * 10000); //printf("%d\n", lyrics[i].color); printf("%s%s", colors[lyrics[i].color], lyrics[i].lyric); } printf(reset); return 0; }
C
#include <stdio.h> #include <omp.h> int main (int argc, char *argv[]) { int max; sscanf (argv[1], "%d", &max); printf("omp_get_nested() = %d\n", omp_get_nested()); #pragma omp parallel for for (int i = 1; i <= max; i++) { printf ("Number of threads in outer team %d: \n", omp_get_num_threads()); printf("I am outer thread %d\n", omp_get_thread_num ()); #pragma omp parallel for for (int j = 1; j <= max; j++) { printf ("Number of threads in inner team %d: \n", omp_get_num_threads()); printf ("I am inner thread %d: (%d,%d)\n", omp_get_thread_num (), i, j); } } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<malloc.h> struct node { int data; struct node *left; struct node *right; }*root= NULL; struct queue { int size; int front; int rear; struct node **Q; }*q=NULL; void createQueue(int size) { q->size = size; q->front = -1; q->rear = -1; q->Q = (struct node **)malloc(q->size * sizeof(struct node*)); } void enqueue(struct node *t) { q->rear = (q->rear + 1)%q->size; q->Q[q->rear] = t; } void dequeue() { q->front = (q->front+1)%q->size; q->Q[q->front]; } int isEmpty() { return (q->front == q->rear); } struct node * peek() { struct node *t = NULL; t = q->Q[q->rear]; return t; } void inOrder(struct node *t) { if(t) { inOrder(t->left); printf("%d |",t->data); inOrder(t->right); } } void insertThroughEmpytLevel(struct node *root, int data) { q = (struct queue *)malloc(sizeof(struct queue)); createQueue(10); enqueue(root); struct node *n = (struct node *)malloc(sizeof(struct node)); n->data = data; n->left = NULL; n->right = NULL; while (!isEmpty()) { //Create a temp node with the front queue data and check its left and right struct node *temp = peek(); dequeue(); if(!temp->left) { temp->left = n; break; }else enqueue(temp->left); if(!temp->right) { temp->right = n; break; }else enqueue(temp->right); } } struct node * insert(struct node *root, int data) { if(root == NULL) { struct node *n = (struct node*)malloc(sizeof(struct node)); n->data = data; n->left = NULL; n->right = NULL; return n; }else { struct node *c; if(data<=root->data) { c = insert(root->left, data); root->left = c; }else { c = insert(root->right, data); root->right = c; } } return root; } int main() { root = insert(root,10); root = insert(root,11); root = insert(root,7); root = insert(root,9); root = insert(root,15); root = insert(root,8); insertThroughEmpytLevel(root, 12); inOrder(root); }
C
#include <unistd.h> #include <stdio.h> int main() { long sem_nsems_max = sysconf(_SC_SEM_NSEMS_MAX); long sem_value_max = sysconf(_SC_SEM_VALUE_MAX); printf(": %ld\n", sem_nsems_max); printf("sem_value_max: %ld\n", sem_value_max); }
C
#include <stdlib.h> #include <stdio.h> #include <strings.h> #include <time.h> #include "cashier.h" static cashier_t* cashier_function(cashier_t* current, xmlNode* curNode){ char *data; char *properties; properties = (char *) xmlGetProp(curNode, (const xmlChar *)"name"); strcpy(current->name, properties); properties = (char *)xmlGetProp(curNode, (const xmlChar *)"surname"); strcpy(current->surname, properties); for(curNode = curNode->children; curNode != NULL; curNode = curNode->next) { if(!xmlStrcmp(curNode->name, (const xmlChar *)"birthday")) { data = (char *)xmlNodeGetContent(curNode); sscanf(data, "%d-%d-%d", &current->birthday.tm_year, &current->birthday.tm_mday, &current->birthday.tm_mon); continue; } if(!xmlStrcmp(curNode->name, (const xmlChar *)"salary")) { data = (char *)xmlNodeGetContent(curNode); current->salary = atof(data); continue; } if(!xmlStrcmp(curNode->name, (const xmlChar *)"cashboxID")) { data = (char *)xmlNodeGetContent(curNode); current->cashboxID = atoi(data); continue; } } return current; } cashier_t* cashier_new() { cashier_t* cashier = (cashier_t *)malloc(sizeof(struct cashier_s)); strcpy(cashier->name, ""); strcpy(cashier->surname, ""); memset(&cashier->birthday, 0, sizeof(cashier->birthday)); cashier->salary = 0.0; cashier->cashboxID = -1; return cashier; } void cashier_delete(cashier_t* cashier) { free(cashier); } void xmlParse(cashier_t* cashierSet[], const char* XMLFileName) { xmlDoc * doc = xmlReadFile(XMLFileName, "UTF-8", 0); if(doc == NULL) { xmlFreeDoc(doc); return; } xmlNode *xml_root = xmlDocGetRootElement(doc); xmlNode *curNode; int i; for(i = 0, curNode = xml_root->children; curNode != NULL; curNode = curNode->next) { if(!xmlStrcmp(curNode->name, (const xmlChar *)"cashier")) { cashier_function(cashierSet[i++], curNode); } } xmlFreeDoc(doc); } void print_function(cashier_t* cashier){ printf("\t[%s]\n" "\t[%s]\n" "\t[%s]\n" "\t%d-%d-%d\n" "\t%f\n" "\t%i\n" "\t[%s]\n" "\t%i\n\n", cashier->name, cashier->surname, cashier->birthday.tm_year, cashier->birthday.tm_mon, cashier->birthday.tm_mday, cashier->salary, cashier->cashboxID ); }
C
/************************* **Crystopher Echavarria** *************************/ #include <stdio.h> #include "graphics.h" #define PIECEE color(100,100,500) #define PIECEC color(0,255,0) #define PIECEF color(0,0,255) #define PIECEM color(255,0,0) #define BORDERC color(255,255,255) #define W 50 #define H 50 #define MW 40 #define MH 40 #define BRDRSZ 50 #define NUMBER_SQUARES_COLUMN 8 // this is what you want to change to make the board taller #define NUMBER_SQUARES_ROW 8 // change this to make it fatter #define WNDWSZ_H (NUMBER_SQUARES_ROW*H+(2*BRDRSZ)) #define WNDWSZ_W (NUMBER_SQUARES_COLUMN*W+(2*BRDRSZ)) #define ENDPIECEX 50*NUMBER_SQUARES_ROW #define ENDPIECEY 50*NUMBER_SQUARES_ROW #define STARTPIECEX 55 #define STARTPIECEY 55 #define CLOSEX STARTPIECEX-W + W*NUMBER_SQUARES_ROW #define CLOSEY STARTPIECEY-H + H*NUMBER_SQUARES_COLUMN int main (int argc, char* args[]){ Graphics g = init(0, 0, WNDWSZ_W, WNDWSZ_H, BORDERC); int key; int x = 0; int y = 0; Color sc; char grid[8][8] = {{"00000000"}, {"00000000"}, {"00000000"}, {"00000000"}, {"00000000"}, {"00000000"}, {"00000000"}, {"00000000"}}; int quit = 0; while (!quit) { clear(g); for (int i = 1; i <= NUMBER_SQUARES_ROW; i--){ for (int j = 1; j <= NUMBER_SQUARES_COLUMN; j--){ if((i+j) % 2 == 1) grid[i][j] = '@'; else grid[i][j] = '#'; printf("%c",grid[i][j]); // drawRect(g, sc, i, j, W, H); break; } } } drawRect(g, PIECEF, ENDPIECEX, ENDPIECEY, W, H); drawRect(g, PIECEM, x, y, MW, MH); key = getKeyB(); printf("Key pressed: %d\n", x); printf("Key pressed: %d\n", y); if(key==44){ quit=1; } if(key==-1) { quit = 1; } if(key == 79 && x < ENDPIECEX) { x+=50; } if(key == 80 && x > STARTPIECEX) { x-=50; } if(key == 81 && y < ENDPIECEY) { y+=50; } if(key == 82 && y > STARTPIECEY) { y-=50; } if(x == CLOSEX && y == CLOSEY) { quit = 1; } printf("Closing program...\n"); obliterate(g); return 0; }
C
/* nxSDK - ioFTPD Software Development Kit Copyright (c) 2006 neoxed Module Name: Resolve Author: neoxed ([email protected]) May 13, 2006 Abstract: Example application, demonstrates how to resolve names and IDs. */ #include <windows.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <nxsdk.h> static void Usage( const char *argv0 ); typedef BOOL (ResolveProc)( IO_MEMORY *memory, const char *input ); static ResolveProc ResolveGroupId; static ResolveProc ResolveGroupName; static ResolveProc ResolveUserId; static ResolveProc ResolveUserName; struct { char *name; ResolveProc *proc; } static const types[] = { {"gid", ResolveGroupId}, {"group", ResolveGroupName}, {"uid", ResolveUserId}, {"user", ResolveUserName} }; int main( int argc, char **argv ) { BOOL result = FALSE; int i; IO_MEMORY *memory; IO_SESSION session; if (argc != 4) { Usage(argv[0]); return 1; } // Locate ioFTPD's message window. if (!Io_ShmInit(argv[1], &session)) { printf("The message window \"%s\" does not exist.\n", argv[1]); return 1; } // Allocate memory for user/group resolving. memory = Io_ShmAlloc(&session, sizeof(DC_NAMEID)); if (memory == NULL) { printf("Unable to allocate shared memory (error %lu).\n", GetLastError()); return 1; } // Call the resolve function. for (i = 0; i < sizeof(types)/sizeof(types[0]); i++) { if (strcmp(types[i].name, argv[2]) == 0) { result = types[i].proc(memory, argv[3]); break; } } if (i >= sizeof(types)/sizeof(types[0])) { Usage(argv[0]); } // Clean up. Io_ShmFree(memory); return (result == TRUE) ? 0 : 1; } static BOOL ResolveGroupId( IO_MEMORY *memory, const char *idText ) { int id; char name[_MAX_NAME+1]; id = atoi(idText); if (!Io_GroupIdToName(memory, id, name)) { printf("The group ID \"%d\" does not exist.\n", id); return FALSE; } printf("Resolved group ID \"%d\" to group name \"%s\".\n", id, name); return TRUE; } static BOOL ResolveGroupName( IO_MEMORY *memory, const char *name ) { int id; if (!Io_GroupNameToId(memory, name, &id)) { printf("The group name \"%s\" does not exist.\n", name); return FALSE; } printf("Resolved group name \"%s\" to group ID \"%d\".\n", name, id); return TRUE; } static BOOL ResolveUserId( IO_MEMORY *memory, const char *idText ) { int id; char name[_MAX_NAME+1]; id = atoi(idText); if (!Io_UserIdToName(memory, id, name)) { printf("The user ID \"%d\" does not exist.\n", id); return FALSE; } printf("Resolved user ID \"%d\" to user name \"%s\".\n", id, name); return TRUE; } static BOOL ResolveUserName( IO_MEMORY *memory, const char *name ) { int id; if (!Io_UserNameToId(memory, name, &id)) { printf("The user name \"%s\" does not exist.\n", name); return FALSE; } printf("Resolved user name \"%s\" to user ID \"%d\".\n", name, id); return TRUE; } static void Usage( const char *argv0 ) { printf("\n"); printf("Usage: %s <window> <type> <input>\n\n", argv0); printf("Arguments:\n"); printf(" window - ioFTPD's message window.\n"); printf(" type - Type of input data: gid, group, uid, or user.\n"); printf(" input - The ID or name of a group or user.\n\n"); printf("Examples:\n"); printf(" %s ioFTPD::MessageWindow gid 1\n", argv0); printf(" %s ioFTPD::MessageWindow group STAFF\n", argv0); printf(" %s ioFTPD::MessageWindow uid 0\n", argv0); printf(" %s ioFTPD::MessageWindow user bill\n", argv0); }
C
#include <math.h> #include <glad/glad.h> #include "camera.h" Camera new_camera(vec3 position, vec3 world_up, float yaw, float pitch, float speed, float sensitivity, float zoom) { vec3 front, up, right; glm_vec3_zero(front); glm_vec3_zero(up); glm_vec3_zero(right); Camera camera = { position, malloc(sizeof(vec3)), malloc(sizeof(vec3)), malloc(sizeof(vec3)), world_up, yaw, pitch, speed, sensitivity, zoom }; // camera.position = position; camera.world_up = world_up; update_camera_vectors(&camera); return camera; } // finds new camera direction void update_camera_vectors(Camera *camera) { vec3 front; glm_vec3_zero(front); // calculate new front vector front[0] = cos(glm_rad(camera->yaw)) * cos(glm_rad(camera->pitch)); front[1] = sin(glm_rad(camera->pitch)); front[2] = sin(glm_rad(camera->yaw)) * cos(glm_rad(camera->pitch)); glm_vec3_normalize_to(front, camera->front); vec3 right; glm_vec3_zero(right); glm_vec3_cross(camera->front, camera->world_up, right); glm_vec3_normalize_to(right, camera->right); vec3 up; glm_vec3_zero(up); glm_cross(right, front, up); glm_normalize_to(up, camera->up); } // copy lookat matrix into matrix variable void get_view_matrix(Camera *camera, mat4 matrix) { vec3 center; glm_vec3_add(camera->position, camera->front, center); glm_lookat(camera->position, center, camera->up, matrix); } void process_keyboard(Camera *camera, CameraMovement direction, float delta) { float velocity = camera->movement_speed * delta; vec3 displacement; if (direction == FORWARD) { glm_vec3_scale(camera->front, velocity, displacement); glm_vec3_add(camera->position, displacement, camera->position); } if (direction == BACKWARD) { glm_vec3_scale(camera->front, velocity, displacement); glm_vec3_sub(camera->position, displacement, camera->position); } if (direction == LEFT) { glm_vec3_scale(camera->right, velocity, displacement); glm_vec3_sub(camera->position, displacement, camera->position); } if (direction == RIGHT) { glm_vec3_scale(camera->right, velocity, displacement); glm_vec3_add(camera->position, displacement, camera->position); } } void process_mouse_movement(Camera *camera, float x_offset, float y_offset) { x_offset *= camera->mouse_sensitivity; y_offset *= camera->mouse_sensitivity; camera->yaw += x_offset; camera->pitch += y_offset; // constrain pitch if (camera->pitch > 89.0f) camera->pitch = 89.0f; if (camera->pitch < -89.0f) camera->pitch = -89.0f; update_camera_vectors(camera); } void process_mouse_scroll(Camera *camera, float y_offset) { camera->zoom -= (float) y_offset; // zoom boundaries if (camera->zoom < 1.0f) camera->zoom = 1.0f; if (camera->zoom > 45.0f) camera->zoom = 45.0f; } void destroy_camera(Camera *camera) { free(camera->front); free(camera->up); free(camera->right); }
C
/** * Project: Assignment 2 - ProgII subject * File: a2_e1_test.c * Version: 2.0 * Date: Mar 18, 2017 * Revision date: May 27, 2018 * * (C) Alejandro Santorum Varela * [email protected] * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "element_int.h" #include "stack_element.h" #define N 10 void _stack_status(Stack *s){ if(stack_isEmpty(s)==TRUE){ printf("Stack status --> EMPTY\n"); return; } if(stack_isFull(s)==TRUE){ printf("Stack status --> FULL\n"); return; } printf("Stack status --> NOT EMPTY WITH FREE SPACE\n"); } int main(int argc, char **argv){ Stack *s=NULL; Element *e=NULL; int n, i; s = stack_ini(); if(!s) exit(EXIT_FAILURE); _stack_status(s); for(i=0; i<N; i++){ e = element_ini(); if(!e){ printf("Error in the iteration number %d\n", i); exit(EXIT_FAILURE); } printf("Introduce a number: "); scanf("%d", &n); if(!element_setInfo(e, &n)){ printf("Error in the iteration number %d\n", i); exit(EXIT_FAILURE); } if(!stack_push(s, e)){ printf("Error in the iteration number %d\n", i); exit(EXIT_FAILURE); } printf("Element introduced successfully\n"); element_destroy(e); } _stack_status(s); printf("Printing stack...\n"); stack_print(stdout, s); for(i=0; i<N; i++){ if(!(e = stack_pop(s))){ exit(EXIT_FAILURE); } printf("Element extracted successfully\n"); element_print(stdout, e); printf("\n"); if(i!=N-1) element_destroy(e); } _stack_status(s); printf("Printing stack...\n"); stack_print(stdout, s); printf("Filling the stack..."); for(i=0; i<MAXSTACK; i++){ if(!stack_push(s, e)) exit(EXIT_FAILURE); } printf("Stack is supposed to be full\n"); element_destroy(e); _stack_status(s); printf("Printing stack...\n"); stack_print(stdout, s); stack_destroy(s); return EXIT_SUCCESS; }
C
/* 8. Un banco necesita para sus cajeros automáticos un programa que lea una cantidad de dinero e informe la cantidad mínima de billetes a entregar, considerando que existen billetes de $100, $50, $10, $5 y $1. Realizar una función que calcule dichas cantidades. */ #include <stdio.h> #pragma warning(disable:4996) void billetes(int *dCien, int *dCincuenta, int *dDiez, int *dCinco, int *dUno, int cantidad); int main(){ int dCien = 0, dCincuenta = 0, dDiez = 0, dCinco = 0, dUno = 0, cantidad = 0; printf("¿Cantidad? "); scanf("%d", &cantidad); billetes(&dCien, &dCincuenta, &dDiez, &dCinco, &dUno, cantidad); if (dCien >= 1) printf("Billestes de \t$100\t%d\n", dCien); if (dCincuenta >= 1)printf("Billestes de \t$50\t%d\n", dCincuenta); if (dDiez >= 1) printf("Billestes de \t$10\t%d\n", dDiez); if (dCinco >= 1) printf("Billestes de \t$5\t%d\n", dCinco); if (dUno >= 1) printf("Billestes de \t$1\t%d\n", dUno); return 0; } void billetes(int *dCien, int *dCincuenta, int *dDiez, int *dCinco, int *dUno, int cantidad){ while (cantidad > 0) { if (cantidad >= 100) { *dCien = *dCien + 1; cantidad = cantidad - 100; }else if (cantidad >= 50) { *dCincuenta = *dCincuenta + 1; cantidad = cantidad - 50; }else if (cantidad >= 10) { *dDiez = *dDiez + 1; cantidad = cantidad - 10; }else if (cantidad >= 5) { *dCinco = *dCinco + 1; cantidad = cantidad - 5; }else{ *dUno = *dUno + 1; cantidad = cantidad - 1; } } }
C
#include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int main() { int a; int lm=0; int nm=0; int line[100][100]; char ch; FILE *file = fopen("hello.txt","r"); line[0][0]; while (read(file, &ch , sizeof(char))>0){ nm++; if (ch == ('\n')) { line[lm][0]=nm; line[lm-1][1]=nm-line[lm-1][0]; lm ++; } } scanf("%d", &a); lseek(file,line[a][0],SEEK_SET); for(int i=0;i<line[a][1];i++){ read(file, &ch , sizeof(char)); printf("%c",ch); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> struct node{ int data; struct node *left; struct node *right; int height; }; struct node *root = NULL; struct node *new_node(int data){ struct node *temp = (struct node *)malloc(sizeof(struct node)); temp->data = data; temp->left = NULL; temp->right = NULL; temp->height = 1; //new node is at leaf level return temp; } // A utility function to get maximum of two integers int max(int a, int b){ if(a>b) return a; else return b; } // A utility function to get height of the tree int height(struct node *temp){ if(temp==NULL) return 0; return temp->height; } // A utility function to right rotate subtree rooted with y // See the diagram given above. struct node *rightRotate(struct node *y){ struct node *x = y->left; struct node *T2 = x->right; // Perform rotation x->right = y; y->left = T2; // Update heights y->height = max(height(y->left), height(y->right))+1; x->height = max(height(x->left), height(x->right))+1; // Return new root return x; } // A utility function to left rotate subtree rooted with x // See the diagram given above. struct node *leftRotate(struct node *x){ struct node *y = x->right; struct node *T2 = y->left; // Perform rotation y->left = x; x->right = T2; // Update heights x->height = max(height(x->left), height(x->right))+1; y->height = max(height(y->left), height(y->right))+1; // Return new root return y; } int get_balance(struct node *node){ if(node==NULL) return 0; return height(node->left) - height(node->right); } struct node *add_node(struct node *node, int data){ if(node==NULL) return new_node(data); if(data > node->data) node->right = add_node(node->right, data); else if(data < node->data) node->left = add_node(node->left, data); else return node; //now operations needs to be performed to check whether the height balanced property is satisfied or not node->height = max(height(node->left), height(node->right)) + 1; int balance = get_balance(node); // Left Left Case if (balance > 1 && data < node->left->data) return rightRotate(node); // Right Right Case if (balance < -1 && data > node->right->data) return leftRotate(node); // Left Right Case if (balance > 1 && data > node->left->data) { node->left = leftRotate(node->left); return rightRotate(node); } // Right Left Case if (balance < -1 && data < node->right->data) { node->right = rightRotate(node->right); return leftRotate(node); } /* return the (unchanged) node pointer */ return node; } int search(struct node *root, int element){ if(root==NULL) return 0; if(element==root->data) return 1; else if(element > root->data) return search(root->right, element); else return search(root->left, element); } int main(int argc, char *argv[]){ FILE *log_random = fopen("log_balanced_bst_random.txt", "a"); FILE *log_asc = fopen("log_balanced_bst_asc.txt", "a"); FILE *log_desc = fopen("log_balanced_bst_desc.txt", "a"); //used for calculating time within the function used for searching the element clock_t begin, end; double time_spent; int input_size; if(log_random==NULL || log_asc==NULL || log_desc==NULL){ printf("Error in opening of the log text files\n"); return 0; } if(argc < 2){ //missing number of arguments printf("Error : enter the value of n as an argument\n"); return 0; } if(argv[1] != NULL){ input_size = atoi(argv[1]);//now we have the input size for the program } //inserting elements into the binary search tree //allocating dyanamic memory for the array in question //this step will be the same for all the three cases to be taken care of //memory equal to the size of the input size is assigned //need to generate numbers in an random order, ascending order and in the descending order //generating numbers in an random order and storing them in the array int j; for (j = 0; j < input_size; j++){ //will store in the BST numbers in a random order equal to the input size root = add_node(root, rand() % input_size); } int search_element = input_size; int i; //beginning with the internal time counter begin = clock(); search(root, search_element); //beginning with the internal time counter end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; fprintf(log_random, "%d %lf\n", input_size, time_spent); root = NULL; //generating numbers in an ascending order and storing them in the array for (j = 0; j < input_size; j++){ //will store in the array numbers in a random order equal to the input size root = add_node(root, j); } begin = clock(); search(root, input_size); //beginning with the internal time counter end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; fprintf(log_asc, "%d %lf\n", input_size, time_spent); root = NULL; //generating numbers in an descending order and storing them in the array for (j = input_size-1; j >= 0; j--){ //will store in the array numbers in a random order equal to the input size root = add_node(root, -1); } search_element = input_size; begin = clock(); search(root, search_element); //beginning with the internal time counter end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; fprintf(log_desc, "%d %lf\n", input_size, time_spent); }
C
/* ** delete_character.c for 42sh in /home/skyrise/Work/Repositories/Epitech/PSU/42sh/PSU_2015_42sh/srcs/class/line_editor/ ** ** Made by Buyumad Anas ** Login <[email protected]@epitech.eu> ** ** Started on Fri Jun 3 22:59:28 2016 Buyumad Anas ** Last update Sun Jun 5 20:15:15 2016 Buyumad Anas */ #include <stdlib.h> #include <string.h> #include "class/line_editor.h" /* ** Removes a character of the input on the current index ** @params self ** @return bool; Success => TRUE, Error => FALSE */ bool line_editor_remove_character(t_line_editor *self) { char *temporary; size_t iterator; size_t index; if (strlen(self->input)) { iterator = 0; index = 0; if ((temporary = malloc(sizeof(char) * (strlen(self->input)))) == NULL) return (false); while (self->input[iterator]) { if (iterator != self->input_index) { temporary[index] = self->input[iterator]; index += 1; } iterator += 1; } temporary[index] = '\0'; free(self->input); self->input = temporary; } return (true); }
C
#include "DumbNet/dumbnet.h" void usage(char * arg0) { printf("Usage: %s server",arg0); printf("Usage: %s client [hostname]",arg0); } void client_main(const char * host) { dn_socket sock = client_connec_init(host); client_connec_proc(sock); } int main(int argc, char * argv []) { if ( argc < 1 ) { client_main("localhost"); } else { client_main(argv[1]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "m_malloc.h" #include <string.h> #include <tgmath.h> int actual_id = 0; void* mem; Lista* lista_libres = NULL; Lista* lista_ocupados = NULL; int tamano_actual = 0; void* m_malloc_aux(int tam) { if(lista_libres->size > 0) { Nodo* nodo = lista_libres->prim; for (int i = 0; i < lista_libres->size; i++){ if(nodo->dato.tam == tam){ lista_libres->eliminar_nodo(lista_libres, lista_libres->buscar_nodo(lista_libres, nodo->dato.id)); return nodo; } nodo = nodo->sig; } } if(tamano_actual > tam){ char* aux = (char*)mem; void* res = mem; aux += tam; mem = aux; tamano_actual -= tam; memset(res, 0, tam); return res; } return NULL; } void* m_aligned_malloc_aux(int tam, int align){ void* dir = m_malloc_aux(tam+align); int num_bits = log2(align); if(sizeof(void*) == 8){ unsigned long mask = 0xFFFFFFFFFFFFFFFF << num_bits; unsigned long direc = (unsigned long)dir; dir = (void*)(direc&mask); } else if(sizeof(void*) == 4){ int mask = 0xFFFFFFFF << num_bits; int direc = (int)dir; dir = (void*)(direc&mask); } return dir; } void* m_malloc(int tam, int align){ lista_ocupados->anadir_nodo(lista_ocupados, tam, align); Nodo* nodo = lista_ocupados->get_nodo(lista_ocupados, lista_ocupados->size-1); return nodo; } void m_free(void* memo){ Nodo* nodo = (Nodo*)memo; lista_libres->insertar_nodo(lista_libres, lista_ocupados->eliminar_nodo(lista_ocupados, lista_ocupados->buscar_nodo(lista_ocupados, nodo->dato.id))); } void* m_realloc(void* memo, int tam, int align){ //solo hecho el nodo, falta memoria void* new_memo; if(align == 0){ new_memo = m_malloc_aux(tam); } else { new_memo = m_aligned_malloc_aux(tam, align); } Nodo* old_nodo = (Nodo*)memo; Nodo* new_nodo = (Nodo*)memo; char* aux_old_nodo = (char*)old_nodo->dato.iniciomem_block; char* aux_new_nodo = (char*)new_nodo->dato.iniciomem_block; int old_tam = old_nodo->dato.tam; int new_tam = tam; new_nodo->prev = old_nodo->prev; new_nodo->sig = new_nodo->sig; if(old_nodo->prev == NULL && old_nodo->sig == NULL){ lista_ocupados->prim = new_nodo; } else if(old_nodo->prev == NULL){ lista_ocupados->prim = new_nodo; old_nodo->sig->prev = new_nodo; } else if(old_nodo->sig == NULL){ old_nodo->prev->sig = new_nodo; } else { old_nodo->prev->sig = new_nodo; old_nodo->sig->prev = new_nodo; } new_nodo->dato.id = old_nodo->dato.id; new_nodo->dato.tam = tam; for (int i = 0; i < old_tam && i < new_tam; i++){ aux_new_nodo[i] = aux_old_nodo[i]; } m_free(memo); lista_ocupados->size++; return new_memo; } void init_nodo(Nodo* nodo, Nodo* prev){ nodo->prev = prev; nodo->sig = NULL; } void anadir_nodo(struct Lista* lista, int size, int aligned){ if(lista->prim == NULL){ lista->prim = (Nodo*)m_malloc_aux(sizeof(Nodo)); lista->prim->prev=NULL; init_nodo(lista->prim, NULL); if(aligned == 0) { lista->prim->dato.iniciomem_block = (void*)m_malloc_aux(size); } else { lista->prim->dato.iniciomem_block = (void*)m_aligned_malloc_aux(size, aligned); } lista->prim->dato.id = actual_id; lista->prim->dato.tam = size; } else { Nodo* aux = lista->prim; while(aux->sig != NULL){ aux = aux->sig; } aux->sig = (Nodo*)m_malloc_aux(sizeof(Nodo)); init_nodo(aux->sig, aux); if(aligned == 0) { aux->sig->dato.iniciomem_block = (void*)m_malloc_aux(size); } else { aux->sig->dato.iniciomem_block = (void*)m_aligned_malloc_aux(size, aligned); } aux->sig->dato.id = actual_id; aux->sig->dato.tam = size; } lista->size++; actual_id++; } Nodo* eliminar_nodo(struct Lista* lista, int posicion){ Nodo* nodo_a_eliminar = NULL; nodo_a_eliminar = lista->get_nodo(lista, posicion); if (nodo_a_eliminar->prev == NULL && nodo_a_eliminar->sig == NULL) { //absolutamente nada } else if(nodo_a_eliminar->prev == NULL){ lista_ocupados->prim = nodo_a_eliminar->sig; } else if(nodo_a_eliminar->sig == NULL) { nodo_a_eliminar->prev->sig = nodo_a_eliminar->sig; } else { nodo_a_eliminar->prev->sig = nodo_a_eliminar->sig; nodo_a_eliminar->sig->prev = nodo_a_eliminar->prev; } nodo_a_eliminar->prev = NULL; nodo_a_eliminar->sig = NULL; lista->size--; return nodo_a_eliminar; } void insertar_nodo(struct Lista* lista, struct Nodo* nodo){ if(lista->prim == NULL){ lista->prim = nodo; init_nodo(nodo, NULL); } else { Nodo* aux = lista->prim; while(aux->sig != NULL){ aux = aux->sig; } init_nodo(nodo, aux); } tamano_actual += nodo->dato.tam; lista->size++; } int buscar_nodo(struct Lista* lista, int id){ Nodo* aux = lista->prim; int i = 0; while(aux != NULL){ if(id == aux->dato.id){ return i; } else { aux = aux->sig; } i++; } return -1; } Nodo* get_nodo(struct Lista* lista, int posicion){ Nodo* nodo = lista->prim; for (int i = 0; i < posicion; i++){ nodo = nodo->sig; } return nodo; } Nodo* get_primer_nodo(struct Lista* lista){ return lista->prim; } Nodo* get_ultimo_nodo(struct Lista* lista){ return lista->ult; } void pintar_lista(Lista* lista){ int size = lista->size; Nodo* nodo = lista->prim; for (int i = 0; i < size; i++){ printf("id: %d; tam: %d\n", nodo->dato.id, nodo->dato.tam); nodo = nodo->sig; } } void printTamanoActual(){ printf("tamano actual: %d\n", tamano_actual); } void init_lista(Lista* lista){ lista->prim = NULL; lista->ult = NULL; lista->size = 0; lista->anadir_nodo = (t_anadir_nodo)anadir_nodo; lista->eliminar_nodo = (t_eliminar_nodo)eliminar_nodo; lista->insertar_nodo = (t_insertar_nodo)insertar_nodo; lista->buscar_nodo = (t_buscar_nodo)buscar_nodo; lista->get_primer_nodo = (t_get_primer_nodo)get_primer_nodo; lista->get_ultimo_nodo = (t_get_ultimo_nodo)get_ultimo_nodo; lista->get_nodo = (t_get_nodo)get_nodo; } void init(void* _mem, int tam){ mem = _mem; char* aux = (char*)mem; //espacio de la lista libres aux += sizeof(Lista); Lista* new_lista = (Lista*)mem; lista_libres = new_lista; mem =(void*) (&aux[0]); init_lista(lista_libres); //espacio de la lista ocupados aux += sizeof(Lista); new_lista = (Lista*)mem; lista_ocupados = new_lista; mem = aux; init_lista(lista_ocupados); //resto el tamano tamano_actual -= sizeof(Lista) + sizeof(Lista); }
C
#pragma once #define check_null(exp, r) check_log(exp != NULL, #exp "is NULL", r) #define check_log(exp, msg, r) \ if (!(exp)) { \ printf("%s\n\tat %s(%s:%d)\n", msg, __FUNCTION__, __FILE__, \ __LINE__ - 1); \ }
C
// if (root == NULL) // { // return root; // } // if (balancedfactor(root) == 2 && balancedfactor(root->left) == 1) // { // return LLrotate(root); // } // else if (balancedfactor(root) == 2 && balancedfactor(root->left) == -1) // { // return LRrotate(root); // } // else if (balancedfactor(root) == -2 && balancedfactor(root->right) == -1) // { // return RRrotate(root); // } // else if (balancedfactor(root) == -2 && balancedfactor(root->right) == 1) // { // return RLrotate(root); // }
C
#include<stdio.h> int j_converse(char s[]); /** *main- conversion de tipos *Return: exit succesfull */ int main(void) { char numeros[10]= "0123456789"; printf("%d\n", j_converse(numeros)); return (0); } /** *j_converse- function to converter an char type an int *Return: exit succesfull */ int j_converse(char s[]) { int i, n; n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; ++i) n = n * 10 + (s[i] - '0'); return (n); }
C
#include <stdlib.h> #include <unistd.h> #include <stdio.h> #include "headers.h" int main() { printf("Bienvenido a la prueba del programa. Suma de enteros ingresados.\n"); int n, i, *ptr, suma = 0; printf("Ingresar cantidad de numeros: "); scanf("%d", &n); ptr = (int*) malloc2(n * sizeof(int)); if(ptr == NULL) { printf("Error! Memoria no alocada."); return -1; } printf("Ingresa los numeros de a uno, presionando enter: \n"); for(i = 0; i < n; i++) { scanf("%d", ptr + i); suma += *(ptr + i); } printf("Suma = %d \n", suma); free2(ptr); return 0; }
C
#include <stdio.h> /** * @Author: fiyc * @Date : 2019-04-07 21:52 * @FileName : demo_6.c * @Description : - 统计单词数 */ #define IN 1 #define OUT 0 int main() { int c, nw, state; state = OUT; nw = 0; while((c = getchar()) != EOF){ if(c == ' ' || c == '\t' || c == '\n'){ state = OUT; }else if(state == OUT){ state = IN; ++nw; } } printf("共有%d个单词", nw); }
C
#include <stdio.h> #include <stdlib.h> #include "args.h" #include "make_with_funcs.h" void make_with_func(){ int i, j, count; args_t args; if (get_args("test.auto", &args)) { print_args(&args); } else { printf("Falha ao obter args\n"); } //cria arquivo FILE * arq = fopen("teste.c", "w"); //insere includes fprintf(arq, "#include <stdio.h>\n"); fprintf(arq, "#include <stdlib.h>\n"); fprintf(arq, "#define TAM 10\n"); fprintf(arq, "\n"); //variaveis globais fprintf(arq, "char v[TAM];\n"); fprintf(arq, "int p = 0;\n"); fprintf(arq, "\n"); //protitipos das funcões for(i = 0; i < args.num_states; i++){ fprintf(arq, "void e%d();\n", i); } fprintf(arq, "void sucesso();\n"); fprintf(arq, "void erro();\n"); fprintf(arq, "\n"); //main fprintf(arq, "int main(void) {\n"); fprintf(arq, " p = 0;\n"); fprintf(arq, " printf(\"Sequencia:\"); \n"); fprintf(arq, " fgets(v, TAM, stdin);\n"); fprintf(arq, " e0();\n"); fprintf(arq, " return(0);\n"); fprintf(arq, "}\n"); fprintf(arq, "\n"); //funcoes dos estados for (i = 0; i < args.num_states; i++) { fprintf(arq, "\nvoid %s(){\n", args.states[i]); count = 0; for (j = 0; j < args.num_symbols; j++) { if (args.transitions[i + j * args.num_states] != -1) { if (count > 0){ fprintf(arq, " else \n"); fprintf(arq, " if(v[p] == '%c'){ \n", args.symbols[j]); } else{ fprintf(arq, " if(v[p] == '%c'){ \n", args.symbols[j]); } fprintf(arq, " p++;\n"); fprintf(arq, " e%d();\n", args.transitions[i + j * args.num_states]); fprintf(arq, " }"); count++; } } if (count > 0) { fprintf(arq, " else {\n"); } if (is_final_state(&args, i)){ fprintf(arq, " sucesso();\n"); fprintf(arq, " }\n"); fprintf(arq, "}\n"); } else { fprintf(arq, " erro();\n"); fprintf(arq, " }\n"); fprintf(arq, "}\n"); } } fprintf(arq, "\n"); //cria funcao sucesso fprintf(arq, "void sucesso(){\n"); fprintf(arq, " printf(\" Sucesso!\");\n"); fprintf(arq, "}\n"); fprintf(arq, "\n"); //cria funcao erro fprintf(arq, "void erro(){\n"); fprintf(arq, " printf(\" Erro!\");\n"); fprintf(arq, "}\n"); fprintf(arq, "\n"); //fecha arquivo fclose(arq); }
C
// https://cs50.harvard.edu/x/2021/shorts/singly_linked_lists/ #include <stdio.h> #include <stdlib.h> /* Scope: * [x] Create a linked list * [x] Search a linked list * [x] Insert a new node into a linked list * [x] Delete a single element from the linked list * [x] Delete/Free the linked list nodes */ typedef struct sll_node { int value; struct sll_node *next; } node; node *NewNode(int value); void PrintList(node *head); void Insert(node *new_node, node **head); node *Find(int value, node *head); void FreeListNodes(node *head); void DeleteNode(int target_val, node **head); int main() { node *head = NULL; node *tmp = NULL; /* Create a linked list */ for (int i = 1; i <= 5; i++) Insert(NewNode(i), &head); /* Search a linked list */ node *find = Find(2, head); if (find != NULL) printf("Number %i, was found!\n", find->value); DeleteNode(5, &head); /* Print the linked list */ PrintList(head); /* Memory Management */ FreeListNodes(head); } /** * @brief Delete node with specific value in the linked list * @note * @param target_val: Node with the value to deallocate and delete * @param **head: Pointer to the linked list * @retval None */ void DeleteNode(int target_val, node **head) { node *prevNode = NULL; // keeps track of the target nodes prev node node *tmp = NULL; // temporary nullpointer node *cur_node = *head; // copy of the head pointer while(cur_node != NULL) { // Set the previous node pointer if ((cur_node->next != NULL) && (cur_node->next->value == target_val)) // IF: next node value has the target value prevNode = cur_node; // point the prevNode pointer to where head is currently pointing // Delete the target node if (cur_node->value == target_val && prevNode != NULL) { if (cur_node->next != NULL) { prevNode->next = cur_node->next; free(cur_node); } // properly remove and de-allocate tail node if (cur_node->next == NULL) { free(prevNode->next); prevNode->next = NULL; } } // properly remove and de-allocate the head node if (cur_node->value == target_val && prevNode == NULL) { tmp = *head; *head = (*head)->next; free(tmp); break; // O(1) operation: no need interate over the entire list if target is head } cur_node = cur_node->next; } } /** * @brief De-allocate the linked list nodes * @note * @param *head: Pointer to the head of the linked list * @retval None */ void FreeListNodes(node *head) { node *tmp = NULL; while (head != NULL) { tmp = head; head = head->next; free(tmp); } } /** * @brief Find a node in a linked list with a specific node value * @note * @param value: Value of the target node you wish to find * @param *head: Pointer to the head of the linked list * @retval Returns a pointer to the node with a specific value you are looking for */ node *Find(int value, node *head) { for (node *tmp = head; tmp != NULL; tmp = tmp->next) if (tmp->value == value) return tmp; return NULL; } /** * @brief Inserts a new node at the begining of a linked list * @note * @param *new_node: Pointer to a new node * @param **head: Pointer to the list * @retval None */ void Insert(node *new_node, node **head) { new_node->next = *head; *head = new_node; } /** * @brief Prints the node values to the console * @note * @param *head: Pointer to the linked list * @retval None */ void PrintList(node *head) { for (node *tmp = head; tmp != NULL; tmp = tmp->next) printf("%i\n", tmp->value); } /** * @brief Allocate a new node in heap memory * @note * @param value: Value to assign in the node value * @retval Returns a pointer to the newly allocated node in heap */ node *NewNode(int value) { node *tmp = malloc(sizeof(node)); tmp->next = NULL; tmp->value = value; return tmp; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> const double time_out = 20.0; const double STEP_TIME = 0.1; // time step, second int status = 0; int main(int argc, char** argv) { int exitno = 0; if(argc == 3){ exit(ft_call(argv[2], atof(argv[1]))); // printf("adf dmain got %d\n", status); } else if (argc == 2) { exitno = ft_call(argv[1], time_out); // printf("main got %d\n", exitno); } else { help(argv[0]); } } int help(char* name) { printf("Useage: %s [timeout_in_second] command\n", name); } void fun(int sig) { kill(0 , SIGKILL); } int ft_call(char *cmdstring, double timeout) { setpgid(0,0); // signal(SIGUSR1, fun ); //signal(SIGCHLD, SIG_IGN); pid_t pid; if (cmdstring == NULL) { return 1; } if ((pid = fork()) < 0) //fork出错 { status = -1; } else if (pid == 0) //子进程 { //execl("/bin/sh", "sh", "-c", cmdstring, (char*)0); status = system(cmdstring); int m = WEXITSTATUS(status); printf("sub process got %d\n", m); //kill(pid, SIGUSR1); exit(m); // ????? //_exit(127); } else { double left = timeout; double ret; while ((ret = waitpid(pid, &status, WNOHANG)) <= 0) { // printf("wait %e\n", left); usleep(STEP_TIME * 1000000); // use usleep to control left -= STEP_TIME; //time out if (left <= 0) { status = 137; kill(pid, SIGUSR1); printf("last got %d\n", status); exit(status); } } } }
C
#include <stdlib.h> #include <math.h> #include <stdio.h> typedef struct heap_item { int key; double sort_key; void *data; } heap_item; typedef struct heap { heap_item *heap_array; int size; } heap; heap *heap_create(int size) { heap *new_heap = (heap *)malloc(sizeof(heap)); new_heap->heap_array = (heap_item *)malloc(sizeof(heap_item) * size); new_heap->size = 0; return new_heap; } int heap_parent(int i) { return floor(i / 2); } int heap_left(int i) { return 2 * i; } int heap_right(int i) { return 2 * i + 1; } void heap_decrease_sort_key(heap *heap_to_decrease_sort_key, int index, double new_sort_key) { if (new_sort_key > heap_to_decrease_sort_key->heap_array[index].sort_key) { printf("New sort key larger than current sort key. %f -> %f\n", heap_to_decrease_sort_key->heap_array[index].sort_key, new_sort_key); return; } heap_to_decrease_sort_key->heap_array[index].sort_key = new_sort_key; while (index > 0 && heap_to_decrease_sort_key->heap_array[heap_parent(index)].sort_key > heap_to_decrease_sort_key->heap_array[index].sort_key) { heap_item tmp = heap_to_decrease_sort_key->heap_array[heap_parent(index)]; heap_to_decrease_sort_key->heap_array[heap_parent(index)] = heap_to_decrease_sort_key->heap_array[index]; heap_to_decrease_sort_key->heap_array[index] = tmp; index = heap_parent(index); } } void heap_insert(heap *heap_to_insert_in, int key, double sort_key, void *data) { heap_to_insert_in->size++; heap_to_insert_in->heap_array[heap_to_insert_in->size - 1].key = key; heap_to_insert_in->heap_array[heap_to_insert_in->size - 1].sort_key = INFINITY; heap_to_insert_in->heap_array[heap_to_insert_in->size - 1].data = data; heap_decrease_sort_key(heap_to_insert_in, heap_to_insert_in->size - 1, sort_key); } void heap_min_heapify(heap *heap_to_min_heapify, int index) { int left = heap_left(index); int right = heap_right(index); int smallest = index; if (left < heap_to_min_heapify->size && heap_to_min_heapify->heap_array[left].sort_key < heap_to_min_heapify->heap_array[index].sort_key) smallest = left; if (right < heap_to_min_heapify->size && heap_to_min_heapify->heap_array[right].sort_key < heap_to_min_heapify->heap_array[smallest].sort_key) smallest = right; if (smallest != index) { heap_item tmp = heap_to_min_heapify->heap_array[index]; heap_to_min_heapify->heap_array[index] = heap_to_min_heapify->heap_array[smallest]; heap_to_min_heapify->heap_array[smallest] = tmp; heap_min_heapify(heap_to_min_heapify, smallest); } } heap_item heap_extract_min(heap *heap_to_extract_min_from) { if (heap_to_extract_min_from->size < 1) { printf("Heap underflow.\n"); } heap_item min = heap_to_extract_min_from->heap_array[0]; heap_to_extract_min_from->heap_array[0] = heap_to_extract_min_from->heap_array[heap_to_extract_min_from->size - 1]; heap_to_extract_min_from->size--; heap_min_heapify(heap_to_extract_min_from, 0); return min; } int heap_get_index_of_key(heap *heap_to_find_key_in, int key) { int index = 0; while (index < heap_to_find_key_in->size) { if (heap_to_find_key_in->heap_array[index].key == key) { return index; } index++; } return -1; } void heap_delete(heap *heap_to_delete) { int i = 0; while (i < heap_to_delete->size) { free(heap_to_delete->heap_array[i].data); } free(heap_to_delete->heap_array); free(heap_to_delete); return; }