language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include "linked_list.h" /* constructs an empty list */ List *list_init() { List *list = (List *)malloc(sizeof(List)); Node *dummy_head = (Node *)malloc(sizeof(Node)); Node *dummy_tail = (Node *)malloc(sizeof(Node)); dummy_head->next = dummy_tail; dummy_tail->prev = dummy_head; list->head = dummy_head; list->tail = dummy_tail; list->cur = NULL; return list; } /* returns the number of elements in the list */ int size(List *list) { int s = 0; Node *cur = list->head; while (cur->next != list->tail) { cur = cur->next; s++; } return s; } /* appends the specified element to the end of this list */ void add_last(List *list, Element e) { Node *new = (Node *)malloc(sizeof(Node)); new->data = e; new->next = list->tail; new->prev = list->tail->prev; list->tail->prev->next = new; list->tail->prev = new; } /* removes the element at the specified position in the list */ Element remove_last(List *list) { if (size(list) == 0) { fprintf(stderr, "Error: list is empty\n"); return INT_MIN; } Node *cur = list->tail->prev; Element data = cur->data; cur->prev->next = cur->next; cur->next->prev = cur->prev; free(cur); return data; }
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <pthread.h> #define THREAD_NUMBER 10 pthread_mutex_t mutex; pthread_cond_t cond; int running[THREAD_NUMBER] = {0}; int check_conflict(void); void *thread_proc(void *arg); int main(int argc, char *argv[]) { int ret, i; pthread_t thread[THREAD_NUMBER]; ret = pthread_mutex_init(&mutex, NULL); assert(ret == 0); ret = pthread_cond_init(&cond, NULL); assert(ret == 0); for (i = 0; i < THREAD_NUMBER; i++) { ret = pthread_create(&thread[i], NULL, thread_proc, (void *)i); assert(ret == 0); } for (i = 0; i < THREAD_NUMBER; i++) { ret = pthread_join(thread[i], NULL); assert(ret == 0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(EXIT_SUCCESS); } int check_conflict(void) { int i; int sum = 0; for (i = 0; i < THREAD_NUMBER; i++) { sum += running[i]; } if (sum > 1) return 1; else return 0; } void *thread_proc(void *arg) { int i = (int)arg; while (1) { pthread_mutex_lock(&mutex); // pthread_cond_wait(&cond, &mutex); running[i] = 1; if (!check_conflict()) printf("conflict error!\n"); running[i] = 0; // pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return NULL; }
C
#include "hash.h" #include <stdio.h> #include <stdlib.h> /* This program reads first argument as file and outputs the sha1 * sum on EOF. It does this twice on the same file to show how to * reuse the hash context. */ #define UPDATE_PAYLOAD_SIZE 8192 int main(int argc, char *argv[]) { if (argc == 1) { abort(); } FILE *fp = fopen(argv[1], "r"); if (!fp) { abort(); } uint8_t buffer[UPDATE_PAYLOAD_SIZE]; struct sha1sum_ctx *ctx = sha1sum_create(NULL, 0); if (!ctx) { fprintf(stderr, "Error creating checksum\n"); return 0; } for(size_t i = 0; i < 2; ++i) { size_t chunk_len = 0; while(!feof(fp)) { size_t cnt = UPDATE_PAYLOAD_SIZE - chunk_len; size_t ret = fread(buffer + chunk_len, 1, cnt, fp); if (ret != cnt) { if (ferror(fp)) { perror("Error reading from file: "); abort(); } } chunk_len += ret; if (chunk_len == UPDATE_PAYLOAD_SIZE) { sha1sum_update(ctx, buffer, UPDATE_PAYLOAD_SIZE); chunk_len = 0; } } uint8_t checksum[20]; sha1sum_finish(ctx, buffer, chunk_len, checksum); printf("0x"); for(size_t i = 0; i < 20; ++i) { printf("%02x", checksum[i]); } putchar('\n'); rewind(fp); sha1sum_reset(ctx); } sha1sum_destroy(ctx); fclose(fp); return EXIT_SUCCESS; }
C
/* Hello World! Hello World! 1 13 */ #include <stdio.h> int main (){ int a, b; a = fputs("Hello World!\n", stdout); b = puts("Hello World!"); printf("%d %d\n", a, b); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<conio.h> //Funo TIME char jogador1; char jogador2; char linha1[10]; char linha2[10]; char linha3[10]; char tecla; void dorme(int t){ int inicio=clock(); int agora, dif=0; while(dif<t){ agora=clock(); dif=1000*(agora-inicio)/CLOCKS_PER_SEC; } } main(){ char tecla; int cont=0; while(tecla!=27){ if(kbhit()){ tecla=getche(); if(tecla==13){ cont++; } } if(tecla=='1' || tecla=='2' || tecla=='3'){ tecla=getche(); for(linha2=0 ; linha2<10 ; linha2++){ jogador1++; } printf("-------------------------------------------",linha2); printf("%c",linha2);*/ system("cls"); printf("%i",cont); dorme(700); cont++; } } /* void jogo(){ char jogador1; char jogador2; printf("Jogador 1 informe seu caracter: \n"); jogador1=getche(); printf("\nJogador 2 informe seu caracter: \n"); jogador2=getche(); for(linha1=0 ; linha1<10 ; linha1++) if(tecla=='1' || tecla=='2' || tecla=='3{'){ tecla=getche(); jogador1++; } } for(linha1=10 ; linha1>1 ; linha1--){ if(tecla=='7' || tecla=='8' || tecla=='0'){ tecla=getche(); jogador2--; } } for(linha2=0 ; linha2<10 ; linha2++){ if(tecla=='1' || tecla=='2' || tecla=='3'){ tecla=getche(); jogador1++; } } for(linha2=10 ; linha2>1 ; linha2--){ if(tecla=='7' || tecla=='8' || tecla=='0'){ tecla=getche(); jogador2--; } } for(linha3=0 ; linha3<10 ; linha3++){ if(tecla=='1' || tecla=='2' || tecla=='3'){ tecla=getche(); jogador1++; } } for(linha3=10 ; linha3>1 ; linha3--){ if(tecla=='7' || tecla=='8' || tecla=='0'){ tecla=getche(); jogador2--; } } while(){ printf("") } } */
C
#include "product.h" int addProduct(Product *s){ int i =0; float j =0; getchar(); printf("\nEnter product name : "); fgets(s->name,20, stdin); for(int i=0;i<20;i++){ if(s->name[i]=='\n'){ s->name[i]='\0'; break; } } printf("Enter product weight : "); scanf("%d", &s->weight); printf("Enter product cost : "); scanf("%d", &s->cost); j = s->weight/10.0; s->s_cost= s->cost/j; printf("Enter product star(1~5) : "); scanf("%d", &s->star); while(s->star<=0||s->star>5){ printf("Enter number between 1 to 5 : "); scanf("%d", &s->star); } printf("Enter product review : "); scanf("%d", &s->review); while(s->review<0){ printf("Enter number 0 or bigger number : "); scanf("%d", &s->review); } printf("If there is a event enter 1, else enter 0: "); scanf("%d", &i); while(i!=1&&i!=0){ printf("Enter number 1(event) or 0(no event) : "); scanf("%d", &i); } if(i==1){ printf("1+1 : enter 1, 2+1 : enter 2 : "); scanf("%d", &s->event); while(s->event!=1&&s->event!=2){ printf("Enter number 1(1+1) or 2(2+1) : "); scanf("%d", &s->event); } } else s->event=0; return 1; } void readProduct(Product s){ char event[4]="\0"; if(s.event==1) strcpy(event, "1+1"); else if(s.event==2) strcpy(event, "2+1"); else strcpy(event, "---"); printf(" %-11s %-10d %-5d %-9.1f %-5d %-7d %s\n", s.name, s.weight, s.cost, s.s_cost, s.star, s.review, event); } int updateProduct(Product *s){ float j=0; int i=0; getchar(); printf("\nName? "); fgets(s->name,20, stdin); for(int i=0;i<20;i++){ if(s->name[i]=='\n'){ s->name[i]='\0'; break; } } printf("Weight? "); scanf("%d", &s->weight); printf("Cost? "); scanf("%d", &s->cost); printf("Star(1~5)? "); j = s->weight/10.0; s->s_cost= s->cost/j; scanf("%d", &s->star); while(s->star<=0||s->star>5){ printf("Enter number between 1 to 5 : "); scanf("%d", &s->star); } printf("Review? "); scanf("%d", &s->review); while(s->review<0){ printf("Enter number 0 or bigger number : "); scanf("%d", &s->review); } printf("If there is a event enter 1, else enter 0: "); scanf("%d", &i); while(i!=1&&i!=0){ printf("Enter number 1(event) or 0(no event) : "); scanf("%d", &i); } if(i==1){ printf("1+1 : enter 1, 2+1 : enter 2: "); scanf("%d", &s->event); while(s->event!=1&&s->event!=2){ printf("Enter number 1(1+1) or 2(2+1) : "); scanf("%d", &s->event); } } else s->event=0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "AVL.h" int main(){ int escolha, x, y=0; no *T; system("cls"); puts("Arvore AVL"); system("pause"); system("cls"); puts("Inicializar a Arvore?"); puts("1.sim"); scanf("%d", &escolha); if(escolha==1){ iniarvore(&T); } system("cls"); while(true){ puts("2. Inserir"); puts("3. Acha valor"); puts("4. Acha menor valor"); puts("5. Acha maior valor"); puts("6. Remover valor"); puts("7. Imprime Arvore"); puts("8. Esvaziar arvore"); puts("99. Sair"); scanf("%d", &escolha); system("cls"); if(escolha==2){ puts("Digite o numero que deseja acrescentar: \n"); scanf("%d", &x); insere(&T, x); system("cls"); } if(escolha==3){ puts("Digite o valor que deseja encontrar: \n"); scanf("%d", &x); system("cls"); percorretree(&T, x); system("cls"); } if(escolha==4){ system("cls"); achamenor(&T, 9999); system("pause"); system("cls"); } if(escolha == 5){ achamaior(&T); system("pause"); system("cls"); } if(escolha == 6){ puts("Digite o valor que deseja remover: \n"); scanf("%d", &x); system("cls"); removeavl(&T, x); } if(escolha==7){ system("cls"); int choice=0; printf("Qual metodo deseja imprimir os valores?\n"); puts("1. Em Ordem"); puts("2. Pre Ordem"); puts("3. Pos Ordem"); scanf("%d", &choice); if(choice == 1){ imprimeOrd(&T); }else if(choice == 2){ imprimePre(&T); }else if(choice == 3){ imprimePos(&T); } system("pause"); system("cls"); puts("\n"); } if(escolha==8){ end(&T); system("cls"); puts("Arvore deletada."); y = 0; system("pause"); system("cls"); } if(escolha==99){ return -1; } } }
C
#include <stdio.h> #include <stdlib.h> int ex4(void) { int x, y, c, d; int a = 45, b = 55; printf("ï]ƶq:"); scanf("%d", &x); printf("Qsƶq:"); scanf("%d", &y); c = x + y; d = (a*x) + (b*y); if (c > 15) { if (d >= 800) printf("ɦ9ufA:%d \n", d * 9 / 10); else printf(":%d \n", d); } else printf(":%d \n", d); }
C
#include <stdio.h> #include <stdarg.h> static void foo(char *fmt, ...) { va_list ap; int d; char c, *s; va_start(ap, fmt); char buf[128] = {0}; snprintf(buf, sizeof(buf), "The buffer is %s\n", fmt); vprintf(buf, ap); va_end(ap); // while (*fmt) { // switch(*fmt++) { // case 's': /* string */ // s = va_arg(ap, char *); // printf("string %s\n", s); // break; // case 'd': /* int */ // d = va_arg(ap, int); // printf("int %d\n", d); // break; // case 'c': /* char */ // /* need a cast here since va_arg only // takes fully promoted types */ // c = (char) va_arg(ap, int); // printf("char %c\n", c); // break; // } // va_end(ap); // } } int main(int argc, char *argv[]) { foo("%d", 2); foo("%s", "I love you"); return 0; }
C
/*Programme réaliser par Aladin SALEH & Paul MINGUET **06/02/21 **IUT Sénart Fontainebleau - Année 2 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <sys/shm.h> #include <assert.h> #include <sys/types.h> #include <sys/wait.h> #include "./Header/types.h" #include "./Header/erreur.h" #include <time.h> int main(int argc, char const *argv[]) { key_t cle; /* cle de la file */ int file_mess, pls_crt_file; /* ID de la file */ struct msqid_ds buff, buf; command_t commande; commandcliserv_t cmdRecue; int nbSpe = (int) strtol((argv[1]), NULL, 0); char cleVal = 'b'; char *tmp = NULL; int choixSpe = -1; pid_t pid = getpid(); tmp = (char *)malloc((4 + 20) * sizeof(char)); sprintf(tmp, "c%c.serv", cleVal); cle = ftok(tmp, cleVal); /* Recuperation file de message : */ pls_crt_file = msgget(cle, 0); assert(pls_crt_file != -1); /* Séléction du serveur le moins occupé */ while(1) { sprintf(tmp, "c%c.serv", cleVal); cle = ftok(tmp, cleVal); if(cle == -1) { file_mess = pls_crt_file; break; } file_mess = msgget(cle, 0); msgctl(file_mess, IPC_STAT, &buf); msgctl(pls_crt_file, IPC_STAT, &buff); if(buff.msg_qnum > buf.msg_qnum) pls_crt_file = file_mess; cleVal++; } /* Choix de la spécialité */ srand(pid); choixSpe = (rand() % nbSpe) + 1; /* creation de la requete : */ commande.type = 1; commande.choix = choixSpe; commande.expediteur = getpid(); /* Envoie la commande au serveur */ if(msgsnd(file_mess, &commande, sizeof(command_t)-sizeof(long), 0) == -1) { perror("Erreur lors de l'envoi de la commande "); exit(-1); } couleur(CYAN); printf("Le client %d envoie la commande %d sur la file ", pid, commande.choix); couleur(BLANC); printf("%d\n", file_mess); couleur(REINIT); /* attente de la reponse : et paie */ if (msgrcv(file_mess, &cmdRecue, sizeof(commandcliserv_t) - sizeof(long), (long) getpid(), 0) == -1) { // On attend un message de type 3 (serveur) perror("Erreur lors de la recuperation de la commande "); exit(-1); } couleur(CYAN); printf("Le client %d paye\n", pid); couleur(REINIT); /*if(msgsnd(file_mess, &commande, sizeof(command_t)-sizeof(long), 0) == -1) { perror("Erreur lors de l'envoi de la commande"); exit(-1); } couleur(CYAN); printf("Le client %d a payé\n", pid); couleur(REINIT);*/ /* attente de la commande */ /*if (msgrcv(file_mess, &cmdRecue, sizeof(commandcliserv_t) - sizeof(long), (long) getpid(), 0) == -1) { // On attend un message de type 3 (serveur) perror("Erreur lors de la recuperation de la commande "); exit(-1); }*/ couleur(CYAN); printf("Le client %d reçoit la commande %d\n",pid, cmdRecue.choix); couleur(REINIT); }
C
/* * mymalloc.c * * Created on: Feb 12, 2019 * Author: FahadMirza */ #include <stdio.h> #include <stdint.h> #include <stdbool.h> #define HEAP_SIZE (256U) static uint8_t heap_space[HEAP_SIZE + 1]; static uint8_t *topOfHeap = heap_space; static int availableHeapSize = HEAP_SIZE; typedef struct sBlockMeta { struct sBlockMeta *next; int size; bool free; }sBlockMeta_t; static sBlockMeta_t *Head = NULL; #define META_SIZE sizeof(sBlockMeta_t) /********************* Private Function Declarations *********************/ static sBlockMeta_t * requestSpace(size_t size); static sBlockMeta_t * findFreeSpace(sBlockMeta_t **last, size_t size); /********************* Function Definitions *********************/ void * Mymalloc(size_t size) { if(size <= 0) { return NULL; } printf("Available size prev: %d\n", availableHeapSize); printf("topOfHeap add prev: %p\n", topOfHeap); sBlockMeta_t *last; sBlockMeta_t *ptr = findFreeSpace(&last, size); if(ptr == NULL) { ptr = requestSpace(size); if(ptr == NULL) { return NULL; } if(Head == NULL) { Head = ptr; } else { last->next = ptr; } } else { ptr->free = false; } printf("Available size cur: %d\n", availableHeapSize); printf("topOfHeap add cur: %p\r\n", topOfHeap); // As last is sBlockMeta_t type, incrementing by one will // point to the address after META_SIZE ptr++; return ((void *)ptr); } static sBlockMeta_t * findFreeSpace(sBlockMeta_t **last, size_t size) { sBlockMeta_t *current = Head; while(current != NULL && !(current->free == true && current->size >= size)) { *last = current; current = current->next; } return current; } static sBlockMeta_t * requestSpace(size_t size) { if((size + META_SIZE) > availableHeapSize) { return NULL; } availableHeapSize -= (size + META_SIZE); sBlockMeta_t *prevTop = (sBlockMeta_t *)topOfHeap; topOfHeap = (topOfHeap + size + META_SIZE); prevTop->free = false; prevTop->next = NULL; prevTop->size = size; return prevTop; } void free(void *ptr) { if(ptr == NULL) { return; } sBlockMeta_t *blockPtr = (sBlockMeta_t *)ptr - 1; blockPtr->free = true; }
C
/* * RepositoryHandler.h * * Created on: Jul 21, 2015 * Author: suryaveer */ /* This function will insert the resource in the repository. Input Parameters: db_key_t* _k: List of Columns. db_val_t* _v: List of Values int _n total: number of values char _rt: Type of resource (Presentity/Subscriber/ etc) char _r: Id of resource in case of PUT request. Optional. */ int insertResource(const db_key_t* _k, const db_val_t* _v, const int _n, const char *_rt, const char *_r); /* This function will insert the resource in the repository. Input Parameters: db_key_t* _k: List of Columns. db_val_t* _v: List of Values int _n total: number of values db_res_t** _r: Pointer to structure where results will be stored. char _rt: Type of resource (Presentity/Subscriber/ etc) char _p: Id of resource. ex username@domain.com */ int getResource(const db_key_t* _k, const db_val_t* _v, const int _n, db_res_t** _r, const char *_rt, char* _u1, char* _u2, const db_key_t* _kr, const int _nr); /* This function will delete the resource in the repository. Input Parameters: db_key_t* _k: List of Columns. db_val_t* _v: List of Values int _n total: number of values char _rt: Type of resource (Presentity/Subscriber/ etc) char _p: Id of resource. ex username@domain.com */ int deleteResource(const db_key_t* _k, const db_val_t* _v, const int _n, const char *_rt, char* _u1, char* _u2); /* This function will check for the resource in the repository. Input Parameters: db_key_t* _k: List of Columns. db_val_t* _v: List of Values int _n total: number of values char _rt: Type of resource (Presentity/Subscriber/ etc) char _p: Id of resource. ex username@domain.com */ int checkResource(const db_key_t* _k, const db_val_t* _v, const int _n, const char *_rt, char* _p); /* This function will update the resource in the repository. Input Parameters: db_key_t* _qk: List of query Columns. db_val_t* _qv: List of query Values int _qn total: number of query values db_key_t* _uk: List of update Columns. db_val_t* _uv: List of update Values int _un total: number of update values char _rt: Type of resource (Presentity/Subscriber/ etc) char _r: Id of resource in case of PUT request. Optional. */ int updateResource(const db_key_t* _qk, const db_val_t* _qv, const db_key_t* _uk, const db_val_t* _uv, const int _qn, const int _un, const char *_rt, char* _u1, char* _u2);
C
#include <stdlib.h> #include <stdio.h> #include "mvm.h" #include "unittest.h" static TInst inst; static bool test_mvm_byte_size(TTestContext* ctx) { return assertEqualInt(1, sizeof(mvm_byte), ctx, "mvm_byte size"); } static bool test_mvm_half_size(TTestContext* ctx) { return assertEqualInt(2, sizeof(mvm_half), ctx, "mvm_half size"); } static bool test_mvm_int_size(TTestContext* ctx) { return assertEqualInt(4, sizeof(mvm_int), ctx, "mvm_int size"); } static bool test_inst_size(TTestContext* ctx) { return assertEqualInt(4, sizeof(TInst), ctx, "TInst size"); } static bool test_inst_uNull_size(TTestContext* ctx) { return assertEqualInt(4, sizeof(inst.uNull), ctx, "inst.uNull size"); } static bool test_inst_uIH_size(TTestContext* ctx) { return assertEqualInt(4, sizeof(inst.uIH), ctx, "inst.uIH size"); } static bool test_inst_uI_size(TTestContext* ctx) { return assertEqualInt(2, sizeof(inst.uI), ctx, "inst.uI size"); } static bool test_inst_uII_size(TTestContext* ctx) { return assertEqualInt(3, sizeof(inst.uII), ctx, "inst.uII size"); } static bool test_inst_uIII_size(TTestContext* ctx) { return assertEqualInt(4, sizeof(inst.uIII), ctx, "inst.uIII size"); } TestCase cases[] = { test_mvm_byte_size, test_mvm_int_size, test_mvm_half_size, test_inst_size, test_inst_uNull_size, test_inst_uIH_size, test_inst_uI_size, test_inst_uII_size, test_inst_uIII_size, }; int main(int argc, const char** argv) { TTestContext ctx; int len; TTestContext_Init(&ctx); len = sizeof(cases)/sizeof(TestCase); test_runner((TTestContext*)&ctx, cases, len); TTestContext_Clean(&ctx); return 0; }
C
#include <stdio.h> void main(){ int data1 = 5, data2 = 3; int result1 = data1 > 7; int result2 = data2 <=data1; int result3 = data2 == 7; int result4 = data2 != data1; printf("result : %d, %d, %d, %d\n", result1, result2, result3, result4); }
C
#include <sys/types.h> #include <unistd.h> #include <stdint.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> int main(void) { uint64_t fileSz = 7281; uint64_t i = 0; /* printf("Enter the size of file: "); scanf("%llu", &fileSz); */ int fd = open("arc.txt", O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); lseek(fd, fileSz - 1, SEEK_SET); write(fd, "", 1); uint8_t* ptr = NULL; ptr = (uint8_t*)mmap(NULL, fileSz, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(ptr != MAP_FAILED) { for(i = 0; i < fileSz; ++i) { ptr[i]='A'; } } msync(ptr, fileSz, MS_SYNC); munmap(ptr, fileSz); close(fd); return 0; }
C
/* ** NAME ** isnobal -- run snowmelt model over a set of images ** ** SYNOPSIS ** #include "pgm.h" ** ** void ** isnobal( ** int out_step) |* # of data tsteps per output img *| ** ** DESCRIPTION ** isnobal reads all input files, performs calculations and writes output ** images for 2-layer energy-balanced snomelt model. ** ** RETURN VALUE ** ** GLOBALS ACCESSED ** */ #include <math.h> #include <string.h> //#include <omp.h> #include "ipw.h" #include "fpio.h" #include "pgm.h" #include "snobal.h" //OUTPUT_REC *create_output( int num) { // //} void isnobal( int out_step, /* # of data tsteps per output img */ int nthreads, /* number of threads to use */ int dynamic_teams, /* number of dynamic teams to use */ int got_opt_F, /* got option F? */ int verbose, /* verbose output */ int nbits) /* number of bits for output image */ { double data_tstep; /* data timestep */ double step_time; /* start time of current data tstep */ int step; /* step loop counter */ int end_step; /* end step index */ bool_t first_step; /* is first step? */ bool_t last_step; /* is last step? */ int out_counter; /* counter for data tsteps per output*/ bool_t output; /* output images this step? */ // char emfile[255]; /* name for temp e/m output file */ // char snowfile[255]; /* name for temp snow output file */ // int tempin; /* index of temp filename for input */ // int tempout; /* index of temp filename for output */ double timeSinceOut; /* local copy of 'time_since_out' */ bool_t sun_up[2]; /* is S_n band in input images? */ char pre_img[255]; /* file name for precip image */ int N; /* number of grid point */ int n; /* loop iteration */ // printf("here\n"); data_tstep = tstep_info[DATA_TSTEP].time_step; nsamps = hnsamps(fdic); nlines = hnlines(fdic); N = nsamps*nlines; // array of pointers to OUTPUT_REC OUTPUT_REC ** output_rec = (OUTPUT_REC **) calloc(N, sizeof(OUTPUT_REC *)); for(n = 0; n < N; ++n) output_rec[n] = malloc(sizeof(OUTPUT_REC)); // initialize the memory (in heap) at that pointer /* set threads */ if (nthreads != 1) { omp_set_num_threads(nthreads); // Use N threads for all consecutive parallel regions } /* * Since no output required by 'snobal' library, don't give it an output * function. */ out_func = NULL; /* Allocate I/O buffers for image files */ buffers(); /* initialize time of starting step */ step_time = start_step * data_tstep; /* determine # of digits for the suffixes of input and output images */ end_step = start_step + nstep - 1; nDigits = (int) (log10((double) end_step)) + 1; /* loop on data timesteps */ out_counter = 0; timeSinceOut = 0.0; for (step = start_step; step <= end_step; step++) { first_step = (step == start_step); last_step = (step == end_step); if (verbose) { printf("Time step -- %i\n", step); } /* open input image files */ if (first_step) { fdi1 = open_input(in_prefix, step, &sun_up[0]); } else { sun_up[0] = sun_up[1]; } fdi2 = open_input(in_prefix, step+1, &sun_up[1]); /* check for precip data this time step */ if (pfp != NULL) { if (precip_event(SEC_TO_HR(step_time), pre_img)) { fdp = uropen(pre_img); if (fdp == ERROR) { error("can't open image \"%s\"", pre_img); } precip_hdrs(pre_img); } else { fdp = ERROR; } } else { fdp = ERROR; } /* * Do we write output images this time step? If it's * the last step, then we do. * If writing output images, open temp files for pixel data. */ out_counter++; if (last_step) { output = TRUE; } else if (out_counter == out_step) { output = TRUE; out_counter = 0; } else { output = FALSE; } /* read input data and do calculations */ read_data(first_step); if (nthreads != 1) { #pragma omp parallel shared(output_rec, ibuf1, ibuf2, icbuf, pbuf, mbuf, sbuf, embuf, fdp, fdm, restart, output, first_step)\ private(n) \ copyin(tstep_info, z_u, z_T, z_g, relative_hts, max_z_s_0, max_h2o_vol, out_func) { #pragma omp for schedule(dynamic, dynamic_teams) for (n = 0; n < N; n++) { /* initialize some global variables for 'snobal' library for each pass since the routine 'do_data_tstep' modifies them */ current_time = step_time; time_since_out = timeSinceOut; precip_now = (fdp != ERROR); /* extract data from I/O buffers */ if (extract_data(first_step, n, sun_up, output_rec)) { /* run model on data for this pixel */ if (! do_data_tstep()) error("During step %d, at pixel %i", step, n); /* assign data to output buffers */ assign_buffers(FALSE, n, output, output_rec); } else { /* masked point */ assign_buffers(TRUE, n, output, output_rec); } } /* for loop on grid */ } /* end of parallel region */ } else { for (n = 0; n < N; n++) { /* initialize some global variables for 'snobal' library for each pass since the routine 'do_data_tstep' modifies them */ current_time = step_time; time_since_out = timeSinceOut; precip_now = (fdp != ERROR); /* extract data from I/O buffers */ if (extract_data(first_step, n, sun_up, output_rec)) { /* run model on data for this pixel */ if (! do_data_tstep()) error("During step %d, at pixel %i", step, n); /* assign data to output buffers */ assign_buffers(FALSE, n, output, output_rec); } else { /* masked point */ assign_buffers(TRUE, n, output, output_rec); } } /* for loop on grid */ } /* write output buffers to output files */ // write_data(output, last_step); /* close input images */ if (first_step) { fpclose(fdi1); } fpclose(fdi2); if (fdp != ERROR) { fpclose(fdp); } /* increment time */ step_time += data_tstep; if (output) { timeSinceOut = 0.0; } else { timeSinceOut += data_tstep; } /* output any images for this time step */ if (output) { uclose(fdem); e_m_image(step, output_rec, nbits); // first_em_pix = TRUE; uclose(fds); snow_image(step, output_rec, nbits); // first_snow_pix = TRUE; } } /* for loop on timesteps */ /* remove temp files */ // uremove(emfile); // uremove(snowfile); // for(n = 0; n < N; ++n) // free(output_rec); for(n=0;n<N;n++){ if (output_rec[n] != NULL){ //don't want to free(NULL), cause coredump free(output_rec[n]); //free allocated memory within array } } free(output_rec); //free array }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "deviceLibrary.h" #include "ArduinoDriverLibrary.h" #define BUFFER_LENGTH 256 /* processMoveDevice: this method call the device driver, it sends nextMove: 1 if the move is touch, 2 if the move is push, 3 if the move is drag, posFin and posIni a number in the range 0-9 */ int processMoveDevice(int posIni, int posFin, int nextMove) { printf("-> Device response new move processed: -i %d -f %d -t %d\n",posIni,posFin,nextMove); char initialPosition[20]; char finalPosition[20]; char nextMovement[20]; char* messageFromArduino; sprintf(initialPosition, "%d",posIni); sprintf(finalPosition, "%d",posFin); sprintf(nextMovement, "%d",nextMove); char coma1[16]; char coma2[16]; strcpy(coma1, ","); strcpy(coma2, ","); strcat(initialPosition, coma1); strcat(initialPosition, finalPosition); strcat(initialPosition, coma2); strcat(initialPosition, nextMovement); //aqui va la logica de comunicacion con el device driver write send_message_to_arduino (initialPosition); //Send this message to the arduino while(strcmp(read_message_send_from_arduino(), "L") != 0){ } //cuando termina tiene que hacer un read y retornar 1 si todo salió bien y 0 si palmo messageFromArduino = read_message_send_from_arduino(); //Read the message send from the arduino if(strcmp(messageFromArduino, "L") == 0){ printf("Todo salio bien\n"); return 1; } else{ printf("Hubo un error\n"); return 0; } } /* processBoardDevice: this method call the device driver, it sends size board: 1 if the board is 1x1, 2 if the board is 2x2, 3 if the board is 4x4 */ int processBoardDevice(int sizeBoard) { char boardSize[20]; char boardType[16]; char* messageFromArduino; sprintf(boardSize, "%d",sizeBoard); strcpy(boardType, "Board:"); strcat(boardType, boardSize); printf("-> Device response new board processed: -b %d\n",sizeBoard); //aqui va la logica de comunicacion con el device driver write send_message_to_arduino (boardType); //Send this message to the arduino //cuando termina tiene que hacer un read y retornar 1 si todo salió bien y 0 si palmo messageFromArduino = read_message_send_from_arduino(); //Read the message send from the arduino if(strcmp(messageFromArduino, "L") == 0){ printf("Todo salio bien\n"); return 1; } else{ printf("Hubo un error\n"); return 0; } }
C
#include <stdio.h> int eh_primo(int n){ int i; for(i=2;i<n;i++){ if(n%i==0){ return 0; } } return 1; } int main(void){ int n; int bol; printf("digite um numero "); scanf("%d",&n); bol = eh_primo(n); if(bol==0){ printf("nao eh primo\n"); } else{ printf("eh primo\n"); } return 0; }
C
// // main.c // OSLab1 // // Created by Алексей Агеев on 08.10.2020. // #include <stdio.h> #include <stdlib.h> #include <memory.h> #include <unistd.h> #include <sys/fcntl.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <string.h> #include <errno.h> #include <sys/file.h> /* A = 146 * 1024 * 1024; B = (void *)0x3C3EE19; C = mmap; D = 13; E = 138; F = nocache; G = 67; H = random; I = 38; J = avg; K = flock */ typedef struct { int fileDescriptor; int* address; int length; } FillMemoryArguments; typedef struct { char *start; size_t size; int file; int upperBound; } WriteToFileArguments; typedef struct { int file; int *sum; int *count; off_t size; } ReadFileArguments; void allocateMemory(void*, int, int); void initialFillingOfMemory(int, void*, int, int); void* fillMemory (void*); void* writeFile (void*); void* readFile(void*); //pthread_mutex_t mallocMutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, const char * argv[]) { const size_t A = 146 * 1024 * 1024; void* B = (void *)0x3C3EE19; const int D = 13; const int E = 138 * 1024 * 1024; const int G = 67; const int I = 38; // void* startAdress = B; int fillLength; if (A % D == 0) { fillLength = A / D; } else { fillLength = A / D + 1; } int outputFileDescriptor = open("output.txt", O_RDWR | O_APPEND | O_CREAT, 0677); printf("Press enter to allocate memory."); getchar(); allocateMemory(B, A, outputFileDescriptor); printf("Memory was allocated. Press enter to fill memory."); getchar(); initialFillingOfMemory(D, B, fillLength, A); printf("Memory was filled. Press enter to deallocate memory."); getchar(); munmap(B - (int)B % getpagesize(), //addr: starting adress of mapping A); //length: length of mapping printf("Memory was deallocated. Press enter for the second part"); getchar(); allocateMemory(B, A, outputFileDescriptor); initialFillingOfMemory(D, B, fillLength, A); unsigned numberOfFiles; if (A % E == 0) { numberOfFiles = A / E; } else { numberOfFiles = A / E + 1; } int descriptors[numberOfFiles]; for (int file = 0; file < numberOfFiles; file += 1) { char filename[7]; sprintf(filename, "%i-file", file); descriptors[file] = open(filename, O_RDWR | O_CREAT | O_TRUNC /*| O_DIRECT*/, 0777); } for (;;) { int count = 0; int sum = 0; pthread_t writeThreads[I]; WriteToFileArguments writeToFileArguments[I]; ReadFileArguments readFileArguments[I]; for (int threadNumber = 0; threadNumber < I; threadNumber += 1) { int fileId = threadNumber % numberOfFiles; writeToFileArguments[threadNumber].start = B; writeToFileArguments[threadNumber].size = G; writeToFileArguments[threadNumber].file = descriptors[fileId]; writeToFileArguments[threadNumber].upperBound = fillLength; readFileArguments[threadNumber].sum = &sum; readFileArguments[threadNumber].count = &count; readFileArguments[threadNumber].file = descriptors[fileId]; readFileArguments[threadNumber].size = fillLength; pthread_create(&writeThreads[threadNumber], NULL, writeFile, &writeToFileArguments[threadNumber]); } pthread_t readThreads[I]; for (int threadNumber = 0; threadNumber < I; threadNumber += 1) { pthread_join(writeThreads[threadNumber], NULL); } for (int threadNumber = 0; threadNumber < I; threadNumber += 1) { pthread_create(&readThreads[threadNumber], NULL, readFile, &readFileArguments[threadNumber]); } for (int threadNumber = 0; threadNumber < I; threadNumber += 1) { pthread_join(readThreads[threadNumber], NULL); } printf("Current sum = %i, count = %i, avg = %f\n", sum, count, (double)sum / (double)count); } return 0; } void allocateMemory(void* address, int length, int outputFileDescriptor) { mmap(address, // addr: starting adress of mapping length, // length: length of mapping PROT_READ | PROT_WRITE, // prot: protection flags MAP_PRIVATE, // flags: visibility flags outputFileDescriptor, // fd: file descriptor 0); // offset: offset in a file } void initialFillingOfMemory(int numberOfThreads, void* address, int fillLength, int length) { pthread_t fillThreads[numberOfThreads]; int randomFileDescriptor = open("/dev/urandom", O_RDONLY); for (int threadNumber = 0; threadNumber < numberOfThreads; threadNumber += 1) { FillMemoryArguments arguments = { .fileDescriptor = randomFileDescriptor, .address = address + fillLength * threadNumber, .length = threadNumber == numberOfThreads - 1 ? fillLength : length - (numberOfThreads - 1) * threadNumber }; pthread_create(&fillThreads[threadNumber], NULL, fillMemory, &arguments); } for (int threadNumber = 0; threadNumber < numberOfThreads; threadNumber += 1) { pthread_join(fillThreads[threadNumber], NULL); } } void* fillMemory (void* arguments) { FillMemoryArguments *data = (FillMemoryArguments*) arguments; read(data->fileDescriptor, data->address, data->length); pthread_exit(NULL); } void* writeFile(void* arguments) { WriteToFileArguments *data = (WriteToFileArguments *) arguments; size_t result; char* random = data->start + rand() % data->upperBound;// - data->size; flock(data->file, LOCK_EX); lseek(data->file, data->size, SEEK_SET); result = write(data->file, &random, data->size); flock(data->file, LOCK_UN); if (result == -1) { printf("Write thread failed, error: %s\n", strerror(errno)); } pthread_exit(NULL); } void* readFile(void* arg) { ReadFileArguments *data = (ReadFileArguments *) arg; char* buf = (char *) malloc(data->size); if (buf == NULL) { printf("Could not allocate read buffer\n"); pthread_exit(NULL); } flock(data->file, LOCK_EX); lseek(data->file, 0, SEEK_SET); size_t result = read(data->file, buf, data->size); flock(data->file, LOCK_UN); if (result == -1) { printf("Read thread failed, error: %s\n", strerror(errno)); free(buf); pthread_exit(NULL); } for (int i = 0; i < data->size; i++) { *(data->sum) += (int) buf[i]; } *(data->count) += data->size; free(buf); pthread_exit(NULL); }
C
#include "bigz.h" /* * Unsigned multiplication. Returns |a * b| */ bigz * bigz_umul(bigz * a, bigz * b) { int i, j; unsigned int sum_carry, carry, mul_carry; unsigned int tmp, c0, c1, c2, c3; /* storage for partial products */ bigz *prod; if (a->size < b->size) { prod = a; a = b; b = prod; } prod = make_bigz(a->size + b->size); for (i = 0; i < b->size; i++) { sum_carry = mul_carry = 0; #define HALF (sizeof(unsigned int) * 8 / 2) #define HALF_INT (((unsigned int) ~0) >> HALF) #define tohi(x) ((x) << HALF) #define hi(x) ((x) >> HALF) #define lo(x) (HALF_INT & (x)) for (j = 0; j < a->size; j++) { c0 = lo(b->limbs[i]) * lo(a->limbs[j]); c1 = hi(b->limbs[i]) * lo(a->limbs[j]); c2 = lo(b->limbs[i]) * hi(a->limbs[j]); c3 = hi(b->limbs[i]) * hi(a->limbs[j]); tmp = c0 + tohi(c1) + tohi(c2) + mul_carry; carry = tmp < mul_carry; carry += lo(c1) + lo(c2) + hi(c0) >> HALF; mul_carry = c3 + hi(c1) + hi(c2) + carry; prod->limbs[i + j] += tmp + sum_carry; if (sum_carry) sum_carry = prod->limbs[i + j] <= tmp; else sum_carry = prod->limbs[i + j] < tmp; } #undef hi #undef lo #undef HALF_INT #undef HALF prod->limbs[i + j] += mul_carry + sum_carry; /* * Last digit is always added to zero. Last digit is always less * than MAX digit, therefore carry won't propagate to the next digit. * No overflow handling is needed. */ } return (prod); } /* * Signed multiplication. Returns a * b. */ bigz * bigz_mul(bigz * a, bigz * b) { bigz *prod; prod = bigz_umul(a, b); if (a->sign != b->sign) prod->sign = NEGATIVE; return prod; }
C
#include <stdio.h> #include <math.h> int main() { double x, y, delta, del; double a, b, c; printf("insert ax²+bx+c :"); scanf("%lf %lf %lf", &a, &b, &c); delta = (b)*(b) - (4*((a)*(c))); printf("%lf \n", delta); if (delta > 0 && a!= 0){ del = sqrt (delta); printf("%lf", del); x = (-b + del)/(2*(a)); y = (-b - del)/(2*(a)); printf(" the roots of %.0lfx² %.0lfx %.0lf are %.2lf %.2lf \n",a ,b ,c, x, y); }else{ printf("roots impossible or imaginary \n"); } return 0; }
C
#include <stdio.h> int main() { int day,x1,x2; day=0; x1=1020; while (x2>=0) { x2=x1-(0.5*x1+2); x1=x2; day++; } printf("day=%d\n",day-1); return 0;}
C
/* ** main.c for in /home/fourni_s/UNIX/WarpZone/Astar ** ** Made by sonny fournier ** Login <fourni_s@epitech.net> ** ** Started on Sun May 22 10:31:00 2016 sonny fournier ** Last update Sun May 22 21:04:47 2016 sonny fournier */ #include "my.h" int check_map(char *s, t_read *lab) { int i; int test; lab->size.x = 0; while (s[lab->size.x] && s[lab->size.x] != '\n') lab->size.x = lab->size.x + 1; i = lab->size.x; lab->size.y = 0; while (s[i]) { if (s[i] == '\n') i++; lab->size.y = lab->size.y + 1; test = 0; while (s[i] && s[i] != '\n' && (s[i] == 'X' || s[i] == '*')) { i++; test++; } if (test != lab->size.x && (test != 0 && s[i])) return (0); } return (cpy_map(s, lab)); } void get_hei(char *s, t_read *lab) { int i; i = -1; while (s[++i]); lab->len = (i - lab->wid); } int cpy_map(char *s, t_read *lab) { int i; int j; i = -1; j = 0; if ((lab->lab = malloc(lab->size.x * lab->size.y + 1)) == NULL) return (0); while (s[++i]) if (s[i] == '\n') { lab->wid = i; break; } get_hei(s, lab); i = 0; while (s[i]) { if (s[i] == '\n') i++; else lab->lab[j++] = s[i++]; } return (1); } int map_to_tab(t_read read, t_move *move) { int i; int j; char **map; i = 0; j = 0; if ((map = malloc(sizeof(char *) * read.len)) == NULL) return (-1); while (j != (read.len / read.wid)) { map[j] = strdup(my_strcut(read.lab, (j * read.wid), (read.wid), 0)); j++; } while (move != NULL) { map[move->x][move->y] = 'o'; move = move->next; } while (i != (read.len / read.wid)) printf("%s\n", map[i++]); return (0); } int main(int ac, char **av) { t_read read; t_move *move; if (ac != 2) return (my_putstr("Use: ./astar map\n", 2)); else if (get_map(av[1], &read) == 0) return (0); read.pos.x = 0; read.pos.y = 0; read.end.x = read.size.x - 1; read.end.y = read.size.y - 1; move = a_star(read.lab, &read.size, &read.pos, &read.end); map_to_tab(read, move); free(read.lab); return (1); }
C
#include <stdlib.h> #include "stack.h" Stack *createNewStack(Tree *tree) { Stack *newStack = (Stack*) malloc(sizeof(Stack)); newStack->tree = tree; newStack->next = NULL; return newStack; } void push(Stack **stack, Tree *tree) { Stack *new = createNewStack(tree); Stack *head = *stack; if (head == NULL) { *stack = new; return; } new->next = head; *stack = new; return; } Tree *pop(Stack **stack) { Stack *head = *stack; if (head == NULL) return NULL; Tree* tree = head->tree; *stack = head->next; free(head); return tree; } void deleteStack(Stack *stack) { if (stack == NULL) return; Stack *next = stack->next; Tree *tree = stack->tree; free(stack); deleteTree(tree); deleteStack(next); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <conio.h> // Prototipos MayMen // int NumSecreto (int ar[11],int N); void IngresoNum (int ar[11],int N); int Puntaje (int ar[11],int N); int MayMen(); // Definiciones int MayMen() { int ar[11],N; IngresoNum (ar,N); } void IngresoNum (int ar[11],int N) { int num,numsecret,lim_sup = 1000,lim_inf=1,aux=0,aux2=0,ganar,lugar; N = N + 10; numsecret = NumSecreto (ar,N); for (int i= 0;i<N;i++) { printf ("==========================\n",i+1); printf ("======| Intento %d |======\n",i+1); printf ("==========================\n\n",i+1);scanf ("%i", &num); if (num>= 1 and num<= 999) { ar[i] = num; if (numsecret == num) { lugar = i + 1; ganar = Puntaje (ar,lugar); break; } if (numsecret > num) { if (i == 0) { aux = num; aux2 = lim_sup; printf ("El numero secreto es mayor y se encuentra entre %i y %i\n",aux+1,aux2-1); } else { aux = num; aux2 = aux2; printf ("El numero secreto es mayor y se encuentra entre %i y %i\n",aux+1,aux2-1); } } else { if(i != 0) { aux=aux; aux2 = num; printf("El numero secreto es menor y se encuentra entre %i y %i\n",aux+1,aux2-1); } else { aux=lim_inf; aux2 = num; printf ("El numero secreto es menor y se encuentra entre %i y %i\n",aux+1,aux2-1); } } if (i == 9) { system("CLS"); printf ("=====================================================\n"); printf ("======No acertaste! El puntaje obtenido es: 0========\n"); printf ("==============El numero secreto fue %d =============\n", numsecret); printf ("=====================================================\n");break; } } else { printf ("El numero ingresado no es valido, ingrese nuevamente\n"); system ("pause"); i = i - 1; } } } int NumSecreto (int ar[11],int N) { int lim_inf = 1,lim_sup = 999,num; srand(time(NULL)); num = lim_inf + rand()%(lim_sup+1 - lim_inf); return num; } int Puntaje (int ar[11],int lugar) { int puntaje,gana; for (int i = 0;i<10;i++) { do { gana = 1; for (int i = 0;i<lugar;i++) { puntaje = 10 - i; gana = 0; } } while (gana == 1); } system("CLS"); printf("=========================================================\n"); printf("==========Acertaste! El puntaje obtenido es %d ==========\n", puntaje); printf("=========================================================\n\n"); }
C
/* * File Name: main.c * * Author: Habiba Mahmoud */ #include "MC1.h" uint8 g_tick = 0; uint8 second; /* Description : * For clock = 8Mhz and prescaler F_CPU/1024 every count will take 128 microsecond * so put initial timer counter=0 0 --> 255 (32ms per overflow) * so we need timer to overflow 31 times to get a 1 second * This is the ISR of timer0 overflow mode */ ISR(TIMER0_OVF_vect) { g_tick++; if (g_tick == NUMBER_OF_OVERFLOWS_PER_SECOND) { second++; g_tick = 0; //clear the tick counter again to count a new 0.5 second } } //START OF MAIN FUNCTION int main(void) { //Variable Declarations uint8 i,key ,new_pass[7],match_pass[7],old_pass[7],match_pass2[7]; //init lcd LCD_init(); //init uart UART_init(); /* These statements out of main as I got first password for new user just one time * I don't have to to make second MCU check for any stranger in this phase * as my user is new one with no reserved data in E2PROM */ get_pass("Enter your PW:", new_pass); _delay_ms(10); get_pass("reEnter your PW:",match_pass); F_compare(new_pass,match_pass,"reEnter your PW:",READY1); while(1) { /* * once the program started and get new password from new user you will continously * see the following messages */ LCD_displayStringRowColumn(0,0,"- open"); LCD_displayStringRowColumn(1,0,"+ New password"); _delay_ms(1000); //Get user option to do specific actions on the second MCU key = KeyPad_getPressedKey(); /* get the pressed key number */ _delay_ms(2000); /* Press time */ if (key =='+'){ get_pass("Enter old PW:", old_pass); UART_sendByte(READY2); for(i=0;i<5;i++){ while(UART_recieveByte()!=READY2){}; match_pass2[i]=UART_recieveByte(); _delay_ms(100); } //Check_Stranger(match_pass2,old_pass,"reEnter old PW:"); F_compare(match_pass2,old_pass,"reEnter old PW:",READY3); get_pass("Enter new PW:", new_pass); _delay_ms(10); get_pass("reEnter new PW:",match_pass); F_compare(new_pass,match_pass,"reEnter new PW:",READY1); } else if(key=='-'){ get_pass("Enter your PW:", new_pass); UART_sendByte(READY6); for(i=0;i<5;i++){ while(UART_recieveByte()!=READY6){}; match_pass2[i]=UART_recieveByte(); _delay_ms(100); } F_compare(match_pass2,new_pass,"reEnter your PW:",READY7); _delay_ms(100); LCD_sendCommand(CLEAR_COMMAND); LCD_displayStringRowColumn(0,0,"DOOR OPEN"); timer0_init_normal_mode(T0_F_CPU_1024, 0); while (second != 2) ; second = 0; LCD_sendCommand(CLEAR_COMMAND); LCD_displayStringRowColumn(0,0,"DOOR CLOSE"); while (second != 2) ; second = 0; } LCD_sendCommand(CLEAR_COMMAND); } }
C
#include<stdio.h> int main(void){ int x=2; printf("\ \n \t%d",x); }
C
#include <scheduler.h> extern int sum; extern pthread_mutex_t sem; extern fcfs_queue gqueue; /* =============================================================== FCFS QUEUES =============================================================== */ void fcfs_wait(fcfs_queue* queue) { uint32_t turn; /* - - Seccion critica - - */ pthread_mutex_lock(&queue->mutex); /* Asigno el turno y aumento total de turnos */ turn = queue->total_turns++; /* Espera activa de turno */ while (turn != queue->current_turn) { pthread_cond_wait(&queue->cond, &queue->mutex); } pthread_mutex_unlock(&queue->mutex); /* - - Fin Seccion critica - - */ } void fcfs_signal(fcfs_queue* queue) { /* - - Seccion Critica - - */ pthread_mutex_lock(&queue->mutex); /* Paso al siguiente turno */ queue->current_turn++; pthread_cond_broadcast(&queue->cond); pthread_mutex_unlock(&queue->mutex); /* - - Fin seccion critica - - */ } void fcfs_queue_init (fcfs_queue* queue){ /* Ambos deben arrancar en el mismo numero, preferentemente cero */ queue->total_turns = queue->current_turn = 0; /* inicializacion standard y chequeo */ pthread_cond_init(&queue->cond, NULL); assert(&queue->cond); pthread_mutex_init(&queue->mutex,NULL); assert(&queue->mutex); } void fcfs_queue_destroy(fcfs_queue* queue){ pthread_cond_destroy(&queue->cond); pthread_mutex_destroy(&queue->mutex); } /* =============================================================== Test =============================================================== */ void* thread_execute(void* arg){ int* ptr = (int*)arg; assert(ptr); int number = *ptr; /* FIFO queue */ fcfs_wait(&gqueue); printf("Thread: %d\tNro de Thread: %d\n", process_get_thread_id(), number); fcfs_signal(&gqueue); /* - - Fin Seccion Critica - - */ pthread_exit(NULL); return NULL; }
C
#ifndef SNFS_COMMON_UTILS_H #define SNFS_COMMON_UTILS_H /* * The macros below are for debugging and printing out verbose output. They are * similar to the Linux debug macros in that defining DEBUG will enable debug * output. The verbose macro will print if DEBUG was defined or if the `active` * parameter is true. */ #ifdef DEBUG #define DEBUG_ 1 #else #define DEBUG_ 0 #endif #define debug_cond(condition, stream, ...) \ do { \ if ((condition)) { \ fprintf(stream, "%s:%d:%s(): ", __FILE__, __LINE__, __func__); \ fprintf(stream, __VA_ARGS__); \ fflush(stream); \ } \ } while (0) #define debug(...) debug_cond(DEBUG_, stderr, __VA_ARGS__) #define verbose(active, ...) \ do { \ if ((active)) { \ printf(__VA_ARGS__); \ fflush(stdout); \ } \ } while (0) #define if_debug \ if (DEBUG_) /* * The macros below are helper macros for printing error messages. * Additionally, err_exit will exit with a failing return code after printing * the message. */ #define print_err(...) \ do { \ fprintf(stderr, "ERROR: "); \ fprintf(stderr, __VA_ARGS__); \ fflush(stderr); \ } while (0) #define err_exit(...) \ do { \ print_err(__VA_ARGS__); \ exit(EXIT_FAILURE); \ } while (0) #define assert_malloc(ptr) \ do { \ if (!(ptr)) { \ err_exit("Couldn't allocate memory for '%s' at %s:%d[%s()].\n", \ #ptr, __FILE__, __LINE__, __func__); \ }; \ } while (0) #define assert(cond) \ do { \ if (!(cond)) { \ err_exit("Assert '%s' failed %s:%d[%s()].\n", \ #cond, __FILE__, __LINE__, __func__); \ }; \ } while (0) /* * Given a usage() function, the macros below print some message, followed by a * new line, followed by the usage information as printed by usage(). The do, * while wrapper is a convention that is used so that an invocation of the macro * mirrors a function invocation. */ #define usage_msg(...) \ do { \ fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "\n"); \ usage(); \ } while (0) #define usage_msg_exit(...) \ do { \ usage_msg(__VA_ARGS__); \ exit(EXIT_FAILURE); \ } while (0) /* * Typed versions of min() and max(). */ #ifndef max #define max(a,b) \ ({ \ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; \ }) #endif #ifndef min #define min(a,b) \ ({ \ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; \ }) #endif /* * A simple macro that allows a variable to pass through unused checks even if * it is actually unused. */ #define UNUSED(var) \ (void)(var) #endif
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ struct TYPE_3__ {long size; } ; typedef int /*<<< orphan*/ ASN1_VALUE ; typedef TYPE_1__ ASN1_ITEM ; /* Variables and functions */ int /*<<< orphan*/ ASN1_F_LONG_C2I ; int /*<<< orphan*/ ASN1_R_ILLEGAL_PADDING ; int /*<<< orphan*/ ASN1_R_INTEGER_TOO_LARGE_FOR_LONG ; int /*<<< orphan*/ ASN1err (int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ COPY_SIZE (int /*<<< orphan*/ *,long) ; int /*<<< orphan*/ memcpy (int /*<<< orphan*/ **,long*,int /*<<< orphan*/ ) ; __attribute__((used)) static int long_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it) { int i; long ltmp; unsigned long utmp = 0, sign = 0x100; if (len > 1) { /* * Check possible pad byte. Worst case, we're skipping past actual * content, but since that's only with 0x00 and 0xff and we set neg * accordingly, the result will be correct in the end anyway. */ switch (cont[0]) { case 0xff: cont++; len--; sign = 0xff; break; case 0: cont++; len--; sign = 0; break; } } if (len > (int)sizeof(long)) { ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } if (sign == 0x100) { /* Is it negative? */ if (len && (cont[0] & 0x80)) sign = 0xff; else sign = 0; } else if (((sign ^ cont[0]) & 0x80) == 0) { /* same sign bit? */ ASN1err(ASN1_F_LONG_C2I, ASN1_R_ILLEGAL_PADDING); return 0; } utmp = 0; for (i = 0; i < len; i++) { utmp <<= 8; utmp |= cont[i] ^ sign; } ltmp = (long)utmp; if (ltmp < 0) { ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } if (sign) ltmp = -ltmp - 1; if (ltmp == it->size) { ASN1err(ASN1_F_LONG_C2I, ASN1_R_INTEGER_TOO_LARGE_FOR_LONG); return 0; } memcpy(pval, &ltmp, COPY_SIZE(*pval, ltmp)); return 1; }
C
#include <stdio.h> int main() { int albumSize,playSize,cases=0,songLen[100],playOrder[1000],isUnique,uniqueCount,time; int i,j,k; while(scanf("%d %d",&albumSize,&playSize)!=EOF && cases<150) { cases+=1; time=0; uniqueCount=0; for(i=0;i<100;++i) songLen[i] = 0; for(i=0;i<1000;++i) playOrder[i] = 0; for(i=0;i<albumSize;++i) fscanf(stdin,"%d",&songLen[i]); for(i=0;i<playSize;++i) fscanf(stdin,"%d",&playOrder[i]); for(i=0;i<playSize;++i) { isUnique=1; for(k=0;k<i;++k) { if(playOrder[i]==playOrder[k]) { isUnique = 0; break; } } if(isUnique==1 && songLen[playOrder[k]-1]) uniqueCount+=1; if(uniqueCount==albumSize) { for(j=0;j<=k;++j) time += songLen[playOrder[j]-1]; break; } } if(uniqueCount!=albumSize) printf("-1\n"); else printf("%d\n", time); } }
C
/* -*- coding: iso-latin-1-unix; -*- */ /* DECLARO QUE SOU O UNICO AUTOR E RESPONSAVEL POR ESTE PROGRAMA. // TODAS AS PARTES DO PROGRAMA, EXCETO AS QUE FORAM FORNECIDAS // PELO PROFESSOR OU COPIADAS DO LIVRO OU DAS BIBLIOTECAS DE // SEDGEWICK OU ROBERTS, FORAM DESENVOLVIDAS POR MIM. DECLARO // TAMBEM QUE SOU RESPONSAVEL POR TODAS AS COPIAS DESTE PROGRAMA // E QUE NAO DISTRIBUI NEM FACILITEI A DISTRIBUICAO DE COPIAS. // // Autor: Victor Wichmann Raposo // Numero USP: 9298020 // Sigla: VICTORWI // Data: 2015-11-23 // // Este arquivo faz parte da tarefa I // da disciplina MAC0121. // ////////////////////////////////////////////////////////////// */ #include "btree.h" static void limpa_lista (celula *aux); static void imprime_lista (celula *p, FILE *saida) ; int altura (arvore r) { if (r == NULL) return -1; else { int he = altura (r->esq); int hd = altura (r->dir); if (he < hd) return hd + 1; else return he + 1; } } arvore insere (arvore r, noh *novo) { noh *filho, *pai; if (r == NULL) return novo; filho = r; while (filho != NULL) { int aux = strcmp (filho->str, novo->str); pai = filho; if (aux > 0) filho = filho->esq; else filho = filho->dir; } if (strcmp (pai->str, novo->str) > 0) pai->esq = novo; else pai->dir = novo; return r; } noh *find (arvore r, char *k) { int aux; if (r == NULL) return r; aux = strcmp (r->str, k); if (aux == 0) return r; if (aux > 0) return find (r->esq, k); else return find (r->dir, k); } void imprime (arvore r, FILE* saida) { if (r != NULL) { imprime (r->esq, saida); fprintf (saida, "%s ", r->str); imprime_lista (r->list, saida); fprintf (saida, "\n"); imprime (r->dir, saida); } } /* Recebe uma lista encadeada p e imprime // o conteudo dessa lista em um arquivo saida */ static void imprime_lista (celula *p, FILE *saida) { if (p == NULL) return; imprime_lista (p->prox, saida); fprintf (saida, "%d, ", p->cont); } int contanoh (arvore r) { if (r == NULL) return 0; return 1 + contanoh (r->esq) + contanoh (r->dir); } void limpa_arvore (arvore r) { if (r == NULL) return; limpa_arvore (r->esq); limpa_arvore (r->dir); limpa_lista (r->list); free (r->str); free (r); } /* Recebe uma lista ligada p e da free em todas suas celulas */ static void limpa_lista (celula *p) { if (p == NULL) return; limpa_lista (p->prox); free (p); }
C
/* *c程序的内存分配,c的内存分配包括代码区,数据区,代码区,顾名思义存放代码的,数据区可以细分为 *堆区,栈区(或者叫堆栈),全局区(或叫静态数据区),常量区(字符串常量等) * * */ #include<stdio.h> extern int c; int c = 0; int m = 10; const static int k = 10; void func(int arg) { static int a = 10; printf("static a addr %p\n",&a); int b; printf("local b addr %p\n",&b); int *p = malloc(10); printf("int *p addr %p\n",p); if(p != NULL) free(p); } int main() { const int a = 10; char * str = "123"; printf("const a addr %p\n",&a); printf("const str addr %p\n",str); printf("global m addr %p\n",&m); printf("static global k addr %p\n",&k); func(0); return 0; }
C
#include <stdio.h> #include <string.h> #include <net/if.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> int main(){ int fd; struct ifreq ifr; struct sockaddr_in *s_in; fd = socket(AF_INET,SOCK_DGRAM,0); /*新しいIPv4アドレスの値や設定を反映させたいインターフェース名をifreq構造体iftに設定*/ s_in = (struct sockaddr_in *)&ifr.ifr_addr; /*IPv4*/ s_in->sin_family = AF_INET; /*変更するIPアドレス*/ s_in->sin_addr.s_addr = inet_addr("10.0.0.2"); /*IPアドレスを変更するインターフェースを指定*/ strncpy(ifr.ifr_name,"host1-veth1",IFNAMSIZ-1); /*IPアドレスを変更*/ if(ioctl(fd,SIOCSIFADDR,&ifr) != 0){ /*失敗したら理由を表示*/ perror("ioctl"); } close(fd); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/types.h> #define port 10200 int sockfd, newsockfd; struct sockaddr_in seraddr, cliaddr; char buf[255]; void CreateServerSocket(){ sockfd = socket(AF_INET, SOCK_STREAM, 0); seraddr.sin_family = AF_INET; seraddr.sin_port = htons(port); seraddr.sin_addr.s_addr = inet_addr("172.16.57.109"); bind(sockfd, (struct sockaddr *)&seraddr, sizeof(seraddr)); } void PerformServerTask(){ listen(sockfd, 5); while(1){ int clilen = sizeof(clilen); newsockfd = accept(sockfd, (struct sockaddr *)&cliaddr, &clilen); if(fork() == 0){ read(newsockfd, buf, sizeof(buf)); printf("PORT for the client: %d", ntohs(cliaddr.sin_port)); printf("\nMessage from Client %s \n", buf); write(newsockfd, buf, sizeof(buf)); close(newsockfd); exit(0); } else{ close(newsockfd); } } } int main(){ CreateServerSocket(); PerformServerTask(); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> int my_strlen(char* str) { int count = 0; while (*str != '\0') { count++; str++; } return count; } int main() { char arr[] = "hello world!"; int ret = 0; ret = my_strlen(arr); printf("%d\n", ret); return 0; }
C
#include <stdio.h> int main() { FILE *file; char buffer[100]; //open a file to write to file = fopen("intro.txt", "w"); //use fgets to get input from user printf("Write a self introduction using less than 100 characters: "); fgets(buffer, 100, stdin); //use fputs to save user input from buffer to file fputs("Your self introduction: ", file); fputs(buffer, file); fclose(file); //use fputs to display string in buffer fputs(buffer, stdout); return 0; }
C
#include<stdio.h> int main() { long long int x,n,i,v[61]; v[0] = 0; v[1] = 1; for(i=2; i<=60; i++){ v[i] = v[i-2] + v[i-1]; } scanf("%lld", &x); for(i=0; i<x; i++){ scanf("%lld", &n); printf("Fib(%lld) = %lld\n", n,v[n]); } return 0; }
C
/***************************************************************************** * * Rokko: Integrated Interface for libraries of eigenvalue decomposition * * Copyright (C) 2012-2014 by Tatsuya Sakashita <t-sakashita@issp.u-tokyo.ac.jp>, * Synge Todo <wistaria@comp-phys.org>, * Tsuyoshi Okubo <t-okubo@issp.u-tokyo.ac.jp> * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * *****************************************************************************/ #include <mpi.h> #include <rokko/rokko.h> #include <rokko/utility/frank_matrix_c.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int dim; struct rokko_parallel_dense_solver solver; struct rokko_distributed_matrix mat, Z; struct rokko_grid grid; struct rokko_localized_vector w; char* solver_name; int provided, ierr, myrank, nprocs, i; ierr = MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); ierr = MPI_Comm_rank(MPI_COMM_WORLD, &myrank); ierr = MPI_Comm_size(MPI_COMM_WORLD, &nprocs); if (argc == 3) { solver_name = argv[1]; dim = atoi(argv[2]); } else { fprintf(stderr, "error: %s solver_name dimension\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 34); } printf("solver name = %s\n", solver_name); printf("matrix dimension = %d\n", dim); rokko_parallel_dense_solver_construct(&solver, solver_name, argc, argv); rokko_grid_construct(&grid, MPI_COMM_WORLD, rokko_grid_row_major); rokko_distributed_matrix_construct(&mat, dim, dim, grid, solver, rokko_matrix_col_major); rokko_distributed_matrix_construct(&Z, dim, dim, grid, solver, rokko_matrix_col_major); rokko_localized_vector_construct(&w, dim); /* generate frank matrix */ rokko_frank_matrix_generate_distributed_matrix(&mat); rokko_distributed_matrix_print(mat); rokko_parallel_dense_solver_diagonalize_distributed_matrix(&solver, &mat, &w, &Z); if (myrank == 0) { printf("Computed Eigenvalues =\n"); for (i = 0; i < dim; ++i) printf("%30.20f\n", rokko_localized_vector_get(w, i)); } rokko_distributed_matrix_destruct(&mat); rokko_distributed_matrix_destruct(&Z); rokko_localized_vector_destruct(&w); rokko_parallel_dense_solver_destruct(&solver); rokko_grid_destruct(&grid); MPI_Finalize(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "parser.h" #include "lexer.h" #include "symbol_table.h" #include "calc.grm.h" static symbol_entry_t* symbol_table = NULL; int lr_parser(int filde) { int value_stack[100]; int value_top = 0; int parse_stack[100]; int parse_top = 0; parse_stack[parse_top] = LR_START_STATE; //Parser Engine while (1) { int crt_token = peek_token(filde); int top_state = parse_stack[parse_top]; int kind = calc_lr_action_table[top_state][crt_token]; if (kind == ACCEPT) { return (EXIT_SUCCESS); } else if (kind & _SHIFT) { parse_stack[++parse_top] = kind ^ _SHIFT; if (crt_token == T_NUM) { value_stack[value_top] = atoi(beg_lex); } else if (crt_token == T_ID) { if ((value_stack[value_top] = new_entry(&symbol_table)) == ERROR) { fprintf(stderr, "Unable to allocate enough memory :(.\n"); return (EXIT_FAILURE); } } ++value_top; advance(filde); } else if (kind & _REDUCE) { parse_top -= calc_rhs_prod_table[kind ^ _REDUCE]; int uncovered_state = parse_stack[parse_top]; int lhs_symbol = calc_lhs_prod_table[kind ^ _REDUCE]; parse_stack[++parse_top] = calc_lr_goto_table[uncovered_state][lhs_symbol] ^ _GOTO; //Place to put semantic action int tmp_val = value_stack[value_top - 1]; symbol_entry_t* crt_entry = NULL; switch (kind ^ _REDUCE) { case P_LHS_NE_RHS_TID_TEQUAL_NE: tmp_val = value_stack[value_top - 3]; crt_entry = entry_at(symbol_table, tmp_val); crt_entry->value = value_stack[value_top - 1]; crt_entry->is_defined = true; printf("-> %d\n", crt_entry->value); tmp_val = crt_entry->value; break; case P_LHS_NLineExp_RHS_NE_TNL: printf("== %d\n", value_stack[value_top - 2]); break; case P_LHS_NE_RHS_NE_TPLUS_NE: tmp_val += value_stack[value_top - 3]; break; case P_LHS_NE_RHS_NE_TMINUS_NE: tmp_val -= value_stack[value_top - 3]; break; case P_LHS_NE_RHS_NE_TMUL_NE: tmp_val *= value_stack[value_top - 3]; break; case P_LHS_NE_RHS_NE_TDIV_NE: if (!tmp_val) { fprintf(stderr, "Try to divide by zero.\n"); return (EXIT_FAILURE); } tmp_val = value_stack[value_top - 3] / tmp_val; break; case P_LHS_NE_RHS_NE_TMOD_NE: if (!tmp_val) { fprintf(stderr, "Try to do a modulo by zero.\n"); return (EXIT_FAILURE); } tmp_val = value_stack[value_top - 3] % tmp_val; break; case P_LHS_NE_RHS_NE_TEXPO_NE: tmp_val = pow(value_stack[value_top - 3], tmp_val); break; case P_LHS_NE_RHS_TPLUS_NE: tmp_val = + tmp_val; break; case P_LHS_NE_RHS_TMINUS_NE: tmp_val = - tmp_val; break; case P_LHS_NE_RHS_TLPAREN_NE_TRPAREN: tmp_val = value_stack[value_top - 2]; break; case P_LHS_NE_RHS_TLPAREN_TERROR_TRPAREN: fprintf(stderr, "Error within subexpr.\n"); break; case P_LHS_NE_RHS_TID: crt_entry = entry_at(symbol_table, tmp_val); if (!crt_entry->is_defined) { fprintf(stderr, "Symbol %s is not defined.\n", crt_entry->ident); return (EXIT_FAILURE); } tmp_val = crt_entry->value; break; } value_top -= calc_rhs_prod_table[kind ^ _REDUCE]; value_stack[value_top++] = tmp_val; } else { fprintf(stderr, "error with the token %d.\n", crt_token); int error_accept = ERROR_SLOT; while (parse_top >= 0) { int top_state = parse_stack[parse_top]; if ((error_accept = calc_lr_action_table[top_state][T_ERROR]) & _SHIFT) { parse_stack[++parse_top] = error_accept ^ _SHIFT; break; } --parse_top; } if (error_accept != ERROR_SLOT) { error_accept ^= _SHIFT; while (peek_token(filde) != T_EOF && (calc_lr_action_table [error_accept][peek_token(filde)] == ERROR_SLOT)) { advance(filde); } if (peek_token(filde) != T_EOF) { continue; } } return (EXIT_FAILURE); } } } void clean_up_parser(void) { del_symbol_table(symbol_table); symbol_table = NULL; }
C
#include <stdio.h> #include <control.h> /* * Function: parser * ----------------------------------------------- * Summary: * Takes a message and parses its type, loads * into 'buffer' or Motor Commands, and * passes into appropriate function. * * @return: * void* to be used with pthread_create to * have parser run int searate thread * * @PARAMS: * msgIN = uint8_t array message passed in * */ void* parser(uint8_t* msgIN) { int END_OF_DATA = -1; //equals MESSAGE_LENGTH int flag = -1; //set by MESSAGE_TYPE; 0 = MOTOR, 1 = DISPLAY float *cmdFront_Back; //float to recast uint32_t FORWARD_BACK float *cmdLeft_Right; //float to recast uint32_t LEFT_RIGHT //get packet_id MESSAGE.PACKET_ID = msgIN[0]; //get message_type MESSAGE.MESSAGE_TYPE = msgIN[1]; //get message_length MESSAGE.MESSAGE_LENGTH = msgIN[3]; MESSAGE.MESSAGE_LENGTH = (MESSAGE.MESSAGE_LENGTH << 8) + msgIN[2]; END_OF_DATA = MESSAGE.MESSAGE_LENGTH; //set message data pointer MESSAGE.MESSAGE_DATA = &(buffer[0]); //determine message type switch(MESSAGE.MESSAGE_TYPE) { case DISPLAY_MESSAGE_ID: //load data into buffer for(int i=0; i < END_OF_DATA; i++) { //unaffected by Endianness at chars buffer[i] = (char) msgIN[i + 4]; } //null terminate ASCII string buffer[END_OF_DATA] = '\0'; logger(1); display_message(buffer); break; case MOTOR_MESSAGE_ID: //load data into commands; account for Endianness COMMAND.FORWARD_BACK = msgIN[7] << 24; COMMAND.FORWARD_BACK += msgIN[6] << 16; COMMAND.FORWARD_BACK += msgIN[5] << 8; COMMAND.FORWARD_BACK += msgIN[4]; COMMAND.LEFT_RIGHT = msgIN[11] << 24; COMMAND.LEFT_RIGHT += msgIN[10] << 16; COMMAND.LEFT_RIGHT += msgIN[9] << 8; COMMAND.LEFT_RIGHT += msgIN[8]; //Recast to float type cmdFront_Back = &COMMAND.FORWARD_BACK; cmdLeft_Right = &COMMAND.LEFT_RIGHT; logger(0); update_motor(*cmdFront_Back, *cmdLeft_Right); break; default: printf("ERROR: Message ID not recognized\n"); break; } } /* * Function: logger * ----------------------------------------------- * Summary: * Prints out parsed Data Message to console * * @return: * void * * @PARAMS: * flag = to print out Display or Motor Message * */ void logger(int flag) { float *temp = &(COMMAND.FORWARD_BACK); float *temp2 = &(COMMAND.LEFT_RIGHT); if(flag == 1) printf("buffer = %s\n", MESSAGE.MESSAGE_DATA); else printf("forward_back = %f\t\tleft_right = %f\n", *temp, *temp2); printf("packet id = 0x%02hhX\n", MESSAGE.PACKET_ID); printf("message type = 0x%02hhX\n", MESSAGE.MESSAGE_TYPE); printf("message length = 0x%04X\n\n", MESSAGE.MESSAGE_LENGTH); } /* * Function: update_motor * ----------------------------------------------- * Summary: * Shell of function; confirms message type * * @return: * void * * @PARAMS: * forward_back = float command * lef_right = float command * */ void update_motor(float forward_back, float left_right) { printf("MOTOR MESSAGE\n"); } /* * Function: display_message * ----------------------------------------------- * Summary: * Shell of function; confirms message type * * @return: * void * * @PARAMS: * data = char* pointer to buffer * */ void display_message(char* data) { printf("DISPLAY MESSAGE\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <SDL.h> #include <glew.h> #include "psys.h" void sdl_panic(const char* msg) { fprintf(stderr, "%s: %s\n", msg, SDL_GetError()); SDL_Quit(); exit(EXIT_FAILURE); } void panic(const char* msg) { fprintf(stderr, "%s\n", msg); SDL_Quit(); exit(EXIT_FAILURE); } int main(int argc, char** argv) { SDL_Init(SDL_INIT_VIDEO); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24); SDL_Window* w = SDL_CreateWindow( "DESTROY THE UNIVERSE", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 0, 0, SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL); if(w == NULL) { sdl_panic("SDL_CreateWindow"); } SDL_GLContext c = SDL_GL_CreateContext(w); SDL_GL_MakeCurrent(w, c); GLenum err = glewInit(); if(GLEW_OK != err) { panic((const char*)glewGetErrorString(err)); } glDisable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glPointSize(2.0f); struct psys psys; psys_init(&psys); int exiting = 0; psys_step(&psys); // kickstart int simulation_running = 1; for(;;) { SDL_Event e; while(SDL_PollEvent(&e)) { if(e.type == SDL_KEYDOWN) { if(e.key.keysym.sym == SDLK_ESCAPE) { exiting = 1; } if(e.key.keysym.sym == SDLK_SPACE) { simulation_running ^= 1; } if(e.key.keysym.sym == SDLK_PERIOD) { simulation_running = 2; } } } if(exiting) break; if(simulation_running) { psys_step(&psys); if(simulation_running > 1) { simulation_running = 0; } } int width, height; SDL_GetWindowSize(w, &width, &height); glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-width/2, width/2, height/2, -height/2, 1, 0); psys_draw(&psys); SDL_GL_SwapWindow(w); } SDL_GL_DeleteContext(c); SDL_Quit(); return EXIT_SUCCESS; }
C
// // main.c // Approximation // // Created by sonnet on 10/6/13. // Copyright (c) 2013 Mad scientist. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { float x0, dt, until; printf("input x0: "); scanf("%f",&x0); printf("input dt: "); scanf("%f",&dt); printf("input until: "); scanf("%f",&until); //In MATLAB/Python, approximate x(1) for x(0)=0.5 and x˙=−3x using Euler integration and dt=0.01. float result; int loop = (int)(until/dt); for(int i=0; i<=loop; i++) { result = x0 + dt * -2 * (dt * i); x0 = result; printf("temp result: %f\n",x0); } printf("\ninput %f %f %d\n",dt,until,loop); printf("result %f\n",result); return 0; }
C
#include "libmx.h" char *mx_charjoin(char *str, char ch) { char *dst = NULL; int len = 0; if (str == NULL) { dst = mx_strnew(1); dst[0] = ch; return dst; } len = mx_strlen(str); dst = mx_strnew(len + 1); for (int i = 0; i <= len + 1; i++) { if (i == len + 1) dst[i] = ch; else dst[i] = str[i]; } return dst; }
C
/*/ 2. Ler uma string e chamar uma funo para realizar a sua inverso dentro da mesma string. Mostrar a string invertida. /*/ #include <stdio.h> #include <stdlib.h> #include <locale.h> #include <string.h> void Inverter(); void Inverter(char palavra[100]) { int i; printf("\n"); for (i = strlen(palavra) - 1; i >= 0; i--) { printf("%c", palavra[i]); } printf("\n\n\n"); } int main() { setlocale(LC_ALL, "Portuguese"); char palavra[100]; printf("Digite uma palavra: "); scanf("%[^\n]s", palavra); Inverter(palavra); system("pause"); return 0; }
C
#ifndef _SORT_H_ #define _SORT_H_ #include <stdio.h> #include <stdlib.h> /** * struct listint_s - Doubly linked list node * * @n: Integer stored in the node * @prev: Pointer to the previous element of the list * @next: Pointer to the next element of the list */ typedef struct listint_s { const int n; struct listint_s *prev; struct listint_s *next; } listint_t; void partition(int *array, size_t size, int *vector, size_t len); void print_array(const int *array, size_t size); void print_list(const listint_t *list); void bubble_sort(int *array, size_t size); void swap(listint_t **list, listint_t *check, listint_t *aux); void insertion_sort_list(listint_t **list); void selection_sort(int *array, size_t size); void quick_sort(int *array, size_t size); void shell_sort(int *array, size_t size); void counting_sort(int *array, size_t size); void sift_down(int *array, size_t size, int len, size_t size1); void make_heap(int *array, size_t size); void heap_sort(int *array, size_t size); void cocktail_sort_list(listint_t **list); void print_side(int *array, size_t size); void split_and_merge(int *array, size_t size, int *copy); void copy_array(int *array, size_t size, int *copy); void merge_sort(int *array, size_t size); void comp_swap(int *array, int j, int dir); void bitonic_merge(int *array, size_t size, int dir); void radix_sort(int *array, size_t size); void sort_digit(int *array, size_t size, int radix, int div); void bitonic_up(int *array, size_t size, int dir, size_t size_f); void bitonic_sort(int *array, size_t size); int partition_h(int *array, size_t size, int high, size_t size_f); void quick_sort_h(int *array, int low, size_t size); void quick_sort_hoare(int *array, size_t size); #endif
C
#include<stdio.h> #include<stdlib.h> #include "searchtree.h" SearchTree CreateSearchTree(Element ele) { SearchTree T; T = (SearchTree)malloc(sizeof(struct SearchTreeNode)); if (T == NULL) { fprintf(stderr, "out of memory\n"); exit(EXIT_FAILURE); } T->Element = ele; T->Left = NULL; T->Right = NULL; return T; } void SearchTreeEmpty(SearchTree T) { if (T->Left) SearchTreeEmpty(T->Left); if (T->Right) SearchTreeEmpty(T->Right); free(T); } int SearchTreeIsLeaf(SearchTree T) { if (T->Left == NULL && T->Right == NULL) return 1; return 0; } PtrToSearchTreeNode SearchTreeFind(SearchTree T, Element ele) { PtrToSearchTreeNode target, result; target = T; result = NULL; while (target != NULL) { if (ele < target->Element) { if (target->Left == NULL) break; target = target->Left; continue; } if (ele > target->Element) { if (target->Right == NULL) break; target = target->Right; continue; } result = target; break; } return result; } PtrToSearchTreeNode SearchTreeFindMin(SearchTree T) { PtrToSearchTreeNode result; result = T; while (result != NULL) { if (result->Left == NULL) break; result = result->Left; } return result; } PtrToSearchTreeNode SearchTreeFindMax(SearchTree T) { PtrToSearchTreeNode result; result = T; while (result != NULL) { if (result->Right == NULL) break; result = result->Right; } return result; } PtrToSearchTreeNode SearchTreeFindParent(SearchTree T, Element ele) { PtrToSearchTreeNode target, result; target = T; result = NULL; while (target != NULL) { if (ele < target->Element) { if (target->Left == NULL) break; if (target->Left->Element == ele) { result = target; break; } target = target->Left; continue; } if (ele > target->Element) { if (target->Right == NULL) break; if (target->Right->Element == ele) { result = target; break; } target = target->Right; continue; } break; } return result; } void SearchTreeInsert(SearchTree T, Element ele) { PtrToSearchTreeNode target, newNode; newNode = (PtrToSearchTreeNode)malloc(sizeof(struct SearchTreeNode)); if (newNode == NULL) { fprintf(stderr, "out of memory\n"); exit(EXIT_FAILURE); } target = T; while (target != NULL) { if (ele < target->Element) { if (target->Left == NULL) { target->Left = newNode; break; } target = target->Left; continue; } if (ele > target->Element) { if (target->Right == NULL) { target->Right = newNode; break; } target = target->Right; continue; } break; } // there is a same node in the tree if (target == NULL) { free(newNode); return; } newNode->Element = ele; newNode->Left = NULL; newNode->Right = NULL; } SearchTree SearchTreeDelete(SearchTree T, Element ele) { PtrToSearchTreeNode parent, target, max, mParent; enum Position {Left, Right, None}; enum Position tPosition; // find parent, target and target position if (T->Element == ele) { parent = NULL; target = T; tPosition = None; } else { parent = SearchTreeFindParent(T, ele); if (parent == NULL) { fprintf(stderr, "wrong delete target\n"); exit(EXIT_FAILURE); } target = SearchTreeFind(parent, ele); if (parent->Left == target) tPosition = Left; else tPosition = Right; } // target is leaf if (SearchTreeIsLeaf(target)) { if (tPosition == None) T = NULL; else if (tPosition == Left) parent->Left = NULL; else parent->Right = NULL; free(target); return T; } // target has left child if (target->Right == NULL) { if (tPosition == None) T = target->Left; else if (tPosition == Left) parent->Left = target->Left; else parent->Right = target->Left; free(target); return T; } // target has right child if (target->Left == NULL) { if (tPosition == None) T = target->Right; else if (tPosition == Left) parent->Left = target->Right; else parent->Right = target->Right; free(target); return T; } // target has two child max = SearchTreeFindMax(target->Right); mParent = SearchTreeFindParent(target, max->Element); if (tPosition == None) T = max; else if (tPosition == Left) parent->Left = max; else parent->Right = max; mParent->Right = NULL; max->Left = target->Left; max->Right = target->Right; free(target); return T; }
C
#include <stdio.h> #include <string.h> int main( ) { char str1[] = "gaeeks" ; char str2[] = "geeks" ; int j = strcmpi ( str1, str2 ) ; printf ( "The function returns = %d",j ) ; getch(); return 0; }
C
#include<stdio.h> #define SIZE 1000000 int sp=-1; int arr[SIZE]; int isempty() { if(sp==-1) { return 1; } else { return 0; } } int isfull() { if(sp==SIZE) { return 1; } else { return 0; } } void push(int x) { if(!isfull()) { sp=sp+1; arr[sp]=x; } } void pop() { if(!isempty()) { int data; data=arr[sp]; sp=sp-1; } } int maxele() { int m; int j; j=sp; int comp; m=arr[sp]; for(j=sp;j>=0;j--) { comp=arr[j]; if(comp>m) { m=comp; } } return m; } int main() { int i; int k; int n,d,b; int choice; int u=0; int y; int store[10]; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&choice); if(choice==1) { scanf("%d",&k); push(k); } else if(choice==2) { pop(); } else if(choice==3) { y=maxele(); store[u]=y; u++; } } for(b=0;b<u;b++) { printf("%d \n",store[b]); } }
C
/***** TCP CONCURRENT SERVER *****/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <inttypes.h> #include "../errlib.h" #include "../sockwrap.h" #include <fcntl.h> #include <signal.h> #include <sys/stat.h> #include <errno.h> /* CONSTANTS */ #define BUFLEN 128 /* Receiver Buffer length */ #define MAXBUFLEN 1000 /* Transmitter Buffer Length */ #define TIMEOUT 15 /* timeout is 15 seconds */ #define TRANSFER_APPROVAL 0 /* If you want to activate the approval mechanism for every single transfer, set this constant 1 */ /* FUNCTION PROTOTYPES */ void err_sys (const char *fmt, ...); int fstat(int fildes, struct stat *buf); /* GLOBAL VARIABLES */ char *prog_name; struct timeval tval; struct stat fileStat; char ackMsg[5] = "+OK\r\n"; int socketAbnormalTermination; void setPromptColor(char *colorName) { if(colorName == "default") printf("\033[0m"); else if(colorName == "red") printf("\033[1;31m"); else if(colorName == "green") printf("\033[1;32m"); if(colorName == "yellow") printf("\033[1;33m"); else if(colorName == "blue") printf("\033[1;34m"); else if(colorName == "magenta") printf("\033[1;35m"); else if(colorName == "cyan") printf("\033[1;36m"); } void sigchldHandler(int signal) { pid_t pid; int stat; while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) { setPromptColor("blue"); printf("\r\n\n**********Child %d Terminated**********\n\n", pid); setPromptColor("default"); } return; } void timeoutHandler(int signal) /* Timeout for in case of Approval mechanism. It is deactivated by default.*/ { if(signal == SIGALRM) { setPromptColor("red"); printf("Timeout has expired!\n"); exit(EXIT_FAILURE); } } void sigPipeHandler(int signal) { if(signal == SIGPIPE) { setPromptColor("red"); printf("\rTransfer Failure! Socket has been closed!\n"); setPromptColor("default"); socketAbnormalTermination = 1; } } void sendErrorMessage(int socket) { char msgError[6] = "-ERR\r\n"; size_t msgLen = strlen(msgError); if( writen(socket, msgError, msgLen) == msgLen ) { setPromptColor("green"); printf("Error message has been successfully sent!\n"); setPromptColor("default"); } else { setPromptColor("red"); printf("Error message failure!\n"); setPromptColor("default"); } } char *getRequestedFileName(char *msg) { char *tmp = NULL; tmp = memchr(msg, ' ', strlen(msg)); tmp += 1; return tmp; } int getFileStats(char *fileName) { int res = open(fileName, O_RDONLY); if(fstat(res, &fileStat) < 0) { setPromptColor("red"); perror("Error in fstat"); setPromptColor("default"); return 1; } close(res); return 0; } int transferFile(char *fileName, int socket) { FILE *fptr = NULL; size_t newLen = 0; uint32_t fSize = 0; long tmpFileSize; uint32_t fLastMod = 0; char *tbuf; int n; tbuf = malloc(MAXBUFLEN * (sizeof *tbuf)); signal(SIGPIPE, sigPipeHandler); fileName = strtok(fileName, "\r"); /* "fileName.txt\r\n" --> "fileName.txt" */ if((fptr = fopen(fileName, "rb")) == NULL) { setPromptColor("red"); fprintf(stderr," An error occured while opening %s\n", fileName); setPromptColor("default"); return 1; } if(getFileStats(fileName) == 0) { fSize = htonl((uint32_t)fileStat.st_size); fLastMod = htonl((uint32_t)fileStat.st_mtime); } else return 1; if(socketAbnormalTermination == 1) return 1; if(writen(socket, ackMsg, strlen(ackMsg)) != strlen(ackMsg)) return 1; if(writen(socket, &fSize, sizeof(uint32_t)) != sizeof(uint32_t)) return 1; tmpFileSize = fileStat.st_size; if(tmpFileSize <= MAXBUFLEN) { newLen = fread(tbuf, sizeof(char), MAXBUFLEN, fptr); if (ferror(fptr) != 0) { setPromptColor("red"); fputs("Error in reading file", stderr); setPromptColor("default"); return 1; } else { tbuf[newLen++] = '\0'; if(socketAbnormalTermination == 1) return 1; if(send(socket, tbuf, strlen(tbuf), 0) != strlen(tbuf)) return 1; } } else { while(tmpFileSize > 0) { newLen = fread(tbuf, sizeof(char), MAXBUFLEN, fptr); if (ferror(fptr) != 0) { setPromptColor("red"); fputs("Error in reading file", stderr); setPromptColor("default"); return 1; } else { tbuf[newLen++] = '\0'; n = send(socket, tbuf, MAXBUFLEN, 0); } if(n == -1) break; tmpFileSize -= n; } } if(writen(socket, &fLastMod, sizeof(uint32_t)) != sizeof(uint32_t)) return 1; strcpy(tbuf, ""); fclose(fptr); free(tbuf); return 0; } void service(int s) { char rbuf[BUFLEN]; /* Receiver buffer */ int n; size_t m; fd_set set; FD_ZERO(&set); FD_SET(s, &set); for (;;) { m = select(FD_SETSIZE, &set, NULL, NULL, &tval); if(m > 0) { if(socketAbnormalTermination == 1) break; n = recv(s, rbuf, BUFLEN-1, 0); if (n < 0) /* In case of only one of the each sides calls reset() in order to close the connection */ { setPromptColor("red"); printf("Read error! Connection is being terminated\n"); setPromptColor("default"); sendErrorMessage(s); close(s); break; } else if(n==0) /* recv returns zero if there is an agreement on handshake from both sides */ { close(s); break; } else { setPromptColor("green"); printf("\n\nReceived data from socket %03d :\n", s); printf("\rReceived message is: %s\n", rbuf); setPromptColor("default"); if(TRANSFER_APPROVAL == 1) /* If you want to activate the approval mechanism for every single transfer, set this constant 0 above. */ { printf("Do you approve the transfer of "); /* Approval mechanism for transfer request. If client does not press ENTER in 15 seconds, connection is get aborted */ printf("%s", getRequestedFileName(rbuf)); printf("to the client? ( Press ENTER )\n"); signal(SIGALRM, timeoutHandler); alarm(15); while(1) { if(getchar() == '\n' || getchar() == EOF) break; } Signal(SIGALRM, SIG_IGN); printf("File transfer request has been approved!\n"); } m = select(FD_SETSIZE, NULL, &set, NULL, &tval); if(m > 0) { if(socketAbnormalTermination == 1) break; if( transferFile(getRequestedFileName(rbuf), s) == 0 ) { setPromptColor("green"); printf("\r\n\n<==================================================>\n"); printf("\r%s has been successfully transferred!", getRequestedFileName(rbuf)); printf("\r\n<==================================================>"); setPromptColor("default"); strcpy(rbuf, ""); } else { setPromptColor("red"); printf("Transfer failure! Connection is being terminated\n"); setPromptColor("default"); if(socketAbnormalTermination == 1) break; sendErrorMessage(s); close(s); break; } } else { setPromptColor("red"); printf("Timeout has expired!\n"); setPromptColor("default"); sendErrorMessage(s); close(s); break; } } } else { setPromptColor("red"); printf("Timeout has expired!\n"); setPromptColor("default"); sendErrorMessage(s); close(s); break; } } } int main (int argc, char *argv[]) { int conn_request_skt; /* passive socket */ uint16_t lport_n, lport_h; /* port used by server (net/host ord.) */ int bklog = 2; /* Maximum length of pending requests queue */ int s; /* connected socket */ socklen_t addrlen; struct sockaddr_in saddr, caddr, sladdr, sraddr; /* server and client addresses */ int childPid; tval.tv_sec = TIMEOUT; /* Timeout for any client connection after the server has been initiated */ tval.tv_usec = 0; prog_name = argv[0]; if (argc != 2) /* To verify correctness of the arguments */ { setPromptColor("red"); printf("Invalid amount of arguments!\n Usage: ./server2_main <port number>\n"); exit(EXIT_FAILURE); } if (sscanf(argv[1], "%" SCNu16, &lport_h)!=1) /* get server port number from command line */ { setPromptColor("red"); err_sys("Invalid port number!\n"); } lport_n = htons(lport_h); /* Socket Creation */ setPromptColor("cyan"); printf("\nCreating socket...\n"); s = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* Socket in internet family, type stream and protocol TCP */ setPromptColor("green"); printf("Done, socket number %u\n", s); setPromptColor("default"); /* Binding the socket to any local IP address */ bzero(&saddr, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = lport_n; saddr.sin_addr.s_addr = INADDR_ANY; /* INADDR_ANY means all zeros */ setPromptColor("cyan"); showAddr("Binding to address", &saddr); setPromptColor("default"); Bind(s, (struct sockaddr *) &saddr, sizeof(saddr)); /* In this part, server has a generic socket that has been bounded to an address. */ setPromptColor("green"); printf("Binding has been completed.\n"); setPromptColor("default"); /* Listening the socket */ setPromptColor("cyan"); printf ("Listening at socket %d with backlog = %d \n",s,bklog); Listen(s, bklog); /* Generic socket becomes a passive socket */ setPromptColor("green"); printf("Done\n"); setPromptColor("default"); conn_request_skt = s; Signal(SIGCHLD, sigchldHandler); /* In order to avoid from zombie processes */ for (;;) /* Main server loop this part, server should never stop */ { fd_set cset; FD_ZERO(&cset); FD_SET(s, &cset); /* Accepting next connection.*/ addrlen = sizeof(struct sockaddr_in); setPromptColor("cyan"); printf("\r\n<==========================>\n"); printf("\rWaiting for a new connection...\n"); printf("\r<==========================>\n\n"); setPromptColor("default"); s = Accept(conn_request_skt, (struct sockaddr *) &caddr, &addrlen); /* Every time "Accept" is called, a new socket is created (Socket for each client) Server calls "accept" and "accept" blocks because there is no request in the queue at the moment. Server can call "accept" even if there are no connection requests. As soon as request comes, if it is possible, server accepts it. */ socketAbnormalTermination = 0; setPromptColor("green"); printf("\r<=========================================>\n"); showAddr("\rAccepted connection from", &caddr); printf("\r<=========================================>\n\n"); setPromptColor("default"); if((childPid = fork()) < 0) { setPromptColor("red"); err_msg("\rServer could not create a new process!\n"); setPromptColor("default"); sendErrorMessage(s); close(s); } else if (childPid > 0) /* Parent process */ { close(s); } else /* Child process */ { close(conn_request_skt); /* Close passive socket */ setPromptColor("blue"); printf("\rCurrent connection has been created by process: %d\n", getpid()); setPromptColor("default"); service(s); /* Serve client in child process */ } } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> // struct struct info { char name[0x20]; char channel[0x20]; char twitter[0x20]; }; // global variable struct info vTubers[5]; // function void init() { setvbuf(stdin, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0); } void banner() { puts(""); puts(" ▄ .▄ ▄▄▌ ▄▄▄▄▄ ▄▄▌ "); puts(" ██▪▐█▪ ██• ▪ •██ ▪ ▪ ██• "); puts(" ██▀▐█ ▄█▀▄ ██▪ ▄█▀▄ ▐█.▪ ▄█▀▄ ▄█▀▄ ██▪ "); puts(" ██▌▐▀▐█▌.▐▌▐█▌▐▌▐█▌.▐▌ ▐█▌·▐█▌.▐▌▐█▌.▐▌▐█▌▐▌"); puts(" ▀▀▀ · ▀█▄▀▪.▀▀▀ ▀█▄▀▪ ▀▀▀ ▀█▄▀▪ ▀█▄▀▪.▀▀▀ "); puts(""); } void init_info() { strcpy(vTubers[0].name, "Gawr Gura"); strcpy(vTubers[0].channel, "https://ppt.cc/fHT61x"); strcpy(vTubers[0].twitter, "https://ppt.cc/fHP2Ax"); strcpy(vTubers[1].name, "Watson Amelia"); strcpy(vTubers[1].channel, "https://ppt.cc/fIaIsx"); strcpy(vTubers[1].twitter, "https://ppt.cc/f675Ox"); strcpy(vTubers[2].name, "Uruha Rushia"); strcpy(vTubers[2].channel, "https://ppt.cc/fYCxrx"); strcpy(vTubers[2].twitter, "https://ppt.cc/f4dK6x"); strcpy(vTubers[3].name, "Usada Pekora"); strcpy(vTubers[3].channel, "https://ppt.cc/fHdPDx"); strcpy(vTubers[3].twitter, "https://ppt.cc/fqbVSx"); strcpy(vTubers[4].name, "Shirakami Fubuki"); strcpy(vTubers[4].channel, "https://ppt.cc/fG5UCx"); strcpy(vTubers[4].twitter, "https://ppt.cc/fmEPUx"); } int read_int() { char buf[0x10]; read(0, buf, 0x10); return atoi(buf); } void show_info() { int idx = 0; puts("Enter which info to read (index should between 0-4)"); write(1, "idx> ", 5); idx = read_int(); if (idx >= 5) { puts("Invalid index!!"); return; } printf("name: %s\n", vTubers[idx].name); printf("YT channel: %s\n", vTubers[idx].channel); printf("Twitter: %s\n", vTubers[idx].twitter); } void edit_info() { int idx = 0; int choice = 0; char buf[0x20]; puts("Enter which info to edit (index should between 0-4)"); write(1, "idx> ", 5); idx = read_int(); if (idx >= 5) { puts("Invalid index!!"); return; } puts("Enter which info to edit"); puts("1.name"); puts("2.YT cahnnel"); puts("3.Twitter"); write(1, "> ", 2); choice = read_int(); if (choice <= 0 || choice > 3) { puts("Wrong argument"); return; } write(1, "Content: ", 9); read(0, buf, 0x20); switch (choice) { case 1: memcpy(vTubers[idx].name, buf, 0x20); break; case 2: memcpy(vTubers[idx].channel, buf, 0x20); break; case 3: memcpy(vTubers[idx].twitter, buf, 0x20); break; default: puts("Invalid argument"); } puts("Edit success"); } int main() { init(); banner(); init_info(); int choice; while (1) { puts("1. show info"); puts("2. edit info"); puts("3. exit"); write(1, "> ", 2); choice = read_int(); switch (choice) { case 1: show_info(); break; case 2: edit_info(); break; case 3: puts("bye~"); exit(0); default: puts("Invalie choice!!"); } puts(""); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putnbr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fpolyans <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/03 05:57:40 by fpolyans #+# #+# */ /* Updated: 2017/07/04 23:02:16 by fpolyans ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include <stdio.h> void ft_putchar(char c) { write(1, &c, 1); } int ft_determine_int_length(int nb) { int digt_cnt; digt_cnt = 1; nb = (nb < 0) ? -nb : nb; while (nb > 10) { nb = (nb / 10); digt_cnt++; } return (digt_cnt); } void ft_putstrl(char *str, int length) { int i; i = 0; while (i < length) { ft_putchar(str[i]); i++; } } void ft_putnbr(int nb) { int temp_nb; int array_index; char billion_digit; char array[ft_determine_int_length(nb)]; temp_nb = nb; if (temp_nb == -2147483648) ft_putstrl("-2147483648", 11); else { array_index = ft_determine_int_length(temp_nb) - 1; temp_nb = (nb < 0) ? (0 - temp_nb) : temp_nb; while (temp_nb > 0) { array[array_index] = ((temp_nb % 10) + '0'); array_index--; temp_nb = temp_nb / 10; } if (nb < 0) ft_putchar('-'); ft_putstrl(array, ft_determine_int_length(nb)); } } int main(void) { ft_putnbr(2147483647); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "singlelinkedlist.h" #include "hiredis.h" int main(int argc, char **argv) { unsigned int j; unsigned int k; redisContext *c; redisReply *reply; const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1"; int port = (argc > 2) ? atoi(argv[2]) : 6379; struct timeval timeout = { 1, 500000 }; // 1.5 seconds c = redisConnectWithTimeout(hostname, port, timeout); if (c == NULL || c->err) { if (c) { printf("Connection error: %s\n", c->errstr); redisFree(c); } else { printf("Connection error: can't allocate redis context\n"); } exit(1); } /* PING server */ // reply = redisCommand(c,"PING"); // printf("PING: %s\n", reply->str); // freeReplyObject(reply); // /* Set a key */ // reply = redisCommand(c,"SET %s %s", "foo", "hello world"); // printf("SET: %s\n", reply->str); // freeReplyObject(reply); // /* Set a key using binary safe API */ // reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); // printf("SET (binary API): %s\n", reply->str); // freeReplyObject(reply); /* Try a GET and two INCR */ redisReply *all_keys; all_keys = redisCommand(c, "KEYS *"); Node *actors; Node *path; int count = 1; actors = make_node("0000138", NULL); char *name = "0000138"; while (strcmp(name, "0356017") != 0) { name = peek(&actors); printf("%s %i\n", name, actors->isVisited); if (actors->isVisited != 1) { if (strcmp(name, "0356017") == 0) { return; } printf("%s %i\n", name, actors->isVisited); char word_reply[100] = ""; strcat(word_reply, "LRANGE "); strcat(word_reply, name); strcat(word_reply, " 0 -1"); reply = redisCommand(c,word_reply); if (reply->type == REDIS_REPLY_ARRAY) { for (k = 0; k < reply->elements; k++) { push(&actors, reply->element[k]->str); } } actors->isVisited = 1; } else { printf("visited %s %i\n", name, actors->isVisited); } pop(&actors); } printf("%s", "success"); /*if (all_keys->type == REDIS_REPLY_ARRAY) { for (j = 0; j < all_keys->elements; j++) { if (j == 0) { actors = make_node(all_keys->element[j]->str, NULL); } else { push(&actors, all_keys->element[j]->str); count = count+1; } //printf("%u) %s\n", j, all_keys->element[j]->str); char word_reply[100] = ""; strcat(word_reply, "LRANGE "); strcat(word_reply, all_keys->element[j]->str); strcat(word_reply, " 0 -1"); reply = redisCommand(c,word_reply); if (reply->type == REDIS_REPLY_ARRAY) { for (k = 0; k < reply->elements; k++) { push(&actors, reply->element[k]->str); count = count+1; } } freeReplyObject(reply); } } freeReplyObject(all_keys);*/ // make a list of even numbers /*Node *test_list = make_node("2", NULL); test_list->next = make_node("4", NULL); test_list->next->next = make_node("6", NULL); print_list(test_list); char *val = pop(&test_list); print_list(test_list); push(&test_list, "3"); print_list(test_list);*/ print_list(actors); printf("%i\n", count); /* Disconnects and frees the context */ redisFree(c); return 0; }
C
#include <glib.h> int main(int argc, char** argv) { GList* list = g_list_append(NULL, "Austin "); list = g_list_append(list, "Bowie "); list = g_list_append(list, "Bowie "); list = g_list_append(list, "Cheyenne "); printf("Here's the list: "); g_list_foreach(list, (GFunc)printf, NULL); printf("\nItem 'Bowie' is located at index %d\n", g_list_index(list, "Bowie ")); printf("Item 'Dallas' is located at index %d\n", g_list_index(list, "Dallas")); GList* last = g_list_last(list); printf("Item 'Cheyenne' is located at index %d\n", g_list_position(list, last)); g_list_free(list); return 0; }
C
#include <WebUSB.h> WebUSB WebUSBSerial(1, "Deno"); #define Serial WebUSBSerial const int ledPin = 13; void setup() { Serial.begin(9600); Serial.write("Sketch begins.\r\n> "); Serial.flush(); pinMode(ledPin, OUTPUT); } void loop() { int byte = Serial.read(); Serial.write(byte); if (byte == 'H') { Serial.write("\r\nTurning LED on."); digitalWrite(ledPin, HIGH); } else if (byte == 'L') { Serial.write("\r\nTurning LED off."); digitalWrite(ledPin, LOW); } Serial.write("\r\n> "); Serial.flush(); }
C
/* Brake Light Warning System ***Subsystem Test for Speed and Deceleration*** Written by StanLee Maslonka Program Purpose: Program the ATmega32 to receive Speed from a Hall Effect Sensor and Deceleration from an Accelerometer and control a LED Bar's brightness and flashing rate accordingly. Inputs: Speed from the Hall Effect Sensor sending a digital logic one (+5V) or logic zero (0V). The signals are detected by the Input Capture One on PD6 using the on board Timer/Counter One Deceleration from the Accelerometer sending an analog voltage (0-2.414V). The signals are detected and converted by the on board Analog-to-Digital Converter. Outputs: PWM (Brightness/Intensity) from OCR0 at PB3 using Timer/Counter Zero to the input of an AND Gate PORTC (Flashing) from PCx to the input of an AND Gate. The Brightness and Flashing will be sent through the AND Gate (IC 7408), then the output of the AND Gate will go to the LED(s). */ //include files #include <avr/io.h> #include <inttypes.h> #include <stdlib.h> #include <math.h> #include <MSOE/delay.c> #include <avr/interrupt.h> #include <avr/signal.h> #include <MSOE/bit.c> //declare variables uint16_t Speed; uint16_t NOWspeed; uint16_t PASTspeed; uint8_t Flash; uint8_t Deceleration; #define PowerOff 0x00 #define Power100percent 0xFF #define Power65percent 0xA5 #define Power30percent 0x4D #define TwentyMPH 0x05A0 #define FortyMPH 0x03C0 #define SixtyMPH 0x0280 #define GforceThree 0x5F #define GforceTwo 0x68 #define GforceOne 0x70 int main(void) //beginning of main function { //Assign I/O PINs and/or PORTs PORTA=0xFF; //enable internal resistors of PORTA DDRB=0xFF; //set PORTB to write DDRC=0xFF; //set PORTC to write DDRD=0xBF; //set PORTD to write and PD6(ICP1) to input PORTC=0x00; /*The next line initializes and configures Timer/Counter Zero to Fast PWM, 8-bit; increment the counter register for a prescalar of one (every clock cycle); the Output Compare Mode is set to clear OCR0 on compare match and set OC0 at TOP.*/ TCCR0=(1<<WGM00)|(1<<WGM01)|(1<<COM01)|(1<<CS00); /*The next two lines initialize and configure Timer/Counter One to Normal PWM, 16-bit; increment the counter register for a prescalar of clk/256 cycle; Input Capture Noise Canceller is enabled and Input Capture Edge Select is enabled on rising (positive) edge; Timer/Counter Interrupt Mask Register (TIMSK) turns on Input Capture Interrupt Enabled.*/ TCCR1B=(1<<ICES1)|(1<<CS10)|(1<<CS12)|(1<<ICNC1); TIMSK=(1<<TICIE1); /*next two lines initialize and configure the ADC to convert the analog voltage at PA0 (ADC0); set reference voltage at +5V (AVCC); set the shift left enable bit to shift the converted voltage value to the left (used for 8-bit conversion accuracy); set ADC enable bit and ADC conversion bit to begin conversion; prescalar set to 128 division factor.*/ ADMUX=(1<<REFS0)|(1<<ADLAR); ADCSRA=(1<<ADEN)|(1<<ADSC)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0); sei(); //set global interrupt flag while(1) { ADMUX=ADMUX&0xFE; //set ADC to read and convert voltage at PA0 (ADC0) ADCSRA=ADCSRA|0x40; //set ADSC bit to start conversion while(ADCSRA==0xC7);//loop and do nothing until ADC conversion has been made Deceleration=ADCH; //store value of ADCH into Deceleration /*Finite State Machine for comparing Deceleration and assigning the appropriate Power intensity to the PWM for LED brightness and for comparing Speed and assigning the appropriate Flash frequency for the LED flashing:The variable values are inverted(negative coefficient)that's why the decisions are backwards.*/ if(Deceleration>GforceOne) { /*Checks to see if Deceleration is greater than the first level of G-Force from the Accelerometer, if true, then set LEDS to Off with OCR0 equal to 0% Duty Cycle, No Power.*/ OCR0=PowerOff; PORTC=0x00; } else if((Deceleration<=GforceOne)&&(Deceleration>GforceTwo)&&(Speed>TwentyMPH)) { /*Checks to see if Deceleration is less than or equal to the First level and is greater than the Second level of G-Force from the Accelerometer, and that the Speed is greater than 20mph, if true, then set LEDS to No Flashing constantly ON with OCR0 equal to 30% Duty Cycle.*/ OCR0=Power30percent; PORTC=0xFF; } else if((Deceleration<=GforceOne)&&(Deceleration>GforceTwo)&&(Speed<=TwentyMPH)&&(Speed>FortyMPH)) { /*Checks to see if Deceleration is less than or equal to the First level and is greater than the Second level of G-Force from the Accelerometer, and that the Speed is less than or equal to 20mph and is greater than 40mph, if true, then set LEDS to Flash at 4Hz with OCR0 equal to 30% Duty Cycle.*/ OCR0=Power30percent; PORTC=~PORTC; delay_ms(90); } else if((Deceleration<=GforceOne)&&(Deceleration>GforceTwo)&&(Speed<=FortyMPH)&&(Speed>SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the First level and is greater than the Second level of G-Force from the Accelerometer, and that the Speed is less than or equal to 40mph and is greater than 60mph, if true, then set LEDS to Flash at 6Hz with OCR0 equal to 30% Duty Cycle.*/ OCR0=Power30percent; PORTC=~PORTC; delay_ms(60); } else if((Deceleration<=GforceOne)&&(Deceleration>GforceTwo)&&(Speed<=SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the First level and is greater than the Second level of G-Force from the Accelerometer, and that the Speed is less than or equal to 60mph, if true, then set LEDS to Flash at 8Hz with OCR0 equal to 30% Duty Cycle.*/ OCR0=Power30percent; PORTC=~PORTC; delay_ms(45); } else if((Deceleration<=GforceTwo)&&(Deceleration>GforceThree)&&(Speed>TwentyMPH)) { /*Checks to see if Deceleration is less than or equal to the Second level and is greater than the Third level of G-Force from the Accelerometer, and that the Speed is greater than to 20mph, if true, then set LEDS to No Flashing constantly ON with OCR0 equal to 65% Duty Cycle.*/ OCR0=Power65percent; PORTC=0xFF; } else if((Deceleration<=GforceTwo)&&(Deceleration>GforceThree)&&(Speed<=TwentyMPH)&&(Speed>FortyMPH)) { /*Checks to see if Deceleration is less than or equal to the Second level and is greater than the Third level of G-Force from the Accelerometer, and that the Speed is less than or equal to 20mph and is greater than 40mph, if true, then set LEDS to Flash at 4Hz with OCR0 equal to 65% Duty Cycle.*/ OCR0=Power65percent; PORTC=~PORTC; delay_ms(90); } else if((Deceleration<=GforceTwo)&&(Deceleration>GforceThree)&&(Speed<=FortyMPH)&&(Speed>SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the Second level and is greater than the Third level of G-Force from the Accelerometer, and that the Speed is less than or equal to 40mph and is greater than 60mph, if true, then set LEDS to Flash at 6Hz with OCR0 equal to 65% Duty Cycle.*/ OCR0=Power65percent; PORTC=~PORTC; delay_ms(60); } else if((Deceleration<=GforceTwo)&&(Deceleration>GforceThree)&&(Speed<=SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the Second level and is greater than the Third level of G-Force from the Accelerometer, and that the Speed is less than or equal to 60mph, if true, then set LEDS to Flash at 8Hz with OCR0 equal to 65% Duty Cycle.*/ OCR0=Power65percent; PORTC=~PORTC; delay_ms(45); } else if((Deceleration<=GforceThree)&&(Speed>TwentyMPH)) { /*Checks to see if Deceleration is less than or equal to the Third level of G-Force from the Accelerometer and that the Speed is greater than 20mph, if true, then set LEDS to No Flashing constantly ON with OCR0 equal to 100% Full Power.*/ OCR0=Power100percent; PORTC=0xFF; } else if((Deceleration<=GforceThree)&&(Speed<=TwentyMPH)&&(Speed>FortyMPH)) { /*Checks to see if Deceleration is less than or equal to the Third level of G-Force from the Accelerometer, and that the Speed is less than or equal to 20mph and is greater than 40mph, if true, then set LEDS to Flash at 6Hz with OCR0 equal to 100% Duty Cycle, Full Power.*/ OCR0=Power100percent; PORTC=~PORTC; delay_ms(60); } else if((Deceleration<=GforceThree)&&(Speed<=FortyMPH)&&(Speed>SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the Third level of G-Force from the Accelerometer, and that the Speed is less than or equal to 40mph and is greater than 60mph, if true, then set LEDS to Flash at 8Hz with OCR0 equal to 100% Duty Cycle, Full Power.*/ OCR0=Power100percent; PORTC=~PORTC; delay_ms(45); } else if((Deceleration<=GforceThree)&&(Speed<=SixtyMPH)) { /*Checks to see if Deceleration is less than or equal to the Third level of G-Force from the Accelerometer and that the Speed is less than or equal to 60mph, if true, then set LEDS to Flash at 8Hz with OCR0 equal to 100% Duty Cycle, Full Power.*/ OCR0=Power100percent; PORTC=~PORTC; delay_ms(45); } } } /*Interrupt Service Routine for Timer/Counter One Input Capture.*/ ISR(TIMER1_CAPT_vect) { /*Stores old Speed (NOWspeed) value in a different register called PASTspeed.*/ PASTspeed=NOWspeed; /*Stores the Timer/Counter One's clock cycle number into a register called NOWspeed.*/ NOWspeed=TCNT1; /*Compares PASTspeed and NOWspeed to find which one is larger.*/ if(PASTspeed<NOWspeed) { /*Finds the difference in time from one Input Capture to the next, and stores it in the register called Speed.*/ Speed=NOWspeed-PASTspeed; } else { /*If PASTspeed is greater than NOWspeed, then Do Nothing; Speed stays the same.*/ Speed=Speed; } }
C
//command.c #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "iodev.h" //Signature global variable extern char signature[5][3]; /* Signature will hold the status of the 5 sensor values in the order: 0: photo 1: gas 2: particle 3: temp 4: humid The values will be: very low (VL), low (L), normal (N), high (H), very high (VH) */ //Command task - Turns actuation equipment (LEDs) on/off based on signature void command(void *pvParameter) { //File descriptor variables int furnacefd, acfd, humidifierfd, dehumidifierfd, aircleanerfd, ealarmfd; //First open all actuation devices as files //printf("a"); furnacefd = dopen("furnace"); //printf("b"); acfd = dopen("ac");//This one //printf("c"); humidifierfd = dopen("humidifier"); //printf("d"); dehumidifierfd = dopen("dehumidifier"); //printf("e"); aircleanerfd = dopen("air cleaner"); //printf("f"); ealarmfd = dopen("e-alarm"); //printf("g"); //Periodically poll the signature and control actuators accordingly while(1) { //Furnace if(!strcmp(signature[3], "L") || !strcmp(signature[3], "VL")) dwrite(furnacefd, 1); else dwrite(furnacefd, 0); //Air conditioner if(!strcmp(signature[3], "H") || !strcmp(signature[3], "VH")) dwrite(acfd, 1); else dwrite(acfd, 0); //Humidifier if(!strcmp(signature[4], "L") || !strcmp(signature[4], "VL")) dwrite(humidifierfd, 1); else dwrite(humidifierfd, 0); //Dehumidifier if(!strcmp(signature[4], "H") || !strcmp(signature[4], "VH")) dwrite(dehumidifierfd, 1); else dwrite(dehumidifierfd, 0); //Air Cleaner if(!strcmp(signature[1], "H") || !strcmp(signature[1], "VH") || !strcmp(signature[2], "H") || !strcmp(signature[2], "H")) dwrite(aircleanerfd, 1); else dwrite(aircleanerfd, 0); //Emergency Alarm if(!strcmp(signature[0], "VH") && !strcmp(signature[1], "VH") && !strcmp(signature[2], "VH") && !strcmp(signature[3], "VH")) dwrite(ealarmfd, 1); else dwrite(ealarmfd, 0); //Delay a small amount of time between iterations vTaskDelay(50 / portTICK_RATE_MS); } }
C
#include <stdio.h> int main(void) { int arr[15][15] = {0, }; int test, h, w; for(int i = 0; i < 15; i++) arr[0][i] = i; for(int i = 1; i < 15; i++) { for(int j = 1; j < 15; j++) arr[i][j] = arr[i - 1][j] + arr[i][j - 1]; } scanf("%d", &test); for(int i=0;i<test;i++) { scanf("%d %d", &h, &w); printf("%d\n", arr[h][w]); } }
C
#include "../../include/my.h" int my_revstr(char* s) { int temp; int rep; int i; int j; if (s == NULL) { return -1; } i =0; j = (my_strlen(s) - 1); while(i < j) { temp = s[i]; rep = s[j]; s[i] = rep; s[j] = temp; i++; j--; } return my_strlen(s); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* prs_recurse_left.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vjacquie <vjacquie@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/14 14:59:36 by jmoiroux #+# #+# */ /* Updated: 2014/03/27 15:24:30 by vjacquie ### ########.fr */ /* */ /* ************************************************************************** */ #include "sh.h" /* ** open link and dup2 it on prev link cmd */ static int recurse_leftfork(t_data *d, int father, int fd, t_more *link) { if ((father = fork()) < 0) { ft_putstr_fd("Fork() error (recurse_left)\n", 2); return (-1); } if (father == 0) { dup2(fd, 0); d->toexec = link->prev->str; exe_build_system(d); _exit(1); } return (1); } static int recurse_leftalone(t_data *d, t_more *link) { int father; int fd; char *tmp; father = -1; tmp = ft_strtrim(link->str); if ((fd = open(tmp, O_RDONLY)) == -1) { ft_putstr_fd("File open error (recurse_left)\n", 2); ft_memdel((void **)&tmp); return (-1); } if (link->prev != NULL && link->prev->str == NULL) { ft_putstr_fd("Operator: < usage: 'executable < file' only\n", 2); ft_memdel((void **)&tmp); return (-1); } ft_memdel((void **)&tmp); if (recurse_leftfork(d, father, fd, link) == -1) return (-1); return (1); } int recurse_left(t_data *d, t_more *link) { if (link->next != NULL || (link->prev != NULL && ft_strlen(link->prev->str) == 0)) { ft_putstr_fd("Operator: < usage: 'executable < file' only\n", 2); return (-1); } else { if (recurse_leftalone(d, link) == -1) return (-1); } return (1); }
C
// // main.c // Shell sort // // Created by Rex Ma on 15/12/11. // Copyright © 2015年 Rex Ma. All rights reserved. // #include <stdio.h> #include <stdlib.h> int main(int argc, const char * argv[]) { // insert code here... int a[10]; for (int k = 0; k < 10; k++) { a[k] = rand(); } int i , j ,Increment; for (Increment = 10 / 2; Increment > 0; Increment /= 2) { for (i = Increment; i < 10; i++) { int Tmp = a[i]; for (j = i; j >= Increment; j -= Increment) { if (Tmp < a[j - Increment]) a[j] = a[j-Increment]; else break; } a[j] = Tmp; } } for (int j = 0; j < 10; j++) { printf("%d\n",a[j]); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* movement.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jluknar- <jluknar-@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/17 17:59:45 by jluknar- #+# #+# */ /* Updated: 2020/07/02 10:45:05 by jluknar- ### ########.fr */ /* */ /* ************************************************************************** */ #include "cub3d.h" void turn_left(t_mlx *mlx, double rot) { if (mlx->map->spawn == 'W') rot = -ROT; mlx->rayc.old_dirx = mlx->rayc.dir_x; mlx->rayc.oldplanex = mlx->rayc.planex; mlx->rayc.dir_x = mlx->rayc.dir_x * cos(rot) - mlx->rayc.dir_y * sin(rot); mlx->rayc.dir_y = mlx->rayc.old_dirx * sin(rot) + mlx->rayc.dir_y * cos(rot); mlx->rayc.planex = mlx->rayc.planex * cos(rot) - mlx->rayc.planey * sin(rot); mlx->rayc.planey = mlx->rayc.oldplanex * sin(rot) + mlx->rayc.planey * cos(rot); } void turn_right(t_mlx *mlx, double rot) { if (mlx->map->spawn != 'W') rot = -ROT; mlx->rayc.old_dirx = mlx->rayc.dir_x; mlx->rayc.oldplanex = mlx->rayc.planex; mlx->rayc.dir_x = mlx->rayc.dir_x * cos(rot) - mlx->rayc.dir_y * sin(rot); mlx->rayc.dir_y = mlx->rayc.old_dirx * sin(rot) + mlx->rayc.dir_y * cos(rot); mlx->rayc.planex = mlx->rayc.planex * cos(rot) - mlx->rayc.planey * sin(rot); mlx->rayc.planey = mlx->rayc.oldplanex * sin(rot) + mlx->rayc.planey * cos(rot); } void movement(t_mlx *mlx) { double rot; rot = ROT; if (mlx->mflags.forward_fl || mlx->mflags.backward_fl) check_mov_fb(mlx); if (mlx->mflags.right_fl || mlx->mflags.left_fl) { if (mlx->map->spawn == 'W') check_mov_lrw(mlx); else check_mov_lr(mlx); } if (mlx->mflags.turn_l == 1) turn_left(mlx, rot); if (mlx->mflags.turn_r == 1) turn_right(mlx, rot); }
C
#include<stdio.h> #include<conio.h> void main() { int m,n,c,d,first[10][10],second[10][10],sum[10][10]; printf("Enter no of rows and columns\n"); scanf("%d%d",&m,&n); printf("Enter elements of first matrix\n"); for(c=0;c<m;c++) for(d=0;d<n;d++) scanf("%d",&first[c][d]); printf("enter elements of 2\n"); for(c=0;c<m;c++) for(d=0;d<n;d++) scanf("%d",&second[c][d]); sum[c][d]=first[c][d]+second[c][d]; printf("sum of matrices is:\n"); for(c=0;c<m;c++) { for(d=0;d<n;d++) printf("%d ",sum[c][d]); printf("\n"); } getch(); return(sum[c][d]); }
C
// bit_array.h // Solution IJC-DU1, example a), 25.03.2016 // Author: Roman Kiselevich, FIT // Compiler: gcc 4.8.4 // Module to working with bit-arrays #ifndef _BIT_ARRAY_H #define _BIT_ARRAY_H #include <limits.h> // CHAR_BIT #include "error.h" // fatal_error() typedef unsigned long* bit_array_t; // The number of bits in ulong type #define ULONG_BIT (CHAR_BIT*sizeof(unsigned long)) // The number of bits in a single element of the array #define BIT_PER_ARRELEM(name) (CHAR_BIT*sizeof(name[0])) /* * some useful macros to manipulation with bits * supports any integer type */ #define BITMASK(name, index) (1ULL << ((index) % BIT_PER_ARRELEM(name))) #define BITSLOT(name, index) (((index) / BIT_PER_ARRELEM(name))) // returns the value of the bit located in the array at bit-index #define DU1_GET_BIT(name, index) (((name)[BITSLOT(name, index)] & BITMASK(name, index)) ? 1U : 0U) // if bit !=0 set 1 on the bit-index otherwise set 0 #define DU1_SET_BIT(name, index, bit) do { \ if ((bit)!=0) ((name)[BITSLOT(name, index)] |= BITMASK(name, index));\ else ((name)[BITSLOT(name, index)] &= ~BITMASK(name, index)); \ } while(0) // end of DU1_SET_BIT // calculate the number of ulong elements for an effective storage bits #define ULONG_COUNT_BA(size) (((size)+(CHAR_BIT*sizeof(unsigned long))-1U)/(CHAR_BIT*sizeof(unsigned long))) /* * declare and initialize the array and initializes it with zeros. * for storage bit-length array used [0] element */ #define ba_create(name, size) unsigned long name[ULONG_COUNT_BA(size)+1U] = {size, 0,} #ifndef USE_INLINE // returns the declared size of the array #define ba_size(name) (name[0]) // similarly, as DU1_SET_BIT, but with checking the allowable range #define ba_set_bit(name,index,bit) do { \ if ((index) >= 0 && (index) < ba_size(name)) \ DU1_SET_BIT(name, ((index)+(BIT_PER_ARRELEM(name))), bit); \ else \ fatal_error("index %lu is out of range 0..%lu\n", \ (unsigned long)index, (unsigned long)(ba_size(name)-1));\ }while(0) // end of ba_set_bit(name,index,bit) // similarly, as DU1_GET_BIT, but with checking the allowable range #define ba_get_bit(name,index) \ (((index) < 0 || (index) >= ba_size(name)) ? \ fatal_error("index %lu is out of range 0..%lu\n", \ (unsigned long)(index), (unsigned long)(ba_size(name)-1)), 0 : \ DU1_GET_BIT(name,((index)+(BIT_PER_ARRELEM(name))))) #else // Declaration some similar inline functions. static inline unsigned long ba_size(bit_array_t barr) { return barr[0]; } static inline void ba_set_bit(bit_array_t barr, unsigned long index, unsigned bit) { if (index < ba_size(barr)) { DU1_SET_BIT(barr, index+BIT_PER_ARRELEM(barr), bit); } else { fatal_error("index %lu is out of range 0..%lu\n", (unsigned long)index, (unsigned long)(ba_size(barr)-1)); } } static inline unsigned ba_get_bit(bit_array_t barr, unsigned long index) { if (index >= ba_size(barr)) { fatal_error("index %lu is out of range 0..%lu\n", (unsigned long)index, (unsigned long)(ba_size(barr)-1)); } return DU1_GET_BIT(barr, index+BIT_PER_ARRELEM(barr)); } #endif // USE_INLINE #endif // _BIT_ARRAY_H
C
#ifndef __DRAWING_FUNCS_H_ #define __DRAWING_FUNCS_H_ #include "glut.h" #include <cmath> #define PI 3.1415926535898 static void draw_rect2d(float width, float height, GLenum drawStyle = GL_POLYGON) { glBegin(drawStyle); glVertex2f(-1.0f * width, 1.0f * height); glVertex2f(-1.0f * width, -1.0f * height); glVertex2f(1.0f * width, -1.0f * height); glVertex2f(1.0f * width, 1.0f * height); glEnd(); } /** * This draws polygons by placing verticies along a unit circle * radius. */ static void draw_circle2d(float radius, int numVerticies, GLenum drawStyle = GL_POLYGON) { int i; float angle; glBegin(drawStyle); // Plot numVerticies number of points from center for (i = 0; i < numVerticies; i++) { angle = PI * 2 * i / numVerticies; // 2PI * i/v glVertex2f(radius * sin(angle), radius * cos(angle)); } glEnd(); } static void draw_triangle2d(float *p1, float *p2, float *p3, GLenum drawStyle = GL_LINE_LOOP) { glBegin(drawStyle); glVertex2fv(p1); glVertex2fv(p2); glVertex2fv(p3); glEnd(); } static void draw_triangle2d(float size, GLenum drawStyle = GL_LINE_LOOP) { glBegin(drawStyle); glVertex2f(-size, 0.0f); glVertex2f(size, 0.0f); glVertex2f(-size, size); glEnd(); } static void draw_star(int size, GLenum drawStyle = GL_LINES) { //glPushMatrix(); glPushAttrib(11); int i; float angle; glLineWidth(2.0f); glBegin(drawStyle); for (i = 0; i < 8; i++) { angle = 3.14159 * 2 * i / 8; // 2PI * i/v glVertex2f((1.0f*size) * sin(angle), (1.0f*size) * cos(angle)); glVertex2f((-1.0f*size) * sin(angle), (-1.0f*size) * cos(angle)); } glEnd(); glPopAttrib(); //glPopMatrix(); } static void draw_fireballs(float size, float fireballSize, int numVerts, GLenum drawStyle = GL_POLYGON) { glPushMatrix(); int i; float angle; for (i = 0; i < 8; i++) { angle = 3.14159 * 2 * i / 8; // 2PI * i/v glTranslatef(size * sin(angle), size * cos(angle), 0.0f); draw_circle2d(fireballSize, numVerts, drawStyle); glTranslatef(-size * sin(angle), -size * cos(angle), 0.0f); } glPopMatrix(); } /** * This is my custom function in which I will draw something fun. */ static void draw_custom() { // First draw the picture frame glPushMatrix(); glPushAttrib(12); glLineWidth(3.0f); glColor3f(0.6f, 0.0f, 0.2f); glBegin(GL_LINE_LOOP); glVertex2f(-2.0f, -2.0f); glVertex2f(2.0f, -2.0f); glVertex2f(2.0f, 2.0f); glVertex2f(-2.0f, 2.0f); glEnd(); glBegin(GL_LINE_LOOP); glVertex2f(-1.8f, -1.8f); glVertex2f(1.8f, -1.8f); glVertex2f(1.8f, 1.8f); glVertex2f(-1.8f, 1.8f); glEnd(); // Draw insides - star (circle) // Inside: Draw Lines int i; float angle; glBegin(GL_LINES); for (i = 0; i < 8; i++) { angle = 3.14159 * 2 * i / 8; // 2PI * i/v glColor3f(angle, angle, angle); glVertex2f(1.0f * sin(angle), 1.0f * cos(angle)); glColor3f(angle/128, angle/128, angle/128); glVertex2f(-1.0f * sin(angle), -1.0f * cos(angle)); } glEnd(); // Inside: Draw Circles on each tip for (i = 0; i < 8; i++) { // Every time I will reset matrix and re-translate to center so that I can properly translate to end of line. glLoadIdentity(); glTranslatef(5.0f, 5.0f, 0.0f); angle = 3.14159 * 2 * i / 8; // 2PI * i/v glTranslatef(1.0f * sin(angle), 1.0f * cos(angle), 0.0f); glColor3f(0.1f, 0.0f, 1.0f); draw_circle2d(0.1f, 16); } glPopAttrib(); glPopMatrix(); } #endif
C
#include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char buffer[100]; char receive[100]; printf("Enter the Word: "); scanf("%s",buffer); int fd,fdd; char * fifoSimple = "/tmp/fifoSimple"; char * fifoCapital = "/tmp/fifoCapital"; mkfifo(fifoSimple,0666); mkfifo(fifoCapital,0666); fd = open(fifoSimple, O_WRONLY); write(fd, buffer,strlen(buffer)); close(fd); fdd = open(fifoCapital, O_RDONLY); read(fdd, receive, 1024); printf("Capitalized Word: %s\n", receive); close(fdd); unlink(fifoSimple); unlink(fifoCapital); return 0; }
C
#ifndef DLIST_H #define DLIST_H #include "error.h" typedef struct Node { int val; struct Node *prev, *next; } Node; typedef struct DList { int length; struct Node *sentinel; } DList; Handle init_dlist(DList **dlist); Handle insert_dlist(DList *dlist, int data, int index); Handle reverse_dlist(DList *dlist, int start_index, int end_index); Handle print_dlist(DList *dlist); Handle free_dlist(DList *dlist); #endif /* DLIST_H */
C
/* ** my_getnbr.c for Jour05 in /home/vitiel_s/PiscineC/Jour05/my_getnbr ** ** Made by VITIELLO Sullivan ** Login <vitiel_s@etna-alternance.net> ** ** Started on Fri Oct 2 14:41:43 2015 VITIELLO Sullivan ** Last update Fri Oct 2 15:23:38 2015 VITIELLO Sullivan */ int my_getnbr(char *str) { int i; int s; int r; r = 0; i = 0; s = 0; while (str[i] == '+' || str[i] == '-') { if (str[i] == '-') s++; i++; } if (str[i] < 48 || str[i] > 57) return (0); while (str[i] > 47 && str[i] < 58) { r = r * 10 + (str[i] - 48); i++; } if (s % 2 == 1) return (-r); return (r); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* response_other.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: obamzuro <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/13 23:50:26 by obamzuro #+# #+# */ /* Updated: 2018/10/14 23:28:35 by obamzuro ### ########.fr */ /* */ /* ************************************************************************** */ #include "server.h" /* ** Response ResetStats RC */ enum e_errors response_resetstats(int clientfd, t_msgheader *receivedHeader, t_metadata *metadata) { t_msgheader responseHeader; ssize_t sendReturned; bzero(&responseHeader, sizeof(responseHeader)); responseHeader.magic = htonl(MAGIC); bzero(metadata, sizeof(*metadata)); sendReturned = send(clientfd, &responseHeader, sizeof(responseHeader), 0); change_metadata(metadata, 0, sendReturned, 0, 0); return (OK); } /* ** Response Ping RC */ enum e_errors response_ping(int clientfd, t_msgheader *receivedHeader, t_metadata *metadata) { t_msgheader responseHeader; ssize_t sendReturned; bzero(&responseHeader, sizeof(responseHeader)); responseHeader.magic = htonl(MAGIC); sendReturned = send(clientfd, &responseHeader, sizeof(responseHeader), 0); change_metadata(metadata, 0, sendReturned, 0, 0); return (OK); } /* ** Response GetStats RC ** P.S (ratio can't be in stats struct because of ** structure alignment) */ enum e_errors response_getstats(int clientfd, t_msgheader *receivedHeader, t_metadata *metadata) { t_msgheader responseHeader; t_stats stats; unsigned char ratio; char *dataSent; ssize_t sendReturned; bzero(&responseHeader, sizeof(responseHeader)); responseHeader.magic = htonl(MAGIC); if (!metadata->compressReceived) ratio = 0; else ratio = (unsigned char)((double)metadata->compressSent / metadata->compressReceived * MAX_RATIO); stats.received = htonl(metadata->totalReceived); stats.sent = htonl(metadata->totalSent); dataSent = (char *)malloc(sizeof(t_msgheader) + sizeof(t_stats) + sizeof(ratio)); memcpy(dataSent, &responseHeader, sizeof(responseHeader)); memcpy(dataSent + sizeof(responseHeader), &stats, sizeof(stats)); memcpy(dataSent + sizeof(responseHeader) + sizeof(stats), &ratio, sizeof(ratio)); sendReturned = send(clientfd, dataSent, sizeof(responseHeader) + sizeof(stats) + sizeof(ratio), 0); change_metadata(metadata, 0, sendReturned, 0, 0); free(dataSent); return (OK); }
C
#include <stdio.h> int main() { char alphabet[51]; scanf ("%s",alphabet); int i; int answer=0; alphabet[50]=alphabet[0]; for(i=0;i<51;i++) { if(alphabet[i]==alphabet[i+1]) { answer=answer+((int)alphabet[i]-48); printf("%d\n",answer); } } return 0; }
C
/* LDR - Sensor Demo -- using ADC */ // ------- Preamble -------- // #define F_CPU 1000000L /* atTiny85 Bautrate */ #include <avr/io.h> /* Defines pins, ports, etc */ #include <util/delay.h> /* Functions to waste time */ #include "pinDefines.h" /*----- Function ADMUX Value AREF Pin Vcc (Power Supply) (1<<REFS0) Leave unconnected Internal 2.56V (1<<REFS0)|(1<<REFS1) Leave unconnected External Reference 0 Connect Voltage Reference -----*/ // ADMUX - This register is used to select reference voltage source, how the result should be stored (either left adjusted or right adjusted), analog port channel to be used for conversion. //ADCSRA - This register is responsible for enabling ADC, start ADC converting, prescaler selection and interrupt control. #define THRESHOLD 800//Threashold (out of 1023) volatile int analogResult = 0; int main(void){ //pin 4 read, pin 3 write DDRB &= ~(1<<DDB4); DDRB |= ((1<<DDB3)|(1<<DDB2)); //set voltage to internal and right adjust (ADLAR) ADMUX &= ~((1<<REFS1)|(1<<REFS0)|(1<<ADLAR)); //set input as ADC2 (PIN 4) ADMUX |= (1<<MUX1); //enable ADC (ADEN) and enables ADC interrupt (ADIE) //Set ADATE to ensure interrupt can trigger at any time ADCSRA |= ((1 << ADPS1) | (1 << ADPS0)); ADCSRA |= (1<<ADEN); while(1){ //convert analog to digital ADCSRA |= ( 1 << ADSC ); while( ADCSRA & ( 1 << ADIF ) );//wait for the value to be computed analogResult = ((ADCH<<8)|ADCL); //enable Pin 3 output if value is over threashold if(analogResult>THRESHOLD){ PORTB |= (1<<PB3); }else{ PORTB &= ~(1<<PB3); } ADCSRA |= ( 1 << ADIF ); } return 0; }
C
/* ** main.c for in /home/nicolas/horbac_n/my_aff_tab_num ** ** Made by HORBACZ Nicolas ** Login <horbac_n@etna-alternance.net> ** ** Started on Tue Mar 21 09:59:35 2017 HORBACZ Nicolas ** Last update Tue Mar 21 10:00:57 2017 HORBACZ Nicolas */ void my_aff_tab_num(int tab[], int size); int main() { int tab[3] = {2, 4, 0}; my_aff_tab_num(tab, 3); return (0); }
C
/* Main source file. Contains program entry point function. Author: Matthew Boyette Date: 6/24/2013 */ #include "main.h" int main (int argc, char *argv[]) { // If there is a command-line argument... if (argc > 1) { // Read the file, build the adjacency list, and get a pointer to it. ADJLIST* adjList = parseFile(argv[1]); if (adjList != NULL) { // Run the main routines on the adjacency list. dfs(adjList); bfs(adjList); topo(adjList); // Free up the memory allocated to the adjacency list. for (size_t i = 0; i < adjList->size; i++) { free(adjList->rows[i].vertex); free(adjList->rows[i].firstAdj); } free(adjList->rows); free(adjList); } } else { // Report error if no command-line parameters were given. fprintf(stderr, "\nError: provide the path to a plain-text file via command-line parameter!\nExample usage: %s <file>\n", argv[0]); exit(1); } fprintf(stdout, "\nExiting...\n"); return 0; }
C
#include <stdio.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "tftp.h" #include "file_utils.h" #define HELP "!help" #define MODE "!mode" #define GET "!get" #define QUIT "!quit" #define MAX_CMD_LINE_LEN 64 #define PROMPT "> " #define GENERIC_ERROR_MSG "Comando non trovato. Usare !help per l'elenco dei comandi.\n" void print_menu() { printf("\n\n\nSono disponibili i seguenti comandi:\n"); printf("!help --> mostra l'elenco dei comandi disponibili\n"); printf("!mode {txt|bin} --> imposta il modo di trasferimento dei files (testo o binario)\n"); printf("!get filename nome_locale --> richiede al server il file di nome " "<filename> e lo salva localmente con il nome <nome_locale>\n"); printf("!quit --> termina il client\n"); } int main(int argc, char** argv) { char* server_ip; int server_port; int sock; struct sockaddr_in server_addr; char command[MAX_CMD_LINE_LEN]; char* tok; char* filemode; char* filename; char* data; char req_packet[MAX_REQ_LEN]; char buffer[MAX_ERROR_LEN]; int filename_len; int received; int error_number; int mode; int block; int received_block; int exit_status; // Controllo parametri client if(argc < 2) { printf("Errore parametri.\nChiamare con ./tftp_client <IP server> <porta server>\n"); return 0; } else if(argc == 2) { server_ip = argv[1]; server_port = 69; // Porta di default } else { server_port = atoi(argv[2]); server_ip = argv[1]; } printf("Indirizzo Server: %s\n", server_ip); printf("Porta Server: %d\n", server_port); // filemode a BIN di default filemode = malloc(10); strcpy(filemode, BIN_MODE); mode = BIN; // Inizializza indirizzo server memset(&server_addr, 0, sizeof server_addr); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(server_port); inet_pton(AF_INET, server_ip, &server_addr.sin_addr); // Creazione socket UDP sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock == -1) { printf("Errore nessun socket disponibile\n"); return 0; } // Associo alla porta UDP l'indirizzo del server per comodita' exit_status = connect(sock, (struct sockaddr*)&server_addr, sizeof server_addr); if (exit_status == -1) { printf("Errore di connessione\n"); close(sock); return 0; } print_menu(); while(1) { printf(PROMPT); fgets(command, MAX_CMD_LINE_LEN, stdin); // Rimuovo il carattere \n finale command[strlen(command)-1] = '\0'; if (strlen(command) == 0) { // Se il comando è stringa vuota printf(GENERIC_ERROR_MSG); continue; } // Prelevo il primo token che rappresenta il comando (e.g. !help) tok = strtok(command, " "); if (strcmp(tok, HELP) == 0) { print_menu(); } else if (strcmp(tok, MODE) == 0) { tok = strtok(NULL, " "); // Prelevo il primo argomento di mode if (tok == NULL) { printf("Formato dell'istruzione mode errato\n"); printf("Utilizzo !mode {txt|bin}\n"); continue; } if (strcmp(tok, "txt") == 0) { printf("Modo di trasferimento testuale configurato\n"); strcpy(filemode, TEXT_MODE); mode = TEXT; } else if (strcmp(tok, "bin") == 0) { printf("Modo di trasferimento binario configurato\n"); strcpy(filemode, BIN_MODE); mode = BIN; } else { printf("Formato dell'istruzione mode errato\n"); printf("Utilizzo !mode {txt|bin}\n"); } } else if (strcmp(tok, QUIT) == 0) { if (filemode != NULL) free(filemode); break; } else if (strcmp(tok, GET) == 0) { set_opcode(req_packet, RRQ); // Inizializzo un pacchetto di richiesta tok = strtok(NULL, " "); // Prelevo il filename if (tok == NULL) { printf("Formato dell'istruzione get errato\n"); printf("Utilizzo !get filename nome_locale\n"); continue; } filename_len = strlen(tok); // tok contiene il filename set_filename(req_packet, tok); set_filemode(req_packet, filemode); tok = strtok(NULL, " "); // tok contiene il nome locale if (tok == NULL) { printf("Formato dell'istruzione get errato\n"); printf("Utilizzo !get filename nome_locale\n"); continue; } if ((send(sock, req_packet, REQ_HEADER_LEN+filename_len+1+strlen(filemode)+1,0) ) < REQ_HEADER_LEN+filename_len+1+strlen(filemode)+1) { printf("Non è stato possibile inviare la richiesta\n"); continue; } filename = get_filename(req_packet); // Prelevo il filename per stamparlo printf("Richiesta file %s al server in corso.\n", filename); free(filename); block = received_block = -1; // Ricevo un pacchetto di risposta alla richiesta while(1) { // La lunghezza del pacchetto che arriva sara' max(MAX_ERROR_LEN, MAX_DATA_LEN) received = recv(sock, buffer, MAX_DATA_LEN, 0); if (get_opcode(buffer) == ERROR) { // Se ricevo un pacchetto di errore error_number = get_errornumber(buffer); if (error_number == FILE_NOT_FOUND) { printf("File non trovato.\n"); } else if (error_number == ILLEGAL_TFTP_OP) { printf("Operazione tftp non valida.\n"); } break; } else if (get_opcode(buffer) == DATA) { // Se ricevo un pacchetto dati received_block = get_blocknumber(buffer); // Controllo di aver ricevuto il blocco che mi aspettavo if (received_block == block + 1) block = received_block; else continue; // Se arriva un blocco che non mi aspetto lo ignoro // Se si tratta del primo blocco stampo if (block == 0) printf("Trasferimento file in corso.\n"); printf("\rTrasferimento blocco %d", block); fflush(stdout); // Forza la stampa precedente che verrebbe bufferizzata data = get_data(buffer, received); // tok punta ancora al nome locale del file append_file_chunk(data, tok, received-DATA_HEADER_LEN, mode); free(data); // Preparo il pacchetto di ack set_opcode(buffer, ACK); set_blocknumber(buffer, block); send(sock, buffer, ACK_LEN, 0); // Invio l'ack // Se il campo data e' piu' piccolo di un blocco allora era l'ultimo if (received-DATA_HEADER_LEN < CHUNK_SIZE) { printf("\nTrasferimento completato (%d/%d blocchi)\n", block+1, block+1); printf("Salvataggio %s completato\n", tok); break; } } else { // Se ricevo un pacchetto con opcode non gestito o errato printf("Opcode %d errato\n", get_opcode(buffer)); break; } } } else { printf(GENERIC_ERROR_MSG); } } close(sock); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<limits.h>//INT_MAX int biggest num #include"show.h" //notice when finish the code find // seg default becasue of : in merge_sort the mid = (low+high)/2 // wrong sort becasue of : when merge the two arr the index i or j cross the line final use the biggest num to be the line of the son arr /** * @brief merge * 将两个已经排好序的数组合并到原数组中 *the min is the low = 0 mid = 0 high = 1 利用limits库函数中int的最大值INT_MAX * @param arr[]] * @param low * @param mid * @param high */ void merge(int arr[],int low, int mid, int high){ //count the num of the arr you want to init; int size_l = mid - low + 1; int size_r = high - mid ; int arr_l[size_l+1]; int arr_r[size_r+1]; int i; int j; int k; //put the left num in arr to the arr_l for(i=0;i<size_l;i++){ arr_l[i] = arr[low+i]; } //put the right num in arr to the arr_r for(j=0;j<size_r;j++){ arr_r[j] = arr[mid+j+1]; } //put the biggest int num to the end of son arr arr_l[size_l] = INT_MAX; arr_r[size_r] = INT_MAX; i = 0; j = 0; //select num from each arr into the arr index from low to high for(k = low;k<=high;k++){ if(arr_l[i] <= arr_r[j] ){ arr[k] = arr_l[i]; i++; }else{ arr[k] = arr_r[j]; j++; } } return ; } /** * @brief merge_sort * sprit two equal arr to sort * like the 5,2,4,6,1,3,7 * {5,2}{4,6}{1,3}{7} * {2,4,5,6}{1,3,7} * {1,2,3,4,5,6,7} * * @param arr[] * @param len */ void merge_sort(int arr[],int low, int high){ if(arr == NULL){ return ; } int mid; //若low >= high则该字数组最多有一个元素 if(low < high){ mid = (low+high)/2; merge_sort(arr, low ,mid); merge_sort(arr,mid+1,high); merge(arr,low,mid,high); } return ; } //------------------------------------------------------------------- /** * @brief merge_flag * 利用flag表示去判断左右数组是否越位 而非最大值 * * @param arr[]] * @param low * @param mid * @param high */ void merge_flag(int arr[],int low, int mid, int high){ //count the num of the arr you want to init; int size_l = mid - low + 1; int size_r = high - mid ; int arr_l[size_l]; int arr_r[size_r]; int i; int j; int k; int outband_l = 0; int outband_r = 0; //put the left num in arr to the arr_l for(i=0;i<size_l;i++){ arr_l[i] = arr[low+i]; } //put the right num in arr to the arr_r for(j=0;j<size_r;j++){ arr_r[j] = arr[mid+j+1]; } i = 0; j = 0; //select num from each arr into the arr index from low to high for(k = low;k<=high;k++){ //whether outband if(outband_l == 1 && outband_r == 0){ arr[k] = arr_r[j]; j++; if(j >= size_r){ outband_r = 1; } continue; } if(outband_r == 1 && outband_l == 0){ arr[k] = arr_l[i]; i++; if(i >= size_l){ outband_l = 1; } continue; } if(arr_l[i] <= arr_r[j] ){ arr[k] = arr_l[i]; i++; if(i >= size_l){ outband_l = 1; } }else{ arr[k] = arr_r[j]; j++; if(j >= size_r){ outband_r = 1; } } } return ; } void merge_sort_flag(int arr[],int low, int high){ if(arr == NULL){ return ; } int mid; //若low >= high则该字数组最多有一个元素 if(low < high){ mid = (low+high)/2; merge_sort_flag(arr, low ,mid); merge_sort_flag(arr,mid+1,high); merge_flag(arr,low,mid,high); } return ; } int main() { int arr[6] = {5,2,4,6,1,3}; int arr1[6] = {5,2,4,6,1,3}; merge_sort(arr,0,5); merge_sort_flag(arr1,0,5); show(arr,6); show(arr1,6); return 0; }
C
/* main.c is the front end/test for list.c */ #include <stdio.h> /* printf */ #include <stdlib.h> /* atoi */ #include "list.h" void test_add_front(void) { int i; struct Node *list = NULL; for (i = 1; i <= 10; i++) { printf("add %2i to front: ", i); add_front(&list, i); print_list(list); } free_list(list); } void test_add_back(void) { int i; struct Node *list = NULL; for (i = 1; i <= 10; i++) { printf("add %2i to back: ", i); add_back(&list, i); print_list(list); } free_list(list); } void test_add_front_back(void) { int i; struct Node *list = NULL; for (i = 1; i <= 5; i++) { printf("add %2i to front and back: ", i); add_front(&list, i); add_back(&list, i); print_list(list); } free_list(list); } void test_remove(void) { int i; struct Node *list = NULL; int items[] = {5, 6, 10, 9, 2, 1, 3, 7, 8, 4}; /* Populate the list */ for (i = 1; i <= 10; i++) add_front(&list, i); printf("Start list : "); print_list(list); /* These values don't exist, but you need to handle that */ remove_item(&list, 100); remove_item(&list, 99); /* Remove "random" order */ for (i = 0; i < 10; i++) { printf("Removing %2i: ", items[i]); remove_item(&list, items[i]); print_list(list); } /* List should empty, but this is legal */ printf("Removing 0: "); remove_item(&list, 1); print_list(list); #if 1 free_list(list); /* should be empty at this point */ free_list(NULL); /* This is legal and you need to handle it */ #endif } void test_size(void) { int i; struct Node *list = NULL; printf("Size is %2i: ", size_list(list)); print_list(list); for (i = 1; i <= 10; i++) { add_front(&list, i); printf("Size is %2i: ", size_list(list)); print_list(list); } free_list(list); } void test_sum(void) { int i, sum = 0; struct Node *list = NULL; for (i = 1; i <= 10; i++) add_front(&list, i); sum = sum_list(list); print_list(list); printf("Sum is %i\n", sum); free_list(list); } int main(int argc, char **argv) { int test = 0; if (argc > 1) test = atoi(argv[1]); switch (test) { case 1: printf("\ntest_add_front ========================================\n"); test_add_front(); break; case 2: printf("\ntest_size ========================================\n"); test_size(); break; case 3: printf("\ntest_sum ========================================\n"); test_sum(); break; case 4: printf("\ntest_add_back ========================================\n"); test_add_back(); break; case 5: printf("\ntest_add_front_back ========================================\n"); test_add_front_back(); break; case 6: printf("\ntest_remove ========================================\n"); test_remove(); break; default: printf("\ntest_add_front ========================================\n"); test_add_front(); printf("\ntest_size ========================================\n"); test_size(); printf("\ntest_sum ========================================\n"); test_sum(); printf("\ntest_add_back ========================================\n"); test_add_back(); printf("\ntest_add_front_back ========================================\n"); test_add_front_back(); printf("\ntest_remove ========================================\n"); test_remove(); break; } return 0; }
C
#include <stdio.h> #include <time.h> #include "db_ctl.h" #include "main.h" /* ** enemies.c : ̺Ʈ ó 1) struct _EnemyInfo *enemy[MAX_ENEMIES]; 2) struct _EnemyInfo *temp[MAX_ENEMIES]; ϴ ü . enemy : ü temp : ӽ ( ҷ ӽ÷ ) === 3) CurrentEnemies *_enemy[3]; (ִ 3) ϴ ü . === 4) static int enemy_stbar_hp_pos_X; 5) static int enemy_stbar_hp_pos_Y; 6) static int _EnemyInfoRows; 4, 5: show_enemy_status() Լ Ǵ 6: enemies ̺ ҷ (= ִ ) === 7) void show_enemy_status_init(int hp_pos_X, int hp_pos_Y) 8) void show_enemy_status(int enemy_id, int is_grayscale_mode) ͸ Ѵ. show_status() Լ ǥÿ . TP , enemy_id ߰ Ϳ boss_flag Ǿ ǥ === 9) int getEnemyInfo(void) κ ͸ Լ. ͸ ٷ ȣǾ . === 10) int SmartFetchEnemies(int enemy_id) 11) int setCurrentEnemies(int enemy1_id, int enemy2_id, int enemy3_id) ͸ /. SmartFetchEnemies() κ ÷̾ ͸ ҷ. ϳ 1~3 . === 12) int freeEnemyInfo(void) 13) int freeCurrentEnemies(void) ޸ Լ. */ struct _EnemyInfo *enemy[MAX_ENEMIES]; struct _EnemyInfo *temp[MAX_ENEMIES]; CurrentEnemies *_enemy[3]; static int enemy_stbar_hp_pos_X; static int enemy_stbar_hp_pos_Y; static int _EnemyInfoRows; void show_enemy_status_init(int hp_pos_X, int hp_pos_Y) { enemy_stbar_hp_pos_X = hp_pos_X; enemy_stbar_hp_pos_Y = hp_pos_Y; } void show_enemy_status(int enemy_id, int is_grayscale_mode) { int j = 0; int hp_ratio = 0; char hp_string[MAX_ARRAY_SIZE]; //HP ⺻ int hp_bg_color = CC_GREEN; if (is_grayscale_mode) { hp_bg_color = CC_DARKGRAY; } if (_enemy[enemy_id]->enemy_id == -1) return; if (_enemy[enemy_id]->boss_flag) { //BOSS HP (HP ȭ ) //ִ HP 100% if (_enemy[enemy_id]->hp == _enemy[enemy_id]->max_hp) { hp_ratio = 50; } else if (_enemy[enemy_id]->hp == 0) { //hp 0̸ 0% hp_ratio = -1; } else { //hp_ratio 1 ̸鼭, ִ HP 10% * hp_ratio HP ū for for (hp_ratio = 49; hp_ratio > 0; hp_ratio--) { if (_enemy[enemy_id]->hp >= _enemy[enemy_id]->max_hp * (double)hp_ratio * 0.02) { break; } } } } else { //HP (HP, TP ȭ ) //ִ HP 100% if (_enemy[enemy_id]->hp == _enemy[enemy_id]->max_hp) { hp_ratio = 10; } else if (_enemy[enemy_id]->hp == 0) { //hp 0̸ 0% hp_ratio = -1; } else { //hp_ratio 1 ̸鼭, ִ HP 10% * hp_ratio HP ū for for (hp_ratio = 9; hp_ratio > 0; hp_ratio--) { if (_enemy[enemy_id]->hp >= _enemy[enemy_id]->max_hp * (double)hp_ratio * 0.1) { break; } } } } gotoxy(enemy_stbar_hp_pos_X, enemy_stbar_hp_pos_Y - 1); printf("Lv. %d %s", _enemy[enemy_id]->level, _enemy[enemy_id]->name); if (_enemy[enemy_id]->boss_flag) { //boss_flag Ǿ gotoxy(enemy_stbar_hp_pos_X + 20, enemy_stbar_hp_pos_Y - 1); sprintf(hp_string, "%d/%d", _enemy[enemy_id]->hp, _enemy[enemy_id]->max_hp); printf("%34s", hp_string); } else { gotoxy(enemy_stbar_hp_pos_X, enemy_stbar_hp_pos_Y + 1); sprintf(hp_string, "%d/%d", _enemy[enemy_id]->hp, _enemy[enemy_id]->max_hp); printf("%14s", hp_string); } //hp gotoxy(enemy_stbar_hp_pos_X, enemy_stbar_hp_pos_Y); printf("HP "); //BG hp_ratio ŭ printf  setBgColor(hp_bg_color); for (j = 0; j <= hp_ratio; j++) { printf(" "); } resetBgColor(); if (_enemy[enemy_id]->boss_flag) { for (j = 0; j <= 50 - hp_ratio; j++) { printf(" "); } } else { for (j = 0; j <= 10 - hp_ratio; j++) { printf(" "); } } //_getch(); } int getEnemyInfo(void) { //κ int i = 0; DB_CONNECT(); SQL_QUERY("select * from enemies"); while ((db.sql_row = mysql_fetch_row(db.sql_result)) != NULL) { enemy[i] = (struct _EnemyInfo *)malloc(sizeof(struct _EnemyInfo)); enemy[i]->enemy_id = atoi(db.sql_row[0]); sprintf(enemy[i]->name, "%s", db.sql_row[1]); enemy[i]->level = atoi(db.sql_row[2]); enemy[i]->max_hp = atoi(db.sql_row[3]); enemy[i]->p_attack = atoi(db.sql_row[4]); enemy[i]->p_defense = atoi(db.sql_row[5]); enemy[i]->m_attack = atoi(db.sql_row[6]); enemy[i]->m_defense = atoi(db.sql_row[7]); enemy[i]->boss_flag = atoi(db.sql_row[8]); enemy[i]->hp = enemy[i]->max_hp; i++; } _EnemyInfoRows = i; /*for (i = 0; i < _EnemyInfoRows; i++) { printf("====================\n"); printf("Enemy ID: %d\n", enemy[i]->enemy_id); printf("̸: %s\n", enemy[i]->name); printf(": %d\n", enemy[i]->level); printf("ִ HP: %d\n", enemy[i]->max_hp); printf(" ݷ: %d\n", enemy[i]->p_attack); printf(" : %d\n", enemy[i]->p_defense); printf(" ݷ: %d\n", enemy[i]->m_attack); printf(" : %d\n", enemy[i]->m_defense); printf("BOSS: %d\n", enemy[i]->boss_flag); }*/ db_disconnect(); //_getch(); return 0; } int SmartFetchEnemies(int enemy_id) { //÷̾ int i = 0, num_row = 0; char buf[512]; DB_CONNECT(); sprintf(buf, "select * from enemies where enemy_id = '%d' AND level <= '%d' AND level >= '%d'", enemy_id, user.level, (user.level) - 2); SQL_QUERY(buf); while ((db.sql_row = mysql_fetch_row(db.sql_result)) != NULL) { temp[i] = (struct _EnemyInfo *)malloc(sizeof(struct _EnemyInfo)); temp[i]->enemy_id = atoi(db.sql_row[0]); //temp[i]->name = db.sql_row[1]; sprintf(temp[i]->name, "%s", db.sql_row[1]); temp[i]->level = atoi(db.sql_row[2]); temp[i]->max_hp = atoi(db.sql_row[3]); temp[i]->p_attack = atoi(db.sql_row[4]); temp[i]->p_defense = atoi(db.sql_row[5]); temp[i]->m_attack = atoi(db.sql_row[6]); temp[i]->m_defense = atoi(db.sql_row[7]); temp[i]->boss_flag = atoi(db.sql_row[8]); temp[i]->hp = enemy[i]->max_hp; i++; } num_row = i; db_disconnect(); return num_row; } int setCurrentEnemies(int enemy1_id, int enemy2_id, int enemy3_id) { // int i = 0, randNum = 0, num_row = 0; for (i = 0; i < 3; i++) { _enemy[i] = (CurrentEnemies *)malloc(sizeof(CurrentEnemies)); } if (enemy1_id != -1) { //enemyX_id -1 ƴ num_row = SmartFetchEnemies(enemy1_id); //num_row : srand((unsigned)time(NULL) + rand()); if (num_row == 1) randNum = 0; else randNum = rand() % num_row; _enemy[0]->enemy_id = temp[randNum]->enemy_id; //_enemy[0]->name = temp[randNum]->name; sprintf(_enemy[0]->name, "%s", temp[randNum]->name); _enemy[0]->level = temp[randNum]->level; _enemy[0]->hp = temp[randNum]->max_hp; _enemy[0]->max_hp = temp[randNum]->max_hp; _enemy[0]->p_attack = temp[randNum]->p_attack; _enemy[0]->p_defense = temp[randNum]->p_defense; _enemy[0]->m_attack = temp[randNum]->m_attack; _enemy[0]->m_defense = temp[randNum]->m_defense; _enemy[0]->boss_flag = temp[randNum]->boss_flag; _enemy[0]->active = 0; //-1 : disabled, 0: alive, 1: user selected //free for (i = 0; i < num_row; i++) { free(temp[i]); } } else { _enemy[0]->enemy_id = -1; _enemy[0]->active = -1; //Ȱȭ } if (enemy2_id != -1) { num_row = SmartFetchEnemies(enemy2_id); srand((unsigned)time(NULL) + rand()); if (num_row == 1) randNum = 0; else randNum = rand() % num_row; _enemy[1]->enemy_id = temp[randNum]->enemy_id; //_enemy[1]->name = temp[randNum]->name; sprintf(_enemy[1]->name, "%s", temp[randNum]->name); _enemy[1]->level = temp[randNum]->level; _enemy[1]->hp = temp[randNum]->max_hp; _enemy[1]->max_hp = temp[randNum]->max_hp; _enemy[1]->p_attack = temp[randNum]->p_attack; _enemy[1]->p_defense = temp[randNum]->p_defense; _enemy[1]->m_attack = temp[randNum]->m_attack; _enemy[1]->m_defense = temp[randNum]->m_defense; _enemy[1]->boss_flag = temp[randNum]->boss_flag; _enemy[1]->active = 0; //free for (i = 0; i < num_row; i++) { free(temp[i]); } } else { _enemy[1]->enemy_id = -1; _enemy[1]->active = -1; } if (enemy3_id != -1) { num_row = SmartFetchEnemies(enemy3_id); srand((unsigned)time(NULL) + rand()); if (num_row == 1) randNum = 0; else randNum = rand() % num_row; _enemy[2]->enemy_id = temp[randNum]->enemy_id; //_enemy[2]->name = temp[randNum]->name; sprintf(_enemy[2]->name, "%s", temp[randNum]->name); _enemy[2]->level = temp[randNum]->level; _enemy[2]->hp = temp[randNum]->max_hp; _enemy[2]->max_hp = temp[randNum]->max_hp; _enemy[2]->p_attack = temp[randNum]->p_attack; _enemy[2]->p_defense = temp[randNum]->p_defense; _enemy[2]->m_attack = temp[randNum]->m_attack; _enemy[2]->m_defense = temp[randNum]->m_defense; _enemy[2]->boss_flag = temp[randNum]->boss_flag; _enemy[2]->active = 0; //free for (i = 0; i < num_row; i++) { free(temp[i]); } } else { _enemy[2]->enemy_id = -1; _enemy[2]->active = -1; } return 0; } int freeEnemyInfo(void) { int i = 0; for (i = 0; i < _EnemyInfoRows; i++) { free(enemy[i]); } return 0; } int freeCurrentEnemies(void) { int i = 0; for (i = 0; i < 3; i++) { free(_enemy[i]); } return 0; }
C
#include "sudoku_game_operation.h" /** * Creates an empty atomic game operation * @return Pointer to the game operation object */ sudoku_game_operation_t *create_atomic_game_operation() { sudoku_game_operation_t *operation = malloc(sizeof(sudoku_game_operation_t)); /* Check if malloc was successful */ if (operation == NULL) { EXIT_ON_ERROR("malloc"); } operation->operation_type = ATOMIC; return operation; } /** * Creates a HEAD game operation, used to mark the beginning of an operation list * @return */ sudoku_game_operation_t *create_head_game_operation() { sudoku_game_operation_t *operation = malloc(sizeof(sudoku_game_operation_t)); /* Check if malloc was successful */ if (operation == NULL) { EXIT_ON_ERROR("malloc"); } operation->operation_type = HEAD; return operation; } /** * Create a composite game operation, representing a command given by the user * @param operation_type * @param arg1 Optional value, integer argument #1 * @param arg2 Optional value, integer argument #2 * @param arg3 Optional value, integer argument #3 * @param farg Optional value, floating point argument * @return */ sudoku_game_operation_t *create_composite_game_operation(enum sudoku_game_operation_type operation_type, int arg1, int arg2, int arg3, float farg) { sudoku_game_operation_t *operation = malloc(sizeof(sudoku_game_operation_t)); operation_node_t *operation_list = create_operation_node(); sudoku_game_operation_t *head = create_head_game_operation(); operation_list_append(operation_list, head); operation->operation_type = operation_type; operation->value.composite_operation.head = operation_list; operation->value.composite_operation.arg1 = arg1; operation->value.composite_operation.arg2 = arg2; operation->value.composite_operation.arg3 = arg3; operation->value.composite_operation.farg = farg; return operation; } /** * Destroy (free) a sudoku game operation * @param operation */ void destruct_game_operation(sudoku_game_operation_t *operation) { if (operation->operation_type != ATOMIC && operation->operation_type != HEAD) { /* Destruct atomic operations comprising the composite operation */ destruct_operation_list(operation->value.composite_operation.head); } free(operation); } /** * Append an atomic game operation to a composite operation * @param composite_operation * @param row * @param col * @param old_value * @param new_value */ void append_atomic_operation(sudoku_game_operation_t *composite_operation, int row, int col, int old_value, int new_value) { sudoku_game_operation_t *operation = create_atomic_game_operation(); operation->value.atomic_operation.row = row; operation->value.atomic_operation.col = col; operation->value.atomic_operation.old_value = old_value; operation->value.atomic_operation.new_value = new_value; operation_list_append(composite_operation->value.composite_operation.head, operation); } /** * Undo a composite game operation * @param game * @param operation */ void undo_operation(sudoku_game_t *game, sudoku_game_operation_t *operation) { operation_node_t *node = operation->value.composite_operation.head->next; /* Iterate over all atomic operations and undo them */ while (node != NULL) { set_cell_flattened(game->board, node->operation->value.atomic_operation.old_value, node->operation->value.atomic_operation.row, node->operation->value.atomic_operation.col); node = node->next; } } /** * Redo a composite game operation * @param game * @param operation */ void redo_operation(sudoku_game_t *game, sudoku_game_operation_t *operation) { operation_node_t *node = operation->value.composite_operation.head->next; /* Iterate over all atomic operations and redo them */ while (node != NULL) { set_cell_flattened(game->board, node->operation->value.atomic_operation.new_value, node->operation->value.atomic_operation.row, node->operation->value.atomic_operation.col); node = node->next; } }
C
#include <msp430f5529.h> //Precision Control /*** initialize prototype functions ***/ void pinOutput(int values); void trianglewave(); void Counter8bit(); int main(void) { WDTCTL = WDTPW | WDTHOLD; // Stop watchdog timer /*** Initialize GPIO pins ***/ P2DIR |= BIT0; // P2.0 output P2SEL |= BIT0; // P2.0 for TA1 CCR1 Output Capture P6DIR |= BIT0 + BIT1 + BIT2 + BIT3 + BIT4; // Initialize GPIO pins for R2R ladder P3DIR |= BIT5 + BIT6; P7DIR |= BIT0; /*** Timer1_A1 Set-Up ***/ TA1CTL |= TASSEL_2 | MC_1 | ID_3; // SMCLK, up-mode, divide by 2^3 TA1CCR0 |= 1000; // 2^12 bits, 12 bit ADC. 1000 Hz output frequency. Change this number to change frequency. TA1CCTL1 |= OUTMOD_7; //P2.0 TA1CCR1 = 500; // 50% duty cycle. Complement the changing of frequency by changing this as well. /*** Begin outputting a triangle wave or a step/staircase function, choose only one. ***/ //Counter8bit(); trianglewave(); return 0; } void Counter8bit(){ int i = 0; // for-loop counters int j = 0; // for-loop delays used in creating pauses in 8-bit counter. while(1){ for(i = 0; i < 256; i=i+16){ // Increment up to 256 in 17 total steps if(i > 255) { //fix i value if i goes beyond 255 (keeping it below 1000 for the timer reg). i = 255; } pinOutput(i); // Set the R2R ladder D/A circuit to increment the 8-bit binary number of 0-255 i *= 125; i = i >> 5; // 255*125 = 31875 = 111110010000011. Ans >> 5 = 1111100100 = 996. TA1CCR1 = i; // converted i index fits within 0-1000 range. for(j = 0; j < 1000; j++); // delay to create steps } for(i = 255; i >= 0; i=i-32){ // Decrement index until 0 (8 bit 0x00) is reached if(i < 0) { //fix i value if i goes below 0 (keeping it above 0 for the timer reg) i = 0; } pinOutput(i); // Set the R2R ladder D/A circuit to decrement the 8-bit binary number of 0-255 i *= 125; i = i >> 5; // 255*125 = 31875 = 111110010000011. Ans >> 5 = 1111100100 = 996. TA1CCR1 = i; // converted i index fits within 0-1000 range. for(j = 0; j < 1000; j++); // delay to create steps } } } void trianglewave(){ int i = 0; // for-loop counters while(1){ for(i = 0; i < 256; i++){ // Increment up to 256 one integer at a time. if(i > 255) { i = 255; } i *= 125; i = i >> 5; // 255*125 = 31875 = 111110010000011. Ans >> 5 = 1111100100 = 996. TA1CCR1 = i; // converted i index fits within 0-1000 range. //pinOutput(i); // This line is not needed since the triangle wave does not solely enter the R2R ladder } for(i = 255; i >= 0; i--){ // Decrement down to 0 one integer at a time. if(i < 0) { i = 0; } i *= 125; i = i >> 5; // 255*125 = 31875 = 111110010000011. Ans >> 5 = 1111100100 = 996. TA1CCR1 = i; // converted i index fits within 0-1000 range. //pinOutput(i); // This line is not needed since the triangle wave does not solely enter the R2R ladder } } } void pinOutput(int i){ int bit0 = i & BIT0; // Mask the bits of input into corresponding i values int bit1 = i & BIT1; int bit2 = i & BIT2; int bit3 = i & BIT3; int bit4 = i & BIT4; int bit5 = i & BIT5; int bit6 = i & BIT6; int bit7 = i & BIT7; if (bit0) { P6OUT |= BIT0; } //Each bit# integer corresponds to the current bit of each input and is sent to its own pin. else { P6OUT &= ~BIT0; //Turn each pin off if integer does not correspond. } if (bit1) { P6OUT |= BIT1; } else { P6OUT &= ~BIT1; } if (bit2) { P6OUT |= BIT2; } else { P6OUT &= ~BIT2; } if (bit3) { P6OUT |= BIT3; } else { P6OUT &= ~BIT3; } if (bit4) { P6OUT |= BIT4; } else { P6OUT &= ~BIT4; } if (bit5) { P7OUT |= BIT0; } else { P7OUT &= ~BIT0; } if (bit6) { P3OUT |= BIT6; } else { P3OUT &= ~BIT6; } if (bit7) { P3OUT |= BIT5; } else { P3OUT &= ~BIT5; } }
C
#ifndef _HASH_H_ #define _HASH_H_ //ϣ() typedef struct hash hash_t; typedef unsigned int (*hashfunc_t)(unsigned int, void*); hash_t* hash_alloc(unsigned int buckets, hashfunc_t hash_func);// void* hash_lookup_entry(hash_t *hash, void* key, unsigned int key_size);//ѯ void hash_add_entry(hash_t *hash, void *key, unsigned int key_size,void *value, unsigned int value_size);// void hash_free_entry(hash_t *hash, void *key, unsigned int key_size);//ɾ #endif /* _HASH_H_ */
C
#include "headers/enlace.h" ////Constantes #define SIZE 1024 /* * Cliente UDP */ //nos[0] guarda as informacoes do no 1. //nos[1] guarda as informacoes do no 2. //etc.. int checkSum(void *); int checksum; int no_do_enlace; // Numero do nó iniciado; void iniciaEnlace(){ no_do_enlace = info.no_de_inicio; int node=0; int number; int elem1; int elem2; int elem3; int elem4; int porta; char str[50]; FILE *arq; int ret=6; printf("\n%s\n",info.arg); arq = fopen(info.arg, "r"); if(arq == NULL) printf("Erro, nao foi possivel abrir o arquivo\n"); else{ fscanf(arq,"%s",str); char aux[10]=""; do{ ret = fscanf(arq,"%d: IP = %d.%d.%d.%d, Porta = %d;", &number,&elem1,&elem2,&elem3,&elem4,&porta); if(ret >= 6){ if(node != 4){ nos[node].no = number; nos[node].porta = porta; fflush(stdout); fflush(stdin); sprintf(nos[node].ip,"%d.%d.%d.%d",elem1,elem2,elem3,elem4); fflush(stdin); fflush(stdout); node++; } } }while(ret >= 6); ret=3; fscanf(arq,"%s",str); do{ ret = fscanf(arq,"%d -> %d, MTU = %d;", &number,&elem1,&elem2); if(ret >= 3){ matriz[number-1][elem1-1]=1; matriz[elem1-1][number-1]=1; mtu[number-1][elem1-1]=elem2; mtu[elem1-1][number-1]=elem2; } }while(ret >= 3); } //Testando funcoes printf("%d: IP:::::::::%s,PORTA = %d\n",nos[0].no,nos[0].ip,nos[0].porta ); printf("%d: IP:::::::::%s,PORTA = %d\n",nos[1].no,nos[1].ip,nos[1].porta ); printf("%d: IP:::::::::%s,PORTA = %d\n",nos[2].no,nos[2].ip,nos[2].porta ); printf("%d: IP:::::::::%s,PORTA = %d\n",nos[3].no,nos[3].ip,nos[3].porta ); fclose(arq); printf("\n"); print_matriz(4,4); printf("\n"); print_mtu(4,4); printf("\n"); printf("\ntem ligacao:%d\n\n", tem_ligacao(1,2)); printf("\nMTU:%d\n\n", getMtu(1,2)); ////UDP printf("\nFRI:%s\n\n", nos[2].ip); iniciaThreads(); } //Threads Produtor e Consumidor ------------- void error(char *msg){ perror(msg); exit(0); } int v[10]; //Recebe Datagrama void *Prod_enlace(void *thread) { int id=*(int *)thread; int sock,length,fromlen, n; struct sockaddr_in server; struct sockaddr_in from; char buf[1024]; char aux[1024]; sock=socket(AF_INET, SOCK_DGRAM,0); if(sock < 0){ error("Opening socket"); } length = sizeof(server); bzero(&server, length); server.sin_family = AF_INET; server.sin_addr.s_addr = inet_addr(nos[no_do_enlace-1].ip); server.sin_port = htons(nos[no_do_enlace-1].porta); if(bind(sock,(struct sockaddr *)&server,length) < 0){ error("binding"); } while(1){ //Mutex pthread_mutex_lock(&rcv1); fromlen = sizeof(struct sockaddr_in); printf("\nSize:%d\n",sizeof(data_rcv)); n = recvfrom(sock,&data_rcv, sizeof(data_rcv),0,(struct sockaddr *)&from,&fromlen); if(n < 0){ error("recvfrom"); } write(1,"Datagrama Recebido: ",20); //write(1, data_rcv.buffer, n); printf("DATA: %s\n\n", data_rcv.buffer); /* n = recvfrom(sock,aux,1024,0,(struct sockaddr *)&from,&fromlen); if(n < 0){ error("recvfrom"); }*/ printf("DATA 2: %d\n\n", data_rcv.tam_buffer); printf("DATA 2: %d\n\n", data_rcv.checksum); //int no_envio; //checksum = atoi(aux); // strcpy(data_rcv.buffer,""); //strcpy(data_rcv.buffer,buf);///<---------------------------Atribui valores para a struct de recebimento // data_rcv.tam_buffer = strlen(buf); //data_rcv.no_envio = no_do_enlace; printf("DATA 3: %d\n\n", data_rcv.no_envio); //RECALCULA CHECKSUM int checksum2 = data_rcv.checksum; printf("\nTam Buffer:%d",data_rcv.tam_buffer); printf("\nNo de Envio:%d",data_rcv.no_envio); printf("\nBuffer:%s",data_rcv.buffer); printf("\nChecksum:%d\n",data_rcv.checksum); printf("\nChecksum:%d\n",sizeof(data_rcv)); int check = checkSum(&data_rcv.buffer); printf("\nCheck %d:::::%d::::::%d",check, data_rcv.checksum, checksum2); if (data_rcv.checksum == check){ printf("Datagrama sem erro\n"); } else { printf("Datagrama com erro\n"); } printf("Buffer:::%s",data_rcv.buffer); pthread_mutex_unlock(&rcv2); } } //Envia Datagrama void *Cons_enlace(void *thread){ int id=*(int *)thread; int teste; //printf("\n%d ::: %s\n",data_env->no, data_env->data); while(1){ int sock,length, n; struct sockaddr_in server; struct sockaddr_in from; struct hostent *hp; int mtu=0; char buffer[1024]; char check_aux[1024]; pthread_mutex_lock(&env2); sock = socket(AF_INET, SOCK_DGRAM,0); if(data_env.tam_buffer != 0){ if(tem_ligacao(no_do_enlace,data_env.no_envio)){ mtu = getMtu(no_do_enlace,data_env.no_envio); //printf("ENVIA::::IP:::::%s PORTA::::%d",nos[data_env.no_envio-1].ip,nos[data_env.no_envio-1].porta); //printf("Mtu:::%d\n\n",mtu); if(sock < 0){ error("socket"); } //Limpa Buffer strcpy(buffer,""); server.sin_family = AF_INET; hp = gethostbyname(nos[data_env.no_envio-1].ip); //Localhost if(hp == 0){ error("Uknown host"); } bcopy((char *)hp->h_addr, (char *)&server.sin_addr,hp->h_length); server.sin_port = htons(nos[data_env.no_envio-1].porta); //5000 length=sizeof(struct sockaddr_in); bzero(buffer, 1024); fgets(buffer,1024,stdin); strcpy(buffer,data_env.buffer); //TESTA MTU if(strlen(data_env.buffer) > mtu){ error("MTU Error-> Nao foi possivel enviar o pacote"); } //CHECKSUM data_env.tam_buffer = strlen(data_env.buffer); checksum = checkSum(4); printf("check::: %d\n\n",checksum); sprintf(check_aux,"%d",checksum); data_env.checksum = checksum; //Garbler printf("Tam Buffer:%d\n",data_env.tam_buffer); printf("No de Envio:%d\n",data_env.no_envio); printf("Buffer:%s\n",data_env.buffer); printf("Checksum:%d\n",data_env.checksum); printf("sizeof:%d\n",sizeof(data_env)); set_garbler(0, 0, 0); n=sendto_garbled(sock,&data_env,sizeof(data_env),0,(struct sockaddr *)&server,length); if(n < 0 ){ error("Sendto_garbled"); } /*sleep(10); n=sendto_garbled(sock,check_aux,strlen(check_aux),0,&server,length); if(n < 0 ){ error("Sendto"); }*/ printf("Datagrama Enviado\n"); } else{ fprintf(stdout,"\nNós não são vizinhos\n"); } pthread_mutex_unlock(&env1); } }//Fecha While } int iniciaThreads(){ pthread_t t1; int a1 = 1; //Recebe pthread_create(&t1, NULL, Prod_enlace, (void *)(&a1)); pthread_t t2; int a2 = 2; //Envia pthread_create(&t2, NULL, Cons_enlace, (void *)(&a2)); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; } //Funções Auxiliares void print_matriz(int lin, int col){ int x,y; for(x=0;x<lin;x++) { for(y=0;y<col;y++) { printf("%d ", matriz[x][y]); } printf("\n"); } } void print_mtu(int lin, int col){ int x,y; for(x=0;x<lin;x++) { for(y=0;y<col;y++) { printf("%d ", mtu[x][y]); } printf("\n"); } } int tem_ligacao(int no1,int no2){ if(matriz[no1-1][no2-1]) return 1; return 0; } int getMtu(int no1, int no2){ if(!tem_ligacao(no1,no2)) return 0; return mtu[no1-1][no2-1]; } int checkSum(void *sum) { int i; int check=0; unsigned char *data; data = sum; data += 2; for (i=2; i < sizeof(struct datagrama); i++) { check += *data++; printf("Check:::IIII::%d::%d\n\n",i,check); } return check; }
C
// BUBBLE SORT #include<stdio.h> void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } void bubble_sort(int arr[],int n) { for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } } } } void printarray(int arr[],int n) { for(int i=0;i<n;i++) { printf("%d",arr[i]); } } int main() { int array[5] = {5,4,3,2,1}; bubble_sort(array,5); printf("sorted array\n"); printarray(array,5); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct polynode { float coef; int exp; struct poly *next; } poly; void file_print(poly *head) { poly *p = head; FILE *fp; fp = fopen("poly_list.txt","w"); for(; p!=NULL; p = p->next) { fprintf(fp,"%f %d, ",p->coef,p->exp); } fclose(fp); } void file_read(poly *head) { poly *p = head; FILE *fp; fp = fopen("poly_list.txt","r"); while(1) { fscanf(fp,"%f %d",&p->coef,&p->exp); if(getchar()== '\n') break; p->next = (poly *)malloc(sizeof(poly)); p = p->next; p->next = NULL; } fclose(fp); } void poly_creat(poly *head) { poly *p = head,*pr =NULL; float coef; int exp; p->next =NULL; printf("ʽÿϵָ:\n"); while(1) { do { scanf("%f %d",&coef,&exp); } while(coef == 0); p->coef = coef; p->exp =exp; if(getchar() == '\n') break; p->next = (poly *)malloc(sizeof(poly)); p = p->next; p->next =NULL; } poly_sort(head); printf(" ʽΪ:\n"); poly_printf(head); } void swap(poly *a,poly *b) { float ex_f; ex_f = a->coef; a->coef = b->coef; b->coef = ex_f; int ex; ex = a->exp; a->exp = b->exp; b->exp= ex; } void poly_printf(poly *head) { if(head->coef == 0) { printf("no data !!!"); return 0; } poly *p = head,*px =NULL; for(; p->next != NULL; p = p->next ) { if(p->coef > 0 && p != head) printf(" + "); printf("%.2f*x^%d ",p->coef,p->exp); } if(p->exp) { if(p->coef > 0) printf(" + "); printf("%.2f*x^%d \n\n ",p->coef,p->exp); } else { if(p->coef > 0) printf(" + "); printf("%.2f\n\n ",p->coef,p->exp); } } void poly_sort(poly *head) { if(head ==NULL ) { printf("no data!\n"); return 0; } else if(head->next == NULL) { printf("neednt sort\n"); return 0; } poly *p = head; poly *px = p->next,*pr = NULL; for(; p->next != NULL; p = p->next) { for(px = p->next; px != NULL; px = px->next) { if(px->coef * px->coef <=0.0001) px->exp =0; if(p->coef * p->coef<=0.0001) p->exp =0; if(p->exp < px->exp) { swap(p,px); } else if(p->exp == px->exp ) { p->coef += px->coef; px->coef =0; px->exp = 0; } } } for(p =head, px =p->next; p->next!=NULL; p=p->next) { if(px->coef == 0) { p->next = NULL; free(px); break; } px = px->next; } } void poly_comp(poly *head) { if(head->coef == 0) { printf("no data!"); return 0; } float x; int i; printf("input:\n"); scanf("%f",&x); poly *p = head; float ret,ans = 0; while(p != NULL) { ret = p->coef; for(i = 0; i < p->exp; i++) ret *= x; ans += ret; p =p->next; } printf(" %f:\n",ans); } void poly_add(poly *head_1,poly *head_2,poly *head_3) { poly *p1 = head_1,*p2 = head_2,*p3 = head_3; while(1) { if(p1 == NULL && p2 == NULL ) break; else if(p1 == NULL ) { p3->coef = p2->coef; p3->exp = p2->exp; p2 = p2->next; } else if(p2 == NULL ) { p3->coef = p1->coef; p3->exp = p1->exp; p1 = p1->next; } else { if(p1->exp > p2->exp) { p3->coef = p1->coef; p3->exp = p1->exp; p1 = p1->next; } else if(p1->exp < p2->exp) { p3->coef = p2->coef; p3->exp = p2->exp; p2 = p2->next; } else { p3->coef = p1->coef + p2->coef; p3->exp = p1->exp; p1 = p1->next; p2 = p2->next; } // } if(p1 != NULL || p2!= NULL) { p3->next = (poly *)malloc(sizeof(poly)); p3 = p3->next; p3->next = NULL; } } printf("\n:\n"); poly_sort(head_3); poly_printf(head_3); } void poly_sub(poly *head_1,poly *head_2,poly *head_3) { poly *p1 = head_1,*p2 = head_2,*p3 = head_3; while(1) { if(p1 == NULL && p2 == NULL ) break; else if(p1 == NULL ) { p3->coef = -p2->coef; p3->exp = p2->exp; p2 =p2->next; } else if(p2 == NULL ) { p3->coef = p1->coef; p3->exp = p1->exp; p1 = p1->next; } else { if(p1->exp > p2->exp) { p3->coef = p1->coef; p3->exp = p1->exp; p1 = p1->next; } else if(p1->exp < p2->exp) { p3->coef = -p2->coef; p3->exp = p2->exp; p2 = p2->next; } else { p3->coef = p1->coef - p2->coef; p3->exp = p1->exp; p1 = p1->next; p2 = p2->next; } } if(p1 != NULL || p2!= NULL) { p3->next = (poly *)malloc(sizeof(poly)); p3 = p3->next; p3->next = NULL; } } printf("\n:\n"); poly_sort(head_3); poly_printf(head_3); } void poly_mult(poly *head_1,poly *head_2,poly *head_3) { poly *p1 = head_1,*p2 = head_2,*p3 = head_3; for(; p1 != NULL; p1 = p1->next) for(p2 = head_2; p2 != NULL; p2 = p2->next) { p3->coef = p1->coef * p2->coef; p3->exp = p1->exp + p2->exp; if(p1->next != NULL || p2->next != NULL) { p3->next= (poly *)malloc(sizeof(poly)); p3 = p3->next; p3->next =NULL; } } poly_sort(head_3); printf("\n :\n"); poly_printf(head_3); } void poly_div(poly *head_1,poly *head_2,poly *head_3) { poly *p1 = head_1,*p2 = head_2,*pq = head_3; if(p1->exp < p2->exp ) { printf("canot div"); return 0; } float q =1,n = p1->exp - p2->exp +1; while(n> 0 && q != 0) { p1 = head_1; p2 = head_2; while(p1->coef * p1->coef <= 0.0001 && p1->next !=NULL) { p1 = p1->next; } if(p1->exp < p2->exp) break; pq->coef = p1->coef / p2->coef; pq->exp = p1->exp - p2->exp; for(q =0; p1 != NULL && p2 != NULL; p1 = p1->next,p2 = p2->next) { p1->coef -= p2->coef * pq->coef; q +=p1->coef; } n -- ; if(q != 0 && n > 0) { pq->next = (poly *)malloc(sizeof(poly)); pq = pq->next; pq->next = NULL; } } printf(":\n"); poly_sort(head_3); poly_printf(head_3); printf(":\n"); poly_sort(head_1); poly_printf(head_1); } int main() { poly head_1,head_2,head_3; head_1.coef = 0; head_2.coef = 0; head_3.coef = 0; poly_creat(&head_1); //poly_comp(&head_1); poly_creat(&head_2); //poly_comp(&head_2); poly_add(&head_1,&head_2,&head_3); poly_sub(&head_1,&head_2,&head_3); poly_mult(&head_1,&head_2,&head_3); poly_div(&head_1,&head_2,&head_3); // file_read(&head_1); // file_print(&head_1); //poly_comp(&head_1); free(&head_1); free(&head_2); free(&head_3); return 0; } /* 1 1 4 5 6 3 7 9 5 2 3 1 3 2 6 3 1 3 -3 2 -1 1 -1 0 3 2 -2 1 1 0 */
C
/*2. Дан текст. Слова в тексте разделены пробелами и знаками препинания. Получить n наиболее часто встречающихся слов и число их появлений.*/ #include <stdio.h> #include <stdlib.h> int memoryCounter(char* text) { int counter = 0, wordLength = 0, lastSymbol = 0; for (int i = 0; i < 256; i++) { if ((text[i] == ' ') || (text[i] == '.') || (text[i] == ',') || (text[i] == '!')) { wordLength = i - lastSymbol; if (wordLength == 0) counter--; counter++; lastSymbol = i + 1; } } counter++; return counter; } int main() { int i, j, k, wordLength = 0, lastSymbol = 0; char buffer[256]; printf("Please, input string: ");// Строки для отладки "I think that BSUIR is the best university in Belarus. BSUIR plays a big role for IT-Industy of our country!", "Nesvizh castle is a residental castle of radzivill family, castle was founded at 1551. It's really old!" rewind(stdin); gets(buffer); char** words = NULL; words = (char**)malloc(memoryCounter(buffer) * sizeof(char*)); for (int i = 0; i < memoryCounter(buffer); i++) { words[i] = (char*)malloc(15 * sizeof(char)); } int counter = 0; // Выделение слов в двумерный массив for (i = 0; i < 256; i++) { if ((buffer[i] == ' ') || (buffer[i] == '.') || (buffer[i] == ',') || (buffer[i] == '!') || (buffer[i] == '\0')) { wordLength = i - lastSymbol; k = 0; for (j = lastSymbol; j <= i; j++) { if (j == i) words[counter][k] = ' '; words[counter][k] = buffer[j]; k++; } if (wordLength == 0) counter--; counter++; lastSymbol = i + 1; } } // Поиск наиболее часто встречающегося слова int repeatCount = 0, maxRepeat = 0, maxIndex = 0, flag = 1; for (int j = 0; j < counter; j++) { for (int i = 0; i < counter; i++) { for (int k = 0; k < 15; k++) { if (words[j][k] != words[i][k]) { flag = 0; break; } } if (flag == 1) { repeatCount++; } flag = 1; } if (maxRepeat < repeatCount) { maxRepeat = repeatCount; maxIndex = j; } repeatCount = 0; } // Вывод информации int len = 0; for (i = 0; i < 15; i++) { if (words[maxIndex][i] == ' ') break; len++; } printf("The number of all words at text = %d", counter); printf("\nThe most common word - "); for (int i = 0; i < len; i++) { printf("%c", words[maxIndex][i]); } printf("\nIt was repeated %d times in text.", maxRepeat); return 0; }
C
/* * Fixed size hash table implementation * * Just a quick hash table implementation for use * with the bot.. will probably switch to * something more standard later.. */ #include <math.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include <sys/queue.h> #include "htable.h" static const struct hentry { char * key; size_t key_sz; struct hentry * next; TAILQ_ENTRY(hentry) tailq_entries; /* Entry for traversal based list */ void * data; } hentry_initializer; /* Linked list structure to keep a list * of the entries in the hash table. * * This is used traverse the hash table iteratively * in a quick manner */ static const struct htable { struct hentry ** tbl; /* this allows us to allocate each entry individually, we just store a table of pointers */ size_t tbl_size; TAILQ_HEAD(hentry_list, hentry) list; /* Stats */ size_t tbl_direct, tbl_linked, tbl_total; int load; } htable_initializer; /* * CURRENT HASH FUNCTION WE'RE USING (THERE ARE MORE AT THE BOTTOM OF THIS FILE) */ /* This hash performs just as good as jenkins hash, for string types * which is the type required for keys.. :) */ static size_t htable_shift_add_xor_hash(const char * key) { size_t h = 0; while ( *key ) h ^= ( h << 5 ) + ( h >> 2 ) + *key++; return h; } /* Create a table of 2*'size'...will resize as necessary but * resizing is very expensive so start out with the size you * think you'll need in a worst case scenario * * The actual size used will be the nearest prime number * larger then 2*'size' */ struct htable * htable_new(size_t size) { struct htable * tbl; do { size_t nsize = 1; /* Initialize table */ if ( !(tbl = malloc(sizeof *tbl)) ) break; *tbl = htable_initializer; TAILQ_INIT(&tbl->list); // Initialize our TAILQ_ head /* Find next power of 2 larger then 'size' */ do nsize *= 2; while (size >>= 1); /* there is a faster method but even with 1000bit int this wouldn't take very long */ tbl->tbl_size = nsize; // fprintf(stderr,"Requested size %lu.. using next larger power of 2 %lu\n", size, tbl->tbl_size); /* Allocate array[tbl_size] of void * (pointer to void) */ tbl->tbl = calloc(tbl->tbl_size, sizeof *tbl->tbl); if (!tbl->tbl) { free(tbl); tbl = NULL; break; } } while(0); return tbl; } void htable_free_cb(struct htable * htab, void (*cb)(const char * key, void * data)) { assert(htab != NULL); /* Free each entry..(using linked list) */ struct hentry * p; while (!TAILQ_EMPTY(&htab->list)) { p = TAILQ_FIRST(&htab->list); TAILQ_REMOVE(&htab->list, p, tailq_entries); if (cb) cb(p->key, p->data); free(p->key); free(p); } free(htab->tbl); free(htab); } void htable_free(struct htable * htab) { htable_free_cb(htab, NULL); } /* * Lookup key in our table and return a pointer * to the entry (if any). The pointer returned may in fact * be the insertion point (->next pointer in the entry) and not * the key itself. * * If 'found' is true then the returned value is in fact the * key you were looking for. If found is 0 then the returned value is * one of the following: * * NULL -> item not found and insertion point would be the table index at 'idx' (below) * valid pointer -> item not found pointer is the insertion point in the linked list we should store this key * * 'last' will be the previous pointer to this pointer (if it was a linked list entry..otherwise itw ill be NULL) * this is used for deletion and can be NULL then will be ignored */ /* This is our macro alias to our current hash function we're using */ #define get_key_index(htab,key) (htable_shift_add_xor_hash(key) & ((htab)->tbl_size-1)) struct hentry * get_key(struct htable * htab, const char * key, struct hentry ** last, size_t * index, int * found) { struct hentry * he = NULL; int depth = 0; *index = get_key_index(htab,key); *last = NULL; *found = 0; /* Return value from the amount of bits that are in tbl_size */ he = htab->tbl[*index]; if (he) { while ( (*found = strncmp(key,he->key,he->key_sz)) && he->next ){ ++depth; // printf("%s -> ", he->key); *last = he, he = he->next; } /* Above it's actually "not" found, so inverse the result */ *found = !*found; if (htab->load < depth) htab->load = depth; } return he; } /* * Search 'htab' for 'key' returning it if found. If item is not NULL * Do one of the following: * if 'key' exists, leave it untouched as well as it's value * if 'key' doesn't exist, add it with value 'item' (return NEW item) * If 'item' is NULL then just return the existing item or NULL of none */ static void * htable_store(struct htable * htab, const char * key, void * data) { size_t idx; int found; struct hentry * ne; struct hentry * he = get_key(htab, key, &ne, &idx, &found); void * rdata = NULL; do { if (!data) break; ne = malloc(sizeof *ne); if (!ne) break; /* Init entry with our key and data */ *ne = hentry_initializer; ne->key_sz = strlen(key); ne->key = malloc(ne->key_sz+1); if (!ne->key) { free(ne); break; } /* assign values */ strcpy(ne->key,key); rdata = ne->data = data; /* add or update item to hashtable */ if (!he) { htab->tbl[idx] = ne; ++htab->tbl_direct; ++htab->tbl_total; //printf("storing '%s' at '%lu'\n", key, idx); // Insert entry at the end of the traversal list TAILQ_INSERT_TAIL(&htab->list, ne, tailq_entries); } else if (!found) { //printf("'%s' -> linked '%s'\n", he->key, key); ne->next = he->next; he->next = ne; ++htab->tbl_linked; ++htab->tbl_total; // Insert entry at the end of the traversal list TAILQ_INSERT_TAIL(&htab->list, ne, tailq_entries); } else { /* key already exists, free new item but update data object */ free(ne->key); free(ne); /* Update entry and return old data */ rdata = he->data; he->data = data; } } while (0); return rdata; } static void * htable_lookup(struct htable * htab, const char * key) { size_t idx; int found; struct hentry * ne = NULL; struct hentry * he = get_key(htab, key, &ne, &idx, &found); void * rdata = NULL; if (he && found) rdata = he->data; return rdata; } static void * htable_delete(struct htable * htab, const char * key) { size_t idx; int found; struct hentry * le; struct hentry * he = get_key(htab, key, &le, &idx, &found); void * rdata = NULL; if ( he && found ) { rdata = he->data; /* Destroy entry */ --htab->tbl_total; if (le) --htab->tbl_linked, le->next = he->next; /* we might be deleting in center of list */ else --htab->tbl_direct, htab->tbl[idx] = NULL; // Remove the entry from the traversal list TAILQ_REMOVE(&htab->list, he, tailq_entries); free(he->key); free(he); } return rdata; } /* * Iterate over the hash table using the TAILQ * this is efficient but the order is not gauranteed * at to be consistent */ static void htable_foreach(struct htable * htab, int (*cb)(const char * key, void * data)) { struct hentry * he; TAILQ_FOREACH(he, &htab->list, tailq_entries) { if (cb(he->key, he->data)) /* non zero return indicates we should end here */ break; } } int htable_load(struct htable * htab) { return htab->load; } size_t htable_direct(struct htable * htab) { return htab->tbl_direct; } size_t htable_linked(struct htable * htab) { return htab->tbl_linked; } size_t htable_total(struct htable * htab) { return htab->tbl_total; } size_t htable_size(struct htable * htab) { return htab->tbl_size; } /* * Install API handlers */ const struct htable_api htable = { .new = htable_new, .free = htable_free, .free_cb = htable_free_cb, .lookup = htable_lookup, .delete = htable_delete, .store = htable_store, .load = htable_load, .direct = htable_direct, .linked = htable_linked, .size = htable_size, .total = htable_total, .foreach = htable_foreach, }; /* * TEST HARNESS */ #if 0 int main(void) { struct htable * htab; int i = 5; char line[BUFSIZ]; htab = htable_new(25); while ( fgets(line, sizeof line, stdin) ) { char * p = strchr(line, '\n'); if (p) *p = 0; htable_store(htab, line, &i); } htable_free(htab); return 0; } #endif /************************************************************************************* * HASH RELATED FUNCTIONS THAT ARE GOOD TO HAVE BUT NOT CURRENTLY USED *************************************************************************************/ #if 0 /* * * Best possible deterministic test (aside from using lookup tables) * for primality * * Probablistic methods are faster but test * for "most likely a prime"..this PROVES its a prime * */ static int is_prime(size_t num) { register size_t cur = 0, sqt; if (num % 2 && num % 3) { /* If number is indivisible by all numbers from * 6k+or-1 to sqrt(num) it is prime * Where k = 1,2,3,4,5 etc.. */ sqt = sqrt(num); for (cur = 5; cur <= sqt; cur+=6) { if ( !(num % cur) || !(num % (cur+2)) ) break; } /* Was prime? set return value to 1 */ cur = (cur > sqt); } /* 1 is prime, anything else is nonprime */ return cur == 1; } /* * Miscellaneous other hash functions we might use later.. */ static size_t htable_fnv_hash(const unsigned char *key) { size_t h = 2166136261; while ( *key ) h = ( h * 16777619 ) ^ *key++; return h; } static size_t htable_elf_hash(const unsigned char * key) { size_t h = 0, g; while ( *key ) { h = ( h << 4 ) + *key++; g = h & 0xf0000000L; if ( g != 0 ) h ^= g >> 24; h &= ~g; } return h; } #define mix(a,b,c) \ { \ a -= b; a -= c; a ^= ( c >> 13 ); \ b -= c; b -= a; b ^= ( a << 8 ); \ c -= a; c -= b; c ^= ( b >> 13 ); \ a -= b; a -= c; a ^= ( c >> 12 ); \ b -= c; b -= a; b ^= ( a << 16 ); \ c -= a; c -= b; c ^= ( b >> 5 ); \ a -= b; a -= c; a ^= ( c >> 3 ); \ b -= c; b -= a; b ^= ( a << 10 ); \ c -= a; c -= b; c ^= ( b >> 15 ); \ } static size_t htable_jen_hash( const unsigned char *k, size_t length, size_t initval ) { unsigned a, b; size_t c = initval; size_t len = length; a = b = 0x9e3779b9; while ( len >= 12 ) { a += ( k[0] + ( (unsigned)k[1] << 8 ) + ( (unsigned)k[2] << 16 ) + ( (unsigned)k[3] << 24 ) ); b += ( k[4] + ( (unsigned)k[5] << 8 ) + ( (unsigned)k[6] << 16 ) + ( (unsigned)k[7] << 24 ) ); c += ( k[8] + ( (unsigned)k[9] << 8 ) + ( (unsigned)k[10] << 16 ) + ( (unsigned)k[11] << 24 ) ); mix ( a, b, c ); k += 12; len -= 12; } c += length; switch ( len ) { case 11: c += ( (unsigned)k[10] << 24 ); case 10: c += ( (unsigned)k[9] << 16 ); case 9 : c += ( (unsigned)k[8] << 8 ); /* First byte of c reserved for length */ case 8 : b += ( (unsigned)k[7] << 24 ); case 7 : b += ( (unsigned)k[6] << 16 ); case 6 : b += ( (unsigned)k[5] << 8 ); case 5 : b += k[4]; case 4 : a += ( (unsigned)k[3] << 24 ); case 3 : a += ( (unsigned)k[2] << 16 ); case 2 : a += ( (unsigned)k[1] << 8 ); case 1 : a += k[0]; } mix ( a, b, c ); return c; } static size_t htable_one_at_a_time_hash(const char * key) { size_t h = 0; while ( *key ) { h += *key++; h += ( h << 10 ); h ^= ( h >> 6 ); } h += ( h << 3 ); h ^= ( h >> 11 ); h += ( h << 15 ); return h; } #endif
C
#include <stdlib.h> #include <stdio.h> #include <stdbool.h> //Binary Search //Class number 4, March 26, 2018 //Recursive Implementation //Check elem in an array bool check_elem(int *v, int min_index, int max_index, int val){ int middle = ((min_index + max_index)/2); if(max_index < min_index) return false; if(val == v[middle]) return true; if(val < v[middle]) check_elem(v, min_index, middle - 1, val); else check_elem(v, middle + 1 , max_index, val); } int main(){ int arr[] = {11,21,33,66,77,88}; printf("%d\n", check_elem(arr,0,(int)(sizeof(arr)/sizeof(arr[0]))-1,11)); return 0; }
C
/* ** change_lines_ai.c for in /home/sepret_f/sem2/cpe/CPE_2015_Allum1 ** ** Made by fabrice sepret ** Login <sepret_f@epitech.net> ** ** Started on Wed Feb 10 14:39:58 2016 fabrice sepret ** Last update Thu Feb 18 14:33:13 2016 fabrice sepret */ #include <stdlib.h> #include "alum1.h" int change_line1_ai(t_va var, char *str) { int i; i = 0; if ((var.line1 = malloc(sizeof(char *) * 10)) == NULL) return (-1); while (str[i] != 0) { var.line1[i] = str[i]; i += 1; } now_display_ai(var); } int change_line2_ai(t_va var, char *str) { int i; i = 0; if ((var.line2 = malloc(sizeof(char *) * 10)) == NULL) return (-1); while (str[i] != 0) { var.line2[i] = str[i]; i += 1; } now_display_ai(var); } int change_line3_ai(t_va var, char *str) { int i; i = 0; if ((var.line3 = malloc(sizeof(char *) * 9)) == NULL) return (-1); while (str[i] != 0) { var.line3[i] = str[i]; i += 1; } now_display_ai(var); } int change_line4_ai(t_va var, char *str) { int i; i = 0; if ((var.line4 = malloc(sizeof(char *) * 10)) == NULL) return (-1); while (str[i] != 0) { var.line4[i] = str[i]; i += 1; } now_display_ai(var); }
C
#include "binary_trees.h" /** * binary_tree_nodes - counts the nodes with at least 1 child * @tree: root node of the tree to count the number of nodes * * Return: number of nodes */ size_t binary_tree_nodes(const binary_tree_t *tree) { size_t child = 0; if (!tree) return (0); if (tree->left || tree->right) child += 1; if (tree->left) child += binary_tree_nodes(tree->left); if (tree->right) child += binary_tree_nodes(tree->right); return (child); }
C
#ifndef OVERDRIVE_H #define OVERDRIVE_H #define LPF1P 0 #define HPF1P 1 typedef struct iir_1p_t { // Coefficients float a1; float b0; float b1; // State variables float x1; float y1; } iir_1p; typedef struct overdrive_t { float fs; // Sampling frequency float clipper_fs; // nonlinear processing sampling frequency unsigned int oversample; // Oversampling rate unsigned int blksz; float inverse_oversample_float; // User control settings float gain; // Distortion amount -- 1.0 ... 1000.0 float tone; // Tone control -- 0.0 ... 1.0 float level; // Output level -- 0.0 ... 1.0 float dry; // Mix like od, or none like distortion bool bypass; // Processing buffers float *procbuf; // State variables float xn1; float xc1; // Pre and post emphasis EQ iir_1p anti_alias; iir_1p pre_emph; iir_1p post_emph; iir_1p tone_lp; iir_1p tone_hp; } overdrive; // Allocate the overdrive struct and set default values overdrive* make_overdrive(overdrive* od, unsigned int oversample, unsigned int bsz, float fs); void overdrive_cleanup(overdrive* od); // Set EQ parameters to non-default // Usually for configuring the overdrive flavor at initialization, // but these can be user-configurable in real-time void od_set_cut_pre_emp(overdrive* od, float fc); void od_set_cut_post_emp(overdrive* od, float fc); void od_set_cut_tone_lp(overdrive* od, float fc); void od_set_cut_tone_hp(overdrive* od, float fc); // Typical real-time user-configurable parameters void od_set_drive(overdrive* od, float drive_db); // 0 dB to 45 dB void od_set_tone(overdrive* od, float hf_level_db); // high pass boost/cut, +/- 12dB void od_set_level(overdrive* od, float outlevel_db); // -40 dB to +0 dB void od_set_dry(overdrive* od, float dry); // Clean mix, 0.0 to 1.0 bool od_set_bypass(overdrive* od, bool bypass); // Run the overdrive effect void overdrive_tick(overdrive* od, float* x); #endif //OVERDRIVE_H
C
/* ** EPITECH PROJECT, 2020 ** PSU_tetris_2019 ** File description: ** test_tetrimino_create_from_file */ #include <criterion/criterion.h> #include <criterion/redirect.h> #include <ncurses.h> #include "tetrimino.h" Test(tetrimino_create_from_file, snake) { tetrimino_t *tetrimino = NULL; char const tetrimino_path[] = "tetriminos/snake.tetrimino"; unsigned char expected_shape[2][3] = { {COLOR_BLACK, COLOR_GREEN, COLOR_GREEN}, {COLOR_GREEN, COLOR_GREEN, COLOR_BLACK}, }; tetrimino = tetrimino_create_from_file(tetrimino_path); cr_assert_not_null(tetrimino); cr_assert_str_eq(tetrimino->name, "snake"); cr_assert_eq(tetrimino->size.x, 3); cr_assert_eq(tetrimino->size.y, 2); cr_assert_eq(tetrimino->square_size, 3); cr_assert_eq(tetrimino->pos.x, 0); cr_assert_eq(tetrimino->pos.y, 0); cr_assert_eq(tetrimino->color, COLOR_GREEN); for (int row = 0 ; row < tetrimino->size.y ; row++) for (int col = 0 ; col < tetrimino->size.x ; col++) cr_assert_eq(tetrimino->shape[row][col], expected_shape[row][col]); } Test(tetrimino_create_from_file, not_existing, .init = cr_redirect_stderr) { tetrimino_t *tetrimino = NULL; char const tetrimino_path[] = "not_existing at all"; tetrimino = tetrimino_create_from_file(tetrimino_path); cr_assert_null(tetrimino); }
C
/* Sample UDP client */ #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> //Хэш-функция, используемая для проверки данных пользователя и пароля unsigned int HashH37(const char * str) { unsigned int hash = 0; for(;*str;str++) hash = (hash * 1664525) + (unsigned char)(*str) + 1013904223; return hash; } //Вывод ошибок клиента void error(const char *msg) { perror(msg);//Открыть сообщение с выводом информации на консоль exit(0); } int main(int argc, char**argv) { int sockfd,n; struct sockaddr_in servaddr,cliaddr; char sendline[1000]; char recvline[1000]; if (argc != 2) { printf("usage: udpcli <IP address>\n"); exit(1); } int pid = getpid(); sockfd=socket(AF_INET,SOCK_DGRAM,0); bzero(&servaddr,sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr=inet_addr(argv[1]); servaddr.sin_port=htons(32000); //Инициализация соединения от клиента //Передача адреса, считывается с консоли fgets(sendline, 10000,stdin); bzero(sendline,256); strncpy(sendline,argv[1],256); sendto(sockfd, sendline, strlen(sendline),0,(struct sockaddr*) &servaddr,sizeof(servaddr)); char buffer[256]; char passbuf[256]; int is_auntentity_ok = 0; bzero(buffer,256); bzero(buffer,256); bzero(passbuf,256); //Отправка кода операций sendto(sockfd,"My data",256,0, (struct sockaddr *)&servaddr,sizeof(servaddr)); n = recvfrom(sockfd,buffer,255,0,NULL,NULL); printf("%s\n",buffer); //Далее происходит этап аутентифкации printf("Please enter the message: \n");//Введите сообщение bzero(buffer,256); fgets(buffer,256,stdin);//Запись сообщения от пользователоя в массив sendto(sockfd,buffer,strlen(buffer)-1,0, (struct sockaddr *)&servaddr,sizeof(servaddr)); strncpy(passbuf,buffer,strlen(buffer)-1); bzero(buffer,256); n = recvfrom(sockfd,buffer,255,0,NULL,NULL); printf("%s\n",buffer); printf("%i\n",strlen(buffer)); if(strcmp(buffer,"Polzovatel' and Parol' neverny!") == 0) { is_auntentity_ok = 1; } is_auntentity_ok = 0; char hashbuf[256]; bzero(hashbuf,256); strcat(hashbuf,passbuf); strcat(hashbuf,buffer); printf("%s\n",hashbuf); printf("%i\n",strlen(hashbuf)); unsigned int res = HashH37(hashbuf); printf("%i\n",res); bzero(buffer,256); sprintf(buffer, "%d", res); sendto(sockfd,buffer,256,0, (struct sockaddr *)&servaddr,sizeof(servaddr)); bzero(buffer,256); n = recvfrom(sockfd,buffer,255,0,NULL,NULL); if (n < 0) error("ERROR reading from socket"); printf("%s\n",buffer);//Выведение сообщения на экран if(strcmp(buffer,"Hello!") == 0) is_auntentity_ok = 1; int i = 0; for(i = 0; i < 10; i++) { printf("Please enter the message: ");//Введите сообщение bzero(buffer,256); fgets(buffer,256,stdin);//Запись сообщения от пользователоя в массив sendto(sockfd,"commands",256,0, (struct sockaddr *)&servaddr,sizeof(servaddr)); sleep(2); sendto(sockfd,buffer,strlen(buffer),0, (struct sockaddr *)&servaddr,sizeof(servaddr)); char tmp[256]; bzero(tmp,256); strncpy(tmp,buffer,strlen(buffer)-1); if(strcmp(tmp,"logout") == 0) { printf("sovpalo\n"); FILE *fp; int status; char path[256]; bzero(path,256); bzero(buffer,256); char command[256]; bzero(command,256); strcat(command,"kill -s 9 "); char n_str[10]; bzero(n_str,10); sprintf(n_str, "%d", pid); strcat(command,n_str); fp = popen(command, "r"); if (fp == NULL) error("Failed to execute a command in the terminal\n"); status = pclose(fp); if (status == -1) { error("Error with executing of command\n"); } } bzero(buffer,256); n = recvfrom(sockfd,buffer,255,0,NULL,NULL); if (n < 0) error("ERROR reading from socket"); printf("%s\n",buffer);//Выведение сообщения на экран //Запись сообщения от пользователоя в массив } close(sockfd);//Закрытие сокета return 0; }
C
#include "print_string.h" void print_it(); int main() { print_it(); } void print_it() { char *str1 = "This is User1"; char *str2 = ".I'm running now."; while(1) { print_string(5, 10, str1); print_string(5, 11, str2); str2[0]++; } }
C
#ifndef __PRIM_AND_KRUSKAL_H__ #define __PRIM_AND_KRUSKAL_H__ #include <stdio.h> #include <stdlib.h> #define MAX_VERTEX 100 //最大结点个数 #define INFINITY 65535 //用来表示无穷大的数据 typedef int ElemType;//自定义用户数据类型 typedef float EdageType;//自定义边的数据类型 //定义图的数据结构 /* typedef struct { int number;//顶点编号 ElemType data;//其他数据信息 }VertexType;//节点类型 */ typedef struct { //VertexType vexs[MAX_VERTEX];//存放顶点信息 int vertex;//指定结点个数 int arcnum;//指定弧的个数 EdageType edages[MAX_VERTEX][MAX_VERTEX];//存储边的大小信息 }Graphics; /*普利姆算法用来求最小生成树*/ /*算法思想: 1.在把生成树看成一个集合(开始集合为空,到各个结点的距离当然未知) 2.结点与集合之间的权值可以看成结点到集合距离 3.将第一个结点加入集合,并初始化集合与其他结点的距离 4.搜索集合与结点最小的权值(距离),并把这点加入集合 5.更新集合与结点之间的距离 6.不断重复4和5步,直到所有的结点都加入了集合 */ Graphics Func_Input(){ Graphics G; int i,j,tempWeight;//权值 //提示输入边的个数 printf("VertexNumber:"); scanf("%d",&G.vertex); //提示输入弧的个数 printf("EdagesNumber:"); scanf("%d",&G.arcnum); for(i = 0;i < G.vertex;i++) for(j = 0;j < G.vertex;j++) { scanf("%d",&tempWeight); G.edages[i][j] = (tempWeight == -1)?INFINITY : tempWeight; } return G; } void Prim_MiniGenerateTree(Graphics G){ int min,i,j,k; int adjvex[MAX_VERTEX];//保存相关顶点下标 int lowcost[MAX_VERTEX];//保存相关顶点间边的权值 lowcost[0] = 0;//V0作为最小生成树的根开始遍历,权值为0 adjvex[0] = 0;//V0第一个加入 //初始化操作 for(i = 1; i < G.vertex;++i) { lowcost[i] = G.edages[0][i];//将邻接矩阵第0行所有权值先加入数组 adjvex[i] = 0;//初始化全部先为V0的下标 } //真正构造最小生成树的过程 for(i = 1; i < G.vertex;++i) { min = INFINITY;//初始化最小权值为INFINITY j = 1; k = 0; //遍历全部顶点 while(j < G.vertex) { //找出lowcost数组已存储的最小权值 if (lowcost[j] != 0 && lowcost[j] < min) { min = lowcost[j]; k = j;//将发现的最小权值的下标存入k,以待使用 } j++; } //打印当前顶点边中权值最小的边 printf("边(%d,%d)\n", adjvex[k],k); //将当前顶点的权值设置为0,表示此顶点已经完成任务,进行下一个顶点的遍历 lowcost[k] = 0; //邻接矩阵k行逐个遍历全部顶点 for(j = 1;j < G.vertex;j++){ if (lowcost[j] != 0 && G.edages[k][j] < lowcost[j]) { lowcost[j] = G.edages[k][j]; adjvex[j] = k; } } } } #endif
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #include <ctype.h> #include <string.h> typedef struct Pessoa cel; struct Pessoa{ cel *prox; cel *anterior; int idade; char nome[30]; float altura; float peso; }; struct No{ int chave; int tamanho; cel *head; struct No *direita; struct No *esquerda; struct No *pai; }; struct Arvore{ int tamanho; struct No *raiz; }; void AdcNo(struct Arvore *arvore, int chave); struct No * buscaNo(struct No *raiz, int key); struct No * buscaMaiorEsquerda(struct No *raiz); struct No * buscaMenorDireita(struct No *raiz); void imprimeArvore(struct No *raiz); void RmvNo(struct Arvore *arvore, struct No *para_excluir); void AdcPessoa(struct Arvore *arvore); void RmvPessoa(struct Arvore *arvore); int stcmp(char nome[], char nome2[]); int main() { setlocale(LC_ALL,"portuguese"); struct Arvore *arvore; arvore = (struct Arvore*)calloc(1,sizeof(struct Arvore)); int loop = 0; do{ printf("1-Cadastrar: "); printf("2-Remover: "); printf("3-Imprimir registros: "); printf("4-Sair: "); printf("\nEscolha: "); scanf("%d", &loop); switch(loop) { case 1: AdcPessoa(arvore); break; case 2: RmvPessoa(arvore); break; case 3: imprimeArvore(arvore->raiz); break; } system("\npause"); system("cls"); }while(loop!=4); AdcNo(arvore, 10); AdcNo(arvore, 4); AdcNo(arvore, 6); AdcNo(arvore, 2); AdcPessoa(arvore); imprimeArvore(arvore->raiz); RmvPessoa(arvore); // AdcPessoa(arvore); imprimeArvore(arvore->raiz); //AdcPessoa(arvore); //AdcPessoa(arvore); //RmvNo(arvore, buscaNo(arvore->raiz,10 )); printf("\n"); imprimeArvore(arvore->raiz); //AdcPessoa(arvore); return 0; } void AdcNo(struct Arvore *arvore, int chave) { int acoplou=0; //variavel responsvel por parar o while quando o n for alocado struct No *aux; struct No *novo_no; novo_no = (struct No*)calloc(1, sizeof(struct No)); //alocao de memria pra um novo n novo_no->chave = chave; //o n recebe sua identificao e tamanho 0 novo_no->tamanho = 0; if(arvore->raiz == NULL) //se a raiz da arvore ainda for nula o n se torna a raiz { arvore->raiz = novo_no; arvore->tamanho++; } else{ aux = arvore->raiz; //aux recebe a raiz da arvore e ser incrementado aos prximos endereos at que chegue a folha while(acoplou==0) { if(novo_no->chave > aux->chave) //lgica da arvore, indice maior vai para a direita { if(aux->direita == NULL) //se a direita for nula, o novo n se torna filho da direita, seno... { aux->direita = novo_no; novo_no->pai = aux; acoplou = 1; }else aux = aux->direita; //aux se torna o elemento a sua direita e retorna ao inicio do while } else if(novo_no->chave < aux->chave) //mesma lgica aplicada acima, porm para o lado esquerdo { if(aux->esquerda == NULL) { aux->esquerda = novo_no; novo_no->pai = aux; acoplou = 1; }else aux = aux->esquerda; } } arvore->tamanho++; } } struct No * buscaNo(struct No *raiz, int key) //busca um c para descobrir se existe, ser removido ou acessar sua lista { if(raiz == NULL) //caso chegue ao fim da arvore e no encontre retorna null; return NULL; if(raiz->chave == key) //caso encontra retorna o endereo da varivel return raiz; else{ if(key > raiz->chave) //se o nmero buscado for maior que o atual, direciona a busca pra direita, seno... buscaNo(raiz->direita, key); else buscaNo(raiz->esquerda, key); //direciona a busca para a esquerda } } void RmvNo(struct Arvore *arvore, struct No *para_excluir) { struct No *pai; struct No *substituto; pai = para_excluir->pai; if(para_excluir->direita == NULL && para_excluir->esquerda == NULL) //verifica se o n a ser excludo folha { if(pai->chave < para_excluir->chave) //caso o n seja folha, remove e retorna pai->direita = NULL; else pai->esquerda = NULL; free(para_excluir); arvore->tamanho--; return; } if(para_excluir->direita != NULL) { substituto = buscaMenorDireita(para_excluir); if(substituto->direita != NULL) { substituto->pai->esquerda = substituto->direita; substituto->direita->pai = substituto->pai; }else substituto->pai->esquerda = NULL; } else{ substituto = buscaMaiorEsquerda(para_excluir); if(substituto->esquerda != NULL) { substituto->pai->direita = substituto->esquerda; substituto->esquerda->pai = substituto->pai; }else substituto->pai->direita = NULL; } if(para_excluir == arvore->raiz) { substituto->pai = NULL; arvore->raiz = substituto; }else{ substituto->pai = para_excluir->pai; if(para_excluir->pai->direita == para_excluir) para_excluir->pai->direita = substituto; else para_excluir->pai->esquerda = substituto; } if(para_excluir->esquerda != NULL && para_excluir->esquerda != substituto) { substituto->esquerda = para_excluir->esquerda; para_excluir->esquerda->pai = substituto; } if(para_excluir->direita != NULL && para_excluir->direita != substituto) { para_excluir->direita->pai = substituto; substituto->direita = para_excluir->direita; } arvore->tamanho--; free(para_excluir); } struct No * buscaMaiorEsquerda(struct No *raiz) { if(raiz->esquerda->direita == NULL) return raiz->esquerda; raiz = raiz->esquerda; while(1==1) { if(raiz->direita == NULL) return raiz; raiz = raiz->direita; } } struct No * buscaMenorDireita(struct No *raiz) { if(raiz->direita->esquerda == NULL) return raiz->direita; raiz = raiz->direita; while(1==1) { if(raiz->esquerda == NULL) return raiz; raiz = raiz->esquerda; } } void imprimeArvore(struct No *raiz) { struct Pessoa *aux; if(raiz == NULL) return; imprimeArvore(raiz->esquerda); printf("\n N:%d ", raiz->chave); aux = raiz->head; while(aux != NULL) { printf("\nIdade: %d Nome: %s Altura: %.2f Peso: %.2f", aux->idade, aux->nome, aux->altura, aux->peso); aux = aux->prox; } imprimeArvore(raiz->direita); } void AdcPessoa(struct Arvore *arvore) { struct No *lista; struct Pessoa *aux; struct Pessoa *ferramenta; aux = (struct Pessoa*)calloc(1,sizeof(struct Pessoa)); int acoplou = 0; printf("\nIdade: "); scanf("%d", &aux->idade); fflush(stdin); printf("\nNome: "); gets(aux->nome); printf("\nAltura: "); scanf("%f", &aux->altura); printf("\nPeso: "); scanf("%f", &aux->peso); lista = buscaNo(arvore->raiz, aux->idade); if(lista == NULL) { AdcNo(arvore, aux->idade); lista = buscaNo(arvore->raiz, aux->idade); } if(lista->head == NULL) lista->head = aux; else{ ferramenta = lista->head; while(acoplou==0) { if(ferramenta->prox == NULL) { ferramenta->prox = aux; aux->anterior = ferramenta; acoplou=1; lista->tamanho+=1; }else ferramenta = ferramenta->prox; } } } void RmvPessoa(struct Arvore *arvore) { struct No *galho; struct Pessoa *aux; int idade=0; char nome[30]; printf("\nIdade: "); scanf("%d",&idade); fflush(stdin); printf("\nNome: "); gets(nome); galho = buscaNo(arvore->raiz, idade); if(galho == NULL) { printf("\nO registro no existe."); return; } aux = galho->head; while(aux != NULL) { if(stcmp(aux->nome, nome)==0) { if(aux == galho->head){ galho->head = NULL; RmvNo(arvore, galho); } else{ aux->anterior->prox = aux->prox; galho->tamanho--; } free(aux); return; }else aux = aux->prox; } printf("\nRegistro no encontrado."); } int stcmp(char nome[], char nome2[]) { int i=0; while(nome[i] != '\0') { toupper(nome[i]); i++; } i=0; while(nome2[i] != '\0') { toupper(nome2[i]); i++; } return (stricmp(nome, nome2)== 0)? 0: 1; }
C
/* ---------------------------------------------------------------------------- * args.c --- Argument parsing utilities * nca-073-9 * * Copyright (c) 1996-2000 by Netcetera AG. * Copyright (c) 2001 by Apache Software Foundation. * All rights reserved. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES. * * @(#) $Id: args.c 506449 2007-02-12 14:02:27Z ronnie $ * ------------------------------------------------------------------------- */ #include <tcl.h> #include "args.h" #include <ctype.h> #include <stdio.h> /* argdbg */ #include <string.h> /* strcmp */ /* -- doc --------------------------------------------------------------------- * argIndexOfKey -- given an array of arguments, return index of arg matching key * 1: array of pointers to Tcl Objects serving as arguments * 2: number of elements in \1 * 3: key to search for * R: 0..objc-1 or -1 in case of error * ------------------------------------------------------------------------- */ int argIndexOfKey(int objc, Tcl_Obj * CONST objv[], char *key) { int pos = 1; if ((objv != NULL) && (key != NULL)) { while (pos < objc) { if (objv[pos] != NULL) { switch (argOptionType(objv[pos])) { case OPTION_TYPE_DASHDASH: return -1; break; case OPTION_TYPE_PARAM: if (strcmp(Tcl_GetString(objv[pos]), key) == 0) return pos; break; default: break; } } pos++; } } return -1; } /* -- doc --------------------------------------------------------------------- * optionType -- determine option type (NONE,PARAM,DASHDASH,NUMBER) * ------------------------------------------------------------------------- */ int argOptionType(Tcl_Obj * in) { char *tmp = NULL; int tmpLen = -1; if (in == NULL) return 0; tmp = Tcl_GetStringFromObj(in, &tmpLen); if (tmp[0] == '-') { if (tmpLen > 1) { if (tmp[1] != '-') { if (isdigit((int)tmp[1])) return OPTION_TYPE_NUMBER; return OPTION_TYPE_PARAM; } else { if ((tmp[1] == '-') && (tmpLen == 2)) return OPTION_TYPE_DASHDASH; } } } return OPTION_TYPE_NONE; } /* -- doc --------------------------------------------------------------------- * argIndexOfNextKey -- search for next argument with "-" * returns index to next Key in objv, or objc * ------------------------------------------------------------------------- */ int argIndexOfNextKey(int objc, Tcl_Obj * CONST objv[], int previous) { int pos = 0; for (pos = (previous + 1); pos < objc; pos++) { if (objv[pos] != NULL) { switch (argOptionType(objv[pos])) { case OPTION_TYPE_PARAM: return pos; break; case OPTION_TYPE_DASHDASH: return objc; break; default: break; } } } return objc; } /* -- doc --------------------------------------------------------------------- * argPosParam -- scan params to find key * returns index to **params, if key is found, or -1 * ------------------------------------------------------------------------- */ int argPosParam(TCLCONST char *params[], char *key) { char **intParams; int pos = 0; intParams = (char **) params; if ((key == NULL) || (params == NULL)) return -1; while (*intParams != NULL) { if (strcmp(*intParams, key) == 0) return pos; pos++; intParams++; } return -1; } /* -- doc --------------------------------------------------------------------- * indexOfFirstOpt -- * ------------------------------------------------------------------------- */ int argIndexOfFirstOpt(int objc, Tcl_Obj * CONST objv[]) { int pos = 1; if (objc < 2) return -1; if (objv == NULL) return -1; while (pos < objc) { if (objv[pos] != NULL) { switch (argOptionType(objv[pos])) { case OPTION_TYPE_PARAM: return pos; break; case OPTION_TYPE_DASHDASH: /* found "--" before any other option * --> first arg is i + 1, and no options to be expected */ return -1; break; default: /* continue search */ break; } } pos++; } return -1; } /* -- doc --------------------------------------------------------------------- * indexOfFirstArg -- for array of args, return index of first arg, * skipping params * 1: number of elements in \2 * 2: array of pointers to Tcl Objects serving as arguments * R: 1..objc-1 or objc if only switches * note: assumes that first arg is command name * ------------------------------------------------------------------------- */ int argIndexOfFirstArg(int objc, Tcl_Obj * CONST objv[], TCLCONST char *params[], int *Nparams) { int pos = -1; int first = -1; int pidx = 0; if (objc < 2) return objc; if (objv == NULL) return objc; if (argOptionType(objv[1]) == OPTION_TYPE_NONE) return 1; first = argIndexOfFirstOpt(objc, objv); /* -------------------------------------------------------------------------- * no switches * ----------------------------------------------------------------------- */ if (first == -1) first = 1; /* -------------------------------------------------------------------------- * scan to the last param * ----------------------------------------------------------------------- */ pos = first; while (pos < objc) { if (objv[pos] != NULL) { switch (argOptionType(objv[pos])) { case OPTION_TYPE_NONE: /* we found the fisrt argument */ return pos; case OPTION_TYPE_DASHDASH: /* first arg is i + 1, and no more options to be expected */ pos++; return pos; break; case OPTION_TYPE_PARAM: /* switch: i ==> -unbuffered --> first arg is i + 1 + 0 * simple param: i ==> -format "$m" --> first arg is i + 1 + 1 * param: i ==> -postdata a b c --> first arg is i + 1 + 3 */ if ((pidx = argPosParam(params, Tcl_GetString(objv[pos]))) != -1) { if (Nparams != NULL) pos += Nparams[pidx]; else pos++; } pos++; break; default: pos++; break; } } } /* ---------------------------------------------------------------------- * no args (switches only) * ------------------------------------------------------------------- */ return objc; } /* ---------------------------------------------------------------------------- * argKeyExists -- check if one element of array of arguments matches key * 1: array of pointers to Tcl Objects serving as arguments * 2: number of elements in \1 * 3: key to search for * R: TCL_OK if found, TCL_ERROR else * ------------------------------------------------------------------------- */ int argKeyExists(int objc, Tcl_Obj * CONST objv[], char *key) { if (argIndexOfKey(objc, objv, key) == -1) { return TCL_ERROR; } return TCL_OK; } /* ---------------------------------------------------------------------------- * argValueOfKey -- returns next arg after key as value * 2: array of pointers to Tcl Objects serving as arguments * 1: number of elements in \2 * 3: key to search for * R: Tcl_Obj* if found, else NULL * ------------------------------------------------------------------------- */ Tcl_Obj *argValueOfKey(int objc, Tcl_Obj * CONST objv[], char *key) { int pos = 0; if ((objv != NULL) && (key != NULL)) { pos = argIndexOfKey(objc, objv, key); if ((pos != -1) && (pos < (objc - 1))) { return objv[pos + 1]; } } return NULL; } /* ---------------------------------------------------------------------------- * argHasOnlyAccepted -- checks if all options are known * (from 1 to min(objc,scanc)). If scanc == -1, scan up to objc. * returns 0 if ok, index of argument which is unknown, if found * ------------------------------------------------------------------------- */ int argHasOnlyAccepted(int objc, Tcl_Obj * CONST objv[], TCLCONST char *params[], int scanc) { int i; char *tmp = NULL; if (scanc < 0) scanc = objc; if (scanc > objc) scanc = objc; for (i = 1; i < scanc; i++) { if (objv[i] != NULL) { /* fprintf(stdout,"DBG argHasOnlyAccepted: '%s'\n",Tcl_GetString(objv[i])); fflush(stdout); */ switch (argOptionType(objv[i])) { case OPTION_TYPE_PARAM: tmp = Tcl_GetString(objv[i]); if (argPosParam(params, tmp) == -1) return i; break; case OPTION_TYPE_DASHDASH: return 0; break; default: break; } } } return 0; } /* -- doc --------------------------------------------------------------------- * argdbg - write args to file handle for debugging * ------------------------------------------------------------------------- */ void argdbg(int objc, Tcl_Obj * CONST objv[], FILE * fh) { int i = 0; for (i = 0; i < objc; i++) { if (objv[i] == NULL) { fprintf(fh, "DBG arg %d -> 'null'\n", i); } else { fprintf(fh, "DBG arg %d -> '%s'\n", i, Tcl_GetString(objv[i])); } } fflush(fh); }
C
#ifndef BRANCH_H #define BRANCH_H #include "sale.h" #include "auxStructs.h" /** * \brief Structure that stores all relations between the clients and products of a branch. * * It uses two hash tables to store information, one matches a product to all the clients who bought it, and the other matches a client to all the products they bought. */ typedef struct branch* Branch; /** * \brief Structure used to store information about a client, in relation to a product that they bought. * * More specifically, it stores how many units of a product that client bought, divided by month and by mode, i.e., whether the product was bought at a discount or not. */ typedef struct clientInfo* ClientInfo; /** * \brief Structure used to store information about a product, in relation to a client who bought it. * * More specifically, it stores how many units of that product were bought by a client, divided by month, and how much money was spent on that product by a client. */ typedef struct productInfo* ProductInfo; Branch initBranch(); void addToBranch(Branch branch, Sale sale); void destroyBranch(Branch branch); void destroyClientInfo(void* object); void destroyProductInfo(void* object); int* getTotalQuantByClient(Branch branch, char* clientID); void fillQuantTableOfProdsByClient(Branch branch, char* clientID, int month, GHashTable* quantTable); void fillQuantTableOfProds(Branch branch, GHashTable* quantTable); StringArray getClientsWhoBoughtProduct(Branch branch, char * prodID, int np); void fillTableWithProducts(Branch branch, char *clientID , GHashTable* moneySpentOnProducts); void fillTopSelledTable(Branch branch, int branchNum, GHashTable* quantTable); #endif
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX_SIZE 100 #define LEN 10 #define MALLOC(p,s)\ if( !((p) = malloc(s)) ){\ printf("malloc fail");\ exit(1);\ } typedef struct { char item[LEN]; int key; }element; typedef struct node* nodePointer; typedef struct node { element data; nodePointer link; }Node; typedef struct { nodePointer link; }HT; int cnt, b = 11; nodePointer list[MAX_SIZE]; HT ht[11] = { NULL}; int h(int k); void insertht(nodePointer x); int stringToInt(char* item); nodePointer createNode(char item[]); void printList(int i); element* search(int k); int main() { FILE* fp; char data[MAX_SIZE][LEN]; int i, k, size; char find[LEN]; element* result = NULL; size = 0; fopen_s(&fp, "input.txt", "r"); if (fp == NULL) { exit(1); } printf(" input strings : "); while (!feof(fp)) { fscanf_s(fp, "%s ", data[size++],LEN); printf("%s ", data[size - 1]); } printf("\n"); for (i = 0; i < size; i++) list[i] = createNode(data[i]); for (i = 0; i < size; i++) insertht(list[i]); printf("\n item key\n"); for (i = 0; i < b; i++) { printf("ht[%2d] :", i); printList(i); } printf("\n"); while (1) { printf("input \"quit\" to quit\n"); printf("string to search >> "); scanf_s("%s", find, LEN); if (!strcmp(find, "quit")) break; k = stringToInt(find); result = search(k); if (!result) printf("it doesn't exist\n\n"); else printf("item : %s, key : %d, the number of comparison : %d\n\n", result->item, result->key, cnt); } fclose(fp); return 0; } int h(int k) { return k % b; } nodePointer createNode(char item[]) { nodePointer temp; MALLOC(temp, sizeof(*temp)); strcpy_s(temp->data.item, LEN,item); temp->data.key = stringToInt(item); temp->link = NULL; return temp; } int stringToInt(char* item) { int num = 0; while (*item) num += *item++; return num; } void insertht(nodePointer x) { nodePointer temp; int index = h(x->data.key); if (!ht[index].link) ht[index].link = x; else { for (temp = ht[index].link; temp; temp = temp->link) { if (!temp->link) { temp->link = x; break; } } } } void printList(int i) { nodePointer temp; if (!ht[i].link) printf("\n"); else { for (temp = ht[i].link; temp; temp = temp->link) printf(" (%s %d)", temp->data.item, temp->data.key); printf("\n"); } } element* search(int k) { nodePointer current; cnt = 1; current = ht[h(k)].link; for (; current; current = current->link) { if (current->data.key == k) return &current->data; cnt++; } return NULL; }
C
/* ** EPITECH PROJECT, 2019 ** get_str.c ** File description: ** read with getline from a fd */ #include "my.h" char *get_str(int fd, int n) { char *buffer = NULL; size_t size = 0; char *res = my_strdup("", KEEP); FILE *pipfd = get_pipe_fd(fd); if (n == -1) return (NULL); while ((n = getline(&buffer, &size, pipfd) != -1)) { buffer[my_strlen(buffer) - 1] = ' '; res = my_strcat(res, buffer, KEEP, KEEP); } fclose(pipfd); return (res); }
C
#include <stdio.h> #include <stdlib.h> void sort(int vet[], int m){//Metodo de ordenamento Descrence bouble sort int i = 0, j =0; int max = 0; int flag = 0; for(i=0;i<m;i++){ max = vet[i];//Considera este sendo o possivel maior numero for (j=0;j<m;j++){ if (vet[j]< max){ vet[i] = vet[j]; vet[j] = max; max = vet[i]; } } } } int diferenca(int vet[], int flag[],int m){ //Analisa a diferenca entre os vetores int i=0,j=0,contador=0; //Verifica se os mesmo indices tem os mesmo valores for (i=0; i<m; i++) //Caso nao, incrementa 1 no contador if(flag[i] == vet[i]) contador++; return contador; } int main(int argc, char* argv[]){ int n = 0,m = 0, i = 0,j = 0; int *resultados; int *v; int *flag; scanf("%i",&n);//Recebendo o numero de casos a serem executado resultados = (int*) malloc(n*sizeof(int));//Alocando memoria para o vetor de resultados for(i=0;i<n;i++){ scanf("%i",&m); //Recebendo o numero de alunos na fila v = (int*) malloc (m*sizeof(int));//Alocando memoria dinamicamente para os vetores flag = (int*) malloc (m*sizeof(int)); for (j=0;j<m;j++){ v[j] = 0; flag[j] = 0; scanf("%d",&v[j]); //Recebendo os valores flag[j]= v[j];//Atribuindo valor a um vetor de flag } sort(v,m);//Ordenando vetor resultados[i] = diferenca(v,flag,m);//Analisando a diferenca entre os veotres m=0; free(v); free(flag); } for(i=0;i<n;i++){//Imprimindo o resultado de todos os casos printf("%i\n",resultados[i]); } free(resultados);//Desalocando memoria do vetor return 0; } /* * URI Online Judge | 1548 * Fila do Recreio * Por Cristhian Bonilha, UTFPR BR Brazil * * Timelimit: 1 * * Na escola onde você estuda, a hora do recreio é a mais aguardada pela * grande maioria dos alunos. Não só porque as vezes as aulas são cansativas, * mas sim porque a merenda servida é muito boa, preparada por um chefe italiano * muito caprichoso. * * Quando bate o sinal para a hora do recreio, todos os alunos saem correndo da sua sala * para chegar o mais cedo possível na cantina, tanta é a vontade de comer. * Um de seus professores notou, porém, que havia ali uma oportunidade. * * Utilizando um sistema de recompensa, seu professor de matemática disse que a ordem * da fila para se servir será dada não pela ordem de chegada, mas sim pela soma das * notas obtidas em sala de aula. Assim, aqueles com maior nota poderão se servir antes * daqueles que tem menor nota. * * Sua tarefa é simples: dada a ordem de chegada dos alunos na cantina, e * as suas respectivas notas na matéria de matemática, reordene a fila de acordo * com as notas de matemática, e diga quantos alunos não precisaram trocar de lugar * nessa reordenação. * * Entrada * * A primeira linha contém um inteiro N, indicando o número de casos de teste a seguir. * * Cada caso de teste inicia com um inteiro M (1 ≤ M ≤ 1000), indicando o * número de alunos. Em seguida haverá M inteiros distintos Pi (1 ≤ Pi ≤ 1000), * onde o i-ésimo inteiro indica a nota do i-ésimo aluno. * * Os inteiros acima são dados em ordem de chegada, ou seja, o primeiro * inteiro diz respeito ao primeiro aluno a chegar na fila, o segundo inteiro diz * respeito ao segundo aluno, e assim sucessivamente. * * Saída * * Para cada caso de teste imprima uma linha, contendo um inteiro, * indicando o número de alunos que não precisaram trocar de lugar mesmo * após a fila ser reordenada. * * Exemplo de Entrada * * 3 * 3 * 100 80 90 * 4 * 100 120 30 50 * 4 * 100 90 30 25 * * Exemplo de Saída * * 1 * 0 * 4 * */
C
#include <stdio.h> int main(void) { int score; printf("Enter your score : "); scanf("%d", &score); //int a = 60; //printf("%d\n", score >= a); int isPassed; isPassed = (score >= 60); printf("score %d is passed? %d\n", score, isPassed); return 0; }