language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "storage_mgr.h" #include "dberror.h" #include "test_helper.h" // test name char *testName; /* test output files */ #define TESTPF "test_pagefile_2.bin" /* prototypes for test functions */ static void testCreateOpenClose(void); static void testMultiPageContent(void); /* main function running all tests */ int main (void) { testName = ""; initStorageManager(); // testCreateOpenClose(); testMultiPageContent(); return 0; } /* check a return code. If it is not RC_OK then output a message, error description, and exit */ /* Try to create, open, and close a page file */ void testMultiPageContent(void) { SM_FileHandle fh; SM_PageHandle ph; int i; testName = "test Multi page content"; ph = (SM_PageHandle) malloc(PAGE_SIZE); // create a new page file TEST_CHECK(createPageFile (TESTPF)); TEST_CHECK(openPageFile (TESTPF, &fh)); printf("created and opened file\n"); // read first page into handle TEST_CHECK(readFirstBlock (&fh, ph)); // the page should be empty (zero bytes) for (i=0; i < PAGE_SIZE; i++) ASSERT_TRUE((ph[i] == 0), "expected zero byte in first page of freshly initialized page"); printf("first block was empty\n"); // change ph to be a string and write that one to disk for (i=0; i < PAGE_SIZE; i++) ph[i] = (i % 10) + '0'; //TEST_CHECK(getBlockPos(&fh)); TEST_CHECK(writeBlock (0, &fh, ph)); printf("writing first block\n"); // read back the page containing the string and check that it is correct // Read current BLock TEST_CHECK(readCurrentBlock (&fh, ph)); printf("\nReading Current block Done"); //Get Block POsition printf("\nCurrent BLock Position is :%d",getBlockPos(&fh)); //Write block 2 TEST_CHECK(writeBlock(1,&fh,ph)); printf ("\nWrote page 2 with same content"); printf("\nNow current Block is:%d",getBlockPos(&fh)); // Reading 0th Block now printf("\nReading previous Block"); TEST_CHECK(readPreviousBlock(&fh,ph)); printf ("\nTo check we are reading previous block. Printing block position.And it is:%d",getBlockPos(&fh)); TEST_CHECK(readNextBlock(&fh,ph)); printf("\n To check we are reading next block. Printing block Position .And it is:%d",getBlockPos(&fh)); // Read First block TEST_CHECK(readFirstBlock(&fh,ph)); printf("\nAgain reading Block %d",getBlockPos(&fh)); // Testing write Current Block for(i=PAGE_SIZE; i<1 ; i--) ph [i] = (i%10) + '0'; TEST_CHECK(writeCurrentBlock(&fh,ph)); printf("Wrote this thing just now to current block:%s",ph); // Reading Last Block TEST_CHECK(readLastBlock(&fh,ph)); printf("\nReading Last block Done.And it is:%d",getBlockPos(&fh)); // Ensurring we are good with 3 pages TEST_CHECK(ensureCapacity(3,&fh)); // Writing 2nd block for that TEST_CHECK(writeBlock(2,&fh,ph)); printf("NOw we are in %d block",getBlockPos(&fh)); // destroy new page file TEST_CHECK(destroyPageFile (TESTPF)); TEST_DONE(); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include"httplib.h" #include<sys/stat.h> void str_slice (char* dst_string, char* src_string) { char tmp_string[64] = {0}; int counter = 0; int tmp_counter = 0; int flag = 1; int compare_condition = 1; while(flag) { if((dst_string[counter] == src_string[counter]) && compare_condition){ // Deleting the whitespace from the array, if u want to delete slash as well increment by 3 counter += 2; }else{ if(counter==64){ flag = 0; }else if(counter<64 && compare_condition){ compare_condition = 0; tmp_string[tmp_counter] = dst_string[counter]; counter++; tmp_counter++; }else{ tmp_string[tmp_counter] = dst_string[counter]; counter++; tmp_counter++; } } } strcpy(dst_string,tmp_string); } int serve_html(char* filename, int socket_des) { char buffer[2100]; int fd = open((const char*)filename,O_RDONLY); if(fd == -1) { perror("file open err"); return -1; } if(read(fd,&buffer,sizeof(buffer)) == -1 ) { perror("read serve_html"); return -1; } if(write(socket_des,buffer,sizeof(buffer)) == -1 ) { perror("write serve_html"); return -1; } if(close(fd) == -1) { perror("serve_html des close"); return -1; } return 1; }
C
#include<stdio.h> #include<pwd.h> #include<signal.h> static void my_alarm(int signo){ struct passwd *rootptr; printf("in signal handler\n"); if((rootptr = getpwnam("root")) == NULL){ printf("getpwname(root) error!\n"); alarm(1); } } int main(void){ struct passwd *ptr; signal(SIGALRM,my_alarm); alarm(1); for(;;){ if((ptr = getpwnam("xiaoli") )== NULL){ printf("getpwname error"); } if(strcmp(ptr->pw_name,"xiaoli") != 0){ printf("return value corrupted!,pw_name = %s\n",ptr->pw_name); } } }
C
#ifndef __THREAD_H__ #define __THREAD_H__ //#pragma comment( lib, "pthreadVCE2.lib") //#pragma comment( lib, "pthreadVSE2.lib") #define OPER_OK 0 #define THREAD_MUTEX_INIT_ERROR 1 #define MUTEX_DESTROY_ERROR 2 #define THREAD_MUTEX_LOCK_ERROR 3 #define THREAD_MUTEX_UNLOCK_ERROR 4 #define THREAD_COND_INIT_ERROR 5 #define COND_DESTROY_ERROR 6 #define COND_SIGNAL_ERROR 7 #define COND_WAIT_ERROR 8 #include "pthread.h" #pragma comment( lib, "pthread.lib") #ifdef __cplusplus extern "C" { #endif /* Define to prevent recursive inclusion -------------------------------------*/ typedef struct _mutex { pthread_mutex_t mutex; }mutex_t; typedef struct _cond { pthread_cond_t cond; }cond_t; typedef pthread_t tid_t; typedef pthread_attr_t attr_t; typedef void* (* thread_fun_t)(void*); typedef struct _thread { tid_t tid; cond_t *cv; int state; int stack_size; attr_t attr; thread_fun_t fun; }thread_t; /* mutex */ extern int mutex_init(mutex_t *m); extern int mutex_destroy(mutex_t *m); extern int mutex_lock(mutex_t *m); extern int mutex_unlock(mutex_t *m); /* cond */ extern int cond_init(cond_t *c); extern int cond_destroy(cond_t *c); extern int cond_signal(cond_t *c); extern int cond_wait(cond_t *c,mutex_t *m); /* thread */ /* ̵߳ĴԵõȶװ */ extern int thread_create(thread_t *t); //extern int thread_init(thread_t *t); #define thread_join(t, p) pthread_join(t, p) #define thread_self() pthread_self() //#define thread_sigmask pthread_sigmask #ifdef __cplusplus } #endif #endif /* END OF FILE ---------------------------------------------------------------*/
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { if (argc == 2) { int kv[strlen(argv[1])]; // Iterate through command line arg for (int i = 0, n = strlen(argv[1]); i < n; i++) { if (isalpha(argv[1][i]) == false) { printf("Usage: ./vignere keyword\n"); return 1; } // Add char to array if alpha char else { if (isupper(argv[1][i])) { kv[i] = argv[1][i] - 65; } else { kv[i] = argv[1][i] - 97; } } } string p = get_string("plaintext: "); int cipher[strlen(p)]; for (int i = 0, n = strlen(p), j = 0; i < n; i++, j = (j + 1) % strlen(argv[1])) { if (isalpha(p[i])) { if (isupper(p[i])) { char c = (((p[i] + kv[j]) - 65) % 26) + 65; cipher[i] = c; } else { char c = (((p[i] + kv[j]) - 97) % 26) + 97; cipher[i] = c; } } else { j -= 1; cipher[i] = p[i]; } } printf("ciphertext: "); for (int i = 0, n = strlen(p); i < n; i++) { printf("%c", cipher[i]); } printf("\n"); return 0; } else { printf("Usage: ./vignere keyword\n"); return 1; } }
C
#include <stdio.h> #include <stdlib.h> int main2() { /*int arr[10] = { 1,2,3,4,5,6,7,8,9,10 }; printf("%x\n", arr); int data = 20; for (int *p = arr; p < arr + 10; p++) { *p = data; data = data - 2; } printf("=======================\n"); for (int i = 0; i < 10; i++) { printf("arr[%d]=%d\n", i, arr[i]); }*/ system("pause"); return 0; }
C
#include <stdio.h> #include <string.h> #define MAXLON 80 int main() { char a[MAXLON+1],b[MAXLON+1]; int l,m,L,n,i; printf("ingrese cadena (max 80 caract.):\n"); gets(a); printf("ingrese otra cadena (max 80 caract.):\n"); gets(b); //leemos longitud de la cadena l=strlen(a); printf("%d\n",l); L=strlen(b); printf("%d\n",L); //eliminamos los valores repetidos for (m=0;m<L;m++) { for (n=0;n<l;n++) { for (i=0;i<l;i++) { if (a[i]==b[m]) for (i=i;i<l;i++) { a[i]=a[i+1]; } } } } a[i]='\0'; printf("%s\n",a); return 0; }
C
#define u64 long long double cosine(double x) { double ret=0,item=1.0,temp; int n=0,i,sign=1; if(x>2*3.1415||x<-2*3.1415){x-=((int)(x/(2*3.1415)))*(2*3.1415);} do{ temp=item; for(i=1;i<=2*n;i++)temp/=i; ret+=sign*temp; item*=x*x; sign *=-1; n++; }while (temp>1e-10); return ret; } double sine(double x) { int m = 1,i; double temp,ret = 0.0; if(x>2*3.1415||x<-2*3.1415){x-=((int)(x/(2*3.1415)))*(2*3.1415);} do{ i=0; if (m%2 == 0){temp= -1.0;} else{temp= 1.0;} for(i=1;i<=2*m-1;i++){temp = temp * x/i;} ret+= temp; m++; }while (temp<-.0000005||temp>0.0000005); return ret; } void taiji(double* base) { double angle; int basex,basey,x,y; *base+=0.01; basex=(int)(100*cosine(*base)); basey=(int)(100*sine(*base)); for(angle=0;angle<3.14;angle+=0.01) { x=basex+(int)(100*cosine(*base+angle)); y=basey+(int)(100*sine(*base+angle)); draw(x+250,y,0xffffffff); draw(-x+250,-y,0); } writescreen(); } void main() { double base=0.0; while(1) { taiji(&base); int input=pollevent(); if(input<=0) return; if(input==0x1b) return; } }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <pthread.h> #include "fish.h" #include "view.h" #include "queue.h" #include "mobility.h" #include "tools.h" #include "string.h" TAILQ_HEAD(fish_queue, fish); struct fish_queue* fishs; static pthread_mutex_t mutex_fishs; static pthread_mutexattr_t recursive; int fish_belongs_to_view(struct fish *fish, struct view *view) { return (fish->coordinates.x >= view->start.x && fish->coordinates.y >= view->start.y && fish->coordinates.x <= view->start.x + view->size.width && fish->coordinates.y <= view->start.y + view->size.height) || (fish->coordinates.x + fish->size.width >= view->start.x && fish->coordinates.x + fish->size.width <= view->start.x + view->size.width && fish->coordinates.y >= view->start.y && fish->coordinates.y <= view->start.y + view->size.height) || (fish->coordinates.x >= view->start.x && fish->coordinates.x <= view->start.x + view->size.width && fish->coordinates.y + fish->size.height <= view->start.y + view->size.height && fish->coordinates.y + fish->size.height >= view->start.y) || (fish->coordinates.x + fish->size.width <= view->start.x + view->size.width && fish->coordinates.x + fish->size.width >= view->start.x && fish->coordinates.y + fish->size.height <= view->start.y + view->size.height && fish->coordinates.y + fish->size.height >= view->start.y); } void fishs_init() { printf("Fishs init\n"); fishs = malloc(sizeof(struct fish_queue)); TAILQ_INIT(fishs); pthread_mutexattr_init(&recursive); pthread_mutexattr_settype(&recursive, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_fishs, &recursive); } void fishs_finalize() { if (fishs == NULL) { return; } while (!TAILQ_EMPTY(fishs)) { struct fish * fish = TAILQ_FIRST(fishs); fish_remove(fish->name); } free(fishs); fishs = NULL; pthread_mutex_destroy(&mutex_fishs); pthread_mutexattr_destroy(&recursive); } void fishs_update() { pthread_mutex_lock(&mutex_fishs); if (!TAILQ_EMPTY(fishs)) { struct fish* f; for (f = TAILQ_FIRST(fishs); f != TAILQ_LAST(fishs, fish_queue); f = TAILQ_NEXT(f, queue_entries)) { fish_update(f); } fish_update(f); } pthread_mutex_unlock(&mutex_fishs); } void fish_update(struct fish *fish) { call_mobility_function(fish); } int fish_add(char* name, int x, int y, int w, int h, char *mobility) { if (fish_find(name) != NULL) { return 0; } struct fish *fish = malloc(sizeof(struct fish)); fish->coordinates.x = x; fish->coordinates.y = y; fish->size.width = w; fish->size.height = h; fish->param = NULL; strcpy(fish->name, name); if (!setup_mobility(fish, mobility)) { return 0; } fish->state = NOT_STARTED; pthread_mutex_lock(&mutex_fishs); TAILQ_INSERT_TAIL(fishs, fish, queue_entries); pthread_mutex_unlock(&mutex_fishs); return 1; } int fish_remove(char *name) { struct fish *fish; if ((fish = fish_find(name)) == NULL) { return 0; } pthread_mutex_lock(&mutex_fishs); TAILQ_REMOVE(fishs, fish, queue_entries); pthread_mutex_unlock(&mutex_fishs); free(fish->param); free(fish); return 1; } int fish_start(char *name) { pthread_mutex_lock(&mutex_fishs); struct fish *f = fish_find(name); if (f == NULL || f->state == STARTED) { pthread_mutex_unlock(&mutex_fishs); return 0; } f->state = STARTED; pthread_mutex_unlock(&mutex_fishs); return 1; } struct fish *fish_find(char *name) { pthread_mutex_lock(&mutex_fishs); struct fish *f; if (!TAILQ_EMPTY(fishs)) { for (f = TAILQ_FIRST(fishs); f != TAILQ_LAST(fishs, fish_queue); f = TAILQ_NEXT(f, queue_entries)) { if (strcmp(f->name,name) == 0) { pthread_mutex_unlock(&mutex_fishs); return f; } } if (strcmp(f->name,name) == 0) { pthread_mutex_unlock(&mutex_fishs); return f; } } pthread_mutex_unlock(&mutex_fishs); return NULL; } char *fish_get_info(struct view *view, struct fish *fish) { const int length = MAX_BUFFER_SIZE + 50; char *info = malloc(length * sizeof(char)); snprintf(info, length - 1, "[%s at %dx%d, %dx%d, 0]", fish->name, (fish->coordinates.x - view->start.x) * 100 / view->size.width, (fish->coordinates.y - view->start.y) * 100 / view->size.height, fish->size.width * 100 / view->size.width, fish->size.height * 100 / view->size.height); return info; } char *fishes_get_info(struct view *client_view) { pthread_mutex_lock(&mutex_fishs); struct fish *fish = NULL; int total_length = 10; TAILQ_FOREACH(fish, fishs, queue_entries) { if (fish_belongs_to_view(fish, client_view)) { total_length += MAX_BUFFER_SIZE + 50; } } char *info_list = malloc(total_length * sizeof(char)); strcpy(info_list, "list"); fish = NULL; TAILQ_FOREACH(fish, fishs, queue_entries) { if (fish_belongs_to_view(fish, client_view)) { char *fish_info = fish_get_info(client_view, fish); strcat(info_list, " "); strcat(info_list, fish_info); free(fish_info); } } pthread_mutex_unlock(&mutex_fishs); strcat(info_list, "\n"); return info_list; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/stat.h> #define PIPE_BUF 100 /* Maximum length of event */ int avg(int inteiro[], int size){ int i, total=0; for(i=0; i<size; i++) total += inteiro[i]; if (size==0) return 0; else return (total/size); } /* Auxilixar function to calculate sum of int array for window function */ int sum(int inteiro[], int size){ int i, total=0; for(i=0; i<size; i++) total += inteiro[i]; if (size==0) return 0; else return total; } /* Auxilixar function to calculate max of int array for window function */ int max(int inteiro[], int size){ int i, max=inteiro[0]; for(i=1; i<size; i++) if (inteiro[i]>max) max = inteiro[i]; if (size==0) return 0; else return max; } /* Auxilixar function to calculate min of int array for window function */ int min(int inteiro[], int size){ int i, min=inteiro[0]; for(i=1; i<size; i++) if (inteiro[i]<min) min = inteiro[i]; if (size==0) return 0; else return min; } /* Auxiliar function to remove an element from an array */ void remove_element(char **array, int index, int array_length) { int i; for(i = index; i < array_length - 1; i++) array[i] = array[i + 1]; } /* Auxiliar function to read line */ ssize_t readln(int fld, char *buf, size_t nbyte){ int i=0; while ((read(fld,buf+i,1)>0) && i<nbyte && (buf[i]!='\n')) i++; buf[i]='\0'; return i; } /* Window component: window <column> <operation> <lines> */ void window(char *col, char *op, char *lines){ int result, a, i, r, loop=0, before[atoi(lines)]; for (i=0; i<atoi(lines); i++) before[i] = 0; char buf[PIPE_BUF+1], bufcpy[PIPE_BUF+1], *del=":", *token; while((r=(readln(0, buf, PIPE_BUF)))) { int x, count; char *buf2 = strdup(buf); for (x=0, count=0; buf2[x]; x++) count += (buf2[x] == ':'); if (count < atoi(col)-1) { write(1, "\n", 1); } else { if (r==PIPE_BUF || ((r+2) > PIPE_BUF)) { write(1, buf, PIPE_BUF); write(1, "\n", 1); } else { if (loop < (atoi(lines))) i = loop; else i = (atoi(lines)); if (!strcmp(op, "avg")){ result = avg(before, i); strcat(buf, ":"); int length = snprintf( NULL, 0, "%d", result ); char* resultS = malloc( length + 1 ); snprintf( resultS, length + 1, "%d", result ); strcat(buf, resultS); write(1, buf, r+1+strlen(resultS)); write(1, "\n", 1); free(resultS); } else if (!strcmp(op, "sum")){ result = sum(before, i); strcat(buf, ":"); int length = snprintf( NULL, 0, "%d", result ); char* resultS = malloc( length + 1 ); snprintf( resultS, length + 1, "%d", result ); strcat(buf, resultS); write(1, buf, r+1+strlen(resultS)); write(1, "\n", 1); free(resultS); } else if (!strcmp(op, "max")){ result = max(before, i); strcat(buf, ":"); int length = snprintf( NULL, 0, "%d", result ); char* resultS = malloc( length + 1 ); snprintf( resultS, length + 1, "%d", result ); strcat(buf, resultS); write(1, buf, r+1+strlen(resultS)); write(1, "\n", 1); free(resultS); } else if (!strcmp(op, "min")){ result = min(before, i); strcat(buf, ":"); int length = snprintf( NULL, 0, "%d", result ); char* resultS = malloc( length + 1 ); snprintf( resultS, length + 1, "%d", result ); strcat(buf, resultS); write(1, buf, r+1+strlen(resultS)); write(1, "\n", 1); free(resultS); } a=1; strcpy(bufcpy, buf); token = strtok(bufcpy, del); if (atoi(col)==1) before[loop%(atoi(lines))] = atoi(token); else { while(((token = strtok(NULL, del)) != NULL) && (a+1)<atoi(col)) { a++; } if (atoi(col)==(a+1)) before[loop%(atoi(lines))] = atoi(token); else before[loop%(atoi(lines))] = 0; } } loop++; } } } int main(int argc, char *argv[]) { window(argv[1], argv[2], argv[3]); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include "ppf4td.h" #include "ppf4td_pipe.h" typedef struct { FILE *fp; pid_t pid; } pipe_privrec_t; int ppf4td_pipe_open (ppf4td_ctx_t *ctx, char *const cmdline[]) { pipe_privrec_t *me; int fds[2]; int r; int saved_errno; /* Check availability of command first */ if (access(cmdline[0], X_OK) != 0) { fprintf(stderr, "unable to exec(\"%s\"): %s\n", cmdline[0], strerror(errno)); errno = ENOEXEC; return -1; } if (pipe(fds) != 0) return -1; me = malloc(sizeof(*me)); if (me == NULL) return -1; r = fork(); /* Failed? */ if (r < 0) goto CLEANUP; /* Is it a child? */ if (r == 0) { close(fds[0]); if (dup2(fds[1], 1) < 0) exit(1); if (fds[1] > 2) close(fds[1]); execv(cmdline[0], cmdline); /* Here only if failed to exec() */ fprintf(stderr, "failed to exec(\"%s\")\n", cmdline[0]); exit(1); } /* Still in a parent */ close(fds[1]); me->fp = fdopen(fds[0], "r"); me->pid = r; ctx->imp_privptr = me; return 0; CLEANUP: saved_errno = errno; close(fds[0]); close(fds[1]); free(me); errno = saved_errno; return -1; } int ppf4td_pipe_close(ppf4td_ctx_t *ctx) { pipe_privrec_t *me = ctx->imp_privptr; int status; fclose(me->fp); waitpid(me->pid, &status, 0); free(me); return 0; } static int result_of_xxxxc(ppf4td_ctx_t *ctx, int ch) { pipe_privrec_t *me = ctx->imp_privptr; int status; if (ferror(me->fp)) return -1; if (ch == EOF) { #if 0 int r; r = waitpid(me->pid, &status, 0); fprintf(stderr, "WAITPID: r=%d WIFEXITED=%d WEXITSTATUS=%d\n", r, WIFEXITED(status), WEXITSTATUS(status)); #else if (waitpid(me->pid, &status, 0) <= 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) return -1; #endif return 0; } return +1; } int ppf4td_pipe_peekc(ppf4td_ctx_t *ctx, int *ch_p) { pipe_privrec_t *me = ctx->imp_privptr; *ch_p = fgetc(me->fp); if (*ch_p != EOF) ungetc(*ch_p, me->fp); return result_of_xxxxc(ctx, *ch_p); } int ppf4td_pipe_nextc(ppf4td_ctx_t *ctx, int *ch_p) { pipe_privrec_t *me = ctx->imp_privptr; *ch_p = fgetc(me->fp); return result_of_xxxxc(ctx, *ch_p); }
C
#include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Header below added by Tulsi */ #include <stdlib.h> /* Header below added by Qahwa for replaced CUBLAS code */ #include <cublas_v2.h> #include <cuda_runtime.h> int N = 3; void symm(float alpha, float beta, float A[N][N], float B[N][N], float C[N][N]) { int i,j,k; cublasStatus_t status; cublasHandle_t handle; float *d_A = 0; float *d_B = 0; float *d_C = 0; const float d_alpha = 1.0f; const float d_beta = 0.0f; cublasCreate(&handle); cudaMalloc((void **)&d_A, N * N * sizeof(d_A[0])); cudaMalloc((void **)&d_B, N * N * sizeof(d_B[0])); cudaMalloc((void **)&d_C, N * N * sizeof(d_C [0])); cudaMemcpy(d_A, A, N * N * sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_B, B, N *N * sizeof(float), cudaMemcpyHostToDevice); cublasSsymm (handle, CUBLAS_SIDE_RIGHT, CUBLAS_FILL_MODE_UPPER, N, N, &d_alpha, d_A, N, d_B, N, &d_beta, d_C, N); cudaMemcpy(C, d_C, N*N*sizeof(float), cudaMemcpyDeviceToHost); cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); cublasDestroy(handle); } int main(int argc, char **argv) { int M = 3; int n = N; float alpha = 1; float beta = 0; float a[3][3] = { 3, 0, 0, 2, 5, 0, 5, 4, 7}; //float b[3][3] = {1, 1, 1, 2, 5, 1, 3, 6, -3}; //, 3, -1, -2, 5, 2, -1}; float b[3][3] = { -1, 3, -3, 0, -6, 5, -5, -3, 1}; float res[3][3]; symm(alpha, beta, a, b, res); int i; int j; printf("The res x is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { printf(" %f ", res[i][j]); } printf("\n"); } printf("\n"); }
C
#include<stdio.h> //more about printf /* printf puts program data into stdout (stream that connects CPU and Monitor) and it returns the number of characters transmitted. */ int main() { int x; x = printf("Hello All"); printf("\n x : %d", x); printf("\n----------------\n"); x = 123; //printf("%5d", x);//print x like a 5 digit number //printf("%05d", x);//print x like a 5 digit number with leading zeros printf("%+d", x);//print x with a sign return 0; }
C
#include<stdio.h> main() { //1.display the menu printf("pick an item : \n1. pen\n2. pencil\n3. eraser\n4. book"); //2.read thier choice int choice=0; scanf("%d",&choice); //3.display based on their choice switch(choice) { case 1: printf("you picked pen"); break; case 2: printf("you picked pencil"); break; case 3: printf("you picked eraser"); break; case 4: printf("you picked book"); break; default: printf(" use the default case.1,2,3,4."); } }
C
#include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #define MAXPENDING 5 #define RECVBUFSIZE 32 #define PORT 14456 void dieWithError(char* errorMessage); //error handling function void handleTCPClient(int clientSocket); //TCP client handling function int main(int argc, char** argv) { int serverSocket; //Socket descriptor for server int clientSocket; //Socket descriptor for client struct sockaddr_in echoServerAddr; //local address struct sockaddr_in echoClientAddr; //client address unsigned short echoServerPort; //server port unsigned int clientLen; //length of client address data structure // if(argc != 2){ // fprintf(stderr, "Usage %s <Server Port>\n", argv[0]); // exit(1); // } echoServerPort = PORT; //create socket for incoming connections if((serverSocket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ dieWithError("socket() failed"); } //construct local address structure memset(&echoServerAddr, 0, sizeof(echoServerAddr)); //zero out structure echoServerAddr.sin_family = AF_INET; //internet address family echoServerAddr.sin_addr.s_addr = htonl(INADDR_ANY); //any incoming interface echoServerAddr.sin_port = htons(echoServerPort); //local port //bind to the local address if(bind(serverSocket, (struct sockaddr*)&echoServerAddr, sizeof(echoServerAddr)) < 0){ dieWithError("bind() failed"); } //mark the socket so it will listen for incoming connections if(listen(serverSocket, MAXPENDING) < 0){ dieWithError("listen() failed"); } //set the size of the in-out parameter clientLen = sizeof(echoClientAddr); //wait for client to connect if((clientSocket = accept(serverSocket, (struct sockaddr*)&echoClientAddr, &clientLen)) < 0){ dieWithError("accept() failed"); } //clientSocket is connected to a client printf("Handling client %s\n", inet_ntoa(echoClientAddr.sin_addr)); handleTCPClient(clientSocket); } void handleTCPClient(int clientSocket) { char echoBuffer[RECVBUFSIZE]; int msgSize; char dle_etx[] = "\x10\x03"; int sent; //recieve message from client int count = 0; while(1) { //see if there is more data to recieve if((msgSize = recv(clientSocket, echoBuffer, RECVBUFSIZE, 0)) < 0){ dieWithError("recv() failed"); } echoBuffer[msgSize] = '\0'; //printf("recved %s\n", echoBuffer); if((sent = send(clientSocket, echoBuffer, msgSize, 0) )!= msgSize){ printf("ms = %d, but sent %d\n",msgSize, sent ); dieWithError("send() failed"); } if(msgSize == 0){ break; } if(strcmp(dle_etx, echoBuffer) == 0){ break; } count++; } printf("EnhancedServer echoed %d strings.\n",count); //recieve last packet to finish recv(clientSocket, echoBuffer, RECVBUFSIZE, 0); close(clientSocket); // } } void dieWithError(char* errorMessage) { fprintf(stderr, "%s\n", errorMessage); exit(1); }
C
#include "holberton.h" #include <stdlib.h> #include <stdio.h> #include <stddef.h> /** * argstostr - function that concatenates * all the arguments of your program. * @ac: the number of arguments * @av: array of the arguments content * Return: str. */ char *argstostr(int ac, char **av) { int i, j, x, h, l, length = 0; char *str; if (ac == 0 || av == NULL) { return (NULL); } for (h = 0; h < ac; h++) { /*printf("ac = %d\n", ac);*/ for (l = 0; av[h][l] != '\0'; l++) { length++; } } /*printf("length: %d\n", length);*/ str = malloc((length + ac + 1) * sizeof(char)); if (str == NULL) return (NULL); x = 0; for (i = 0; i < ac; i++) { for (j = 0; av[i][j] != '\0'; j++) { str[x] = av[i][j]; x++; } str[x] = '\n'; x++; } str[x] = '\0'; return (str); }
C
#include "../sllist.h" #include <stdio.h> int main() { int n; scanf("%d", &n); int data; struct node *list = NULL; while (n--) { scanf("%d", &data); append(&list, data); } // Make the list circular struct node *temp = list; while (temp->next != NULL) temp = temp->next; temp->next = list->next->next->next; // Start detection struct node *slow = list, *fast = list; int flag = 0; while (slow != NULL) { if (fast == NULL || fast->next == NULL || fast->next->next == NULL) break; slow = slow->next; fast = fast->next->next; if (fast == slow) { flag = 1; break; } } if (flag) { printf("Loop exists...\n"); fast = list; while (1) { if (fast == slow) { printf("Loop begins at %d\n", slow->data); break; } fast = fast->next; slow = slow->next; } } else { printf("Loop doesn't exist...\n"); } return 0; }
C
// seven different ways to print the odd numbers // between 0 and 10 on a single line. #include <stdio.h> void amaze1(); void amaze2(); void amaze3(); void amaze4(); void amaze5(); void amaze6(); void amaze7(); void amazeWOW(); int main(int argc, char ** argv) { amaze1(); amaze2(); amaze3(); amaze4(); amaze5(); amaze6(); amaze7(); amazeWOW(); return 0; } void amazeWOW() { int i; printf("amazeWOW:\t"); for (i = 0; i <= 10; i++) { if (i % 2 == 1) { printf("%d ", i); } } printf("\n"); } // direct way void amaze1() { int i, num[5] = {1, 3, 5, 7, 9}; printf("amaze1:\t\t"); for (i = 0; i < 5; i++) { printf("%d ", num[i]); } printf("\n"); } // a more direct way void amaze2() { int i; printf("amaze2:\t\t"); for (i = 1; i <= 10; i = i + 2) { printf("%d ", i); } printf("\n"); } //while void amaze3() { int i = 0; printf("amaze3:\t\t"); while (i <= 10) { if (i % 2 == 1) { printf("%d ", i); } i++; } printf("\n"); } // using do while void amaze4() { int i = 0; printf("amaze4:\t\t"); do { if (i % 2 == 1) { printf("%d ", i); } i++; } while (i <= 10); printf("\n"); } // using goto void amaze5() { int i = 0; printf("amaze5:\t\t"); start: if (i <= 10) { if (i % 2 == 1) { printf("%d ", i); } i++; goto start; } printf("\n"); } // using switch instead of if void amaze6() { int i = 0; printf("amaze6:\t\t"); while (i <= 10) { switch(i % 2) { case(1): printf("%d ", i); i++; break; default: i++; break; } } printf("\n"); } // the last way I can think of void amaze7() { printf("amaze7:\t\t"); printf("1 3 5 7 9\n"); }
C
/* ** tkp_z.c for ctrlz in /home/gotte_a/rendu/infographie/tekpaint/current/gfx_tekpaint ** ** Made by Alexandre Gotte ** Login <gotte_a@epitech.net> ** ** Started on Fri Jan 22 09:48:28 2016 Alexandre Gotte ** Last update Fri Jan 22 15:36:24 2016 Alexandre Gotte */ #include "paint.h" void fill_zpix(t_bjr *bjr) { t_bunny_position p; t_color c; p = init_bun_pos(0, 0); while (p.y < W_HEIGHT) { p.x = 0; while (p.x < W_WIDTH - 500) { c = get_pixel(bjr->m_pix, &p); tekpixel(bjr->ctz.z_pix[bjr->ctz.nb], &p, c.full); p.x = p.x + 1; } p.y = p.y + 1; } } void fill_zpix2(t_bjr *bjr) { t_bunny_position p; t_color c; p = init_bun_pos(0, 0); while (p.y < W_HEIGHT) { p.x = 0; while (p.x < W_WIDTH - 500) { c = get_pixel(bjr->ctz.z_pix[bjr->ctz.nb], &p); tekpixel(bjr->m_pix, &p, c.full); p.x = p.x + 1; } p.y = p.y + 1; } } void hun_ctz(t_bjr *bjr) { bunny_delete_clipable(&bjr->ctz.z_pix[bjr->ctz.nb]->clipable); bjr->ctz.z_pix[bjr->ctz.nb] = bunny_new_pixelarray(W_WIDTH - 500, W_HEIGHT); fill_zpix(bjr); bjr->ctz.nb = bjr->ctz.nb + 1; if (bjr->ctz.nb > 2) bjr->ctz.nb = 0; bjr->ctz.us = 1; } void hun_ctz2(t_bjr *bjr) { fill_zpix2(bjr); bjr->ctz.nb -= 1; if (bjr->ctz.nb < 0) { bjr->ctz.nb = 0; bjr->ctz.us = 0; } }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include "ext2.h" #include <string.h> #include <errno.h> #include "ext2_helper.c" int main(int argc, char **argv) { unsigned char *disk; char* current_path; // make sure the parameter is enogu and the input is abs path if (argc != 3 || argv[2][0] != '/') { fprintf(stderr, "Usage: %s <disk_img path> <new directory's absolute path>\n", argv[0]); exit(1); } current_path = argv[2]; // read the disk image disk = read_disk(argv[1]); int inode_index = read_path (disk, current_path); if (inode_index != -1) { fprintf(stderr, "%s: already exist\n", argv[2]); exit(EEXIST); } int path_length = strlen(current_path); char dir_name[path_length]; // remove any ending slash remove_ending_slash(current_path); // get the parent directory path and pop_last_file_name(current_path, dir_name); // get the inode number fo the parent_directory inode_index = read_path(disk, current_path); // check if inode is found if (inode_index == -1) { fprintf(stderr, "%s: No such directory\n", argv[2]); exit(ENOENT); } // get the parent inode struct ext2_inode *place_inode = get_inode(disk, inode_index); // make sure it is a directory if (!S_ISDIR(place_inode->i_mode)) { fprintf(stderr, "%s: No such directory\n", argv[2]); exit(ENOENT); } // allocate a new inode int free_inode_index = find_free_inode(disk); if (free_inode_index == -1) { fprintf(stderr, "%s: No inode avaiable\n", argv[0]); exit(1); } // allocate blocks int* free_blocks = find_free_blocks(disk, 1); if (free_blocks[0] == -1) { free(free_blocks); fprintf(stderr, "%s: No blocks avaiable\n", argv[0]); exit(1); } // update bitmap to make sure we are working on it for sure set_bitmap(0, disk, free_inode_index, 1); set_bitmap(1, disk, free_blocks[0], 1); // update the parent directory inode's dir_entry int result = add_link_to_dir(place_inode, disk, dir_name, free_inode_index, EXT2_FT_DIR); // if there isn't any blcok for the new dir_entry if (result == -1) { // need to revert the bitmap set_bitmap(0, disk, free_inode_index, 0); set_bitmap(1, disk, free_blocks[0], 0); free(free_blocks); fprintf(stderr, "%s: No blocks avaiable\n", argv[0]); exit(1); } place_inode->i_links_count++; // init inode amd set up property struct ext2_inode *dir_inode = initialize_inode(disk, free_inode_index,EXT2_S_IFDIR,EXT2_BLOCK_SIZE); // init block as dir_entry for the dir_inode unsigned long pos = (unsigned long) disk + EXT2_BLOCK_SIZE * free_blocks[0]; // init first dir_entry for . struct ext2_dir_entry_2 *dir_entry = (struct ext2_dir_entry_2 *) pos; dir_entry->name[0] = '.'; dir_entry->name_len = 1; dir_entry->inode = free_inode_index; dir_entry->rec_len = 12; dir_entry->file_type = EXT2_FT_DIR; // init first dir_entry for .. pos = pos + dir_entry->rec_len; dir_entry = (struct ext2_dir_entry_2 *) pos; dir_entry->name[0] = '.'; dir_entry->name[1] = '.'; dir_entry->name_len = 2; dir_entry->inode = inode_index; dir_entry->rec_len = EXT2_BLOCK_SIZE - 12; dir_entry->file_type = EXT2_FT_DIR; // update the link count of the directory and others blocks dir_inode->i_links_count ++; dir_inode->i_block[0] = free_blocks[0]; dir_inode->i_blocks = 2; // udpate the group descriptor // update used block and inodes struct ext2_super_block *sb = (struct ext2_super_block *)(disk + 1024); // get the inode bitmap to manipulate its bits if there are free inode in the bitmap struct ext2_group_desc *bgd = (struct ext2_group_desc *) (disk + 2048); bgd->bg_free_inodes_count --; sb->s_free_inodes_count --; bgd->bg_free_blocks_count --; sb->s_free_blocks_count --; bgd->bg_used_dirs_count ++; }
C
#include <sys/types.h> #include <sys/event.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <fcntl.h> #include <errno.h> #include <dirent.h> #include <syslog.h> #include <mach/boolean.h> /* * Monitor whether or not something has entered postfix's maildrop and, when * it does, start postfix. When last entry goes away, stop postfix. */ #define POSTFIX_DROP "/var/spool/postfix/maildrop" #define POSTFIX_FIFO "/var/spool/postfix/public/pickup" static int postfix_on = FALSE; #define START 1 #define STOP 2 static void postfix_control(int); static int directory_numfiles(char *); int main(int argc, char *argv[]) { int i, kq, stop_pending = FALSE; struct kevent kin, kout; struct timespec timeout; /* properly daemonize ourselves */ daemon(0, 0); /* Create the submission fifo if it doesn't exist */ if (access(POSTFIX_FIFO, W_OK)) if (!mkfifo(POSTFIX_FIFO, 0622)) (void)chmod(POSTFIX_FIFO, 0622); /* If there are files left over from some previous invocation, start postfix*/ if (directory_numfiles(POSTFIX_DROP)) postfix_control(START); /* Initialize our kevent structures to zero */ bzero(&kin, sizeof(struct kevent)); bzero(&kout, sizeof(struct kevent)); /* * Allocate a kevent for monitoring the directory. ident is a * file descriptor, filter is a vnode monitor set to watch for * writes. */ kin.ident = open(POSTFIX_DROP, O_EVTONLY, 0); if (kin.ident < 0) { syslog(LOG_ERR, "Unable to open postfix drop: %s\n", strerror(errno)); exit(1); } kin.filter = EVFILT_VNODE; kin.flags = EV_ADD | EV_CLEAR; kin.fflags = NOTE_DELETE | NOTE_WRITE; kin.data = NULL; kin.udata = POSTFIX_DROP; /* Create kqueue. */ kq = kqueue(); if (kq == -1) { syslog(LOG_ERR, "Unable to create kqueue: %s\n", strerror(errno)); exit(1); } /* * Input our list of file descriptors to watch. */ kevent(kq, &kin, 1, NULL, 0, NULL); /* * We'll wait for events for 3600 seconds at a time. One hour should * be a very reasonable "large timeout". */ timeout.tv_sec = 3600; timeout.tv_nsec = 0; /* * Big loop to monitor for events. */ for (;;) { /* * Get events. */ i = kevent(kq, NULL, 0, &kout, 1, &timeout); if (i == 0) { /* We've timed out after an hour's wait so check status */ if (stop_pending) { /* Did anything sneak in? */ if (!directory_numfiles(POSTFIX_DROP)) postfix_control(STOP); stop_pending = FALSE; } continue; } else if (i == -1) { syslog(LOG_ERR, "kevent returned error: %s\n", strerror(errno)); goto cleanup; } /* Do appropriate things with file modifications. */ if (kout.fflags & NOTE_WRITE) { i = directory_numfiles(POSTFIX_DROP); if (i == 0 && postfix_on == TRUE) { /* Time to shut down, so set it up to happen an hour from now */ stop_pending = TRUE; } else if (i > 0 && postfix_on == FALSE) postfix_control(START); } else if (kout.fflags & NOTE_DELETE) { syslog(LOG_ERR, "Postfix maildrop was deleted! Stopping postfix permanently.\n"); if (postfix_on == TRUE) postfix_control(STOP); goto cleanup; } } cleanup: close(kq); exit(1); } static void postfix_control(int what) { pid_t pid; int status; if (what == START) { pid = fork(); if (pid == 0) { execl("/sbin/service", "service", "smtp", "start", NULL); syslog(LOG_ERR, "Unable to invoke /sbin/service!\n"); _exit(1); } else { /* Should probably do something meaningful with the return status someday */ (void)waitpid(pid, &status, 0); postfix_on = TRUE; } } else if (what == STOP) { pid = fork(); if (pid == 0) { execl("/sbin/service", "service", "smtp", "stop", NULL); syslog(LOG_ERR, "Unable to invoke /sbin/service!\n"); _exit(1); } else { /* Should probably do something meaningful with the return status someday */ (void)waitpid(pid, &status, 0); postfix_on = FALSE; } } } static int directory_numfiles(char *dirname) { int num = 0; DIR *dp; struct dirent *de; dp = opendir(dirname); if (!dp) { perror("opendir"); return 0; } while ((de = readdir(dp)) != 0) { /* A better heuristic for actually determining what postfix * queue files look like should probably go here, just to * eliminate false positives. */ if (de->d_name[0] != '.') ++num; } closedir(dp); return num; }
C
/* DS ASSINGMENT */ /* a program to convert prefix to infix */ #include<stdio.h> #include<stdlib.h> #include<malloc.h> #define MAX 10 struct stack_element{ int arr[MAX]; int top; struct stack_element *ptr; };//*ptr; //int stackEMPTY(struct stack_element *); //int stackFULL(struct stack_element *); //void PREFIXtoPOSTFIX(); void push(struct stack_element *, int); void pop(struct stack_element *); //void display(&ptr); void main(){ //struct stack_element obj; char postfix[10];// array to store the basic value for(int i=0;i<10;i++){ printf("\nENTER THE POSTFIX\n"); scanf("%s",postfix); } printf("\nPOSTFIX TO INFIX CONVERSION\n"); //PREFIXtoPOSTFIX(); push(struct stack_element *,int); pop(struct stack_element *,); } //void PREFIXtoPOSTIX(){ //} /*int stackEMPTY(){ if(ptr->top=-1){ printf("STACK UNDERFLOW"); return (-1); } } int stackFULL(struct stack *ptr){ if(ptr->top==MAX-1) { printf("STACK OVERFLOW"); return (-1); } } */ void push(struct stack *ptr,int x,) { if(ptr->top==MAX-1) { printf("STACK OVERFLOW"); } else //if(stackFULL(struct stack *ptr)!=-1){ ptr->top++; ptr->arr[ptr-top]=x; } } int pop(struct stack *ptr){ int x; if(ptr->top=-1){ printf("STACK UNDERFLOW"); return (-1); }// check stack empty function else{ // if(stackEMPTY(struct stack *ptr)!=-1){ x=ptr->arr[ptr->top]; ptr->top--; } return(x); } //void display(struct stack_element *ptr){ //int i; //if(i.ptr
C
#include <stdio.h> #include "getnum.h" int main(){ unsigned a = abs(getint("Inserte un entero positivo: ")); int digit, sum; digit = sum = 0; for (; a != 0; a/=10){ digit = a%10; sum += digit; } printf("La suma de digitos es %d\n", sum); }
C
/* * SPIStringMess.c * * Created: 5/9/2016 5:46:32 PM * Author : Noah */ #define F_CPU 8000000L #define CS PB3 #define LED PB4 #include <avr/io.h> #include <avr/sleep.h> #include <avr/wdt.h> #include <avr/interrupt.h> #include <util/delay.h> #include <string.h> #include <stdbool.h> volatile char filename[4] = ""; volatile bool newFile = false; void init_spi(void); void spi_slave(void); void spi_master(void); static inline void new_spi_slave(){ DDRB &= ~(1 << PB2); USICR |= (1 << USIWM0); USISR = (1 << USIOIF); USIDR = 0; } static inline void new_spi_master(){ DDRB |= (1 << PB2); USICR &= ~(1 << USIWM0); USISR = (1 << USIOIF); USIDR = 0; } static inline void new_init_spi(){ USICR = (1 << USICS1); } int main(void) { cli(); DDRB = 0b111110 & ~(1 << CS); PORTB = 0b101001 | (1 << CS); /* Initialize port: - - H L H L L P */ new_init_spi(); new_spi_master(); set_sleep_mode(SLEEP_MODE_PWR_DOWN); sleep_enable(); PORTB |= (1 << PB4); _delay_ms(200); PORTB &= ~(1 << PB4); _delay_ms(100); sei(); /* Replace with your application code */ while (1) { //while(!newFile) sleep_cpu(); } } ISR(PCINT0_vect){ if(PINB & (1 << CS)){ new_spi_slave(); newFile = true; while(PINB & (1 << CS)) { //wait until CS is low, meaning transmission is done if(USISR & (1 << USIOIF)){ //if USIDR is full const char temp = USIDR; for(uint8_t i=0; i<4; i++){ //copy char into next slot if(filename[i] == '\0'){ filename[i] = temp; filename[i+1] = '\0'; break; } } USIDR = filename[0]; USISR = (1 << USIOIF); } } const char *temp = (const char *)filename; if(strstr("BEE BEE MCBEEFACE (that should do it)", temp)){ PORTB |= (1 << LED); //Woohoo! } newFile = false; new_spi_master(); } }
C
#include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include "./id.c" void die(char *msg, int status) { if(!errno) errno = ENOTRECOVERABLE; perror(msg); exit(status); } void clean_connect(int serverfd, unsigned long clientid) { char ack; char buffer[25]; sprintf(buffer, "I%019lu", clientid); send(serverfd, buffer, 20, 0); recv(serverfd, &ack, 1, 0); } void clean_disconnect(int serverfd) { char ack; send(serverfd, "E", 1, 0); recv(serverfd, &ack, 1, 0); close(serverfd); } void send_line(int serverfd, char *line) { //NOTE line is 0 terminated, send message is not char buffer[1024]; char ack; int plsize = strlen(line) + 1; sprintf(buffer, "L%03d%s", (int) strlen(line), line); send(serverfd, buffer, strlen(line) + 3, 0); if(recv(serverfd, &ack, 1, 0) < 0) die("Did not get ACK", 7); //TODO maybe check value of ack ? } void send_log(int serverfd, unsigned long clientid, char *filename) { char buffer[1024]; FILE *logfile = fopen(filename, "r"); while(fgets(buffer, sizeof(buffer), logfile)) { send_line(serverfd, buffer); sleep(1); } fclose(logfile); } int main(int argc, char *argv[]) { if(argc < 2) die("logfile required", 6); int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) die("Can't start server", 1); struct sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(8109); if(inet_pton(AF_INET, "127.0.0.1", &address.sin_addr) <= 0) die("Can't understand localhost IP", 4); if(connect(sockfd, (struct sockaddr *) &address, sizeof(address)) < 0) die("Can't connect to server", 5); unsigned long clientid = stouid(argv[1]); printf("I am %lu, sending %s\n", clientid, argv[1]); clean_connect(sockfd, clientid); send_log(sockfd, clientid, argv[1]); clean_disconnect(sockfd); return 0; }
C
#include "library.h" /** * takeInput - function to take user input params. * * @keep_prompt: it takes the keep_prompt address from main. * * Return: buffer. */ char *takeInput(int *keep_prompt) { size_t buffer_size = BUFF_MAX; char *buffer = (char *)malloc(buffer_size * sizeof(char)); int char_count; if (buffer == NULL) { perror("Unable to allocate buffer"); exit(1); } char_count = getline(&buffer, &buffer_size, stdin); if (char_count == EOF) { *keep_prompt = 0; write(2, "\n", 1); return (buffer); } if (buffer[char_count - 1] == '\n') { buffer[char_count - 1] = '\0'; --char_count; } if (empty_line(buffer) == 1) { buffer = NULL; } return (buffer); }
C
#include "SSNavierStokesEquations.h" #include "../../../00_CommonFiles/BLAS_Operations/ourBLAS.h" #include <math.h> double eta_newton(double *Fold, double *F, double etaold, int pricek, int it, double talnl, double eta0, ParametersType *Parameters) { double alpha, gamma, beta, etaa, etaaux, eta=0; double delta, delta1, delta2, old, ak, bk, thetak; int caso, neq; caso = Parameters->SolverToleranceCase; neq = Parameters->neq; delta1 = sqrt(ddot(neq, F, F)); delta2 = sqrt(ddot(neq, Fold, Fold)); delta = delta1/delta2; switch(caso){ //case 0: // eta = eta0; // break; case 1: // etapp eta = (eta0 < delta)? eta0: delta*delta; break; case 2: // etaewk alpha = 2.; gamma = 0.9; beta = 0.1; etaa = gamma*pow(delta,alpha); old = gamma*pow(etaold,alpha); if(old < beta){ eta = (eta0 < etaa)? eta0: etaa; }else{ etaaux = (etaa > old)? etaa: old; eta = (eta0 < etaaux)? eta0: etaaux; } break; case 3: // etaewc alpha = (1.+sqrt(5))*0.5; gamma = 1.0; beta = 0.; etaa = gamma*pow(delta,alpha); old = gamma*pow(etaold,alpha); if(old < beta){ eta = (eta0 < etaa)? eta0: etaa; }else{ etaaux = (etaa > old)? etaa: old; eta = (eta0 < etaaux)? eta0: etaaux; }break; case 4: // etaglt ak = log10(delta1) - log10(delta2); bk = log10(pricek); thetak = bk/sqrt(ak*ak + bk*bk); gamma = pow(1./(it+1),1.1)*cos(thetak)*cos(thetak); etaa = gamma*delta; eta = (eta0 < etaa)? eta0: etaa; break; } old = 0.5*talnl/delta1; etaaux = (eta > old)? eta: old; eta = (eta0 < etaaux)? eta0: etaaux; if(caso == 0) eta = eta0; printf("\n Eta: %3.2E, Iteracao Newton: %d, Pricek: %d \n", eta, it+1, pricek); return eta; }
C
/** **************************************************************************************************** * @file lv_port_disp_template.c * @author ԭŶ(ALIENTEK) * @version V1.0 * @date 2020-03-29 * @brief LVGL ʾӿڳʼ * @license Copyright (c) 2020-2032, ӿƼ޹˾ **************************************************************************************************** * @attention * * ʵƽ̨:ԭ Mini Pro H750 * Ƶ:www.yuanzige.com * ̳:www.openedv.com * ˾ַ:www.alientek.com * ַ:openedv.taobao.com * **************************************************************************************************** */ #include "lv_port_disp_template.h" #include "./BSP/LCD/lcd.h" #include "./SYSTEM/sys/sys.h" #include "./MALLOC/malloc.h" #define USE_SRAM 0 /* ʹⲿsramΪ1Ϊ0 */ #if USE_SRAM /* */ #define COLOR_BUF_SIZE (LV_HOR_RES_MAX*LV_VER_RES_MAX) /* ȫĴС */ #define color_buf mymalloc(SRAMEX,COLOR_BUF_SIZE) #else #define COLOR_BUF_SIZE (LV_HOR_RES_MAX*20) /* ûɫڴС */ static lv_color_t color_buf[COLOR_BUF_SIZE];/* ʾ,̬sram */ #endif /* */ static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p); #if LV_USE_GPU static void gpu_blend(lv_color_t * dest, const lv_color_t * src, uint32_t length, lv_opa_t opa); static void gpu_fill(lv_color_t * dest, uint32_t length, lv_color_t color); #endif /** * @brief lvglʾӿڳʼ * @param * @retval */ void lv_port_disp_init(void) { static lv_disp_buf_t disp_buf; /* ʾʼ */ lv_disp_buf_init(&disp_buf, color_buf, NULL,COLOR_BUF_SIZE); /* ʾĬֵʼ */ lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); /* ĻʾС,Ϊ֧ԭӵĶĻ,ö̬ȡķʽ */ /* ʵĿĻ,Բ,ôĬֵlv_conf.hLV_HOR_RES_MAXLV_VER_RES_MAX궨ֵ */ disp_drv.hor_res = lcddev.width; disp_drv.ver_res = lcddev.height; /* עʾص */ disp_drv.flush_cb = disp_flush; /* עʾ */ disp_drv.buffer = &disp_buf; #if LV_USE_GPU /* ѡ,ֻҪʹõGPUʱ,Ҫʵgpu_blendgpu_fillӿ */ /* ʹ͸ȻɫʱҪõgpu_blendӿ */ disp_drv.gpu_blend = gpu_blend; /* һɫһڴʱҪõgpu_fillӿ */ disp_drv.gpu_fill = gpu_fill; #endif /* עʾlvgl */ lv_disp_drv_register(&disp_drv); } /** * @brief ָʾд뵽Ļ,ʹDMAӲں̨ȥ ֮,õlv_disp_flush_ready() * @param disp_drv : ʾ * @param area : ʾ * @param color_p ʾɫ * @retval */ static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p) { /*ָʾд뵽Ļ*/ lcd_color_fill(area->x1,area->y1,area->x2,area->y2,(uint16_t*)color_p); /*õ,֪ͨlvglѾflushing*/ lv_disp_flush_ready(disp_drv); } /* ѡ */ #if LV_USE_GPU /* MCUӲ(GPU)ôʹò͸ڴ ֻڻģʽʹ(LV_VDB_SIZE != 0lv_conf.h)*/ static void gpu_blend(lv_disp_drv_t * disp_drv, lv_color_t * dest, const lv_color_t * src, uint32_t length, lv_opa_t opa) { /* GPUɵʾ */ uint32_t i; for(i = 0; i < length; i++) { dest[i] = lv_color_mix(dest[i], src[i], opa); } } /* MCUӲ(GPU)ôڴɫ ֻڻģʽʹ(LV_VDB_SIZE != 0lv_conf.h)*/ static void gpu_fill_cb(lv_disp_drv_t * disp_drv, lv_color_t * dest_buf, lv_coord_t dest_width, const lv_area_t * fill_area, lv_color_t color); { /* GPUɵʾ */ uint32_t x, y; dest_buf += dest_width * fill_area->y1; /*Go to the first line*/ for(y = fill_area->y1; y < fill_area->y2; y++) { for(x = fill_area->x1; x < fill_area->x2; x++) { dest_buf[x] = color; } dest_buf+=dest_width; /*Go to the next line*/ } } #endif
C
#include <stdlib.h> #include <assert.h> #include <ctype.h> #include "pure.h" path *pc; void (*todo)(void); ast *program; int main() { program = parse(stdin); pc = malloc(sizeof *pc); pc->up = NULL; pc->here = program; todo = &f_raw; while (pc) todo(); output(stdout, program); printf("\n"); release(program); } void output(FILE *f, ast *program) { if (program->is_node) { fputc('`', f); output(f, program->data.t.left); output(f, program->data.t.right); return; } fputc(program->data.c, f); } ast *parse(FILE *f) { char next; while (isspace(next = fgetc(f))) ; switch (next) { case EOF: return NULL; case '`': (void) 0; // Because a label can't be attached to a declaration. ast *left = parse(f); ast *right = parse(f); if (!(left && right)) return NULL; return node(left, right); default: return leaf(next); } } void release(ast *a) { if (--a->count) return; if (a->is_node) { release(a->data.t.left); release(a->data.t.right); } free(a); } ast *node(ast *left, ast *right) { ast *ret = malloc(sizeof *ret); assert(ret); ret->is_node = 1; ret->data.t.left = left; ret->data.t.right = right; ret->count = 1; return ret; } ast *leaf(char c) { ast *ret = malloc(sizeof *ret); assert(ret); ret->is_node = 0; ret->data.c = c; ret->count = 1; return ret; } void f_raw(void) { if (pc->here->is_node) { descend(); return; } switch (pc->here->data.c) { case 's': ascend(); todo = &f_s; return; case 'k': ascend(); todo = &f_k; return; case 'i': ascend(); todo = &f_i; return; default: while (pc) ascend(); return; } } void f_s(void) { ascend(); todo = &f_s1; } void f_s1(void) { ascend(); todo = &f_s2; } void f_s2(void) { ast *left1, *left2, *x, *y, *z; left1 = pc->here->data.t.left; z = pc->here->data.t.right; left2 = left1->data.t.left; y = left1->data.t.right; release(left2->data.t.left); // the 's' x = left2->data.t.right; ++z->count; replace(node(node(x, z), node(y, z))); free(left1); free(left2); todo = &f_raw; } void f_k(void) { ascend(); todo = &f_k1; } void f_k1(void) { ast *left = pc->here->data.t.left; release(pc->here->data.t.right); // ignored parameter release(left->data.t.left); // the 'k' replace(left->data.t.right); free(left); todo = &f_raw; } void f_i(void) { release(pc->here->data.t.left); // the 'i' replace(pc->here->data.t.right); todo = &f_raw; } void ascend(void) { path *to_free = pc; pc = pc->up; free(to_free); } void descend(void) { path *newp = malloc(sizeof *newp); assert(newp); newp->up = pc; newp->here = pc->here->data.t.left; pc = newp; } void replace(ast *a) { free(pc->here); if (pc->up) pc->up->here->data.t.left = a; else program = a; pc->here = a; }
C
// Project 1 // CS 3013 // Jeffrey Huang and Jyalu Wu #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/types.h> #include <getopt.h> #include <pthread.h> #include "multi.h" proc_bg* bg_list = NULL; int bgIndex = 0; int* bg; /* * Parses the given line and splits it into separate strings * whenever it sees a space. * @param line, the given line * @param args, where it stores the split strings */ void parse(char* line, char** args){ const char s[2] = " "; char* token = strtok(line, s); int argc = 0; while(token!=NULL){ args[argc] = strdup(token); argc++; token = strtok(NULL, s); } args[argc] = NULL; } /* * Executes the given command in the given directory. If ccd, * cpwd or cproclist are called, it processes those commands * internally. It also pays attention to which processes should * run in the background (as specified by the user) and has * those processes run in the background while it reads and * executes the next line. * @param command, the given command * @param currentDir_ptr, a pointer to the given directory * @param lineNum, the current line number */ void execute(char* command, char** currentDir_ptr, int lineNum) { struct rusage usage; struct timeval start, end; long int fg_faults[2] = {0,0}; gettimeofday(&start,NULL); char* cmd_dup = strdup(command); // parent variables int childExitStatus; int* childExitStatus_ptr = &childExitStatus; pid_t wait3Return = 0; pid_t wait4Return = 0; pid_t processID = 0; // child pid pid_t* processID_ptr = &processID; printf("Running command: %s\n", command); char *myargs[34]; myargs[33] = NULL; parse(command, myargs); if(strcmp(myargs[0],"ccd")==0){ changeDir(&myargs[1]); *(currentDir_ptr) = myargs[1]; printDir(currentDir_ptr); } else if(strcmp(myargs[0],"cpwd")==0){ printDir(currentDir_ptr); } else if(strcmp(myargs[0],"cproclist")==0){ printBgList(); } else{ changeDir(currentDir_ptr); int rc = fork(); // *processID_ptr = getpid(); // printf("fork process ID for command %s: %d\n", command, *processID_ptr); getrusage(RUSAGE_SELF,&usage); fg_faults[0] = usage.ru_majflt; fg_faults[1] = usage.ru_minflt; proc_bg* new = findProc_Bg_cmd(cmd_dup); if(new!=NULL){ new->sec = start.tv_sec; new->usec = start.tv_usec; } if (rc < 0) { // fork failed; exit fprintf(stderr, "fork failed\n"); exit(1); } else if (rc == 0) { // CHILD // *processID_ptr = getpid(); // printf("Child %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); execvp(myargs[0], myargs); // printf("Child exit %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); } else { // PARENT *processID_ptr = rc; // printf("linenum: %d\n", lineNum); // printf("next bg ine num: %d\n", bg[bgIndex]); if (bg[bgIndex] == lineNum) { // BACKGROUND proc_bg* current = NULL; // printf("Background parent %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); addBgProc(start.tv_sec, start.tv_usec, cmd_dup, *processID_ptr); current = findProc_Bg_pid(wait3Return); if(current!=NULL)printf("Background: ID [%d]: %s\n",current->queue_num,current->cmd); // printBgList(); // proc_bg* new = findProc_Bg_cmd(cmd_dup); // new->start_faults[0] = fg_faults[0]; // new->start_faults[1] = fg_faults[1]; // new->start_time = &start; // new->pid = *processID_ptr; // proc_bg* tmp = findProc_Bg_pid(*processID_ptr); // if(tmp!=NULL)printf("added proc_bg with pid: %d\n", tmp->pid); bgIndex++; // printf("bg index: %d", ) // bgIndex_ptr = &newIndex; while (wait3(childExitStatus_ptr, WNOHANG, &usage) > 0) { // printf("about to print stats\n"); current = findProc_Bg_pid(wait3Return); if(current!=NULL)printStats(0,0,usage.ru_majflt,usage.ru_minflt,current->sec,current->usec); // printf("finished printing stats\n"); } // printf("wait3return is now %d\n", wait3Return); // while (wait3(childExitStatus_ptr, WNOHANG, &usage) == 0) { // printStats(fg_faults[0], fg_faults[1], usage.ru_majflt, usage.ru_minflt,&start); // } // printf("Background parent exit %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); } else { // FOREGROUND // printf("is foreground for command %s, process ID %d\n", command, getpid()); // printf("Foreground parent %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); proc_bg* current = NULL; while(wait4(*processID_ptr, childExitStatus_ptr, 0, &usage) <= 0) { wait3Return = wait3(childExitStatus_ptr, WNOHANG, &usage); // printf("wait 3 return %d, process id %d\n", wait3Return, *processID_ptr); if (wait3Return > 0) { if (wait3Return == *processID_ptr) { // printf("reached if\n"); printStats(0,0,usage.ru_majflt,usage.ru_minflt,start.tv_sec,start.tv_usec); goto FG_FINISHED; } // printf("about to print stats\n"); current = findProc_Bg_pid(wait3Return); if(current!=NULL){ printf("-- Job Complete [%d: %s] --\n", current->queue_num,current->cmd); printf("Process ID: %d\n", current->pid); printStats(0,0,usage.ru_majflt,usage.ru_minflt,current->sec,current->usec); } // printf("finished printing stats\n"); } // printf("stuck in wait4\n"); } printStats(fg_faults[0], fg_faults[1], usage.ru_majflt, usage.ru_minflt,start.tv_sec,start.tv_usec); // printf("foreground done\n"); FG_FINISHED:while ((wait3Return = wait3(childExitStatus_ptr, WNOHANG, &usage)) > 0) { // printf("about to print stats\n"); current = findProc_Bg_pid(wait3Return); if(current!=NULL){ printf("-- Job Complete [%d: %s] --\n", current->queue_num,current->cmd); printf("Process ID: %d\n", current->pid); printStats(0,0,usage.ru_majflt,usage.ru_minflt,current->sec,current->usec); } // printf("finished printing stats\n"); } // printf("Foreground parent exit %s %s\t pid: %d\n", command, myargs[1], *processID_ptr); } // getrusage(RUSAGE_SELF,&usage); // printStats(fg_faults[0], fg_faults[1], usage.ru_majflt, usage.ru_minflt,&start); // printf("lets check bg_list in parent\n"); // printBgList(); } } } /* * Parses through "multi.txt" and executes each line in the * text file. If the directory is changed, it remembers which * directory it was changed to and uses that directory in * future child processes. If a command line is specified by the * user to run in the background, it makes sure that it runs in * the background while other lines are parsed and executed. * @param argc, the number of arguments in the command line * @param argv, the arguments in the command line */ int main(int argc, char *argv[]) { char* file_path = "multi.txt"; char* line; char* line_dup; ssize_t size; size_t n = 0; char arr[LINE_MAX]; char* currentDir = arr; char** currentDir_ptr = &currentDir; // bg_list = (proc_bg*)malloc(sizeof(proc_bg)); // bg_list->next = NULL; // bg_list->prev = NULL; // background variables int i, bgArr[argc-1]; bg = bgArr; // int** bg_ptr = &bg; int lineNum = 1; // get the current working directory getcwd(arr, sizeof(arr)); // parsing background line numbers from command line for(i = 1; i < argc; i++) sscanf(argv[i],"%i",&bg[i-1]); // parsing FILE* file = fopen(file_path,"r"); size = getline(&line,&n,file); while(size >=0){ if(line[size-1]=='\n') line[size-1]='\0'; line_dup = strdup(line); // if (bg[bgIndex] == lineNum) { // BACKGROUND - ADD TO LINKED LIST // addBgProc(0, 0, line_dup, -1); // // printBgList(); // } execute(line, currentDir_ptr, lineNum); // printf("lets check the bg_list\n"); // printBgList(); lineNum++; size = getline(&line,&n,file); } // printBgList(); int* childExitStatus_ptr; struct rusage usage; pid_t wait3Return = wait3(childExitStatus_ptr, WNOHANG, &usage); proc_bg* current = NULL; while (wait3Return >= 0) { // printf("straggling bg processes\n"); // if(wait3Return>0) printf("process with pid %d has finished\n", wait3Return); current = findProc_Bg_pid(wait3Return); if(current!=NULL){ // printf("found bg proc\n"); printf("-- Job Complete [%d: %s] --\n", current->queue_num,current->cmd); printf("Process ID: %d\n", current->pid); printStats(0, 0, usage.ru_majflt, usage.ru_minflt,current->sec, current->usec); } // printf("finished printing stats\n"); wait3Return = wait3(childExitStatus_ptr, WNOHANG, &usage); } // testing bg_list // printf("initial bg_list\n"); // printBgList(); // printf("adding 3 bg tasks\n"); // addBgProc(0,0,NULL,strdup("cmd1"),0); // addBgProc(0,0,NULL,strdup("cmd2"),1); // addBgProc(0,0,NULL,strdup("cmd3"),2); // printf("printing bg_list with 3 proc_bg\n"); // printBgList(); // printf("finding proc_bg with pid 1\n"); // proc_bg* search = findProc_Bg(1); // if(search!=NULL) printf("found proc_bg with pid: %s\n", search->cmd); // printf("removing bg_list proc_bgs\n"); // rmBgProc(0); // printBgList(); // rmBgProc(2); // printBgList(); // rmBgProc(1); // printBgList(); return 0; } /* * Changes the current directory to the given directory for * this current process as well as for any children processes. * Called when "ccd" is parsed. * @param newDir_ptr, a pointer to the new directory */ void changeDir(char** newDir_ptr) { if (chdir(*newDir_ptr) != 0) { perror(("Error changing the directory to %s\n", *newDir_ptr)); } } /* * Prints out the name of the current working directory. * @param currentDir_ptr, a pointer to the current directory */ void printDir(char** currentDir_ptr) { getcwd(*currentDir_ptr, sizeof(*currentDir_ptr)); printf("Current directory: %s\n\n", *currentDir_ptr); } /* * Prints out the statistics of a given child process. */ void printStats(long int start_majflt, long int start_minflt, long int end_majflt, long int end_minflt, time_t start_sec, suseconds_t start_usec){ struct timeval end; gettimeofday(&end, NULL); printf("\n-- Statistics --\n"); printf("Elapsed time: %ld millisecond(s)\n", (end.tv_sec - start_sec)*1000 + (end.tv_usec - start_usec) / 1000); printf("Page Faults: %ld\n", end_majflt-start_majflt); printf("Page Faults (reclaimed): %ld \n", end_minflt-start_minflt); printf("-- End of Statistics --\n\n"); } /* * Prints out a list of the processes that are currently running * in the background. */ void printBgList(){ if(bg_list == NULL){ printf("bg_list points to NULL\n"); return; } printf("-- Background Processes --\n"); proc_bg* current = bg_list; if(bg_list!=NULL){ while(current!=NULL){ printf("[%d] %s\n", current->queue_num, current->cmd); current = current->next; } } printf("\n"); } /* * Adds a background process to the linked list. */ void addBgProc(time_t sec, suseconds_t usec, char* cmd, pid_t pid){ if(bg_list==NULL){ bg_list = (proc_bg*)malloc(sizeof(proc_bg)); bg_list->sec = sec; bg_list->usec = usec; bg_list->cmd = cmd; bg_list->pid = pid; bg_list->queue_num = 0; bg_list->next = NULL; bg_list->prev = NULL; // return bg_list; }else{ proc_bg* current = bg_list; int cnt = 1; while(current->next!=NULL){ cnt++; current = current->next; } // printf("current is currently pointing to: %s\n", current->cmd); proc_bg* new = (proc_bg*)malloc(sizeof(proc_bg)); new->sec = sec; new->usec = usec; new->cmd = cmd; new->pid = pid; new->queue_num = cnt; new->next = NULL; new->prev = current; // printf("the new proc_bg's cmd: %s\n", new->cmd); current->next = new; // printf("current->next's cmd: %s\n",current->next->cmd); // return new; } } /* * Removes the given process from the linked list. */ void rmBgProc(pid_t pid){ if(bg_list==NULL) return; if(bg_list->pid == pid){ proc_bg* tmp = bg_list; printf("found matching pid\n"); if(bg_list->next!=NULL){ printf("head's next: %s\n",bg_list->next->cmd); bg_list->next->prev = NULL; } bg_list = bg_list->next; free(tmp); return; } proc_bg* current = bg_list; while(current!=NULL){ if(current->pid == pid){ printf("found matching pid\n"); if(current->prev!=NULL){ printf("current's prev: %s\n",current->prev->cmd); current->prev->next = current->next; } if(current->next!=NULL){ printf("current's next: %s\n",current->next->cmd); current->next->prev = current->prev; } free(current); return; }else current = current->next; } } /* Finds the given process in the linked list. */ proc_bg* findProc_Bg_pid(pid_t pid){ if(bg_list==NULL) return NULL; proc_bg* current = bg_list; while(current!=NULL){ if(current->pid == pid)return current; else current = current->next; } // printf("couldn't find proc_bg"); return NULL; } /* Finds the given process in the linked list. */ proc_bg* findProc_Bg_cmd(char* cmd){ // printf("looking for cmd in list\n"); if(bg_list==NULL) return NULL; proc_bg* current = bg_list; while(current!=NULL){ // printf("current node's cmd: %s, desired cmd: %s\n", current->cmd, cmd); if(strcmp(current->cmd, cmd)==0)return current; else current = current->next; } // printf("couldn't find proc_bg\n"); return NULL; }
C
/****************************************************************************** Construa um algoritmo que leia dois números e efetue a adição. Caso o valor somado seja maior que 20, este deverá ser apresentado somando e a ele mais 8; caso o valor somado seja menor ou igual a 20, este deverá ser apresentado subtraindo-se 5 *******************************************************************************/ #include <stdio.h> int main() { int num1, num2, menos, mais; printf("digite um numero: "); scanf("%i",&num1); printf("digite outro numero: "); scanf("%i",&num2); if (num1+num2>20){ mais=num1+num2+8; printf("o resultado e: %i",mais); } else if(num1+num2<=20){ menos=num1+num2-5; printf("o resultado e: %i",menos); } return 0; }
C
#include "symbol.h" #include "prime_generator.h" #include <memory.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include <string.h> long long int Hash(char *str) { long long int sum = 0; int current; int i = 0; sum = (int) str[i]; i++; while(str[i] != '\0' && i < MAX_VARIABLE_SIGNIFICANCE) { current = (int) str[i]; sum = sum << 1; sum = sum + current; i++; } return sum; } int hash_index(array_list *hash_table, char *str) { long long int hash = Hash(str); int size = hash_table->size; return hash % size; } symbol_table *init_symbol_table() { symbol_table *tbl = NEW(symbol_table); tbl->hash_table = al_init_list(11, sizeof(void*)); // 11 is prime we choose this to avoid colisions -> good for the report tbl->parent = NULL; tbl->size = 0; al_set_max(tbl->hash_table); return tbl; } symbol_table *scope_symbol_table(symbol_table *table) { symbol_table *new = init_symbol_table(); new->parent = table; return new; } symbol *put_symbol(symbol_table *table, char *name, int value) { int name_hash = hash_index(table->hash_table, name); symbol *ptr; AL_GET(symbol *, ptr, table->hash_table, name_hash); if(ptr == NULL) { symbol* sprt = _sym_init_symbol(name, value); al_set(table->hash_table, name_hash, &sprt); _sym_increment_size(table); return sprt; } while(ptr->next != NULL && strcmp(ptr->name, name) != 0) { ptr = ptr->next; } // ERROR: id already exists; if(strcmp(ptr->name,name) == 0) { fprintf(stderr, "Identifier: %s, already exists.\n", ptr->name); // abort(); TODO make compiler abort later; return NULL; } symbol *sptr = _sym_init_symbol(name, value); ptr->next = sptr; _sym_increment_size(table); return sptr; } void sym_assign(symbol_table *table, char *name, int value) { symbol *ptr = get_symbol(table, name); // TODO: check values match if (ptr != NULL) { ptr->value = value; } } symbol *_sym_init_symbol(char *name, int value) { symbol* sprt = NEW(symbol); sprt->name = name; sprt->next = NULL; sprt->value = value; return sprt; } void _sym_increment_size(symbol_table *table) { table->size += 1; double ratio = table->size / (double)table->hash_table->size; double tolerence = log10(table->hash_table->size); if (ratio >= tolerence) { _sym_resize(table); } } symbol *get_symbol(symbol_table *table, char *name) { while(table != NULL) { int name_hash = hash_index(table->hash_table, name); symbol *ptr; AL_GET(symbol *, ptr, table->hash_table, name_hash); if(ptr != NULL) { while(ptr->next != NULL && strcmp(ptr->name, name) != 0) { ptr = ptr->next; } if(strcmp(ptr->name,name) == 0) { return ptr; } } table = table->parent; } fprintf(stderr, "Identifier: %s, doesn't exist.\n", name); // abort(); TODO make compiler abort later; return NULL; } void _sym_resize(symbol_table *table) { int new_size; new_size = prime_next(table->hash_table->size * SYM_RESIZE_SCALE); array_list *new_list, *old_list; new_list = al_init_list(new_size, sizeof(void *)); al_set_max(new_list); old_list = table->hash_table; table->hash_table = new_list; table->size = 0; symbol *ptr; for (int i = 0; i < old_list->size; i++) { AL_GET(symbol *, ptr, old_list, i); while(ptr != NULL) { put_symbol(table, ptr->name, ptr->value); ptr = ptr->next; } } al_clean(old_list, NULL); } void dump_symbol_table(symbol_table *table) { int table_index = 1; while(table != NULL){ fprintf(stderr, "Table %d\n", table_index); for (int index = 0; index < table->hash_table->size; index++) { symbol *ptr; AL_GET(symbol *, ptr, table->hash_table, index); fprintf(stderr, "%d ", index); if (ptr == NULL) { fprintf(stderr, "NULL\n"); continue; } fprintf(stderr, "(%s, %d)", ptr->name, ptr->value); while(ptr->next != NULL) { ptr = ptr->next; fprintf(stderr, " -> (%s, %d)", ptr->name, ptr->value); } fprintf(stderr, "\n"); } fprintf(stderr, "------------------\n"); fprintf(stderr, "\n"); table = table->parent; table_index++; } // TODO: method for freeing memory }
C
#include <stdio.h> #include <linux/ioctl.h> #include <fcntl.h> #include <errno.h> #include <stdlib.h> #include <sys/mman.h> #include <string.h> #include <linux/ion.h> #include <ion/ion.h> #include <cutils/log.h> //#include "ion_test_module.h" #define TEST_MODULE_NAME "/dev/vion_dev" #define DEFAULT_BUF_SIZE 128 int share_with_testdrv(int shared_fd) { int test_fd; char buff[DEFAULT_BUF_SIZE] = "ion buffer test magic string"; int size = 0; // TEST_MODULE_NAME : vion_dev 를 open test_fd = open(TEST_MODULE_NAME, O_RDWR); if (test_fd < 0) { printf("Failed to open test driver(vion)\n"); perror("fail:"); return 0; } // register ion client in driver with shared file descriptor ioctl(test_fd, 10, &shared_fd); // write a string for confirm. size = write(test_fd, (char*)buff, DEFAULT_BUF_SIZE - 1); if (size > 0) { printf("write \"%s\" string to ion test driver complete\n", buff); } // for sync?? printf("sleep 1sec...\n"); sleep(1); close(test_fd); return size; } int main(int argc, char ** argv) { struct ion_handle *ion_hnd; size_t size = DEFAULT_BUF_SIZE; int ion_fd, shared_fd, test_fd; int ret = 0; int write_size = 0; unsigned char *confirm_vaddr = NULL; // open ion device driver ion_fd = ion_open(); if (ion_fd < 0) { printf("Failed to open ion device driver\n"); ret = ion_fd; goto out; } // allocation ion buffer with ION_HEAP_SYSTEM_CONTIG type. // ion driver 의 physical address 를 얻어오는 interface(ion_phys()) 는 // ION_HEAP_SYSTEM 의 memory type은 지원하지 않음. ret = ion_alloc(ion_fd, size, 0, ION_HEAP_SYSTEM_CONTIG_MASK, ION_FLAG_CACHED | ION_FLAG_CACHED_NEEDS_SYNC, &ion_hnd ); if (ret) { printf("ion_alloc failed\n"); goto close_fd; } // get shared file descriptor ret = ion_share(ion_fd, ion_hnd, &shared_fd); if (ret) { printf("ion_share failed %d\n", ret); goto close_ion; } // open test driver(vion_dev) and write test string. write_size = share_with_testdrv(shared_fd); if (write_size <= 0) { printf("Failed to share with test drv\n"); goto close_ion; } // mmap memory with shared file descriptor. confirm_vaddr = (unsigned char*)mmap( NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shared_fd, 0 ); if (confirm_vaddr != NULL) // check a string which is written in ion test kernel driver. printf("confirm_vaddr is not NULL, confirm data string \"%s\"\n", confirm_vaddr); else printf("mmap failed\n"); if (confirm_vaddr) munmap((void*)confirm_vaddr, size); printf("\nion test application terminated.\n"); close_ion: ion_free(ion_fd, ion_hnd); close_fd: close(ion_fd); out: return ret; }
C
#include <signal.h> #include <stdio.h> #include <unistd.h> int entra; void signalHandler(int sig){ printf("recibi señal %d\n", sig); entra=0; } int main(){ entra=1; signal(2,signalHandler); signal(15,signalHandler); while(entra){ printf("trabajando \n"); sleep(1); } printf("voy a terminar \n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int calculaRand(int *x, int *y) { int valorAleatorio; valorAleatorio = *x + (rand() % (*y - *x)); printf("%d %d %d\n", *x, *y, valorAleatorio); return valorAleatorio; } int main() { int x, y; printf("Digite o valor de x: "); scanf("%d", &x); printf("Digite o valor de y: "); scanf("%d", &y); printf("Numero aleatorio entre %d e %d = %d\n", x, y, (calculaRand(&x, &y))); }
C
#include <stdio.h> #include <stdlib.h> #include <SDL.h> #define NODO_POS_NODO 0 typedef struct inputs{ SDL_Rect insertar, borrar, buscar; int edo_insertar, edo_borrar, edo_buscar; int w,h,y; }Inputs; SDL_Surface *image_nodos, *screen, *img_bg; SDL_Rect nodo_rectBlitOrg, nodo_rectBlitDest, rect_screen; Inputs inputs; /* prototipo de funciones */ void die(char *s); void show_nodo_element(); void paintBackground(); void mostrar_nodo(int valor, int pos_x); void mostrar_apuntador(int pos_x); void mostrar_null(int pos_x); /* * Carga los graficos a utilizar durante el trascurso de la ejecución * */ void cargar_img_nodos(){ // Cargamos gráfico image_nodos = IMG_Load("img/nodos.png"); if ( image_nodos == NULL ) die("No pude cargar gráfico: img/nodos.png\n"); //imag de fondo img_bg = IMG_Load("img/fondo.png"); if ( img_bg == NULL ) die("No pude cargar gráfico: img/fondo.png\n"); //rectangulo que describe el fondo rect_screen.w = SCREEN_W; rect_screen.h = SCREEN_H; rect_screen.x = 0; rect_screen.y = 0; //iniciamos 2 rectangulos los cuales usaremos en los flits //el rect para el bit blitting del origen nodo_rectBlitOrg.w = 50; nodo_rectBlitOrg.h = 50; nodo_rectBlitOrg.y = 0; //el rect para el bit blitting del destino nodo_rectBlitDest.w = 50; nodo_rectBlitDest.h = 50; nodo_rectBlitDest.y = 200; //posiciones y estados iniciales de los inputs } void die(char *s){ printf("%s\n",s); exit(1); } /* SDL_Rect rect_setear(int w, int h, int x,int y){ SDL_Rect rect; rect.x = w; rect.y = h; rect.y = y; rect.y = y; return rect; } * */ void show_nodo_element(){ SDL_BlitSurface(image_nodos, &nodo_rectBlitOrg, screen, &nodo_rectBlitDest); } void paintBackground(){ SDL_Rect rect_aux; SDL_BlitSurface(img_bg, &rect_screen, screen, &rect_screen); rect_aux.x = 100; rect_aux.y = 445; rect_aux.h = 20; rect_aux.w = 80; SDL_FillRect(screen, &rect_aux, SDL_MapRGB(screen->format,200,200,200)); rect_aux.x += 200; SDL_FillRect(screen, &rect_aux, SDL_MapRGB(screen->format,200,200,200)); rect_aux.x += 200; SDL_FillRect(screen, &rect_aux, SDL_MapRGB(screen->format,200,200,200)); } void mostrar_nodo(int valor, int pos_x){ nodo_rectBlitOrg.x = 0; nodo_rectBlitDest.x = pos_x; show_nodo_element(); } void mostrar_apuntador(int pos_x){ nodo_rectBlitOrg.x = 50; nodo_rectBlitDest.x = pos_x; show_nodo_element(); } void mostrar_null(int pos_x){ nodo_rectBlitOrg.x = 100; nodo_rectBlitDest.x = pos_x; show_nodo_element(); }
C
//Exercício 1589 #include<stdio.h> int main(){ int vezes, r1, r2, cont = 0, resp =0; scanf("%d", &vezes); while(cont < vezes){ scanf("%d%d", &r1, &r2); resp = r1 + r2; printf("%d\n", resp); cont++; } return 0; }
C
// vga.c // Written by Harry Rigg // A VGA driver. Currently only supports text, but will support graphics in the future. #include <kernel/drivers/video/vga.h> // Scrolls the screen if the cursor has exceed the screen size void scroll_screen() { uint32_t blank,tmp; blank=0x20|(style<<8); if(crs_y >= 25) { tmp=crs_y-25+1; memcpy(text_ptr, text_ptr+tmp*80, (25-tmp)*80*2); memsetw(text_ptr+(25-tmp)*80, blank, 80); crs_y=25-1; } } // Updates hardware cursor position void update_hw_cursor() { uint32_t tmp; tmp = crs_y * 80 + crs_x; outb(0x3D4, 14); outb(0x3D5, tmp >>8); outb(0x3D4, 15); outb(0x3D5, tmp); } // Clears the screen void clear_screen() { uint32_t blank; uint32_t i; blank = 0x20| (style << 8); for(i=0;i<25;i++) memsetw(text_ptr+i*80, blank, 80); crs_x=0; crs_y=0; update_hw_cursor(); } // Prints a char void vga_putch(uint8_t c) { uint16_t *loc; uint32_t att=style<<8; if(c == 0x08) { if(crs_x !=0) crs_x--; }else if(c == 0x09) { crs_x=(crs_x + 8)&-(8-1); }else if(c == '\r') { crs_x=0; }else if(c == '\n') { crs_x=0; crs_y++; }else if(c >= ' ') { loc=text_ptr + (crs_y * 80 + crs_x); *loc=c | att; crs_x++; } if(crs_x >= 80) { crs_x = 0; crs_y++; } scroll_screen(); update_hw_cursor(); } // Prints a string void vga_print(char* text) { uint32_t i; for(i=0;i<strlen(text);i++) vga_putch(text[i]); } // Sets text and and background color void vga_color(uint8_t text, uint8_t back) { style=(back<<4)|(text&0x0f); } // Sets the cursor position void vga_crs(int x, int y) { crs_x = x; crs_y = y; update_hw_cursor(); } // Initiates VGA driver void vga_init() { style = 0x0F; crs_x=0; crs_y=0; text_ptr=(uint16_t*)0xB8000; clear_screen(); }
C
#include "packet.h" void die(char *message) { perror(message); exit(1); } void PrintPacket(Packet* pack) { fprintf(ClientLogs, "*******************************\n"); fprintf(ClientLogs, "PAYLOAD : %s\n", pack->payload); fprintf(ClientLogs, "SIZE : %d\n", pack->payloadsize); fprintf(ClientLogs, "SEQUENCE NUMBER : %d\n", pack->SeqNo); fprintf(ClientLogs, "LAST PACKET : %s\n", pack->lastPacket==0?"NO":"YES"); fprintf(ClientLogs, "DATA/ACK: %s\n", pack->DATA_ACK==0?"DATA":"ACK"); fprintf(ClientLogs, "RELAY NODE : %d\n", pack->RelayNode); fprintf(ClientLogs, "*******************************\n\n\n"); return; } char* GetCurrentTime() { char *tim = (char *)malloc(sizeof(char)*20); int rc; time_t curr; struct tm* timeptr; struct timeval tv; curr = time(NULL); timeptr = localtime(&curr); gettimeofday(&tv, NULL); rc = strftime(tim, 20, "%H:%M:%S", timeptr); char ms[8]; sprintf(ms, ".%06ld", tv.tv_usec); strcat(tim, ms); return tim; } void FilePrint(char *format, ...) { MainLog = fopen("Logs.txt", "a+"); va_list ap; va_start(ap, format); int over = vfprintf(MainLog, format, ap); va_end(ap); fclose(MainLog); } void PrintLog(char *Event, Packet* pkt, char* source, char* dest) { printf("CLIENT\t\t%s\t%s\t\t%s\t\t%d\t\t%s\t\t%s\n", Event, GetCurrentTime(), pkt->DATA_ACK==0?"DATA":"ACK", pkt->SeqNo, source, dest); FilePrint(" CLIENT\t\t\t%s\t\t\t%s\t\t\t%s\t\t\t%d\t\t\t%s\t\t\t%s\n", Event, GetCurrentTime(), pkt->DATA_ACK==0?"DATA":"ACK", pkt->SeqNo, source, dest); } int NoofChars(char *filename) { FILE *fp = fopen(filename, "r"); if(fp==NULL) die("ERROR : Reading from file input.txt\n"); char c; int count = 0; while((c=fgetc(fp))!=EOF) count++; return count; } void CreateTimers() { struct sigevent events[WINDOW_SIZE]; for(int i=0; i<WINDOW_SIZE; i++) { timer[i] = (timer_t*)malloc(sizeof(timer_t)); events[i].sigev_notify = SIGEV_SIGNAL; events[i].sigev_signo = SIGALRM; events[i].sigev_value.sival_ptr = timer[i]; timer_create(CLOCK_REALTIME, &events[i], timer[i]); timerValue[i].it_interval.tv_sec = 0; timerValue[i].it_interval.tv_nsec = 0; timerValue[i].it_value.tv_sec = RETRANSMIT_TIME; timerValue[i].it_value.tv_nsec = 0; } return; } Packet* ConstructPacket(FILE* fp, Packet* pack) { int bytesRead = fread(pack->payload, 1, PACKET_SIZE, fp); if(bytesRead == PACKET_SIZE) { pack->payloadsize = PACKET_SIZE; pack->SeqNo = Sequence; pack->lastPacket = 0; pack->DATA_ACK = 0; pack->RelayNode = Sequence % 2; pack->FileOffset = Sequence*PACKET_SIZE; } else { if(!feof(fp)) die("ERROR : Reading from file input.txt\n"); else { pack->payloadsize = bytesRead; pack->SeqNo = Sequence; pack->lastPacket = 1; pack->DATA_ACK = 0; pack->RelayNode = Sequence % 2; pack->FileOffset = Sequence*PACKET_SIZE; } } Sequence++; return pack; } static void SignalHandler(int signal, siginfo_t *siginfo, void *uc) { timer_t *temptime; temptime = siginfo->si_value.sival_ptr; struct sockaddr_in DestinAddr; DestinAddr.sin_family = AF_INET; inet_aton("127.0.0.1", &DestinAddr.sin_addr); int i; for(i=0; i<WINDOW_SIZE; i++) { if(*temptime == *timer[i]) { fprintf(ClientLogs, "Resending Packet...\n"); printf(RED); if(UnAcked[i]->RelayNode==0) { PrintLog("TO", UnAcked[i], "CLIENT", "RELAY1"); DestinAddr.sin_port = htons(RELAY0_PORT); printf(YELLOW); PrintLog("RE", UnAcked[i], "CLIENT", "RELAY1"); } else { PrintLog("TO", UnAcked[i], "CLIENT", "RELAY2"); DestinAddr.sin_port = htons(RELAY1_PORT); printf(YELLOW); PrintLog("RE", UnAcked[i], "CLIENT", "RELAY2"); } printf(RESET); int tempResend = sendto(clientSocket, UnAcked[i], sizeof(Packet), MSG_CONFIRM, (struct sockaddr *) &DestinAddr, sizeof(DestinAddr)); if(tempResend < 0) die("Couldn't Resend Packet\n"); if(timer_settime(*timer[i], 0, &timerValue[i], NULL) == -1) die("ERROR : Resetting Timer\n"); PrintPacket(UnAcked[i]); break; } } if(i==WINDOW_SIZE) die("ERROR : Timer Malfunctioned\n"); return; } int main() { clientSocket = socket(AF_INET, SOCK_DGRAM, 0); if(clientSocket < 0) die("ERROR : Couldn't Connect to Socket\n"); struct sockaddr_in clientAddr, receiverAddr; memset(&clientAddr, 0, sizeof(clientAddr)); memset(&receiverAddr, 0, sizeof(receiverAddr)); receiverAddr.sin_family = AF_INET; inet_aton("127.0.0.1", &receiverAddr.sin_addr); clientAddr.sin_family = AF_INET; clientAddr.sin_port = htons(CLIENT_PORT); clientAddr.sin_addr.s_addr = INADDR_ANY; if(bind(clientSocket, (struct sockaddr *) &clientAddr, sizeof(clientAddr)) < 0) die("ERROR : Binding Client\n"); int AddrLen = sizeof(receiverAddr), recvStat; ClientLogs = fopen("ClientLogs.txt", "w"); if(ClientLogs == NULL) die("ERROR : Opening file logs\n"); FILE* fp = fopen("input.txt", "r"); if(fp == NULL) die("ERROR : Opening file input.txt\n"); Sequence = 0; int filesize = NoofChars("input.txt"); FilePkts = ceil((double)(filesize)/(PACKET_SIZE)); Packet *RecvPacket = (Packet *)malloc(sizeof(Packet)), *SentPacket = (Packet *)malloc(sizeof(Packet)); for(int i=0 ; i<WINDOW_SIZE ; i++) UnAcked[i] = (Packet *)(malloc(sizeof(Packet))); CreateTimers(); struct sigaction signalAction; signalAction.sa_sigaction = SignalHandler; signalAction.sa_flags = SA_SIGINFO; sigemptyset(&signalAction.sa_mask); if(sigaction(SIGALRM, &signalAction, NULL) == -1) die("ERROR : Couldn't Create Signal Handler\n"); for(int i=0; i<((FilePkts<=WINDOW_SIZE)?FilePkts:WINDOW_SIZE); i++) { UnAcked[i] = ConstructPacket(fp, UnAcked[i]); if(UnAcked[i]->RelayNode == 0) receiverAddr.sin_port = htons(RELAY0_PORT); else receiverAddr.sin_port = htons(RELAY1_PORT); fprintf(ClientLogs, "Sending Packet...\n"); if(sendto(clientSocket, UnAcked[i], sizeof(Packet), MSG_CONFIRM, (struct sockaddr *) &receiverAddr, AddrLen) == -1) die("ERROR : Sending Packets to Relay Node\n"); if(timer_settime(*timer[i], 0, &timerValue[i], NULL) == -1) die("ERROR : Resetting Timer...\n"); printf(BLUE); if(UnAcked[i]->RelayNode==0) PrintLog("S", UnAcked[i], "CLIENT", "RELAY1"); else PrintLog("S", UnAcked[i], "CLIENT", "RELAY2"); printf(RESET); PrintPacket(UnAcked[i]); } int AckIndex; bool AckedPackets[FilePkts], AllPacketsAcked = 0; memset(&AckedPackets, 0, FilePkts); while(1) { recvStat = recvfrom(clientSocket, RecvPacket, sizeof(Packet), MSG_WAITALL, (struct sockaddr *) &receiverAddr, &AddrLen); if(recvStat == 0) die("ERROR : Receiving Packet from Relay\n"); if(recvStat == -1) continue; AckedPackets[RecvPacket->SeqNo] = 1; for(AckIndex=0; AckIndex<FilePkts; AckIndex++) if(AckedPackets[AckIndex]==0) break; if(AckIndex==FilePkts) AllPacketsAcked = 1; else AllPacketsAcked = 0; printf(GREEN); if(RecvPacket->RelayNode==0) PrintLog("R", RecvPacket, "RELAY1", "CLIENT"); else PrintLog("R", RecvPacket, "RELAY2", "CLIENT"); printf(RESET); fprintf(ClientLogs, "Recieved Packet...\n"); PrintPacket(RecvPacket); if(AllPacketsAcked==1) die("File Sent to Server Successfully\n"); if(Sequence < FilePkts) { for(int i=0 ; i<WINDOW_SIZE; i++) { if(UnAcked[i]!= NULL && UnAcked[i]->SeqNo == RecvPacket->SeqNo) { UnAcked[i] = ConstructPacket(fp, UnAcked[i]); if(UnAcked[i]->RelayNode == 0) receiverAddr.sin_port = htons(RELAY0_PORT); else receiverAddr.sin_port = htons(RELAY1_PORT); fprintf(ClientLogs, "Sending Packet...\n"); if(sendto(clientSocket, UnAcked[i], sizeof(Packet), MSG_CONFIRM, (struct sockaddr *) &receiverAddr, AddrLen) == -1) die("ERROR : Sending Packets to Relay Node\n"); if(timer_settime(*timer[i], 0, &timerValue[i], NULL) == -1) die("ERROR : Resetting Timer\n"); printf(BLUE); if(UnAcked[i]->RelayNode==0) PrintLog("S", UnAcked[i], "CLIENT", "RELAY1"); else PrintLog("S", UnAcked[i], "CLIENT", "RELAY2"); printf(RESET); PrintPacket(UnAcked[i]); } } } } close(clientSocket); fclose(ClientLogs); fclose(fp); return 0; }
C
#include "holberton.h" /** *_memset-fills memory with constant byte *@s: pointer to the destination memory *@b: value of byte to be filled *@n: number of bytes to be filled starting from s * *Return: value of s */ char *_memset(char *s, char b, unsigned int n) { unsigned int i; for (i = 0; i < n; i++) *(s + i) = b; return (s); }
C
/* ************************************ */ /* */ /* vc_strrev.c */ /* */ /* By: Natsumi, Kenta, Juan */ /* */ /* ************************************ */ #include <stdio.h> char *vc_strrev (char *str) { char rstr[100]; int first; int last; int count = 0; while (str[count] != '\0') count++; last = count - 1; for (first = 0; first < count; first++) { rstr[first] = str[last]; last--; } rstr[first] = '\0'; return rstr; }
C
// // Created by Thalles Batista on 11/09/16. // #include <stdlib.h> #include <stdio.h> #include "headers/graph.h" void checkGrapValid(Grafo grafo) { if (grafo == NULL) { printf("\n**** ERROR ****"); printf("\n**** VOCÊ ESTÁ TENTANDO MANIPULAR UM GRAFO INVÁLIDO(NULO) ****"); exit(0); } } void checkPosValidVertices(Grafo g, int x1, int x2) { if (x1 >= MAX || x2 >= MAX) { printf("\n**** ERROR ****"); printf("\nVocê tentou acessar uma aresta inexistente!!!"); printf("\nO NÚMERO LIMITE DE ARESTAS É %i", MAX); exit(0); } if (x1 > g->numElem || x2 > g->numElem) { printf("\n**** ATENÇÃO ****"); printf("\nVocê está manipulando arestas cujo os vertices ainda não existem"); } } Grafo inicGrafo() { Grafo graph = (Grafo) malloc(sizeof(TGrafo)); graph->vertices = (Vertice *) calloc(MAX, (sizeof(Vertice))); graph->arcos = (int **) calloc(MAX, sizeof(int *)); graph->numElem = 0; int i, j; for (i = 0; i < MAX; i++) { graph->arcos[i] = (int *) calloc(MAX, sizeof(int *)); for (j = 0; j < MAX; j++) { graph->arcos[i][j] = -1; } } return graph; } void insGrafo(Grafo g, TipoG elem) { checkGrapValid(g); if (g->numElem == MAX) { printf("\n\n\tTODAS AS %i POSIÇÕES JÁ FORAM PREENCHIDAS **** \n\tNão é possível adicionar novos vertices", MAX); return; } g->vertices[g->numElem++] = (Vertice) {.info = elem, .marca = 0}; } void insArco(Grafo g, int x1, int x2, int c) { checkGrapValid(g); checkPosValidVertices(g, x1, x2); g->arcos[x1][x2] = c; } void elimArco(Grafo g, int x1, int x2) { checkGrapValid(g); checkPosValidVertices(g, x1, x2); g->arcos[x1][x2] = -1; } int custoArco(Grafo g, int x1, int x2) { checkPosValidVertices(g, x1, x2); return g->arcos[x1][x2]; } Node sucessores(Grafo g, int v) { Node root = inicNode(); for (int i = 0; i < MAX; i++) { int valArc = g->arcos[v][i]; if (valArc != -1) { anxLista(root, i); } } if (root->info == -1) { return NULL; } return root; } TipoG infoVertice(Grafo g, int v) { checkGrapValid(g); if (v >= g->numElem) { printf("\n**** ATENÇÃO **** "); printf("\nVOCÊ ESTÁ BUSCANDO POR UMA INFORMAÇÃO ASSOCIADA DE UM VERTICE QUE AINDA NÃO EXISTE POR ISSO SEU VALOR SERÁ NULO"); } return g->vertices[v].info; } int ordemGrafo(Grafo g) { checkGrapValid(g); return g->numElem; } void destruirGrafo(Grafo g) { if (g == NULL) { return; } free(g); } void salvarGrafo(Grafo g, FILE *fp) { fprintf(fp, "%i\n", ordemGrafo(g)); for (int i = 0; i < MAX; i++) { fprintf(fp, "%s\n", infoVertice(g, i)); } for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) { int custo = custoArco(g, i, j); if (custo != -1) { fprintf(fp, "%i\t%i\t%i\n", i, j, custo); } } } fprintf(fp, "-1\t-1\t-1"); fclose(fp); } Grafo carregarGrafo(FILE *fp) { Grafo grafo = inicGrafo(); char *elem; int x1, x2, custo, size; char *nameFile = "data/output_graph.txt"; fp = fopen(nameFile, "r"); fscanf(fp, "%i\n", &size); for (int i = 0; i < size; i++) { fscanf(fp, "%s", &elem); insGrafo(grafo, elem); } grafo->numElem = size; while ((fscanf(fp, "%i\t%i\t%i\n", &x1, &x2, &custo)) != EOF) { if (x1 != -1 && x2 != -1 && custo != -1) { insArco(grafo, x1, x2, custo); } } fclose(fp); return grafo; } void marcarVertice(Grafo g, int v) { g->vertices[v].marca = 1; } void desmarcarVertice(Grafo g, int v) { g->vertices[v].marca = 0; } void desmarcarGrafo(Grafo g) { for (int i = 0; i < MAX; i++) { desmarcarVertice(g, i); } } int marcadoVertice(Grafo g, int v) { return g->vertices[v].marca == 1; } int existeCiclo(Grafo g, int x1) { return existeCaminho(g, x1, x1); } int existeCaminho(Grafo g, int x1, int x2) { if (g->arcos[x1][x2] != -1) { return 1; } marcarVertice(g, x1); Node root = sucessores(g, x1); while (root != NULL) { if (marcadoVertice(g, root->info) == 0 && existeCaminho(g, root->info, x2) == 1) { desmarcarGrafo(g); return 1; } root = root->prox; } desmarcarVertice(g, x1); return 0; } void exibeCaminhos(Grafo g, int x1, int x2) { Node root = sucessores(g, x1); if (existeCaminho(g, x1, x2) == 0) { return; } printf("%i,", x1); while (root != NULL) { if (existeCaminho(g, root->info, x2) == 1) { exibeCaminhos(g, root->info, x2); } if (root->info == x2) { printf("%i;\n", root->info); return; } root = root->prox; } }
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(int argc, string argv[]) { string fir = argv[1]; string sec = argv[2]; if (argc == 3) { printf("Usage: enter key\n"); // Alert user if key is not entered properly return 1; if () { } } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #include <pthread.h> #define RUN_TIME 5 #define MAX_SIZE 64 #define MAX_THREADS 8 #define MAX_PRODUCERS 3 typedef struct t_par { int id; int flag; } TPAR; /* Shared buffer */ int shared_buf[MAX_SIZE]; int n = 0; int n_transactions = 0; int max_buf = 0; long acc_buf = 0; int prod_wait = 0; int cons_wait = 0; pthread_mutex_t mutex; void *producer (void *arg) { TPAR *par = (TPAR*)arg; int id = par->id; while (!par->flag) { pthread_mutex_lock (&mutex); // Lock the resource while (n == MAX_SIZE - 1) { prod_wait++; pthread_mutex_unlock (&mutex); usleep (0); if (par->flag) return 0; pthread_mutex_lock (&mutex); } shared_buf[n] = rand () % 100; printf ("\033[32m Producer %d : %d (%d items)\033[m\n", id, shared_buf[n], n+1); //usleep (10000); n++; if (n > max_buf) max_buf = n; acc_buf += n; pthread_mutex_unlock (&mutex); usleep (100); } //printf ("** Producer %d terminated\n", id); } void *consumer (void *arg) { TPAR *par = (TPAR*)arg; int id = par->id; while (!par->flag) { pthread_mutex_lock (&mutex); while (n == 0) { cons_wait++; pthread_mutex_unlock (&mutex); usleep (0); if (par->flag) return 0; pthread_mutex_lock (&mutex); } n_transactions ++; n--; //usleep (10000); printf ("\033[31m Consumer %d : %d (%d items-%d)\033[m\n", id, shared_buf[n], n, n_transactions); pthread_mutex_unlock (&mutex); usleep (100); } //printf ("** Consumer %d terminated\n", id); } int main () { pthread_t tid[MAX_THREADS]; TPAR tpar[MAX_THREADS] = {0}; int i; srand (time(NULL)); /* Initialise synchronisation objects*/ pthread_mutex_init (&mutex, NULL); /* Launch threads */ for (i = 0; i < MAX_THREADS; tpar[i++].id=i) pthread_create (&tid[i], NULL, (i > MAX_PRODUCERS - 1? consumer : producer), (void*)&tpar[i]); sleep (RUN_TIME); for (i = 0; i < MAX_THREADS; i++ ) tpar[i].flag= 1; for (i = 0; i < MAX_THREADS; i++ ) pthread_join(tid[i], NULL); printf ("WAIT: Prod: %d || Cons: %d\n", prod_wait, cons_wait); printf ("Buffer size: %d (%d-%ld)|| %d Producers || %d Consumers\n", MAX_SIZE, max_buf, acc_buf/n_transactions, MAX_PRODUCERS, MAX_THREADS-MAX_PRODUCERS); printf ("%d transactions processed\n", n_transactions); /* We will never reach this part*/ return 0; }
C
/* memoryCalloc.c */ #include "memory_types.h" void *memoryCalloc( SceSize nelem, SceSize size ) { void *memblock; /* ǂ炩0̏ꍇA1oCgm */ if( nelem == 0 || size == 0 ){ nelem = 1; size = 1; } /* TCY`FbN nelem * sizeSceSize^̍ől𒴂(I[o[t[)ꍇA ̎͋UƂȂNULLԂB */ if( ( nelem * size ) / size != nelem ) return NULL; memblock = memoryAlloc( nelem * size ); if( memblock ) memset( memblock, 0, nelem * size ); return memblock; }
C
//numberSquare //Language/Type: C++ parameters for % //Author: Marty Stepp (on 2016/08/27) //Write a function named numberSquare that accepts two integer parameters, a min and a max, and prints the numbers in the range from min to max inclusive in a square pattern. Each line of the square consists of a wrapping sequence of integers increasing from min and max. The first line begins with min, the second line begins with min + 1, and so on. When the sequence in any line reaches max, it wraps around back to min. You may assume that min is less than or equal to max. For example, the call of numberSquare(1, 5); should print: //12345 //23451 //34512 //45123 //51234 //Solution: //Shift Left void numberSquare(int min, int max) { int col = max-min; int ix; int iy; for (int i=min; i<max+1; i++) { for (int ix=min;ix<min+col+1;ix++) { cout << ix-min+i; } for (int iy=min+col; iy<max; iy++) { cout << iy-max+i; } cout << '\n'; col--; } }
C
#include "NetTools.h" char* RawMacToCStrMac(struct Raw_Mac* In_Raw_Mac) { char* ret = malloc(sizeof(unsigned char) * 18); sprintf(ret, "%x-%x-%x-%x-%x-%x", In_Raw_Mac->un[0], In_Raw_Mac->un[1], In_Raw_Mac->un[2], In_Raw_Mac->un[3], In_Raw_Mac->un[4], In_Raw_Mac->un[5]); return ret; } struct Raw_Mac CStrMacToRawMac(char* In_Str_Mac) { struct Raw_Mac ret; memset(ret.un, '\0', 6); int ndelim = 0; /*if (In_len < 16) return; if (In_len > 18) return; */ const char* pchr=In_Str_Mac; int flag = 0; unsigned char cur = 0; for(pchr;*pchr!='\0';pchr++) { if (*pchr == '-') { if (ndelim > 6) { return; } ret.un[ndelim] = cur; ndelim++; cur=0; flag = 0; }else if (*pchr <= '9' && *pchr >= '0') { if (flag==0) { cur += *pchr - '0'; flag = 1; }else{ cur = cur << 4; cur += *pchr - '0'; flag = 0; } }else if (*pchr <= 'F' && *pchr >= 'A') { if (flag == 0) { cur += *pchr - 'A' + 10; flag = 1; }else{ cur = cur << 4; cur += *pchr - 'A'+10; flag = 0; } }else if (*pchr <="f" && *pchr>='a'){ if (flag == 0) { cur += *pchr - 'a' + 10; flag = 1; }else{ cur = cur << 4; cur += *pchr - 'a' + 10; flag = 0; } } else { //printf("无法解析的字符"); return; } } ret.un[ndelim] = cur; return ret; } int EndianConvert(void* _In_Un,size_t Size) { unsigned char tmp; unsigned char *Un = _In_Un; int i = 0; int j = Size - 1; while (i != j && i<=j) { tmp = Un[i]; Un[i] = Un[j]; Un[j] = tmp; i++; j--; } return 0; } unsigned long CalcBroadAddr(unsigned long Raw_IP, unsigned long Raw_Mask) { unsigned char *un_Ip = (unsigned char *)&Raw_IP; unsigned char *un_Mask = (unsigned char *)&Raw_Mask; unsigned long BroadAddr=0; unsigned char *un_BA = (unsigned char *)&BroadAddr; for (int i = 0; i < sizeof(unsigned long); i++) { un_BA[i] = un_Ip[i] & un_Mask[i]; un_BA[i] = un_Ip[i] | (~un_Mask[i]); } return BroadAddr; } unsigned long CalcNetAddr(unsigned long Raw_IP, unsigned long Raw_Mask) { unsigned char *un_Ip = (unsigned char *)&Raw_IP; unsigned char *un_Mask = (unsigned char *)&Raw_Mask; unsigned long NetAddr = 0; unsigned char *un_NA = (unsigned char *)&NetAddr; for (int i = 0; i < sizeof(unsigned long); i++) { un_NA[i] = un_Ip[i] & un_Mask[i]; } return NetAddr; } char* RawIPToCStr(unsigned long Raw_IP) { unsigned char *un_Ip = (unsigned char *)&Raw_IP; char* pIPStr = malloc(16 * sizeof(char)); memset(pIPStr, '\0', 16); sprintf(pIPStr, "%u\.%u\.%u\.%u", un_Ip[0], un_Ip[1], un_Ip[2], un_Ip[3]); return pIPStr; } unsigned long Raw_IP_Pool(unsigned char* Ip_Addr, unsigned char* Mask, int IsInit) { u_char un[4]; static unsigned long retIP=0; unsigned long raw_BA=0; unsigned long raw_NA=0; static unsigned long raw_High_IP = 0; static unsigned long raw_Low_IP = 0; unsigned char * un_IP = (unsigned char *)&retIP; if (IsInit==0) { unsigned long raw_Ip = inet_addr(Ip_Addr); unsigned long raw_Mask = inet_addr(Mask); raw_BA = CalcBroadAddr(raw_Ip, raw_Mask); raw_NA = CalcNetAddr(raw_Ip, raw_Mask); raw_High_IP = raw_BA; raw_Low_IP = raw_NA; retIP = raw_Low_IP; EndianConvert(&raw_High_IP, sizeof(unsigned long)); EndianConvert(&raw_Low_IP, sizeof(unsigned long)); return retIP; }else{ EndianConvert(&retIP, sizeof(unsigned long)); retIP++; if (retIP >= raw_High_IP || retIP <= raw_Low_IP) { goto MyERROR; } EndianConvert(&retIP, sizeof(unsigned long)); return retIP; } MyERROR: return 0; } //struct RawIP_Iter Create_IPIter(char* CStr_IP, char* CStr_Mask) //{ // u_long ip = inet_addr(CStr_IP); // u_long mask = inet_addr(CStr_Mask); // struct RawIP_Iter iter; // iter._raw_High_IP = CalcBroadAddr(ip, mask); // EndianConvert(&(iter._raw_High_IP), sizeof(iter._raw_High_IP)); // iter._raw_Low_IP = CalcNetAddr(ip, mask); // EndianConvert(&(iter._raw_Low_IP), sizeof(iter._raw_Low_IP)); // iter._raw_Cur_IP = iter._raw_Low_IP; // iter.Index = 0; // iter.State = 0; // iter.Size = 1; // for (int i = 0; i < 32; i++) // { // int chk = mask&(1 << i); // if (chk == 0) // { // iter.Size = iter.Size << 1; // } // } // iter.Size -= 2; // return iter; //} //u_long NextRawIP(struct RawIP_Iter* Iter) //{ // u_long low = Iter->_raw_Low_IP; // u_long high = Iter->_raw_High_IP; // u_long *cur = &(Iter->_raw_Cur_IP); // u_long ret = NULL; // (*cur)++; // if (*cur >= high || *cur < low) // { // Iter->State = 1; // return NULL; // } // Iter->Index++; // ret = *cur; // EndianConvert(&ret, sizeof(ret)); // return ret; //} void* LineSearch(const void* Key, const void* Base, size_t NumOfElements, size_t SizeofElements, int(*PtFuncCompare)(const void*, const void*)) { for (int i = 0; i < NumOfElements; i++) { char* cur = (const char*)Base + i*SizeofElements; if (PtFuncCompare(Key, cur) == 0) { return cur; } } return NULL; } #ifdef TEST int main() { struct Raw_Mac raw_mac=StrMacToRawMac("1-1-1-1-1-1"); //printf("%x-%x-%x-%x-%x-%x\n", raw_mac.un[0], raw_mac.un[1], raw_mac.un[2], raw_mac.un[3], raw_mac.un[4], raw_mac.un[5]); printf("%s\n", RawMacToCStrMac(&raw_mac)); raw_mac = StrMacToRawMac("84-C9-B2-29-54-C0"); //printf("%x-%x-%x-%x-%x-%x\n", raw_mac.un[0], raw_mac.un[1], raw_mac.un[2], raw_mac.un[3], raw_mac.un[4], raw_mac.un[5]); printf("%s\n", RawMacToCStrMac(&raw_mac)); u_long dst_addr = inet_addr("10.10.10.123"); u_long mask_addr = inet_addr("255.255.240.0"); char* Ip_Str = RawIPToCStr(dst_addr); printf("%s\n", Ip_Str); u_long raw_BA=CalcBroadAddr(dst_addr, mask_addr); printf("%s\n", RawIPToCStr(raw_BA)); printf("%s\n", RawIPToCStr(raw_BA-(1<<24))); u_long raw_NA = CalcNetAddr(dst_addr, mask_addr); printf("%s\n", RawIPToCStr(raw_NA)); printf("%s\n", RawIPToCStr(raw_NA +(1 << 24))); for (int i = 0; i < sizeof(dst_addr); i++) { printf("%x ", ((unsigned char*)(&dst_addr))[i]); } puts("\n"); u_long hl = htonl(dst_addr); for (int i = 0; i < sizeof(dst_addr); i++) { printf("%x ", ((unsigned char*)(&hl))[i]); } puts("\n"); //u_long nl = ntohl(dst_addr)+1; EndianConvert(&dst_addr, sizeof(u_long)); dst_addr+=255; for (int i = 0; i < sizeof(dst_addr); i++) { printf("%x ", ((unsigned char*)(&dst_addr))[i]); } puts("\n"); EndianConvert(&dst_addr, sizeof(u_long)); for (int i = 0; i < sizeof(dst_addr); i++) { printf("%x ", ((unsigned char*)(&dst_addr))[i]); } puts("\n"); //u_long Cur_IP = Raw_IP_Pool("192.168.10.1", "255.255.240.0",0); //while (Cur_IP = Raw_IP_Pool("192.168.10.1", "255.255.240.0", 1)) //{ // printf("%s\n", RawIPToCStr(Cur_IP)); // getchar(); //} struct RawIP_Iter raw_ip_iter = Create_IPIter("10.10.10.123","255.255.240.0"); u_long cur_ip = NULL; while (cur_ip = NextRawIP(&raw_ip_iter)) { printf("%ld/%ld: %s\n", raw_ip_iter.Index,raw_ip_iter.Size,RawIPToCStr(cur_ip)); } getchar(); return; } #endif
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "sim.h" struct registro_segmentacion RS_IF_ID; struct registro_segmentacion RS_ID_EX; struct registro_segmentacion RS_EX_MEM; struct registro_segmentacion RS_MEM_WB; instruccion mem_ins[TAM]; int mem_principal[RAM]; int banco_registros[10]; //Cuando se carga en los registros el dato inmediato??? suponog que solo puede en la etapa IF void etapa_if(int i){ //mem_ins[i]; RS_IF_ID.cod=mem_ins[i].operacion; RS_IF_ID.ra=mem_ins[i].ra; RS_IF_ID.rb=mem_ins[i].rb; RS_IF_ID.rdest=mem_ins[i].rdest; char str[80] = "This is - www.tutorialspoint.com - website"; RS_IF_ID.inmediato=mem_ins[i].inmediato; //los operandos no los queremos en esta etapa } void etapa_id(){ //leemos de RS_IF_ID RS_ID_EX.cod=RS_IF_ID.cod; RS_ID_EX.ra=RS_IF_ID.ra; RS_ID_EX.rb=RS_IF_ID.rb; RS_ID_EX.rdest=RS_IF_ID.rdest; RS_ID_EX.inmediato=RS_IF_ID.inmediato; //DECODIFICAMOS y leemos operando, con esto le pasamos los operandos a la etapa RS_ID_EX.opra=banco_registros[RS_ID_EX.ra]; RS_ID_EX.oprb=banco_registros[RS_ID_EX.rb]; } void etapa_ex(){ //leemos de RS_ID_EX //Antes de nada miramos por ejemplo si RS_ID_EX.ra== RS_EX_MEM.rdest ---> RS_ID_EX.opra == RS_EX_MEM.rdest //Riesgo de datos del registro a en la anterior instruccion if(RS_ID_EX.ra == RS_EX_MEM.rdest) { RS_ID_EX.opra == RS_EX_MEM.rdest; }else { RS_EX_MEM.opra=RS_ID_EX.opra; } //Riesgo de datos del registro b en las anterior instruccion if (RS_ID_EX.rb == RS_EX_MEM.rdest) { RS_ID_EX.oprb == RS_EX_MEM.rdest; }else { RS_EX_MEM.oprb=RS_ID_EX.oprb; } RS_EX_MEM.cod=RS_ID_EX.cod; RS_EX_MEM.ra=RS_ID_EX.ra; RS_EX_MEM.rb=RS_ID_EX.rb; RS_EX_MEM.rdest=RS_ID_EX.rdest; RS_EX_MEM.inmediato=RS_ID_EX.inmediato; switch (RS_EX_MEM.cod){ case ADD: RS_EX_MEM.resultado=RS_EX_MEM.opra + RS_EX_MEM.inmediato; break; case SUB: RS_EX_MEM.resultado=RS_EX_MEM.opra - RS_EX_MEM.inmediato; break; case ADDI: RS_EX_MEM.resultado=RS_EX_MEM.opra + RS_EX_MEM.inmediato; //SUMA CON EL INMEDIATO break; case SUBI: RS_EX_MEM.resultado=RS_EX_MEM.opra - RS_EX_MEM.inmediato; //RESTA CON EL INMEDIATO break; case MULT: RS_EX_MEM.resultado=RS_EX_MEM.opra * RS_EX_MEM.inmediato; break; case LW: RS_EX_MEM.resultado=RS_EX_MEM.oprb + RS_EX_MEM.inmediato; break; case SW: RS_EX_MEM.resultado=RS_EX_MEM.oprb + RS_EX_MEM.inmediato; break; } } void etapa_mem(){ RS_MEM_WB.cod=RS_EX_MEM.cod; RS_MEM_WB.ra=RS_EX_MEM.ra; RS_MEM_WB.rb=RS_EX_MEM.rb; RS_MEM_WB.rdest=RS_EX_MEM.rdest; RS_MEM_WB.opra=RS_EX_MEM.opra; RS_MEM_WB.oprb=RS_EX_MEM.oprb; RS_MEM_WB.inmediato=RS_EX_MEM.inmediato; if(RS_MEM_WB.cod==LW) { //Actualizamos el valor del resultado, de manera que el resultado de la etapa anterior //es la direccion de memoria de la que leemos el valor que vamos a almacenar en //el resultado de esta etapa RS_MEM_WB.resultado = mem_principal[RS_EX_MEM.resultado]; } else if (RS_MEM_WB.cod == SW) { mem_principal[RS_MEM_WB.resultado] = RS_MEM_WB.opra; } } void etapa_wb(){ banco_registros[RS_MEM_WB.rdest] = RS_MEM_WB.resultado; } /* void generar_instrucciones(char * fichero, instruccion mem_ins[TAM]) { } */ int main(int argc,char* argv[] ){ int n_ins=10; int i=0; int riesgo=0; char * fichero; fichero = argv[1]; char linea[128]; FILE *fich; int contador =0; char* delim=" "; fich = fopen(fichero, "r"); char *puntero; char *iteracion; while(fgets(linea, 128, (FILE*) fich)){ char *p1, *p2; p1 = linea; int iteracion=0; while(p2 = strchr(p1, ' '))//vamos leyendo los datos de la instruccion. { *p2++ = '\0'; if(iteracion==0) { printf("Iteracion 0\n"); printf("valor de p1 %s\n", p1); if(!strcmp(p1, "add")){//ADD printf("Estoy en add ---> "); mem_ins[contador].operacion=ADD; printf("%d\n",mem_ins[contador].operacion); }else if (!strcmp(p1, "sub")) { printf("Estoy en sub --->"); mem_ins[contador].operacion=SUB; printf("%d\n",mem_ins[contador].operacion); }else if(!strcmp(p1, "addi")) { mem_ins[contador].operacion=ADDI; }else if (!strcmp(p1, "subi")) { mem_ins[contador].operacion=SUBI; }else if (!strcmp(p1, "mult")) { mem_ins[contador].operacion=MULT; }else if (!strcmp(p1, "lw")) { mem_ins[contador].operacion=LW; }else if (!strcmp(p1, "sw")) { mem_ins[contador].operacion=SW; }else if (!strcmp(p1, "nop") || !strcmp(p1, "NOP") ) { mem_ins[contador].operacion=NOP; } }else if (iteracion==1) { printf("Iteracion 1\n"); //asumimos que tiene como maximo 9 registros mem_ins[contador].rdest=(int) p1[1]; if(mem_ins[contador].operacion==LW || mem_ins[contador].operacion==SW) { p1=p2; iteracion++; } } if (iteracion==2) { printf("Iteracion 2\n"); if(mem_ins[contador].operacion!=LW && mem_ins[contador].operacion!=SW) { mem_ins[contador].ra=(int) p1[1]; p1=p2; iteracion++; }else{ //Leemos dato inmediato p2=strchr(p1,'('); *p2++='\0'; mem_ins[contador].inmediato=atoi(p1); //actualizamos el puntero p1=p2; *p1++; //leemos el numero de registro mem_ins[contador].rb=atoi(p1); } } if(iteracion==3){//no fa aquesta iteració if(mem_ins[contador].operacion!=LW && mem_ins[contador].operacion!=SW) { printf("Iteracion 3\n"); //Comprobamos si es o no, dato inmediato if(p1[0]=='r') { mem_ins[contador].rb=(int) p1[1]; }else { *p1++; mem_ins[contador].inmediato=atoi(p1); } } } p1=p2; iteracion++; } printf("OPERACION: %d\n", mem_ins[contador].operacion); contador++; } /* while(i<n_ins){ etapa_wb(); etapa_mem(); etapa_ex(); if(RS_IF_ID.ra == RS_ID_EX.rdest && RS_IF_ID.rb == RS_EX_MEM.rdest) { RS_IF_ID.opra == RS_ID_EX.resultado; RS_IF_ID.oprb == RS_EX_MEM.resultado; riesgo = RIESGO_ARITMETICO_AB; } else if (RS_IF_ID.rb == RS_ID_EX.rdest && RS_IF_ID.ra == RS_EX_MEM.rdest){ RS_IF_ID.oprb == RS_ID_EX.resultado; RS_IF_ID.opra == RS_EX_MEM.resultado; riesgo = RIESGO_ARITMETICO_AB; } else if () { } etapa_id(); etapa_if(i); i++; } */ //EL WHILE DEBEMOS HACERLO DE WB A IF }
C
#include <assert.h> #include <stdlib.h> #include "../incbin.h" INCBIN(Lorem, "loremipsum.txt"); INCBIN(Onebyte, "onebyte.txt"); INCBIN(Sevenbytes, "sevenbytes.txt"); int main(int argc, char **argv) { assert(gLoremSize==962); assert(&gLoremData[gLoremSize] == (const unsigned char*) &gLoremEnd); assert(gOnebyteSize == 1); assert(&gOnebyteData[gOnebyteSize] == (const unsigned char*) &gOnebyteEnd); assert(gSevenbytesSize==7); assert(&gSevenbytesData[gSevenbytesSize] == (const unsigned char*) &gSevenbytesEnd); exit(0); }
C
/** * @file pdf.c gcc -I"include" -D debug_pdf bytearray.c pdf.c adler32.c inftrees.c inffast.c crc32.c zutil.c inflate.c && ./a.out * @author db0@qq.com * @version 1.0.1 * @date 2015-10-29 */ #include "zlib.h" #include "pdf.h" //Keep this many previous recent characters for back reference: #define oldchar 15 //Convert a recent set of characters into a number if there is one. //Otherwise return -1: float ExtractNumber(const char* search, int lastcharoffset) {/*{{{*/ int i = lastcharoffset; while (i>0 && search[i]==' ') i--; while (i>0 && (isdigit(search[i]) || search[i]=='.')) i--; float flt=-1.0; char buffer[oldchar+5]; memset(buffer,0,sizeof(buffer)); strncpy(buffer, search+i+1, lastcharoffset-i); if (buffer[0] && sscanf(buffer, "%f", &flt)) { return flt; } return -1.0; }/*}}}*/ //Check if a certain 2 character token just came along (e.g. BT): int seen2(const char* search, char* recent) {/*{{{*/ if ( recent[oldchar-3]==search[0] && recent[oldchar-2]==search[1] && (recent[oldchar-1]==' ' || recent[oldchar-1]==0x0d || recent[oldchar-1]==0x0a) && (recent[oldchar-4]==' ' || recent[oldchar-4]==0x0d || recent[oldchar-4]==0x0a) ) { return 1; } return 0; }/*}}}*/ //This method processes an uncompressed Adobe (text) object and extracts text. void ProcessOutput(FILE* file, char* output, size_t len) {/*{{{*/ //Are we currently inside a text object? int intextobject = 0; //Is the next character literal (e.g. \\ to get a \ character or \( to get ( ): int nextliteral = 0; //() Bracket nesting level. Text appears inside () int rbdepth = 0; //Keep previous chars to get extract numbers etc.: char oc[oldchar]; int j=0; for (j=0; j<oldchar; j++) oc[j]=' '; for (size_t i=0; i<len; i++) { unsigned char c = output[i]; if (intextobject) { if (rbdepth==0 && seen2("TD", oc)) { //Positioning. //See if a new line has to start or just a tab: float num = ExtractNumber(oc,oldchar-5); if (num>1.0) { fputc(0x0d, file); fputc(0x0a, file); } if (num<1.0) { fputc('\t', file); } } if (rbdepth==0 && seen2("ET", oc)) { //End of a text object, also go to a new line. intextobject = 0; fputc(0x0d, file); fputc(0x0a, file); } else if (c=='(' && rbdepth==0 && !nextliteral) { //Start outputting text! rbdepth=1; //See if a space or tab (>1000) is called for by looking //at the number in front of ( int num = ExtractNumber(oc,oldchar-1); if (num>0) { if (num>1000.0) { fputc('\t', file); } else if (num>100.0) { fputc(' ', file); } } } else if (c==')' && rbdepth==1 && !nextliteral) { //Stop outputting text rbdepth=0; } else if (rbdepth==1) { //Just a normal text character: if (c=='\\' && !nextliteral) { //Only print out next character no matter what. Do not interpret. nextliteral = 1; } else { nextliteral = 0; if ( ((c>=' ') && (c<='~')) || ((c>=128) && (c<255)) ) { fputc(c, file); } } } } //Store the recent characters for when we have to go back for a number: for (j=0; j<oldchar-1; j++) oc[j]=oc[j+1]; oc[oldchar-1]=c; if (!intextobject) { if (seen2("BT", oc)) { //Start of a text object: intextobject = 1; } } } }/*}}}*/ int getNumChars(char * string,char sign) { int num = 0; if(string) { int len = strlen(string); int i=0; while(i<len) { if(string[i]==sign) num++; ++i; } } return num; } typedef struct PdfObj{ int id; int modify; int length; char * properties; char * data; int numChildren; struct PdfObj ** children; struct PdfObj * parent; }PdfObj; typedef struct PdfTrailer{ int size; PdfObj *root; PdfObj *info; char * ID; }PdfTrailer; typedef struct PdfHeader{ char * version; }PdfHeader; typedef struct PdfXref{ int start; int num; int * offsets; }PdfXref; typedef struct PdfFile{ ByteArray *bytearray; PdfHeader * header; PdfXref * xref; PdfObj ** objs; int numObjs; PdfTrailer * trailer; }PdfFile; PdfTrailer * PdfTrailer_read(PdfFile * file,ByteArray * bytearray); void startline(PdfFile *,ByteArray * bytearray); PdfObj * PdfFile_getObjById(PdfFile * file,int id) { if(file->objs) { int i = 0; while(i<file->numObjs) { PdfObj * obj = file->objs[i]; if(obj && obj->id==id){ return obj; } ++i; } } return NULL; } void PdfXref_free(PdfXref * xref) { if(xref) { free(xref); } } PdfXref * PdfXref_read(ByteArray * bytearray) { PdfXref * pdfxref = malloc(sizeof(PdfXref)); memset(pdfxref,0,sizeof(PdfXref)); char * line = ByteArray_readLine(bytearray); printf("line:%s,",line); pdfxref->start = atoi(line); printf("start:%d,",pdfxref->start); int id = pdfxref->start; int len = 1; while(id >10){ len++; id /= 10; } pdfxref->num = atoi(line+len); printf("num:%d,",pdfxref->num); free(line); int i = pdfxref->start; while(i<pdfxref->num) { line = ByteArray_readLine(bytearray); //printf("%s",line); free(line); ++i; } return pdfxref; } PdfTrailer * PdfTrailer_read(PdfFile * file,ByteArray * bytearray) { PdfTrailer * trailer = malloc(sizeof(*trailer)); memset(trailer,0,sizeof(*trailer)); char * line = NULL; int numL = 0; int numR = 0; while(numL-numR || numL==0) { if(line)free(line); line = ByteArray_readLine(bytearray); numL += getNumChars(line,'<'); numR += getNumChars(line,'>'); //printf("%s",line); char * per = NULL; if(trailer->size == 0) { per = strstr(line,"/Size "); if(per) { trailer->size = atoi(per+6); printf("size:%d,",trailer->size); } } if(trailer->root == NULL) { per = strstr(line,"/Root "); if(per) { int rootId = atoi(per+6); printf("rootId:%d,",rootId); trailer->root = PdfFile_getObjById(file,rootId); if(trailer->root) { char * s = trailer->root->properties; printf("\nroot obj:\n%s\n",s); char *p = strstr(s,"/Pages "); if(p) { PdfObj * pageObj = PdfFile_getObjById(file,atoi(p+7)); if(pageObj) { char* properties = pageObj->properties; printf("pages found! %s\n",properties); } } } } } if(trailer->info==NULL) { per = strstr(line,"/Info "); if(per) { int infoId = atoi(per+6); printf("infoId:%d,",infoId); trailer->info = PdfFile_getObjById(file,infoId); if(trailer->info) { printf("info obj found!\n"); } } } if(trailer->ID==NULL) { per = strstr(line,"/ID[< "); if(per) { trailer->ID = per+6; if(trailer->ID) { printf("ID:%s,",trailer->ID); } } } } printf("\n"); //printf("%s",line); free(line); return trailer; } void PdfTrailer_free(PdfTrailer * trailer) { if(trailer) { free(trailer); } } void PdfObj_free(PdfObj * obj) { if(obj) { if(obj->data) free(obj->data); if(obj->properties) free(obj->properties); free(obj); } } void Text_printf(char * data,int length,char * out,int outsize) { z_stream zstrm; memset(&zstrm, 0,sizeof(zstrm)); zstrm.avail_in = length + 1; zstrm.avail_out = outsize; zstrm.next_in = (Bytef*)data; zstrm.next_out = (Bytef*)out; int rsti = inflateInit(&zstrm); if (rsti == Z_OK) { int rst2 = inflate (&zstrm, Z_FINISH); if (rst2 >= 0) { size_t totout = zstrm.total_out; ProcessOutput(stdout, out, totout); }else{ printf("error\n"); } }else{ printf("error\n"); } } PdfObj * PdfObj_read(PdfFile * file,char *line) { ByteArray * bytearray = file->bytearray; PdfObj * obj = malloc(sizeof(*obj)); memset(obj,0,sizeof(*obj)); obj->id = atoi(line); printf("id:%d,",obj->id); if(file->numObjs < obj->id) { if(file->objs==NULL) { file->objs = malloc(obj->id*sizeof(PdfObj*)); memset(file->objs,0,obj->id*sizeof(PdfObj*)); }else{ int len = obj->id*sizeof(PdfObj*); file->objs = realloc(file->objs,len); int dealed = file->numObjs*sizeof(PdfObj*); memset((char*)file->objs+dealed,0,len-dealed); } file->numObjs = obj->id; } file->objs[obj->id-1] = obj; int position = bytearray->position - strlen(line); int numL = getNumChars(line,'<'); int numR = getNumChars(line,'>'); while(numL-numR || numL==0) { if(line)free(line);line = NULL; line = ByteArray_readLine(bytearray); numL += getNumChars(line,'<'); numR += getNumChars(line,'>'); } int propertiesLen = bytearray->position - position; obj->properties = malloc(propertiesLen); bytearray->position = position; ByteArray_readBytes(bytearray,propertiesLen,obj->properties); if(obj->length==0){ char * length = strstr(obj->properties,"/Length "); if(length){ obj->length = atoi(length+strlen("/Length ")); printf("(%d)",obj->length); } } if(obj->length>0) { if((line+strlen(line)-strrchr(line,'>'))<3) { if(line)free(line);line=NULL; line = ByteArray_readLine(bytearray); } obj->data = malloc(obj->length); ByteArray_readBytes(bytearray,obj->length,obj->data); //printf("data:%s,",obj->data); if(line)free(line);line=NULL; line = ByteArray_readLine(bytearray); while(strlen(line)<3){ //printf("line:%s,",line); if(line)free(line);line = NULL; line = ByteArray_readLine(bytearray); } if(line && strncmp(line,"endstream",9)){ printf("\nXXXXXXXXXXXXxx type_end:%s",line); } } if(line)free(line);line = NULL; line = (ByteArray_readLine(bytearray)); if(strncmp(line,"endobj",6)){ printf("\nXXXXXXXXXXXXxx endobj:%s",line); } //printf("endobj:%s",line); free(line); //printf("\n----------------------------------------,\n"); if(obj->data) { size_t outsize = obj->length*10; char out[outsize]; memset(out, 0,outsize); //Text_printf(obj->data,obj->length,out,outsize); } return obj; } void PdfHeader_free(PdfHeader * header) { if(header) { if(header->version) free(header->version); free(header); } } PdfHeader * PdfHeader_read(ByteArray * bytearray) { PdfHeader * header = malloc(sizeof(*header)); memset(header,0,sizeof(*header)); header->version = ByteArray_readLine(bytearray); if(strncmp(header->version,"%PDF-1.",7)) { printf("not a pdf file!\n"); PdfHeader_free(header); return 0; } free(ByteArray_readLine(bytearray)); //printf("--------------------"); fflush(stdout); return header; } void PdfFile_free(PdfFile * file) { if(file) { if(file->header) PdfHeader_free(file->header); if(file->objs) { int i=0; while(i<file->numObjs) { if(file->objs[i]) { //printf("0x%x,",(int)file->objs[i]); PdfObj_free(file->objs[i]); } ++i; } free(file->objs); } if(file->xref) PdfXref_free(file->xref); if(file->trailer) PdfTrailer_free(file->trailer); free(file); } } void startline(PdfFile * file,ByteArray * bytearray) { char * line = ByteArray_readLine(bytearray); if(strstr(line," obj")) { PdfObj_read(file,line); line = NULL; }else if(strncmp(line,"xref",4)==0){ printf("xref!\n"); PdfXref_read(bytearray); }else if(strncmp(line,"trailer",7)==0){ printf("trailer!\n"); PdfTrailer_read(file,bytearray); }else if(strncmp(line,"startxref",7)==0){ printf("startxref!\n"); free(line); line = ByteArray_readLine(bytearray); printf("%d,",atoi(line)); }else if(strncmp(line,"%%EOF",5)==0){ printf("\nfile end!\n"); //free(line); line = NULL; } if(line){ free(line); } if(bytearray->position < bytearray->length) startline(file,bytearray); } PdfFile * PdfFile_parse(ByteArray * bytearray,char * out) { PdfFile * file = malloc(sizeof(PdfFile)); memset(file,0,sizeof(PdfFile)); file->bytearray = bytearray; file->header = PdfHeader_read(bytearray); if(file->header==NULL) { PdfFile_free(file); return 0; } startline(file,bytearray); return file; } #ifdef debug_pdf int main(int argc,char**argv) { char * filename; if(argc>1) { filename = argv[argc-1]; }else{ filename = "doc/PDF.pdf"; } FILE * _file = fopen(filename,"rb"); int fileLen = fseek(_file,0,SEEK_END); fileLen = ftell(_file); rewind(_file); printf("%s,%d\n",filename,fileLen); ByteArray * bytearray = ByteArray_new(fileLen); fread(bytearray->data,1,fileLen,_file); fclose(_file); char * out = malloc(fileLen); memset(out,0,fileLen); PdfFile_free(PdfFile_parse(bytearray,out)); printf("%s\n",out); return 0; } #endif #ifdef as_api #include "AS3.h" //Method exposed to ActionScript //Takes a String and echos it static AS3_Val echo(void* self, AS3_Val args) { AS3_Val byteArray; AS3_ArrayValue( args, "AS3ValType", &byteArray); AS3_Val length = AS3_GetS(byteArray, "length"); sztrace("length getted!"); int len = AS3_IntValue(length); //if(len>0) return length; char *data=NULL; data=malloc(len); memset(data,0,len); int fileLen = AS3_ByteArray_readBytes(data,byteArray, len); char *out= NULL; out = malloc(fileLen); memset(out,0,fileLen); ByteArray * bytearray = ByteArray_new(fileLen); bytearray->data = data; PdfFile_free(PdfFile_parse(bytearray,out)); ByteArray_free(bytearray); return AS3_String(out); } int main() { //define the methods exposed to ActionScript //typed as an ActionScript Function instance AS3_Val echoMethod = AS3_Function( NULL, echo ); // construct an object that holds references to the functions AS3_Val result = AS3_Object( "echo: AS3ValType", echoMethod ); // Release AS3_Release( echoMethod ); // notify that we initialized -- THIS DOES NOT RETURN! AS3_LibInit( result ); // should never get here! return 0; } #endif
C
#include <stdio.h> #include <ctype.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include "eval.h" CAL_ERROR ERROR; typedef enum { false = 0, true = 1, } bool; typedef enum { ADD = '+', MINUS = '-', MULT = '*', DIV = '/', L_PARE = '(', R_PARE = ')', NUMBER = 'a', } item_type; typedef struct { item_type type; double data; } item; item items[20]; int k; /* index for items */ void convert_items(char expression[]) { int i; int j; char buffer[10]; /* save a number */ int buffer_i; k = 0; for (i = 0; i < strlen(expression); i++) { if (isdigit(expression[i])) { j = i + 1; buffer_i = 0; buffer[buffer_i++] = expression[i]; while (isdigit(expression[j]) || expression[j] == '.') { buffer[buffer_i++] = expression[j]; i = j; j++; } buffer[buffer_i] = '\0'; items[k].type = NUMBER; items[k].data = atof(buffer); k++; } else { items[k].type = expression[i]; items[k].data = expression[i]; k++; } } } char stack[20]; int idx; void push(char x) { assert(idx < 20); stack[idx++] = x; } char pop() { assert(idx > 0); return stack[--idx]; } bool higher_precedence(char a, char b) { if ( (a == '*' || a == '/') && (b == '-' || b == '+') ) return true; else return false; } item suffix[20]; int si; /* index for suffix items */ void convert_to_suffix() { int i; idx = 0; for (i = 0; i < k; i++) { if (items[i].type == NUMBER) { suffix[si++] = items[i]; } else switch (items[i].type) { case ')': while (stack[idx-1] != '(') { suffix[si].type = suffix[si].data = pop(); si++; } pop(); /* pop '(', don't print */ break; case '(': push('('); break; default: /* +, -, *, / */ if (higher_precedence(stack[idx-1], items[i].type)) { // print all stack while (idx != 0) { suffix[si].type = suffix[si].data = pop(); si++; } } push(items[i].type); break; } } while (idx != 0) { suffix[si].type = suffix[si].data = pop(); si++; } } double stack2[20]; double *sp; #define pop3(sp) (*--(sp)) #define push3(sp, n) (*((sp)++) = (n)) double calculate_suffix() { int i; double a, b; sp = stack2; for (i = 0; i < si; i++) { if (suffix[i].type == NUMBER) push3(sp, suffix[i].data); else switch (suffix[i].type) { case '+': a = pop3(sp); b = pop3(sp); push3(sp, a + b); break; case '*': a = pop3(sp); b = pop3(sp); push3(sp, a * b); break; case '-': a = pop3(sp); b = pop3(sp); push3(sp, b - a); break; case '/': a = pop3(sp); b = pop3(sp); if (a == 0) { ERROR.code = 1; ERROR.message = strdup("Error: div-by-zero"); return 0.0; } push3(sp, b / a); break; default: assert(0); break; } } return stack2[0]; } double eval_suffix_expr(char expression[], CAL_ERROR *cal_error) { double rtv; convert_items(expression); convert_to_suffix(); rtv = calculate_suffix(); idx = k = si = 0; *cal_error = ERROR; return rtv; }
C
/******************************************************** Ӽʵϰ ************************************************************/ /************************ MEI ******************************* Module Name: HD7279.c Module Date: 11/14/2013 Module Auth: Description: 7279̵ʹ ************************* MEI *****************************/ /*------------------------Includes------------------------*/ #include "HD7279.h" /***************ⲿú*******************************/ /********************************************************** HD7279ʼ ܣʼHD7279ܽáHD7279λ 룺 أ עʹȣѡùܽŵĺ궨 *********************************************************/ void init_7279(void) { unsigned int tmr; DR7279 |= cs7279; //cs7279Ϊ DR7279 |= clk7279; //clk7279Ϊ DR7279 |= dat7279; //dat7279Ϊ DR7279 &= ~(key7279); //key7279Ϊ WR7279 |= cs7279; //cs7279ʼΪ1 WR7279 |= clk7279; //clk7279ʼΪ1 WR7279 |= dat7279; //dat7279ʼΪ1 WR7279 |= key7279; //key7279ʼΪ for(tmr=0;tmr<0xf000;tmr++); //ϵʱ send_byte(CMD_RESET); //λHD7279 } /****************** ********************** HD7279д뺯 ܣHD7279д 룺cmdΪָ; dtaΪ أ עHD7279Ŀƺ ******************************************/ void write7279(unsigned char cmd,unsigned char dta) //д뵽HD7279 { send_byte(cmd); //дָ send_byte(dta); // } /****************** ********************** HD7279ȡ ܣHD7279ȡԭʼֵ 룺 أԭʼֵ עHD7279Ŀƺ ******************************************/ unsigned char read7279(void) { send_byte(0x15); //Ͷȡָ return(receive_byte()); //ؼֵ } /****************** ********************** HD7279ȴպ ܣһΰؼֵ 룺 أֵ̼ עHD7279Ŀƺ ******************************************/ unsigned char get_key7279(void) { unsigned char KeyNum; while( (RD7279&key7279) ); //ȴм,ʱΪߵƽ delay10ms(1); //ʱ100ms KeyNum=read7279(); // KeyNum=num_change7279(KeyNum); //תΪʮ delay10ms(1); //ʱ100ms while( !(RD7279&key7279) ); //ȴɿ return KeyNum; //ؼֵ } /******************************ڲ************************************/ void long_delay(void) //ʱӺ { unsigned char i; for(i=0;i<80;i++); } void short_delay(void) //ʱӺ { unsigned char i; for(i=0;i<46;i++); } void delay10ms(unsigned int count)//10msʱӺ { unsigned char i,j,k; for (i=0;i<count;i++) for(j=0;j<100;j++) for(k=0;k<100;k++); } /****************** ********************** HD7279ֽڷͺ ܣHD7279һֽ 룺һֽ أ עHD7279Ӳ ******************************************/ void send_byte(unsigned char out_byte) { unsigned char i; WR7279&=~clk7279; //clk7279=0; WR7279&=~cs7279; //cs7279=0 long_delay(); for(i=0;i<8;i++) { if(out_byte&0x80) { WR7279|=dat7279; //dat7279=1; } else { WR7279&=~dat7279; //dat7279=0; } WR7279|=clk7279; //clk7279=1; short_delay(); WR7279&=~clk7279; //clk7279=0; short_delay(); out_byte=out_byte<<1; } WR7279|=dat7279; //dat7279=1; } /****************** ********************** HD7279ֽڽպ ܣHD7279һֽ 룺 أһֽ עHD7279Ӳ ******************************************/ unsigned char receive_byte(void) { unsigned char i,in_byte; WR7279|=clk7279; //clk7279=1; DR7279&=~dat7279; //dat7279Ϊ long_delay(); for(i=0;i<8;i++) { WR7279|=clk7279; //clk7279=1; short_delay(); in_byte=in_byte<<1; if(RD7279&dat7279) { in_byte=in_byte|0x01; } WR7279&=~clk7279; //clk7279=0; short_delay(); } DR7279|=dat7279; //dat7279ԭΪ return(in_byte); } /****************** ********************** HD7279ȴպ ܣһΰؼֵ 룺 أֵ̼ עHD7279Ŀƺ ******************************************/ unsigned char num_change7279 (unsigned char X) { switch (X) { case ONE : return 0X01; case TWO : return 0X02; case THREE : return 0X03; case FOUR : return 0X04; case FIVE : return 0X05; case SIX : return 0X06; case SEVEN : return 0X07; case EIGHT : return 0X08; case NINE : return 0X09; case ZERO : return 0X00; case AAAA : return 0x0A; case BBBB : return 0x0B; case CCCC : return 0x0C; case DDDD : return 0x0D; case EEEE : return 0x0E; case FFFF : return 0x0F; default : return 0xFF; } } /****************** HD7279Ժ*************************/ void test_7279(void) { unsigned long wait_cnter; unsigned long tmr,j,k; unsigned char key7279_number; init_7279(); while(1) { for(tmr=0;tmr<0xf000;tmr++); //ϵʱ send_byte(CMD_RESET); //λHD7279 //ָʾ send_byte(CMD_TEST); for(j=0;j<3;j++) //ʱԼ3 { delay10ms(100); } send_byte(CMD_RESET); //ʾ { write7279(DECODE0+0,0x80); write7279(DECODE0+1,0x81); write7279(DECODE0+2,0x82); write7279(DECODE0+3,0x83); write7279(DECODE0+4,0x84); write7279(DECODE0+5,0x85); write7279(DECODE0+6,0x86); write7279(DECODE0+7,0x87); } delay10ms(200); //˸ָ̽ӿڲԣ //ûļʾ //10ްS0һʾ wait_cnter=0; key7279_number=0xff; write7279(BLINKCTL,0xfc); //1?2λΪ˸ʾ 11111100 write7279(UNDECODE,0x08); //0x08 is '_' write7279(UNDECODE+1,0x08); //ڵ1?2λʾ»'_' do { if(!(RD7279&key7279)) //м { write7279(DECODE0+7,0x88); key7279_number=read7279(); // write7279(BLINKCTL,0xff); write7279(DECODE1+1,key7279_number/16); //ڵ2 λʾ8λ write7279(DECODE1,key7279_number&0x0f); //ڵ1λʾ8λ while(!(RD7279&key7279)); //ȴſ wait_cnter=0; delay10ms(10); } } while(wait_cnter<1000); //Ϊ'0'ͳʱһʾ write7279(BLINKCTL,0xff); //˸ λʾ˸1111,1111 send_byte(CMD_RESET); //ʾ //ݵָ write7279(UNDECODE+7,0x49); //ڵ8λ뷽ʽʾһַ delay10ms(80); //ѭƲԣ3Σ3Ρ for(j=0;j<23;j++) { send_byte(RTR_CYCLE); //ѭ23 delay10ms(12); } for(j=0;j<23;j++) { send_byte(RTL_CYCLE); //ѭ23 delay10ms(12); } //뷽ʽ0ָ for(j=0;j<16;j++) { send_byte(RTL_UNCYL); //ѭָ write7279(DECODE0,j); //뷽ʽ0ʾڵ1λ delay10ms(50); } delay10ms(150); send_byte(CMD_RESET); //뷽ʽ1ָ for(j=0;j<16;j++) { send_byte(RTR_UNCYL); //ѭָ write7279(DECODE1+7,j); //뷽ʽ1ʾڵ8λ delay10ms(50); } delay10ms(150); //ָ for(j=0;j<6;j++) { k=k>>1; write7279(ACTCTL,k); //ÿһһλ delay10ms(100); } write7279(ACTCTL,0xff); //ָ8λʾ delay10ms(100); send_byte(CMD_RESET); //ʾ //εָͶιرָ for(j=0;j<64;j++) { write7279(SEGON,j); //64ʾ write7279(SEGOFF,j-1); //ͬʱǰһʾιر delay10ms(20); } } } /********************************** HD7279 *******************************************/ void dis_data ( unsigned char dig_start,unsigned char dig_end,signed long num) { unsigned char i,temp_char; for( i = dig_start; i <= dig_end; i++ ) { temp_char = num % 10; num -= temp_char; num /= 10; write7279 ( DECODE0 + i , 0x00 + temp_char );//0x00Ϊӵʾ0x80Ϊӵʾ } } //СʾrpλʾС void dis_data_RP ( unsigned char dig_start,unsigned char dig_end,signed long num,int rp) { unsigned char i,temp_char; for( i = dig_start; i <= dig_end; i++ ) { temp_char = num % 10; num -= temp_char; num /= 10; if(i!=rp) write7279 ( DECODE0 + i , 0x00 + temp_char );//0x00Ϊӵʾ0x80Ϊӵʾ else write7279 ( DECODE0 + i , 0X80 + temp_char ); } }/**/ signed long get_data ( signed char dig_start,signed char dig_end ) { signed long temp_long = 0; signed char i,temp_char; for( i = dig_start; i <= dig_end; i++ ) write7279(UNDECODE + i,0x08); //ʾΪ'_' for( i = dig_end; i >= dig_start ; i-- ) { temp_char = get_key7279(); temp_long *= 10; temp_long += temp_char; write7279 ( DECODE1 + i , 0x80 + temp_char); //1ʾĸ } delay10ms(5); send_byte(CMD_RESET); return temp_long; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jpeyron <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/21 14:57:20 by jpeyron #+# #+# */ /* Updated: 2021/06/25 15:14:13 by jpeyron ### ########.fr */ /* */ /* ************************************************************************** */ #include "pushswap.h" int choose_algorithm(t_swap *swap) { if (is_sorted(swap->a->list)) return (1); if (swap->a->size < 3) return (swap_stack(swap, swap->a)); else if (swap->a->size == 3) return (sort_three(swap)); else if (swap->a->size <= 15) return (sort_fifteen(swap)); else if (swap->a->size <= 100) return (sort_big(swap, 30)); else return (sort_big(swap, 80)); return (1); } int main(int ac, char **av) { t_swap *swap; swap = init_swap(ac, av); choose_algorithm(swap); ft_lstclear(&swap->a->list, free); ft_lstclear(&swap->b->list, free); free(swap->a); free(swap->b); free(swap); }
C
/** * @file cloudbox.c * Troulakis Giorgos Rafail * rtroulak@gmail.com * * **/ #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <dirent.h> #include "cloudbox.h" #include <sys/time.h> #include <time.h> #include <stddef.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> /* * The list that holds all the current watched files. * * It is very convinient this list to be shorted by the file name * in order to be able to find immediatly inconsistencies, */ struct dir_files_status_list *watched_files; /* * Print mutex, for printing nicely the messages from different threads */ pthread_mutex_t print_mutex; /* * Mutex used to protect the accesses from different threads * of the file list of the watched directory */ pthread_mutex_t file_list_mutex; /*insert from list*/ struct dir_files_status_list* insert_file(struct dir_files_status_list *head,char *filename ,size_t size_in_bytes ,char sha1sum[SHA1_BYTES_LEN], long long int modifictation_time_from_epoch){ struct dir_files_status_list *cur ,*newnode,*prev; prev=NULL; cur=head; while((cur)&&(strcmp(filename,cur->filename)>0)){ prev=cur; cur=cur->next; } if((cur)&&(strcmp(cur->filename,filename)==0)) return head; newnode=(struct dir_files_status_list*)malloc(sizeof(struct dir_files_status_list)); newnode->filename=(char*)malloc(sizeof(char*)); strcpy(newnode->filename,filename); strcpy(newnode->sha1sum,sha1sum); newnode->size_in_bytes=size_in_bytes; newnode->modifictation_time_from_epoch=modifictation_time_from_epoch; newnode->next=cur; newnode->previous=prev; if((!cur)&&(!prev)){ head=newnode; return head; } if(!cur){ prev->next=newnode; return head; } if(!prev) head=newnode; else{ prev->next=newnode; cur->previous=newnode; } return head; } /*delete from list*/ struct dir_files_status_list* delete_file(struct dir_files_status_list *head,char *filename){ struct dir_files_status_list *cur,*prev,*next; cur=head; prev=NULL; while((cur)&&(strcmp(cur->filename,filename)!=0)){ prev=cur; cur=cur->next; } if(!cur) return head; if(!prev){ prev=cur; cur=cur->next; if(cur) cur->previous=NULL; free(prev->filename); free(prev); return cur; } if(!cur->next){ prev->next=NULL; free(cur->filename); free(cur); return head; } prev->next=cur->next; next=cur->next; next->previous=prev; free(cur->filename); free(cur); return head; } /**Function of TCP Client*/ void tcp_client(){ int sock; struct sockaddr *client_addr; socklen_t client_addr_len; if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1){ perror("opening TCP socket"); exit(EXIT_FAILURE); } struct sockaddr_in sin; memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; /*Port that server listens at */ sin.sin_port = htons(6886); /* The server's IP*/ sin.sin_addr.s_addr = inet_addr("192.168.1.212"); if(connect(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == -1){ perror("tcp connect"); exit(EXIT_FAILURE); } sleep(15); send(sock, "Hello Server!", 14, 0); close(sock); } /**Function of UDP Client*/ void udp_client(){ int sock; unsigned int i = 0; struct sockaddr *client_addr; socklen_t client_addr_len; if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){ perror("opening UDP socket"); exit(EXIT_FAILURE); } struct sockaddr_in sin; memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; /*Port that server listens at */ sin.sin_port = htons(6886); /* The server's IP*/ sin.sin_addr.s_addr = inet_addr("192.168.1.212"); if(connect(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == -1){ perror("udp connect"); exit(EXIT_FAILURE); } while(i < 10){ printf("Look me, look me I do not block!!!\n"); if( sendto(sock, "Hello Server!", 14, 0, (struct sockaddr *)&sin, sizeof(struct sockaddr)) == -1){ perror("send status report"); exit(EXIT_FAILURE); } i++; sleep(1); } close(sock); } /**Function of TCP Server*/ void tcp_server(){ char buffer[512]; int sock; int accepted; int received; struct sockaddr_in sin; struct sockaddr client_addr; socklen_t client_addr_len; if((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1){ perror("opening TCP socket"); exit(EXIT_FAILURE); } memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(6886); /* Bind to all available network interfaces */ sin.sin_addr.s_addr = INADDR_ANY; if(bind(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == -1){ perror("TCP bind"); exit(EXIT_FAILURE); } if(listen(sock, 1000) == -1){ perror("TCP listen"); exit(EXIT_FAILURE); } /* Ok, a tricky part here. See man accept() for details */ client_addr_len = sizeof(struct sockaddr); while((accepted = accept(sock, &client_addr, &client_addr_len)) > 0 ){ printf("New connection accepted!\n"); received = recv(accepted, buffer, 511, 0); buffer[received] = 0; printf("Received from client: %s\n",buffer); close(accepted); } } /**Function of UDP Server*/ void udp_server(){ char buffer[512]; int sock; int accepted; int received; struct sockaddr_in sin; struct sockaddr client_addr; socklen_t client_addr_len; if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){ perror("opening UDP socket"); exit(EXIT_FAILURE); } memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(6886); /* Bind to all available network interfaces */ sin.sin_addr.s_addr = INADDR_ANY; if(bind(sock, (struct sockaddr *)&sin, sizeof(struct sockaddr_in)) == -1){ perror("UDP bind"); exit(EXIT_FAILURE); } while(1){ memset(buffer, 0, 512); if( (received = read(sock, buffer, 511)) == -1){ perror("UDP read"); exit(EXIT_FAILURE); } buffer[received] = 0; printf("Received: %s\n", buffer); printf("Going to sleep for 5 secs... Like a boss!\n"); sleep(5); } } int main(int argc, char **argv){ int opt; int scan_interval; int broadcast_port; char *client_name; char *watched_dir; DIR *dir; struct dirent *files; watched_files=NULL; /* * Initialize the mutexes */ pthread_mutex_init(&print_mutex, NULL); pthread_mutex_init(&file_list_mutex, NULL); while ((opt = getopt(argc, argv, "hn:d:i:b:")) != -1) { switch(opt){ case 'n': client_name = strdup(optarg); break; case 'd': watched_dir = strdup(optarg); /* A few checks will be nice here...*/ /* Convert the given dir to absolute path */ break; case 'i': scan_interval = atoi(optarg); break; case 'b': broadcast_port = atoi(optarg); /* To check or not to check? */ break; default: printf("Usage: cloudbox -n client_name -d directory_to_use -i scan_interval -b broadcast_port\n" "Options:\n" " -n Specifies the name of the client\n" " -d The directory absolute path, to watch for changes\n" " -i The interval time in seconds, that the client should scan for file changes\n" " -b The port that is going to be used for receiving and transmitting broadcasts UDP meesages\n" " -h prints this help\n"); exit(EXIT_FAILURE); } } printf("Cloudbox client %s:\n" "Wathced directory: %s\n" "Scan interval: %d seconds\n" "Broadcast port: %d\n", client_name, watched_dir, scan_interval, broadcast_port); dir=opendir(watched_dir);/*opens directory watched_dir and copies files in watched_files list*/ if(!dir){ printf("\nThe directory path does not exist "); exit(-1); } files=readdir( dir); while(files){ watched_files=insert_file(watched_files,files->d_name,14,"sha",0); files=readdir(dir); } while(watched_files){/*prints watched_files list*/ printf("\n%s",watched_files->filename); watched_files=watched_files->next; } udp_server(); tcp_server(); udp_client(); tcp_client(); return 0; }
C
// Mario DeCristofaro, EE222, collatz_continued HW, October 15, 2019 #include <stdio.h> #include <stdlib.h> #include "collatz_fill.h" #include "dbg.h" bool collatz_fill( int array[] ) { FILE * collatz_file; int collatz, number; // opens file collatz_file = fopen( COLLATZ_FILE, "r" ); probe( collatz_file, "Error opening file %s", collatz_file ); // read collatz numbers from file while( fscanf( collatz_file, "%d - %d", &number, &collatz) == 2 ) { array[ number - 1 ] = collatz; } // terminates array by setting the last index to 0 array[ number ] = 0; // closes file fclose( collatz_file ); return true; error: printf( "Oopsie!" ); return false; } int collatz_max( int array[] ) { int index = 1; int maxNum = 0; // loops through array and searches for max while( array[ index ] != 0 ) { // looks for new max if( array[ index ] > maxNum ) { maxNum = array[ index ]; // debugger that helped me //debug( "The max number is: %d", maxNum ); } index++; } return maxNum; } float collatz_average( int array[] ) { int index = 1; float sum = 0.0; // loops through array in search for the average while( array[index] != 0 ) { sum += array[index]; index++; } return sum/(float)index; } int collatz_greater_average( int array[] ) { int index = 1; int count = 0; float average = collatz_average( array ); // loops through array and counts how many numbers are greater than the average while( array[ index ] != 0 ) { if(array[ index ] > average) { count++; } index++; } return count; }
C
#include "sort.h" /* SCSORT.C */ scsort(scin, scout) /* called from smain.c or some other main */ FILE *scin, *scout; /* reads,sorts,timewarps each score sect in turn */ { int n; SCOREIN = scin; SCOREOUT = scout; sectcnt = 0; do if ((n = sread()) > 0) { /* allout(); */ sort(); /* textout(); */ twarp(); swrite(); } while (n > 1); sfree(); /* return all memory used */ return(0); }
C
/* Enunciado do problema: * Implemente o procedimento ordena(int v[], int n) que põe em ordem crescente o vetor v com n elementos. * A ordenação deve ser efeita por intermédio de uma árvore binária de pesquisa. */ typedef struct NoABP { int chave; struct NoABP *esq; struct NoABP *dir; } NoABP; NoABP *alocaNo(int k); NoABP *insereNo(NoABP **raiz, int k); NoABP *passaVetorParaABP(int vetor[], int n, NoABP **raiz); int abp_sort(NoABP *raiz, int v[], int i); void ordena(int v[], int n);
C
#include "holberton.h" /** * times_table - prints times table up to 9 * * Return: Always 0. */ void times_table(void) { int r, d, m, n, p, s; for (m = 0; m < 10; m++) { for (n = 0; n < 10; n++) { r = m * n; d = m * (n + 1); p = r / 10; s = r % 10; if (r >= 10) { _putchar(p + '0'); _putchar(s + '0'); } else { _putchar(r + '0'); } if (d >= 10 && n != 9) { _putchar(','); _putchar(' '); } else if (n != 9) { _putchar(','); _putchar(' '); _putchar(' '); } } _putchar('\n'); } }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "st.h" SequentialSearchST *get_sst() { SequentialSearchST *st = (SequentialSearchST *) malloc(sizeof(SequentialSearchST)); st->size = 0; st->first = NULL; return st; } int sst_size(SequentialSearchST *st) { return st->size; } int sst_empty(SequentialSearchST *st) { return st->size == 0; // return st->first == NULL; } int sst_contains(SequentialSearchST *st, char *key) { return sst_get(st, key) != NULL; } int sst_get(SequentialSearchST *st, char *key) { if(key == NULL) { printf("key of sst_get() is null"); exit(-1); } STNode *x; for(x=st->first; x!=NULL; x=x->next) { if(strcmp(x->key, key) == 0) { return x->value; } } return NULL; } STNode *sst_get_node(SequentialSearchST *st, char *key) { if(key == NULL) { printf("key of sst_get_node() is null"); exit(-1); } STNode *x = st->first; for(; x!= NULL; x=x->next) { if(strcmp(key, x->key) == 0) { return x; } } return NULL; } void sst_put(SequentialSearchST *st, char *key, int value) { if(key == NULL) { printf("key to sst_put() is null"); exit(-1); } if(value == NULL) { sst_delete(st, key); return; } STNode *x; for(x=st->first; x!=NULL; x=x->next) { if(strcmp(key, x->key) == 0) { x->value = value; return; } } STNode *tmp = (STNode *) malloc(sizeof(STNode)); tmp->key = key; tmp->value = value; tmp->next = st->first; st->first = tmp; st->size++; } void sst_delete(SequentialSearchST *st, char *key) { if(key == NULL) { printf("key of sst_delete() is null"); exit(-1); } int found = 1; STNode *pre = NULL, *cur = st->first; for(; cur!=NULL; pre=cur, cur=cur->next) { if(strcmp(key, cur->key) == 0){ found=0; break; } } if(found == 1) return; // contains key, begin delete if(pre == NULL) { st->first = st->first->next; // cur = cur->next; st->size--; return; } pre->next = cur->next; st->size--; } void sst_display(SequentialSearchST *st) { STNode *x = st->first; int i; for(i=0; i<st->size; i++) { printf("[%s, %d]->", x->key, x->value); x = x->next; } printf("NULL\n"); }
C
#include "Listas.h" #include <stdlib.h> struct Entidad { double x,y,vel_x,vel_y,radio,dat; int estado; }; struct Nodo { Lista_Entidad Elemento; struct Nodo* Sig; }; Listas_NodoPtr Listas_crear() { Listas_NodoPtr p = malloc(sizeof(struct Nodo)); p->Sig = NULL; return p; } void Listas_Insertar_crear(Listas_NodoPtr p, double x, double y, double vel_x, double vel_y, double radio, double dat, int estado) { Lista_Entidad e; e.x = x; e.y = y; e.vel_x = vel_x; e.vel_y = vel_y; e.radio = radio; e.dat= dat; e.estado = estado; Listas_Insertar_Inicio(p, e); } void Listas_Insertar_Inicio(Listas_NodoPtr p, Lista_Entidad e) { Listas_NodoPtr aux = malloc(sizeof(struct Nodo)); aux->Elemento = e; aux->Sig = p->Sig; p->Sig = aux; } void Listas_SuprimeNodo(Listas_NodoPtr q) { Listas_NodoPtr aux = q->Sig; q->Sig = q->Sig->Sig; free(aux); } Listas_NodoPtr Listas_siguiente(Listas_NodoPtr p) { return p->Sig; } Lista_Entidad* Lista_elemento(Listas_NodoPtr p) { return &(p->Sig->Elemento); } /* double x,y,vel_x,vel_y,radio,dat; int estado; */ double Listas_obtener_x(Listas_NodoPtr p) { return p->Sig->Elemento.x; } double Listas_obtener_y(Listas_NodoPtr p) { return p->Sig->Elemento.y; } double Listas_obtener_vel_x(Listas_NodoPtr p) { return p->Sig->Elemento.vel_x; } double Listas_obtener_vel_y(Listas_NodoPtr p) { return p->Sig->Elemento.vel_y; } double Listas_obtener_radio(Listas_NodoPtr p) { return p->Sig->Elemento.radio; } double Listas_obtener_dat(Listas_NodoPtr p) { return p->Sig->Elemento.dat; } int Listas_obtener_estado(Listas_NodoPtr p) { return p->Sig->Elemento.estado; } void Listas_cambiar_x(Listas_NodoPtr p, double d) { p->Sig->Elemento.x = d; } void Listas_cambiar_y(Listas_NodoPtr p, double d) { p->Sig->Elemento.y = d; } void Listas_cambiar_vel_x(Listas_NodoPtr p, double d) { p->Sig->Elemento.vel_x = d; } void Listas_cambiar_vel_y(Listas_NodoPtr p, double d) { p->Sig->Elemento.vel_y = d; } void Listas_cambiar_radio(Listas_NodoPtr p, double d) { p->Sig->Elemento.radio = d; } void Listas_cambiar_dat(Listas_NodoPtr p, double d) { p->Sig->Elemento.dat = d; } void Listas_cambiar_estado(Listas_NodoPtr p, int d) { p->Sig->Elemento.estado = d; } void Listas_liberar(Listas_NodoPtr p) { while(p != NULL) { Listas_NodoPtr aux = p; p = p->Sig; free(aux); } }
C
#include <stdio.h> int main(void) { int i = 1; while (i < 11) { printf("Hello, world %i!\n", i); i++; } }
C
#include <stdio.h> #include <limits.h> #include <float.h> int main() { printf("The value of INT_MAX is %i\n", INT_MAX); printf("The value of INT_MIN is %i\n", INT_MIN); printf("An int takes %zu bytes\n", sizeof(int)); printf("The value of FLT_MAX is %i\n", FLT_MAX); printf("The value of FLT_MIN is %i\n", FLT_MIN); printf("A float takes %zu bytes\n", sizeof(float)); printf("The value of CHAR_MAX is %i\n", CHAR_MAX); printf("The value of CHAR_MIN is %i\n", CHAR_MIN); printf("A char takes %zu bytes\n", sizeof(char)); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct node{ int val; struct node* next; }node; typedef struct _list { int size; node* head; }list; node* newnode(int data){ //fill here node *tmp = (node *)malloc(sizeof(node)); tmp->val = data; tmp->next = NULL; return tmp; } list* init_list(); void appendTo(list* list, node* newnode); void add(list* list, node* newnode, int idx); void removed(list* list, int idx); void print_list(list* list); int main(int argc, char const *argv[]){ list* linked = init_list(); for(int i = 0; i < 6; i++){ appendTo(linked, newnode(i)); } print_list(linked); removed(linked, -1); print_list(linked); add(linked, newnode(10), 3); print_list(linked); add(linked, newnode(11), 20); print_list(linked); removed(linked, 5); print_list(linked); removed(linked, 0); print_list(linked); add(linked, newnode(12), 0); print_list(linked); return 0; } /* initialize single linked list */ list* init_list(){ list* tmp = malloc(sizeof(list)); tmp->size = 0; tmp->head = NULL; return tmp; } void appendTo(list *list, node *newnode) { //fill here if (list->size == 0) { list->head = newnode; list->size++; } else if (list->size == 1) { list->head->next = newnode; list->size++; } else { // list->size > 1 node *current = list->head; while (current->next != NULL) { current = current->next; } current->next = newnode; list->size++; } } /* add a new node at idx */ void add(list* list, node* newnode, int idx){ //fill here int cnt = 0; node *tmp = (node*)malloc(sizeof(node)); if (list->size > idx) { if(idx==0){ tmp=list->head; list->head = newnode; list->head->next = tmp; list->size++; } else { node *current= list->head; while(current->next != NULL) { if(cnt == idx) { tmp = current->next; current->next = newnode; current->next->next = tmp; list->size++; } current = current->next; cnt++; } } } } /* removed the node at idx */ void removed(list* list, int idx){ //fill here int cnt = 0; node *tmp=(node *)malloc(sizeof(node)); if(list->size > idx && idx > -1) { node *current = list->head; if(idx == 0) { list->head = list->head->next; list->size--; } else { while(current->next != NULL) { if(cnt == idx -1) { tmp = current->next; current->next = current->next->next; list->size--; free(tmp); } current = current->next; cnt++; } } } } /* print all values of nodes in your single linked list */ void print_list(list* list){ //fill here //Show list size and list number in order printf("list size = %d\n",list->size); node *current = list->head; while (current->next != NULL) { printf("%d ",current->val); current = current->next; } printf("%d",current->val); printf("\n"); }
C
#include<stdio.h> #include<string.h> //include string library /*Function to check if the charcter in string1 is already present in string 2 The function takes a char variable, a char array and an integer*/ int ifexists(char c,char temp[],int z){ int k; for(k=0;k<z;k++){ if(temp[k]==c) return 1; } return 0; } void main(){ char string1[30],string2[30]; //Define two strings. sting1 will hold the input string and string2 will be used to check for repetition int n,i,x; printf("Enter the string\n"); //Ask user to input a string scanf("%s",string1); //store the value in string1 variable n= strlen(string1); //store the length of entered string in variable n string2[0]=string1[0]; // assign the first character of string1 to string2 x = 1; /*Compare each of the characters in string1 to all the characters in string2*/ for (i=1;i<n;i++){ if(ifexists(string1[i],string2,x)) //If a retpeating character is found, the function returns 1 and the if loop is executed { printf("The first repeating letter in %s is %c\n",string1,string1[i]); //Print the repeating character break; } else{ string2[x]=string1[i]; //if the character in string1 is not in string2, add the character to string2 x++; } } if(i==n){ printf("There are no repeating characters\n"); } }
C
#include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <time.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #define MAXIMUM_TESTS 15 #define RAND_MAX 1000 int main() { printf("*** Testing Stward Card ***\n"); int k[10] = {adventurer, council_room, feast, gardens, mine, steward, smithy, village, baron, great_hall}; int i; int j; int p = 0; int players; //int player; int seed; int choice; int startcards; int endcards; // int discard; // int old_discard; struct gameState g; for (i = 1; i <= MAXIMUM_TESTS; i++){ m[i] =0; seed = rand(); players = rand()%3+1; choice = rand()%3; initializeGame(players, k, seed, &g); g.deckCount[players] = rand() % MAX_DECK; g.discardCount[players] = rand() % MAX_DECK; g.handCount[players] = rand() % MAX_HAND; startcards = g.deckCount[players] + g.handCount[players]; // old_discard = g.discardCount[players]; j=stewardcard(choice,1,2, &g,0,players); if (j == 0){ printf("*** card run Test %d Passed \n", i); } else{ printf("*** card run Test %d Failed \n", i); p++; } endcards =g.deckCount[players] + g.handCount[players]; // discard = g.discardCount[players]; if (endcards != startcards){ printf("*** card ammount Test %d Passed\n", i); } else{ printf("*** card ammount Test %d Failed \n", i); p++; } // if (discard != old_discard){ // printf("*** discard ammount Test %d Passed\n", i); // } // else{ // printf("*** discard ammount Test %d Failed \n", i); // p++; // } } printf("*** End of Test, %d Tests Failed ****\n", p); return 0; }
C
#include <unistd.h> #include <stdlib.h> #include <signal.h> #include <stdio.h> #include <time.h> #define GAME_TIMEOUT 10 void timer_handler(){ printf("Tempo scaduto !"); exit(EXIT_FAILURE); } int main(int argc, char *argv[]){ struct sigaction act; int number, guess; char guess_str[2]; //set timer_handler as handler for the signal SIGALRM(TIMER) //and clear the list of signals to block during //the handler execution act.sa_flags = 0; act.sa_handler = timer_handler; sigemptyset(&act.sa_mask); sigaction(SIGALRM, &act, NULL); //generate a random number between 0 and 99 srand((int)time(NULL)); number = rand()%100; //schedule alarm after 10 seconds alarm(GAME_TIMEOUT); while(1){ printf("inserisci un numero: "); scanf("%d", &guess); if(guess == number){ printf("Hai indovinato, il numero è: %d \n", number); exit(EXIT_SUCCESS); } else if(guess < number){ printf("minore\n"); } else { printf("maggiore \n"); } } }
C
#include <stdio.h> main() { int alunos; float nota1, nota2, media; alunos=1; while (alunos<=10) { printf("Digite a primeira e a segunda nota do aluno %d: \n", alunos); scanf("%f %f", &nota1, &nota2); media=(nota1+nota2)/2; printf("A media do aluno %d eh %.2f.\n\n", alunos, media); alunos=alunos+1; } }
C
/* 25/08/18 – Autor: Cassio Algoritmo escrito em C que encontra e imprime os numeros primos presentes entre 1 e 200. Calcula e imprime a quantidade total de numeros encontrados nesse intevaldo */ #include <stdio.h> int main(){ int quantidade = 0; int contador = 0; int contadorPrimos = 0; int soma = 0; for (int i = 1; i <= 20; i++) { quantidade = quantidade + 1; contador = 0; for (int j = 1; j <= i; j++){ if (i % j == 0){ contador++; } } if (contador == 2) { printf("Primo %d: \n", i); contadorPrimos = contadorPrimos + 1; soma += i; } } printf("A soma eh: %d \n", soma); printf("Total de primos encontrados entre 1 e 20: %d \n", contadorPrimos); return 0; }
C
#include<stdio.h> #include<string.h> #include<ctype.h> /*STRUCTURE*/ typedef struct { char idno[13]; char name[50]; char gender; char res_status; float cgpa; char emailaddress[33]; } STUDENT; STUDENT arr[6]; /*PROTOTYPES*/ void populate_records(STUDENT arr[]); void generate_email_address(char id[],char email[]); void print_records(STUDENT arr[]); void sort_strings(char *idnos[], int n); float cal_avg_cgpa(STUDENT arr[]); /*MAIN()*/ void main() { populate_records(arr); /*STUDENT Is a Datatype*/ print_records(arr); printf("\n The Average CGPA Of all Students Is: %f ", cal_avg_cgpa(arr)); } /*GENERATE EMAIL()*/ void generate_email_addr(char idno[], char email[]) { int i=0,j,count=0; for(i=1,j=0;j<4;i++,j++) email[i]=idno[j]; for(i=8,j=5;i<11;i++,j++) email[j]=idno[i]; email[j+1]='\0'; email[0]='f'; email=strcat(email,"@dubai.bits-pilani.ac.in"); printf("\n Th Email Address Is: %s",email); } /*POPULATE()*/ void populate_records(STUDENT arr[]) { int i=0; for(i=0; i<6; i++) { scanf("%[^,]s",arr[i].idno); getchar(); scanf("%[^,]s",arr[i].name); getchar(); scanf("%[^,]c",arr[i].gender); getchar(); scanf("%[^,]c",arr[i].res_status); getchar(); scanf("%f",arr[i].cgpa); getchar(); //There is a \n at the end of each record } } /*PRINTING()*/ void print_records(STUDENT arr[]) { int i=0; for(i=0; i<6; i++) { printf("%s %s",arr[i].idno,arr[i].name); getchar(); printf("\n Gender: %c",arr[i].gender); printf("\n Residence Status: %c",arr[i].res_status); printf("\n CGPA: %f",arr[i].cgpa); generate_email_addr(arr[i].idno, arr[i].emailaddress); } } /*AVERAGE CGPA OF 6 STUDENTS*/ float cal_avg_cgpa(STUDENT arr[]) { float sum=0,avg; int i; for(i=0; i<6; i++) sum=sum+arr[i].cgpa; avg=sum/6; return avg; }
C
/* @file prim.c * @author Andrei Negret - grupa CR 1.3. A * @brief implementeaza functiile necesare pentru algoritmul lui Prim */ #include <stdio.h> #include <stdlib.h> #include <limits.h> #include "prim.h" /* Functie folosita pentru a gasi pentru un varf costul minim al unei muchii * formata de acel varf impreuna cu alte noduri si care nu afla in multimea MST(varfurile care afla deja in arborele partial de cost minim) * @param list lista de varfuri * @param mstSet multimea de varfuri care se afla deja in arbore * @param V numarul de varfuri din graf */ int computeMinimumCostEdge(int list[], int mstSet[], int V){ int min = INT_MAX, index, i; for(i = 0; i < V; i++){ if(list[i] && min > list[i] && !mstSet[i]){ min = list[i]; index = i; } } return index; } /* Calculeaza arborele partial de cost minim folosind algoritmul lui Prim * @param verticesList lista de varfuri * @param adjancencyLists array-ul de liste de adiacenta reprezentand graful * @param minimumSpanningTree referinta catre arborele de cost minim care va fi calculat de algoritm * @param V numarul de varfuri din graf */ int prim(vertex *verticesList, int **adjancencyLists, int *mstSet, vertex *minimumSpanningTree, int V) { int i, j, k = 0; // Alege un varf aleator prima data int currentVertexIndex = rand() % V; mstSet[currentVertexIndex] = 1; minimumSpanningTree[k++] = verticesList[currentVertexIndex]; for(i = 0; i < V-1; i++){ currentVertexIndex = computeMinimumCostEdge(adjancencyLists[currentVertexIndex], mstSet, V); if(mstSet[currentVertexIndex] == 1){ for(j = 0; j < V; j++){ if(!mstSet[verticesList[j].index]){ currentVertexIndex = verticesList[j].index; break; } } } mstSet[currentVertexIndex] = 1; minimumSpanningTree[k++] = verticesList[currentVertexIndex]; } return k; } /* Citeste graful ca liste de adiacenta alocand dinamic resursele necesare * @param verticesList lista de varfuri * @param adjancencyLists array-ul de liste de adiacenta reprezentand graful * @param mstSet multimea de varfuri care se afla deja in arbore * @param V numarul de varfuri din graf */ void readGraph(vertex *verticesList, int **adjancencyLists, int *mstSet, int V){ int i, j; for(i = 0; i < V; i++){ vertex v; mstSet[i] = 0; printf("Varf : "); scanf("%s", v.label); v.index = i; verticesList[i] = v; adjancencyLists[i] = malloc(V * sizeof(int)); printf("Lista de adiacenta pentru %s : \n", v.label); for(j = 0; j < V; j++){ if(j != i) { scanf("%d", &adjancencyLists[i][j]); } } } printf("\n"); for(i = 0; i < V; i++){ printf("%s -> ", verticesList[i].label); for(j = 0; j < V; j++){ if(i != j){ printf("%d ", adjancencyLists[i][j]); } } printf("\n"); } } /* Afiseaza arborele partial de cost minim * */ void print(vertex *minimumSpanningTree, int k){ printf("\nArborele de cost minim : \n"); int i; for(i = 0; i < k; i++){ printf("%s", minimumSpanningTree[i].label); if(i < k - 1){ printf(" -> "); } } } /* Elibereaza resursele alocate dinamic * @param verticesList lista de varfuri * @param adjancencyLists array-ul de liste de adiacenta reprezentand graful * @param mstSet multimea de varfuri care se afla deja in arbore * @param minimumSpanningTree arborele de cost minim * @param V numarul de varfuri din graf */ //Elibereaza resursele alocate dinamic void freeResources(int **adjancencyLists, vertex *verticesList, int *mstSet, vertex *minimumSpanningTree, int V){ int i; for(i = 0; i < V; i++){ free(adjancencyLists[i]); } free(adjancencyLists); free(verticesList); free(mstSet); free(minimumSpanningTree); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include"m_seqlist.h" void init_seqlist(pseq seq) { assert(seq); seq->arr = (Datatype *)malloc(3*sizeof(Datatype));//ȷ3ռ if(NULL == seq->arr) { printf("out of memory.\n"); exit(1); } else { memset(seq->arr,0,3*sizeof(Datatype)); seq->size = 0; seq->capacity = 3; } } void check_capacity(pseq seq) { Datatype *temp = NULL; assert(seq); if(seq->size >= seq->capacity)//˵ˣҪ { temp = (Datatype *)realloc(seq->arr,(3+seq->capacity*2)*sizeof(Datatype)); if(NULL == temp) { printf("out of memory.\n"); exit(1); } else { seq->arr = temp; seq->capacity += 3+seq->capacity*2; } } } void print_seqlist(pseq seq) { int i = 0; assert(seq); for(i=0; i<seq->size; i++) { printf("%d->",seq->arr[i]); } printf("end\n"); } void pushback(pseq seq,Datatype x) { assert(seq); check_capacity(seq); seq->arr[seq->size++] = x; printf("ɹ\n"); } void popback(pseq seq) { assert(seq); if(seq->size==0) printf("˳ѿ\n"); else { //1 seq->size--;//һԪɾ ////2:òʵ //erase(seq,seq->size-1); printf("ɾɹ\n"); } } void pushfront(pseq seq,Datatype x) { int i = 0; assert(seq); check_capacity(seq); // //1(˳Ԫ˳޹) //seq->arr[seq->size]=seq->arr[0];//Ԫر浽λ //seq->arr[0]=x; //seq->size++; ////2:ò뺯 //insert(seq,0,x); ////3: //int i = 0; //for(i=seq->size; i>0; i--)//ƶԪ //{ // seq->arr[i] = seq->arr[i-1]; //} //seq->arr[0] = x;//Ԫ //seq->size++; //4: for(i=seq->size-1; i>=0; i--)//ƶԪ { seq->arr[i+1] = seq->arr[i]; } seq->arr[0] = x;//Ԫ seq->size++; printf("ɹ\n"); } void popfront(pseq seq) { assert(seq); if(seq->size == 0) printf("˳ѿ\n"); else { // //1(˳Ԫ˳޹) //seq->arr[0]=seq->arr[seq->size-1];//Ԫر浽 //seq->size--; ////2ֱӵò //erase(seq,0); ////3: //int i = 0; //for(i=0; i<seq->size-1; i++)//ƶԪ //{ // seq->arr[i] = seq->arr[i+1]; //} //seq->size--; //4: int i = 0; for(i = 1; i<seq->size; i++)//ƶԪ { seq->arr[i-1] = seq->arr[i]; } seq->size--; } printf("ɾɹ\n"); } void insert(pseq seq,int pos,Datatype x) { int i = 0; assert(seq); check_capacity(seq); ////1: // int i = 0; //for(i=seq->size; i>pos; i--) //{ // seq->arr[i] = seq->arr[i-1]; //} //seq->arr[pos] = x; //seq->size++; //2: for(i=seq->size-1; i>=pos; i--) { seq->arr[i+1] = seq->arr[i]; } seq->arr[pos] = x; seq->size++; printf("ɹ\n"); } void erase(pseq seq,int pos) { assert(seq); if(seq->size==0) printf("˳ѿ\n"); else { int i = 0; for(i=pos; i<seq->size-1; i++) { seq->arr[i] = seq->arr[i+1]; } seq->size--; printf("ɹ\n"); } } int find(pseq seq,Datatype x) { int i = 0; assert(seq); for(i=0; i<seq->size; i++) { if(seq->arr[i] == x) return i;//״γλõ± } return -1; } void remmove(pseq seq,Datatype x) { assert(seq); if(seq->size==0) printf("˳ѿ\n"); else { int i = 0; for(i=0; i<seq->size; i++) { if(seq->arr[i]==x) { int j = 0; for(j=i; j<seq->size; j++)//ƶԪ { seq->arr[j]=seq->arr[j+1]; } } } seq->size--; printf("ɾɹ\n"); } } void remmove_all(pseq seq,Datatype x) { assert(seq); if(seq->size==0) printf("˳ѿ\n"); else { // //1:һɾһ //int i = 0; //int count = 0; //for(i=0; i<seq->size; ++i) //{ // if(seq->arr[i] == x) // { // int j = 0; // for(j=i; j<seq->size; j++)//ƶԪ // { // seq->arr[j]=seq->arr[j+1]; // } // seq->size--; // } //} //2 int i = 0; int count = 0; assert(seq); for(i=0; i<seq->size; i++) { seq->arr[i-count]=seq->arr[i]; if(seq->arr[i] == x) count++; } seq->size-=count; } printf("ɾɹ\n"); } void empty(pseq seq) { assert(seq); if(seq->size == 0) printf("˳Ϊ\n"); else printf("˳Ϊ\n"); } int size(pseq seq) { assert(seq); return seq->size; } void bubble_sort(pseq seq) { // //ͨд //int i = 0; //int flag = 0; //assert(seq); //for(i=0; i<seq->size-1; i++) //{ // int j = 0; // flag = 0; // for(j=0; j<seq->size-1-i; j++) // { // if(seq->arr[j]>seq->arr[j+1])// // { // Datatype temp = seq->arr[j]; // seq->arr[j] = seq->arr[j+1]; // seq->arr[j+1] = temp; // flag = 1; // } // } // if(flag == 0) // break; //} //ѡ int option = 0; int i = 0; int flag = 0; assert(seq); printf("ѡ:(0. 1.)"); scanf("%d",&option); for(i=0; i<seq->size-1; i++) { int j = 0; flag = 0; for(j=0; j<seq->size-1-i; j++) { if(option == 0) { if(seq->arr[j]>seq->arr[j+1])// { Datatype temp = seq->arr[j]; seq->arr[j] = seq->arr[j+1]; seq->arr[j+1] = temp; flag = 1; } } else if(option == 1) { if(seq->arr[j]<seq->arr[j+1])// { Datatype temp = seq->arr[j]; seq->arr[j] = seq->arr[j+1]; seq->arr[j+1] = temp; flag = 1; } } } if(flag == 0) break; } printf("ɹ\n"); } void select_sort(pseq seq) { ; } //int binary_search(pseq seq,Datatype x)//˳Ѿк //{ // int left = 0; // int right = 0; // int mid = 0; // assert(seq); // ////1ǰպ // /*right = seq->size-1; // while(left <= right) // { // mid = left + ((right - left)>>1); // if(seq->arr[mid] > x) // right = mid-1; // else if(seq->arr[mid] < x) // left = mid+1; // else // return mid; // } // return -1;*/ // // ////2:ǰպ // //right = seq->size; // //while(left < right) // //{ // // mid = (left & right)+((left ^ right)>>1); // // if(seq->arr[mid] > x) // // right = mid; // // else if(seq->arr[mid] < x) // // left = mid+1; // // else // // return mid; // //} // //return -1; //} //3:ݹʵ int binary_search(pseq seq,int left,int right,Datatype x)//˳Ѿк { int mid = 0; assert(seq); if(left > right) return -1; mid = left + ((right - left)>>1); if(seq->arr[mid] > x) return binary_search(seq,left,mid-1,x); else if(seq->arr[mid] < x) return binary_search(seq,mid+1,right,x); else return mid; } void clear(pseq seq) { assert(seq); seq->size = 0; } void destroy(pseq seq) { assert(seq); free(seq->arr); seq->arr = NULL; }
C
#include <stdio.h> #include <stdlib.h> int main() { int dizi1[3][3]={{1,1,1},{2,2,2},{3,3,3}}; int dizi2[3][3]={{2,2,2},{1,1,1},{3,3,3}}; int toplam=0; int carpim[3][3]; for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ toplam += (dizi1[i][j]*dizi2[j][i]); } for(int j=0;j<3;j++){ carpim[i][j] = toplam; } toplam = 0; } for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ printf("%d ",carpim[i][j]); } printf("\n"); } return 0; }
C
typedef char Itemp; typedef struct pilha { int max; int topo; Itemp *item; } *Pilha; Pilha pilha( int m ) { Pilha P = malloc( sizeof( struct pilha ) ); P->max = m; P->topo = -1; P->item = malloc( m * sizeof( Itemp )); } int vaziap( Pilha P ) { if ( P->topo == -1 ) return 1; else return 0; } int cheiap( Pilha P ) { if ( P->topo == P->max - 1 ) return 1; else return 0; } void empilha( Itemp x, Pilha P ) { if( cheiap( P ) ) { puts( "pilha cheia!" ); abort(); } P->topo++; P->item[ P->topo ] = x; } Itemp desempilha( Pilha P ){ if( vaziap( P ) ) { puts( "Pilha vazia!" ); abort(); } Itemp x = P->item[ P->topo ]; P->topo--; return x; } Itemp topo( Pilha P ) { if ( vaziap( P ) ) { puts( "Pilha vazia!" ); abort(); } return P->item[ P->topo ]; } void destroip( Pilha *Q ) { free( (*Q)->item ); free(*Q); *Q = NULL; }
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define MAX_RESOURCES 5 #define OK 0 #define FAILED -1 pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int available_resources = MAX_RESOURCES; int decrease_count(int count) { int ret = OK; pthread_mutex_lock(&mtx); if (available_resources < count) { printf("failed to take %d from %d\n", count, available_resources); ret = FAILED; } else { printf("Got %d, remaining %d\n", count, available_resources - count); available_resources -= count; } pthread_mutex_unlock(&mtx); return ret; } int increase_count(int count) { pthread_mutex_lock(&mtx); available_resources += count; pthread_mutex_unlock(&mtx); return OK; } void* thfunc(void* arg) { pthread_mutex_lock(&mtx); int res = rand() % MAX_RESOURCES+1; pthread_mutex_unlock(&mtx); printf("want %d\n", res); for (int i = 0; i < 10; i++) { while (decrease_count(res) == FAILED) {} increase_count(res); sleep(1); } } int main() { srand(time(0)); pthread_t th[10]; for (int i = 0; i < 10; i++) { pthread_create(&th[i], NULL, &thfunc, NULL); } for (int i = 0; i < 10; i++) { pthread_join(th[i], NULL); } return 0; }
C
/* BOJ - 2309 ϰ */ #include <stdio.h> int nine[9], seven[7]; void init() { int i; for (i = 0; i < 7; i++) { seven[i] = 0; nine[i] = 0; } nine[7] = 0; nine[8] = 0; } void getnine() { int i; for (i = 0; i < 9; i++) scanf("%d", &nine[i]); } void find() { int i, j, tmp; tmp = 0; for (i = 0; i < 9; i++) tmp += nine[i]; for (i = 0; i < 8; i++) { for (j = i + 1; j < 9; j++) { if (tmp - nine[i] - nine[j] == 100) { nine[i] = 0; nine[j] = 0; break; } } if (nine[i] == 0 && nine[j] == 0) break; } for (i = 0, j = 0; i < 9; i++) { if (nine[i] != 0) { seven[j] = nine[i]; j++; } } for (i = 1; i < 7; i++) { for (j = 0; j < 7 - i; j++) { if (seven[j] > seven[j + 1]) { tmp = seven[j]; seven[j] = seven[j + 1]; seven[j + 1] = tmp; } } } for (i = 0; i < 7; i++) printf("%d\n", seven[i]); } int main() { init(); getnine(); find(); return 0; }
C
/* * Ex1.c * * Created on: Jul 29, 2021 * Author: Dyno */ #include <stdio.h> int main() { int a,b; printf("two intg : "); scanf("%d %d",&a,&b); a=a+b; b=a-b; a=a-b; printf("a:%d b:%d",a,b); return 0; }
C
#include "dawm.h" #define MW(N, NM, W, MF) ((N > NM) ? (NM ? (W * MF) : 0) : W) #define MH(N, NM, H, MF) ((N > NM) ? (NM ? (H * MF) : 0) : H) /** Callback struct */ struct layout_cb { void (*arrange) (struct layout *); void (*client_added) (struct layout *); void (*client_removed) (struct layout *); void (*clients_changed) (struct layout *, unsigned); void (*geom_changed) (struct layout *, int, int); void (*mfact_changed) (struct layout *, float); void (*nmaster_changed) (struct layout *, int); }; void layout_allocate_pos(struct layout *, unsigned); /* Horizontal layout functions */ void horz_arrange(struct layout *); void horz_client_added(struct layout *); void horz_client_removed(struct layout *); void horz_clients_changed(struct layout *, unsigned); void horz_geom_changed(struct layout *, int, int); void horz_mfact_changed(struct layout *, float); void horz_nmaster_changed(struct layout *, int); /* Vertical layout functions */ void vert_arrange(struct layout *); void vert_client_added(struct layout *); void vert_client_removed(struct layout *); void vert_clients_changed(struct layout *, unsigned); void vert_geom_changed(struct layout *, int, int); void vert_mfact_changed(struct layout *, float); void vert_nmaster_changed(struct layout *, int); /* Max layout functions */ void max_arrange(struct layout *); void max_client_added(struct layout *); void max_client_removed(struct layout *); void max_clients_changed(struct layout *, unsigned); void max_geom_changed(struct layout *, int, int); /** Callbacks */ static struct layout_cb callbacks[LASTLayout] = { { .arrange = horz_arrange, .client_added = horz_client_added, .client_removed = horz_client_removed, .clients_changed = horz_clients_changed, .geom_changed = horz_geom_changed, .mfact_changed = horz_mfact_changed, .nmaster_changed = horz_nmaster_changed }, { .arrange = vert_arrange, .client_added = vert_client_added, .client_removed = vert_client_removed, .clients_changed = vert_clients_changed, .geom_changed = vert_geom_changed, .mfact_changed = vert_mfact_changed, .nmaster_changed = vert_nmaster_changed }, { .arrange = max_arrange, .client_added = max_client_added, .client_removed = max_client_removed, .clients_changed = max_clients_changed, .geom_changed = max_geom_changed, .mfact_changed = NULL, .nmaster_changed = NULL } }; void horz_arrange(struct layout *layout) { struct layout_pos *pos; unsigned int i, mw, my, ty; mw = MW(layout->n, layout->nmaster, layout->ww, layout->mfact); for (i = my = ty = 0, pos = layout->pos; i < layout->n; i++, pos++) { if (i < layout->nmaster) { pos->x = 0; pos->y = my; pos->w = mw; pos->h = (layout->wh - my) / (MIN(layout->n, layout->nmaster) - i); my += pos->h; } else { pos->x = mw; pos->y = ty; pos->w = layout->ww - mw; pos->h = (layout->wh - ty) / (layout->n - i); ty += pos->h; } } } void horz_client_added(struct layout *layout) { /* TODO */ layout_allocate_pos(layout, layout->n + 1); horz_arrange(layout); } void horz_client_removed(struct layout *layout) { /* TODO */ if (layout->n > 0) { layout_allocate_pos(layout, layout->n - 1); horz_arrange(layout); } } void horz_clients_changed(struct layout *layout, unsigned n) { /* TODO */ layout_allocate_pos(layout, n); horz_arrange(layout); } void horz_geom_changed(struct layout *layout, int ww, int wh) { /* TODO: handle width and height diffs instead of re-arranging */ layout->ww = ww; layout->wh = wh; horz_arrange(layout); } void horz_mfact_changed(struct layout *layout, float mfact) { struct layout_pos *pos; unsigned int i, mw; mw = MW(layout->n, layout->nmaster, layout->ww, mfact); for (i = 0, pos = layout->pos; i < layout->n; i++, pos++) { if (i < layout->nmaster) { pos->w = mw; } else { pos->x = mw; pos->w = layout->ww - mw; } } } void horz_nmaster_changed(struct layout *layout, int nmaster) { /* TODO */ } void vert_arrange(struct layout *layout) { struct layout_pos *pos; unsigned int i, mh, mx, tx; mh = MH(layout->n, layout->nmaster, layout->wh, layout->mfact); for (i = mx = tx = 0, pos = layout->pos; i < layout->n; i++, pos++) { if (i < layout->nmaster) { pos->x = mx; pos->y = 0; pos->w = (layout->ww - mx) / (MIN(layout->n, layout->nmaster) - i); pos->h = mh; mx += pos->w; } else { pos->x = tx; pos->y = mh; pos->w = (layout->ww - tx) / (layout->n - i); pos->h = layout->wh - mh; tx += pos->w; } } } void vert_client_added(struct layout *layout) { /* TODO */ layout_allocate_pos(layout, layout->n + 1); vert_arrange(layout); } void vert_client_removed(struct layout *layout) { /* TODO */ if (layout->n > 0) { layout_allocate_pos(layout, layout->n - 1); vert_arrange(layout); } } void vert_clients_changed(struct layout *layout, unsigned n) { /* TODO */ layout_allocate_pos(layout, n); vert_arrange(layout); } void vert_geom_changed(struct layout *layout, int ww, int wh) { /* TODO: handle width and height diffs instead of re-arranging */ layout->ww = ww; layout->wh = wh; vert_arrange(layout); } void vert_mfact_changed(struct layout *layout, float mfact) { struct layout_pos *pos; unsigned int i, mh; mh = MH(layout->n, layout->nmaster, layout->wh, mfact); for (i = 0, pos = layout->pos; i < layout->n; i++, pos++) { if (i < layout->nmaster) { pos->h = mh; } else { pos->y = mh; pos->h = layout->wh - mh; } } } void vert_nmaster_changed(struct layout *layout, int nmaster) { /* TODO */ } void max_arrange(struct layout *layout) { struct layout_pos *pos; unsigned int i = 0; for (i = 0, pos = layout->pos; i < layout->n; i++, pos++) { pos->x = pos->y = 0; pos->w = layout->ww; pos->h = layout->wh; } } void max_client_added(struct layout *layout) { layout_allocate_pos(layout, layout->n + 1); max_arrange(layout); } void max_client_removed(struct layout *layout) { if (layout->n > 0) { layout_allocate_pos(layout, layout->n - 1); max_arrange(layout); } } void max_clients_changed(struct layout *layout, unsigned n) { layout_allocate_pos(layout, n); max_arrange(layout); } void max_geom_changed(struct layout *layout, int ww, int wh) { /* TODO: handle width and height diffs instead of re-arranging */ layout->ww = ww; layout->wh = wh; max_arrange(layout); } struct layout * layout_init(LayoutID id, int mw, int mh, int ww, int wh, int nmaster, float mfact) { struct layout *layout = xcalloc(1, sizeof(struct layout)); assert(id < LASTLayout); layout->pos = NULL; layout->n = 0; layout->mw = mw; layout->mh = mh; layout->ww = ww; layout->wh = wh; layout->mfact = mfact; layout->nmaster = nmaster; layout->id = id; return layout; } void layout_add_client(struct layout *layout) { if (callbacks[layout->id].client_added) callbacks[layout->id].client_added(layout); } void layout_allocate_pos(struct layout *layout, unsigned n) { if (layout->pos) free(layout->pos); layout->pos = xcalloc(n, sizeof(struct layout_pos)); layout->n = n; } int layout_pos_index(struct layout *layout, int x, int y) { struct layout_pos *pos; unsigned int i; for (i = 0, pos = layout->pos; i < layout->n; i++, pos++) { if (INSIDE(x, y, pos->x, pos->y, pos->w, pos->h)) return i; } return -1; } void layout_remove_client(struct layout *layout) { if (callbacks[layout->id].client_removed) callbacks[layout->id].client_removed(layout); } void layout_set(struct layout *layout, LayoutID id) { assert(id < LASTLayout); layout->id = id; if (callbacks[layout->id].arrange) callbacks[layout->id].arrange(layout); } void layout_set_clients(struct layout *layout, unsigned n) { if (callbacks[layout->id].clients_changed) callbacks[layout->id].clients_changed(layout, n); } void layout_set_geom(struct layout *layout, int ww, int wh) { if (callbacks[layout->id].geom_changed) callbacks[layout->id].geom_changed(layout, ww, wh); layout->ww = ww; layout->wh = wh; } void layout_set_mfact(struct layout *layout, float mfact) { mfact = MAX(0.01, MIN(0.99, mfact)); if (callbacks[layout->id].mfact_changed) callbacks[layout->id].mfact_changed(layout, mfact); layout->mfact = mfact; } void layout_set_nmaster(struct layout *layout, unsigned nmaster) { nmaster = MIN(4, nmaster); if (callbacks[layout->id].nmaster_changed) callbacks[layout->id].nmaster_changed(layout, nmaster); layout->nmaster = nmaster; } int layout_str2id(const char *str) { if (STREQ(str, "horz")) return TileHorzLayout; else if (STREQ(str, "vert")) return TileVertLayout; else if (STREQ(str, "max")) return MaxLayout; return -1; } char * layout_symbol(const struct layout *layout) { char buf[10]; switch(layout->id) { case TileHorzLayout: strcpy(buf, "|"); break; case TileVertLayout: strcpy(buf, "-"); break; case MaxLayout: if (layout->n > 0) snprintf(buf, sizeof(buf), "%u", layout->n); else strcpy(buf, "M"); break; default: strcpy(buf, ""); break; } return xstrdup(buf); }
C
/** * debug.c * * Rob Bowden * rob@cs.harvard.edu * * Intentionally buggy program that (in theory) never terminates. * * Meant to be debugged with GDB! */ #include <stdio.h> #include <cs50.h> void foo(int i) { while (i != 0) { i = i - 3; } printf("%i\n", i); } int main(void) { printf("Enter an integer: "); int i = GetInt(); while (i > 10) { i--; } foo(i); }
C
#include "crc32.h" static unsigned long reflect(unsigned long data, unsigned char nBits) { unsigned long reflection = 0x00000000; unsigned char bit; /* * Reflect the data about the center bit. */ for (bit = 0; bit < nBits; ++bit) { /* * If the LSB bit is set, set the reflection of it. */ if (data & 0x01) { reflection |= (1 << ((nBits - 1) - bit)); } data = (data >> 1); } return (reflection); } /* reflect() */ crc_t crc32_c(unsigned char const message[], int nBytes) { crc_t remainder = INITIAL_REMAINDER; int byte; unsigned char bit; /* * Perform modulo-2 division, a byte at a time. */ for (byte = 0; byte < nBytes; ++byte) { /* * Bring the next byte into the remainder. */ remainder ^= (REFLECT_DATA(message[byte]) << (WIDTH - 8)); /* * Perform modulo-2 division, a bit at a time. */ for (bit = 8; bit > 0; --bit) { /* * Try to divide the current data bit. */ if (remainder & TOPBIT) { remainder = (remainder << 1) ^ POLYNOMIAL; } else { remainder = (remainder << 1); } } } /* * The final remainder is the CRC result. */ return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE); }
C
/* * Copyright (C) Arthur */ #include <art_linux.h> #include <art_config.h> #include <art_core.h> static inline void *\ art_memalign(size_t alignment, size_t size); static inline void *\ art_palloc_small(art_pool_t *pool, size_t size, art_u32_t align); static void *\ art_palloc_block(art_pool_t *pool, size_t size); static void *\ art_palloc_large(art_pool_t *pool, size_t size); static inline void * art_memalign(size_t alignment, size_t size) { void *p; size_t err; err = posix_memalign(&p, alignment, size); if (err) { p = NULL; } return p; } static inline void * art_palloc_small(art_pool_t *pool, size_t size, art_u32_t align) { art_u8_t *m; art_pool_t *p; p = pool->current; do { m = p->d.last; if (align) { m = art_align_ptr(m, ART_POOL_ALIGNMENT); } if ((size_t) (p->d.end - m) >= size) { p->d.last = m + size; p->d.leisure = 0; return m; } p = p->d.next; } while (p); return art_palloc_block(pool, size); } static void * art_palloc_block(art_pool_t *pool, size_t size) { art_u8_t *m; size_t psize; art_pool_t *p, *new; psize = (size_t)(pool->d.end - (art_u8_t *) pool); m = (art_u8_t *)art_memalign(ART_POOL_ALIGNMENT, psize); if (m == NULL) { return NULL; } new = (art_pool_t *) m; new->d.end = (art_u8_t *)m + psize; new->d.next = NULL; new->d.failed = 0; new->d.leisure = 0; m += sizeof(art_pool_data_t); m = art_align_ptr(m, ART_POOL_ALIGNMENT); new->d.last = m + size; for (p = pool->current; p->d.next; p = p->d.next) { if (p->d.failed++ > 4) { pool->current = p->d.next; } } p->d.next = new; return m; } static void * art_palloc_large(art_pool_t *pool, size_t size) { art_uptr_t *p; art_pool_large_t *large; size_t n; p = art_malloc(size); if (p == NULL) { return NULL; } n = 0; for(large = pool->large; large; large = large->next) { if(large->alloc == NULL) { large->alloc = p; return p; } if(n++ > 3) { break; } } large = (art_pool_large_t *) \ art_palloc_small(pool, sizeof(art_pool_large_t), 1); if (large == NULL) { art_free(p); return NULL; } large->alloc = p; large->next = pool->large; pool->large = large; return p; } art_pool_t * art_create_pool(size_t size) { art_pool_t *p; size = ((size < ART_MAX_ALLOC_FROM_POOL) ? size : ART_MAX_ALLOC_FROM_POOL); p = (art_pool_t *)art_memalign(ART_POOL_ALIGNMENT, size); if (p==NULL) { return NULL; } p->d.last = (art_u8_t *)p + sizeof(art_pool_t); p->d.end = (art_u8_t *)p + size; p->d.next = NULL; p->d.failed = 0; p->d.leisure = 0; size = size - sizeof(art_pool_t); p->max = size; if(p->max <= 0) { art_free(p); return NULL; } p->lock = 0; p->current = p; p->large = NULL; p->cleanup = NULL; return p; } void art_destroy_pool(art_pool_t *pool) { art_pool_t *p, *pre; art_pool_cleanup_t *ph; art_pool_large_t *pl; for(ph = pool->cleanup; ph; ph = ph->next) { if(ph->handler) { ph->handler(ph->data); } } for(pl = pool->large; pl; pl = pl->next) { if(pl->alloc) { art_free(pl->alloc); } } for(pre = pool, p = pool->d.next; /* void */; pre = p, p = p->d.next) { art_free(pre); if(p == NULL) { break; } } } void art_reset_pool(art_pool_t *pool) { art_pool_t *p; art_pool_large_t *pl; for(pl = pool->large; pl; pl = pl->next) { if(pl->alloc) { art_free(pl->alloc); } } for(p = pool; p; p = p->d.next) { p->d.last = (art_u8_t *)p + sizeof(art_pool_t); p->d.failed = 0; p->d.leisure++; } pool->current = pool; pool->large = NULL; } void * art_palloc(art_pool_t *pool, size_t size, art_u8_t init) { art_uptr_t *p; art_spinlock(&(pool->lock), 1, 2048); if (size <= pool->max) { p = art_palloc_small(pool, size, 1); } else { p = art_palloc_large(pool, size); } art_unlock(&(pool->lock)); if(init) { art_memzero(p, size); } return p; } void * art_pnalloc(art_pool_t *pool, size_t size, art_u8_t init) { art_uptr_t *p; art_spinlock(&(pool->lock), 1, 2048); if (size <= pool->max) { p = art_palloc_small(pool, size, 0); } else { p = art_palloc_large(pool, size); } art_unlock(&(pool->lock)); if(init) { art_memzero(p, size); } return p; } /* get a large memory block that alignmently */ void * art_pmemalign(art_pool_t *pool, size_t size, size_t alignment) { art_uptr_t *p; art_pool_large_t *large; size_t n; p = art_memalign(alignment, size); if (p == NULL) { return NULL; } art_spinlock(&(pool->lock), 1, 2048); n = 0; for (large = pool->large; large; large = large->next) { if (large->alloc == NULL) { large->alloc = p; return p; } if(n++ > 3) { break; } } large = (art_pool_large_t *) \ art_palloc_small(pool, sizeof(art_pool_large_t), 1); if (large == NULL) { art_free(p); return NULL; } art_unlock(&(pool->lock)); large->alloc = p; large->next = pool->large; pool->large = large; return p; } art_state_t art_pfree(art_pool_t *pool, art_uptr_t p) { art_pool_large_t *l; /* Free the memory specified by 'p' */ for (l = pool->large; l; l = l->next) { if ((void *)p == l->alloc) { art_free(l->alloc); l->alloc = NULL; return ART_OK; } } return ART_ERROR; } art_pool_cleanup_t * art_pool_cleanup_add(art_pool_t *pool, size_t size) { art_pool_cleanup_t *c; c = (art_pool_cleanup_t *) \ art_palloc_small(pool, sizeof(art_pool_cleanup_t), 1); if (c == NULL) { return NULL; } if (size) { c->data = art_palloc(pool, size, 1); if (c->data == NULL) { return NULL; } } else { c->data = NULL; } c->handler = NULL; c->next = pool->cleanup; pool->cleanup = c; return c; } void art_manage_small(art_pool_t *pool) { art_pool_t *p, *pre; for(pre = pool, p = pool->d.next; p; /* void */) { if(p->d.leisure > LEISURETIMES) { pre->d.next = p->d.next; art_free(p); p=pre->d.next; } pre = p; p = p->d.next; } } /* update on 2018-12-18 */
C
//Write the function any(s1,s2) which returns the first location in a string s1 //Where any character from the string s2 occurs, or -1 if s1 contains no //characters from s2. #include <stdio.h> #define MAX 1000 #define NO_MATCH -1 #define MATCH (!NO_MATCH) int any(char str1[], char str2[]); int main () { char str1[MAX] = "hello2"; char str2[MAX] = "tzxcv2b"; int match = any(str1, str2); printf("The first matching character is %c", match); printf("The first matching character is at index %d", match); } int any(char str1[], char str2[]) { int state=NO_MATCH; int j,k; //Nested for loop, checks if a value in the second string //Matches a value in the first string //If they do store the value and escape the loop for (j=0; str1[j]!= '\0' ;++j) { for (k=0; str2[k]!='\0'||state==MATCH; ++k) { if (str1[j] == str2[k]) { //Finding the first matching value state = j; //Finding the first matching index in s1 //printf("%d\n",j); } } } return state; }
C
#include "mpi.h" #include <stdio.h> #include <stdlib.h> struct message { int num; char name[MPI_MAX_PROCESSOR_NAME]; }; int main(int argc, char* argv[]) { int rank, size, len, tag = 1, rc, i, lens[2] = { 1, MPI_MAX_PROCESSOR_NAME}; struct message mess, *buff; MPI_Datatype type, types[2] = { MPI_INT, MPI_CHAR }; MPI_Aint offsets[2] = {0, 1}; MPI_Init(&argc, &argv); MPI_Type_create_struct(2, lens, offsets, types, &type); MPI_Type_commit(&type); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); mess.num = rank; MPI_Get_processor_name( mess.name, &len ); if ( rank == 0 ) { buff = malloc(size * (sizeof(int) + lens[1])); } MPI_Gather( &mess, 1, type, buff, 1, type, 0, MPI_COMM_WORLD ); if ( rank == 0 ) for ( i = 0; i < size; i++ ) printf("num: %d, name: %s\n", buff[i].num, buff[i].name); MPI_Finalize(); return 0; }
C
#pragma once #include "String.h" typedef enum e_TokenType { TokenUnknown, TokenIdentifier, TokenPlus, TokenMinus, TokenColon, TokenAsterisk, TokenLessThan, // < TokenGreaterThan, // > TokenEquals1, // = TokenEquals2, // := TokenEquals3, // =:= TokenExclamation, // ! TokenAnd, // && TokenSemicolon, TokenBracketOpen1, // ( TokenBracketClose1, // ) TokenBracketOpen2, // { TokenBracketClose2, // } TokenBracketOpen3, // [ TokenBracketClose3, // ] TokenComment, TokenEOF, TokenSeparator, // whitespace, \n, \t TokenLengthExceeded, TokenError, TokenInteger, TokenKeyWordIf, TokenKeyWordWhile, TokenKeyWordRead, TokenKeyWordWrite, TokenKeyWordElse, TokenKeyWordInt } TokenType; typedef enum e_NodeType { NodeUnknown, NodeProg, NodeDecls, NodeDecl, NodeArray, NodeStatements, NodeStatement, NodeExp, NodeExp2, NodeIndex, NodeOpExp, NodeOp } NodeType; typedef enum e_NodeCheckType { NotInited, IntType, IntArrayType, ArrayType, NoType, ErrorType, OpPlus, OpMinus, OpMult, OpDiv, OpLess, OpGreater, OpEqual, OpUnequal, OpAnd } NodeCheckType; const char* tokenToString(TokenType type); const char* wrapChar(const char& c);
C
#include <stdio.h> double atof(char *s){ int i;double x, n; n = 0;x=1; for(i = 0; s[i] >= '0' && s[i] <= '9'; i++){ n = 10 * n + (s[i] - '0'); } if (s[i]=='.'){ i++; for(i; s[i] >= '0' && s[i] <= '9'; i++){ x*=10; n = 10 * n + (s[i] - '0'); } } return n/x; } int main(){ char x[]= "123.456"; printf("%lf",atof(x)); }
C
#include "list.h" /******************************* * Average Time O(n^2) * Space O(1) *******************************/ void SORT_SIMPLE(link_list_t *list) { int i; link_node_t *n = list->head; link_node_t *c; link_node_t *t; while(n) { t = n; for(c = n->next; c; c = c->next) { if(c->val < t->val) t = c; /* select the smallest firstly */ } /* lastly, exchange */ exchange_link_node(list, n, t); n = t->next; } }
C
#include <stdio.h> #include <stdlib.h> #include "grafo.h" void inicializar (grafo *g, int tamanho) { int i,j; g->v = tamanho; g->mapa = (char *) malloc(sizeof(char) * tamanho); g->matriz = (long **) malloc(sizeof(long) * tamanho); for(i =0; i < tamanho; i++) g->matriz[i] = (long *) malloc(sizeof(long) * tamanho); for(i =0; i < tamanho; i++) { for(j=0; j < tamanho; j++) { if(i==j) { g->matriz[i][j] = 1; } else { g->matriz[i][j] = 0; } } } } /*void ler_arquivo_grafo(grafo *g, char caminho[]){ int i; int vertices = -1; int arestas = -1; char t1, t2, t3, t4; FILE *arq = fopen(caminho, "rt"); if(arq != NULL){ fscanf(arq, "%d %d", &vertices, &arestas); inicializar(g, vertices); for(i=0; i<vertices; i++){ fscanf(arq, "%c %c", &t1,&t2); g->mapa[i] = t2; struct vertice* novo = (vertice*)malloc(sizeof(vertice)); novo->letra = t2; novo->d = 0; novo->pi = NULL; novo->cor = BRANCO; novo->f = 0; novo->index = i; } for(i=0; i<arestas; i++){ fscanf(arq, "%c%c%c", &t1,&t2,&t3); adicionarAresta(g, t3, t4); } fclose(arq); } }*/ void ler_arquivo_grafo(grafo*g ,char caminho[]){ int i; int vertices = -1; int arestas = -1; char t1;//\n's char t2;//vertices char t3; char t4; FILE *arq = fopen(caminho,"rt"); if(arq != NULL){ fscanf(arq,"%d %d",&vertices,&arestas); inicializar(g,vertices); for(i=0;i<vertices;i++){//vertices no t2 fscanf(arq,"%c %c",&t1,&t2); g->mapa[i]=t2;//atualizacao do mapa struct vertice* novo = (vertice*)malloc(sizeof(vertice)); novo->letra = t2; novo->d = 0; novo->pi = NULL; novo->cor = BRANCO; novo->f = 0; novo->index = i; g->vertices[i] = novo; } for(i=0;i<arestas;i++){//aresta entre t3 e t4 fscanf(arq,"%c%c%c",&t1,&t3,&t4); adicionarAresta(g,t3,t4); } fclose(arq); } } void imprimir(grafo *g) { int i,j; for(i=0;i<(g->v);i++){ printf("\t%c",g->mapa[i]); } printf("\n\n"); for(i =0; i < g->v; i++) { printf("%c",g->mapa[i]); for(j = 0; j < g->v; j++) { printf("\t%ld", g->matriz[i][j]); } printf("\n"); } } void adicionarAresta(grafo *g, char v1, char v2){ int i, pos1,pos2; for(i=0;i<(g->v);i++){ if(v1 == g->mapa[i]){ pos1 = i; } if(v2 == g->mapa[i]){ pos2 = i; } } g->matriz[pos1][pos2] = 1; g->matriz[pos2][pos1] = 1; } int verifAdj(grafo* g, char v1, char v2){ int i, posi1, posi2; for(i=0; i<g->v; i++){ if(g->mapa[i] == v1){ posi1 = i; } if (g->mapa[i] == v2){ posi2 = i; } } if(g->matriz[posi1][posi2] == 1){ return 1; } else{ return 0; } } void DFS(grafo * g){ int i; for(i=0; i<g->v; i++){ g->vertices[i]->cor = BRANCO; g->vertices[i]->pi = NULL; } int tempo = 0; for(i = 0; i < g->v; i++){ if(g->vertices[i]->cor == BRANCO) tempo = DFS_VISIT (g, g->vertices[i], tempo); } for(i=0; i<g->v; i++){ printf("%c: %d - %d\n", g->vertices[i]->letra, g->vertices[i]->d, g->vertices[i]->f); } } int DFS_VISIT(grafo *g, vertice * u, int tempo){ u->cor = CINZA; tempo +=1; u->d = tempo; int i; for(i=0; i<g->v; i++){ if(verifAdj(g, g->vertices[i]->letra, u->letra) & g->vertices[i]->letra != u->letra){ if(g->vertices[i]->cor == BRANCO){ g->vertices[i]->pi = u; tempo = DFS_VISIT(g, g->vertices[i], tempo); } } } u->cor = PRETO; tempo = tempo+1; u->f = tempo; return tempo; } int main(int argc, int* argv) { grafo g; char diretorio[100]; scanf("%s",diretorio); ler_arquivo_grafo(&g,diretorio); imprimir(&g); //BGS(&g,'S');//busca em largura DFS(&g);//busca em profundidade }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "unmap.h" int main() { size_t i = 0; char str[9] = {0}; char *p = 0; unmap_t *map = unmap_init(); for(i = 0; i < 10000000; i++){ sprintf(str, "%08lu", i); p = malloc(9); memcpy(p, str, 9); unmap_set(map, str, 8, p); } for(i = 0; i < 10000000; i++){ sprintf(str, "%08lu", i); p = unmap_find(map, str, 8); if(strcmp(str, p)){ printf("%s - %s\n", str, p); } //free(p); } return 0; }
C
/* $Id: apmctrl.c,v 1.16 2004/12/02 04:25:37 Exp $ */ /* S[i|a]mple APM control applet */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define INCL_BASE #include <os2.h> #include "viaapm.h" #include "viaapmp.h" /* Local variables */ static HFILE hf; /* Perform IOCTL with necessary checks */ static void do_ioctl(PVOID pData, ULONG cbDataLenMax, PVOID pParams, ULONG cbParmLenMax, ULONG function, ULONG category, HFILE hDevice) { USHORT rc; ULONG pcbParmLen=cbParmLenMax, pcbDataLen=cbDataLenMax; if(rc=DosDevIOCtl2(hDevice, category, function, pParams, cbParmLenMax, &pcbParmLen, pData, cbDataLenMax, &pcbDataLen)) { printf("IOCtl #%02lx/%02lx failed, rc=%u\n", category, function, rc); DosClose(hDevice); exit(1); } } /* Reinitialize the driver */ static void reset() { USHORT rc; do_ioctl(&rc, 2, NULL, 0, VIAAPM_CMD_RESET, IOCTL_CAT_VIAAPM, hf); if(!rc) printf("Reset OK\n"); else printf("Reset failed, rc=%u\n", rc); } /* Set throttling */ static void set_throttling(char *arg) { USHORT t; t=atoi(arg); if(t==0) { fprintf(stderr, "Invalid parameter <%s> ignored\n", arg); return; } if(strchr(arg, '%')!=NULL) { if(t==100) t=16; else { t=(t+6)*3/20; if(t==16) t--; /* Enable throttling if not 100% */ } } if(t==0) t=1; do_ioctl(NULL, 0, &t, 2, VIAAPM_CMD_SET_THROTTLING, IOCTL_CAT_VIAAPM, hf); } /* Query throttling */ static void query_throttling() { USHORT rc; do_ioctl(&rc, 2, NULL, 0, VIAAPM_CMD_QUERY_THROTTLING, IOCTL_CAT_VIAAPM, hf); if(rc==16) printf("100%% duty cycle (throttling disabled)\n"); else printf("%u%% [+/-3%%] duty cycle (throttling enabled)\n", (unsigned int)(rc*20/3-3)); } /* Query chipset */ static void query_chipset() { USHORT rc; unsigned int j; static CHIPSET_TYPES; do_ioctl(&rc, 2, NULL, 0, VIAAPM_CMD_QUERY_CHIPSET, IOCTL_CAT_VIAAPM, hf); for(j=0; chipset_types[j]!=NULL&&j<rc; j++) ; if(chipset_types[j]!=NULL) printf("Chipset type: %s\n", chipset_types[j]); else printf("Unknown chipset type (%u)\n", rc); } /* ** Undocumented ** */ static void set_fsb(char *arg) { unsigned long f; f=atoi(arg); if(strchr(arg, 'M')!=NULL) f*=1000000L; else if(strchr(arg, 'K')!=NULL||strchr(arg, 'k')!=NULL) f*=1000L; if(f<1000000||f>1000000000) fprintf(stderr, "FSB frequency of %lu Hz can't be accepted\n", f); else do_ioctl(NULL, 0, &f, sizeof(f), VIAAPM_CMD_SET_FSB, IOCTL_CAT_VIAAPM, hf); } /* ** Undocumented ** */ static void query_fsb() { unsigned long f; do_ioctl(&f, sizeof(f), NULL, 0, VIAAPM_CMD_QUERY_FSB, IOCTL_CAT_VIAAPM, hf); fprintf(stderr, "FSB frequency is %lu Hz\n", f); } /* ** Undocumented ** */ static void set_cpu_freq(char *arg) { unsigned long f; f=atoi(arg); if(strchr(arg, 'M')!=NULL) f*=1000000L; else if(strchr(arg, 'K')!=NULL||strchr(arg, 'k')!=NULL) f*=1000L; if(f<10000000) fprintf(stderr, "CPU frequency of %lu Hz can't be accepted\n", f); else do_ioctl(NULL, 0, &f, sizeof(f), VIAAPM_CMD_SET_CPU_FREQ, IOCTL_CAT_VIAAPM, hf); } /* ** Undocumented ** */ static void query_cpu_freq() { unsigned long f; do_ioctl(&f, sizeof(f), NULL, 0, VIAAPM_CMD_QUERY_CPU_FREQ, IOCTL_CAT_VIAAPM, hf); f/=10000; fprintf(stderr, "CPU frequency is %lu.%02lu MHz\n", f/100, f%100); } /* Main routine */ int main(int argc, char **argv) { unsigned int i; USHORT rc, t; ULONG action; if(argc<2||!stricmp(argv[1], "/?")) { fprintf(stderr, "APM/ACPI control program v 2.50 on " __DATE__ ", " __TIME__ "\n" "\n" "Usage: APMCTRL <option> [<option> ...]\n" "\n" "General VIA chipset options:\n" " /RESET Reconfigure the chipset and reinstall idle hook\n" " /T[:<value>[%%]] Query/set throttling mode\n" " /Q Query chipset type\n" "\n" /* This is just "FYI", we aren't going to document this. */ #if 0 "ICS942xx PLL options (where available):\n" " /FSB[:<x>] Query/set front-side bus frequency (xxxxxxK[Hz]|xxxM[Hz])\n" " /CPUFREQ[:<x>] Query/set CPU frequency (requires /CPUMUL for VIAAPM.SYS)\n" #endif ); return(1); } if(DosOpen(APM_DRIVER, &hf, &action, 0L, FILE_NORMAL, OPEN_ACTION_FAIL_IF_NEW|OPEN_ACTION_OPEN_IF_EXISTS, OPEN_ACCESS_READONLY|OPEN_SHARE_DENYNONE, 0L)) { fprintf(stderr, "APM driver not installed\n"); return(2); } do_ioctl(&rc, 2, NULL, 0, VIAAPM_CMD_QUERY_HOOK, IOCTL_CAT_VIAAPM, hf); if(!rc) { fprintf(stderr, "APM hook not installed\n"); return(3); } for(i=1; i<argc; i++) { if(!stricmp(argv[i], "/RESET")) reset(); else if(!memicmp(argv[i], "/T:", 3)) set_throttling(argv[i]+3); else if(!stricmp(argv[i], "/T")) query_throttling(); else if(!stricmp(argv[i], "/Q")) query_chipset(); else if(!memicmp(argv[i], "/FSB:", 5)) set_fsb(argv[i]+5); else if(!stricmp(argv[i], "/FSB")) query_fsb(); else if(!memicmp(argv[i], "/CPUFREQ:", 9)) set_cpu_freq(argv[i]+9); else if(!stricmp(argv[i], "/CPUFREQ")) query_cpu_freq(); else fprintf(stderr, "Invalid parameter <%s> ignored\n", argv[i]); } DosClose(hf); return(0); }
C
#include <iostream> #include <cmath> using namespace std; struct node { int data; node *right,*left; }; int height(node* root) { if(root==NULL)return 0; return (max(height(root->left),height(root->right))+1); } void inorder_print(node* root) { if(root==NULL)return; int h=height(root); inorder_print(root->left); cout << root->data << " height= " << h << endl; inorder_print(root->right); } void create_tree(node* &root,int arr[],int start,int end) { if(start>end)return; if(root==NULL){ node* p=new node; int ind=start+(end-start)/2; p->data=arr[ind]; p->left=NULL; p->right=NULL; root=p; create_tree(root->left,arr,start,ind-1); create_tree(root->right,arr,ind+1,end); } } int main() { int arr[]={1,2,3,4,5,6,7,8,9}; node* root; root=NULL; create_tree(root,arr,0,8); cout << root->left->data << " " << root->data << " " << root->right->data << endl; cout << "Height= " << height(root) << endl; inorder_print(root); return 0; }
C
/// https://stackoverflow.com/questions/1733881/c-correctly-freeing-memory-of-a-multi-dimensional-array /// http://phyweb.physics.nus.edu.sg/~phywjs/CZ1102/lecture20/tsld014.htm #include<stdio.h> #include<stdlib.h> int main() { int i; double **b; b = (double **) calloc(100, sizeof(double*)); for(i = 0; i < 100; ++i) { b[i] = (double *) calloc(30, sizeof(double)); } // double b[100][30]; b[79][21] = 2.1; // free(**b); free(*b); free(b); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <dirent.h> #include <arpa/inet.h> /* Programmer: Andrew Sunderland Program Name: ftserver Program Description: This is a server program that listens for clients to connect. Once connected the client can ask the server for a directory listing or a file to be sent Course Name: CS 372 Intro to Computer Networks Last Modified: 3/8/2020 */ /* # Function: startUp # Description : Sets up the socket for the server and starts listening for connections # Parameters : char* portNum # Pre - Conditions: A port number must be provided for the server to use # Post - Conditions: The socket is set up and returned for use */ int startUp(char* portNum) { int socketFD, portNumber; struct sockaddr_in serverAddress; // Set up the server address struct memset((char*)&serverAddress, '\0', sizeof(serverAddress)); // Clear out the address struct portNumber = atoi(portNum); // Get the port number, convert to an integer from a string serverAddress.sin_family = AF_INET; // Create a network-capable socket serverAddress.sin_port = htons(portNumber); // Store the port number serverAddress.sin_addr.s_addr = INADDR_ANY; // Any address is allowed for connection to this process // Set up the socket socketFD = socket(AF_INET, SOCK_STREAM, 0); // Create the socket if (socketFD < 0) fprintf(stderr, "CLIENT: ERROR opening socket"); // Bind and start listening on the socket if (bind(socketFD, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) < 0) // Connect socket to port { fprintf(stderr, "ERROR on binding\n", 18); return -1; } listen(socketFD, 5); // Flip the socket on so it can now receive up to 5 connections return socketFD; } /* Function: handleRequest Description: Receives input from the command socket to either send a directory listing or a file to be sent on a newly created data socket Parameters: int socketFD Pre-Conditions: The command socket must be created and initialized Post-Conditions: A directory listing or a binary file is sent over a data socket */ void handleRequest(int socketFD) { int charsRead, charsWritten, terminalLocation, dataPortLocation, fileLocation, dataPort; static char buffer[500], command[500], dataPortstr[500], filestr[500], clientIP[20], directorystr[5000]; char * invalidCommand = "Invalid command recieved closing connection."; char * fileNotFound = "FILE NOT FOUND"; void * fileBuffer = malloc(2000000000); // Allocating enough memory for a file to be stored completely in memory // Getting client's ip for later use struct sockaddr_in clientaddr; socklen_t clientSize = sizeof(clientaddr); int result = getpeername(socketFD, (struct sockaddr *)&clientaddr, &clientSize); memset(clientIP, '\0', sizeof(clientIP)); strcpy(clientIP, inet_ntoa(clientaddr.sin_addr)); // Receiving message from server memset(buffer, '\0', sizeof(buffer)); // Clear out the buffer again for reuse charsRead = recv(socketFD, buffer, sizeof(buffer) - 1, 0); // Read data from the socket, leaving \0 at end if (charsRead < 0) error("CLIENT: ERROR reading from socket"); // Parse through message for commands int commandLocation = strstr(buffer, "$$") - buffer; memset(command, '\0', sizeof(command)); strcpy(command, buffer); command[commandLocation] = '\0'; // If no valid command is received if (strcmp(command, "-l") != 0 && strcmp(command, "-g") != 0) { printf("Invalid message received!\n"); charsWritten = send(socketFD, invalidCommand, strlen(invalidCommand), 0); // Sending invalid command error to client if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); if (charsWritten < strlen(invalidCommand)) printf("SERVER: WARNING: Not all data written to socket!\n"); } // If a valid command is received else { memset(dataPortstr, '\0', sizeof(dataPortstr)); // Received the GET command if (strstr(buffer, "&&") != NULL) { // Separating the file name from the message fileLocation = strstr(buffer, "$$") - buffer; strncpy(filestr, buffer + fileLocation + 2, strlen(buffer)); terminalLocation = strstr(filestr, "&&") - filestr; filestr[terminalLocation] = '\0'; // Separating the data port from the message dataPortLocation = strstr(buffer, "&&") - buffer; strncpy(dataPortstr, buffer + dataPortLocation + 2, strlen(buffer)); terminalLocation = strstr(dataPortstr, "@@") - dataPortstr; dataPortstr[terminalLocation] = '\0'; dataPort = atoi(dataPortstr); // Converting data port string to integer // Locating file to send FILE * fileD = fopen(filestr, "rb"); printf("File %s is requested on port %d.\n", filestr, dataPort); if (fileD == NULL) // If the file can't be located { printf("File not found. Sending error message to %s:%d\n", clientIP, dataPort); charsWritten = send(socketFD, fileNotFound, strlen(fileNotFound), 0); // Sending file not found to client if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); if (charsWritten < strlen(fileNotFound)) printf("SERVER: WARNING: Not all data written to socket!\n"); free(fileBuffer); return; } // File is located and sent else { charsWritten = send(socketFD, "Good", 4, 0); // Valid command received if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); if (charsWritten < 4) printf("SERVER: WARNING: Not all data written to socket!\n"); printf("Sending %s to %s:%d\n", filestr, clientIP, dataPort); // Opening Data Socket int listenDataFD = startUp(dataPortstr); if (listenDataFD == -1) { free(fileBuffer); return; } int dataFD = accept(listenDataFD, (struct sockaddr *)&clientaddr, &clientSize); if (dataFD < 0) fprintf(stderr, "ERROR on accept\n", 17); // Preparing the file to be sent fseek(fileD, 0, SEEK_END); long fileSize = ftell(fileD); // Getting the file size size_t bytesRead; fseek(fileD, 0, SEEK_SET); bytesRead = fread(fileBuffer, fileSize, 1, fileD); // Copying the file into memory char fsize[256]; sprintf(fsize, "%ld", fileSize); // Converting the file size to an integer // Sending the file size to the client charsWritten = send(socketFD, fsize, strlen(fsize), 0); if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); // Sending the file to the client while (fileSize > 0) { charsWritten = send(dataFD, fileBuffer, fileSize, 0); if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); fileSize = fileSize - charsWritten; } close(dataFD); // Close out the data socket } free(fileBuffer); // Free up the file memory fclose(fileD); // Close out the file stream } // Received the LIST command else { charsWritten = send(socketFD, "Good", 4, 0); // Valid command received if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); if (charsWritten < 4) printf("SERVER: WARNING: Not all data written to socket!\n"); // Separating the data port from the message dataPortLocation = strstr(buffer, "$$") - buffer; strncpy(dataPortstr, buffer + dataPortLocation + 2, strlen(buffer)); terminalLocation = strstr(dataPortstr, "@@") - dataPortstr; dataPortstr[terminalLocation] = '\0'; dataPort = atoi(dataPortstr); // Converting data port string to integer. // Opening Data Socket int listenDataFD = startUp(dataPortstr); int dataFD = accept(listenDataFD, (struct sockaddr *)&clientaddr, &clientSize); if (dataFD < 0) fprintf(stderr, "ERROR on accept\n", 17); printf("List directory requested on port %d.\n", dataPort); printf("Sending directory contents to %s : %d\n", clientIP, dataPort); // Getting working directory DIR* currentDir; struct dirent *currentFile; currentDir = opendir("./"); memset(directorystr, '\0', sizeof(directorystr)); // Reading through files in CWD and copying to a string while ((currentFile = readdir(currentDir)) != NULL) { memset(buffer, '\0', sizeof(buffer)); strcpy(buffer, currentFile->d_name); buffer[strlen(buffer)] = '\n'; strcat(directorystr, buffer); } strcat(directorystr, "@@"); // Adding terminator for client // Sending directory to client charsWritten = send(dataFD, directorystr, strlen(directorystr), 0); if (charsWritten < 0) fprintf(stderr, "SERVER: ERROR writing to socket", 32); if (charsWritten < strlen(directorystr)) printf("SERVER: WARNING: Not all data written to socket!\n"); close(dataFD); // Close out the data socket } } } int main(int argc, char *argv[]) { int listenFD, charsWritten, charsRead, connectedFD; char message[510]; socklen_t clientSize; struct sockaddr_in clientIP; if (argc < 2) { fprintf(stderr, "USAGE: %s port\n", argv[0]); exit(0); } // Check usage & args listenFD = startUp(argv[1]); // Start up the server if (listenFD == -1) return 2; printf("Server open on %s\n", argv[1]); // Loop for continual acceptance while (1) { // Accept the incoming connection clientSize = sizeof(clientIP); // Get the address size of connecting client connectedFD = accept(listenFD, (struct sockaddr *)&clientIP, &clientSize); if (connectedFD < 0) fprintf(stderr, "ERROR on accept\n", 17); // Handle the incoming request handleRequest(connectedFD); close(connectedFD); // Close out the command socket } close(listenFD); // Close the listen socket return 0; }
C
#include <stdio.h> int main() { int num,d1,d2,d3,d4; printf("Enter four digit number\n"); scanf("%d", &num); d1=num%10; d2=(num/10)%10; d3=(num/100)%10; d4=(num/1000)%10; if(num>9 && num<99) {printf("The reverse is %d%d", d1,d2);} else if(num>99 && num<1000) {printf("the reverse is %d%d%d", d1,d2,d3);} else if(num>999 && num<10000) {printf("the reverse is %d%d%d%d", d1,d2,d3,d4);} else {printf("no reverse");} return 0; }
C
/* ** my_strcmp.c for my_printf in /home/dabbec_j/projets/my_select/my_printf ** ** Made by jalil dabbech ** Login <dabbec_j@epitech.net> ** ** Started on Wed May 22 19:01:21 2013 jalil dabbech ** Last update Tue Jun 18 16:23:16 2013 jalil dabbech */ int my_strcmp(char *s1, char *s2) { int i; i = 0; while (s1[i] == s2[i]) { if (s1[i] == '\0') return (0); i = i + 1; } return (s1[i] - s2[i]); }
C
#include "common.h" void quickSort_algo(int * inputArray, int size); static void problemDescription(void) { printf( "\nQuicksort" ); } static int problemOptions(void) { printf( "\n" "\n0. Exit" "\n1. Use random array" "\n2. Enter array values" "\n3. Default array values" "\n" ); return readInputInteger(); } void quickSort(void) { clearScreen(); problemDescription(); int choice = problemOptions(); if (choice == 0) return; int numberOfArrayValues = 0; int *inputArray = NULL; if (choice == 1) { printf("\nEnter number of random values: "); numberOfArrayValues = readInputInteger(); if (numberOfArrayValues <= 0) numberOfArrayValues = 10; srand(time(NULL)); inputArray = (int *)(calloc(numberOfArrayValues, sizeof(char))); for (int i = 0; i < numberOfArrayValues; i++) { inputArray[i] = rand() % 100; } } else if (choice == 2) { numberOfArrayValues = readInputIntegerArray(inputArray); if (!inputArray) {printf("Invalid input"); return;} } else if (choice == 3) { numberOfArrayValues = 8; inputArray = (int *)(calloc(numberOfArrayValues, sizeof(int))); inputArray[0] = 10; inputArray[1] = 5; inputArray[2] = 50; inputArray[3] = 100; inputArray[4] = 2; inputArray[5] = 0; inputArray[6] = 7; } if (inputArray) { quickSort_algo(inputArray, numberOfArrayValues); free(inputArray); } } void quickSort_algo(int * inputArray, int size) { printf ("\n"); for (int i=0; i < size; i++) { printf("%d ", inputArray[i]); } }
C
/** ****************************************************************************** * @file main.c * @brief main function * @author Xli * @email xieliyzh@163.com * @version 1.0.0 * @date 2020-02-06 * @copyright 2020, XIELI Co.,Ltd. All rights reserved ****************************************************************************** **/ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "bsp_clk.h" #include "bsp_delay.h" #include "bsp_led.h" #include "bsp_beep.h" #include "bsp_key.h" #include "bsp_exit.h" #include "bsp_epit.h" #include "bsp_uart.h" #include "stdio.h" /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function ----------------------------------------------------------*/ /**============================================================================= * @brief 主函数 * * @param[in] none * * @return none *============================================================================*/ int main(void) { uint8_t state = 0; //uint8_t a, b; /*!< 如果用uint8_t定义,必须在终端输入字符 */ int a, b; bsp_int_init(); bsp_imx6u_clk_init(); bsp_clk_enable(); /* 使能所有时钟 */ bsp_delay_init(); bsp_led_init(); /* 初始化led */ bsp_beep_init(); /*!< 初始化蜂鸣器 */ //bsp_key_init(); /*!< 按键初始化 */ bsp_exit_int_init(); /*!< 外部中断初始化 */ //bsp_epit1_init(0, (66000000/2)); /*!< EPIT1定时器初始化 */ bsp_uart_init(); /*!< 串口初始化 */ while (1) { printf("输入两个整数,使用空格隔开:"); scanf("%d %d", &a, &b); /* 输入两个整数 */ printf("\r\n 数据%d + %d = %d\r\n\r\n", a, b, a+b);/* 输出和 */ state = !state; bsp_led_switch(LED0, state); } return 0; }
C
/* C Primer Plus Ch.7 - Problem 1 * @reproduced by yoonBot */ #include <stdio.h> int main(){ char ch; int space_cnt, other_cnt, newline_cnt; space_cnt = other_cnt = newline_cnt = 0; printf("Enter input (Enter # to quit):\n"); while((ch = getchar()) != '#'){ switch (ch){ case '#': break; case ' ': space_cnt++; break; case '\n': newline_cnt++; break; default : other_cnt++; break; } } printf("Number of space characters entered: %d\n", space_cnt); printf("Number of newline characters entered: %d\n", newline_cnt); printf("Number of other characteres entered: %d\n", other_cnt); return 0; }
C
#include<stdio.h> int binary(int n) { static int i=0; printf("%d",i); if(n>0) { i=n%2; binary(n/2); return i; } return 0; } int main() { int n; printf("enter the no:\n"); scanf("%d",&n); binary(n); }
C
#include <stdio.h> #include <stdlib.h> int main() { int a[5],i,t; printf("enter array a:\n"); for(i=0;i<5;i++) scanf("%d",&a[i]); printf("array a:\n"); for(i=0;i<5;i++) printf("%4d",a[i]); for(i=0;i<5/2;i++) { t=a[i]; a[i]=a[5-i-1]; a[5-i-1]=t; } printf("\nNow,array a:\n"); for(i=0;i<5;i++) printf("%4d",a[i]); printf("\n"); return 0; }
C
#ifndef __LSIT_H_INCLUDED_ #define __LSIT_H_INCLUDED_ typedef int DataElem; //ԪΪ // struct Node { DataElem data; struct Node *next; }; //Ա struct List { struct Node *pHead; struct Node *pTail; }; typedef struct Node * Position; //Աλ //1. Ա //ձĵֻһͷ㣬ʧʱβָΪNULL struct List Create (); //2. Աա //ͷгͷн void Clear (struct List *pList); //3. һԱʹãͷн㡣 //ָĵַٵ void Destroy (struct List *pList); //4. ԱһͬԱ //ԭԱԭԱΪԱ //ظƺԱʧʱԱͷָΪNULL struct List Copy (struct List srcList); //5. Աпա //жԱǷΪձ򷵻1򷵻0 int IsEmpty (struct List list); //6. Ա󳤶ȡ //ԱԪصĸ int Length (struct List list); //7. ȡʼλá //ԱдһԪصλãձEndPosition (L) Position BeginPosition (struct List list); //8. ȡλá //شԱλ Position EndPosition (struct List list); //9. һλá //ԱpЧλõ¸λãҪѭԱ Position NextPosition (struct List list, Position pos); //10. ȡԪλá //ԱiԪλã1inԱıΪn Position LocatePosition (struct List list, int i); //11. λԪλá //ԪeԱгֵλãڣ򷵻Чλã //򷵻EndPosition (L) Position LocateElem (struct List list, DataElem e); //12. ȡԪء //ԱLposЧλõԪ DataElem GetElem (struct List list, Position pos); //13. ȡԪء //ԱposЧλõԪΪe void SetElem (struct List list, Position pos, DataElem e); //14. Ԫء //ԱposλǰһµԪأ //posΪEndPosition (L)ʱβԱȼ1 //ɹʱ1ʧʱ0 int InsertBefore (struct List *pList, Position pos, DataElem e); //15. ɾԪء //ɾԱposЧλԪأԱı1 void Delete (struct List *pList, Position pos); #endif // __LSIT_H_INCLUDED_
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "simple_shell.h" /* * Function printPrompt prints prompt parts */ int printPrompt() { char * buffer = malloc(PATH_LEN); /* Dynamic memory allocation for buffer */ char * path = getcwd(buffer, PATH_LEN); /* Get path of directory */ if(path != 0) fprintf(stdout, "2015040719@osh:%s> ", buffer); /* Prompt print with my Student ID*/ free(buffer); /* free the buffer */ return 0; }