language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<sys/select.h> #include<signal.h> #include<sys/stat.h> #include<stdio.h> #include<sys/ipc.h> #include<sys/types.h> #include <unistd.h> #include <fcntl.h> #include<stdlib.h> #include<sys/shm.h> #include <sys/poll.h> #include <sys/time.h> #define MAX 9 int shmid,shmid1; int *no; int *grp; int prc=0,gp=0; int csfd[MAX][MAX]; int scfd[MAX][MAX]; char myfifo1[12]="ctos_fifo1"; char myfifo2[12]="stoc_fifo1"; int max(int a,int b) { if(a>b)return a; return b; } void fun2() { printf("entered....\n"); gp=grp[0]; prc=no[gp]; printf("%d %d\n",gp,prc); myfifo1[9]=(char)gp+'0'; myfifo1[10]=(char)prc+'0'; myfifo1[11]='\0'; myfifo2[9]=(char)gp+'0'; myfifo2[10]=(char)prc+'0'; myfifo2[11]='\0'; printf("%s\n%s\n",myfifo1,myfifo2); csfd[gp][prc]= open(myfifo1, O_RDWR); scfd[gp][prc]= open(myfifo2, O_RDWR); printf("pipe %d%d created\n",gp,prc); signal(SIGUSR1,fun2); } void fun1() { char str[500]; int i,j,k; printf("cant reach there\n"); struct pollfd rpfds[MAX*MAX]; printf("done till here\n"); while (1) { int sum=0,id; j=0; for(i=0;i<2;i++) { prc=no[i+1]; for(j=0;j<prc;j++) { rpfds[sum+j].fd=csfd[i+1][j+1]; rpfds[sum+j].events=POLLIN; } sum+=prc; } int n; if((n =poll(rpfds,sum,500)) > 0) { sum=0; for(i=0;i<2;i++) { prc=no[i+1]; for(j=0;j<prc;j++) { if(rpfds[sum+j].revents & POLLIN) { int n = read(csfd[i+1][j+1],str,sizeof(str)); str[n]='\0'; printf("SERVER: %d bytes message from CLIENT %d%d : %s \n",n,i+1,j+1,str); for(k=0;k<prc;k++) { if(j!=k) { write(scfd[i+1][k+1],str,sizeof(str)); } } } rpfds[sum+j].events=POLLIN; rpfds[sum+j].revents=0; } sum+=prc; } } } } int main() { signal(SIGUSR1,fun2); int i,j; if((shmid=shmget(2276,9*sizeof(int),IPC_CREAT|0666))==-1) { perror("shmget1 error\n"); exit(0); } no=(int *)shmat(shmid,NULL,0); no[1]=0; no[2]=0; no[0]=getpid(); if((shmid1=shmget(2274,sizeof(int),IPC_CREAT|0666))==-1) { perror("shmget2 error\n"); exit(0); } grp=(int *)shmat(shmid1,NULL,0); grp[0]=0; for(j=1;j<=2;j++) { myfifo1[9]=(char)j+'0'; myfifo2[9]=(char)j+'0'; prc=no[j]; for(i=1;i<=prc;i++) { myfifo1[10]=(char)i+'0'; myfifo1[11]='\0'; myfifo2[10]=(char)i+'0'; myfifo2[11]='\0'; mkfifo(myfifo1,0666); mkfifo(myfifo2,0666); csfd[j][i]= open(myfifo1, O_RDWR); scfd[j][i]= open(myfifo2, O_RDWR); printf("pipe%d created\n",i); } } printf("SERVER STARTED\n"); fun1(); for(j=1;j<=2;j++) { prc=no[j]; myfifo1[9]=(char)j+'0'; myfifo2[9]=(char)j+'0'; for(i=1;i<=prc;i++) { close(csfd[j][i]); close(scfd[j][i]); myfifo1[10]=i+'0'; myfifo1[11]='\0'; myfifo2[10]=i+'0'; myfifo2[11]='\0'; unlink(myfifo1); unlink(myfifo2); } } return 0; }
C
//verifie si un domnaine est syntaxiquement correcte // retourne 1 si correcte et 0 sinon int check(char *domaine) ; //argv représente le tableau des paramères du programme //cette fonction retourne la taille de la liste de domaine à partir argv[pos] //la fin la liste est localisée soit par la fin du tableau d'argument soit par une option connue int get_nbre_domaines(char *const argv[], int pos); //retourne 1 si la syntaxe de domaine est correcte et place le début et la fin du domaine dans debut et fin //retourne 0 si la syntaxe de domaine est incorrecte //max est utilisé pour que <nun>- represente le domaine <num>-max int get_debut(char * domaine, int *debut); int get_fin(char * domaine, int *fin);
C
#include <sys/socket.h> #include <arpa/inet.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <malloc.h> #include <signal.h> #include <stdlib.h> #include <pthread.h> #define QS_MSGLEN 256 int sfd; char *buf; void finish(int sig) { close(sfd); free(buf); exit(0); } int main() { sigset_t sigmask; sigfillset(&sigmask); struct sigaction act; act.sa_mask = sigmask; act.sa_flags = SA_RESTART; act.sa_handler = &finish; sigaction(SIGINT, &act, NULL); struct sockaddr_in sockaddr; buf = malloc(QS_MSGLEN); sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); int bro = 1; setsockopt(sfd, SOL_SOCKET, SO_BROADCAST, &bro, sizeof(int)); sockaddr.sin_family = AF_INET; sockaddr.sin_port = htons(3110); inet_aton("224.0.0.1", &sockaddr.sin_addr); while(1) { socklen_t addrlen = sizeof(sockaddr); scanf(" %[^\n]s", buf); sendto(sfd, buf, QS_MSGLEN, 0, (struct sockaddr*)&sockaddr, sizeof(struct sockaddr)); } }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; void insertAtTheBegin(struct node **head_ref, int data); void bubbleSort(struct node *head); void swap(struct node *a, struct node *b); void print(struct node *head); void insertAtTheBegin(struct node **head_ref, int data) { struct node *ptr1 = (struct node*)malloc(sizeof(struct node)); ptr1->data = data; ptr1->next = *head_ref; *head_ref = ptr1; } void print(struct node *head) { struct node *temp = head; printf("\n"); while (temp!=NULL) { printf("%d ", temp->data); temp = temp->next; } } void bubbleSort(struct node *head) { int swapped, i; struct node *ptr1; struct node *lptr = NULL; if (ptr1 == NULL) return; do { swapped = 0; ptr1 = head; while (ptr1->next != lptr) { if (ptr1->data > ptr1->next->data) { swap(ptr1, ptr1->next); swapped = 1; } ptr1 = ptr1->next; } lptr = ptr1; } while (swapped); } void swap(struct node *a, struct node *b) { int temp = a->data; a->data = b->data; b->data = temp; } int main() { int arr[] = {3, 5, 2, 71, 1, -2, 40}; struct node *head = NULL; for (int i = 0; i< 6; i++) insertAtTheBegin(&head, arr[i]); printf("\n Linked list before sorting "); print(head); bubbleSort(head); printf("\n Linked list after sorting "); print(head); return 0; }
C
#include <gb/gb.h> #include <gb/drawing.h> #include <stdio.h> void main(){ // start screen (press start to continue) gotogxy(3,8); // set text start position gprintf("Press Start..."); waitpad(J_START); // wait for start gotogxy(3,8); // reset text start position gprintf(" "); // clear message // display message to screen gotogxy(3,8); // set text start position gprintf("Hello World!"); // print message }
C
#include <REGX52.H> #include "Delay.h" /** * @brief 矩阵键盘读取按键键码 * @param 无 * @retval KeyNumber 按下按键的键码值 如果按键按下不放,程序会停留在此函数,松手的一瞬间,返回按键键码,没有按键按下时,返回0 */ unsigned char MatrixKey() { unsigned char KeyNumber=0; P1=0xFF; P1_3=0; if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=1;} if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=5;} if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=9;} if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=13;} P1=0xFF; P1_2=0; if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=2;} if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=6;} if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=10;} if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=14;} P1=0xFF; P1_1=0; if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=3;} if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=7;} if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=11;} if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=15;} P1=0xFF; P1_0=0; if(P1_7==0){Delay(20);while(P1_7==0);Delay(20);KeyNumber=4;} if(P1_6==0){Delay(20);while(P1_6==0);Delay(20);KeyNumber=8;} if(P1_5==0){Delay(20);while(P1_5==0);Delay(20);KeyNumber=12;} if(P1_4==0){Delay(20);while(P1_4==0);Delay(20);KeyNumber=16;} return KeyNumber; }
C
/* Enter your solutions in this file */ #include <stdio.h> int max(int a[],int b ) { int max_now= a[0]; for(int i=0;i<b ;i++) { if ( a[i]>max_now) { max_now= a[i]; } } return max_now; } int min(int c[],int d) { int min_now= c[0]; for(int i=0;i<d ;i++) { if ( c[i]<min_now) { min_now= c[i]; } } return min_now; } float average(int e[], int f) { int sum=0; int i; for (i=0;i<f;i++) { sum+=e[i]; } float average = sum/f; return average; } int mode(int g[],int h) { int t[]= {0,1,2,3,4,5,6,7,8,9,10,11}; for (int k=0;k<12;k++) { int s= 0 ; for(int i=0;i<h;i++) { if(g[i]==t[k]) { s+=1; } } t[k]=s; } int max1=t[0]; int u ; for (int i=1;i<12;i++) { if (t[i]>max1) { max1=t[i]; u=i; } } return u; } int factors(int n, int x[]) { int t =0 ; int k=n; for(int i=2; i<n; i++) { if (k%i==0) { k=k/i; x[t]=i; t++; i=1; } } return t; }
C
/* ** list.c for in /home/simoni_w/projet/teck2/Ftrace/Ftrace ** ** Made by ** Login <[email protected]> ** ** Started on Sat Jun 29 16:53:18 2013 ** Last update Sat Jun 29 16:53:18 2013 */ #include "stack.h" t_head *stack_init() { t_head *stack; stack = malloc(sizeof(t_head)); stack->size = 0; stack->head = NULL; stack->tail = NULL; return stack; } void stack_add(t_head *stack, _ADDR addr) { t_stack *e; e = malloc(sizeof(t_stack)); e->addr = addr; if (stack->size == 0) { stack->size = 1; stack->head = e; stack->tail = e; e->next = NULL; } else { stack->size++; e->next = stack->head; stack->head = e; } } void stack_pop(t_head *stack) { t_stack *save; if (stack->size == 0) return; save = stack->head; if (stack->size == 1) { free(save); stack->head = NULL; stack->tail = NULL; } else { stack->head = stack->head->next; free(save); } stack->size--; } _ADDR stack_get_first(t_head *stack) { if (stack == NULL || stack->head == NULL) return NULL; return stack->head->addr; }
C
#include <stdio.h> int main() { int a = 10, b = 20; if(a <= b) { printf("Hello World!"); } printf("This line will always be printed\n"); return 0; }
C
#include <stdio.h> #include <string.h> #include <errno.h> #include <pthread.h> #include <stdlib.h> #include <signal.h> int quitflags; sigset_t mask; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static void *thr_fn(void *arg) { int err, signo; for( ; ; ){ err = sigwait(&mask, &signo);// sigwait在mask的信号屏蔽字条件下阻塞等待信号到来 if(err != 0){ perror("sigwait error"); return (void *)-1; } switch(signo){ case SIGINT: printf("\ninterrupt\n"); break; case SIGQUIT: printf("\nsigquit\n"); pthread_mutex_lock(&mutex); quitflags = 1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); return((void*)0); default: printf("unexpected signal %d\n", signo); exit(1); } } return((void *)1); } int main(int argc, char const *argv[]) { int err; sigset_t old_mask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &old_mask)) != 0){ perror("pthread_sigmask error"); return -1; } if((err = pthread_create(&tid, NULL, thr_fn, 0)) != 0){ perror("pthread_create error"); return -1; } pthread_mutex_lock(&mutex); while(quitflags==0) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); quitflags = 0; if(sigprocmask(SIG_SETMASK, &old_mask, NULL) != 0){ perror("sigprocmask error"); return -1; } return 0; } /* 1:程序描述了在多线程中使用信号处理的典型例子,思路就是: 1.1 先在主进程中屏蔽关注的信号 2.2 利用线程继承进程的屏蔽集特点创建线程,在线程中调用sigwait函数等待被阻塞的信号 2:API描述(在多线程的程序中尽量使用多线程信号相关API) 2.1: int pthread_sigmask(int how, const sigset_t *set, sigset_t *oldset); 函数类似进程中的sigprocmask,指定对set描述集的动作,how的取值有:SIG_BLOCK, SIG_SETMASK, SIG_UNBLOCK 2.2: int sigwait(const sigset_t *set, int *signop); 调用此函数前应该阻塞线程等待的那些信号,函数会执行以下步骤: A:原子的取消信号集的阻塞状态,直到有新的信号被递送 B:返回之前将恢复信号集 注:在线程中使用signal或者sigaction会使得除本线程外的所有其他线程也具有相同的信号处理方式,所以在多线程中最好使用sigwait函数来保证 某信号的处理方式仅仅在本线程中有效 2.3: int pthread_kill(pthread_t thread, int signo); 替代kill函数,kill函数是对进程发送信号,在多线程环境下导致所有线程都收到该信号 st@ubuntu:~/git_project/APUE/ch12_ThreadsControl$ ./a.out ^C interrupt ^C interrupt ^C interrupt ^C interrupt ^\ sigquit st@ubuntu:~/git_project/APUE/ch12_ThreadsControl$ */
C
//Program to convert the binary number to decimal number #include<stdio.h> #include<math.h> int main() { long int a,d=0; int r,i=0; printf("Enter the binary number : "); scanf("%d",&a); while(a>0) { r=a%10; if(r!=0&&r!=1) { printf("\nWrong Input\nBinary number should consist only 0 and 1."); return 0; } a=a/10; d=d+r*pow(2,i); i++; } printf("\nThe decimal number is : %d",d); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <linux/sched.h> #include "main.h" #define PAGE_MAP_MASK 0x0000FF8000000000 #define PDPT_MASK 0x0000007FC0000000 #define PDE_MASK 0x000000003FE00000 #define PTE_MASK 0x00000000001FF000 #define PAGE_OFF_MASK 0x0000000000000FFF void test_masks() { // 1111 1111 1111 1111 // 1111 1111 1-111 1111 10-00 0001 110-0 0000 1110 1011 0101 1000 unsigned long long vaddr = 0xffff88007c988358; unsigned int pgt_offset = (vaddr & PAGE_MAP_MASK) >> 39; printf("pgt_offset: %x\n", pgt_offset); unsigned int pdpt_offset = (vaddr & PDPT_MASK) >> 30; printf("pdpt_offset: %x\n", pdpt_offset); unsigned int pde_offset = (vaddr & PDE_MASK) >> 21; printf("pde_offset: %x\n", pde_offset); unsigned int pte_offset = (vaddr & PTE_MASK) >> 12; printf("pte_offset: %x\n", pte_offset); unsigned int page_offset = vaddr & PAGE_OFF_MASK; printf("page_off: %x\n", page_offset); } void test_bit_shift() { unsigned long long y = 0x9678200000000000; printf("x: %llx\n", y); int byte; while ((byte = (y & 0xFF)) == 0) { y = y >> 8; printf("byte: %x, x: %llx\n", byte, y); } printf("byte: %x, x: %llx\n", byte, y); } unsigned long long to_little_endian(unsigned long long x) { unsigned long long y = ( ((x >> 56) & 0x00000000000000ff) | ((x >> 40) & 0x000000000000ff00) | ((x >> 24) & 0x0000000000ff0000) | ((x >> 8) & 0x00000000ff000000) | ((x << 8) & 0x000000ff00000000) | ((x << 24) & 0x0000ff0000000000) | ((x << 40) & 0x00ff000000000000) | ((x << 56) & 0xff00000000000000) ); int byte; while (y != 0 && (byte = (y & 0xFF)) == 0) { y = y >> 8; } return y; } void test_little_endian() { unsigned long long x = 0x12345678; unsigned long long y = to_little_endian(x); printf("x: %llx\ny: %llx\n", x, y); } int main(void) { test_masks(); // printf("%d\n", sizeof(struct list_head)); }
C
#include <stdio.h> int main() { long long int a, b; scanf("%lld %lld", &a, &b); printf("%lld\n", a+b); printf("%lld\n", a-b); printf("%lld\n", a*b); printf("%lld\n", a/b); printf("%lld\n", a%b); printf("%.2lf\n", (float)a / (float)b); }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> /* This program reads a string input from a file "badfile" and copys that string into a buffer size 517 then into another buffer thats only size 18. This overflow vulnerability can be easily exploited by the user. Our goal is to create the file "badfile" so that we can inject code and gain a root access shell. compile: gcc -o stack -z execstack -fno-stack-protector stack.c -z execstack defines that the program stack is executable. Must be set as linux does not allow by default -fno-stack-protector removes the stack boundary protection */ int bof(char* str){ char buffer[18]; printf("Buffer base address: %p\n", &buffer); strcpy(buffer,str); //Buffer Overflow Vulnerability return 1; } int main(int argc, char**argv){ char str[517]; FILE *badfile; badfile = fopen("badfile", "r"); fread(str, sizeof(char), 517, badfile); bof(str); printf("Returned Properly\n"); return 1; }
C
/* FILE NAME - app.c */ #include "mld.h" #include <memory.h> #include <stdlib.h> #include <stdio.h> /* EMPLOYEE STRUCTURE */ typedef struct emp_ { char emp_name[30]; unsigned int emp_id; unsigned int age; struct emp_ *mgr; float salary; } emp_t; /* STUDENT STRUCTURE */ typedef struct student_ { char stud_name[32]; unsigned int rollno; unsigned int age; float aggregate; struct student_ *best_colleague; } student_t; int main( int argc, char **argv ) { /* STEP 1 : INITIALIZE A NEW STRUCTURE DATABASE */ struct_db_t *struct_db = calloc( 1, sizeof( struct_db_t ) ); /* STORING INFORMATION OF FIELDS FOR EMPLOYEE STRUCTURE */ static field_info_t emp_fields[] = { FIELD_INFO( emp_t, emp_name, CHAR, 0 ), FIELD_INFO( emp_t, emp_id, UINT32,0 ), FIELD_INFO( emp_t, age, UINT32, 0 ), FIELD_INFO( emp_t, mgr, OBJ_PTR, emp_t ), FIELD_INFO( emp_t, salary, FLOAT, 0 ) }; /* REGISTERING EMPLOYEE STRUCTURE IN STRUCTURE DATABASE */ REG_STRUCT( struct_db, emp_t, emp_fields ); /* STORING INFORMATION OF FIELDS OF STUDENT STRUCTURE */ static field_info_t stud_fields[] = { FIELD_INFO( student_t, stud_name, CHAR, 0 ), FIELD_INFO( student_t, rollno, UINT32, 0 ), FIELD_INFO( student_t, age, UINT32, 0 ), FIELD_INFO( student_t, aggregate, FLOAT, 0), FIELD_INFO( student_t, best_colleague, OBJ_PTR, student_t) }; /* REGISTERING STUDENT STRUCTURE IN STRUCTURE DATABASE */ REG_STRUCT( struct_db, student_t, stud_fields ); /* PRINTING COMPLETE STRUCTURE DATABASE */ print_structure_db( struct_db ); /* PHASE 2 ASSIGNMENT STARTS HERE */ printf( "\n PHASE 2 ASSIGNMNET STARTS HERE \n"); struct_db_rec_t *k = struct_db_look_up ( struct_db, "emp_t" ) ; printf("%d\n", k->n_fields ); /* PHASE 2 ASSIGNMENT ENDS HERE */ /* PHASE 2 OBJECT DATABASE STARTS HERE */ /* STEP 1 : INITIALIZE A NEW OBJECT DATABASE */ object_db_t *object_db = calloc( 1, sizeof( object_db_t ) ); object_db->struct_db = struct_db; /* STEP 2 : CREATE SOME SAMPLE OBJECTS */ student_t *david = xcalloc( object_db, "student_t", 1 ); student_t *abraham = xcalloc( object_db, "student_t", 1 ); emp_t *joseph = xcalloc( object_db, "emp_t", 2 ); /* STEP 3 : PRINTING OBJECT DATABASE */ print_object_db( object_db ); /* ASSIGNMENT 3 STARTS */ strcpy( david->stud_name, "David" ); david->rollno = 12; david->age = 15; david->aggregate = 450; david->best_colleague = NULL; strcpy( joseph[0].emp_name , "Joseph" ); joseph[0].emp_id = 1221; joseph[0].age = 30; joseph[0].mgr = NULL; joseph[0].salary = 2000000; strcpy( joseph[1].emp_name , "Ismael" ); joseph[1].emp_id = 1222; joseph[1].age = 28; joseph[1].mgr = NULL; joseph[1].salary = 3000000; strcpy( abraham->stud_name, "Abraham" ); abraham->rollno = 1; abraham->age = 14; abraham->best_colleague = david; abraham->aggregate = 455; printf("\n\n\n============== ASSIGNMENT 3 STARTS ========================\n\n"); mld_dump_object_rec_detail( object_db->head ); mld_dump_object_rec_detail( object_db->head->next ); mld_dump_object_rec_detail( object_db->head->next->next ); // xfree( void *ptr ) starts here // if ( xfree( abraham, object_db ) == 1 ) printf( "\n\nObject Abraham deleted\n\n" ); else printf( "\n\nObject Abraham could not be deleted\n\n" ); mld_dump_object_rec_detail( object_db->head ); mld_dump_object_rec_detail( object_db->head->next ); if( xfree( joseph, object_db ) == 1 ) printf( "\n\nObject Joseph deleted\n\n" ); else printf( "\n\nObject Joseph could not be deleted\n\n" ); mld_dump_object_rec_detail( object_db->head ); if( xfree( david, object_db ) == 1 ) printf( "\n\nObject David deleted\n\n" ); else printf( "\n\nObject David could not be deleted\n" ); printf("\n============== ASSIGNMENT 3 ENDS ===========================\n\n\n"); /* ASSIGNMENT 3 ENDS */ return(0); }
C
/* ** EPITECH PROJECT, 2018 ** zappy ** File description: ** Client exit related functions */ #include "graphical_commands.h" #include "containers.h" #include "entity.h" #include "game.h" /// Removes a player from the list of players // `list_t *players`: the adress of the list_t *players pointer in game_t // `player_t *to_remove`: the adress of the player to be removed void player_remove(list_t **players, player_t *to_remove) { list_t *tmp = *players; player_t *pl; while (tmp) { pl = (player_t *)tmp->element; if (pl == to_remove) { pl = list_remove((*players == tmp) ? players : &tmp); player_destroy(pl); return; } tmp = tmp->next; } return; } /// Handles the disconnection of a client bool disconnect_handle(game_t *game, struct epoll_event *ev, int efd) { list_t *tmp; player_t *player; if (game->graph_stream && ev->data.fd == fileno(game->graph_stream)) { epoll_ctl(efd, EPOLL_CTL_DEL, fileno(game->graph_stream), NULL); fclose(game->graph_stream); game->graph_stream = NULL; return (true); } tmp = game->players; while (tmp) { player = (player_t *)tmp->element; if (player->fd == ev->data.fd) { list_remove((tmp == game->players) ? &game->players : &tmp); epoll_ctl(efd, EPOLL_CTL_DEL, player->fd, NULL); send_pdi(game->graph_stream, player->id); player_destroy(player); return (true); } tmp = tmp->next; } return (false); }
C
#include <stdio.h> #include <stdlib.h> #define x 3 int main() { /// Como funciona un array. /* int datos [50]; for(int i=0;i<x;i++) { printf("Ingrese la edad del alumno: "); scanf("%d",&datos[i]) ; } */ /// maximo y minimo int datos[5]; for(i= 0; i < x; i++) { if(i==0||datos[i] > max) { max = datos[i]; } if(i == 0 || datos[i]<min) { min = datos[i]; } } return 0; }
C
#include<stdio.h> #include<stdlib.h> void reverseWords(char* s); int main(void) { char ch[]= "Let's take LeetCode contest"; reverseWords(ch); puts(ch); return 0; } void reverseWords(char* s) { int index=0; int count=0,count1=-1,i=0; while(s[count]!='\0') { count++; } char temp[100]; int j; while(index!=count) { i=0; count1+=1; while(s[count1]!=' ' && count1<count) { temp[i]=s[count1]; count1++; i++; } for(i=i-1;i>=0;i--) { s[index++]=temp[i]; } if(index!=count) s[index++]=' '; } }
C
#include "utili.h" /*---------------ʱӳ----------------*/ void delay (uint us) { while(us--); } void delay1 (uint ms) { int i,j; for(i=0;i<ms;i++) for(j=0;j<1000;j++) ; } //ַ uchar strlen(uchar *s) { uchar len = 0; while(*s++) len ++; return len; } double buf2double() //convert rdata.tempbuf to double { double tmp = 0.0; uchar i = 0; uchar pos = 0; for(i=0;i<rdata.pos_len;i++) { if(rdata.tempbuf[i] != KEY_DOT) tmp = tmp * 10.0+(rdata.tempbuf[i] - '0'); else pos = rdata.pos_len - i - 1; } while(pos > 0) { tmp = tmp / 10.0; pos--; } return tmp; } int buf2byte() //convert rdata.tempbuf to byte (00-99) { int tmp = 0; uchar i; for(i=0;i<rdata.pos_len;i++) { tmp = tmp * 10+(rdata.tempbuf[i] - '0'); } return tmp; }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> int main () { FILE *fd; fd = fopen ("file.txt", "w+"); pid_t pid; int status; pid = fork (); if (pid > 0) { wait (&status); printf ("Parent Process \n"); printf ("%d \n", getpid ()); fputs ("Lakshmi", fd); fclose (fd); } else if (pid == 0) { printf ("Child Process \n"); printf ("%d \n", getpid ()); fputs (" Gadupudi", fd); fclose (fd); } else { printf ("No child \n"); } if (pid == 0 && WIFSIGNALED (status)) { printf ("Child terminated normally \n"); } else { printf ("not exe \n"); } return 0; }
C
/* 3. Uma empresa de engenheiros necessita melhorar o seu trabalho tornando-o mais eficaz, pensando em resolver esse problema você foi contratado para criar um programa para calcular a área de um terreno em forma de quadrado. Faça um programa que receba os diâmetros dos lados de um terreno em metros, calcule e mostre a área do terreno. Teste os lados para verificar se de fato é um quadrado.Formula para calcular (lado x lado) o terreno em forma de quadrado. Obs: Lembre-se que o quadrado é um quadrilátero regular que apresenta quatro lados congruentes (mesa medida). */ #include <stdio.h> #include <stdlib.h> int main() { float x,y; printf("Entre com um valor: "); scanf("%f",&x); printf("Entre com outro valor: "); scanf("%f",&y); system("CLS");//limpa a tela if(x == y){ printf("\nOk! QUADRILATERO. \nOs valores digitados foram %.1f MT e %.1f MT",x,y); printf("\nA area e: %.1f metros", x*y); } else{ printf("\nDesculpe! Nao e QUADRILATERO.\n"); printf("\nOs valores digitados foram %.1f MT e %.1f MT",x,y); printf("\nA area e: %.1f metros", x*y); } printf("\n\n"); }
C
/* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ #include <linux/bpf.h> #include <linux/if_ether.h> #include <linux/in.h> #include "bpf_helpers.h" #include "bpf_endian.h" /* NOTICE: Re-defining VLAN header levels to parse */ #define VLAN_MAX_DEPTH 10 #include "../common/parsing_helpers.h" #define VLAN_VID_MASK 0x0fff /* VLAN Identifier */ struct vlans { __u16 id[VLAN_MAX_DEPTH]; }; /* Based on parse_ethhdr() */ static __always_inline int __parse_ethhdr_vlan(struct hdr_cursor *nh, void *data_end, struct ethhdr **ethhdr, struct vlans* vlans) { struct ethhdr *eth = nh->pos; int hdrsize = sizeof(*eth); struct vlan_hdr *vlh; __u16 h_proto; int i; /* Byte-count bounds check; check if current pointer + size of header * is after data_end. */ if (nh->pos + hdrsize > data_end) return -1; nh->pos += hdrsize; *ethhdr = eth; vlh = nh->pos; h_proto = eth->h_proto; /* Use loop unrolling to avoid the verifier restriction on loops; * support up to VLAN_MAX_DEPTH layers of VLAN encapsulation. */ #pragma unroll for (i = 0; i < VLAN_MAX_DEPTH; i++) { if (!proto_is_vlan(h_proto)) break; if (vlh + 1 > data_end) break; h_proto = vlh->h_vlan_encapsulated_proto; if (vlans) { vlans->id[i] = vlh->h_vlan_TCI & VLAN_VID_MASK; } vlh++; } nh->pos = vlh; return bpf_ntohs(h_proto); } SEC("xdp_vlan02") int xdp_vlan_02(struct xdp_md *ctx) { void *data_end = (void *)(long)ctx->data_end; void *data = (void *)(long)ctx->data; /* These keep track of the next header type and iterator pointer */ struct hdr_cursor nh; int eth_type; nh.pos = data; struct vlans vlans; struct ethhdr *eth; eth_type = __parse_ethhdr_vlan(&nh, data_end, &eth, &vlans); if (eth_type < 0) return XDP_ABORTED; /* The LLVM compiler is very clever, it sees that program only access * 2nd "inner" vlan (array index 1), and only does loop unroll of 2, and * only does the VLAN_VID_MASK in the 2nd "inner" vlan case. */ if (vlans.id[1] == 42) return XDP_ABORTED; /* If using eth_type (even compare against zero), it will cause full * loop unroll and walking all VLANs (for VLAN_MAX_DEPTH). Still only * "inner" VLAN is masked out. */ #if 0 if (eth_type == 0) return XDP_PASS; #endif /* Unless we only want to manipulate VLAN, then next step will naturally * be parsing the next L3 headers. This (also) cause compiler to create * VLAN loop, as this uses nh->pos */ #if 0 int ip_type; struct iphdr *iphdr; if (eth_type == ETH_P_IP) { ip_type = parse_iphdr(&nh, data_end, &iphdr); if (eth_type < 0) return XDP_ABORTED; if (ip_type == IPPROTO_UDP) return XDP_DROP; } #endif /* Hint: to inspect BPF byte-code run: * llvm-objdump -S xdp_vlan02_kern.o */ return XDP_PASS; }
C
/* * File: util.h * Author: Maurits * * Created on 26 september 2012, 21:55 */ #include "util.h" #include "serial.h" #include <string.h> // Alternative gets() implementation. Reads from the USART and outputs the characters into // the specified array until one of two conditions arises: // 1) The given buffer is full // 2) A LF is encountered (LF and CR are never copied into the buffer) void alt_gets(ubyte *buf, ubyte buf_size) { ubyte i = 0, c = 0; // Clear the given buffer: memset(buf, '\0', buf_size); // Read characters until the buffer is full or LF is encountered: while (i < (buf_size - 1) && c != '\n') { // Make sure the buffer is always null-terminated // Blocking wait for a character to arrive and echo it to the screen: c = getc_uart(); putch(c); // Copy the character to the buffer if it's not a CR or LF: if (c != '\r' && c != '\n') { buf[i] = c; i++; } else { break; } } } void alt_gets_no_echo(ubyte *buf, ubyte buf_size) { ubyte i = 0, c = 0; // Clear the given buffer: memset(buf, '\0', buf_size); // Read characters until the buffer is full or LF is encountered: while (i < (buf_size - 1) && c != '\n') { // Make sure the buffer is always null-terminated // Blocking wait for a character to arrive: c = getc_uart(); // Copy the character to the buffer if it's not a CR or LF: if (c != '\r' && c != '\n') { buf[i] = c; i++; } else { break; } } } /** * Delay for one second. * TODO: verify this calculation. */ void delay_1sec(void) { ubyte i; // Delay for 10M cycles = 1 sec @20MHz: for (i = 0; i < 100; i++) { __delay_ms(10); } }
C
#include "stm32f0xx.h" // Device header /** * Set System Clock Speed to 48Mhz */ void setToMaxSpeed(void); /** * Initialized the timer 2 as a down counter triggering from the ETR pin * Also enables the update interrupt for this timer * @param upToValue number of counts to issue and iterrupt */ void timer_3_encoder_init(); /** * Initialize Pin B1 as output */ void led_init(void); unsigned int encoder_position=0; int main(void){ setToMaxSpeed(); led_init(); timer_3_encoder_init(); while(1){ encoder_position=TIM_GetCounter(TIM3); //for(int i=0; i<0xFFFFF;i++); //GPIO_WriteBit(GPIOA,GPIO_Pin_1,!GPIO_ReadOutputDataBit(GPIOA,GPIO_Pin_1));//toggles led } } void setToMaxSpeed(void){ int internalClockCounter; RCC_PLLCmd(DISABLE); while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY)); RCC_HSEConfig(RCC_HSE_OFF); RCC_PLLConfig(RCC_PLLSource_HSI_Div2,RCC_PLLMul_12); RCC_PREDIV1Config(RCC_PREDIV1_Div1); RCC_PLLCmd(ENABLE); while(!RCC_GetFlagStatus(RCC_FLAG_PLLRDY)); RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); for(internalClockCounter=0;internalClockCounter<1024;internalClockCounter++){ if(RCC_GetSYSCLKSource()==RCC_SYSCLKSource_PLLCLK){ SystemCoreClockUpdate(); break; } } } void timer_3_encoder_init(){ //Configure Pin B4 TIM3_CH1, PB5 TIM3_CH2 RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB,ENABLE); GPIO_InitTypeDef myGPIO; GPIO_StructInit(&myGPIO); myGPIO.GPIO_Pin=GPIO_Pin_4|GPIO_Pin_5; myGPIO.GPIO_Mode=GPIO_Mode_AF; myGPIO.GPIO_PuPd=GPIO_PuPd_UP; GPIO_Init(GPIOB,&myGPIO); GPIO_PinAFConfig(GPIOB,GPIO_PinSource4,GPIO_AF_1); GPIO_PinAFConfig(GPIOB,GPIO_PinSource5,GPIO_AF_1); //time base configuration RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3,ENABLE); TIM_TimeBaseInitTypeDef myTimer; TIM_TimeBaseStructInit(&myTimer); myTimer.TIM_CounterMode=TIM_CounterMode_Up; myTimer.TIM_Prescaler=(0);//microsecond count myTimer.TIM_ClockDivision=TIM_CKD_DIV1; myTimer.TIM_Period=(1000-1);//Overflow every 1000 pulses TIM_TimeBaseInit(TIM3,&myTimer); //capture channel 1 configuration TIM_ICInitTypeDef myCapture; TIM_ICStructInit(&myCapture); myCapture.TIM_Channel=TIM_Channel_1; myCapture.TIM_ICFilter=0xF;//no filter myCapture.TIM_ICPolarity=TIM_ICPolarity_Rising; myCapture.TIM_ICPrescaler=TIM_ICPSC_DIV1; myCapture.TIM_ICSelection=TIM_ICSelection_DirectTI; TIM_ICInit(TIM3,&myCapture); //capture channel 3 configuration myCapture.TIM_Channel=TIM_Channel_2; TIM_ICInit(TIM3,&myCapture); //Encoder configuration TIM_EncoderInterfaceConfig(TIM3,TIM_EncoderMode_TI1,TIM_ICPolarity_Rising,TIM_ICPolarity_Rising); //Interrupt configuration //TIM_ITConfig(TIM3,TIM_IT_Update,ENABLE); //NVIC_EnableIRQ(TIM3_IRQn); //start timer TIM_Cmd(TIM3,ENABLE); } void led_init(void){ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB,ENABLE); RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA,ENABLE); GPIO_InitTypeDef myGPIO; GPIO_StructInit(&myGPIO); myGPIO.GPIO_Pin=GPIO_Pin_1; myGPIO.GPIO_Mode=GPIO_Mode_OUT; GPIO_Init(GPIOB,&myGPIO); GPIO_ResetBits(GPIOB,GPIO_Pin_1); GPIO_Init(GPIOA,&myGPIO); GPIO_ResetBits(GPIOA,GPIO_Pin_1); } int update_counter; int capture_counter; int capture_val; void TIM3_IRQHandler(void){ if(TIM_GetITStatus(TIM3,TIM_IT_Update)){ TIM_ClearITPendingBit(TIM3,TIM_IT_Update); //GPIO_WriteBit(GPIOB,GPIO_Pin_1,!GPIO_ReadOutputDataBit(GPIOB,GPIO_Pin_1));//toggles led update_counter++; } }
C
#include <mpi.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { // Initialize the MPI environment MPI_Init(NULL, NULL); // Find out rank, size int world_rank; MPI_Comm_rank(MPI_COMM_WORLD, &world_rank); int world_size; MPI_Comm_size(MPI_COMM_WORLD, &world_size); // We are assuming at least 2 processes for this task if (world_size < 2) { printf("World size must be greater than 1 for %s\n", argv[0]); MPI_Abort(MPI_COMM_WORLD, 1); } int number; MPI_Request sendRequest; MPI_Status sendStatus; MPI_Request receiveRequest; MPI_Status receiveStatus; if(world_rank==0){ number = -1; MPI_Isend(&number,1,MPI_INT,1,0,MPI_COMM_WORLD,&sendRequest); } else if(world_rank==1){ MPI_Irecv(&number,1,MPI_INT,0,0,MPI_COMM_WORLD,&receiveRequest); MPI_Wait(&receiveRequest,&receiveStatus); printf("Process 1 received number %d from process 0\n",number); } if(world_rank==0){ MPI_Wait(&sendRequest,&sendStatus); } MPI_Finalize(); }
C
#include <stdio.h> #include <stdlib.h> int v; int opcount; void swap(int ans[], int a, int b) { int temp = ans[a]; ans[a] = ans[b]; ans[b] = temp; } void permute(int arr[][v], int ans[], int l,int *min, int finans[]) { opcount++; if(l==v) { int sum = 0; for(int i=0; i<v; i++) sum += arr[i][ans[i]]; if(sum<*min) { for(int i=0; i<v; i++) finans[i] = ans[i]; *min = sum; } return; } for(int i=l; i<v; i++) { swap(ans,i,l); permute(arr,ans,l+1,min,finans); swap(ans,i,l); } } void prob() { opcount = 0; int min = 99999999; int arr[v][v]; for(int i=0; i<v; i++) { for(int j=0; j<v; j++) arr[i][j] = i+j; } int ans[v]; for(int i=0; i<v; i++) ans[i] = i; int finans[v]; permute(arr,ans,0,&min,finans); printf("\nFINALASSIGMT: "); for(int i=0; i<v; i++) printf("%d",finans[i]); printf("\n%d\n",opcount); } int main() { for(int i=0; i<10; i++) { v = i+2; prob(); } return 0; }
C
#include "my_msg.h" int main(void) { int msgid; msg_t data; long int msgtype = 0; //注意1 if(-1==(msgid=msgget((key_t)1234, 0666 | IPC_CREAT))){ fprintf(stderr, "msgget failed with error: %d\n", errno); exit(EXIT_FAILURE); } do{ if(-1==msgrcv(msgid,&data,BUFSIZ,msgtype,0)){ fprintf(stderr, "msgsnd failed\n"); exit(EXIT_FAILURE); } printf("You wrote: %s\n",data.txt); sleep(1); }while(strncmp(data.txt, "end", 3)); if(-1==msgctl(msgid,IPC_RMID,0)) { fprintf(stderr, "msgctl(IPC_RMID) failed\n"); exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); }
C
#include <stdio.h> #include<stdlib.h> //Mr. Santa asks all the great programmers of the world to solve a trivial problem. //He gives them an integer m and asks for the number of positive integers n, such that the //factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem? int findTrailingZeros(int n) { // Initialize result int count = 0; // Keep dividing n by powers of // 5 and update count for (int i = 5; n / i >= 1; i *= 5) count= count + n/i; return count; } int main(){ int m; int nums[1000000]; int i=0; scanf("%i", &m); for(int n=1; n<1000000; n++){ if(findTrailingZeros(n) == m){ nums[i]=n; i++; } } printf("%i\n", i); for(int j=0; j<i; j++){ printf("%i ", nums[j]); } return 0; }
C
/* Trasformazione della rappresentazione di un grafo da una matrice di adiacenze a una lista di successori */ #include <stdio.h> #include <malloc.h> struct nodo { /* struttura di un nodo */ char inf; struct successore *pun; }; struct successore { /* elemento della lista di successori */ int inf; struct successore *pun; }; int a[10][10]; /* matrice di adiacenze */ struct nodo s[10]; /* array di nodi */ int n; /* numero di nodi */ void matAdiacenze(void); void visMatAdiacenze(void); void successori(void); void creaSucc(int, int); void visita(void); int main() { matAdiacenze(); /* creazione della matrice di adiacenze */ visMatAdiacenze(); /* visualizzazione della matrice */ successori(); /* creazione delle liste di successori */ visita(); /* visual. dei successori di ogni nodo */ } /* Crea la matrice di adiacenze */ void matAdiacenze(void) { int i, j; char invio; printf("\nNumero di nodi: "); scanf("%d", &n); scanf("%c", &invio); for(i=0; i<n; i++) { /* richiesta etichette dei nodi */ printf("\nEtichetta del nodo: "); scanf("%c", &s[i].inf); scanf("%c", &invio); s[i].pun = NULL; } for(i=0; i<n; i++) /* richiesta archi orientati */ for(j=0; j<n; j++) { printf("\nArco orientato da [%c] a [%c] (0 no, 1 si) ? ", s[i].inf, s[j].inf); scanf("%d", &a[i][j]); } } /* Visualizza la matrice di adiacenze */ void visMatAdiacenze(void) { int i, j; printf("\nMATRICE DI ADIACENZE\n"); for(i=0; i<n; i++) /* visualizza i nodi (colonne) */ printf(" %c", s[i].inf); for(i=0; i<n; i++) { printf("\n%c ", s[i].inf); /* visualizza i nodi (righe) */ for(j=0; j<n; j++) printf("%d ", a[i][j]); /* visualizza gli archi */ } } /* Crea le liste di successori. Per ogni arco rappresentato nella matrice di adiacenze chiama creaSucc */ void successori(void) { int i, j; for(i=0; i<n; i++) for(j=0; j<n; j++) { if(a[i][j]==1) creaSucc(i, j); } } /* Dato un certo arco nella matrice di adiacenze, crea il rispettivo elemento di lista */ void creaSucc( int i, int j ) { struct successore *p; if(s[i].pun==NULL) { /* non esiste la lista dei successori */ s[i].pun = (struct successore *)(malloc(sizeof(struct successore))); s[i].pun->inf = j; s[i].pun->pun = NULL; } else { /* esiste la lista dei successori */ p = s[i].pun; while(p->pun!=NULL) p = p->pun; p->pun = (struct successore *)(malloc(sizeof(struct successore))); p = p->pun; p->inf = j; p->pun = NULL; } } /* Per ogni nodo del grafo restituisce i suoi successori. Lavora sulle liste di successori */ void visita(void) { int i; struct successore *p; printf("\n"); for(i=0; i<n; i++) { printf("\n[%c] ha come successori: ", s[i].inf); p = s[i].pun; while(p!=NULL) { printf(" %c", s[p->inf].inf); p = p->pun; } } }
C
int work(int arr[5][5],int m,int n) { int k,t; if ((m>=0)&&(m<5)&&(n>=0)&&(n<5)) { for (k=0;k<5;k++) { t=arr[m][k]; arr[m][k]=arr[n][k]; arr[n][k]=t; } return 1; } else return 0; } int main() { int i,j,m,n; int a[5][5]; for (i=0;i<5;i++) for (j=0;j<5;j++) scanf("%d",&a[i][j]); scanf("%d %d",&m,&n); if (work(a,m,n)==1) { for (i=0;i<5;i++) { printf("%d",a[i][0]); for (j=1;j<5;j++) printf(" %d",a[i][j]); printf("\n"); } } else printf("error\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jcatinea <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/10 10:01:05 by jcatinea #+# #+# */ /* Updated: 2016/11/13 12:15:10 by jcatinea ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static char **tab_realloc(char **tab, char *s, size_t size) { size_t i; char **new; i = 0; if (!(new = (char **)malloc((sizeof(char *)) * (size + 1)))) return (NULL); while (i < size) { new[i] = tab[i]; i++; } if (size > 0) new[size - 1] = s; new[size] = 0; free(tab); return (new); } static char **init(size_t *i, size_t *size) { char **tab; *i = 0; *size = 0; if (!(tab = (char **)malloc(sizeof(char *)))) return (NULL); tab[0] = 0; return (tab); } char **ft_strsplit(char const *s, char c) { char **tab; char *str; size_t i; size_t j; size_t size; if (!s || !(tab = init(&i, &size))) return (NULL); while (s[i]) { j = 0; while (s[i + j] && s[i + j] != c) j++; if (j > 0) { if (!(str = ft_strsub(s, i, j))) return (NULL); if (!(tab = tab_realloc(tab, str, ++size))) return (NULL); i += (j - 1); } i++; } return (tab); }
C
/* NO.198 You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Credits: Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases. */ #include <stdio.h> int rob(int* nums, int numsSize) { int *re = (int*) malloc(numsSize * sizeof(int)); for (int i = 0; i < numsSize; i++) { re[i] = -1; } return robMemorized(nums, 0, numsSize, re); } int robMemorized(int* nums, int start, int numsSize, int* re) { if (-1 != re[start]) return re[start]; else if (start == numsSize - 1) { re[start] = nums[start]; return re[start]; } else if (start == numsSize - 2) { re[start] = nums[start] > nums[start + 1] ? nums[start] : nums[start + 1]; return re[start]; } else if (start == numsSize - 3) { re[start] = nums[start] + nums[start + 2] > nums [start + 1] ? nums[start] + nums[start + 2] : nums[start + 1]; return re[start]; } else { int F = nums[start] + robMemorized(nums, start + 2, numsSize, re); int L = robMemorized(nums, start + 1, numsSize, re); re[start] = F > L ? F : L; return re[start]; } } int main() { int a[100] = {114,117,207,117,235,82,90,67,143,146,53,108,200,91,80,223,58,170,110,236,81,90,222,160,165,195,187,199,114,235,197,187,69,129,64,214,228,78,188,67,205,94,205,169,241,202,144,240}; printf("YU::%d\n", rob(a, 100)); }
C
//判断一个数字中二进制中有多少个1 //反复除以2.如果余数是1,就+1 #include <iostream> using namespace std; int main(){ int n; cin >>n; for (int i = 0;i<n;i++){ int x,ans = 0; cin >>x; while(x >0){ ans += x %2; x /= 2; } cout << ans <<endl; } return 0; }
C
#include "cclient/api/core/core_api.h" #include "cclient/api/extended/extended_api.h" #include <inttypes.h> #include "iota_client_service/config.h" #include "iota_client_service/client_service.h" retcode_t get_iota_node_info(iota_client_service_t *iota_client_service, get_node_info_res_t *node_response) { retcode_t ret = RC_ERROR; ret = iota_client_get_node_info(iota_client_service, node_response); trit_t trytes_out[NUM_TRYTES_HASH + 1]; size_t trits_count = 0; if (ret == RC_OK) { printf("appName %s \n", node_response->app_name->data); printf("appVersion %s \n", node_response->app_version->data); //Converting returned latest_milestone trits to tryte chars //Read for more information: https://docs.iota.org/docs/iota-basics/0.1/references/tryte-alphabet trits_count = flex_trits_to_trytes(trytes_out, NUM_TRYTES_HASH, node_response->latest_milestone, NUM_TRITS_HASH, NUM_TRITS_HASH); if (trits_count == 0) { printf("trit converting failed\n"); goto done; } trytes_out[NUM_TRYTES_HASH] = '\0'; printf("latestMilestone %s \n", trytes_out); printf("latestMilestoneIndex %u\n", (uint32_t) node_response->latest_milestone_index); printf("milestoneStratIndex %u\n", node_response->milestone_start_index); printf("neighbors %d \n", node_response->neighbors); printf("packetsQueueSize %d \n", node_response->packets_queue_size); printf("time %" PRIu64 "\n", node_response->time); printf("tips %u \n", node_response->tips); printf("transactionsToRequest %u\n", node_response->transactions_to_request); }else{ printf("Node info failed."); } done: get_node_info_res_free(&node_response); return ret; } int main(void) { iota_client_service_t iota_client_service; init_iota_client(&iota_client_service); get_node_info_res_t *node_response = get_node_info_res_new(); get_iota_node_info(&iota_client_service, node_response); }
C
/*-----------------------------------------------------------------------------------------------------------*/ /* */ /* Copyright (C) 2016 Brite Semiconductor Co., Ltd. All rights reserved. */ /* */ /*-----------------------------------------------------------------------------------------------------------*/ #include "test_led.h" #if (CONFIG_LED_TEST == 1) /*************************************************************************************************************/ // macro definition /*************************************************************************************************************/ /*************************************************************************************************************/ // global variable definition /*************************************************************************************************************/ cmdline_entry led_test_menu[]; /*************************************************************************************************************/ // function prototype /*************************************************************************************************************/ /*************************************************************************************************************/ // function implementation /*************************************************************************************************************/ static int cmd_help(int argc, char *argv[]) { return cmdline_help_general(&led_test_menu[0]); } /*****************************************************************************/ // Function: static int led_test_reset(int argc, char *argv[]) // // Parameters: // argc : argument count // // argv : argument // // Return: // 0 : success // // Description: // led reset test. // /*****************************************************************************/ static int led_test_reset(int argc, char *argv[]) { int ret_val; E_LED_RST_MODE rst_mode; info("%s: led reset test\n\n", argv[0]); // Check the validity of parameter count if (argc < 2) { info("format: %s rst_mode\n", argv[0]); info("rst_mode : 0, poweron; 1, shutdown\n"); return ERR_TEST_ARGC; } // Get the parameters rst_mode = get_arg_ulong(argv[1]) & 0x1; info("%s , reset mode: %d\n", argv[0], rst_mode); ret_val = led_reset(rst_mode); if (ret_val) { info("%s: test fail\n", argv[0]); } else { info("%s: test pass\n", argv[0]); } return ERR_TEST_DONE; } /*****************************************************************************/ // Function: static int led_test_oe(int argc, char *argv[]) // // Parameters: // argc : argument count // // argv : argument // // Return: // 0 : success // // Description: // led output enable test. // /*****************************************************************************/ static int led_test_oe(int argc, char *argv[]) { int fail = 0; E_LED_OE led_oe; info("%s: led oe test\n\n", argv[0]); // Check the validity of parameter count if (argc < 2) { info("format: %s led_oe\n", argv[0]); info("led_oe : \n"); info(" 0x1 : LED_RGB_0_2_OE\n"); info(" 0x2 : LED_RGB_3_5_OE\n"); info(" 0x4 : LED_RGB_6_7_OE\n"); info(" 0x8 : LED_RGB_8_9_OE\n"); info(" 0x10 : LED_RGB_10_12_OE\n"); info(" 0x20 : LED_RGB_13_15_OE\n"); info(" 0x3F : LED_RGB_0_15_OE\n"); return ERR_TEST_ARGC; } if (led_reset(LED_POWERON)) { fail++; goto end; } // Get the parameters led_oe = get_arg_ulong(argv[1]) & LED_RGB_OE_MASK; info("%s , oe_no: %d\n", argv[0], led_oe); if (led_rgb_oe(led_oe)) { fail++; } end: if (fail) { info("%s: test fail\n", argv[0]); } else { info("%s: test pass\n", argv[0]); } return ERR_TEST_DONE; } /*****************************************************************************/ // Function: static int led_test_brightness(int argc, char *argv[]) // // Parameters: // argc : argument count // // argv : argument // // Return: // 0 : success // // Description: // led brightness test. // /*****************************************************************************/ static int led_test_brightness(int argc, char *argv[]) { int fail = 0; E_LED_PORT port; uint8_t brightness; info("%s: led brightness test\n\n", argv[0]); // Check the validity of parameter count if (argc < 3) { info("format: %s port brightness\n", argv[0]); info("port : [0, 15]\n"); info("brightness : [0, 0x7F], 0, the min light, 0x7F, the max light\n"); return ERR_TEST_ARGC; } // Get the parameters port = get_arg_ulong(argv[1]); brightness = get_arg_ulong(argv[2]); info("%s , port: %d, brightness: %d\n", argv[0], port, brightness); // set bfightness if (led_fix_brightness(port, brightness)) { fail++; goto end; } end: if (fail) { info("%s: test fail\n", argv[0]); } else { info("%s: test pass\n", argv[0]); } return ERR_TEST_DONE; } int led_test_prepare(int port) { led_init(); return ERR_TEST_DONE; } int led_test_cleanup(int port) { return ERR_TEST_DONE; } //***************************************************************************** // // This is the table that holds the command names, implementing functions, // and brief description. // //***************************************************************************** cmdline_entry led_test_menu[] = { {"help", cmd_help, " : Display list of commands"}, {"h", cmd_help, " : alias for help"}, {"?", cmd_help, " : alias for help"}, {"led_test_reset", led_test_reset, " : led reset test"}, {"led_test_oe", led_test_oe, " : led output enable test"}, {"led_test_brightness", led_test_brightness, " : led brightness test"}, {"q", NULL, " : quit uart test"}, {0, 0, 0} }; #endif
C
#define _CRT_SECURE_NO_WARNINGS #define QMAX 100 #include<stdio.h> #include<math.h> #include<malloc.h> #include<locale.h> #include<time.h> #include<windows.h> #include<stdbool.h> struct queue { int qu[QMAX]; int rear, frnt; }queue; void init(struct queue* q) { q->frnt = 1; q->rear = 0; return; } void insert(struct queue* q, int x) { if (q->rear < QMAX - 1) { q->rear++; q->qu[q->rear] = x; } else printf(" !\n"); return; } int isempty(struct queue* q) { if (q->rear < q->frnt) return 1; else return 0; } void print(struct queue* q) { int h; if (isempty(q) == 1) { return; } for (h = q->frnt; h <= q->rear; h++) printf("%d ", q->qu[h]); printf("\n\n"); return; } int remove(struct queue* q) { int x; if (isempty(q) == 1) { printf(" !\n"); return(0); } x = q->qu[q->frnt]; q->frnt++; return x; } int add(struct queue* q) { srand(time(NULL)); int j = rand() % 10 ; insert(q,j); } void hirurg(float *y,float *t) { struct queue* p; int a,b; int Time = 0,Time1; int Time2 = 0, Time22; p = (struct queue*)malloc(sizeof(struct queue)); init(p); print(p); printf(". :"); srand(time(NULL)); *y = rand() % 8 + 1; for (int i = 1;i <= *y;i++) { insert(p,i); } printf("\n"); print(p); int g=0; for (int j = 0;j < 3;j++){ int k = rand() % 3; a = remove(p); Time1 = rand() % 3000; Time += Time1; Sleep(Time1); system("cls"); printf(". :\n"); print(p); if ( g == k) { b = add(p); Time22 = rand() % 1000; Time2 += Time22; Sleep(Time2); system("cls"); printf(". :\n"); print(p); } } *t = Time / 1000; } void terapeft(float *b, float *t1) { struct queue* p; int q,v; int Time2 = 0, Time22; p = (struct queue*)malloc(sizeof(struct queue)); init(p); print(p); printf(". :"); srand(time(NULL)); *b = rand() % 10 + 1.0; for (int i = 1;i <= *b;i++) { insert(p, i); } printf("\n"); print(p); int Time = 0, Time1; int g = 0; for (int j = 0;j < 5;j++) { int k = rand() % 3; q = remove(p); Time1 = rand() % 5000; Time += Time1; Sleep(Time1); system("cls"); printf(". :\n"); print(p); if (g == k) { v = add(p); Time22 = rand() % 1000; Time2 += Time22; Sleep(Time2); system("cls"); printf(". :\n"); print(p); } } *t1 = Time / 1000; } void psycho(float *c, float *t2) { struct queue* p; int h,b; int Time2 = 0, Time22; p = (struct queue*)malloc(sizeof(struct queue)); init(p); print(p); printf(". :"); srand(time(NULL)); *c = rand() % 14 + 1; for (int i = 1;i <= *c;i++) { insert(p, i); } printf("\n"); print(p); int Time = 0, Time1; int g = 0; for (int j = 0;j < 4;j++) { int k = rand() % 3; h = remove(p); Time1 = rand() % 5000; Time += Time1; Sleep(Time1); system("cls"); printf(". :\n"); print(p); if (g == k) { b = add(p); Time22 = rand() % 1000; Time2 += Time22; Sleep(Time2); system("cls"); printf(". :\n"); print(p); } } *t2 = Time / 1000; } void dentist(float *n, float *t3) { struct queue* p; int o,b; p = (struct queue*)malloc(sizeof(struct queue)); init(p); print(p); printf(". :"); srand(time(NULL)); *n =rand() % 12 + 1; for (int i = 1;i <= *n;i++) { insert(p, i); } printf("\n"); print(p); int Time = 0, Time1; int Time2 = 0, Time22; for (int j = 0;j < 5;j++) { int k = rand() % 3; o = remove(p); Time1 = rand() % 5000; Time += Time1; Sleep(Time1); system("cls"); printf(". :\n"); print(p); int g = 0; if (g == k) { b = add(p); Time22 = rand() % 1000; Time2 += Time22; Sleep(Time2); system("cls"); printf(". :\n"); print(p); } } *t3 = Time / 1000; } void nevropotolog(float *m, float *t4) { struct queue* p; int l,b; int Time2 = 0, Time22; p = (struct queue*)malloc(sizeof(struct queue)); init(p); print(p); printf(". :"); srand(time(NULL)); *m = rand() % 11 + 1; for (int i = 1;i <= *m;i++) { insert(p, i); } printf("\n"); print(p); int Time = 0, Time1; int g = 0; for (int j = 0;j < 3;j++) { int k = rand() % 3; l = remove(p); Time1 = rand() % 5000; Time += Time1; Sleep(Time1); system("cls"); printf(". :\n"); print(p); if (g == k) { b = add(p); Time22 = rand() % 1000; Time2 += Time22; Sleep(Time2); system("cls"); printf(". :\n"); print(p); } } *t4 = Time / 1000; } float y,b,c,n,m; float t, t1, t2, t3, t4; float t5=0; int main(float t) { char* locale = setlocale(LC_ALL,"ru"); bool a = true; system("chcp 1251"); system("cls"); int Time; int timeo = 0; while (a) { Time = rand() % 3000; timeo += Time; Sleep(Time); hirurg(&y,&t); terapeft(&b,&t1); psycho(&c,&t2); dentist(&n,&t3); nevropotolog(&m,&t4); a=false; } t5 = t + t1 + t2 + t3 + t4; printf(" : %.2f min",t5); return 0; }
C
/* algo7-7.c ʵ㷨7.16ij */ #define MAX_NAME 5 /* ַ󳤶+1 */ #define MAX_INFO 20 /* Ϣַ󳤶+1 */ typedef int VRType; typedef char VertexType[MAX_NAME]; typedef char InfoType; #include"c1.h" #include"c7-1.h" /* ڽӾ洢ʾ */ #include"bo7-1.c" /* ڽӾ洢ʾĻ */ typedef int PathMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM][MAX_VERTEX_NUM]; /* 3ά */ typedef int DistancMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; /* 2ά */ #include"func7-2.c" /* иԶ֮̾Floyd㷨 */ void main() { MGraph g; int i,j,k; PathMatrix p; /* 3ά */ DistancMatrix d; /* 2ά */ CreateDN(&g); /* g */ for(i=0;i<g.vexnum;i++) g.arcs[i][i].adj=0; /* ShortestPath_FLOYD()ҪԽԪֵΪ0ΪͬΪ0 */ Display(g); /* g */ ShortestPath_FLOYD(g,p,d); /* ÿԶ·func7-2.c */ printf("d:\n"); for(i=0;i<g.vexnum;i++) { for(j=0;j<g.vexnum;j++) printf("%6d",d[i][j]); printf("\n"); } for(i=0;i<g.vexnum;i++) for(j=0;j<g.vexnum;j++) if(i!=j) printf("%s%s̾Ϊ%d\n",g.vexs[i],g.vexs[j],d[i][j]); printf("p:\n"); for(i=0;i<g.vexnum;i++) for(j=0;j<g.vexnum;j++) if(i!=j) { printf("%s%s",g.vexs[i],g.vexs[j]); for(k=0;k<g.vexnum;k++) if(p[i][j][k]==1) printf("%s ",g.vexs[k]); printf("\n"); } } 
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include "tabuleiro.h" // *************** Protótipos de Funções**************** int mostrarMenu(); void jogar(int tabuleiro[][DIMENSAO]); void terminarJogo(int vencedor); void realizarJogada(int jogador, int tabuleiro[][DIMENSAO]); int main(void) { int tabuleiro[DIMENSAO][DIMENSAO]; int opcao; do { opcao = mostrarMenu(); if (opcao == 1) jogar(tabuleiro); } while (opcao != 2); return 0; } int mostrarMenu() { int opcao; system("cls||clear"); printf("\n======= JOGO DA VELHA - VERSAO %s =======\n", VERSAO); printf("@autor: Jelson Matheus\n\n"); printf("MENU:\n"); printf("> 1 - Jogar\n"); printf("> 2 - Sair\n"); printf("# Escolha: "); scanf("%d", &opcao); if (opcao < 1 || opcao > 2) mostrarMenu(); return opcao; } void jogar(int tabuleiro[][DIMENSAO]) { int jogador = 0; int totalJogadas = 0; bool vencedor = false; limparTabuleiro(tabuleiro); desenharTabuleiro(tabuleiro); do { jogador = (jogador == 1) ? 2 : 1; realizarJogada(jogador, tabuleiro); desenharTabuleiro(tabuleiro); vencedor = verificarVencedor(tabuleiro); totalJogadas++; } while (!vencedor && totalJogadas < 9); if (vencedor) terminarJogo(jogador); else terminarJogo(0); } void terminarJogo(int vencedor) { switch (vencedor) { case 1: case 2: printf("\nJOGO ENCERRADO! - JOGADOR %d VENCEU.\n", vencedor); break; default: printf("\nJOGO ENCERRADO! - EMPATE.\n"); break; } printf("@ Pressione qualquer tecla para continuar."); getchar(); } void realizarJogada(int jogador, int tabuleiro[][DIMENSAO]) { int linha, coluna, valor; bool check; valor = (jogador == 1) ? 1 : -1; do { printf(">Jogador %d: \n", jogador); printf("\t#Linha: "); scanf("%d", &linha); printf("\t#Coluna: "); scanf("%d%*c", &coluna); check = marcarTabuleiro(tabuleiro, linha, coluna, valor); if (check == false) printf("\t@ERRO! Posição invalida ou ja preenchida.\n"); } while (!check); }
C
#include "datastructure.h" #include <stdlib.h> #include <err.h> #include <assert.h> #include <string.h> int * new_copy_int_array(const int *arr, int len) { int *cpy = malloc(len * sizeof(*cpy)); if (cpy == NULL) err(1, "impossible d'allouer un tableau d'entiers"); memcpy(cpy, arr, len * sizeof(*cpy)); return cpy; } void copy_int_array(const int *src, int *dst, int len) { memcpy(dst, src, len * sizeof(*src)); } bool item_is_primary(const struct instance_t *instance, int item) { return item < instance->n_primary; } struct sparse_array_t * sparse_array_init(int n) { struct sparse_array_t *S = malloc(sizeof(*S)); if (S == NULL) err(1, "impossible d'allouer un tableau creux"); S->len = 0; S->capacity = n; S->p = malloc(n * sizeof(int)); S->q = malloc(n * sizeof(int)); if (S->p == NULL || S->q == NULL) err(1, "Impossible d'allouer p/q dans un tableau creux"); // TODO: memset or parallel for loop for (int i = 0; i < n; i++) S->q[i] = n; // initialement vide return S; } struct sparse_array_t * new_copy_sparse_array(const struct sparse_array_t *S) { struct sparse_array_t *cpy = malloc(sizeof(*cpy)); if (cpy == NULL) err(1, "impossible d'allouer un tableau creux"); cpy->capacity = S->capacity; cpy->len = S->len; cpy->p = new_copy_int_array(S->p, S->capacity); cpy->q = new_copy_int_array(S->q, S->capacity); return cpy; } void copy_sparse_array(const struct sparse_array_t *src, struct sparse_array_t *dst) { assert(src->capacity == dst->capacity); dst->len = src->len; copy_int_array(src->p, dst->p, src->capacity); copy_int_array(src->q, dst->q, src->capacity); } void free_sparse_array(struct sparse_array_t **S) { assert(S != NULL && *S != NULL); free((*S)->p); free((*S)->q); free(*S); *S = NULL; } bool sparse_array_membership(const struct sparse_array_t *S, int x) { return (S->q[x] < S->len); } bool sparse_array_empty(const struct sparse_array_t *S) { return (S->len == 0); } void sparse_array_add(struct sparse_array_t *S, int x) { int i = S->len; S->p[i] = x; S->q[x] = i; S->len = i + 1; } void sparse_array_remove(struct sparse_array_t *S, int x) { int j = S->q[x]; int n = S->len - 1; // échange p[j] et p[n] int y = S->p[n]; S->p[n] = x; S->p[j] = y; // met q à jour S->q[x] = n; S->q[y] = j; S->len = n; } void sparse_array_unremove(struct sparse_array_t *S) { S->len++; } void sparse_array_unadd(struct sparse_array_t *S) { S->len--; } bool item_is_active(const struct context_t *ctx, int item) { return sparse_array_membership(ctx->active_items, item); } struct context_t * new_copy_context(const struct context_t *ctx) { struct context_t *cpy = malloc(sizeof(*cpy)); if (cpy == NULL) err(1, "impossible d'allouer un contexte"); int nb_items = ctx->active_items->capacity; cpy->active_items = new_copy_sparse_array(ctx->active_items); cpy->active_options = malloc(nb_items * sizeof(*cpy->active_options)); if (cpy->active_options == NULL) err(1, "impossible d'allouer le tableau d'options actives"); for (int i = 0; i < nb_items; i++) cpy->active_options[i] = new_copy_sparse_array(ctx->active_options[i]); cpy->chosen_options = new_copy_int_array(ctx->chosen_options, nb_items); cpy->chosen_items = new_copy_int_array(ctx->chosen_items, nb_items); cpy->child_num = new_copy_int_array(ctx->child_num, nb_items); cpy->num_children = new_copy_int_array(ctx->num_children, nb_items); cpy->level = ctx->level; cpy->nodes = ctx->nodes; cpy->solutions = ctx->solutions; return cpy; } void copy_context(const struct context_t *src, struct context_t *dst) { assert(src->active_items->capacity == dst->active_items->capacity); int n_items = src->active_items->capacity; copy_sparse_array(src->active_items, dst->active_items); for (int i = 0; i < n_items; i++) copy_sparse_array(src->active_options[i], dst->active_options[i]); copy_int_array(src->chosen_options, dst->chosen_options, n_items); copy_int_array(src->chosen_items, dst->chosen_items, n_items); copy_int_array(src->child_num, dst->child_num, n_items); copy_int_array(src->num_children, dst->num_children, n_items); dst->level = src->level; dst->nodes = src->nodes; dst->next_work_share = src->next_work_share; dst->solutions = src->solutions; } void free_context(struct context_t **ctx) { assert(ctx != NULL && *ctx != NULL); int nb_items = (*ctx)->active_items->capacity; free_sparse_array(&(*ctx)->active_items); for (int i = 0; i < nb_items; i++) free_sparse_array(&(*ctx)->active_options[i]); free((*ctx)->chosen_options); free((*ctx)->child_num); free((*ctx)->num_children); free(*ctx); *ctx = NULL; } void free_instance(struct instance_t **instance) { assert(instance != NULL && *instance != NULL); if ((*instance)->item_name != NULL) for (int i = 0; i < (*instance)->n_items; i++) free((*instance)->item_name[i]); free((*instance)->item_name); free((*instance)->options); free((*instance)->ptr); free(*instance); *instance = NULL; }
C
//Standard IO, Standard C library, Math and Similation Header #include <stdio.h> #include <stdlib.h> #include "sim.h" #include <math.h> /* Data Structures: Include BinaryHeap file */ #include "heap.h" // Simulation clock variable and BinaryHeap creation BinaryHeap* priorityQueue = createHeap(); double Now = 0.0; // Uniformly distributed random value between 0 and 1 double urand(void) { double x = ((double) rand() / (double) RAND_MAX); return x; } double randexp(double mean) { double x = -1 * mean * (log(1.0 - urand())); return x; } double CurrentTime (void) { return (Now); } void Schedule(double ts, void* data) { insert(priorityQueue, data, ts); } void RunSim(double EndTime) { while (priorityQueue->root != NULL) { Now = priorityQueue->root->key; if (Now > EndTime) break; Node* event = extract_min(priorityQueue); EventHandler(event->data); free(event); } }
C
/* ** my_printf.c for in /home/da-pur_c/delivery/PSU/PSU_2016_my_printf ** ** Made by Clem Da ** Login <[email protected]> ** ** Started on Tue Nov 8 10:24:37 2016 Clem Da ** Last update Thu Nov 16 18:29:03 2017 clem */ #include "my.h" void my_charal(char *str) { int i; i = 0; while (str[i]) { my_putchar(str[i]); i++; } } int check(char c) { int i; char *str; i = 0; str = my_strdup("csdioxXubpS"); while (str[i]) { if (c == str[i]) return (0); i++; } return (1); } int affichage(const char *format, int i) { if (format[i] == '%' && format[i + 1] != '%') { my_putchar(format[i]); my_putchar(format[i + 1]); i++; } else { if (format[i] == '%' && format[i + 1] == '%') { my_putchar(format[i]); i++; } else my_putchar(format[i]); } return (i); } void declara(void (*op[10])()) { op[0] = &my_char; op[1] = &my_charal; op[2] = &my_nbr; op[3] = &my_nbr; op[4] = &my_octal; op[5] = &my_hexamin; op[6] = &my_hexamaj; op[7] = &my_ptr; op[8] = &my_binaire; op[9] = &my_ptr; op[10] = &my_schelou; } int my_printf(const char *format, ...) { va_list ap; int i; int j; char *str; void (*op[10])(); declara(op); va_start(ap, format); i = 0; str = my_strdup("csdioxXubpS"); while (format[i]) { if (format[i] == '%' && (check(format[i + 1]) != 1)) { j = 0; while (str[j] != format[i + 1] && str[j]) j++; str[j]== 's' ? op[j](va_arg(ap, char*)) : op[j](va_arg(ap, int)); i++; } else i = affichage(format, i); i++; } va_end(ap); }
C
// token_enums.h // Copyright (C) 2009 Willow Schlanger #ifndef token_enums_h__ncc__included #define token_enums_h__ncc__included typedef unsigned char U1; typedef unsigned short U2; typedef unsigned U4; typedef unsigned long U8; typedef signed char S1; typedef signed short S2; typedef signed S4; typedef signed long S8; // this is used for enumeration's. typedef long double LongDouble; typedef unsigned long UINT; typedef signed long SINT; // 0..0xffff : corresponding UNICODE character // 0x10000..0x1ffff : symbolic terminals (e.g. PLUSEQ which means "+=") // 0x20000..0x2ffff : rules, e.g. nonterminals (see out_chdr.h) // 0x30000..0x3ffff : identifier keywords (see out_keywords.h) // 0xfffffe00..0xfffffeff : special tokens we introduce to avoid ambiguities // 0xffffff00..0xffffffff : special tokens introduced by lexer such as TOKEN_EOF. // Note: TOKEN_EOF is indicated by the current NCC lexer when we reach end of an // already-preprocessed line. We want to automatically go to the next line when // this happens, and return TOKEN_EOF only when we're at the end of the LAST line. struct CTokenEnums { enum { TOKEN_ANDAND = 0x10000, TOKEN_ANDEQ, TOKEN_DIVEQ, TOKEN_DOTDOTDOT, TOKEN_DOTSTAR, TOKEN_EQEQ, TOKEN_GE, TOKEN_LE, TOKEN_MINUSEQ, TOKEN_MINUSMINUS, TOKEN_MODEQ, TOKEN_NOTEQ, TOKEN_NUMNUM, TOKEN_OREQ, TOKEN_OROR, TOKEN_PLUSEQ, TOKEN_PLUSPLUS, TOKEN_POINT, TOKEN_POINTSTAR, TOKEN_SCOPE, TOKEN_SHL, TOKEN_SHLEQ, TOKEN_SHR, TOKEN_SHREQ, TOKEN_STAREQ, TOKEN_XOREQ, TOKEN_TYPEREFID = 0xfffffe00, TOKEN_SPACE = 0xffffff00, TOKEN_IDENT, TOKEN_NUM, TOKEN_CLITERAL, TOKEN_SLITERAL, TOKEN_UNKNOWN = 0xfffffffe, TOKEN_EOF = 0xffffffff }; }; #endif // token_enums_h__ncc__included
C
// // Created by Jenny on 2017-07-26. // #ifndef LINKEDLIST_MPASSWDSORT_H #define LINKEDLIST_MPASSWDSORT_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include "list.h" /** * Name: userInfo * Description: this is the structure of list elements in this laboration. * @param uid * @param uname * @param next (pointer to next element in list) */ struct userInfo{ unsigned int uid; char* uname;}; /** * Name: controlLine * Description: controls the format of the lines. If something departs message * is written on stderr * @param buffer * @param lineCounter * @return (true or false if the program should exit with !=0) */ bool controlLine(char *buffer, int lineCounter); /** * Name: extractUIFromBuffer * Description: Here the UID and uname information is extracted from the rest * of the file information. * @param Buffer * @return user_info (information to insert in the list) */ struct userInfo *extractUIFromBuffer(char *buffer); /** * Name: getDataFields * Description: Extract the fields of file passwd into an matrix * @param buffer * @return (the matrix with data) */ char **getDataFields(char *buffer); /** * Name: controlIfEmpty * Description: controls if a mandatory field is empty * @param parameter * @return */ bool controlIfEmpty(char *parameter); /** * Name: controlIfNumber * Description: Controls if the field is a number or not. * @param parameter * @return */ bool controlIfNumber(char *parameter); /** * Helper function to get the name of fields UID GID and user name * @param field * @return */ const char* getFieldName(int field); /** * Name: openfile * Description: Open a textfile and control if the textfile is possible to open, * failed to read or might be empty. * @return fp (pointer to the file) */ FILE *openFile(int argc, char **argv); /** * Name: freeDataFields * Description: frees the memory allocated in a matrix. * @param dataFields (the matrix items to be freed) */ void freeDataFields(char **dataFields); /** * Name: systemCheck * Description: A function to control if mempory was allocated for pointer. * @param memory */ void systemCheck(void *memory); /** * Name: freeListItems * Description: frees the memory of the lists allocated items * @param ls: list to be freed */ void freeListItems(list *ls); /** * Name: comparefunc * Description: Compare function to be send to the list for comparing elements * in the list. * @param element1 * @param element2 * @return */ bool comparefunc(node *element1, node *element2); #endif //LINKEDLIST_MPASSWDSORT_H
C
/* Esercizio N 3 Fare la somma dei primi cento numeri */ // Studente: Rossi Edoardo Data:14/11/2016 Classe: 3 INA Numero: 17 #include<stdio.h> #include<stdlib.h> #include<math.h> main() { int Somma; // variabile che definisce la somma dei cento numeri int I; // variabile che definisce il contatore Somma=0; I=1; while(I<=100){ Somma=Somma+I; I=I+1; } printf("\nil valore della somma: %d", Somma); }
C
#include "matrix.h" #include <stdlib.h> #include <string.h> #include <math.h> const mat MAT_UNDEFINED = {0, 0, NULL}; mat allocateMat(unsigned int rows, unsigned int cols) { mat ret; ret.rows = rows; ret.cols = cols; ret.elements =mallloc(rows * sizeof(float)); for (unsigned int i = 0; i < rows; i++) { ret.elements[i] = malloc(cols *sizeof(float)); } } mat identity(unsigned int dim) { mat ret = allocateMat(dim, dim); for (unsigned int r = 0; r < dim; r++) { for (unsigned int c = 0; c < dim; c++) { ret.elements[r][c] = (r == c) ? 1.0f : 0.0f: } } return ret; } mat zeroMatrix(unsigned int rows, unsigned int cols) { mat ret = allocateMat(dim, dim); for (unsigned int r = 0; r < dim; r++) { for (unsigned int c = 0; c < dim; c++) { ret.elements[r][c] = 0.0f; } } return ret; } mat newMatrix(unsigned int row, unsigned int cols, ...) { mat ret = allocateMat(rows, cols); va_list; va_start(list, rows * cols); for (unsigned int r = 0; i < rows; r++) { for (unsigned int c = 0; c < cols; c++) { ret.elements[r][c] = va_arg(list, double); } } va_end(list); return ret; } mat copy(mat m); mat copyPtr(mat *m); void printMat(mat m ) { printf("\n"); for (unsigned int r =0; r < m.rows; r ++) { printf("\n"); printf("|"); for (unsigned int c = 0; c < m.cols; c++) { printf("%f", m.elements[r][c]); } printf("|"); } printf("\n"); }
C
#include <X11/Xlib.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <omp.h> typedef struct complextype { double real, imag; } Compl; int main(int argc, char *argv[] ) { Display *display; Window window; //initialization for a window int screen; //which screen GC gc; if(argc != 9) { printf("input error!"); return 0; } int thread_n, width, height, window_en, grid_size=10, grid_width, grid_height, gx, gy; double sx, bx, sy, by, t; thread_n = atoi(argv[1]); //{little, big} x {x, y} sx = atof(argv[2]); bx = atof(argv[3]); sy = atof(argv[4]); by = atof(argv[5]); width = atoi(argv[6]); height = atoi(argv[7]); window_en = 1-strcmp(argv[8],"enable"); grid_width = (width % grid_size) ? width/grid_size + 1 : width/grid_size; grid_height = (height % grid_size) ? height/grid_size + 1 : height/grid_size; int i, j; int *count = malloc(thread_n * sizeof(int) ); for (i=0; i<thread_n; i++) count[i] = 0; int **color_buf = (int **)malloc(width * sizeof(int *)); for (i=0; i<width; i++) color_buf[i] = (int *)malloc(height * sizeof(int)); /* open connection with the server */ if(window_en == 1){ display = XOpenDisplay(NULL); if(display == NULL) { fprintf(stderr, "cannot open display\n"); return 0; } screen = DefaultScreen(display); } /* set window position */ int x = 0; int y = 0; /* border width in pixels */ int border_width = 0; /* create window */ if(window_en == 1){ window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y, width, height, border_width,BlackPixel(display, screen), WhitePixel(display, screen)); /* create graph */ XGCValues values; long valuemask = 0; gc = XCreateGC(display, window, valuemask, &values); XSetForeground (display, gc, BlackPixel (display, screen)); XSetBackground(display, gc, 0X0000FF00); XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound); /* map(show) the window */ XMapWindow(display, window); XSync(display, 0); } /* draw points */ Compl z, c; int repeats, tid; double temp, lengthsq; //int i, j; t = omp_get_wtime(); #pragma omp parallel num_threads(thread_n) private(z, c, repeats, temp, lengthsq, i , j, tid) { #pragma omp for collapse(2) schedule(guided, 10) for(i = 0; i < width; i++) { for(j = 0; j < height; j++) { tid = omp_get_thread_num(); count[tid]++; z.real = 0.0; z.imag = 0.0; c.real = sx + i*(bx-sx)/(double)width; c.imag = sy + j*(by-sy)/(double)height; repeats = 0; lengthsq = 0.0; while(repeats < 100000 && lengthsq < 4.0) { temp = z.real*z.real - z.imag*z.imag + c.real; z.imag = 2*z.real*z.imag + c.imag; z.real = temp; lengthsq = z.real*z.real + z.imag*z.imag; repeats++; } color_buf[i][j]=repeats; } } printf("t=%f count:%d rank:%d \n", omp_get_wtime() - t, count[tid], tid); } if(window_en == 1){ for(i = 0; i < width; i++) { for(j = 0; j < height; j++) { XSetForeground (display, gc, 1024 * 1024 * (color_buf[i][j] % 256)); XDrawPoint (display, window, gc, i, j); } } XFlush(display); sleep(5); } free(color_buf); return 0; }
C
#include <stdio.h> #include <stdlib.h> typedef struct def_Elemento { int dato; struct def_Elemento *sig; struct def_Elemento *ant; }TipoElemento; void InsertaInicio (TipoElemento **Inicio, int numero); void InsertaFin(TipoElemento **Inicio, int numero); void ImprimirDerecha(TipoElemento *Inicio); void ImprimirIzquierda(TipoElemento *Inicio); void Borrar_Lista(TipoElemento *Inicio); int main(void) { TipoElemento *Primero=NULL; int valor; printf("Ingrese numeros (letra para terminar)\n"); while(scanf("%d",&valor)==1) InsertaFin(&Primero,valor); printf("Los valores son: \n"); ImprimirDerecha(Primero); ImprimirIzquierda(Primero); Borrar_Lista(Primero); } /*void InsertaInicio (TipoElemento **Inicio, int numero) { TipoElemento *temp; temp=(TipoElemento *)malloc(sizeof(TipoElemento)); temp->dato=numero; temp->ant=NULL; temp->sig=*Inicio; if(*Inicio!=NULL) *Inicio->ant=temp; *Inicio=temp; }*/ void InsertaFin(TipoElemento **Inicio, int numero) { TipoElemento *temp, *temp2; temp=(TipoElemento *)malloc(sizeof(TipoElemento)); temp->dato=numero; temp->sig=NULL; if(*Inicio!=NULL) { temp2=*Inicio; while(temp2->sig!=NULL) temp2=temp2->sig; temp->ant=temp2; temp2->sig=temp; } else { temp->ant=NULL; *Inicio=temp; } } void ImprimirDerecha(TipoElemento *Inicio) { TipoElemento *temp; temp=Inicio; while(temp!=NULL) { printf("%d\n",temp->dato); temp=temp->sig; } } void ImprimirIzquierda(TipoElemento *Inicio) { TipoElemento *temp; temp=Inicio; while(temp->sig!=NULL) { temp=temp->sig; } while(temp!=NULL) { printf("%d\n",temp->dato); temp=temp->ant; } } void Borrar_Lista(TipoElemento *Inicio) { TipoElemento *temp; temp=Inicio; while(temp!=NULL) { Inicio=Inicio->sig; free(temp); temp=Inicio; } }
C
#include <stdio.h> int main(void) { int sum=0; int input=0; int i; /*INDEX */ while(scanf("%d",&input)!=EOF) { sum=0; while(input%2 == 0) { input/=2; sum+=2; } for(i=3; i*i<=input && input != 1; i+=2) { while(input%i == 0) { input/=i; sum+=i; } } if(input != 1) { sum+=input; } printf("%d\n",sum); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX 10000 typedef struct proizvod{int sifra; int zapremina; char naziv[51];} Proizvod; typedef struct elem{Proizvod p; struct elem *sl;}Elem; typedef struct elem1{Elem e; struct elem1 *sl;}Elem1; Elem *na_kraj(Elem *prvi, Proizvod pp){ Elem *novi, *tek; novi=(Elem*)malloc(sizeof(Elem)); if(novi==NULL) exit(2); novi->p.sifra=pp.sifra; novi->p.zapremina=pp.zapremina; strcpy(novi->p.naziv,pp.naziv); novi->sl=NULL; if(prvi==NULL) prvi=novi; else for(tek=prvi;tek->sl;tek=tek->sl); tek->sl=novi; return(prvi); } void sortiraj_listu(Elem *prvi){ Elem *tek1, *tek2; int sifra, zapremina; char naziv[51]; tek1=prvi; while(tek1->sl){ tek2=tek->sl; while(tek2){ if(tek2->p.zapremina>tek1->p.zapremina) zapremina=tek1->p.zapremina; tek1->p.zapremina=tek2->p.zapremina; tek2->p.zapremina=zapremina; sifra=tek1->p.sifra; tek1->p.sifra=tek2->p.sifra; tek2->p.sifra=sifra; strcpy(naziv,tek1->p.naziv); strcpy(tek1->p.naziv, tek2->p.naziv); strcpy(tek->p.naziv,naziv); tek2=tek2->sl; } tek1=tek1->sl; } } void obrada(Elem *prvi){ Elem *tek=prvi, *tek1; int ukupna_zapremina, br; Elem1 *novi; while(tek){ novi=(Elem1*)malloc(sizeof(Elem1)); if(novi==NULL) exit(3); novi=tek; ukupna_zapremina=tek->p.zapremina; tek1=tek->sl; br=0; while(tek1){ if(tek1->p.zapremina+ukupna_zapremina<=MAX){ tek1=tek1->sl; } else } } void brisi(Elem *prvi){ Elem *tek; while(prvi){ tek=prvi; prvi=prvi->sl; free(tek); } } void main(){ Elem *prvi=NULL, tek FILE *posiljka; Posiljka pp; posiljka=fopen("posiljka.txt", "r"); if(!posiljka) exit(1); while(!feof(posiljka)){ if(fscanf("%d %d %s \n", &pp.sifra, &pp.zapremina, pp.naziv)==EOF) break; prvi=na_kraj(prvi,pp); } sortiraj_listu(prvi); obrada(prvi); brisi(prvi); }
C
/**************************************************************************** * caesar.c * * Provotorov Daniil * [email protected] * * Cipher text via caesar cipher * ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <cs50.h> #include <string.h> #include <ctype.h> int main(int argc, string argv[]) { if (argc != 2) // проверка на 2 агрумента командной строки { printf("Введите одно значение ключа\n"); // если аргументов не 2 - вернули ошибку return 1; } int key = atoi(argv[1]); // вытащили ключ из аргумента printf("plaintext: "); string plaintext = get_string(); // запросили строку текста printf("ciphertext: "); for (int i = 0, n = strlen(plaintext); i < n; i ++) //проходимся по тексту { if (isupper(plaintext[i])) // что делать, если верхняя буква { int alphabetic_index0 = plaintext[i] - 65; int alphabetic_index1 = (alphabetic_index0 + key) % 26; int cipherletter = 65 + alphabetic_index1; printf("%c", (char) cipherletter); } else if (islower(plaintext[i])) // что делать, если нижняя буква { int alphabetic_index0 = plaintext[i] - 97; int alphabetic_index1 = (alphabetic_index0 + key) % 26; int cipherletter = 97 + alphabetic_index1; printf("%c", (char) cipherletter); } else { printf("%c", (char) plaintext[i]); } } printf("\n"); return 0; }
C
/** Ƕ ǶǶһʱ,ְһ ,main()ⶨ ׳ s=(2^2)!+(3^2)! ˼·:Ƕ׵ԭ,һƽsquare һ׳factorial(׳) ȵsquareٰsquareֵΪʵΣ ٵfactorialٷsquareٷ **/ #include <stdio.h> int square(int p); int factorial(int q); //ǰ void main() { int a=2, b=0; for(a=2; a<=3; a++) { b=b+square(a);//square } printf("%d", b); } int square(int p) //square,ʽҪһ { int j, k; j = p * p; k = factorial(j); //squareֵfactorial return k; //صǾfactorialֵ //kصintٸa } int factorial(int q)//factorial,Ҫһ { int l=1; for(q; q>0; q--) { l=l*q; } return l; //lֵصڸk }
C
/*Many studies suggest that smiling has benefits. Write a program that produces the following output: Smile!Smile!Smile! Smile!Smile! Smile! Have the program define a function that displays the string Smile! once, and have the program use the function as often as needed.*/ #include<stdio.h> void smile(); int main(void) { smile(); smile(); smile(); printf("\n"); smile(); smile(); printf("\n"); smile(); return 0; } void smile() { printf("Smile!"); }
C
// hooded cloak by *Styx* to shade eyes for light sensitivity #include <std.h> inherit "/std/armour"; void create() { ::create(); set_name("hooded cloak"); set_id( ({ "cloak", "hooded cloak" }) ); set_short("A hooded cloak"); set_long("This is a hooded cloak woven from a dark, dense, soft cloth " "that does not reflect much light. The cloth is tightly woven " "and is heavy enough that the hood can help shade sensitive eyes " "from sunlight or bright room lighting." ); set_weight(10); set_value(30); set_type("clothing"); set_limbs( ({ "neck" }) ); set_ac(0); set_size(2); set_wear((:TO,"wearme":)); set_remove((:TO,"removeme":)); } int wearme() { tell_object(ETO,"As you pull on the cloak, the hood helps shade your eyes " "from bright lights."); ETO->add_sight_bonus(-2); return 1; } int removeme() { tell_object(ETO,"Your eyes adjust to no longer being shaded from light as you " "remove the cloak."); ETO->add_sight_bonus(2); return 1; } int is_metal() { return 0; }
C
#include "holberton.h" #include <stdlib.h> /** * *create_array - creates an array of chars, and initializes it with a char * @size: size of the array * @c: char to be initialized with * Return: pointer to array or null **/ char *create_array(unsigned int size, char c) { char *str; unsigned int i; if (size == 0) return (NULL); str = malloc(sizeof(char) * size); if (str == NULL) return (NULL); i = 0; while (i < size) { str[i] = c; i++; } return (str); }
C
#include <stdio.h> int main() { int n,i,count=0,arr[100],n2; printf("How many numbers? "); scanf("%d",&n); printf("\nEnter the numbers : "); for(i=0; i<n; i++) { scanf("%d",&arr[i]); } printf("\nEnter the search key : "); scanf("%d",&n2); for(i=0; i<n; i++) { if(n2==arr[i]) { printf("\nFound at position %d",count); break; } count++; if(n==count) { printf("\nNOT FOUND"); break; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> /* sockaddr, sa_family_t, socklen_t */ #include <netinet/in.h> /* in_port_t, in_addr_t, sa_family_t, sockaddr_in */ #include <pthread.h> #include "02.data_transfer.h" #include <fcntl.h> /* File open option */ #include <dirent.h> /* This file to use readdir function */ #define PORT 8081 int socket_init(int *accept_fd); void *server_control_task(void * arg); void server_list_file_send(int accept_fd); void server_data_file_send(int accept_fd, char* file_name); static int private_sever_data_file_send(int accept_fd, char* file_name); int main(int argc, char const *argv[]) { /* Define variable to manage socket */ int accept_fd = 0; int result = 0; pthread_t thread = 0; printf("accept_fd: %d\n", accept_fd); /* Init socket and get a fd to read and write file */ result = socket_init(&accept_fd); if(result < 0) { return -1; } printf("accept_fd before thread create: %d\n", accept_fd); /* Create task to receive request and send file data */ pthread_create(&thread, NULL, server_control_task, (void *)&accept_fd); pthread_join(thread, NULL); return 0; } int socket_init(int *accept_fd) { /* Define variable to manage socket */ int socket_fd = 0; struct sockaddr_in address; int addrlen = sizeof(address); /* Creating socket file descriptor */ if((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) { printf("Socket create failed\n"); return -1; } /* Set address to bind from server */ address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); /* Bind the socket to port 8080 */ if(bind(socket_fd, (struct sockaddr *)&address, sizeof(address)) < 0) { printf("Bind socket failed\n"); return -1; } printf("Listen to client connect\n"); /* Listen for the connection from client */ if(listen(socket_fd, 3) < 0) { printf("Listen failed\n"); return -1; } /* Accept the connection */ if((*accept_fd = accept(socket_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) { printf("Accept failed\n"); return -1; } printf("accept_fd value: %d\n", *accept_fd); return 0; } /* Server proccessing center */ void * server_control_task(void * arg) { int accept_fd = * (int *)arg; TRANFER_MESSAGE_ST message = {0}; printf("accept_fd: %d\n", accept_fd); while(1) { /* Receive request from client */ memset(&message, 0, sizeof(message)); read(accept_fd, &message, sizeof(message)); switch(message.request) { case CL_SRV_REQUEST_SEND_FILE: printf("Client request send file: %s\n", message.data); server_data_file_send(accept_fd, message.data); break; case CL_SRV_REQUEST_FILE_LIST: printf("Client request file list\n"); server_list_file_send(accept_fd); break; default: break; } } } void server_list_file_send(int accept_fd) { TRANFER_MESSAGE_ST message = {0}; /*Get file list to send to client */ DIR *dir = NULL; /* Pointer to directiry entry */ struct dirent *de; /* Open current dir */ dir = opendir("."); /* Read current dir to get all file name */ while((de = readdir(dir)) != NULL) { /* Ignore hidden file */ if(de->d_name[0] != '.') { /*printf("%s\n", de->d_name);*/ memset(&message, 0, sizeof(message)); /* Copy file name to message data */ snprintf(message.data, strlen(de->d_name) + 1, "%s", de->d_name); /* Send message to client */ message.request = SRV_CL_SEND_FILE_LIST; send(accept_fd, &message, sizeof(message), 0); } } closedir(dir); } void server_data_file_send(int accept_fd, char *file_name) { TRANFER_MESSAGE_ST message = {0}; /*Get file list to send to client */ DIR *dir = NULL; /* Pointer to directiry entry */ struct dirent *de; /* Open current dir */ dir = opendir("."); /* Read current dir to get all file name */ while((de = readdir(dir)) != NULL) { /* Ignore hidden file */ if(de->d_name[0] != '.') { /* If file exist */ if(strncmp(de->d_name, file_name, strlen(file_name)) == 0) { /* Send file exist to client */ message.request = SRV_CL_SEND_FILE_EXIST; send(accept_fd, &message, sizeof(message), 0); /* Send file data to client */ private_sever_data_file_send(accept_fd, file_name); closedir(dir); return; } } } /* Send message to client */ message.request = SRV_CL_SEND_FILE_NOT_EXIST; send(accept_fd, &message, sizeof(message), 0); return; } static int private_sever_data_file_send(int accept_fd, char* file_name) { int fd = 0; /* Character variable to read file */ char c = 0; /* Buffer to store data to save sending time */ char buff[128] = {0}; /* Index to manage the buffer status */ unsigned int index = 0; TRANFER_MESSAGE_ST message = {0}; fd = open(file_name, O_RDONLY); if(fd < 0) { printf("Open file failed\n"); return -1; } /* Loop to read all data file */ while(read(fd, &c, 1) != 0) { /* Read data byte one by one, if not EOF push data to buffer */ buff[index] = c; index++; if(index == sizeof(buff)) { memset(message.data, 0, sizeof(message.data)); memcpy(message.data, buff, sizeof(buff)); message.request = SRV_CL_SEND_FILE_DATA; send(accept_fd, &message, sizeof(message), 0); index = 0; } } /* Finish the loop and data not full the buff */ if((0 < index) && (index < sizeof(buff))) { memset(message.data, 0, sizeof(message.data)); memcpy(message.data, buff, index); message.request = SRV_CL_SEND_FILE_DATA; send(accept_fd, &message, sizeof(message), 0); index = 0; } message.request = SRV_CL_SEND_FILE_END; send(accept_fd, &message, sizeof(message), 0); close(fd); return 0; }
C
/* Copyright Digital Equipment Corporation & INRIA 1988, 1989 */ /* Last modified_on Fri Mar 2 16:49:23 GMT+1:00 1990 by herve */ /* modified_on Mon Feb 19 20:22:20 GMT+1:00 1990 by shand */ /* KerN.c: the kernel written in C */ /* * Description of types and constants. * * Several conventions are used in the commentary: * A "BigNum" is the name for an infinite-precision number. * Capital letters (e.g., "N") are used to refer to the value of BigNums. * The word "digit" refers to a single BigNum digit. * The notation "Size(N)" refers to the number of digits in N, * which is typically passed to the subroutine as "nl". * The notation "Length(N)" refers to the number of digits in N, * not including any leading zeros. * The word "Base" is used for the number 2 ** BN_DIGIT_SIZE, where * BN_DIGIT_SIZE is the number of bits in a single BigNum digit. * The expression "BBase(N)" is used for Base ** NumDigits(N). * The term "leading zeros" refers to any zeros before the most * significant digit of a number. * * * In the code, we have: * * "nn" is a pointer to a big number, * "nl" is the number of digits from nn, * "d" is a digit. * */ /* */ #define BNNMACROS_OFF #include "BigNum.h" /*** copyright ***/ static char copyright[]="@(#)KerN.c: copyright Digital Equipment Corporation & INRIA 1988, 1989\n"; /******* non arithmetic access to digits ********/ void BnnSetToZero (nn, nl) register BigNum nn; register int nl; /* * Sets all the specified digits of the BigNum to 0 */ { #ifdef NOMEM while (--nl >= 0) *(nn++) = 0; #else bzero (nn, nl*BN_DIGIT_SIZE/BN_BYTE_SIZE); #endif } /***************************************/ void BnnAssign (mm, nn, nl) register BigNum mm, nn; register int nl; /* * Copies N => M */ { if (mm < nn || mm > nn+nl) #ifdef NOMEM while (--nl >= 0) *mm++ = *nn++; #else /* be care: bcopy (SRC, DEST, L): SRC-->DEST !!! */ bcopy (nn, mm, nl*BN_DIGIT_SIZE/BN_BYTE_SIZE); #endif else if (mm > nn) { nn += nl; mm += nl; while (--nl >= 0) *--mm = *--nn; } } /***************************************/ /* */ void BnnSetDigit (nn, d) BigNum nn; int d; /* * Sets a single digit of N to the passed value */ { *nn = d; } /***************************************/ BigNumDigit BnnGetDigit (nn) BigNum nn; /* * Returns the single digit pointed by N */ { return (*nn); } /***************************************/ /* */ BigNumLength BnnNumDigits (nn, nl) register BigNum nn; register int nl; /* * Returns the number of digits of N, not counting leading zeros */ { nn += nl; while (nl != 0 && *--nn == 0) nl--; return (nl == 0 ? 1 : nl); } /***************************************/ BigNumDigit BnnNumLeadingZeroBitsInDigit (d) BigNumDigit d; /* * Returns the number of leading zero bits in a digit */ { register BigNumDigit mask = 1 << (BN_DIGIT_SIZE - 1); register int p = 0; if (d == 0) return (BN_DIGIT_SIZE); while ((d & mask) == 0) { p++; mask >>= 1; } return (p); } /***************************************/ /* */ /************** Predicates on one digit ***************/ Boolean BnnDoesDigitFitInWord (d) BigNumDigit d; /* * Returns TRUE iff the digit can be represented in just BN_WORD_SIZE bits */ { /* The C compiler must evaluate the predicate at compile time */ if (BN_DIGIT_SIZE > BN_WORD_SIZE) return (d >= 1 << BN_WORD_SIZE ? FALSE : TRUE); else return (TRUE); } /***************************************/ Boolean BnnIsDigitZero (d) BigNumDigit d; /* Returns TRUE iff digit = 0 */ { return (d == 0); } /***************************************/ Boolean BnnIsDigitNormalized (d) BigNumDigit d; /* * Returns TRUE iff Base/2 <= digit < Base * i.e., if digit's leading bit is 1 */ { return (d & (1 << (BN_DIGIT_SIZE - 1)) ? TRUE : FALSE); } /***************************************/ Boolean BnnIsDigitOdd (d) BigNumDigit d; /* * Returns TRUE iff digit is odd */ { return (d & 1 ? TRUE : FALSE); } /***************************************/ BigNumCmp BnnCompareDigits (d1, d2) BigNumDigit d1, d2; /* * Returns BN_GREATER if digit1 > digit2 * BN_EQUAL if digit1 = digit2 * BN_LESS if digit1 < digit2 */ { return (d1 > d2 ? BN_GT : (d1 == d2 ? BN_EQ : BN_LT)); } /***************** Logical operations ********************/ void BnnComplement (nn, nl) register BigNum nn; register int nl; /* * Performs the computation BBase(N) - N - 1 => N */ { while (--nl >= 0) *(nn++) ^= -1; } /***************************************/ /* */ void BnnAndDigits (n, d) BigNum n; BigNumDigit d; /* * Returns the logical computation n[0] AND d in n[0] */ { *n &= d; } /***************************************/ void BnnOrDigits (n, d) BigNum n; BigNumDigit d; /* * Returns the logical computation n[0] OR d2 in n[0]. */ { *n |= d; } /***************************************/ void BnnXorDigits (n, d) BigNum n; BigNumDigit d; /* * Returns the logical computation n[0] XOR d in n[0]. */ { *n ^= d; } /***************************************/ /* */ /****************** Shift operations *******************/ BigNumDigit BnnShiftLeft (mm, ml, nbits) register BigNum mm; register int ml; int nbits; /* * Shifts M left by "nbits", filling with 0s. * Returns the leftmost "nbits" of M in a digit. * Assumes 0 <= nbits < BN_DIGIT_SIZE. */ { register BigNumDigit res = 0, save; int rnbits; if (nbits != 0) { rnbits = BN_DIGIT_SIZE - nbits; while (--ml >= 0) { save = *mm; *mm++ = (save << nbits) | res; res = save >> rnbits; } } return (res); } /***************************************/ /* */ BigNumDigit BnnShiftRight (mm, ml, nbits) register BigNum mm; register int ml; int nbits; /* * Shifts M right by "nbits", filling with 0s. * Returns the rightmost "nbits" of M in a digit. * Assumes 0 <= nbits < BN_DIGIT_SIZE. */ { register BigNumDigit res = 0, save; int lnbits; if (nbits != 0) { mm += ml; lnbits = BN_DIGIT_SIZE - nbits; while (--ml >= 0) { save = *(--mm); *mm = (save >> nbits) | res; res = save << lnbits; } } return (res); } /***************************************/ /* */ /******************* Additions **************************/ BigNumCarry BnnAddCarry (nn, nl, carryin) register BigNum nn; register int nl; BigNumCarry carryin; /* * Performs the sum N + CarryIn => N. * Returns the CarryOut. */ { if (carryin == 0) return (0); if (nl == 0) return (1); while (--nl >= 0 && !(++(*nn++))) ; return (nl >= 0 ? 0 : 1); } /***************************************/ /* */ BigNumCarry BnnAdd (mm, ml, nn, nl, carryin) register BigNum mm, nn; int ml; register int nl; BigNumCarry carryin; /* * Performs the sum M + N + CarryIn => M. * Returns the CarryOut. * Assumes Size(M) >= Size(N). */ { register BigNumProduct c = carryin; ml -= nl; /* test computed at compile time */ if (sizeof (BigNumProduct) > sizeof (BigNumDigit)) { while (--nl >= 0) { c += *mm + *(nn++); *(mm++) = c; c >>= BN_DIGIT_SIZE; } } else { register BigNumProduct save; while (--nl >= 0) { save = *mm; c += save; if (c < save) { *(mm++) = *(nn++); c = 1; } else { save = *(nn++); c += save; *(mm++) = c; c = (c < save) ? 1 : 0; } } } return (BnnAddCarry (mm, ml, (BigNumCarry) c)); } /***************************************/ /* */ /****************** Subtraction *************************/ BigNumCarry BnnSubtractBorrow (nn, nl, carryin) register BigNum nn; register int nl; BigNumCarry carryin; /* * Performs the difference N + CarryIn - 1 => N. * Returns the CarryOut. */ { if (carryin == 1) return (1); if (nl == 0) return (0); #ifdef ibm032 while (--nl >= 0 && !(*nn)--) nn++; #else while (--nl >= 0 && !((*nn++)--)) ; #endif return (nl >= 0 ? 1 : 0); } /***************************************/ /* */ BigNumCarry BnnSubtract (mm, ml, nn, nl, carryin) register BigNum mm, nn; int ml; register int nl; BigNumCarry carryin; /* * Performs the difference M - N + CarryIn - 1 => M. * Returns the CarryOut. * Assumes Size(M) >= Size(N). */ { register BigNumProduct c = carryin; register BigNumDigit invn; ml -= nl; /* test computed at compile time */ if (sizeof (BigNumProduct) > sizeof (BigNumDigit)) { while (--nl >= 0) { invn = *(nn++) ^ -1; c += *mm + invn; *(mm++) = c; c >>= BN_DIGIT_SIZE; } } else { register BigNumProduct save; while (--nl >= 0) { save = *mm; invn = *(nn++) ^ -1; c += save; if (c < save) { *(mm++) = invn; c = 1; } else { c += invn; *(mm++) = c; c = (c < invn) ? 1 : 0; } } } return (BnnSubtractBorrow (mm, ml, (BigNumCarry) c)); } /***************************************/ /* */ /***************** Multiplication ************************/ BigNumCarry BnnMultiplyDigit (pp, pl, mm, ml, d) register BigNum pp, mm; int pl, ml; BigNumDigit d; /* * Performs the product: * Q = P + M * d * BB = BBase(P) * Q mod BB => P * Q div BB => CarryOut * Returns the CarryOut. * Assumes Size(P) >= Size(M) + 1. */ { register BigNumProduct c = 0; if (d == 0) return (0); if (d == 1) return (BnnAdd (pp, pl, mm, ml, (BigNumCarry) 0)); pl -= ml; /* test computed at compile time */ if (sizeof (BigNumProduct) > sizeof (BigNumDigit)) { while (ml != 0) { ml--; c += *pp + (d * (*(mm++))); *(pp++) = c; c >>= BN_DIGIT_SIZE; } while (pl != 0) { pl--; c += *pp; *(pp++) = c; c >>= BN_DIGIT_SIZE; } return (c); } else { /* help for stupid compilers--may actually be counter productive on pipelined machines with decent register allocation!! */ #define m_digit X0 #define X3 Lm #define X1 Hm register BigNumDigit Lm, Hm, Ld, Hd, X0, X2 /*, X1, X3 */; Ld = d & ((1 << (BN_DIGIT_SIZE / 2)) -1); Hd = d >> (BN_DIGIT_SIZE / 2); while (ml != 0) { ml--; m_digit = *mm++; Lm = m_digit & ((1 << (BN_DIGIT_SIZE / 2)) -1); Hm = m_digit >> (BN_DIGIT_SIZE / 2); X0 = Ld * Lm; X2 = Hd * Lm; X3 = Hd * Hm; X1 = Ld * Hm; if ((c += X0) < X0) X3++; if ((X1 += X2) < X2) X3 += (1<<(BN_DIGIT_SIZE / 2)); X3 += (X1 >> (BN_DIGIT_SIZE / 2)); X1 <<= (BN_DIGIT_SIZE / 2); if ((c += X1) < X1) X3++; if ((*pp += c) < c) X3++; pp++; c = X3; #undef m_digit #undef X1 #undef X3 } X0 = *pp; c += X0; *(pp++) = c; if (c >= X0) return (0); pl--; while (pl != 0 && !(++(*pp++))) pl--; return (pl != 0 ? 0 : 1); } } #ifdef mips BigNumCarry BnnMultiply2Digit (pp, pl, mm, ml, d0, d1) register BigNum pp, mm; register int pl, ml; BigNumDigit d0, d1; /* * Provided for compatibility with mips assembler implementation. * Performs the product: * Q = P + M * d0_d1 * BB = BBase(P) * Q mod BB => P * Q div BB => CarryOut * Returns the CarryOut. * Assumes Size(P) >= Size(M) + 1. */ { return BnnMultiplyDigit (pp, pl, mm, ml, d0) + BnnMultiplyDigit (pp+1, pl-1, mm, ml, d1); } #endif mips /***************************************/ /* */ /********************** Division *************************/ /* xh:xl -= yh:yl */ #define SUB(xh,xl,yh,yl) if (yl > xl) {xl -= yl; xh -= yh + 1;}\ else {xl -= yl; xh -= yh;} #define LOW(x) (x & ((1 << (BN_DIGIT_SIZE / 2)) -1)) #define HIGH(x) (x >> (BN_DIGIT_SIZE / 2)) #define L2H(x) (x << (BN_DIGIT_SIZE / 2)) BigNumDigit BnnDivideDigit (qq, nn, nl, d) register BigNum qq, nn; register int nl; BigNumDigit d; /* Performs the quotient: N div d => Q * Returns R = N mod d * Assumes leading digit of N < d, and d > 0. */ { /* test computed at compile time */ if (sizeof (BigNumProduct) > sizeof (BigNumDigit)) { register BigNumProduct quad; nn += nl; nl--; qq += nl; quad = *(--nn); while (nl != 0) { nl--; quad = (quad << BN_DIGIT_SIZE) | *(--nn); *(--qq) = quad / d; quad = quad % d; } return (quad); } else { int k; int orig_nl; BigNumDigit rh; /* Two halves of current remainder */ BigNumDigit rl; /* Correspond to quad above */ register BigNumDigit qa; /* Current appr. to quotient */ register BigNumDigit ph, pl; /* product of c and qa */ BigNumDigit ch, cl, prev_qq; /* Normalize divisor */ k = BnnNumLeadingZeroBitsInDigit (d); if (k != 0) { prev_qq = qq[-1]; orig_nl = nl; d <<= k; BnnShiftLeft (nn, nl, k); } nn += nl; nl--; qq += nl; ch = HIGH (d); cl = LOW (d); rl = *(--nn); while (nl != 0) { nl--; rh = rl; rl = *(--nn); qa = rh / ch; /* appr. quotient */ /* Compute ph, pl */ pl = cl * qa; ph = ch * qa; ph += HIGH (pl); pl = L2H (pl); /* While ph:pl > rh:rl, decrement qa, adjust qh:ql */ while (ph > rh || ph == rh && pl > rl) { qa--; SUB (ph, pl, ch, L2H (cl)); } SUB (rh, rl, ph, pl); /* Top half of quotient is correct; save it */ *(--qq) = L2H (qa); qa = (L2H (rh) | HIGH (rl)) / ch; /* Approx low half of q */ /* Compute ph, pl, again */ pl = cl * qa; ph = ch * qa; ph += HIGH (pl); pl = LOW (pl) | L2H (LOW (ph)); ph = HIGH (ph); /* While ph:pl > rh:rl, decrement qa, adjust qh:ql */ while (ph > rh || ph == rh && pl > rl) { qa--; SUB (ph, pl, 0, d); } /* Subtract ph:pl from rh:rl; we know rh will be 0 */ rl -= pl; *qq |= qa; } /* Denormalize dividend */ if (k != 0) { if((qq > nn) && (qq < &nn[orig_nl])) { /* Overlap between qq and nn. Care of *qq! */ orig_nl = (qq - nn); BnnShiftRight (nn, orig_nl, k); nn[orig_nl - 1] = prev_qq; } else if(qq == nn) { BnnShiftRight(&nn[orig_nl - 1], 1, k); } else { BnnShiftRight (nn, orig_nl, k); } } return (rl >> k); } } /***************************************/
C
#include <stdio.h> #include <stdlib.h> int main() { int dia, mes, anio; printf("Ingrese la fecha de Nacimiento (dd/mm/aaaa): "); scanf("%2d/%2d/%4d",&dia, &mes, &anio); printf("\n%02d/%02d/%4d",dia, mes, anio); return 0; }
C
#include <stdio.h> long power(int base, int exponent); int main(){ long int answer; int base,exponent; printf("Enter base integer: "); scanf("%d",&base); printf("Enter exponent integer: "); scanf("%d",&exponent); answer=power(base,exponent); printf("%d raised to the power %d is %ld\n", base, exponent, answer); } long power(int base, int exponent){ long int answer; answer=base; for (int indx=0; indx<exponent-1; indx++) answer *= base; return answer; }
C
#include "ping_ka.h" int main(int argc, char *argv[]) { int sockfd; char *ip_addr, *reverse_hostname; struct sockaddr_in addr_con; int addrlen = sizeof(addr_con); char net_buf[NI_MAXHOST]; if(argc!=2) { printf("\nFormat %s <address>\n", argv[0]); return 0; } ip_addr = dns_lookup(argv[1], &addr_con); if(ip_addr==NULL) { printf("\nDNS lookup failed! Could not resolve hostname!\n"); return 0; } reverse_hostname = reverse_dns_lookup(ip_addr); printf("\nTrying to connect to '%s' IP: %s\n", argv[1], ip_addr); printf("\nReverse Lookup domain: %s", reverse_hostname); //socket() sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if(sockfd<0) { printf("\nSocket file descriptor not received!!\n"); return 0; } else printf("\nSocket file descriptor %d received\n", sockfd); signal(SIGINT, intHandler);//catching interrupt //send pings continuously send_ping(sockfd, &addr_con, reverse_hostname, ip_addr, argv[1]); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_misc.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jjolivot <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/20 22:20:56 by jjolivot #+# #+# */ /* Updated: 2018/09/20 22:24:32 by jjolivot ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/ft_ls.h" char ft_filetype(int mod) { if (S_ISREG(mod)) return ('-'); if (S_ISDIR(mod)) return ('d'); if (S_ISLNK(mod)) return ('l'); if (S_ISCHR(mod)) return ('c'); if (S_ISBLK(mod)) return ('b'); if (S_ISFIFO(mod)) return ('p'); if (S_ISSOCK(mod)) return ('s'); return ('?'); } char *ft_file_and_permissions(int mod) { char *str; str = (char *)malloc(sizeof(str) * 10 + 1); str[0] = ft_filetype(mod); str[1] = (S_IRUSR & mod ? 'r' : '-'); str[2] = (S_IWUSR & mod ? 'w' : '-'); str[3] = (S_IXUSR & mod ? 'x' : '-'); str[4] = (S_IRGRP & mod ? 'r' : '-'); str[5] = (S_IWGRP & mod ? 'w' : '-'); str[6] = (S_IXGRP & mod ? 'x' : '-'); str[7] = (S_IROTH & mod ? 'r' : '-'); str[8] = (S_IWOTH & mod ? 'w' : '-'); str[9] = (S_IXOTH & mod ? 'x' : '-'); if (S_ISVTX & mod && str[9] == 'x') str[9] = 't'; else if (S_ISVTX & mod) str[9] = 'T'; str[10] = '\0'; return (str); }
C
// given elements in array. add if its even else subtract. #include <stdio.h> int f(int *a, int n) { if (n == 0) return 0; if (*a % 2 == 0) // Even return *a + f(a + 1, n - 1); else return *a - f(a + 1, n - 1); } int main() { int a[] = {12, 7, 13, 4, 11, 6}; printf("%d\n", f(a, 6)); return 0; }
C
/* * Created: Jan 2016 * Author: hyunsungkim <[email protected]> */ /** * Blink LED * * This example shows how to handle GPIO. Connect an LED to PB0 with properly valued resistor (e.g. 220 Ohm) */ #define F_CPU 8000000UL #include <avr/io.h> #include <util/delay.h> int main(void) { DDRB = 0x01; // To blink LED, set PB0 as output while (1) { PORTB = 0x01; // Apply HIGH (5V or 3.3V) to PB0 _delay_ms(1000); // Do nothing for some interval (I know it seems nonsense but, actually it's not 1000ms) PORTB = 0x00; // Apply LOW (0V) to PB0 _delay_ms(1000); // Do nothing for some interval } }
C
#include <Date.H> #include <iostream> #include <string> void prettyprint(Date date){ std::string postfix; if( date.day == 11 || date.day == 12 || date.day == 13) { postfix = "th"; } else if ( date.day == 1 || date.day == 21 || date.day == 31 ) { postfix = "st"; } else if ( date.day == 2 || date.day == 22 ) { postfix = "nd"; } else if ( date.day == 3 || date.day == 23 ) { postfix = "rd"; } else { postfix = "th";} switch( date.month){ case 1: std::cout << date.day << postfix << " January " << date.year << std::endl; break; case 2: std::cout << date.day << postfix << " Febuary " << date.year << std::endl; break; case 3: std::cout << date.day << postfix << " March " << date.year << std::endl; break; case 4 : std::cout << date.day << postfix << " April " << date.year << std::endl; break; case 5: std::cout << date.day << postfix << " May " << date.year << std::endl; break; case 6: std::cout << date.day << postfix << " June " << date.year << std::endl; break; case 7: std::cout << date.day << postfix << " July " << date.year << std::endl; break; case 8: std::cout << date.day << postfix << " August " << date.year << std::endl; break; case 9: std::cout << date.day << postfix << " September " << date.year << std::endl; break; case 10: std::cout << date.day << postfix << " October " << date.year << std::endl; break; case 11: std::cout << date.day << postfix << " November " << date.year << std::endl; break; case 12: std::cout << date.day << postfix << " December " << date.year << std::endl; break; default: std::cout << "Invalid Month" << std::endl; } } Date getDate(int day, int month, int year){ Date date {}; date.day = day; date.month = month; date.year = year; return date; } Date max(Date date1, Date date2){ if( date1.year > date2.year){ return date1; } else if ( date1.year < date2.year){ return date2; } else{ if( date1.month > date2.month){ return date1; } else if ( date1.month < date2.month){ return date2; } else{ if( date1.day > date2.day){ return date1; } else if ( date2.day > date1.day){ return date2; } else{ return date1; } } } } void swapDates(Date *date1, Date *date2){ Date temp { *date1 }; *date1 = *date2; *date2 = temp; } void setDateToJanNextYear(Date *date){ (*date).year = (*date).year + 1; (*date).month = 1; (*date).day = 1; }
C
# include <stdio.h> void main() { int a,b,c; } int add (int p,q) { } int subtract (int p,q) { return p-q; }
C
#include "global.h" // used for debugging and tracing execution. see client's ".getDebugCodes()" xdata u8 lastCode[2]; void sleepMillis(int ms) { int j; while (--ms > 0) { for (j=0; j<SLEEPTIMER;j++); // about 1 millisecond } } void sleepMicros(int us) { while (--us > 0) ; } void blink_binary_baby_lsb(u16 num, char bits) { EA=0; LED = 1; sleepMillis(1000); LED = 0; sleepMillis(500); bits -= 1; // 16 bit numbers needs to start on bit 15, etc.... for (; bits>=0; bits--) { if (num & 1) { sleepMillis(25); LED = 1; sleepMillis(550); LED = 0; sleepMillis(25); } else { sleepMillis(275); LED = 1; sleepMillis(50); LED = 0; sleepMillis(275); } num = num >> 1; } LED = 0; sleepMillis(1000); EA=1; } /* void blink_binary_baby_msb(u16 num, char bits) { LED = 1; sleepMillis(1500); LED = 0; sleepMillis(100); bits -= 1; // 16 bit numbers needs to start on bit 15, etc.... for (; bits>=0; bits--) { if (num & (1<<bits)) { LED = 0; sleepMillis(10); LED = 1; } else { LED = 1; sleepMillis(10); LED = 0; } sleepMillis(350); } LED = 0; sleepMillis(1500); }*/ /* FIXME: not convinced libc hurts us that much int memcpy(volatile xdata void* dst, volatile xdata void* src, u16 len) { u16 loop; for (loop^=loop;loop<len; loop++) { *(dst++) = *(src++); } return loop+1; } int memset(volatile xdata void* dst, const char ch, u16 len) { u16 loop; for (loop^=loop;loop<len; loop++) { *(ptr++) = 0; } return loop+1; } */ int strncmp(const char *s1, const char *s2, u16 n) { char tst; for (;n>0;n--) { tst = *s1 - *s2; if (tst) return tst; s1++; s2++; } return 0; } __code u8 sernum[] = { 'S','D','C','C','v', LE_WORD(SDCC) };
C
#include <sys/time.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "usage: io <file>\n"); exit(1); } int fd = open(argv[1], O_WRONLY|O_CREAT, S_IRWXU); assert(fd >= 0); char buffer[20] = { "hello world\n" }; int rc = write(fd, buffer, strlen(buffer)); assert(rc == strlen(buffer)); close(fd); return 0; }
C
#include <stdint.h> #include <string.h> #ifndef BUFFER_H #define BUFFER_H typedef struct _buffer { uint8_t* content; size_t length; /* amount of buffer used */ size_t capacity; /* total capacity of the buffer */ size_t offset; /* start next read/write here */ } buffer_t; buffer_t* buffer_init(); /* free the buffer and all contents return new buffer address */ buffer_t* buffer_destroy(buffer_t* buf); /* delete data and buffer return new buffer address */ void buffer_reset(buffer_t* buf); /* delete the requested content returns the number of bytes deleted */ size_t buffer_erase(buffer_t* buf, size_t length); /* seek to 'offset' in buffer returns the new offset (unchanged if offset is out of range) */ size_t buffer_seek(buffer_t* buf, size_t offset); size_t buffer_seek_start(buffer_t* buf); size_t buffer_seek_end(buffer_t* buf); /* read data from the buffer, 'data' should be an existing block of memory large enough to accomodate 'length' bytes returns the number of bytes read into 'data' */ size_t buffer_read(buffer_t* buf, uint8_t* data, size_t length); /* write data to the buffer, re-sizing the buffer as needed returns the number of bytes written */ size_t buffer_write(buffer_t* buf, const uint8_t* data, size_t length); size_t buffer_size(const buffer_t* buf); int buffer_terminate(buffer_t* buf); uint8_t* buffer_detach(buffer_t* buf); #endif
C
/* ** EPITECH PROJECT, 2020 ** My Defender ** File description: ** Windows related function */ #include "function.h" void give_player_item(item_t item, global_t *g) { for (int i = 0; i < 30; i++) if (g->player.inventory[i].item.init == 0) { g->player.inventory[i] = item; return; } } void drop_items(ennemi_t ennemi, global_t *g) { int random_rate = 0; int random_max = 0; int check = 0; for (int i = 0; g->items[i].item.init; i++) { check = 0; for (int j = 0; g->items[i].arr[j]; j++) if (my_strcmp(g->items[i].arr[j], ennemi.name)) check = 1; if (check == 0) continue; random_rate = rand() % 100; random_max = (rand() % (g->items[i].drop_max)) + 1; if (random_rate <= g->items[i].drop_rate) for (int j = 0; j < random_max; j++) give_player_item(g->items[i], g); } } void update_pos_item_in_inventory(global_t *g) { sfVector2f pos_ui; pos_ui.x = 1200 + 18; pos_ui.y = 300 + 14; for (int i = 0; i < 30; i++) { g->player.inventory[i].item.pos.x = pos_ui.x + (i % 6) * 89 + 5; g->player.inventory[i].item.pos.y = pos_ui.y + (i / 6) * 89 + 5; } pos_ui.x = 1075 + 18; for (int i = 30; i < 34; i++) { g->player.inventory[i].item.pos.x = pos_ui.x + 5; g->player.inventory[i].item.pos.y = pos_ui.y + (i - 30) * 89 + 5; } } void display_info_text_item(global_t *g, text_info_t text, \ sfVector2f pos, item_t item) { text.color = (sfColor) {246, 192, 0, 255}; text.pos = (v2f) {pos.x + 10, pos.y + 5}; text.data = my_strcat("Item name: ", my_strdup(item.item.name)); draw_text_ui(text, g->view_pos, g->window); text.pos.y += 50; text.data = my_strcat("Item sell price: ", my_itostr(item.price)); draw_text_ui(text, g->view_pos, g->window); text.pos.y += 50; if (item.level != 0) { text.data = my_strcat("Item level: ", my_itostr(item.level)); text.color = sfGreen; } else { text.data = my_strdup("Cannot be equipped"); text.color = sfRed; } draw_text_ui(text, g->view_pos, g->window); free(text.data); } void display_info_item(global_t *g) { static int init = 0; static gameobject_t bg; static text_info_t text; if (!init++) { bg = init_sprite("res/info_item.png", 450, 150, (v2f) {0, 0}); text = init_text_sys(30, NULL, (v2f) {0, 0}); sfText_setOutlineThickness(text.text, 2); } for (int i = 0; i < 34; i++) { if (hover_button_ui(g->player.inventory[i].item, g->window, g)) { bg.pos.x = g->player.inventory[i].item.pos.x - 460; bg.pos.y = g->player.inventory[i].item.pos.y - 35; draw_ui(bg, g->view_pos, g->window); display_info_text_item(g, text, bg.pos, g->player.inventory[i]); } } }
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_6__ TYPE_3__ ; typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ struct TYPE_6__ {scalar_t__ size; scalar_t__ max_size; int /*<<< orphan*/ device_count; } ; struct TYPE_5__ {int /*<<< orphan*/ path; } ; typedef TYPE_1__ PnP_AudioDevice ; typedef int /*<<< orphan*/ BOOL ; /* Variables and functions */ int /*<<< orphan*/ FALSE ; int /*<<< orphan*/ LockAudioDeviceList () ; int /*<<< orphan*/ TRUE ; int /*<<< orphan*/ UnlockAudioDeviceList () ; scalar_t__ WideStringSize (int /*<<< orphan*/ ) ; TYPE_3__* audio_device_list ; int /*<<< orphan*/ logmsg (char*) ; int /*<<< orphan*/ memcpy (char*,TYPE_1__*,int) ; BOOL AppendAudioDeviceToList(PnP_AudioDevice* device) { int device_info_size; /* Figure out the actual structure size */ device_info_size = sizeof(PnP_AudioDevice); device_info_size += WideStringSize(device->path); LockAudioDeviceList(); /* printf("list size is %d\n", audio_device_list->size); printf("device info size is %d bytes\n", device_info_size); */ /* We DON'T want to overshoot the end of the buffer! */ if (audio_device_list->size + device_info_size > audio_device_list->max_size) { /*printf("max_size would be exceeded! Failing...\n");*/ UnlockAudioDeviceList(); return FALSE; } /* Commit the device descriptor to the list */ memcpy((char*)audio_device_list + audio_device_list->size, device, device_info_size); /* Update the header */ audio_device_list->device_count ++; audio_device_list->size += device_info_size; UnlockAudioDeviceList(); logmsg("Device added to list\n"); return TRUE; }
C
#ifndef _GOOG_MACROS_H_ #define _GOOG_MACROS_H_ #include <stdlib.h> /** * Determines the minimum of two values. * * @param x The first value. * @param y The second value. */ #define goog_min(x, y) (((x) < (y)) ? (x) : (y)) /** * Determines the maximum of two values. * * @param x The first value. * @param y The second value. */ #define goog_max(x, y) (((x) < (y)) ? (y) : (x)) /** * Checks a pointer before calling free on it. * * @param p The pointer to the memory to free. */ #define goog_free(p) \ do { \ if (p) { \ free(p); \ } \ } while (0) /** * Returns value if the condition is true. * * @param cond The condition to test. * @param val The value to return. */ #define goog_return_if(cond, val) \ do { \ if ((cond)) { \ return (val); \ } \ } while (0) /** * Returns value if the pointer is NULL. * * @param ptr The pointer to check. * @param val The value to return. */ #define goog_return_if_null(ptr, val) \ do { \ if (!(ptr)) { \ return (val); \ } \ } while (0) /** * Bail by returning from the function if the pointer is NULL. * * @param cond The condition to test. */ #define goog_bail_if_null(ptr) \ do { \ if (!(ptr)) { \ return; \ } \ } while (0) /** * Bail by returning from the function if the condition is satisfied. * * @param cond The condition to test. */ #define goog_bail_if(cond) \ do { \ if (cond) { \ return; \ } \ } while (0) #endif /* _GOOG_MACROS_H_ */
C
// CODE FOR AN EXERCISE /* I Insere no início. F Insere no final. P Remove no final e imprime valor removido. D Remove no início e imprime valor removido. V Remove por valor e retorna a quantidade de itens removidos. E Remove por posição e retorna o valor removido. T Troca o valor da primeira ocorrencia do item pelo valor novo. C Retorna ocorrencias de valor. X Indica o final das operações e que a lista resultante deve ser impressa. */ #include "../linked_list.c" #define INSERT_BEGIN 'I' #define INSERT_FINAL 'F' #define REMOVE_FINAL 'P' #define REMOVE_BEGIN 'D' #define REMOVE_VAL 'V' #define REMOVE_POS 'E' #define CHANGE_FIRST 'T' #define COUNT 'C' #define END 'X' #define DEBUG 0 int datacmp(data da, data db) { return *(int*)da - *(int*)db; } int main() { char opcode; int v, v2; int runs = 0; unsigned int pos; list_t* list = createList(sizeof(int)); element_t* aux; int* p; #define bindp(a, b) 0*(a=b) + &a // READ COMMANDS AND INSERT DATA INTO THE LIST while (scanf("%c", &opcode) && opcode != END && (runs++ < 50)) { if (opcode == '\n' || opcode == ' ') continue; if (DEBUG) printf("Code: %c\n", opcode); if (opcode == REMOVE_FINAL) { removeLast(list, &v); printf("%d\n", v); } else if (opcode == REMOVE_BEGIN){ removeFirst(list, &v); printf("%d\n", v); } else { scanf("%d", &v); switch(opcode) { case INSERT_BEGIN: insertFirst(list, &v); break; case INSERT_FINAL: insertLast(list, &v); break; case REMOVE_VAL: printf("%d\n", removeVal(list, &v, &datacmp)); break; case REMOVE_POS: removeAt(list, &p, (unsigned int) v - 1); printf("%d\n", *p); free(p); break; case CHANGE_FIRST: scanf("%d", &((*findVal(list, &v, &datacmp, &pos))->val)); break; case COUNT: printf("%u\n", countVal(list, &v, &datacmp)); break; } } if (DEBUG) printList(list); } // PRINT THE LIST printf("\n"); if(list->size > 0){ aux = list->first; while (printf("%d\n", aux->val) && (aux = aux->next)); removeAll(list); } free(list); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "tree.h" #include "linkedlist.h" #ifndef QUEUE_H #define QUEUE_H // doubly linked list as queue typedef struct queue { int size; Node* head; Node* tail; } Queue; // Creates an empty queue // returns: an empty queue Queue* CreateQueue(); // Destroys a queue // INPUT: // queue - the queue to be destroyed void DestroyQueue(Queue* queue); // Checks if a queue is empty // INPUT: // queue - a queue to be check bool IsEmptyQueue(Queue* queue); // Adds a tree node to the tail of the queue // INPUT: // queue - a queue the node to be inserted to // node - a given node to insert to queue void Enqueue(Queue* queue, TreeNode* node); // Removes the first element of the queue // INPUT: // queue - a given queue // Returns: a treeNode TreeNode* Dequeue(Queue* queue); #endif // QUEUE_H
C
#include <stdio.h> #include <stdlib.h> typedef int DATA; typedef struct node { struct node* prev; DATA data; struct node* next; } NODE; typedef NODE* LIST; int addFirst(NODE** ppnode, DATA Data) { NODE* newNode = (NODE*)malloc(sizeof(NODE)); newNode->prev = NULL; newNode->data = Data; newNode->next = *ppnode; if (*ppnode == NULL) *ppnode = newNode; else { (*ppnode)->prev = newNode; (*ppnode) = newNode; } return 0; } int print(NODE* pnode) { if (pnode == NULL) { fprintf(stderr, "The list is empty.\n"); return -1; } while (pnode) { printf("%d ", pnode->data); pnode = pnode->next; } printf("\n"); return 0; } int printBack(NODE* pnode) { if (pnode == NULL) { fprintf(stderr, "The list is empty.\n"); return -1; } // traverse to the last node while (pnode) { if (pnode->next) pnode = pnode->next; else break; } // start printing while (pnode) { printf("%d ", pnode->data); if (pnode->prev) pnode = pnode->prev; else break; } printf("\n"); return 0; } int length(NODE* pnode) { int length = 0; for (; pnode; pnode = pnode->next) length++; return length; } DATA removeFirst(NODE** ppnode) { if (*ppnode == NULL) { fprintf(stderr, "Call to removeFirst failed. The list is already empty\n"); return -1; } NODE* pointerToRemovedNode = (*ppnode); DATA retValue = (*ppnode)->data; *ppnode = (*ppnode)->next; free(pointerToRemovedNode); return retValue; } int addLast(NODE** ppnode, DATA Data) { NODE* newNode = (NODE*)malloc(sizeof(NODE)); newNode->data = Data; newNode->next = NULL; newNode->prev = NULL; if (*ppnode == NULL) { *ppnode = newNode; return 0; } // traverse to the last node NODE* pnode = *ppnode; while (pnode) { if (pnode->next) pnode = pnode->next; else break; } pnode->next = newNode; newNode->prev = pnode; return 0; } DATA removeLast(NODE** ppnode) { if (length(*ppnode) == 0) { fprintf(stderr, "Call to remove last failed. The list is already empty."); return -1; } if (length(*ppnode) == 1) { return removeFirst(ppnode); } NODE* pnode = *ppnode; while (pnode->next->next) pnode = pnode->next; DATA retValue = pnode->next->data; free(pnode->next); pnode->next = NULL; return retValue; } DATA removePos(NODE** ppnode, int pos) { if (pos == 0) return removeFirst(ppnode); else if (pos == length(*ppnode)) return removeLast(ppnode); NODE* pnode = *ppnode; while (pnode && --pos) { if (pnode->next) pnode = pnode->next; else { fprintf(stderr, "List index out of bound\n"); return -1; } } NODE* temp = pnode->next; pnode->next = temp->next; free(temp); return 0; } int addPos(NODE** ppnode, DATA Data, int pos) { if (pos == 0) return addFirst(ppnode, Data); else if (pos == length(*ppnode)) return addLast(ppnode, Data); NODE* pnode = *ppnode; while (pnode && --pos) { if (pnode->next) pnode = pnode->next; else { fprintf(stderr, "List index out of bound\n"); return -1; } } NODE* newNode = (NODE*)malloc(sizeof(NODE)); newNode->data = Data; newNode->next = pnode->next; newNode->prev = pnode; pnode->next->prev = newNode; pnode->next = newNode; return 0; } DATA getData(NODE* pnode, int pos) { while (pnode && pos--) { if (pnode->next) pnode = pnode->next; else { fprintf(stderr, "List index out of bound\n"); return -1; } } return pnode->data; } // Add data after the first occurrence of a given key value in the linked list int addAfterKey(NODE** ppnode, DATA Data, DATA key) { if (*ppnode == NULL) { fprintf(stderr, "The key was not found in the list\n"); return -1; } NODE* pnode = *ppnode; int pos = 0; while (pnode->data != key) { if (pnode->next) { pnode = pnode->next; pos++; } else { fprintf(stderr, "The key was not found in the list\n"); return -1; } } return addPos(ppnode, Data, pos + 1); } // Remove the first occurrence of a given data in the list int removeByValue(NODE** ppnode, DATA key) { if (*ppnode == NULL) { fprintf(stderr, "The key was not found in the list\n"); return -1; } NODE* pnode = *ppnode; int pos = 0; while (pnode->data != key) { if (pnode->next) { pnode = pnode->next; pos++; } else { fprintf(stderr, "The key was not found in the list\n"); return -1; } } return removePos(ppnode, pos); } // TODO: This function is not working // Reverse the elements in the list outplace LIST reverseOutplace(LIST pnode) { LIST* pReversedList = (LIST*)malloc(sizeof(LIST)); while (pnode) { addFirst(pReversedList, pnode->data); if (pnode->next) pnode = pnode->next; else break; } return *pReversedList; } // Reverse the elements in the list without creating a new list int reverseInplace(NODE** ppnode) { NODE* pnode = *ppnode; while (pnode) { // swap next and prev NODE* temp = pnode->next; pnode->next = pnode->prev; pnode->prev = temp; if (pnode->prev) pnode = pnode->prev; else { *ppnode = pnode; break; } } return 0; } // insert an element in a sorted list such that the final list is also sorted int insertIntoSorted(NODE** ppnode, DATA Data) { if (*ppnode == NULL) addFirst(ppnode, Data); NODE* pnode = *ppnode; int pos = 0; while (pnode->data < Data) { pos++; if (pnode->next) { pnode = pnode->next; } else { addLast(ppnode, Data); return 0; } } addPos(ppnode, Data, pos); return 0; } // change first list by appending second list to it int mergeList(NODE* pnode1, NODE* pnode2) { while (pnode1 && pnode1->next) { pnode1 = pnode1->next; } pnode1->next = pnode2; return 0; } // print list using recursion int printRecursive(NODE* pnode) { if (pnode) { printf("%d ", pnode->data); return printRecursive(pnode->next); } printf("\n"); return 0; } // print list in reverse order using recursion int printReverseRecursion(NODE* pnode) { if (pnode == NULL) return 0; printReverseRecursion(pnode->next); printf("%d ", pnode->data); return 0; } // the linked list clockwise by n modulo l nodes, where l is the length of the list int rotateList(NODE** ppnode, int offset) { // convert this list into a circular list NODE* head = *ppnode; { NODE* pnode = *ppnode; while (pnode) { if (pnode->next) pnode = pnode->next; else break; } pnode->next = head; } { NODE* pnode = head; while (--offset) { pnode = pnode->next; } *ppnode = pnode->next; pnode->next = NULL; } return 0; } // sorts linked list using selection sort int sort(NODE** ppnode) { // handle trivial cases if (*ppnode == NULL || (*ppnode)->next == NULL) return 0; for (NODE* i = *ppnode; i != NULL; i = i->next) { NODE* min = i; for (NODE* j = i->next; j != NULL; j = j->next) if (j->data < min->data) min = j; // swap if (min != i) { DATA temp = i->data; i->data = min->data; min->data = temp; } } return 0; }
C
#include "client.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <pthread.h> #define CLIENT_IPADDR "172.21.128.67" #define SERVPORT 1012 userList cast; FILE *fp; pthread_t t_processRecvThread; void main() { initUserList(&cast); int sockfd,sendbytes; char buf[100]; struct sockaddr_in serv_addr; if((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1) { perror("create socket Error!"); exit(1); } serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(SERVPORT); serv_addr.sin_addr.s_addr = inet_addr(CLIENT_IPADDR); bzero(&(serv_addr.sin_zero),8); if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1) { perror("network connect Error!"); exit(1); } int select = 0; char username[NAME_MAX_LEN]; char password[PWD_MAX_LEN]; while (1) { printf("----------- 请先登陆/注册 -----------\n"); printf("1.登陆\n2.注册\n"); printf("-------------------------------\n"); scanf("%d", &select); printf("请输入用户名:\n"); scanf("%s", username); printf("请输入密码:\n"); scanf("%s", password); MsgEntity tmp; if(select == 1) { configLoginEty(&tmp, username, password); } else if(select == 2) { configRegisterEty(&tmp, username, password); } else { printf("输入有误,请重新输入\n"); continue; } sendCmd(&tmp, sockfd); int bytesNum; MsgContainer tmpbag; memset((char*)&tmpbag,0,sizeof(tmpbag)); do{ bytesNum = recv(sockfd,(void *)&tmpbag,sizeof(MsgContainer),0); }while (bytesNum <= 0); showMsgContainer(tmpbag); if(tmpbag.type == COMMAND && (tmpbag.content.object) == (select - 3)) { printf("成功\n"); break; } else { printf("失败,请重试\n"); } } int res = pthread_create(&t_processRecvThread, NULL, processRecv, (void*)&sockfd); if(res != 0) { printf("create thread in main error!%d\n", res); exit(1); } int cycle = 1; while(cycle) { int type; int bagType; int object; char str[DETAILS_LEN]; int flag; printf("----------- 请输入命令 -----------\n"); printf("1.获取用户列表\n2.文件传输\n3.发送私信\n4.群发消息\n5.退出\n"); printf("-------------------------------\n"); scanf("%d", &type); switch (type) { case 1: // 获取用户列表 bagType = COMMAND; object = CMD_GETLIST; strcpy(str, ""); flag = SEND_FLAG; break; case 2: // 文件传输 printf("请输入文件的发送对象(输入用户序号):\n"); scanf("%d", &flag); while (searchNameInUserList(&cast, flag) == NULL) { printf("输入序号有误,请重新输入:\n"); printf("---------- 用户列表 ------------\n"); showUserList(cast); printf("----------------------------\n"); scanf("%d", &flag); } printf("请输入文件名:\n"); scanf("%s", str); sendFileProcess(sockfd, flag, str); break; case 3: // 发送私信 printf("请输入信息的发送对象(输入用户序号):\n"); scanf("%d", &object); while (searchNameInUserList(&cast, object) == NULL) { printf("输入序号有误,请重新输入:\n"); printf("---------- 用户列表 ------------\n"); showUserList(cast); printf("----------------------------\n"); scanf("%d", &object); } printf("请输入要发送的消息(请不要添加空格):\n"); scanf("%s", str); bagType = DIALOGUE; flag = SEND_FLAG; break; case 4: // 群发消息 printf("请输入要发送的消息(请不要添加空格):\n"); scanf("%s", str); bagType = DIALOGUE; object = 0; flag = sockfd; break; case 5: // 退出 object = CMD_EXIT; strcpy(str, ""); flag = SEND_FLAG; cycle = 0; break; default: break; } if(type != 2) { MsgContainer tmp; tmp.type = bagType; tmp.content.object = object; strcpy(tmp.content.details, str); tmp.content.flag = flag; // printf("I send a package as follow:\n"); // printf("----------------------\n"); // showMsgContainer(tmp); // printf("----------------------\n"); if((sendbytes = send(sockfd, (void *)&tmp, sizeof(MsgContainer), 0)) == -1) { perror("send Error!"); exit(1); } //printf("send successful\n"); } } if(fp != NULL) { fclose(fp); } deleteUserList(&cast); } void *processRecv(void *arg) { int socket = *(int *)arg; int bytesNum; MsgContainer tmp; do { memset((char*)&tmp,0,sizeof(tmp)); bytesNum = recv(socket,(void *)&tmp,sizeof(MsgContainer),0); if(bytesNum == -1) { perror("recv Error:"); } else { if(bytesNum <= 0) { printf("与服务器断开连接\n"); break; } else { if(tmp.type == COMMAND) { char who[NAME_MAX_LEN]; switch (tmp.content.object) { case CMD_GETLIST: makeUserList(tmp.content.details, &cast); printf("---------- 更新用户列表 ------------\n"); showUserList(cast); printf("---------------------------------\n"); break; case CMD_SEND_FILE: strcpy(who, searchNameInUserList(&cast, tmp.content.flag)); printf(" %s 向你发送文件 %s,为您将文件转存为copy_%s:\n", who, tmp.content.details, tmp.content.details); readyForRecvFile(tmp.content.details); break; case CMD_TRANSFERING: recvFilefrom(&tmp.content); break; case CMD_END_TRANSFER: finishRecvFile(); break; default: break; } } else if(tmp.type == DIALOGUE) { if(tmp.content.object == 0) { char *name = searchNameInUserList(&cast, tmp.content.flag); printf("------------------------\n"); printf(" %s 对全部人说: %s\n", name, tmp.content.details); printf("------------------------\n"); } else { char *name = searchNameInUserList(&cast, tmp.content.object); printf("------------------------\n"); printf("%s 对你说: %s\n", name, tmp.content.details); printf("------------------------\n"); } } } } }while (bytesNum > 0); } Status sendFileProcess(const int socdID, const int sendForwho, const char *fileName) { int sendBytes = 0; MsgContainer tmp; char buf[DETAILS_LEN]; int len = 0; tmp.type = COMMAND; configSendFileCmd(&tmp.content, sendForwho, fileName); if((sendBytes = send(socdID, (void *)&tmp, sizeof(MsgContainer), 0)) == -1) { perror("send Error!"); return FAILURE; } printf("文件正在发送中,请稍后...\n"); fp = fopen(fileName, "rb"); if(fp == NULL) { printf("Open File failure\n"); return FAILURE; } do { memset(buf, 0, DETAILS_LEN); len = fread(buf, sizeof(char), DETAILS_LEN, fp); if(len > 0) { unsigned short tmplen = (unsigned short)len; unsigned short sendFor = (unsigned short)sendForwho; int tmpp; unsigned short *point = &tmpp; point[0] = len; point[1] = sendFor; tmp.type = COMMAND; tmp.content.object = CMD_TRANSFERING; tmp.content.flag = tmpp; for(int i = 0; i < len; i++) { tmp.content.details[i] = buf[i]; } if((sendBytes = send(socdID, (void *)&tmp, sizeof(MsgContainer), 0)) == -1) { perror("send Error!"); return FAILURE; } } } while (feof(fp) == 0); tmp.type = COMMAND; configEndTransferCmd(&tmp.content, sendForwho); if((sendBytes = send(socdID, (void *)&tmp, sizeof(MsgContainer), 0)) == -1) { perror("send Error!"); return FAILURE; } fclose(fp); printf("发送文件成功\n"); return SUCCESSFUL; } int putStreamIntoFile(char *stream, int len) { int res; res = fwrite(stream, sizeof(char), len, fp); if(feof(fp) != 0) { fclose(fp); } return res; } Status readyForRecvFile(char *str) { char newName[FILE_NAME_MAX_LEN]; strcpy(newName, "copy_"); strcat(newName, str); fp = fopen(newName, "wb"); if(fp == NULL) { printf("Create File failure\n"); return FAILURE; } return SUCCESSFUL; } void finishRecvFile() { if(fp != NULL) fclose(fp); printf("成功接收到文件\n"); } int recvFilefrom(MsgEntity *ety) { int len = 0; if(NULL == ety) { return 0; } len = putStreamIntoFile(ety->details, ety->flag); return len; }
C
#include "vector.h" inline Vector *NewVector(){ Vector *v; v = malloc(sizeof(Vector)); v->data = make_SparseVectorMap(); return v; } inline void DestroyVector(Vector *v){ kh_destroy(SparseVector, v->data); free(v); } inline uint32_t GetSize(Vector *v){ return v->data->size; } inline void AddValue(Vector *v, int64_t key, double value){ khiter_t k; int ret; k = kh_get(SparseVector, v->data, key); if(k == kh_end(v->data)){ k = kh_put(SparseVector, v->data, key, &ret); kh_value(v->data, k) = value; }else{ kh_value(v->data, k) += value; } } inline double GetValue(Vector *v, int64_t key, int *ret){ khiter_t k; k = kh_get(SparseVector, v->data, key); if(k == kh_end(v->data)){ *ret = 0; return 0.0; }else{ *ret = 1; return kh_value(v->data, k); } } inline void SetValue(Vector *v, int64_t key, double value){ int ret; khiter_t k; k = kh_get(SparseVector, v->data, key); if(k == kh_end(v->data)){ k = kh_put(SparseVector, v->data, key, &ret); } kh_value(v->data, k) = value; } inline void RandomInit(Vector *v, int64_t key, double c){ khiter_t k; k = kh_get(SparseVector, v->data, key); if(k != kh_end(v->data)){ kh_value(v->data, k) = (rand() + 0.0) / RAND_MAX * c; } } inline void AddVector(Vector *v, Vector *v2, double alpha){ khiter_t k; for(k = kh_begin(v2->data); k != kh_end(v2->data); k++){ if(kh_exist(v2->data, k)){ AddValue(v, kh_key(v2->data, k), kh_value(v2->data, k) * alpha); } } } inline double NormL2(Vector *v){ khiter_t k; double ret = 0.0; for(k = kh_begin(v->data); k != kh_end(v->data); k++){ if(kh_exist(v->data, k)){ ret += kh_value(v->data, k) * kh_value(v->data, k); } } return ret; } inline Vector *Copy(Vector *v){ Vector *v2 = NewVector(); khiter_t k; for(k = kh_begin(v->data); k != kh_end(v->data); k++){ if(kh_exist(v->data, k)){ SetValue(v2, kh_key(v->data, k), kh_value(v->data, k)); } } return v2; } inline double Dot(Vector *v, Vector *v2){ Vector *va = v; Vector *vb = v2; if(GetSize(v2) < GetSize(v)){ va = v2; vb = v; } double dot = 0.0; khiter_t k; int ret; for(k = kh_begin(va->data); k != kh_end(va->data); k++){ if(kh_exist(va->data, k)){ // if this key dose not exist in vb, GetValue will return 0.0 and the value checking of ret can be omitted. dot += kh_value(va->data, k) * GetValue(vb, kh_key(va->data, k), &ret); } } return dot; } // inline double DotFeatures(Vector *v, ) inline Vector *ApplyOnElem(Vector *v, ElemOperation f){ Vector *v2 = NewVector(); khiter_t k; for(k = kh_begin(v->data); k != kh_end(v->data); k++){ if(kh_exist(v->data, k)){ SetValue(v2, kh_key(v->data, k), f(kh_value(v->data, k))); } } return v2; } inline Vector *Scale(Vector *v, double scale){ Vector *v2 = NewVector(); khiter_t k; for(k = kh_begin(v->data); k != kh_end(v->data); k++){ if(kh_exist(v->data, k)){ SetValue(v2, kh_key(v->data, k), kh_value(v->data, k) * scale); } } return v2; } inline Vector *ElemWiseAddVector(Vector *v, Vector *u){ Vector *v2 = Copy(v); khiter_t k; for(k = kh_begin(u->data); k != kh_end(u->data); k++){ if(kh_exist(u->data, k)){ AddValue(v2, kh_key(u->data, k), kh_value(u->data, k)); } } return v2; } inline Vector *ElemWiseMultiply(Vector *v, Vector *u){ Vector *v2 = NewVector(); khiter_t k; int ret; double val, ual; for(k = kh_begin(v->data); k != kh_end(v->data); k++){ if(kh_exist(v->data, k)){ val = kh_value(v->data, k); ual = GetValue(u, kh_key(v->data, k), &ret); if(val != 0 && ual != 0){ SetValue(v2, kh_key(v->data, k), val*ual); } } } return v2; }
C
#include <unistd.h> void print_memory(const void *addr, size_t size); int main(void) { int tab[10] = {1, 98, 54332, 67, 23, 5, 98, 345, 563, 46}; print_memory(tab, 10); return (0); }
C
/* * Copyright (c) 2023 Antmicro <www.antmicro.com> * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __EXT2_BITMAP_H__ #define __EXT2_BITMAP_H__ #include <stdint.h> #include <stdbool.h> /* Functions to make operations on bitmaps. * * NOTICE: Assumed size of the bitmap is 256 B (1024 bits). * (Hence, the greatest valid index is 1023.) */ /** * @brief Set bit at given index to one * * @param bm Pointer to bitmap * @param index Index in bitmap * @param size Size of bitmap in bytes * * @retval 0 on success; * @retval -EINVAL when index is too big; */ int ext2_bitmap_set(uint8_t *bm, uint32_t index, uint32_t size); /** * @brief Set bit at given index to zero * * @param bm Pointer to bitmap * @param index Index in bitmap * @param size Size of bitmap in bytes * * @retval 0 on success; * @retval -EINVAL when index is too big; */ int ext2_bitmap_unset(uint8_t *bm, uint32_t index, uint32_t size); /** * @brief Find first bit set to zero in bitmap * * @param bm Pointer to bitmap * @param size Size of bitmap in bytes * * @retval >0 found inode number; * @retval -ENOSPC when not found; */ int32_t ext2_bitmap_find_free(uint8_t *bm, uint32_t size); /** * @brief Helper function to count bits set in bitmap * * @param bm Pointer to bitmap * @param size Size of bitmap in bits * * @retval Number of set bits in bitmap; */ uint32_t ext2_bitmap_count_set(uint8_t *bm, uint32_t size); #endif /* __EXT2_BITMAP_H__ */
C
#include "cbuf.h" #include "derp.h" #include <assert.h> #include <arpa/inet.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> // Open socket and connect to server. int get_fd(struct in_addr host, unsigned short port) { int fd = socket(PF_INET, SOCK_STREAM, 0); if (fd < 0) { return -1; } struct sockaddr_in addr; memset(&addr, 0, sizeof addr); addr.sin_family = AF_INET; addr.sin_port = htons(port); addr.sin_addr = host; if (connect(fd, (struct sockaddr *) &addr, sizeof addr) < 0) { close(fd); return -2; } return fd; } // Main loop. int loop(int fd, char *id) { assert(fd > 0); derp_t *derp = derp_new(); if (derp == NULL) { goto error; } derp_send_msg(derp, id, strnlen(id, DERP_MAX_MSG_LEN + 1)); // Register client. fd_set read_set, write_set, ready_read_set, ready_write_set; FD_ZERO(&read_set); FD_ZERO(&write_set); FD_SET(STDIN_FILENO, &read_set); FD_SET(fd, &read_set); FD_SET(fd, &write_set); while (1) { ready_read_set = read_set; ready_write_set = write_set; if (select(fd + 1, &ready_read_set, &ready_write_set, NULL, NULL) < 0) { printf("select error\n"); goto error_derp; } if (FD_ISSET(STDIN_FILENO, &ready_read_set)) { ssize_t n; char buf[BUFSIZ]; n = read(STDIN_FILENO, buf, BUFSIZ); // Read actual data. buf[n - 1] = '\0'; // Replace trailing newline with null byte. if (derp_send_msg(derp, buf, n) < 0) { printf("send error\n"); } else { FD_SET(fd, &write_set); } } if (FD_ISSET(fd, &ready_read_set)) { char buf[DERP_MAX_MSG_LEN]; char len; if (derp_on_readable_fd(derp, fd) < 0) { goto error_derp; } while ((len = derp_recv_msg(derp, buf)) >= 0) { printf("%s\n", buf); } } if (FD_ISSET(fd, &ready_write_set)) { int n = derp_on_writable_fd(derp, fd); if (n < 0) { goto error_derp; } else if (!n) { // Nothing more to write, clear bit. FD_CLR(fd, &write_set); } } } error_derp: derp_del(derp); error: return -1; } int main(int argc, char **argv) { if (argc != 4) { printf("usage: derp HOST PORT NAME\n"); return -1; } struct in_addr host; if (!inet_aton(argv[1], &host)) { printf("invalid ip\n"); return -2; } short port = (short) atol(argv[2]); if (!port) { printf("invalid port\n"); return -3; } char *id = argv[3]; if (strnlen(id, DERP_MAX_MSG_LEN + 1) > DERP_MAX_MSG_LEN) { printf("id too long\n"); return -4; } int fd = get_fd(host, port); if (fd < 0) { printf("error while connecting"); return fd; } return loop(fd, id); }
C
#include "edit_str.h" int edit_str(char* ld_str, char* ed_str, char* tr_str, int ed_length) { static int pos = 0; struct pos initPos; unsigned char ascii, scan; static int insert = 0; /* 0 => overwrite, 1 => insert */ setcursortype(99); for (int i = 0; i < (int)strlen(ld_str); i++) putchar(ld_str[i]); initPos.x = wherex(); initPos.y = wherey(); for (int i = 0; i < ed_length; i++) putchar(ed_str[i]); for (int i = 0; i < (int)strlen(tr_str); i++) putchar(tr_str[i]); gotoxy(initPos.x, initPos.y); int last_digit = ed_length - 1; pos = 0; do { scan = 0; ascii = _getch(); if (ascii == 0x00 || ascii == 0xE0 || ascii == 0x08) { if (ascii == 0x00 || ascii == 0xE0) { ascii = 0; scan = _getch(); } else { scan = ascii; ascii = 0; } switch (scan) { case 8: /* Backspace Key */ if (wherex() > initPos.x) { gotoxy(wherex() - 1, wherey()); for (int i = pos - 1; i < last_digit; i++) { ed_str[i] = ed_str[i + 1]; putchar(ed_str[i]); } ed_str[last_digit] = ' '; putchar(' '); pos--; gotoxy(initPos.x + pos, initPos.y); } else putchar('\a'); break; case 83: /* Delete Key */ if (ed_str[pos] != 0) { for (int i = pos; i < last_digit; i++) { ed_str[i] = ed_str[i + 1]; putchar(ed_str[i]); } ed_str[last_digit] = ' '; putchar(' '); gotoxy(initPos.x + pos, initPos.y); } else putchar('\a'); break; case 75: /* Left Arrow Key */ if (wherex() > initPos.x) { gotoxy(wherex() - 1, wherey()); pos--; } else putchar('\a'); break; case 77: /* Right Arrow Key */ if ((wherex() < initPos.x + ed_length - 1) && ed_str[pos + 1] != 0) { gotoxy(wherex() + 1, wherey()); pos++; } else putchar('\a'); break; case 71: /* Pos1 Key */ gotoxy(initPos.x, initPos.y); pos = 0; break; case 79: /* End Key */ pos = 0; while (ed_str[pos] != 0) pos++; gotoxy(initPos.x + pos, initPos.y); break; case 82: /* Insert Key */ if (insert == 0) { insert = 1; setcursortype(10); } else { insert = 0; setcursortype(99); } break; default: break; } } if (ascii > 31) { if (pos <= last_digit) { if (insert == 0) { ed_str[pos] = ascii; putchar(ascii); pos++; if (pos > last_digit) { gotoxy(initPos.x + ed_length - 1, initPos.y); pos = ed_length - 1; } } else { int index = 0; do { ed_str[last_digit - index] = ed_str[last_digit - index - 1]; index++; } while ((pos + index + 1) <= ed_length); putchar(ascii); ed_str[pos] = ascii; for (int i = pos + 1; i <= last_digit; i++) putchar(ed_str[i]); gotoxy(initPos.x + pos + 1, initPos.y); pos++; } } } } while (ascii != 13); int length = 0; while (ed_str[length] != 0) length++; return length; }
C
/* * gcode.h * Author: pavel */ #ifndef GSTRUCT_H_ #define GSTRUCT_H_ // structure for holding the G-code typedef struct { char cmd_type[3]; /*command type of the G-code*/ int x_pos; /*goto x position value*/ int y_pos; /*goto y position value*/ int pen_pos; /*pen position(servo value)*/ int pen_up; /*pen up value*/ int pen_dw; /*pen down value*/ int laserPower; /*laser power (inverse)*/ int x_dir; /*stepper x-axis direction*/ int y_dir; /*stepper y-axis direction*/ int speed; /*speed of the stepper motor*/ int plot_area_h; /*height of the plotting area*/ int plot_area_w; /*width of the plotting area*/ int abs; /*coordinates absolute or relative(absolute: abs = 1)*/ }Gstruct; #endif /* GSTRUCT_H_ */
C
//RFID Functionality #ifndef RFID_H #define RFID_H #include <SoftwareSerial.h> #include "tag_db.h" #define RFID_D9_PIN 4 #define txPin 5 SoftwareSerial rfid = SoftwareSerial( RFID_D9_PIN, txPin ); //SimpleTimer timer; // Check the number of tags defined int numberOfTags = sizeof(allowedTags) / sizeof(allowedTags[0]); int incomingByte = 0; // To store incoming serial data void RFID_setup() { rfid.begin(9600); //timerId = timer.setTimer(<repeat interval>, <function call to be rpeated>, <no. of times to be repeated before timeout>); //timer.run(), to be called from the loop. } //void unlock(int num) { // delay(num * 1000); //} // searches for a specific tag in the database and returns its index int findTag( char tagValue[10] ) { for (int thisCard = 0; thisCard < numberOfTags; thisCard++) { // Check if the tag value matches this row in the tag database if (strcmp(tagValue, allowedTags[thisCard]) == 0) { // The row in the database starts at 0, so add 1 to the result so // that the card ID starts from 1 instead (0 represents "no match") return (thisCard + 1); } } // If we don't find the tag return a tag ID of 0 to show there was no match return (0); } //return RFID Tag index int RFID_read() { while (true) { byte i = 0; byte val = 0; byte checksum = 0; byte bytesRead = 0; byte tempByte = 0; byte tagBytes[6]; // "Unique" tags are only 5 bytes but we need an extra byte for the checksum char tagValue[10]; // Read from the RFID module. Because this connection uses SoftwareSerial // there is no equivalent to the Serial.available() function, so at this // point the program blocks while waiting for a value from the module if (rfid.available() > 0) { if ((val = rfid.read()) == 2) { // Check for header bytesRead = 0; while (bytesRead < 12) { // Read 10 digit code + 2 digit checksum if (rfid.available() > 0) { val = rfid.read(); // Append the first 10 bytes (0 to 9) to the raw tag value if (bytesRead < 10) { tagValue[bytesRead] = val; } // Check if this is a header or stop byte before the 10 digit reading is complete if ((val == 0x0D) || (val == 0x0A) || (val == 0x03) || (val == 0x02)) { break; // Stop reading } // Ascii/Hex conversion: if ((val >= '0') && (val <= '9')) { val = val - '0'; } else if ((val >= 'A') && (val <= 'F')) { val = 10 + val - 'A'; } // Every two hex-digits, add a byte to the code: if (bytesRead & 1 == 1) { // Make space for this hex-digit by shifting the previous digit 4 bits to the left tagBytes[bytesRead >> 1] = (val | (tempByte << 4)); if (bytesRead >> 1 != 5) { // If we're at the checksum byte, checksum ^= tagBytes[bytesRead >> 1]; // Calculate the checksum... (XOR) }; } else { tempByte = val; // Store the first hex digit first }; bytesRead++; } // Ready to read next digit } // Send the result to the host connected via USB if (bytesRead == 12) { // 12 digit read is complete tagValue[10] = '\0'; // Null-terminate the string //Serial.print("Tag read: "); // for (i = 0; i < 5; i++) { // Add a leading 0 to pad out values below 16 //if (tagBytes[i] < 16) { //Serial.print("0"); //} //Serial.print(tagBytes[i], HEX); //} //Serial.println(); //Serial.print("Checksum: "); //Serial.print(tagBytes[5], HEX); //Serial.println(tagBytes[5] == checksum ? " -- passed." : " -- error."); // Show the raw tag value //Serial.print("VALUE: "); //Serial.println(tagValue); // Search the tag database for this particular tag int tagId = findTag( tagValue ); // Only fire the strike plate if this tag was found in the database if ( tagId > 0 ) { //Serial.print("Authorized tag ID "); //Serial.print(tagId); //Serial.print(": unlocking for "); //Serial.println(tagName[tagId - 1]); // Get the name for this tag from the database //unlock(2); // Fire the strike plate to open the lock return (tagId - 1); //returning zero based index } else { //Serial.println("Tag not authorized"); return -1;// to perform exception handling } //Serial.println(); // Blank separator line in output } bytesRead = 0; } } } } bool if_correct(int tag_id, int correct_index) { if (tag_id == correct_index) return true; else return false; } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_tab_rangecpy.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tgouedar <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/09 20:44:46 by tgouedar #+# #+# */ /* Updated: 2020/01/05 15:13:42 by tgouedar ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include "libft.h" char **ft_emergency_tabfree(char **tab_cpy, int nb, size_t end, size_t i) { while ((size_t)nb <= end) { ft_memdel((void**)&tab_cpy[++i]); ++nb; } free(tab_cpy); return (NULL); } char **ft_tab_rangecpy(char **table, size_t start, size_t end) { char **tab_cpy; int nb; size_t i; if (!table) return (NULL); nb = ft_tablen(table); if ((end > (size_t)nb || (nb = end - start + 1) <= 0) || !(tab_cpy = (char**)ft_memalloc(sizeof(char**) * (nb + 1)))) return (NULL); i = nb; tab_cpy[i--] = NULL; nb = end; while ((size_t)nb >= start) { if (!(tab_cpy[i--] = ft_strdup(table[nb]))) return (ft_emergency_tabfree(tab_cpy, nb, end, i)); nb--; } return (tab_cpy); }
C
#include <stdio.h> #include <stdlib.h> #include "heap.h" int main() { Heap h; criaHeap(&h); char opcao; int num; do{ scanf("%c",&opcao); switch(opcao){ case 'I': scanf("%d\n",&num); insereValor(&h,num); break; case 'M': printf("%d\n",minValor(h)); break; case 'P': imprimeHeap(h); break; case 'S': break; } }while(opcao!='S'); return 0; }
C
#include<stdlib.h> #include<stdbool.h> #include<stdio.h> #include<string.h> #include<math.h> #include"statistics.h" //-------------------------------------------------------- // FUNCTION compare_doubles //-------------------------------------------------------- static int compare_doubles(const void* a, const void* b) { if(*(double*)a < *(double*)b) return -1; else if(*(double*)a > *(double*)b) return 1; else return 0; } //-------------------------------------------------------- // FUNCTION is_even //-------------------------------------------------------- static bool is_even(int n) { return n % 2 == 0; } // -------------------------------------------------------- // FUNCTION output_data // -------------------------------------------------------- void output_data(double* data, int size) { for(int i = 0; i < size; i++) { printf("%d\t%lf\n", i, data[i]); } } //-------------------------------------------------------- // FUNCTION output_statistics //-------------------------------------------------------- void output_statistics(statistics* stats) { printf("%-33s%12d\n", "Count", stats->count); printf("%-33s%12.4lf\n", "Total", stats->total); printf("%-33s%12.4lf\n", "Arithmetic Mean", stats->arithmetic_mean); printf("%-33s%12.4lf\n", "Minimum", stats->minimum); printf("%-33s%12.4lf\n", "Lower Quartile", stats->lower_quartile); printf("%-33s%12.4lf\n", "Median", stats->median); printf("%-33s%12.4lf\n", "Upper Quartile", stats->upper_quartile); printf("%-33s%12.4lf\n", "Maximum", stats->maximum); printf("%-33s%12.4lf\n", "Range", stats->range); printf("%-33s%12.4lf\n", "Inter-Quartile Range", stats->inter_quartile_range); printf("%-33s%12.4lf\n", "Standard Deviation of Population", stats->standard_deviation_population); printf("%-33s%12.4lf\n", "Standard Deviation of Sample", stats->standard_deviation_sample); printf("%-33s%12.4lf\n", "Variance of Population", stats->variance_population); printf("%-33s%12.4lf\n", "Variance of Sample", stats->variance_sample); printf("%-33s%12.4lf\n", "Skew", stats->skew); } //-------------------------------------------------------- // FUNCTION calculate_statistics //-------------------------------------------------------- void calculate_statistics(double* data, int size, statistics* stats) { double sum_of_squares = 0; int lower_quartile_index_1; int lower_quartile_index_2; // data needs to be sorted for median etc qsort(data, size, sizeof(double), compare_doubles); output_data(data, size); // count is just the size of the data set stats->count = size; // initialize total to 0, and then iterate data // calculating total and sum of squares stats->total = 0; for(int i = 0; i < size; i++) { stats->total += data[i]; sum_of_squares += pow(data[i], 2); } // the arithmetic mean is simply the total divided by the count stats->arithmetic_mean = stats->total / stats->count; // method of calculating median and quartiles is different for odd and even count if(is_even(stats->count)) { stats->median = (data[((stats->count) / 2) - 1] + data[stats->count / 2]) / 2; // even / even if(is_even(stats->count / 2)) { lower_quartile_index_1 = (stats->count / 2) / 2; lower_quartile_index_2 = lower_quartile_index_1 - 1; stats->lower_quartile = (data[lower_quartile_index_1] + data[lower_quartile_index_2]) / 2; stats->upper_quartile = (data[stats->count - 1 - lower_quartile_index_1] + data[stats->count - 1 - lower_quartile_index_2]) / 2; } // even / odd else { lower_quartile_index_1 = ((stats->count / 2) - 1) / 2; stats->lower_quartile = data[lower_quartile_index_1]; stats->upper_quartile = data[stats->count - 1 - lower_quartile_index_1]; } } else { stats->median = data[((stats->count + 1) / 2) - 1]; // odd / even if(is_even((stats->count - 1) / 2)) { lower_quartile_index_1 = ((stats->count - 1) / 2) / 2; lower_quartile_index_2 = lower_quartile_index_1 - 1; stats->lower_quartile = (data[lower_quartile_index_1] + data[lower_quartile_index_2]) / 2; stats->upper_quartile = (data[stats->count - 1 - lower_quartile_index_1] + data[stats->count - 1 - lower_quartile_index_2]) / 2; } // odd / odd else { lower_quartile_index_1 = (((stats->count - 1) / 2) - 1) / 2; stats->lower_quartile = data[lower_quartile_index_1]; stats->upper_quartile = data[stats->count - 1 - lower_quartile_index_1]; } } // the data is sorted so the mimimum and maximum are the first and last values stats->minimum = data[0]; stats->maximum = data[size - 1]; // the range is difference between the minimum and the maximum stats->range = stats->maximum - stats->minimum; // and the inter-quartile range is the difference between the upper and lower quartiles stats->inter_quartile_range = stats->upper_quartile - stats->lower_quartile; // this is the formula for the POPULATION variance stats->variance_population = (sum_of_squares - ((pow(stats->total, 2)) / stats->count)) / stats->count; // the standard deviation is the square root of the variance stats->standard_deviation_population = sqrt(stats->variance_population); // the formula for the sample variance is slightly different in that it use count -1 stats->variance_sample = (sum_of_squares - ((pow(stats->total, 2)) / stats->count)) / (stats->count - 1); // the sample standard deviation is the square root of the sample variance stats->standard_deviation_sample = sqrt(stats->variance_sample); // this is Pearson's second skewness coefficient, one of many measures of skewness stats->skew = (3.0 * (stats->arithmetic_mean - stats->median)) / stats->standard_deviation_population; }
C
/* nested array assignments: mixed global/local, int/char arrays */ char y[5]; extern void print_int (int n); extern void print_string (char s[]); void main(void) { int x[5]; int u; x[0] = 0; y[0] = 1; x[1] = 1; y[1] = 2; x[2] = 2; y[2] = 3; x[3] = 3; y[3] = 4; x[4] = 4; y[4] = 55; u = y[x[y[x[y[x[y[x[y[x[0]]]]]]]]]]; print_int(u); print_string("\n"); }
C
#include<stdio.h> void main() { int i,j,n; int a[50]; int sum=0; scanf("%d\t",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); sum=sum+a[i]; } printf("%d",sum); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* floorcast.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pthorell <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/08/31 17:41:41 by pthorell #+# #+# */ /* Updated: 2018/08/31 18:59:15 by pthorell ### ########.fr */ /* */ /* ************************************************************************** */ #include "wolf3d.h" #include "raycast.h" #include "draw.h" #include "libft.h" #include "texture_handler.h" #include "color.h" #include <math.h> #define GPOSX g->player.pos.x #define GPOSY g->player.pos.y #define FLTEX g->textures[3][TEXTURE_WIDTH * floor_tex.y + floor_tex.x] #define RFTEX g->textures[2][TEXTURE_WIDTH * floor_tex.y + floor_tex.x] #define FLSHA (RENDER_DIST / 1.8) static t_2d get_floor_wall(t_ray *ray) { t_2d result; if (ray->side == 0 && (ray->dir >= 270.0 || ray->dir <= 90.0)) { result.x = ray->map_pos.x; result.y = ray->map_pos.y + ray->wall_x; } else if (ray->side == 0) { result.x = ray->map_pos.x + 1.0; result.y = ray->map_pos.y + ray->wall_x; } else if (ray->side == 1 && ray->dir >= 180.0) { result.x = ray->map_pos.x + ray->wall_x; result.y = ray->map_pos.y; } else { result.x = ray->map_pos.x + ray->wall_x; result.y = ray->map_pos.y + 1.0; } return (result); } void draw_floor(t_ray *ray, t_game *g, int x) { int y; t_2d floor_wall; t_2d current_floor; double weight; t_point floor_tex; floor_wall = get_floor_wall(ray); if (ray->line.end < 0) ray->line.end = RES_Y; y = ray->line.end + 1; while (y < RES_Y) { if ((RES_Y - y) / 2 >= 255) break ; weight = (RES_Y / (2.0 * y - RES_Y)) / ray->wall_dist; current_floor.x = weight * floor_wall.x + (1.0 - weight) * GPOSX; current_floor.y = weight * floor_wall.y + (1.0 - weight) * GPOSY; floor_tex.x = (int)(current_floor.x * TEXTURE_WIDTH) % TEXTURE_WIDTH; floor_tex.y = (int)(current_floor.y * TEXTURE_HEIGHT) % TEXTURE_HEIGHT; put_pixel(x, y, sub_color(FLTEX, (RES_Y - y + 1) / FLSHA), g); put_pixel(x, RES_Y - y, sub_color(RFTEX, (RES_Y - y + 1) / FLSHA), g); ++y; } }
C
#include <stdio.h> #include <stdlib.h> #define INPUTFILE "projectInput.txt" int currentTime = 0; // Shortest Job First typedef struct hold1{ // data for each waiting process in holding queue 1 struct hold1 * next; } hold1_t; // First in First out typedef struct hold2{ // data for each waiting process in holding queue 2 struct hold2 * next; } hold2_t; void systemConfiguration(char* buffer){ // set system configuration } void jobArrival(char* buffer){ // handle new job } void deviceRequest(char* buffer){ // handle device request } void deviceRelease(char* buffer){ // handle device release } void display(char* buffer){ // display the system in a readable format } void parseLine(char* buffer){ switch(buffer[0]){ case 'C': systemConfiguration(buffer); break; case 'A': jobArrival(buffer); break; case 'Q': deviceRequest(buffer); break; case 'L': deviceRelease(buffer); break; case 'D': display(buffer); break; } } int main(){ FILE *file = fopen(INPUTFILE, "r"); if(NULL == file) { fprintf(stderr, "Cannot open file: %s\n", INPUTFILE); return 1; } size_t buffer_size = 30; char *buffer = malloc(buffer_size * sizeof(char)); while(-1 != getline(&buffer, &buffer_size, file)){ printf("%s", buffer); parseLine(buffer); } fflush(stdout); fclose(file); free(buffer); return 0; }
C
#pragma once #ifndef DEBUG_H #define DEBUG_H // 调试日志接口,可以使接入log系统时不用改任何日志既可以使用 #include "common_time.h" #include <cstdio> #include <stdarg.h> static void DebugLog(int log_level, const char *fmt, ...) { if (log_level == 5) { #ifdef __NO_DEBUG_LOG return; #endif } char buf[4096] = {0}; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); if (log_level == 1 || log_level == 2) { printf("%s \033[0;31m%s\033[0m\n", TimeHelper::GetNowTimeStr().c_str(), buf); } else { printf("%s %s\n", TimeHelper::GetNowTimeStr().c_str(), buf); } fflush(stdout); } #define FLOG(...) DebugLog(1, __VA_ARGS__) #define ELOG(...) DebugLog(2, __VA_ARGS__) #define WLOG(...) DebugLog(3, __VA_ARGS__) #define NLOG(...) DebugLog(4, __VA_ARGS__) #define DLOG(...) DebugLog(5, __VA_ARGS__) #endif
C
#include <stdio.h> void shuffle(int *A, int n) { // shuffle n cards for(int i = n-1; i >= 1; i--) { int r = rand() % (i+1); // r = [0, i] swap(A[i], A[r]); } }
C
#include<stdio.h> #include <unistd.h> int fd[2]; pid_t id; unsigned char buffer[120]; int main(int argc, char *argv[]) { pipe(fd); id=fork(); if(0==id){ close(fd[1]); read(fd[0],buffer,120); printf("child:%s\n",buffer); } else if(buffer==0) printf("read error"); else{ close(fd[0]); write(fd[1],"hi\n",3); close(fd[1]); } }
C
/* * queue.c * * Created on: 2017年10月19日 * Author: linzer */ #include <queue.h> /* 私有宏. */ #define QUEUE_EMPTY(head) DCLIST_EMPTY(head) #define QUEUE_HEAD(head) DCLIST_HEAD(head) #define QUEUE_TAIL(head) DCLIST_TAIL(head) #define QUEUE_INIT(node) DCLIST_INIT(node) #define QUEUE_ADD(head, other) DCLIST_ADD(head, other) #define QUEUE_REMOVE(node) DCLIST_REMOVE(node) #define QUEUE_MOVE(head, other) DCLIST_MOVE(head, other) #define QUEUE_SPLIT(head, split, other) \ DCLIST_SPLIT(head, split, other) #define QUEUE_INSERT_HEAD(head, node) \ DCLIST_INSERT_HEAD(head, node) #define QUEUE_INSERT_TAIL(head, node) \ DCLIST_INSERT_TAIL(head, node) queue *queue_create() { queue *q = (queue *)malloc(sizeof(queue)); assert(NULL != q); QUEUE_INIT(&q->queue_head); SPIN_INIT(q); q->size = 0; return q; } int queue_empty(const queue *q) { assert(q != NULL); return q->size == 0; } int queue_size(const queue *q) { assert(q != NULL); return q->size; } void queue_push(queue *q, queue_node *node) { assert(q != NULL); assert(NULL != node); SPIN_LOCK(q); QUEUE_INSERT_TAIL(&q->queue_head, node); ++ q->size; SPIN_UNLOCK(q); } queue_node *queue_unpush(queue *q) { assert(q != NULL); queue_node *node = NULL; SPIN_LOCK(q); if(!queue_empty(q)) { node = QUEUE_TAIL(&q->queue_head); QUEUE_REMOVE(node); -- q->size; } SPIN_UNLOCK(q); return node; } queue_node *queue_pop(queue *q) { assert(q != NULL); queue_node *node = NULL; SPIN_LOCK(q); if(!queue_empty(q)) { node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); -- q->size; } SPIN_UNLOCK(q); return node; } queue_node *queue_front(queue *q) { assert(q != NULL); queue_node *node = NULL; SPIN_LOCK(q); if(!queue_empty(q)) { node = QUEUE_HEAD(&q->queue_head); } SPIN_UNLOCK(q); return node; } queue_node *queue_back(queue *q) { assert(q != NULL); queue_node *node = NULL; SPIN_LOCK(q); if(!queue_empty(q)) { node = QUEUE_TAIL(&q->queue_head); } SPIN_UNLOCK(q); return node; } void queue_clear(queue *q, queue_node_free_cb free_cb) { assert(q != NULL); queue_node *node = NULL; if(NULL == q) return; SPIN_LOCK(q); while(!queue_empty(q)) { node = queue_pop(q); free_cb(node); } q->size = 0; SPIN_UNLOCK(q); } /* 非线程安全 */ void queue_destroy(queue **q, queue_node_free_cb free_cb) { if(q==NULL || *q==NULL) return; queue_clear(*q, free_cb); SPIN_DESTROY(*q); free(*q); *q = NULL; } /* quick queue */ quick_queue *quick_queue_create() { quick_queue *q = (quick_queue *)malloc(sizeof(quick_queue)); assert(NULL != q); atomic_ptr_set(&q->node, NULL); return q; } int quick_queue_empty(const quick_queue *q) { assert(q != NULL); return NULL == atomic_ptr_get(&q->node); } void quick_queue_push(quick_queue *q, queue_node *node) { assert(q != NULL); node = atomic_ptr_set(&q->node, node); if(node) { free(node); } } queue_node *quick_queue_pop(quick_queue *q) { assert(q != NULL); return atomic_ptr_set(&q->node, NULL); } queue_node *quick_queue_unpush(quick_queue *q) { assert(q != NULL); return quick_queue_pop(q); } void quick_queue_clear(quick_queue *q) { assert(q != NULL); queue_node *node = quick_queue_unpush(q); if(node) { free(node); } } /* 非线程安全 */ void quick_queue_destroy(quick_queue **q) { if(q==NULL || *q==NULL) return; quick_queue_clear(*q); free(*q); *q = NULL; } /* block queue */ block_queue *block_queue_create() { block_queue *q = (block_queue *)malloc(sizeof(block_queue)); assert(NULL != q); QUEUE_INIT(&q->queue_head); MUTEX_INIT(q); condition_init(&q->cond, &q->lock); q->size = 0; q->finish = false; return q; } int block_queue_empty(const block_queue *q) { assert(q != NULL); return q->size == 0; } int block_queue_size(const block_queue *q) { assert(q != NULL); return q->size; } bool block_queue_push(block_queue *q, queue_node *node) { assert(q != NULL); assert(node != NULL); bool ret = true; MUTEX_LOCK(q); if(q->finish) { ret = false; } else { QUEUE_INSERT_TAIL(&q->queue_head, node); ++ q->size; if(1 == q->size) { /* 优化:只在为空时才notify */ condition_notify(&q->cond); } } MUTEX_UNLOCK(q); return ret; } queue_node *block_queue_pop(block_queue *q) { assert(q != NULL); queue_node *node = NULL; MUTEX_LOCK(q); while(!q->finish && block_queue_empty(q)) { condition_wait(&q->cond); } assert(q->finish || !block_queue_empty(q)); if(!block_queue_empty(q)) { node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); -- q->size; } MUTEX_UNLOCK(q); return node; } queue_node *block_queue_try_pop(block_queue *q) { assert(q != NULL); queue_node *node = NULL; MUTEX_LOCK(q); if(!block_queue_empty(q)) { node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); -- q->size; } MUTEX_UNLOCK(q); return node; } void block_queue_finish(block_queue *q) { assert(q != NULL); MUTEX_LOCK(q); q->finish = true; MUTEX_UNLOCK(q); } void block_queue_clear(block_queue *q, queue_node_free_cb free_cb) { assert(q != NULL); queue_node *node = NULL; if(NULL == q) return; MUTEX_LOCK(q); while(!QUEUE_EMPTY(&q->queue_head)) { /* 不能用pop否则会阻塞 */ // node = block_queue_pop(q); node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); free_cb(node); } q->size = 0; MUTEX_UNLOCK(q); } /* 非线程安全 */ void block_queue_destroy(block_queue **q, queue_node_free_cb free_cb) { if(q && *q) { block_queue_clear(*q, free_cb); MUTEX_DESTROY(*q); condition_destroy(&(*q)->cond); free(*q); *q = NULL; } } /* bound block queue */ bound_block_queue *bound_block_queue_create(int capacity) { bound_block_queue *q = (bound_block_queue *)malloc(sizeof(bound_block_queue)); assert(NULL != q); QUEUE_INIT(&q->queue_head); MUTEX_INIT(q); condition_init(&q->no_full, &q->lock); condition_init(&q->no_empty, &q->lock); q->size = 0; q->capacity = capacity; q->finish = false; return q; } int bound_block_queue_empty(const bound_block_queue *q) { assert(q != NULL); return q->size == 0; } int bound_block_queue_full(const bound_block_queue *q) { assert(q != NULL); return q->size >= q->capacity; } int bound_block_queue_size(const bound_block_queue *q) { assert(q != NULL); return q->size; } int bound_block_queue_capacity(const bound_block_queue *q) { assert(q != NULL); return q->capacity; } bool bound_block_queue_push(bound_block_queue *q, queue_node *node) { assert(q != NULL); assert(node != NULL); int ret = true; MUTEX_LOCK(q); while(!q->finish && bound_block_queue_full(q)) { condition_wait(&q->no_full); } assert(q->finish || !bound_block_queue_full(q)); if(q->finish) { ret = false; } else { QUEUE_INSERT_TAIL(&q->queue_head, node); ++ q->size; } condition_notify(&q->no_empty); MUTEX_UNLOCK(q); return ret; } queue_node *bound_block_queue_pop(bound_block_queue *q) { assert(q != NULL); queue_node *node = NULL; MUTEX_LOCK(q); while(!q->finish && bound_block_queue_empty(q)) { condition_wait(&q->no_empty); } assert(q->finish || !bound_block_queue_empty(q)); if(!bound_block_queue_empty(q)) { node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); -- q->size; } condition_notify(&q->no_full); MUTEX_UNLOCK(q); return node; } void bound_block_queue_finish(bound_block_queue *q) { assert(q != NULL); MUTEX_LOCK(q); q->finish = true; condition_notify_all(&q->no_full); condition_notify_all(&q->no_empty); MUTEX_UNLOCK(q); } void bound_block_queue_set_capacity(bound_block_queue *q, int capacity) { assert(q != NULL); ATOM_SET_OLD(&q->capacity, capacity); } void bound_block_queue_clear(bound_block_queue *q, queue_node_free_cb free_cb) { assert(q != NULL); queue_node *node = NULL; if(NULL == q) return; MUTEX_LOCK(q); while(!QUEUE_EMPTY(&q->queue_head)) { /* 不能用pop否则会阻塞 */ // node = bound_block_queue_pop(q); node = QUEUE_HEAD(&q->queue_head); QUEUE_REMOVE(node); // 不能对node直接释放,因为node不是malloc直接分配的地址 free_cb(node); } q->size = 0; MUTEX_UNLOCK(q); } /* 非线程安全 */ void bound_block_queue_destroy(bound_block_queue **q, queue_node_free_cb free_cb) { if(q && *q) { bound_block_queue_clear(*q, free_cb); MUTEX_DESTROY(*q); condition_destroy(&(*q)->no_full); condition_destroy(&(*q)->no_empty); free(*q); *q = NULL; } }
C
#include<stdio.h> #include<malloc.h> int max_min(int *arr,int n){ int i,max,min; max=min=arr[0]; for(i=0;i<n;i++){ if(arr[i]>max){ max=arr[i]; } if(arr[i]<min){ min=arr[i]; } } printf("Maximum Element is : %d\n",max); printf("Minimum Element is : %d",min); } int main() { int n,min,*arr,max,i; scanf("%d",&n); arr=malloc(n*sizeof(int)); for(i=0;i<n;i++){ scanf("%d",&arr[i]); } max_min(arr,n); return 0; }
C
#include "headers/file_reader.h" int calc_hyperperiod(Process *processes, int no_of_processes) { int lcm = processes[0].burst_duration; int a, b; for(int i = 1 ; i < no_of_processes ; i++) { a = lcm; b = processes[i].burst_duration; while(a != b) { if (a > b) a = a - b; else b = b - a; } lcm = (lcm * processes[i].burst_duration) / a; } return lcm; } int calc_last_deadline(Process *processes, int no_of_processes){ int deadline = -1; for(int i=0; i<no_of_processes; i++){ if(processes[i].deadline_time > deadline){ deadline = processes[i].deadline_time; } } return deadline; }
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> #include <time.h> #include <sys/wait.h> #define _POSIX_SOURCE 1 /* int NB_THREADS = 10; int somme = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // On initialise la donnée mutex. void* Fils(void *t) // Fonction qui sera convertie en thread. { srand(time(NULL) ^ (getpid() << 16)); int i = (long) t; pthread_mutex_lock(&mutex); // On laisse passer le premier thread exécutant cette fonction et on bloque les autres. int tmp = somme; tmp ++; int randomTime; randomTime = rand() % 3; // Remarque: La fonction "rand()" génère un entier aléatoire qui correspondra ici au temps d'attente du thread. sleep(randomTime); // Remarque: La fonction "sleep(x)" met en pause pendant x secondes le thread courant. somme = tmp; pthread_mutex_unlock(&mutex); // Le premier thread à être passé a fini d'exécuter sa série d'instructions. On débloque alors les threads en attente et on laisse passer le suivant. printf("Je suis le processus fils d'indice %d : somme = %d. \n", i, somme); pthread_exit(0); // Le thread courant se termine. } int main(int argc, char** argv) // "char** argv" est un pointeur vers un pointeur d'un caractère. { pthread_t tid; // Variable prenant pour valeurs les identifiants des threads. pthread_t Threads_id[NB_THREADS]; // Tableau dans lequel on stocke les identifiants des 10 threads créés, identifiants dont le type est "pthread_t". int i; printf("Je suis le processus père : somme = %d. \n", somme); for(i=0; i < NB_THREADS; i++) { if(pthread_create(&tid, NULL, Fils, NULL) != 0) { printf("Un nouveau thread vient d'être créé. \n"); exit(1); } else { Threads_id[i] = tid; } } for(i=0; i < NB_THREADS; i++) { pthread_join(Threads_id[i], NULL); } printf("Je suis le processus père : somme = %d. \n", somme); return EXIT_SUCCESS; } */
C
/* ** EPITECH PROJECT, 2018 ** MUL_my_hunter_2018 ** File description: ** main file of the prog */ #include <SFML/Graphics/RenderWindow.h> #include <SFML/Graphics/Texture.h> #include <SFML/Graphics/Sprite.h> #include <SFML/System/Clock.h> #include <SFML/System/Time.h> #include <stdlib.h> #include "./../include/object.h" #include "./../include/my.h" void display_usage(void) { my_putstr("\nTo play just do that : ./my_hunter ; with no argments\n"); my_putstr("The player is a hunter who shoots ducks with right click.\n"); my_putstr("Ducks appear randomly and move from one side to another.\n"); my_putstr("The duck move faster than the nb of time a duck is killed.\n"); my_putstr("___________________________________________________\n\n"); my_putstr("**I've done that :\n"); my_putstr("-The window is closed using events\n"); my_putstr("-The program manage the input from the mouse click.\n"); my_putstr("-The program isanimated sprites rendered thanks"); my_putstr(" to sprite sheets.\n"); my_putstr("-The program contain moving elements.\n"); my_putstr("-The program accept the “-h” option, then display a short "); my_putstr("description of the program, and theavailable user inputs.\n"); my_putstr("-Animations and movements in your program don t depend on the "); my_putstr("speed of your computer.\n"); my_putstr("-Animations and movements in your program are "); my_putstr("timed by sfClock elements.\n"); my_putstr("-The window is stick between 800x600 and 1920x1080 pixels.\n"); my_putstr("-The window have a limited frame rate .\n"); my_putstr("-The program display the score of the player .\n\n"); } int main(int ac, char **av) { backg_t *backg = malloc(sizeof(backg)); duck_t *duck = malloc(sizeof(duck_t)); sfEvent *event = malloc(sizeof(event)); my_clock_t *time = malloc(sizeof(time)); if (ac >= 2 && av[1] != NULL) { display_usage(); return (0); } backg->window = create_my_window(1920, 1080); backg = initialise_background(backg); duck = initialise_rect(duck); time->clock = sfClock_create(); time->elapsed = 0.0; game_loop(backg, duck, event, time); sfRenderWindow_destroy(backg->window); display_scoreboard(duck); return (0); }
C
#define VGA_MEM (unsigned short *)0xb8000 #include "system.h" unsigned char kbdus[128] = { 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ '9', '0', '-', '=', '\b', /* Backspace */ '\t', /* Tab */ 'q', 'w', 'e', 'r', /* 19 */ 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */ 0, /* 29 - Control */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ '\'', '`', 15, /* Left shif */ '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ 'm', ',', '.', '/', 15, /* Right shift */ '*', 14, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock*/ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key*/ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, 0, 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ }; unsigned short *video_out = VGA_MEM; unsigned short color_arr[3] = {YELLOW, RED, PURPLE}; unsigned short font_color; unsigned char cur_color = 0; unsigned char shiftbit = 0; int cur_line() { return (video_out - VGA_MEM) / 80 + 1; } void print(char *str) { if (video_out < VGA_MEM) { video_out = VGA_MEM; return; } while (*str != '\0') { if (*str == '\n') video_out = VGA_MEM + 80 * cur_line(); else if (*str == '\b') *(--video_out) = *video_out | font_color | ' '; else if (shiftbit && (*str >= 'a') && (*str <= 'z')) *video_out++ = *video_out | font_color | (*str - 32); else *video_out++ = *video_out | font_color | *str; str++; } } void putc(unsigned char c) { if (video_out < VGA_MEM) { video_out = VGA_MEM; return; } if (c == '\n') video_out = VGA_MEM + 80 * cur_line(); else if (c == '\b') *(--video_out) = *video_out | font_color | ' '; else if (shiftbit && (c >= 'a') && (c <= 'z')) *video_out++ = *video_out | font_color | (c - 32); else *video_out++ = *video_out | font_color | c; } unsigned char inportb (unsigned short _port) { unsigned char rv; __asm__ __volatile__ ("inb %1, %0" : "=a" (rv) : "dN" (_port)); return rv; } void outportb (unsigned short _port, unsigned char _data) { __asm__ __volatile__ ("outb %1, %0" : : "dN" (_port), "a" (_data)); } void set_bg_color(unsigned short color) { video_out = VGA_MEM; for (int cnt = 0; cnt < 80 * 25; cnt++) *(video_out + cnt) = color; } void change_font_color(unsigned short color) { font_color = color / 16; } void keyboard_handler(struct regs *r) { unsigned char scancode, key; scancode = inportb(0x60); if (scancode & 0x80) { if (kbdus[scancode & 0x7F] == 15) shiftbit = 0; } else { key = kbdus[scancode]; if (key == 15) shiftbit = 1; else if (key == 14) change_font_color(color_arr[cur_color = ((cur_color + 1) % 3)]); else putc(key); } } void keyboard_install() { irq_install_handler(1, keyboard_handler); }
C
#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> #include <errno.h> #define THREAD_CREATION_SUCCESS 0 #define THREAD_JOIN_SUCCESS 0 #define EXIT_ERROR 1 #define DECIMAL_CONSTANT 0 #define num_steps 200000000 #define THREAD_NUMBER_TOP_LIMIT 300 #define NO_ERROR 0 struct param{ long long threadNumber; double result; int threadsAmount; } typedef params; void printError(int code, char* error) { char* buf = strerror(code); printf("%s: %s\n", error, buf); } void* calculate(void* arg) { double localpi = 0.0; long long i; params* param = (params *) arg; for (i = param->threadNumber; i < num_steps ; i += param->threadsAmount) { localpi += 1.0 / (i * 4.0 + 1.0); localpi -= 1.0 / (i * 4.0 + 3.0); } param->result = localpi; return param; } int parseArguments(int argc, char **argv) { char* ret; int numOfThreads; if (argc != 2) { printf("Usage %s [number of threads] format\n", argv[0]); exit(EXIT_ERROR); } numOfThreads = strtol(argv[1], &ret, DECIMAL_CONSTANT); if (errno != NO_ERROR) { printError(errno, "Failed to convert argument to number"); exit(EXIT_ERROR); } if (ret[0] != '\0') { printf("Only number available as argument\n"); exit(EXIT_ERROR); } if (numOfThreads < 1) { printf("Invalid number of threads: %d\n", numOfThreads); exit(EXIT_ERROR); } return numOfThreads; } int main(int argc, char** argv) { double pi = 0; int i, code; long int threadsAmount; pthread_t* threads; params* param; threadsAmount = parseArguments(argc, argv); threads = (pthread_t*) malloc(threadsAmount * sizeof(pthread_t)); if (threads == NULL) { printError(errno, "Failed to alloc memory for threads"); exit(EXIT_ERROR); } param = (params*) malloc(threadsAmount * sizeof(params)); if (param == NULL) { printError(errno, "Failed to alloc memory for args"); exit(EXIT_ERROR); } for(i = 0; i < threadsAmount; i++) { param[i].threadNumber = i; param[i].threadsAmount = threadsAmount; code = pthread_create(threads + i, NULL, calculate, &param[i]); if (code != THREAD_CREATION_SUCCESS){ printError(code, "Failed to create thread"); exit(EXIT_ERROR); } } for(i = 0; i < threadsAmount; i++) { code = pthread_join(threads[i], NULL); if (code != THREAD_JOIN_SUCCESS) { printError(code, argv[0]); exit(EXIT_ERROR); } pi += param[i].result; } pi *= 4.0; printf("pi = %.16f\n", pi); free(param); free(threads); pthread_exit(NULL); }
C
#include <stdio.h> #include "dlinklist.h" //˫ѭѭ֣֮дʱѭ˫ typedef struct _tag_DoubleLinkList//һϢ { DLinkListNode header;//һڵָ DLinkListNode* slider;//һα int length; }TDLinkList; DLinkList* DLinkList_Create() { TDLinkList* tmp = NULL; int ret = 0; tmp = (TDLinkList*)malloc(sizeof(TDLinkList)); if (tmp == NULL) { ret = -1; printf("func (TLinkList*)malloc(sizeof(TLinkList)) err:%d\n", ret); return NULL; } /*tmp->slider = (struct _tag_LinkListNode*)malloc(sizeof(struct _tag_CircleListNode));//sliderֲǶָ룬Ҫзڴ //ʼʱDzҪڴģԿʼʱֶϵ㣬ڴй© if (tmp->slider == NULL) { ret = -2; printf("func (struct _tag_LinkListNode*)malloc(sizeof(struct _tag_LinkListNode)) err:%d\n", ret); return NULL; }*/ tmp->header.next = NULL; tmp->header.pre = NULL; tmp->slider = NULL; tmp->length = 0; return tmp; } void DLinkList_Destory(DLinkList* list) { if (list == NULL) { return; } /*tmp = (TCircleList*)list; if (tmp->slider != NULL) { free(tmp->slider); }*/ free(list); } void DLinkList_Clear(DLinkList* list) { TDLinkList *tmp = NULL; if (list == NULL) { return; } tmp = (TDLinkList*)list; tmp->header.next = NULL;//ָʼʱ tmp->header.pre = NULL; tmp->slider = NULL; tmp->length = 0; return; } int DLinkList_Length(DLinkList* list) { int ret = 0; TDLinkList* tmp = NULL; if (list == NULL) { ret = -1; printf("func list == NULL err:%d\n", ret); return ret; } tmp = (TDLinkList*)list; return tmp->length; } int DLinkList_Insert(DLinkList* list, DLinkListNode* node, int pos)//insertʱʼѭͬ { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* current = &(tmp->header);//ӵڶָ int ret = 0, i = 0; if (list == NULL || node == NULL || pos < 0) { ret = -1; printf("func list == NULL || node == NULL || pos < 0 err:%d\n", ret); return ret; } //ônodeӽڴ if (pos > tmp->length)//λý { pos = tmp->length; } if (tmp->length == 0)//տʼһڵ { current->next = node; node->pre = node; node->next = node; } else { for (i = 0; (i < pos) && (current->next != NULL); i++) { current = current->next;//ͷָƶָλ } node->next = current->next;//ڵڵ֮, current->next->pre = node; current->next = node; if (current == &(tmp->header))//!!!!ͷ巨ʱȫһ { //ҪĽڵһڵ㴮 for (i = 0; i < tmp->length + 1; i++)//ĽڵλѾԪصλ { current = current->next;//ͷָƶָλ } current->next = node; node->pre = current; } else { //ѭҲкôģҪǺΪNULL,ΪҪcurrentжϣﲻܶcurrentֵ node->pre = current;//ڵڵ֮, } //ԣٿβ巨ҪҪر } tmp->slider = node;//αָڵλãӦö԰ɣƵָһڵλ tmp->length++; return ret; } DLinkListNode* DLinkList_Get(DLinkList* list, int pos) { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* current = &(tmp->header); int i = 0; if (list == NULL || pos < 0) { printf("func list == NULL || pos < 0 err\n"); return NULL; } for (i = 0; i <= pos; i++) { current = current->next;//ͷָƶָλ } tmp->slider = current;//αָڵλ return current; } DLinkListNode* DLinkList_Delete(DLinkList* list, int pos) { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* current = &(tmp->header); DLinkListNode* tmpnode; int i = 0; if (list == NULL || pos < 0) { printf("func list == NULL || pos < 0 err"); return NULL; } if (pos >= tmp->length)//λýɾгλõݣɾһ { pos = tmp->length - 1; } if (tmp->length == 1)//ֻʣһԪʱ { tmpnode = current->next; current->next = NULL; current->pre = NULL; current = NULL; } else { for (i = 0; i < pos; i++) { current = current->next;//ͷָƶָλ } tmpnode = current->next; current->next = tmpnode->next; tmp->slider = tmpnode->next;//αָɾڵĺһλ if (current == &(tmp->header))//ɾͷڵҪرǣҪܹѭ { for (i = 0; i < tmp->length - 1; i++)//ԪҪָڶڵ { current = current->next; } current->next = tmpnode->next; tmpnode->pre = current; } else { tmpnode->next->pre = current; } } tmp->length--; return tmpnode; } //**************α***************// DLinkListNode* DLinkList_Reset(DLinkList* list)//α,ָһԪ { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* current = &(tmp->header); if (list == NULL) { printf("func list == NULL err\n"); return NULL; } tmp->slider = current->next; return current->next; } DLinkListNode* DLinkList_Current(DLinkList* list)//ȡαָԪ { TDLinkList* tmp = (TDLinkList*)list; if (list == NULL) { printf("func list == NULL err\n"); return NULL; } return tmp->slider; } DLinkListNode* DLinkList_Next(DLinkList* list)//αָĵǰԪأαƶһԪ { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* tmpslider = tmp->slider;//αʱ if (list == NULL) { printf("func list == NULL err\n"); return NULL; } tmp->slider = tmpslider->next; return tmpslider; } DLinkListNode* DLinkList_Pre(DLinkList* list)//αָĵǰԪأαƶһԪ { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* tmpslider = tmp->slider;//αʱ if (list == NULL) { printf("func list == NULL err\n"); return NULL; } tmp->slider = tmpslider->pre; return tmpslider; } DLinkListNode* DLinkList_Delete2(DLinkList* list, DLinkListNode* node)//Ԫɾ,ɾԪ { TDLinkList* tmp = (TDLinkList*)list; DLinkListNode* current = &(tmp->header);//Ϊʲôڶξʱcurrent->nextΪnullѽ DLinkListNode* tmpslider = &(tmp->header);//ʱ if (list == NULL) { printf("func list == NULL err\n"); return NULL; } if (tmp->length == 1)//ֻʣһԪʱ { tmpslider = current->next; current->next = NULL; current->pre = NULL; current = NULL; } else { tmpslider = current->next; if (node == tmpslider)//ѵһɾˣľͶѽðѵڶǰ { current->next = tmpslider->next;//ͷڵָڶԪ for (int i = 0; i < tmp->length - 1; i++)//βڵҲҪָڶԪز,ȴˣΪǰһѾһˣϾõĴ { current = current->next; } tmp->slider = tmpslider->next;//αָɾԪصһԪزź current->next = tmpslider->next; tmpslider->pre = current;//ǵpre tmp->length--;//ǵýȼȥ1 return tmpslider; } while (tmpslider != node)//ֱҵһֵ { current = current->next; tmpslider = current->next; } tmp->slider = tmpslider->next;//αָɾԪصһԪزź current->next = tmpslider->next; tmpslider->next->pre = current; } tmp->length--; return tmpslider; }